code stringlengths 82 54.1k | code_codestyle int64 0 699 | style_context stringlengths 111 35.6k | style_context_codestyle int64 0 699 | label int64 0 1 |
|---|---|---|---|---|
from typing import TYPE_CHECKING
from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
a_ : Tuple = {
'configuration_trajectory_transformer': [
'TRAJECTORY_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP',
'TrajectoryTransformerConfig',
],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a_ : Tuple = [
'TRAJECTORY_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST',
'TrajectoryTransformerModel',
'TrajectoryTransformerPreTrainedModel',
'load_tf_weights_in_trajectory_transformer',
]
if TYPE_CHECKING:
from .configuration_trajectory_transformer import (
TRAJECTORY_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP,
TrajectoryTransformerConfig,
)
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_trajectory_transformer import (
TRAJECTORY_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
TrajectoryTransformerModel,
TrajectoryTransformerPreTrainedModel,
load_tf_weights_in_trajectory_transformer,
)
else:
import sys
a_ : str = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__) | 623 |
import os
import shutil
import tempfile
from unittest import TestCase
from unittest.mock import patch
import numpy as np
from datasets import Dataset
from transformers.models.realm.configuration_realm import RealmConfig
from transformers.models.realm.retrieval_realm import _REALM_BLOCK_RECORDS_FILENAME, RealmRetriever
from transformers.models.realm.tokenization_realm import VOCAB_FILES_NAMES, RealmTokenizer
class UpperCAmelCase_ ( lowercase ):
"""simple docstring"""
def UpperCAmelCase ( self ) -> Tuple:
UpperCamelCase :Union[str, Any] = tempfile.mkdtemp()
UpperCamelCase :List[str] = 5
# Realm tok
UpperCamelCase :List[Any] = [
'''[UNK]''',
'''[CLS]''',
'''[SEP]''',
'''[PAD]''',
'''[MASK]''',
'''test''',
'''question''',
'''this''',
'''is''',
'''the''',
'''first''',
'''second''',
'''third''',
'''fourth''',
'''fifth''',
'''record''',
'''want''',
'''##want''',
'''##ed''',
'''wa''',
'''un''',
'''runn''',
'''##ing''',
''',''',
'''low''',
'''lowest''',
]
UpperCamelCase :Dict = os.path.join(self.tmpdirname , '''realm_tokenizer''' )
os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Union[str, Any] = os.path.join(SCREAMING_SNAKE_CASE_ , VOCAB_FILES_NAMES['''vocab_file'''] )
with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer:
vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) )
UpperCamelCase :Any = os.path.join(self.tmpdirname , '''realm_block_records''' )
os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self ) -> RealmTokenizer:
return RealmTokenizer.from_pretrained(os.path.join(self.tmpdirname , '''realm_tokenizer''' ) )
def UpperCAmelCase ( self ) -> List[Any]:
shutil.rmtree(self.tmpdirname )
def UpperCAmelCase ( self ) -> str:
UpperCamelCase :Union[str, Any] = RealmConfig(num_block_records=self.num_block_records )
return config
def UpperCAmelCase ( self ) -> List[str]:
UpperCamelCase :Tuple = Dataset.from_dict(
{
'''id''': ['''0''', '''1'''],
'''question''': ['''foo''', '''bar'''],
'''answers''': [['''Foo''', '''Bar'''], ['''Bar''']],
} )
return dataset
def UpperCAmelCase ( self ) -> str:
UpperCamelCase :Optional[Any] = np.array(
[
b'''This is the first record''',
b'''This is the second record''',
b'''This is the third record''',
b'''This is the fourth record''',
b'''This is the fifth record''',
b'''This is a longer longer longer record''',
] , dtype=SCREAMING_SNAKE_CASE_ , )
return block_records
def UpperCAmelCase ( self ) -> Union[str, Any]:
UpperCamelCase :Optional[int] = RealmRetriever(
block_records=self.get_dummy_block_records() , tokenizer=self.get_tokenizer() , )
return retriever
def UpperCAmelCase ( self ) -> Tuple:
UpperCamelCase :Optional[Any] = self.get_config()
UpperCamelCase :str = self.get_dummy_retriever()
UpperCamelCase :int = retriever.tokenizer
UpperCamelCase :Optional[Any] = np.array([0, 3] , dtype='''long''' )
UpperCamelCase :Optional[Any] = tokenizer(['''Test question'''] ).input_ids
UpperCamelCase :Tuple = tokenizer(
['''the fourth'''] , add_special_tokens=SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , ).input_ids
UpperCamelCase :Optional[Any] = config.reader_seq_len
UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :str = retriever(
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , answer_ids=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , return_tensors='''np''' )
self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 2 )
self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 2 )
self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 2 )
self.assertEqual(concat_inputs.input_ids.shape , (2, 10) )
self.assertEqual(concat_inputs.attention_mask.shape , (2, 10) )
self.assertEqual(concat_inputs.token_type_ids.shape , (2, 10) )
self.assertEqual(concat_inputs.special_tokens_mask.shape , (2, 10) )
self.assertEqual(
tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[0] ) , ['''[CLS]''', '''test''', '''question''', '''[SEP]''', '''this''', '''is''', '''the''', '''first''', '''record''', '''[SEP]'''] , )
self.assertEqual(
tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[1] ) , ['''[CLS]''', '''test''', '''question''', '''[SEP]''', '''this''', '''is''', '''the''', '''fourth''', '''record''', '''[SEP]'''] , )
def UpperCAmelCase ( self ) -> int:
UpperCamelCase :Union[str, Any] = self.get_config()
UpperCamelCase :Union[str, Any] = self.get_dummy_retriever()
UpperCamelCase :Dict = retriever.tokenizer
UpperCamelCase :str = np.array([0, 3, 5] , dtype='''long''' )
UpperCamelCase :List[str] = tokenizer(['''Test question'''] ).input_ids
UpperCamelCase :Optional[Any] = tokenizer(
['''the fourth''', '''longer longer'''] , add_special_tokens=SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , ).input_ids
UpperCamelCase :Any = config.reader_seq_len
UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :Any = retriever(
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , answer_ids=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , return_tensors='''np''' )
self.assertEqual([False, True, True] , SCREAMING_SNAKE_CASE_ )
self.assertEqual([[-1, -1, -1], [6, -1, -1], [6, 7, 8]] , SCREAMING_SNAKE_CASE_ )
self.assertEqual([[-1, -1, -1], [7, -1, -1], [7, 8, 9]] , SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self ) -> Optional[Any]:
UpperCamelCase :str = self.get_dummy_retriever()
retriever.save_pretrained(os.path.join(self.tmpdirname , '''realm_block_records''' ) )
# Test local path
UpperCamelCase :List[str] = retriever.from_pretrained(os.path.join(self.tmpdirname , '''realm_block_records''' ) )
self.assertEqual(retriever.block_records[0] , b'''This is the first record''' )
# Test mocked remote path
with patch('''transformers.models.realm.retrieval_realm.hf_hub_download''' ) as mock_hf_hub_download:
UpperCamelCase :Tuple = os.path.join(
os.path.join(self.tmpdirname , '''realm_block_records''' ) , _REALM_BLOCK_RECORDS_FILENAME )
UpperCamelCase :List[Any] = RealmRetriever.from_pretrained('''google/realm-cc-news-pretrained-openqa''' )
self.assertEqual(retriever.block_records[0] , b'''This is the first record''' )
| 658 | 0 |
'''simple docstring'''
import shutil
import tempfile
import unittest
from transformers import (
SPIECE_UNDERLINE,
AddedToken,
BatchEncoding,
NllbTokenizer,
NllbTokenizerFast,
is_torch_available,
)
from transformers.testing_utils import (
get_tests_dir,
nested_simplify,
require_sentencepiece,
require_tokenizers,
require_torch,
)
from ...test_tokenization_common import TokenizerTesterMixin
__UpperCamelCase : Optional[int] = get_tests_dir("""fixtures/test_sentencepiece.model""")
if is_torch_available():
from transformers.models.mam_aaa.modeling_mam_aaa import shift_tokens_right
__UpperCamelCase : Optional[int] = 256047
__UpperCamelCase : Union[str, Any] = 256145
@require_sentencepiece
@require_tokenizers
class __SCREAMING_SNAKE_CASE ( _lowerCAmelCase , unittest.TestCase ):
__a =NllbTokenizer
__a =NllbTokenizerFast
__a =True
__a =True
__a ={}
def __UpperCamelCase ( self ) ->int:
'''simple docstring'''
super().setUp()
# We have a SentencePiece fixture for testing
__a = NllbTokenizer(SCREAMING_SNAKE_CASE_ , keep_accents=SCREAMING_SNAKE_CASE_ )
tokenizer.save_pretrained(self.tmpdirname )
def __UpperCamelCase ( self ) ->Tuple:
'''simple docstring'''
__a = NllbTokenizer(SCREAMING_SNAKE_CASE_ , keep_accents=SCREAMING_SNAKE_CASE_ )
__a = tokenizer.tokenize('This is a test' )
self.assertListEqual(SCREAMING_SNAKE_CASE_ , ['▁This', '▁is', '▁a', '▁t', 'est'] )
self.assertListEqual(
tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , )
__a = tokenizer.tokenize('I was born in 92000, and this is falsé.' )
self.assertListEqual(
SCREAMING_SNAKE_CASE_ , [
SPIECE_UNDERLINE + 'I',
SPIECE_UNDERLINE + 'was',
SPIECE_UNDERLINE + 'b',
'or',
'n',
SPIECE_UNDERLINE + 'in',
SPIECE_UNDERLINE + '',
'9',
'2',
'0',
'0',
'0',
',',
SPIECE_UNDERLINE + 'and',
SPIECE_UNDERLINE + 'this',
SPIECE_UNDERLINE + 'is',
SPIECE_UNDERLINE + 'f',
'al',
's',
'é',
'.',
] , )
__a = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ )
self.assertListEqual(
SCREAMING_SNAKE_CASE_ , [
value + tokenizer.fairseq_offset
for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4]
] , )
__a = tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE_ )
self.assertListEqual(
SCREAMING_SNAKE_CASE_ , [
SPIECE_UNDERLINE + 'I',
SPIECE_UNDERLINE + 'was',
SPIECE_UNDERLINE + 'b',
'or',
'n',
SPIECE_UNDERLINE + 'in',
SPIECE_UNDERLINE + '',
'<unk>',
'2',
'0',
'0',
'0',
',',
SPIECE_UNDERLINE + 'and',
SPIECE_UNDERLINE + 'this',
SPIECE_UNDERLINE + 'is',
SPIECE_UNDERLINE + 'f',
'al',
's',
'<unk>',
'.',
] , )
def __UpperCamelCase ( self ) ->List[str]:
'''simple docstring'''
__a = (self.rust_tokenizer_class, '''hf-internal-testing/tiny-random-nllb''', {})
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ):
__a = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
__a = self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
__a = tempfile.mkdtemp()
__a = tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE_ )
__a = tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE_ )
# Checks it save with the same files + the tokenizer.json file for the fast one
self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) )
__a = tuple(f for f in tokenizer_r_files if 'tokenizer.json' not in f )
self.assertSequenceEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# Checks everything loads correctly in the same way
__a = tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE_ )
__a = tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE_ )
# Check special tokens are set accordingly on Rust and Python
for key in tokenizer_pp.special_tokens_map:
self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) )
shutil.rmtree(SCREAMING_SNAKE_CASE_ )
# Save tokenizer rust, legacy_format=True
__a = tempfile.mkdtemp()
__a = tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE_ , legacy_format=SCREAMING_SNAKE_CASE_ )
__a = tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE_ )
# Checks it save with the same files
self.assertSequenceEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# Checks everything loads correctly in the same way
__a = tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE_ )
__a = tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE_ )
# Check special tokens are set accordingly on Rust and Python
for key in tokenizer_pp.special_tokens_map:
self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) )
shutil.rmtree(SCREAMING_SNAKE_CASE_ )
# Save tokenizer rust, legacy_format=False
__a = tempfile.mkdtemp()
__a = tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE_ , legacy_format=SCREAMING_SNAKE_CASE_ )
__a = tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE_ )
# Checks it saved the tokenizer.json file
self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) )
# Checks everything loads correctly in the same way
__a = tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE_ )
__a = tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE_ )
# Check special tokens are set accordingly on Rust and Python
for key in tokenizer_pp.special_tokens_map:
self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) )
shutil.rmtree(SCREAMING_SNAKE_CASE_ )
@require_torch
def __UpperCamelCase ( self ) ->Any:
'''simple docstring'''
if not self.test_seqaseq:
return
__a = self.get_tokenizers()
for tokenizer in tokenizers:
with self.subTest(F"""{tokenizer.__class__.__name__}""" ):
# Longer text that will definitely require truncation.
__a = [
''' UN Chief Says There Is No Military Solution in Syria''',
''' Secretary-General Ban Ki-moon says his response to Russia\'s stepped up military support for'''
''' Syria is that \'there is no military solution\' to the nearly five-year conflict and more weapons'''
''' will only worsen the violence and misery for millions of people.''',
]
__a = [
'''Şeful ONU declară că nu există o soluţie militară în Siria''',
'''Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al'''
''' Rusiei pentru Siria este că "nu există o soluţie militară" la conflictul de aproape cinci ani şi'''
''' că noi arme nu vor face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.''',
]
try:
__a = tokenizer.prepare_seqaseq_batch(
src_texts=SCREAMING_SNAKE_CASE_ , tgt_texts=SCREAMING_SNAKE_CASE_ , max_length=3 , max_target_length=10 , return_tensors='pt' , src_lang='eng_Latn' , tgt_lang='ron_Latn' , )
except NotImplementedError:
return
self.assertEqual(batch.input_ids.shape[1] , 3 )
self.assertEqual(batch.labels.shape[1] , 10 )
# max_target_length will default to max_length if not specified
__a = tokenizer.prepare_seqaseq_batch(
SCREAMING_SNAKE_CASE_ , tgt_texts=SCREAMING_SNAKE_CASE_ , max_length=3 , return_tensors='pt' )
self.assertEqual(batch.input_ids.shape[1] , 3 )
self.assertEqual(batch.labels.shape[1] , 3 )
__a = tokenizer.prepare_seqaseq_batch(
src_texts=SCREAMING_SNAKE_CASE_ , max_length=3 , max_target_length=10 , return_tensors='pt' )
self.assertEqual(batch_encoder_only.input_ids.shape[1] , 3 )
self.assertEqual(batch_encoder_only.attention_mask.shape[1] , 3 )
self.assertNotIn('decoder_input_ids' , SCREAMING_SNAKE_CASE_ )
@unittest.skip('Unfortunately way too slow to build a BPE with SentencePiece.' )
def __UpperCamelCase ( self ) ->int:
'''simple docstring'''
pass
def __UpperCamelCase ( self ) ->Optional[Any]:
'''simple docstring'''
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ):
__a = [AddedToken('<special>' , lstrip=SCREAMING_SNAKE_CASE_ )]
__a = self.rust_tokenizer_class.from_pretrained(
SCREAMING_SNAKE_CASE_ , additional_special_tokens=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
__a = tokenizer_r.encode('Hey this is a <special> token' )
__a = tokenizer_r.encode('<special>' , add_special_tokens=SCREAMING_SNAKE_CASE_ )[0]
self.assertTrue(special_token_id in r_output )
if self.test_slow_tokenizer:
__a = self.rust_tokenizer_class.from_pretrained(
SCREAMING_SNAKE_CASE_ , additional_special_tokens=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , )
__a = self.tokenizer_class.from_pretrained(
SCREAMING_SNAKE_CASE_ , additional_special_tokens=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
__a = tokenizer_p.encode('Hey this is a <special> token' )
__a = tokenizer_cr.encode('Hey this is a <special> token' )
self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
self.assertTrue(special_token_id in p_output )
self.assertTrue(special_token_id in cr_output )
@require_torch
@require_sentencepiece
@require_tokenizers
class __SCREAMING_SNAKE_CASE ( unittest.TestCase ):
__a ='facebook/nllb-200-distilled-600M'
__a =[
' UN Chief Says There Is No Military Solution in Syria',
' Secretary-General Ban Ki-moon says his response to Russia\'s stepped up military support for Syria is that "there is no military solution" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.',
]
__a =[
'Şeful ONU declară că nu există o soluţie militară în Siria',
'Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei'
' pentru Siria este că "nu există o soluţie militară" la conflictul de aproape cinci ani şi că noi arme nu vor'
' face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.',
]
__a =[
256_047,
16_297,
134_408,
8_165,
248_066,
14_734,
950,
1_135,
105_721,
3_573,
83,
27_352,
108,
49_486,
2,
]
@classmethod
def __UpperCamelCase ( cls ) ->Tuple:
'''simple docstring'''
__a = NllbTokenizer.from_pretrained(
cls.checkpoint_name , src_lang='eng_Latn' , tgt_lang='ron_Latn' )
__a = 1
return cls
def __UpperCamelCase ( self ) ->int:
'''simple docstring'''
self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['ace_Arab'] , 25_6001 )
self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['ace_Latn'] , 25_6002 )
self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['fra_Latn'] , 25_6057 )
def __UpperCamelCase ( self ) ->Any:
'''simple docstring'''
__a = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0]
self.assertListEqual(self.expected_src_tokens , SCREAMING_SNAKE_CASE_ )
def __UpperCamelCase ( self ) ->Optional[Any]:
'''simple docstring'''
self.assertIn(SCREAMING_SNAKE_CASE_ , self.tokenizer.all_special_ids )
# fmt: off
__a = [RO_CODE, 4254, 9_8068, 11_2923, 3_9072, 3909, 713, 10_2767, 26, 1_7314, 3_5642, 1_4683, 3_3118, 2022, 6_6987, 2, 25_6047]
# fmt: on
__a = self.tokenizer.decode(SCREAMING_SNAKE_CASE_ , skip_special_tokens=SCREAMING_SNAKE_CASE_ )
__a = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=SCREAMING_SNAKE_CASE_ )
self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
self.assertNotIn(self.tokenizer.eos_token , SCREAMING_SNAKE_CASE_ )
def __UpperCamelCase ( self ) ->List[str]:
'''simple docstring'''
__a = ['''this is gunna be a long sentence ''' * 20]
assert isinstance(src_text[0] , SCREAMING_SNAKE_CASE_ )
__a = 10
__a = self.tokenizer(SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ ).input_ids[0]
self.assertEqual(ids[-1] , 2 )
self.assertEqual(ids[0] , SCREAMING_SNAKE_CASE_ )
self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ )
def __UpperCamelCase ( self ) ->Dict:
'''simple docstring'''
self.assertListEqual(self.tokenizer.convert_tokens_to_ids(['<mask>', 'ar_AR'] ) , [25_6203, 3] )
def __UpperCamelCase ( self ) ->int:
'''simple docstring'''
__a = tempfile.mkdtemp()
__a = self.tokenizer.fairseq_tokens_to_ids
self.tokenizer.save_pretrained(SCREAMING_SNAKE_CASE_ )
__a = NllbTokenizer.from_pretrained(SCREAMING_SNAKE_CASE_ )
self.assertDictEqual(new_tok.fairseq_tokens_to_ids , SCREAMING_SNAKE_CASE_ )
@require_torch
def __UpperCamelCase ( self ) ->Any:
'''simple docstring'''
__a = self.tokenizer(
self.src_text , text_target=self.tgt_text , padding=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , max_length=len(self.expected_src_tokens ) , return_tensors='pt' , )
__a = shift_tokens_right(
batch['labels'] , self.tokenizer.pad_token_id , self.tokenizer.lang_code_to_id['ron_Latn'] )
self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
self.assertEqual((2, 15) , batch.input_ids.shape )
self.assertEqual((2, 15) , batch.attention_mask.shape )
__a = batch.input_ids.tolist()[0]
self.assertListEqual(self.expected_src_tokens , SCREAMING_SNAKE_CASE_ )
self.assertEqual(SCREAMING_SNAKE_CASE_ , batch.decoder_input_ids[0, 0] ) # EOS
# Test that special tokens are reset
self.assertEqual(self.tokenizer.prefix_tokens , [EN_CODE] )
self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] )
def __UpperCamelCase ( self ) ->List[str]:
'''simple docstring'''
__a = self.tokenizer(self.src_text , padding=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , max_length=3 , return_tensors='pt' )
__a = self.tokenizer(
text_target=self.tgt_text , padding=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , max_length=10 , return_tensors='pt' )
__a = targets['''input_ids''']
__a = shift_tokens_right(
SCREAMING_SNAKE_CASE_ , self.tokenizer.pad_token_id , decoder_start_token_id=self.tokenizer.lang_code_to_id[self.tokenizer.tgt_lang] , )
self.assertEqual(batch.input_ids.shape[1] , 3 )
self.assertEqual(batch.decoder_input_ids.shape[1] , 10 )
@require_torch
def __UpperCamelCase ( self ) ->Any:
'''simple docstring'''
__a = self.tokenizer._build_translation_inputs(
'A test' , return_tensors='pt' , src_lang='eng_Latn' , tgt_lang='fra_Latn' )
self.assertEqual(
nested_simplify(SCREAMING_SNAKE_CASE_ ) , {
# A, test, EOS, en_XX
'input_ids': [[25_6047, 70, 7356, 2]],
'attention_mask': [[1, 1, 1, 1]],
# ar_AR
'forced_bos_token_id': 25_6057,
} , )
@require_torch
def __UpperCamelCase ( self ) ->Tuple:
'''simple docstring'''
__a = True
__a = self.tokenizer(
'UN Chief says there is no military solution in Syria' , src_lang='eng_Latn' , tgt_lang='fra_Latn' )
self.assertEqual(
inputs.input_ids , [1_6297, 13_4408, 2_5653, 6370, 248, 254, 10_3929, 9_4995, 108, 4_9486, 2, 25_6047] )
__a = False
__a = self.tokenizer(
'UN Chief says there is no military solution in Syria' , src_lang='eng_Latn' , tgt_lang='fra_Latn' )
self.assertEqual(
inputs.input_ids , [25_6047, 1_6297, 13_4408, 2_5653, 6370, 248, 254, 10_3929, 9_4995, 108, 4_9486, 2] ) | 448 |
import inspect
import unittest
from huggingface_hub import hf_hub_download
from transformers import ASTConfig
from transformers.testing_utils import require_torch, require_torchaudio, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_torchaudio_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from torch import nn
from transformers import ASTForAudioClassification, ASTModel
from transformers.models.audio_spectrogram_transformer.modeling_audio_spectrogram_transformer import (
AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
)
if is_torchaudio_available():
import torchaudio
from transformers import ASTFeatureExtractor
class UpperCAmelCase_ :
"""simple docstring"""
def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=24 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=37 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=10 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=2 , ) -> Optional[Any]:
UpperCamelCase :int = parent
UpperCamelCase :List[Any] = batch_size
UpperCamelCase :List[Any] = patch_size
UpperCamelCase :Optional[int] = max_length
UpperCamelCase :Union[str, Any] = num_mel_bins
UpperCamelCase :Optional[int] = is_training
UpperCamelCase :Dict = use_labels
UpperCamelCase :Dict = hidden_size
UpperCamelCase :Optional[int] = num_hidden_layers
UpperCamelCase :str = num_attention_heads
UpperCamelCase :Optional[int] = intermediate_size
UpperCamelCase :List[str] = hidden_act
UpperCamelCase :List[str] = hidden_dropout_prob
UpperCamelCase :List[Any] = attention_probs_dropout_prob
UpperCamelCase :str = type_sequence_label_size
UpperCamelCase :List[Any] = initializer_range
UpperCamelCase :Union[str, Any] = scope
UpperCamelCase :List[Any] = frequency_stride
UpperCamelCase :Tuple = time_stride
# in AST, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens)
UpperCamelCase :List[Any] = (self.num_mel_bins - self.patch_size) // self.frequency_stride + 1
UpperCamelCase :List[str] = (self.max_length - self.patch_size) // self.time_stride + 1
UpperCamelCase :Tuple = frequency_out_dimension * time_out_dimension
UpperCamelCase :Optional[int] = num_patches + 2
def UpperCAmelCase ( self ) -> Any:
UpperCamelCase :Tuple = floats_tensor([self.batch_size, self.max_length, self.num_mel_bins] )
UpperCamelCase :Tuple = None
if self.use_labels:
UpperCamelCase :List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size )
UpperCamelCase :str = self.get_config()
return config, input_values, labels
def UpperCAmelCase ( self ) -> List[Any]:
return ASTConfig(
patch_size=self.patch_size , max_length=self.max_length , num_mel_bins=self.num_mel_bins , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=SCREAMING_SNAKE_CASE_ , initializer_range=self.initializer_range , frequency_stride=self.frequency_stride , time_stride=self.time_stride , )
def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Optional[int]:
UpperCamelCase :Optional[Any] = ASTModel(config=SCREAMING_SNAKE_CASE_ )
model.to(SCREAMING_SNAKE_CASE_ )
model.eval()
UpperCamelCase :Tuple = model(SCREAMING_SNAKE_CASE_ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def UpperCAmelCase ( self ) -> Dict:
UpperCamelCase :List[Any] = self.prepare_config_and_inputs()
(
(
UpperCamelCase
) , (
UpperCamelCase
) , (
UpperCamelCase
) ,
) :Union[str, Any] = config_and_inputs
UpperCamelCase :List[Any] = {'''input_values''': input_values}
return config, inputs_dict
@require_torch
class UpperCAmelCase_ ( lowercase, lowercase, unittest.TestCase ):
"""simple docstring"""
UpperCamelCase_ : Optional[int] =(
(
ASTModel,
ASTForAudioClassification,
)
if is_torch_available()
else ()
)
UpperCamelCase_ : Any =(
{'audio-classification': ASTForAudioClassification, 'feature-extraction': ASTModel}
if is_torch_available()
else {}
)
UpperCamelCase_ : Optional[int] =False
UpperCamelCase_ : List[Any] =False
UpperCamelCase_ : Optional[Any] =False
UpperCamelCase_ : Dict =False
def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> List[str]:
if pipeline_test_casse_name == "AudioClassificationPipelineTests":
return True
return False
def UpperCAmelCase ( self ) -> Dict:
UpperCamelCase :List[Any] = ASTModelTester(self )
UpperCamelCase :Dict = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , has_text_modality=SCREAMING_SNAKE_CASE_ , hidden_size=37 )
def UpperCAmelCase ( self ) -> Any:
self.config_tester.run_common_tests()
@unittest.skip(reason='''AST does not use inputs_embeds''' )
def UpperCAmelCase ( self ) -> str:
pass
def UpperCAmelCase ( self ) -> int:
UpperCamelCase , UpperCamelCase :List[Any] = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
UpperCamelCase :Dict = model_class(SCREAMING_SNAKE_CASE_ )
self.assertIsInstance(model.get_input_embeddings() , (nn.Module) )
UpperCamelCase :Optional[int] = model.get_output_embeddings()
self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE_ , nn.Linear ) )
def UpperCAmelCase ( self ) -> Tuple:
UpperCamelCase , UpperCamelCase :int = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
UpperCamelCase :Dict = model_class(SCREAMING_SNAKE_CASE_ )
UpperCamelCase :List[str] = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
UpperCamelCase :Any = [*signature.parameters.keys()]
UpperCamelCase :Optional[int] = ['''input_values''']
self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self ) -> List[Any]:
UpperCamelCase :Optional[int] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ )
@slow
def UpperCAmelCase ( self ) -> Optional[int]:
for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
UpperCamelCase :Union[str, Any] = ASTModel.from_pretrained(SCREAMING_SNAKE_CASE_ )
self.assertIsNotNone(SCREAMING_SNAKE_CASE_ )
def _A ( ):
UpperCamelCase :Any = hf_hub_download(
repo_id='''nielsr/audio-spectogram-transformer-checkpoint''' , filename='''sample_audio.flac''' , repo_type='''dataset''' )
UpperCamelCase , UpperCamelCase :Any = torchaudio.load(SCREAMING_SNAKE_CASE__ )
return audio, sampling_rate
@require_torch
@require_torchaudio
class UpperCAmelCase_ ( unittest.TestCase ):
"""simple docstring"""
@cached_property
def UpperCAmelCase ( self ) -> Tuple:
return (
ASTFeatureExtractor.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593''' )
if is_torchaudio_available()
else None
)
@slow
def UpperCAmelCase ( self ) -> str:
UpperCamelCase :Union[str, Any] = self.default_feature_extractor
UpperCamelCase :Union[str, Any] = ASTForAudioClassification.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593''' ).to(SCREAMING_SNAKE_CASE_ )
UpperCamelCase :str = self.default_feature_extractor
UpperCamelCase , UpperCamelCase :Dict = prepare_audio()
UpperCamelCase :Dict = audio.squeeze().numpy()
UpperCamelCase :int = feature_extractor(SCREAMING_SNAKE_CASE_ , sampling_rate=SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' ).to(SCREAMING_SNAKE_CASE_ )
# forward pass
with torch.no_grad():
UpperCamelCase :Union[str, Any] = model(**SCREAMING_SNAKE_CASE_ )
# verify the logits
UpperCamelCase :List[Any] = torch.Size((1, 527) )
self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE_ )
UpperCamelCase :int = torch.tensor([-0.8760, -7.0042, -8.6602] ).to(SCREAMING_SNAKE_CASE_ )
self.assertTrue(torch.allclose(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) )
| 658 | 0 |
from math import ceil
def __lowerCamelCase ( __lowerCAmelCase : int = 1001 ) -> Union[str, Any]:
__UpperCamelCase : Optional[int] = 1
for i in range(1 , int(ceil(n / 2.0 ) ) ):
__UpperCamelCase : Any = 2 * i + 1
__UpperCamelCase : Any = 2 * i
__UpperCamelCase : Tuple = total + 4 * odd**2 - 6 * even
return total
if __name__ == "__main__":
import sys
if len(sys.argv) == 1:
print(solution())
else:
try:
UpperCamelCase = int(sys.argv[1])
print(solution(n))
except ValueError:
print('Invalid entry - please enter a number')
| 269 |
import inspect
from typing import Optional, Union
import numpy as np
import PIL
import torch
from torch.nn import functional as F
from torchvision import transforms
from transformers import CLIPFeatureExtractor, CLIPModel, CLIPTextModel, CLIPTokenizer
from diffusers import (
AutoencoderKL,
DDIMScheduler,
DiffusionPipeline,
DPMSolverMultistepScheduler,
LMSDiscreteScheduler,
PNDMScheduler,
UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput
from diffusers.utils import (
PIL_INTERPOLATION,
randn_tensor,
)
def _A ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ):
if isinstance(SCREAMING_SNAKE_CASE__ , torch.Tensor ):
return image
elif isinstance(SCREAMING_SNAKE_CASE__ , PIL.Image.Image ):
UpperCamelCase :Dict = [image]
if isinstance(image[0] , PIL.Image.Image ):
UpperCamelCase :Any = [np.array(i.resize((w, h) , resample=PIL_INTERPOLATION['''lanczos'''] ) )[None, :] for i in image]
UpperCamelCase :int = np.concatenate(SCREAMING_SNAKE_CASE__ , axis=0 )
UpperCamelCase :Optional[Any] = np.array(SCREAMING_SNAKE_CASE__ ).astype(np.floataa ) / 2_55.0
UpperCamelCase :List[str] = image.transpose(0 , 3 , 1 , 2 )
UpperCamelCase :Tuple = 2.0 * image - 1.0
UpperCamelCase :Any = torch.from_numpy(SCREAMING_SNAKE_CASE__ )
elif isinstance(image[0] , torch.Tensor ):
UpperCamelCase :str = torch.cat(SCREAMING_SNAKE_CASE__ , dim=0 )
return image
def _A ( SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : int=0.99_95 ):
if not isinstance(SCREAMING_SNAKE_CASE__ , np.ndarray ):
UpperCamelCase :int = True
UpperCamelCase :Dict = va.device
UpperCamelCase :List[Any] = va.cpu().numpy()
UpperCamelCase :str = va.cpu().numpy()
UpperCamelCase :Dict = np.sum(va * va / (np.linalg.norm(SCREAMING_SNAKE_CASE__ ) * np.linalg.norm(SCREAMING_SNAKE_CASE__ )) )
if np.abs(SCREAMING_SNAKE_CASE__ ) > DOT_THRESHOLD:
UpperCamelCase :Any = (1 - t) * va + t * va
else:
UpperCamelCase :Union[str, Any] = np.arccos(SCREAMING_SNAKE_CASE__ )
UpperCamelCase :List[str] = np.sin(SCREAMING_SNAKE_CASE__ )
UpperCamelCase :Union[str, Any] = theta_a * t
UpperCamelCase :str = np.sin(SCREAMING_SNAKE_CASE__ )
UpperCamelCase :Tuple = np.sin(theta_a - theta_t ) / sin_theta_a
UpperCamelCase :List[Any] = sin_theta_t / sin_theta_a
UpperCamelCase :Union[str, Any] = sa * va + sa * va
if inputs_are_torch:
UpperCamelCase :Dict = torch.from_numpy(SCREAMING_SNAKE_CASE__ ).to(SCREAMING_SNAKE_CASE__ )
return va
def _A ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Tuple ):
UpperCamelCase :int = F.normalize(SCREAMING_SNAKE_CASE__ , dim=-1 )
UpperCamelCase :int = F.normalize(SCREAMING_SNAKE_CASE__ , dim=-1 )
return (x - y).norm(dim=-1 ).div(2 ).arcsin().pow(2 ).mul(2 )
def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Any ):
for param in model.parameters():
UpperCamelCase :Any = value
class UpperCAmelCase_ ( lowercase ):
"""simple docstring"""
def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , ) -> str:
super().__init__()
self.register_modules(
vae=SCREAMING_SNAKE_CASE_ , text_encoder=SCREAMING_SNAKE_CASE_ , clip_model=SCREAMING_SNAKE_CASE_ , tokenizer=SCREAMING_SNAKE_CASE_ , unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ , feature_extractor=SCREAMING_SNAKE_CASE_ , coca_model=SCREAMING_SNAKE_CASE_ , coca_tokenizer=SCREAMING_SNAKE_CASE_ , coca_transform=SCREAMING_SNAKE_CASE_ , )
UpperCamelCase :Union[str, Any] = (
feature_extractor.size
if isinstance(feature_extractor.size , SCREAMING_SNAKE_CASE_ )
else feature_extractor.size['''shortest_edge''']
)
UpperCamelCase :Any = transforms.Normalize(mean=feature_extractor.image_mean , std=feature_extractor.image_std )
set_requires_grad(self.text_encoder , SCREAMING_SNAKE_CASE_ )
set_requires_grad(self.clip_model , SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ = "auto" ) -> Tuple:
if slice_size == "auto":
# half the attention head size is usually a good trade-off between
# speed and memory
UpperCamelCase :Tuple = self.unet.config.attention_head_dim // 2
self.unet.set_attention_slice(SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self ) -> int:
self.enable_attention_slicing(SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self ) -> str:
set_requires_grad(self.vae , SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self ) -> Union[str, Any]:
set_requires_grad(self.vae , SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self ) -> int:
set_requires_grad(self.unet , SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self ) -> str:
set_requires_grad(self.unet , SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Any:
# get the original timestep using init_timestep
UpperCamelCase :Union[str, Any] = min(int(num_inference_steps * strength ) , SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Optional[Any] = max(num_inference_steps - init_timestep , 0 )
UpperCamelCase :Optional[Any] = self.scheduler.timesteps[t_start:]
return timesteps, num_inference_steps - t_start
def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None ) -> int:
if not isinstance(SCREAMING_SNAKE_CASE_ , torch.Tensor ):
raise ValueError(F'''`image` has to be of type `torch.Tensor` but is {type(SCREAMING_SNAKE_CASE_ )}''' )
UpperCamelCase :Tuple = image.to(device=SCREAMING_SNAKE_CASE_ , dtype=SCREAMING_SNAKE_CASE_ )
if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ):
UpperCamelCase :int = [
self.vae.encode(image[i : i + 1] ).latent_dist.sample(generator[i] ) for i in range(SCREAMING_SNAKE_CASE_ )
]
UpperCamelCase :List[str] = torch.cat(SCREAMING_SNAKE_CASE_ , dim=0 )
else:
UpperCamelCase :Any = self.vae.encode(SCREAMING_SNAKE_CASE_ ).latent_dist.sample(SCREAMING_SNAKE_CASE_ )
# Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor
UpperCamelCase :List[str] = 0.1_8215 * init_latents
UpperCamelCase :Optional[Any] = init_latents.repeat_interleave(SCREAMING_SNAKE_CASE_ , dim=0 )
UpperCamelCase :List[Any] = randn_tensor(init_latents.shape , generator=SCREAMING_SNAKE_CASE_ , device=SCREAMING_SNAKE_CASE_ , dtype=SCREAMING_SNAKE_CASE_ )
# get latents
UpperCamelCase :Optional[Any] = self.scheduler.add_noise(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
UpperCamelCase :str = init_latents
return latents
def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ ) -> List[str]:
UpperCamelCase :List[str] = self.coca_transform(SCREAMING_SNAKE_CASE_ ).unsqueeze(0 )
with torch.no_grad(), torch.cuda.amp.autocast():
UpperCamelCase :Any = self.coca_model.generate(transformed_image.to(device=self.device , dtype=self.coca_model.dtype ) )
UpperCamelCase :List[Any] = self.coca_tokenizer.decode(generated[0].cpu().numpy() )
return generated.split('''<end_of_text>''' )[0].replace('''<start_of_text>''' , '''''' ).rstrip(''' .,''' )
def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> List[Any]:
UpperCamelCase :str = self.feature_extractor.preprocess(SCREAMING_SNAKE_CASE_ )
UpperCamelCase :List[str] = torch.from_numpy(clip_image_input['''pixel_values'''][0] ).unsqueeze(0 ).to(self.device ).half()
UpperCamelCase :int = self.clip_model.get_image_features(SCREAMING_SNAKE_CASE_ )
UpperCamelCase :str = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Union[str, Any] = image_embeddings_clip.repeat_interleave(SCREAMING_SNAKE_CASE_ , dim=0 )
return image_embeddings_clip
@torch.enable_grad()
def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ) -> Optional[int]:
UpperCamelCase :List[str] = latents.detach().requires_grad_()
UpperCamelCase :List[str] = self.scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# predict the noise residual
UpperCamelCase :List[Any] = self.unet(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ ).sample
if isinstance(self.scheduler , (PNDMScheduler, DDIMScheduler, DPMSolverMultistepScheduler) ):
UpperCamelCase :List[str] = self.scheduler.alphas_cumprod[timestep]
UpperCamelCase :Optional[int] = 1 - alpha_prod_t
# compute predicted original sample from predicted noise also called
# "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
UpperCamelCase :List[Any] = (latents - beta_prod_t ** 0.5 * noise_pred) / alpha_prod_t ** 0.5
UpperCamelCase :int = torch.sqrt(SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Tuple = pred_original_sample * (fac) + latents * (1 - fac)
elif isinstance(self.scheduler , SCREAMING_SNAKE_CASE_ ):
UpperCamelCase :str = self.scheduler.sigmas[index]
UpperCamelCase :Union[str, Any] = latents - sigma * noise_pred
else:
raise ValueError(F'''scheduler type {type(self.scheduler )} not supported''' )
# Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor
UpperCamelCase :int = 1 / 0.1_8215 * sample
UpperCamelCase :List[Any] = self.vae.decode(SCREAMING_SNAKE_CASE_ ).sample
UpperCamelCase :str = (image / 2 + 0.5).clamp(0 , 1 )
UpperCamelCase :List[str] = transforms.Resize(self.feature_extractor_size )(SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Any = self.normalize(SCREAMING_SNAKE_CASE_ ).to(latents.dtype )
UpperCamelCase :List[Any] = self.clip_model.get_image_features(SCREAMING_SNAKE_CASE_ )
UpperCamelCase :str = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Union[str, Any] = spherical_dist_loss(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).mean() * clip_guidance_scale
UpperCamelCase :Union[str, Any] = -torch.autograd.grad(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )[0]
if isinstance(self.scheduler , SCREAMING_SNAKE_CASE_ ):
UpperCamelCase :Dict = latents.detach() + grads * (sigma**2)
UpperCamelCase :Optional[Any] = noise_pred_original
else:
UpperCamelCase :List[str] = noise_pred_original - torch.sqrt(SCREAMING_SNAKE_CASE_ ) * grads
return noise_pred, latents
@torch.no_grad()
def __call__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 512 , SCREAMING_SNAKE_CASE_ = 512 , SCREAMING_SNAKE_CASE_ = 0.6 , SCREAMING_SNAKE_CASE_ = 50 , SCREAMING_SNAKE_CASE_ = 7.5 , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = 100 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "pil" , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = 0.8 , SCREAMING_SNAKE_CASE_ = 0.1 , SCREAMING_SNAKE_CASE_ = 0.1 , ) -> Dict:
if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) and len(SCREAMING_SNAKE_CASE_ ) != batch_size:
raise ValueError(F'''You have passed {batch_size} batch_size, but only {len(SCREAMING_SNAKE_CASE_ )} generators.''' )
if height % 8 != 0 or width % 8 != 0:
raise ValueError(F'''`height` and `width` have to be divisible by 8 but are {height} and {width}.''' )
if isinstance(SCREAMING_SNAKE_CASE_ , torch.Generator ) and batch_size > 1:
UpperCamelCase :Optional[int] = [generator] + [None] * (batch_size - 1)
UpperCamelCase :Tuple = [
('''model''', self.coca_model is None),
('''tokenizer''', self.coca_tokenizer is None),
('''transform''', self.coca_transform is None),
]
UpperCamelCase :Union[str, Any] = [x[0] for x in coca_is_none if x[1]]
UpperCamelCase :Dict = ''', '''.join(SCREAMING_SNAKE_CASE_ )
# generate prompts with coca model if prompt is None
if content_prompt is None:
if len(SCREAMING_SNAKE_CASE_ ):
raise ValueError(
F'''Content prompt is None and CoCa [{coca_is_none_str}] is None.'''
F'''Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.''' )
UpperCamelCase :Any = self.get_image_description(SCREAMING_SNAKE_CASE_ )
if style_prompt is None:
if len(SCREAMING_SNAKE_CASE_ ):
raise ValueError(
F'''Style prompt is None and CoCa [{coca_is_none_str}] is None.'''
F''' Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.''' )
UpperCamelCase :str = self.get_image_description(SCREAMING_SNAKE_CASE_ )
# get prompt text embeddings for content and style
UpperCamelCase :List[Any] = self.tokenizer(
SCREAMING_SNAKE_CASE_ , padding='''max_length''' , max_length=self.tokenizer.model_max_length , truncation=SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' , )
UpperCamelCase :Dict = self.text_encoder(content_text_input.input_ids.to(self.device ) )[0]
UpperCamelCase :List[Any] = self.tokenizer(
SCREAMING_SNAKE_CASE_ , padding='''max_length''' , max_length=self.tokenizer.model_max_length , truncation=SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' , )
UpperCamelCase :Tuple = self.text_encoder(style_text_input.input_ids.to(self.device ) )[0]
UpperCamelCase :Dict = slerp(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# duplicate text embeddings for each generation per prompt
UpperCamelCase :Union[str, Any] = text_embeddings.repeat_interleave(SCREAMING_SNAKE_CASE_ , dim=0 )
# set timesteps
UpperCamelCase :str = '''offset''' in set(inspect.signature(self.scheduler.set_timesteps ).parameters.keys() )
UpperCamelCase :List[str] = {}
if accepts_offset:
UpperCamelCase :Tuple = 1
self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
# Some schedulers like PNDM have timesteps as arrays
# It's more optimized to move all timesteps to correct device beforehand
self.scheduler.timesteps.to(self.device )
UpperCamelCase , UpperCamelCase :Tuple = self.get_timesteps(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , self.device )
UpperCamelCase :Any = timesteps[:1].repeat(SCREAMING_SNAKE_CASE_ )
# Preprocess image
UpperCamelCase :Union[str, Any] = preprocess(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Optional[Any] = self.prepare_latents(
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , text_embeddings.dtype , self.device , SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Dict = preprocess(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Optional[Any] = self.prepare_latents(
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , text_embeddings.dtype , self.device , SCREAMING_SNAKE_CASE_ )
UpperCamelCase :str = slerp(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
if clip_guidance_scale > 0:
UpperCamelCase :Dict = self.get_clip_image_embeddings(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Optional[int] = self.get_clip_image_embeddings(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Optional[Any] = slerp(
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
# corresponds to doing no classifier free guidance.
UpperCamelCase :Optional[int] = guidance_scale > 1.0
# get unconditional embeddings for classifier free guidance
if do_classifier_free_guidance:
UpperCamelCase :Any = content_text_input.input_ids.shape[-1]
UpperCamelCase :Any = self.tokenizer([''''''] , padding='''max_length''' , max_length=SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' )
UpperCamelCase :Optional[Any] = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0]
# duplicate unconditional embeddings for each generation per prompt
UpperCamelCase :Optional[int] = uncond_embeddings.repeat_interleave(SCREAMING_SNAKE_CASE_ , dim=0 )
# For classifier free guidance, we need to do two forward passes.
# Here we concatenate the unconditional and text embeddings into a single batch
# to avoid doing two forward passes
UpperCamelCase :str = torch.cat([uncond_embeddings, text_embeddings] )
# get the initial random noise unless the user supplied it
# Unlike in other pipelines, latents need to be generated in the target device
# for 1-to-1 results reproducibility with the CompVis implementation.
# However this currently doesn't work in `mps`.
UpperCamelCase :Any = (batch_size, self.unet.config.in_channels, height // 8, width // 8)
UpperCamelCase :int = text_embeddings.dtype
if latents is None:
if self.device.type == "mps":
# randn does not work reproducibly on mps
UpperCamelCase :List[str] = torch.randn(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device='''cpu''' , dtype=SCREAMING_SNAKE_CASE_ ).to(
self.device )
else:
UpperCamelCase :int = torch.randn(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device=self.device , dtype=SCREAMING_SNAKE_CASE_ )
else:
if latents.shape != latents_shape:
raise ValueError(F'''Unexpected latents shape, got {latents.shape}, expected {latents_shape}''' )
UpperCamelCase :str = latents.to(self.device )
# scale the initial noise by the standard deviation required by the scheduler
UpperCamelCase :Union[str, Any] = latents * self.scheduler.init_noise_sigma
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
# and should be between [0, 1]
UpperCamelCase :Optional[int] = '''eta''' in set(inspect.signature(self.scheduler.step ).parameters.keys() )
UpperCamelCase :Dict = {}
if accepts_eta:
UpperCamelCase :int = eta
# check if the scheduler accepts generator
UpperCamelCase :Optional[int] = '''generator''' in set(inspect.signature(self.scheduler.step ).parameters.keys() )
if accepts_generator:
UpperCamelCase :List[str] = generator
with self.progress_bar(total=SCREAMING_SNAKE_CASE_ ):
for i, t in enumerate(SCREAMING_SNAKE_CASE_ ):
# expand the latents if we are doing classifier free guidance
UpperCamelCase :Optional[int] = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents
UpperCamelCase :List[Any] = self.scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# predict the noise residual
UpperCamelCase :List[str] = self.unet(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ ).sample
# perform classifier free guidance
if do_classifier_free_guidance:
UpperCamelCase , UpperCamelCase :Any = noise_pred.chunk(2 )
UpperCamelCase :Optional[Any] = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
# perform clip guidance
if clip_guidance_scale > 0:
UpperCamelCase :int = (
text_embeddings.chunk(2 )[1] if do_classifier_free_guidance else text_embeddings
)
UpperCamelCase , UpperCamelCase :str = self.cond_fn(
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , )
# compute the previous noisy sample x_t -> x_t-1
UpperCamelCase :List[str] = self.scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample
# Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor
UpperCamelCase :List[Any] = 1 / 0.1_8215 * latents
UpperCamelCase :Optional[Any] = self.vae.decode(SCREAMING_SNAKE_CASE_ ).sample
UpperCamelCase :str = (image / 2 + 0.5).clamp(0 , 1 )
UpperCamelCase :Dict = image.cpu().permute(0 , 2 , 3 , 1 ).numpy()
if output_type == "pil":
UpperCamelCase :List[str] = self.numpy_to_pil(SCREAMING_SNAKE_CASE_ )
if not return_dict:
return (image, None)
return StableDiffusionPipelineOutput(images=SCREAMING_SNAKE_CASE_ , nsfw_content_detected=SCREAMING_SNAKE_CASE_ )
| 658 | 0 |
def _SCREAMING_SNAKE_CASE ( snake_case , snake_case , snake_case ) -> Tuple:
def count_of_possible_combinations(snake_case ) -> int:
if target < 0:
return 0
if target == 0:
return 1
return sum(count_of_possible_combinations(target - item ) for item in array )
return count_of_possible_combinations(SCREAMING_SNAKE_CASE__ )
def _SCREAMING_SNAKE_CASE ( snake_case , snake_case , snake_case ) -> str:
def count_of_possible_combinations_with_dp_array(
snake_case , snake_case ) -> int:
if target < 0:
return 0
if target == 0:
return 1
if dp_array[target] != -1:
return dp_array[target]
_UpperCAmelCase = sum(
count_of_possible_combinations_with_dp_array(target - item , SCREAMING_SNAKE_CASE__ )
for item in array )
_UpperCAmelCase = answer
return answer
_UpperCAmelCase = [-1] * (target + 1)
return count_of_possible_combinations_with_dp_array(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
def _SCREAMING_SNAKE_CASE ( snake_case , snake_case , snake_case ) -> Dict:
_UpperCAmelCase = [0] * (target + 1)
_UpperCAmelCase = 1
for i in range(1 , target + 1 ):
for j in range(SCREAMING_SNAKE_CASE__ ):
if i - array[j] >= 0:
dp_array[i] += dp_array[i - array[j]]
return dp_array[target]
if __name__ == "__main__":
import doctest
doctest.testmod()
a = 3
a = 5
a = [1, 2, 5]
print(combination_sum_iv(n, array, target)) | 518 |
from __future__ import annotations
def _A ( SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : int ):
UpperCamelCase :list[list[int]] = []
UpperCamelCase :list[int] = []
UpperCamelCase :List[str] = 0
UpperCamelCase :Any = sum(SCREAMING_SNAKE_CASE__ )
create_state_space_tree(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
return result
def _A ( SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : list[list[int]] , SCREAMING_SNAKE_CASE__ : int , ):
if sum(SCREAMING_SNAKE_CASE__ ) > max_sum or (remaining_nums_sum + sum(SCREAMING_SNAKE_CASE__ )) < max_sum:
return
if sum(SCREAMING_SNAKE_CASE__ ) == max_sum:
result.append(SCREAMING_SNAKE_CASE__ )
return
for index in range(SCREAMING_SNAKE_CASE__ , len(SCREAMING_SNAKE_CASE__ ) ):
create_state_space_tree(
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , index + 1 , [*path, nums[index]] , SCREAMING_SNAKE_CASE__ , remaining_nums_sum - nums[index] , )
__snake_case = [3, 34, 4, 12, 5, 2]
__snake_case = 9
__snake_case = generate_sum_of_subsets_soln(nums, max_sum)
print(*result)
| 658 | 0 |
import math_equivalence # From: git+https://github.com/hendrycks/math.git
import datasets
UpperCAmelCase__ = "\\n@article{hendrycksmath2021,\n title={Measuring Mathematical Problem Solving With the MATH Dataset},\n author={Dan Hendrycks\n and Collin Burns\n and Saurav Kadavath\n and Akul Arora\n and Steven Basart\n and Eric Tang\n and Dawn Song\n and Jacob Steinhardt},\n journal={arXiv preprint arXiv:2103.03874},\n year={2021}\n}\n"
UpperCAmelCase__ = "\\nThis metric is used to assess performance on the Mathematics Aptitude Test of Heuristics (MATH) dataset.\nIt first canonicalizes the inputs (e.g., converting \"1/2\" to \"\\frac{1}{2}\") and then computes accuracy.\n"
UpperCAmelCase__ = R"\nCalculates accuracy after canonicalizing inputs.\n\nArgs:\n predictions: list of predictions to score. Each prediction\n is a string that contains natural language and LaTex.\n references: list of reference for each prediction. Each\n reference is a string that contains natural language\n and LaTex.\nReturns:\n accuracy: accuracy after canonicalizing inputs\n (e.g., converting \"1/2\" to \"\\frac{1}{2}\")\n\nExamples:\n >>> metric = datasets.load_metric(\"competition_math\")\n >>> results = metric.compute(references=[\"\\frac{1}{2}\"], predictions=[\"1/2\"])\n >>> print(results)\n {'accuracy': 1.0}\n"
@datasets.utils.file_utils.add_end_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION )
class lowercase_ ( datasets.Metric ):
'''simple docstring'''
def __lowerCAmelCase ( self : Optional[int] ) ->Optional[Any]:
"""simple docstring"""
return datasets.MetricInfo(
description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(
{
'''predictions''': datasets.Value('''string''' ),
'''references''': datasets.Value('''string''' ),
} ) , homepage='''https://github.com/hendrycks/math''' , codebase_urls=['''https://github.com/hendrycks/math'''] , )
def __lowerCAmelCase ( self : Optional[Any] , __UpperCAmelCase : Any , __UpperCAmelCase : str ) ->Any:
"""simple docstring"""
a = 0.0
for i, j in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ):
n_correct += 1.0 if math_equivalence.is_equiv(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else 0.0
a = n_correct / len(SCREAMING_SNAKE_CASE_ )
return {
"accuracy": accuracy,
}
| 117 |
def _A ( SCREAMING_SNAKE_CASE__ : int ):
if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
raise ValueError('''check_bouncy() accepts only integer arguments''' )
UpperCamelCase :int = str(SCREAMING_SNAKE_CASE__ )
UpperCamelCase :Optional[Any] = ''''''.join(sorted(SCREAMING_SNAKE_CASE__ ) )
return sorted_str_n != str_n and sorted_str_n[::-1] != str_n
def _A ( SCREAMING_SNAKE_CASE__ : float = 99 ):
if not 0 < percent < 100:
raise ValueError('''solution() only accepts values from 0 to 100''' )
UpperCamelCase :Tuple = 0
UpperCamelCase :str = 1
while True:
if check_bouncy(SCREAMING_SNAKE_CASE__ ):
bouncy_num += 1
if (bouncy_num / num) * 100 >= percent:
return num
num += 1
if __name__ == "__main__":
from doctest import testmod
testmod()
print(f'''{solution(99)}''')
| 658 | 0 |
from typing import List
import jiwer
import jiwer.transforms as tr
from packaging import version
import datasets
from datasets.config import PY_VERSION
if PY_VERSION < version.parse('3.8'):
import importlib_metadata
else:
import importlib.metadata as importlib_metadata
__UpperCamelCase : Dict = ''
if version.parse(importlib_metadata.version('jiwer')) < version.parse('2.3.0'):
class lowercase__ ( tr.AbstractTransform):
def __init__( self : List[str] , UpperCamelCase__ : List[str] = " " ):
'''simple docstring'''
SCREAMING_SNAKE_CASE : str = sentence_delimiter
def __A ( self : List[str] , UpperCamelCase__ : Optional[Any] ):
'''simple docstring'''
return list(SCREAMING_SNAKE_CASE_ )
def __A ( self : Any , UpperCamelCase__ : Union[str, Any] ):
'''simple docstring'''
SCREAMING_SNAKE_CASE : str = []
for sent_idx, sentence in enumerate(SCREAMING_SNAKE_CASE_ ):
chars.extend(self.process_string(SCREAMING_SNAKE_CASE_ ) )
if self.sentence_delimiter is not None and self.sentence_delimiter != "" and sent_idx < len(SCREAMING_SNAKE_CASE_ ) - 1:
chars.append(self.sentence_delimiter )
return chars
__UpperCamelCase : Optional[int] = tr.Compose(
[tr.RemoveMultipleSpaces(), tr.Strip(), SentencesToListOfCharacters(SENTENCE_DELIMITER)]
)
else:
__UpperCamelCase : List[Any] = tr.Compose(
[
tr.RemoveMultipleSpaces(),
tr.Strip(),
tr.ReduceToSingleSentence(SENTENCE_DELIMITER),
tr.ReduceToListOfListOfChars(),
]
)
__UpperCamelCase : str = '\\n@inproceedings{inproceedings,\n author = {Morris, Andrew and Maier, Viktoria and Green, Phil},\n year = {2004},\n month = {01},\n pages = {},\n title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.}\n}\n'
__UpperCamelCase : Optional[Any] = '\\nCharacter error rate (CER) is a common metric of the performance of an automatic speech recognition system.\n\nCER is similar to Word Error Rate (WER), but operates on character instead of word. Please refer to docs of WER for further information.\n\nCharacter error rate can be computed as:\n\nCER = (S + D + I) / N = (S + D + I) / (S + D + C)\n\nwhere\n\nS is the number of substitutions,\nD is the number of deletions,\nI is the number of insertions,\nC is the number of correct characters,\nN is the number of characters in the reference (N=S+D+C).\n\nCER\'s output is not always a number between 0 and 1, in particular when there is a high number of insertions. This value is often associated to the percentage of characters that were incorrectly predicted. The lower the value, the better the\nperformance of the ASR system with a CER of 0 being a perfect score.\n'
__UpperCamelCase : Optional[Any] = '\nComputes CER score of transcribed segments against references.\nArgs:\n references: list of references for each speech input.\n predictions: list of transcribtions to score.\n concatenate_texts: Whether or not to concatenate sentences before evaluation, set to True for more accurate result.\nReturns:\n (float): the character error rate\n\nExamples:\n\n >>> predictions = [\"this is the prediction\", \"there is an other sample\"]\n >>> references = [\"this is the reference\", \"there is another one\"]\n >>> cer = datasets.load_metric(\"cer\")\n >>> cer_score = cer.compute(predictions=predictions, references=references)\n >>> print(cer_score)\n 0.34146341463414637\n'
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION)
class lowercase__ ( datasets.Metric):
def __A ( self : Optional[int] ):
'''simple docstring'''
return datasets.MetricInfo(
description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(
{
'''predictions''': datasets.Value('''string''' , id='''sequence''' ),
'''references''': datasets.Value('''string''' , id='''sequence''' ),
} ) , codebase_urls=['''https://github.com/jitsi/jiwer/'''] , reference_urls=[
'''https://en.wikipedia.org/wiki/Word_error_rate''',
'''https://sites.google.com/site/textdigitisation/qualitymeasures/computingerrorrates''',
] , )
def __A ( self : Any , UpperCamelCase__ : Dict , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Optional[int]=False ):
'''simple docstring'''
if concatenate_texts:
return jiwer.compute_measures(
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , truth_transform=SCREAMING_SNAKE_CASE_ , hypothesis_transform=SCREAMING_SNAKE_CASE_ , )["wer"]
SCREAMING_SNAKE_CASE : List[str] = 0
SCREAMING_SNAKE_CASE : str = 0
for prediction, reference in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ):
SCREAMING_SNAKE_CASE : str = jiwer.compute_measures(
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , truth_transform=SCREAMING_SNAKE_CASE_ , hypothesis_transform=SCREAMING_SNAKE_CASE_ , )
incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
total += measures["substitutions"] + measures["deletions"] + measures["hits"]
return incorrect / total
| 248 |
def _A ( SCREAMING_SNAKE_CASE__ : str ):
UpperCamelCase :Union[str, Any] = hex_num.strip()
if not hex_num:
raise ValueError('''No value was passed to the function''' )
UpperCamelCase :str = hex_num[0] == '''-'''
if is_negative:
UpperCamelCase :Union[str, Any] = hex_num[1:]
try:
UpperCamelCase :Optional[Any] = int(SCREAMING_SNAKE_CASE__ , 16 )
except ValueError:
raise ValueError('''Invalid value was passed to the function''' )
UpperCamelCase :Dict = ''''''
while int_num > 0:
UpperCamelCase :Tuple = str(int_num % 2 ) + bin_str
int_num >>= 1
return int(('''-''' + bin_str) if is_negative else bin_str )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 658 | 0 |
import unittest
from transformers import AlbertTokenizer, AlbertTokenizerFast
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow
from ...test_tokenization_common import TokenizerTesterMixin
lowercase__ =get_tests_dir('fixtures/spiece.model')
@require_sentencepiece
@require_tokenizers
class UpperCamelCase__ ( __lowercase ,unittest.TestCase ):
_SCREAMING_SNAKE_CASE : Any = AlbertTokenizer
_SCREAMING_SNAKE_CASE : str = AlbertTokenizerFast
_SCREAMING_SNAKE_CASE : Optional[int] = True
_SCREAMING_SNAKE_CASE : Any = True
_SCREAMING_SNAKE_CASE : str = True
def lowerCAmelCase (self : Any ):
super().setUp()
# We have a SentencePiece fixture for testing
__a : Any = AlbertTokenizer(SCREAMING_SNAKE_CASE_ )
tokenizer.save_pretrained(self.tmpdirname )
def lowerCAmelCase (self : List[str] , snake_case_ : int ):
__a : int = '''this is a test'''
__a : Any = '''this is a test'''
return input_text, output_text
def lowerCAmelCase (self : Dict ):
__a : str = '''<pad>'''
__a : Union[str, Any] = 0
self.assertEqual(self.get_tokenizer()._convert_token_to_id(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ )
self.assertEqual(self.get_tokenizer()._convert_id_to_token(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ )
def lowerCAmelCase (self : Tuple ):
__a : int = list(self.get_tokenizer().get_vocab().keys() )
self.assertEqual(vocab_keys[0] , '''<pad>''' )
self.assertEqual(vocab_keys[1] , '''<unk>''' )
self.assertEqual(vocab_keys[-1] , '''▁eloquent''' )
self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 3_0_0_0_0 )
def lowerCAmelCase (self : Union[str, Any] ):
self.assertEqual(self.get_tokenizer().vocab_size , 3_0_0_0_0 )
def lowerCAmelCase (self : List[str] ):
if not self.test_rust_tokenizer:
return
__a : List[Any] = self.get_tokenizer()
__a : List[str] = self.get_rust_tokenizer()
__a : Optional[int] = '''I was born in 92000, and this is falsé.'''
__a : Any = tokenizer.tokenize(SCREAMING_SNAKE_CASE_ )
__a : str = rust_tokenizer.tokenize(SCREAMING_SNAKE_CASE_ )
self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
__a : Any = tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ )
__a : Optional[int] = rust_tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ )
self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
__a : Optional[Any] = self.get_rust_tokenizer()
__a : Any = tokenizer.encode(SCREAMING_SNAKE_CASE_ )
__a : Dict = rust_tokenizer.encode(SCREAMING_SNAKE_CASE_ )
self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
def lowerCAmelCase (self : Union[str, Any] ):
__a : Optional[Any] = AlbertTokenizer(SCREAMING_SNAKE_CASE_ , keep_accents=SCREAMING_SNAKE_CASE_ )
__a : Any = tokenizer.tokenize('''This is a test''' )
self.assertListEqual(SCREAMING_SNAKE_CASE_ , ['''▁this''', '''▁is''', '''▁a''', '''▁test'''] )
self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) , [4_8, 2_5, 2_1, 1_2_8_9] )
__a : Optional[Any] = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' )
self.assertListEqual(
SCREAMING_SNAKE_CASE_ , ['''▁i''', '''▁was''', '''▁born''', '''▁in''', '''▁9''', '''2000''', ''',''', '''▁and''', '''▁this''', '''▁is''', '''▁fal''', '''s''', '''é''', '''.'''] )
__a : Optional[Any] = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ )
self.assertListEqual(SCREAMING_SNAKE_CASE_ , [3_1, 2_3, 3_8_6, 1_9, 5_6_1, 3_0_5_0, 1_5, 1_7, 4_8, 2_5, 8_2_5_6, 1_8, 1, 9] )
__a : Optional[Any] = tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE_ )
self.assertListEqual(
SCREAMING_SNAKE_CASE_ , ['''▁i''', '''▁was''', '''▁born''', '''▁in''', '''▁9''', '''2000''', ''',''', '''▁and''', '''▁this''', '''▁is''', '''▁fal''', '''s''', '''<unk>''', '''.'''] , )
def lowerCAmelCase (self : List[Any] ):
__a : int = AlbertTokenizer(SCREAMING_SNAKE_CASE_ )
__a : str = tokenizer.encode('''sequence builders''' )
__a : Union[str, Any] = tokenizer.encode('''multi-sequence build''' )
__a : str = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE_ )
__a : Union[str, Any] = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
assert encoded_sentence == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id]
assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [
tokenizer.sep_token_id
]
@slow
def lowerCAmelCase (self : List[Any] ):
# fmt: off
__a : Optional[int] = {'''attention_mask''': [[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, 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, 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, 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], [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, 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]], '''input_ids''': [[2, 2_1_9_7_0, 1_3, 5, 6_0_9_2, 1_6_7, 2_8, 7_1_0_3, 2_1_5_3, 6_7_3, 8, 7_0_2_8, 1_2_0_5_1, 1_8, 1_7, 7_1_0_3, 2_1_5_3, 6_7_3, 8, 3_5_1_5, 1_8_6_8_4, 8, 4_4_6_1, 6, 1_9_2_7, 2_9_7, 8, 1_2_0_6_0, 2_6_0_7, 1_8, 1_3, 5, 4_4_6_1, 1_5, 1_0_5_3_8, 3_8, 8, 1_3_5, 1_5, 8_2_2, 5_8, 1_5, 9_9_3, 1_0_3_6_3, 1_5, 1_4_6_0, 8_0_0_5, 4_4_6_1, 1_5, 9_9_3, 2_5_5, 2_3_2_8, 9, 9, 9, 6, 2_6, 1_1_1_2, 8_1_6, 3_2_6_0, 1_3, 5, 1_0_3, 2_3_7_7, 6, 1_7, 1_1_1_2, 8_1_6, 2_7_8_2, 1_3, 5, 1_0_3, 1_0_6_4_1, 6, 2_9, 8_4, 2_5_1_2, 2_4_3_0, 7_8_2, 1_8_6_8_4, 2_7_6_1, 1_9, 8_0_8, 2_4_3_0, 2_5_5_6, 1_7, 8_5_5, 1_4_8_0, 9_4_7_7, 4_0_9_1, 1_2_8, 1_1_7_1_2, 1_5, 7_1_0_3, 2_1_5_3, 6_7_3, 1_7, 2_4_8_8_3, 9_9_9_0, 9, 3], [2, 1_1_5_0_2, 2_5, 1_0_0_6, 2_0, 7_8_2, 8, 1_1_8_0_9, 8_5_5, 1_7_3_2, 1_9_3_9_3, 1_8_6_6_7, 3_7, 3_6_7, 2_1_0_1_8, 6_9, 1_8_5_4, 3_4, 1_1_8_6_0, 1_9_1_2_4, 2_7, 1_5_6, 2_2_5, 1_7, 1_9_3, 4_1_4_1, 1_9, 6_5, 9_1_2_4, 9, 3, 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], [2, 1_4, 2_2_3_1, 8_8_6, 2_3_8_5, 1_7_6_5_9, 8_4, 1_4, 1_6_7_9_2, 1_9_5_2, 9, 3, 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]], '''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, 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, 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]]} # noqa: E501
# fmt: on
self.tokenizer_integration_test_util(
expected_encoding=SCREAMING_SNAKE_CASE_ , model_name='''albert-base-v2''' , revision='''6b6560eaf5ff2e250b00c50f380c5389a9c2d82e''' , )
| 521 |
from __future__ import annotations
def _A ( SCREAMING_SNAKE_CASE__ : tuple[int, int] , SCREAMING_SNAKE_CASE__ : int ):
UpperCamelCase , UpperCamelCase :List[Any] = position
UpperCamelCase :Any = [
(y + 1, x + 2),
(y - 1, x + 2),
(y + 1, x - 2),
(y - 1, x - 2),
(y + 2, x + 1),
(y + 2, x - 1),
(y - 2, x + 1),
(y - 2, x - 1),
]
UpperCamelCase :Dict = []
for position in positions:
UpperCamelCase , UpperCamelCase :str = position
if 0 <= y_test < n and 0 <= x_test < n:
permissible_positions.append(SCREAMING_SNAKE_CASE__ )
return permissible_positions
def _A ( SCREAMING_SNAKE_CASE__ : list[list[int]] ):
return not any(elem == 0 for row in board for elem in row )
def _A ( SCREAMING_SNAKE_CASE__ : list[list[int]] , SCREAMING_SNAKE_CASE__ : tuple[int, int] , SCREAMING_SNAKE_CASE__ : int ):
if is_complete(SCREAMING_SNAKE_CASE__ ):
return True
for position in get_valid_pos(SCREAMING_SNAKE_CASE__ , len(SCREAMING_SNAKE_CASE__ ) ):
UpperCamelCase , UpperCamelCase :Optional[int] = position
if board[y][x] == 0:
UpperCamelCase :Any = curr + 1
if open_knight_tour_helper(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , curr + 1 ):
return True
UpperCamelCase :Union[str, Any] = 0
return False
def _A ( SCREAMING_SNAKE_CASE__ : int ):
UpperCamelCase :List[Any] = [[0 for i in range(SCREAMING_SNAKE_CASE__ )] for j in range(SCREAMING_SNAKE_CASE__ )]
for i in range(SCREAMING_SNAKE_CASE__ ):
for j in range(SCREAMING_SNAKE_CASE__ ):
UpperCamelCase :Tuple = 1
if open_knight_tour_helper(SCREAMING_SNAKE_CASE__ , (i, j) , 1 ):
return board
UpperCamelCase :str = 0
UpperCamelCase :List[Any] = F'''Open Kight Tour cannot be performed on a board of size {n}'''
raise ValueError(SCREAMING_SNAKE_CASE__ )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 658 | 0 |
"""simple docstring"""
import argparse
import json
import os
from pathlib import Path
import requests
import torch
from transformers import JukeboxConfig, JukeboxModel
from transformers.utils import logging
logging.set_verbosity_info()
UpperCAmelCase = logging.get_logger(__name__)
UpperCAmelCase = """https://openaipublic.azureedge.net/jukebox/models/"""
UpperCAmelCase = {
"""jukebox-1b-lyrics""": [
"""5b/vqvae.pth.tar""",
"""5b/prior_level_0.pth.tar""",
"""5b/prior_level_1.pth.tar""",
"""1b_lyrics/prior_level_2.pth.tar""",
],
"""jukebox-5b-lyrics""": [
"""5b/vqvae.pth.tar""",
"""5b/prior_level_0.pth.tar""",
"""5b/prior_level_1.pth.tar""",
"""5b_lyrics/prior_level_2.pth.tar""",
],
}
def __magic_name__ ( _lowerCamelCase: Optional[int] ) -> List[Any]:
'''simple docstring'''
if key.endswith('''.model.1.bias''' ) and len(key.split('''.''' ) ) > 10:
lowerCAmelCase = key.replace('''.model.1.bias''', '''.conv1d_1.bias''' )
elif key.endswith('''.model.1.weight''' ) and len(key.split('''.''' ) ) > 10:
lowerCAmelCase = key.replace('''.model.1.weight''', '''.conv1d_1.weight''' )
elif key.endswith('''.model.3.bias''' ) and len(key.split('''.''' ) ) > 10:
lowerCAmelCase = key.replace('''.model.3.bias''', '''.conv1d_2.bias''' )
elif key.endswith('''.model.3.weight''' ) and len(key.split('''.''' ) ) > 10:
lowerCAmelCase = key.replace('''.model.3.weight''', '''.conv1d_2.weight''' )
if "conditioner_blocks.0." in key:
lowerCAmelCase = key.replace('''conditioner_blocks.0''', '''conditioner_blocks''' )
if "prime_prior" in key:
lowerCAmelCase = key.replace('''prime_prior''', '''encoder''' )
if ".emb." in key and "total" not in key and "absolute" not in key and "relative" not in key:
lowerCAmelCase = key.replace('''.emb.''', '''.''' )
if key.endswith('''k''' ): # replace vqvae.X.k with vqvae.X.codebook
return key.replace('''.k''', '''.codebook''' )
if "y_emb." in key:
return key.replace('''y_emb.''', '''metadata_embedding.''' )
if "x_emb.emb." in key:
lowerCAmelCase = key.replace('''0.x_emb.emb''', '''embed_tokens''' )
if "prime_state_ln" in key:
return key.replace('''prime_state_ln''', '''encoder.final_layer_norm''' )
if ".ln" in key:
return key.replace('''.ln''', '''.layer_norm''' )
if "_ln" in key:
return key.replace('''_ln''', '''_layer_norm''' )
if "prime_state_proj" in key:
return key.replace('''prime_state_proj''', '''encoder.proj_in''' )
if "prime_x_out" in key:
return key.replace('''prime_x_out''', '''encoder.lm_head''' )
if "prior.x_out" in key:
return key.replace('''x_out''', '''fc_proj_out''' )
if "x_emb" in key:
return key.replace('''x_emb''', '''embed_tokens''' )
return key
def __magic_name__ ( _lowerCamelCase: str, _lowerCamelCase: Tuple, _lowerCamelCase: List[str], _lowerCamelCase: str ) -> Optional[int]:
'''simple docstring'''
lowerCAmelCase = {}
import re
lowerCAmelCase = re.compile(r'''encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)''' )
lowerCAmelCase = re.compile(
r'''encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)''' )
lowerCAmelCase = re.compile(r'''encoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)''' )
lowerCAmelCase = re.compile(r'''decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)''' )
lowerCAmelCase = re.compile(
r'''decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)''' )
lowerCAmelCase = re.compile(r'''decoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)''' )
lowerCAmelCase = re.compile(r'''conditioner_blocks.(\d*).cond.model.(\d*).(\d).(bias|weight)''' )
lowerCAmelCase = re.compile(
r'''conditioner_blocks.(\d*).cond.model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)''' )
lowerCAmelCase = re.compile(r'''conditioner_blocks.(\d*).cond.model.(\d*).(bias|weight)''' )
for original_key, value in state_dict.items():
# rename vqvae.encoder keys
if re_encoder_block_conv_in.fullmatch(SCREAMING_SNAKE_CASE__ ):
lowerCAmelCase = re_encoder_block_conv_in.match(SCREAMING_SNAKE_CASE__ )
lowerCAmelCase = regex_match.groups()
lowerCAmelCase = int(groups[2] ) * 2 + int(groups[3] )
lowerCAmelCase = F"""encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.{groups[-1]}"""
lowerCAmelCase = re_encoder_block_conv_in.sub(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ )
elif re_encoder_block_resnet.fullmatch(SCREAMING_SNAKE_CASE__ ):
lowerCAmelCase = re_encoder_block_resnet.match(SCREAMING_SNAKE_CASE__ )
lowerCAmelCase = regex_match.groups()
lowerCAmelCase = int(groups[2] ) * 2 + int(groups[3] )
lowerCAmelCase = {'''1''': 1, '''3''': 2}[groups[-2]]
lowerCAmelCase = F"""encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}."""
lowerCAmelCase = F"""resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}"""
lowerCAmelCase = prefix + resnet_block
lowerCAmelCase = re_encoder_block_resnet.sub(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ )
elif re_encoder_block_proj_out.fullmatch(SCREAMING_SNAKE_CASE__ ):
lowerCAmelCase = re_encoder_block_proj_out.match(SCREAMING_SNAKE_CASE__ )
lowerCAmelCase = regex_match.groups()
lowerCAmelCase = F"""encoders.{groups[0]}.level_blocks.{groups[1]}.proj_out.{groups[-1]}"""
lowerCAmelCase = re_encoder_block_proj_out.sub(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ )
# rename vqvae.decoder keys
elif re_decoder_block_conv_out.fullmatch(SCREAMING_SNAKE_CASE__ ):
lowerCAmelCase = re_decoder_block_conv_out.match(SCREAMING_SNAKE_CASE__ )
lowerCAmelCase = regex_match.groups()
lowerCAmelCase = int(groups[2] ) * 2 + int(groups[3] ) - 2
lowerCAmelCase = F"""decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.{groups[-1]}"""
lowerCAmelCase = re_decoder_block_conv_out.sub(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ )
elif re_decoder_block_resnet.fullmatch(SCREAMING_SNAKE_CASE__ ):
lowerCAmelCase = re_decoder_block_resnet.match(SCREAMING_SNAKE_CASE__ )
lowerCAmelCase = regex_match.groups()
lowerCAmelCase = int(groups[2] ) * 2 + int(groups[3] ) - 2
lowerCAmelCase = {'''1''': 1, '''3''': 2}[groups[-2]]
lowerCAmelCase = F"""decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}."""
lowerCAmelCase = F"""resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}"""
lowerCAmelCase = prefix + resnet_block
lowerCAmelCase = re_decoder_block_resnet.sub(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ )
elif re_decoder_block_proj_in.fullmatch(SCREAMING_SNAKE_CASE__ ):
lowerCAmelCase = re_decoder_block_proj_in.match(SCREAMING_SNAKE_CASE__ )
lowerCAmelCase = regex_match.groups()
lowerCAmelCase = F"""decoders.{groups[0]}.level_blocks.{groups[1]}.proj_in.{groups[-1]}"""
lowerCAmelCase = re_decoder_block_proj_in.sub(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ )
# rename prior cond.model to upsampler.upsample_block and resnet
elif re_prior_cond_conv_out.fullmatch(SCREAMING_SNAKE_CASE__ ):
lowerCAmelCase = re_prior_cond_conv_out.match(SCREAMING_SNAKE_CASE__ )
lowerCAmelCase = regex_match.groups()
lowerCAmelCase = int(groups[1] ) * 2 + int(groups[2] ) - 2
lowerCAmelCase = F"""conditioner_blocks.upsampler.upsample_block.{block_index}.{groups[-1]}"""
lowerCAmelCase = re_prior_cond_conv_out.sub(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ )
elif re_prior_cond_resnet.fullmatch(SCREAMING_SNAKE_CASE__ ):
lowerCAmelCase = re_prior_cond_resnet.match(SCREAMING_SNAKE_CASE__ )
lowerCAmelCase = regex_match.groups()
lowerCAmelCase = int(groups[1] ) * 2 + int(groups[2] ) - 2
lowerCAmelCase = {'''1''': 1, '''3''': 2}[groups[-2]]
lowerCAmelCase = F"""conditioner_blocks.upsampler.upsample_block.{block_index}."""
lowerCAmelCase = F"""resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}"""
lowerCAmelCase = prefix + resnet_block
lowerCAmelCase = re_prior_cond_resnet.sub(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ )
elif re_prior_cond_proj_in.fullmatch(SCREAMING_SNAKE_CASE__ ):
lowerCAmelCase = re_prior_cond_proj_in.match(SCREAMING_SNAKE_CASE__ )
lowerCAmelCase = regex_match.groups()
lowerCAmelCase = F"""conditioner_blocks.upsampler.proj_in.{groups[-1]}"""
lowerCAmelCase = re_prior_cond_proj_in.sub(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ )
# keep original key
else:
lowerCAmelCase = original_key
lowerCAmelCase = replace_key(SCREAMING_SNAKE_CASE__ )
if F"""{key_prefix}.{key}""" not in model_state_dict or key is None:
print(F"""failed converting {original_key} to {key}, does not match""" )
# handle missmatched shape
elif value.shape != model_state_dict[F"""{key_prefix}.{key}"""].shape:
lowerCAmelCase = model_state_dict[F"""{key_prefix}.{key}"""]
print(F"""{original_key}-> {key} : \nshape {val.shape} and { value.shape}, do not match""" )
lowerCAmelCase = original_key
lowerCAmelCase = original_key
lowerCAmelCase = value
return new_dict
@torch.no_grad()
def __magic_name__ ( _lowerCamelCase: Dict=None, _lowerCamelCase: Optional[Any]=None ) -> Union[str, Any]:
'''simple docstring'''
for file in MODEL_MAPPING[model_name]:
if not os.path.isfile(F"""{pytorch_dump_folder_path}/{file.split("/" )[-1]}""" ):
lowerCAmelCase = requests.get(F"""{PREFIX}{file}""", allow_redirects=SCREAMING_SNAKE_CASE__ )
os.makedirs(F"""{pytorch_dump_folder_path}/""", exist_ok=SCREAMING_SNAKE_CASE__ )
open(F"""{pytorch_dump_folder_path}/{file.split("/" )[-1]}""", '''wb''' ).write(r.content )
lowerCAmelCase = MODEL_MAPPING[model_name.split('''/''' )[-1]]
lowerCAmelCase = JukeboxConfig.from_pretrained(SCREAMING_SNAKE_CASE__ )
lowerCAmelCase = JukeboxModel(SCREAMING_SNAKE_CASE__ )
lowerCAmelCase = []
lowerCAmelCase = {}
for i, dict_name in enumerate(SCREAMING_SNAKE_CASE__ ):
lowerCAmelCase = torch.load(F"""{pytorch_dump_folder_path}/{dict_name.split("/" )[-1]}""" )['''model''']
lowerCAmelCase = {}
for k in old_dic.keys():
if k.endswith('''.b''' ):
lowerCAmelCase = old_dic[k]
elif k.endswith('''.w''' ):
lowerCAmelCase = old_dic[k]
elif "level_2" not in dict_name and "cond.model." in k:
lowerCAmelCase = old_dic[k]
else:
lowerCAmelCase = old_dic[k]
lowerCAmelCase = '''vqvae''' if i == 0 else F"""priors.{3 - i}"""
lowerCAmelCase = fix_jukebox_keys(SCREAMING_SNAKE_CASE__, model.state_dict(), SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ )
weight_dict.append(SCREAMING_SNAKE_CASE__ )
lowerCAmelCase = weight_dict.pop(0 )
model.vqvae.load_state_dict(SCREAMING_SNAKE_CASE__ )
for i in range(len(SCREAMING_SNAKE_CASE__ ) ):
model.priors[i].load_state_dict(weight_dict[2 - i] )
Path(SCREAMING_SNAKE_CASE__ ).mkdir(exist_ok=SCREAMING_SNAKE_CASE__ )
with open(F"""{pytorch_dump_folder_path}/mapping.json""", '''w''' ) as txtfile:
json.dump(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ )
print(F"""Saving model {model_name} to {pytorch_dump_folder_path}""" )
model.save_pretrained(SCREAMING_SNAKE_CASE__ )
return weight_dict
if __name__ == "__main__":
UpperCAmelCase = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"""--model_name""",
default="""jukebox-5b-lyrics""",
type=str,
help="""Name of the model you'd like to convert.""",
)
parser.add_argument(
"""--pytorch_dump_folder_path""",
default="""jukebox-5b-lyrics-converted""",
type=str,
help="""Path to the output PyTorch model directory.""",
)
UpperCAmelCase = parser.parse_args()
convert_openai_checkpoint(args.model_name, args.pytorch_dump_folder_path)
| 535 |
import copy
import tempfile
import unittest
from huggingface_hub import HfFolder, delete_repo
from parameterized import parameterized
from requests.exceptions import HTTPError
from transformers import AutoConfig, GenerationConfig
from transformers.testing_utils import TOKEN, USER, is_staging_test
class UpperCAmelCase_ ( unittest.TestCase ):
"""simple docstring"""
@parameterized.expand([(None,), ('''foo.json''',)] )
def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ ) -> List[str]:
UpperCamelCase :int = GenerationConfig(
do_sample=SCREAMING_SNAKE_CASE_ , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , )
with tempfile.TemporaryDirectory() as tmp_dir:
config.save_pretrained(SCREAMING_SNAKE_CASE_ , config_name=SCREAMING_SNAKE_CASE_ )
UpperCamelCase :str = GenerationConfig.from_pretrained(SCREAMING_SNAKE_CASE_ , config_name=SCREAMING_SNAKE_CASE_ )
# Checks parameters that were specified
self.assertEqual(loaded_config.do_sample , SCREAMING_SNAKE_CASE_ )
self.assertEqual(loaded_config.temperature , 0.7 )
self.assertEqual(loaded_config.length_penalty , 1.0 )
self.assertEqual(loaded_config.bad_words_ids , [[1, 2, 3], [4, 5]] )
# Checks parameters that were not specified (defaults)
self.assertEqual(loaded_config.top_k , 50 )
self.assertEqual(loaded_config.max_length , 20 )
self.assertEqual(loaded_config.max_time , SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self ) -> str:
UpperCamelCase :Optional[Any] = AutoConfig.from_pretrained('''gpt2''' )
UpperCamelCase :Union[str, Any] = GenerationConfig.from_model_config(SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Optional[Any] = GenerationConfig()
# The generation config has loaded a few non-default parameters from the model config
self.assertNotEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# One of those parameters is eos_token_id -- check if it matches
self.assertNotEqual(generation_config_from_model.eos_token_id , default_generation_config.eos_token_id )
self.assertEqual(generation_config_from_model.eos_token_id , model_config.eos_token_id )
def UpperCAmelCase ( self ) -> Dict:
UpperCamelCase :List[str] = GenerationConfig()
UpperCamelCase :List[str] = {
'''max_new_tokens''': 1024,
'''foo''': '''bar''',
}
UpperCamelCase :Dict = copy.deepcopy(SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Any = generation_config.update(**SCREAMING_SNAKE_CASE_ )
# update_kwargs was not modified (no side effects)
self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# update_kwargs was used to update the config on valid attributes
self.assertEqual(generation_config.max_new_tokens , 1024 )
# `.update()` returns a dictionary of unused kwargs
self.assertEqual(SCREAMING_SNAKE_CASE_ , {'''foo''': '''bar'''} )
def UpperCAmelCase ( self ) -> Optional[Any]:
UpperCamelCase :List[Any] = GenerationConfig()
UpperCamelCase :Tuple = '''bar'''
with tempfile.TemporaryDirectory('''test-generation-config''' ) as tmp_dir:
generation_config.save_pretrained(SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Any = GenerationConfig.from_pretrained(SCREAMING_SNAKE_CASE_ )
# update_kwargs was used to update the config on valid attributes
self.assertEqual(new_config.foo , '''bar''' )
UpperCamelCase :Union[str, Any] = GenerationConfig.from_model_config(SCREAMING_SNAKE_CASE_ )
assert not hasattr(SCREAMING_SNAKE_CASE_ , '''foo''' ) # no new kwargs should be initialized if from config
def UpperCAmelCase ( self ) -> Any:
UpperCamelCase :Dict = GenerationConfig()
self.assertEqual(default_config.temperature , 1.0 )
self.assertEqual(default_config.do_sample , SCREAMING_SNAKE_CASE_ )
self.assertEqual(default_config.num_beams , 1 )
UpperCamelCase :Tuple = GenerationConfig(
do_sample=SCREAMING_SNAKE_CASE_ , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , )
self.assertEqual(config.temperature , 0.7 )
self.assertEqual(config.do_sample , SCREAMING_SNAKE_CASE_ )
self.assertEqual(config.num_beams , 1 )
with tempfile.TemporaryDirectory() as tmp_dir:
config.save_pretrained(SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Tuple = GenerationConfig.from_pretrained(SCREAMING_SNAKE_CASE_ , temperature=1.0 )
self.assertEqual(loaded_config.temperature , 1.0 )
self.assertEqual(loaded_config.do_sample , SCREAMING_SNAKE_CASE_ )
self.assertEqual(loaded_config.num_beams , 1 ) # default value
@is_staging_test
class UpperCAmelCase_ ( unittest.TestCase ):
"""simple docstring"""
@classmethod
def UpperCAmelCase ( cls ) -> Optional[Any]:
UpperCamelCase :List[str] = TOKEN
HfFolder.save_token(SCREAMING_SNAKE_CASE_ )
@classmethod
def UpperCAmelCase ( cls ) -> Union[str, Any]:
try:
delete_repo(token=cls._token , repo_id='''test-generation-config''' )
except HTTPError:
pass
try:
delete_repo(token=cls._token , repo_id='''valid_org/test-generation-config-org''' )
except HTTPError:
pass
def UpperCAmelCase ( self ) -> Any:
UpperCamelCase :Optional[Any] = GenerationConfig(
do_sample=SCREAMING_SNAKE_CASE_ , temperature=0.7 , length_penalty=1.0 , )
config.push_to_hub('''test-generation-config''' , use_auth_token=self._token )
UpperCamelCase :List[Any] = GenerationConfig.from_pretrained(F'''{USER}/test-generation-config''' )
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(SCREAMING_SNAKE_CASE_ , getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) )
# Reset repo
delete_repo(token=self._token , repo_id='''test-generation-config''' )
# Push to hub via save_pretrained
with tempfile.TemporaryDirectory() as tmp_dir:
config.save_pretrained(
SCREAMING_SNAKE_CASE_ , repo_id='''test-generation-config''' , push_to_hub=SCREAMING_SNAKE_CASE_ , use_auth_token=self._token )
UpperCamelCase :Any = GenerationConfig.from_pretrained(F'''{USER}/test-generation-config''' )
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(SCREAMING_SNAKE_CASE_ , getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) )
def UpperCAmelCase ( self ) -> Union[str, Any]:
UpperCamelCase :List[str] = GenerationConfig(
do_sample=SCREAMING_SNAKE_CASE_ , temperature=0.7 , length_penalty=1.0 , )
config.push_to_hub('''valid_org/test-generation-config-org''' , use_auth_token=self._token )
UpperCamelCase :Any = GenerationConfig.from_pretrained('''valid_org/test-generation-config-org''' )
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(SCREAMING_SNAKE_CASE_ , getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) )
# Reset repo
delete_repo(token=self._token , repo_id='''valid_org/test-generation-config-org''' )
# Push to hub via save_pretrained
with tempfile.TemporaryDirectory() as tmp_dir:
config.save_pretrained(
SCREAMING_SNAKE_CASE_ , repo_id='''valid_org/test-generation-config-org''' , push_to_hub=SCREAMING_SNAKE_CASE_ , use_auth_token=self._token )
UpperCamelCase :Tuple = GenerationConfig.from_pretrained('''valid_org/test-generation-config-org''' )
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(SCREAMING_SNAKE_CASE_ , getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) )
| 658 | 0 |
"""simple docstring"""
import argparse
import os
import shutil
import torch
from emmental.modules import MagnitudeBinarizer, ThresholdBinarizer, TopKBinarizer
def __snake_case ( __A ) -> Any:
lowercase : Optional[Any] = args.pruning_method
lowercase : str = args.threshold
lowercase : Optional[int] = args.model_name_or_path.rstrip("""/""" )
lowercase : Union[str, Any] = args.target_model_path
print(F'''Load fine-pruned model from {model_name_or_path}''' )
lowercase : str = torch.load(os.path.join(SCREAMING_SNAKE_CASE__ ,"""pytorch_model.bin""" ) )
lowercase : List[str] = {}
for name, tensor in model.items():
if "embeddings" in name or "LayerNorm" in name or "pooler" in name:
lowercase : Union[str, Any] = tensor
print(F'''Copied layer {name}''' )
elif "classifier" in name or "qa_output" in name:
lowercase : Optional[int] = tensor
print(F'''Copied layer {name}''' )
elif "bias" in name:
lowercase : str = tensor
print(F'''Copied layer {name}''' )
else:
if pruning_method == "magnitude":
lowercase : str = MagnitudeBinarizer.apply(inputs=SCREAMING_SNAKE_CASE__ ,threshold=SCREAMING_SNAKE_CASE__ )
lowercase : Optional[int] = tensor * mask
print(F'''Pruned layer {name}''' )
elif pruning_method == "topK":
if "mask_scores" in name:
continue
lowercase : str = name[:-6]
lowercase : Union[str, Any] = model[F'''{prefix_}mask_scores''']
lowercase : int = TopKBinarizer.apply(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ )
lowercase : Dict = tensor * mask
print(F'''Pruned layer {name}''' )
elif pruning_method == "sigmoied_threshold":
if "mask_scores" in name:
continue
lowercase : List[str] = name[:-6]
lowercase : Optional[Any] = model[F'''{prefix_}mask_scores''']
lowercase : Union[str, Any] = ThresholdBinarizer.apply(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ )
lowercase : int = tensor * mask
print(F'''Pruned layer {name}''' )
elif pruning_method == "l0":
if "mask_scores" in name:
continue
lowercase : Union[str, Any] = name[:-6]
lowercase : Tuple = model[F'''{prefix_}mask_scores''']
lowercase : int = -0.1, 1.1
lowercase : Tuple = torch.sigmoid(SCREAMING_SNAKE_CASE__ )
lowercase : Any = s * (r - l) + l
lowercase : Optional[int] = s_bar.clamp(min=0.0 ,max=1.0 )
lowercase : Dict = tensor * mask
print(F'''Pruned layer {name}''' )
else:
raise ValueError("""Unknown pruning method""" )
if target_model_path is None:
lowercase : Tuple = os.path.join(
os.path.dirname(SCREAMING_SNAKE_CASE__ ) ,F'''bertarized_{os.path.basename(SCREAMING_SNAKE_CASE__ )}''' )
if not os.path.isdir(SCREAMING_SNAKE_CASE__ ):
shutil.copytree(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ )
print(F'''\nCreated folder {target_model_path}''' )
torch.save(SCREAMING_SNAKE_CASE__ ,os.path.join(SCREAMING_SNAKE_CASE__ ,"""pytorch_model.bin""" ) )
print("""\nPruned model saved! See you later!""" )
if __name__ == "__main__":
lowerCAmelCase: List[Any] =argparse.ArgumentParser()
parser.add_argument(
"--pruning_method",
choices=["l0", "magnitude", "topK", "sigmoied_threshold"],
type=str,
required=True,
help=(
"Pruning Method (l0 = L0 regularization, magnitude = Magnitude pruning, topK = Movement pruning,"
" sigmoied_threshold = Soft movement pruning)"
),
)
parser.add_argument(
"--threshold",
type=float,
required=False,
help=(
"For `magnitude` and `topK`, it is the level of remaining weights (in %) in the fine-pruned model."
"For `sigmoied_threshold`, it is the threshold \tau against which the (sigmoied) scores are compared."
"Not needed for `l0`"
),
)
parser.add_argument(
"--model_name_or_path",
type=str,
required=True,
help="Folder containing the model that was previously fine-pruned",
)
parser.add_argument(
"--target_model_path",
default=None,
type=str,
required=False,
help="Folder containing the model that was previously fine-pruned",
)
lowerCAmelCase: str =parser.parse_args()
main(args)
| 607 |
def _A ( SCREAMING_SNAKE_CASE__ : int ):
if length <= 0 or not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
raise ValueError('''Length must be a positive integer.''' )
return [n * (2 * n - 1) for n in range(SCREAMING_SNAKE_CASE__ )]
if __name__ == "__main__":
print(hexagonal_numbers(length=5))
print(hexagonal_numbers(length=10))
| 658 | 0 |
from __future__ import annotations
import matplotlib.pyplot as plt # type: ignore
import numpy
# initial triangle of Koch snowflake
UpperCamelCase : Union[str, Any] = numpy.array([0, 0])
UpperCamelCase : Any = numpy.array([0.5, 0.866_0254])
UpperCamelCase : Optional[int] = numpy.array([1, 0])
UpperCamelCase : Any = [VECTOR_1, VECTOR_2, VECTOR_3, VECTOR_1]
def UpperCamelCase_ ( __a , __a ) -> List[Any]:
a__ : Union[str, Any] = initial_vectors
for _ in range(SCREAMING_SNAKE_CASE__ ):
a__ : Optional[int] = iteration_step(SCREAMING_SNAKE_CASE__ )
return vectors
def UpperCamelCase_ ( __a ) -> List[str]:
a__ : List[str] = []
for i, start_vector in enumerate(vectors[:-1] ):
a__ : List[str] = vectors[i + 1]
new_vectors.append(SCREAMING_SNAKE_CASE__ )
a__ : Optional[Any] = end_vector - start_vector
new_vectors.append(start_vector + difference_vector / 3 )
new_vectors.append(
start_vector + difference_vector / 3 + rotate(difference_vector / 3 , 60 ) )
new_vectors.append(start_vector + difference_vector * 2 / 3 )
new_vectors.append(vectors[-1] )
return new_vectors
def UpperCamelCase_ ( __a , __a ) -> Union[str, Any]:
a__ : List[Any] = numpy.radians(SCREAMING_SNAKE_CASE__ )
a__ : Tuple = numpy.cos(SCREAMING_SNAKE_CASE__ ), numpy.sin(SCREAMING_SNAKE_CASE__ )
a__ : Optional[Any] = numpy.array(((c, -s), (s, c)) )
return numpy.dot(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
def UpperCamelCase_ ( __a ) -> Any:
a__ : str = plt.gca()
axes.set_aspect("equal" )
# matplotlib.pyplot.plot takes a list of all x-coordinates and a list of all
# y-coordinates as inputs, which are constructed from the vector-list using
# zip()
a__ : Tuple = zip(*SCREAMING_SNAKE_CASE__ )
plt.plot(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
plt.show()
if __name__ == "__main__":
import doctest
doctest.testmod()
UpperCamelCase : Optional[int] = iterate(INITIAL_VECTORS, 5)
plot(processed_vectors)
| 37 |
# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer
from .base import PipelineTool
__snake_case = {
"""Acehnese Arabic""": """ace_Arab""",
"""Acehnese Latin""": """ace_Latn""",
"""Mesopotamian Arabic""": """acm_Arab""",
"""Ta'izzi-Adeni Arabic""": """acq_Arab""",
"""Tunisian Arabic""": """aeb_Arab""",
"""Afrikaans""": """afr_Latn""",
"""South Levantine Arabic""": """ajp_Arab""",
"""Akan""": """aka_Latn""",
"""Amharic""": """amh_Ethi""",
"""North Levantine Arabic""": """apc_Arab""",
"""Modern Standard Arabic""": """arb_Arab""",
"""Modern Standard Arabic Romanized""": """arb_Latn""",
"""Najdi Arabic""": """ars_Arab""",
"""Moroccan Arabic""": """ary_Arab""",
"""Egyptian Arabic""": """arz_Arab""",
"""Assamese""": """asm_Beng""",
"""Asturian""": """ast_Latn""",
"""Awadhi""": """awa_Deva""",
"""Central Aymara""": """ayr_Latn""",
"""South Azerbaijani""": """azb_Arab""",
"""North Azerbaijani""": """azj_Latn""",
"""Bashkir""": """bak_Cyrl""",
"""Bambara""": """bam_Latn""",
"""Balinese""": """ban_Latn""",
"""Belarusian""": """bel_Cyrl""",
"""Bemba""": """bem_Latn""",
"""Bengali""": """ben_Beng""",
"""Bhojpuri""": """bho_Deva""",
"""Banjar Arabic""": """bjn_Arab""",
"""Banjar Latin""": """bjn_Latn""",
"""Standard Tibetan""": """bod_Tibt""",
"""Bosnian""": """bos_Latn""",
"""Buginese""": """bug_Latn""",
"""Bulgarian""": """bul_Cyrl""",
"""Catalan""": """cat_Latn""",
"""Cebuano""": """ceb_Latn""",
"""Czech""": """ces_Latn""",
"""Chokwe""": """cjk_Latn""",
"""Central Kurdish""": """ckb_Arab""",
"""Crimean Tatar""": """crh_Latn""",
"""Welsh""": """cym_Latn""",
"""Danish""": """dan_Latn""",
"""German""": """deu_Latn""",
"""Southwestern Dinka""": """dik_Latn""",
"""Dyula""": """dyu_Latn""",
"""Dzongkha""": """dzo_Tibt""",
"""Greek""": """ell_Grek""",
"""English""": """eng_Latn""",
"""Esperanto""": """epo_Latn""",
"""Estonian""": """est_Latn""",
"""Basque""": """eus_Latn""",
"""Ewe""": """ewe_Latn""",
"""Faroese""": """fao_Latn""",
"""Fijian""": """fij_Latn""",
"""Finnish""": """fin_Latn""",
"""Fon""": """fon_Latn""",
"""French""": """fra_Latn""",
"""Friulian""": """fur_Latn""",
"""Nigerian Fulfulde""": """fuv_Latn""",
"""Scottish Gaelic""": """gla_Latn""",
"""Irish""": """gle_Latn""",
"""Galician""": """glg_Latn""",
"""Guarani""": """grn_Latn""",
"""Gujarati""": """guj_Gujr""",
"""Haitian Creole""": """hat_Latn""",
"""Hausa""": """hau_Latn""",
"""Hebrew""": """heb_Hebr""",
"""Hindi""": """hin_Deva""",
"""Chhattisgarhi""": """hne_Deva""",
"""Croatian""": """hrv_Latn""",
"""Hungarian""": """hun_Latn""",
"""Armenian""": """hye_Armn""",
"""Igbo""": """ibo_Latn""",
"""Ilocano""": """ilo_Latn""",
"""Indonesian""": """ind_Latn""",
"""Icelandic""": """isl_Latn""",
"""Italian""": """ita_Latn""",
"""Javanese""": """jav_Latn""",
"""Japanese""": """jpn_Jpan""",
"""Kabyle""": """kab_Latn""",
"""Jingpho""": """kac_Latn""",
"""Kamba""": """kam_Latn""",
"""Kannada""": """kan_Knda""",
"""Kashmiri Arabic""": """kas_Arab""",
"""Kashmiri Devanagari""": """kas_Deva""",
"""Georgian""": """kat_Geor""",
"""Central Kanuri Arabic""": """knc_Arab""",
"""Central Kanuri Latin""": """knc_Latn""",
"""Kazakh""": """kaz_Cyrl""",
"""Kabiyè""": """kbp_Latn""",
"""Kabuverdianu""": """kea_Latn""",
"""Khmer""": """khm_Khmr""",
"""Kikuyu""": """kik_Latn""",
"""Kinyarwanda""": """kin_Latn""",
"""Kyrgyz""": """kir_Cyrl""",
"""Kimbundu""": """kmb_Latn""",
"""Northern Kurdish""": """kmr_Latn""",
"""Kikongo""": """kon_Latn""",
"""Korean""": """kor_Hang""",
"""Lao""": """lao_Laoo""",
"""Ligurian""": """lij_Latn""",
"""Limburgish""": """lim_Latn""",
"""Lingala""": """lin_Latn""",
"""Lithuanian""": """lit_Latn""",
"""Lombard""": """lmo_Latn""",
"""Latgalian""": """ltg_Latn""",
"""Luxembourgish""": """ltz_Latn""",
"""Luba-Kasai""": """lua_Latn""",
"""Ganda""": """lug_Latn""",
"""Luo""": """luo_Latn""",
"""Mizo""": """lus_Latn""",
"""Standard Latvian""": """lvs_Latn""",
"""Magahi""": """mag_Deva""",
"""Maithili""": """mai_Deva""",
"""Malayalam""": """mal_Mlym""",
"""Marathi""": """mar_Deva""",
"""Minangkabau Arabic """: """min_Arab""",
"""Minangkabau Latin""": """min_Latn""",
"""Macedonian""": """mkd_Cyrl""",
"""Plateau Malagasy""": """plt_Latn""",
"""Maltese""": """mlt_Latn""",
"""Meitei Bengali""": """mni_Beng""",
"""Halh Mongolian""": """khk_Cyrl""",
"""Mossi""": """mos_Latn""",
"""Maori""": """mri_Latn""",
"""Burmese""": """mya_Mymr""",
"""Dutch""": """nld_Latn""",
"""Norwegian Nynorsk""": """nno_Latn""",
"""Norwegian Bokmål""": """nob_Latn""",
"""Nepali""": """npi_Deva""",
"""Northern Sotho""": """nso_Latn""",
"""Nuer""": """nus_Latn""",
"""Nyanja""": """nya_Latn""",
"""Occitan""": """oci_Latn""",
"""West Central Oromo""": """gaz_Latn""",
"""Odia""": """ory_Orya""",
"""Pangasinan""": """pag_Latn""",
"""Eastern Panjabi""": """pan_Guru""",
"""Papiamento""": """pap_Latn""",
"""Western Persian""": """pes_Arab""",
"""Polish""": """pol_Latn""",
"""Portuguese""": """por_Latn""",
"""Dari""": """prs_Arab""",
"""Southern Pashto""": """pbt_Arab""",
"""Ayacucho Quechua""": """quy_Latn""",
"""Romanian""": """ron_Latn""",
"""Rundi""": """run_Latn""",
"""Russian""": """rus_Cyrl""",
"""Sango""": """sag_Latn""",
"""Sanskrit""": """san_Deva""",
"""Santali""": """sat_Olck""",
"""Sicilian""": """scn_Latn""",
"""Shan""": """shn_Mymr""",
"""Sinhala""": """sin_Sinh""",
"""Slovak""": """slk_Latn""",
"""Slovenian""": """slv_Latn""",
"""Samoan""": """smo_Latn""",
"""Shona""": """sna_Latn""",
"""Sindhi""": """snd_Arab""",
"""Somali""": """som_Latn""",
"""Southern Sotho""": """sot_Latn""",
"""Spanish""": """spa_Latn""",
"""Tosk Albanian""": """als_Latn""",
"""Sardinian""": """srd_Latn""",
"""Serbian""": """srp_Cyrl""",
"""Swati""": """ssw_Latn""",
"""Sundanese""": """sun_Latn""",
"""Swedish""": """swe_Latn""",
"""Swahili""": """swh_Latn""",
"""Silesian""": """szl_Latn""",
"""Tamil""": """tam_Taml""",
"""Tatar""": """tat_Cyrl""",
"""Telugu""": """tel_Telu""",
"""Tajik""": """tgk_Cyrl""",
"""Tagalog""": """tgl_Latn""",
"""Thai""": """tha_Thai""",
"""Tigrinya""": """tir_Ethi""",
"""Tamasheq Latin""": """taq_Latn""",
"""Tamasheq Tifinagh""": """taq_Tfng""",
"""Tok Pisin""": """tpi_Latn""",
"""Tswana""": """tsn_Latn""",
"""Tsonga""": """tso_Latn""",
"""Turkmen""": """tuk_Latn""",
"""Tumbuka""": """tum_Latn""",
"""Turkish""": """tur_Latn""",
"""Twi""": """twi_Latn""",
"""Central Atlas Tamazight""": """tzm_Tfng""",
"""Uyghur""": """uig_Arab""",
"""Ukrainian""": """ukr_Cyrl""",
"""Umbundu""": """umb_Latn""",
"""Urdu""": """urd_Arab""",
"""Northern Uzbek""": """uzn_Latn""",
"""Venetian""": """vec_Latn""",
"""Vietnamese""": """vie_Latn""",
"""Waray""": """war_Latn""",
"""Wolof""": """wol_Latn""",
"""Xhosa""": """xho_Latn""",
"""Eastern Yiddish""": """ydd_Hebr""",
"""Yoruba""": """yor_Latn""",
"""Yue Chinese""": """yue_Hant""",
"""Chinese Simplified""": """zho_Hans""",
"""Chinese Traditional""": """zho_Hant""",
"""Standard Malay""": """zsm_Latn""",
"""Zulu""": """zul_Latn""",
}
class UpperCAmelCase_ ( lowercase ):
"""simple docstring"""
UpperCamelCase_ : Optional[Any] ='facebook/nllb-200-distilled-600M'
UpperCamelCase_ : Optional[Any] =(
'This is a tool that translates text from a language to another. It takes three inputs: `text`, which should '
'be the text to translate, `src_lang`, which should be the language of the text to translate and `tgt_lang`, '
'which should be the language for the desired ouput language. Both `src_lang` and `tgt_lang` are written in '
'plain English, such as \'Romanian\', or \'Albanian\'. It returns the text translated in `tgt_lang`.'
)
UpperCamelCase_ : Dict ='translator'
UpperCamelCase_ : Any =AutoTokenizer
UpperCamelCase_ : Optional[Any] =AutoModelForSeqaSeqLM
UpperCamelCase_ : List[Any] =LANGUAGE_CODES
UpperCamelCase_ : int =['text', 'text', 'text']
UpperCamelCase_ : Union[str, Any] =['text']
def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> str:
if src_lang not in self.lang_to_code:
raise ValueError(F'''{src_lang} is not a supported language.''' )
if tgt_lang not in self.lang_to_code:
raise ValueError(F'''{tgt_lang} is not a supported language.''' )
UpperCamelCase :Optional[int] = self.lang_to_code[src_lang]
UpperCamelCase :Union[str, Any] = self.lang_to_code[tgt_lang]
return self.pre_processor._build_translation_inputs(
SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' , src_lang=SCREAMING_SNAKE_CASE_ , tgt_lang=SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ ) -> Optional[Any]:
return self.model.generate(**SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ ) -> int:
return self.post_processor.decode(outputs[0].tolist() , skip_special_tokens=SCREAMING_SNAKE_CASE_ )
| 658 | 0 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
a__ = logging.get_logger(__name__)
a__ = {
'''google/switch-base-8''': '''https://huggingface.co/google/switch-base-8/blob/main/config.json''',
}
class SCREAMING_SNAKE_CASE_ ( _UpperCamelCase ):
"""simple docstring"""
__magic_name__ : Optional[int] = 'switch_transformers'
__magic_name__ : Any = ['past_key_values']
__magic_name__ : Union[str, Any] = {'hidden_size': 'd_model', 'num_attention_heads': 'num_heads', 'num_hidden_layers': 'num_layers'}
def __init__( self : Optional[Any] , lowerCAmelCase : int=32128 , lowerCAmelCase : Optional[int]=768 , lowerCAmelCase : Optional[int]=64 , lowerCAmelCase : List[str]=2048 , lowerCAmelCase : int=64 , lowerCAmelCase : List[str]=12 , lowerCAmelCase : str=3 , lowerCAmelCase : Dict=12 , lowerCAmelCase : str=3 , lowerCAmelCase : List[Any]=12 , lowerCAmelCase : List[Any]=8 , lowerCAmelCase : Dict=False , lowerCAmelCase : List[Any]=0.01 , lowerCAmelCase : Union[str, Any]="float32" , lowerCAmelCase : Union[str, Any]=False , lowerCAmelCase : Optional[Any]=32 , lowerCAmelCase : Dict=128 , lowerCAmelCase : Tuple=0.1 , lowerCAmelCase : Dict=1E-6 , lowerCAmelCase : Dict=0.0_01 , lowerCAmelCase : List[str]=0.0_01 , lowerCAmelCase : int=1.0 , lowerCAmelCase : List[str]="relu" , lowerCAmelCase : Dict=True , lowerCAmelCase : int=False , lowerCAmelCase : Tuple=True , lowerCAmelCase : str=0 , lowerCAmelCase : Any=1 , **lowerCAmelCase : Tuple , ) -> int:
"""simple docstring"""
__UpperCamelCase : Optional[Any] = vocab_size
__UpperCamelCase : Union[str, Any] = d_model
__UpperCamelCase : List[str] = d_kv
__UpperCamelCase : Any = d_ff
__UpperCamelCase : Optional[int] = num_sparse_encoder_layers
__UpperCamelCase : List[str] = num_layers
__UpperCamelCase : int = (
num_decoder_layers if num_decoder_layers is not None else self.num_layers
) # default = symmetry
__UpperCamelCase : List[Any] = num_sparse_decoder_layers
# This tells us, each how many encoder layer we'll have to set a sparse layer.
if self.num_sparse_encoder_layers > 0:
__UpperCamelCase : Union[str, Any] = self.num_layers // self.num_sparse_encoder_layers
else:
__UpperCamelCase : Any = self.num_layers # HACK: this will create 0 sparse layers
# This tells us, each how many encoder layer we'll have to set a sparse layer.
if self.num_sparse_decoder_layers > 0:
__UpperCamelCase : List[str] = self.num_decoder_layers // self.num_sparse_decoder_layers
else:
__UpperCamelCase : Optional[int] = self.num_decoder_layers # HACK: this will create 0 sparse layers
__UpperCamelCase : str = num_heads
__UpperCamelCase : Optional[Any] = num_experts
__UpperCamelCase : Dict = expert_capacity
__UpperCamelCase : str = router_bias
__UpperCamelCase : Union[str, Any] = router_jitter_noise
if router_dtype not in ["float32", "float16", "bfloat16"]:
raise ValueError(F'''`router_dtype` must be one of \'float32\', \'float16\' or \'bfloat16\', got {router_dtype}''' )
__UpperCamelCase : str = router_dtype
__UpperCamelCase : Tuple = router_ignore_padding_tokens
__UpperCamelCase : Any = relative_attention_num_buckets
__UpperCamelCase : Any = relative_attention_max_distance
__UpperCamelCase : Union[str, Any] = dropout_rate
__UpperCamelCase : List[str] = layer_norm_epsilon
__UpperCamelCase : str = initializer_factor
__UpperCamelCase : List[str] = feed_forward_proj
__UpperCamelCase : List[Any] = use_cache
__UpperCamelCase : Optional[Any] = add_router_probs
__UpperCamelCase : Tuple = router_z_loss_coef
__UpperCamelCase : str = router_aux_loss_coef
__UpperCamelCase : int = self.feed_forward_proj.split("""-""" )
__UpperCamelCase : List[str] = act_info[-1]
__UpperCamelCase : str = act_info[0] == '''gated'''
if len(SCREAMING_SNAKE_CASE_ ) > 1 and act_info[0] != "gated" or len(SCREAMING_SNAKE_CASE_ ) > 2:
raise ValueError(
F'''`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.'''
"""Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. """
"""\'gated-gelu\' or \'relu\'""" )
# for backwards compatibility
if feed_forward_proj == "gated-gelu":
__UpperCamelCase : List[str] = '''gelu_new'''
super().__init__(
pad_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , is_encoder_decoder=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , )
| 279 |
from __future__ import annotations
# This is the precision for this function which can be altered.
# It is recommended for users to keep this number greater than or equal to 10.
__snake_case = 10
def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : int ):
for i in range(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
if array[i] == target:
return i
return -1
def _A ( SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : int ):
UpperCamelCase :Tuple = 0
UpperCamelCase :Dict = len(SCREAMING_SNAKE_CASE__ )
while left <= right:
if right - left < precision:
return lin_search(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
UpperCamelCase :Union[str, Any] = (left + right) // 3 + 1
UpperCamelCase :str = 2 * (left + right) // 3 + 1
if array[one_third] == target:
return one_third
elif array[two_third] == target:
return two_third
elif target < array[one_third]:
UpperCamelCase :int = one_third - 1
elif array[two_third] < target:
UpperCamelCase :Any = two_third + 1
else:
UpperCamelCase :Any = one_third + 1
UpperCamelCase :int = two_third - 1
else:
return -1
def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : int ):
if left < right:
if right - left < precision:
return lin_search(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
UpperCamelCase :Optional[Any] = (left + right) // 3 + 1
UpperCamelCase :Tuple = 2 * (left + right) // 3 + 1
if array[one_third] == target:
return one_third
elif array[two_third] == target:
return two_third
elif target < array[one_third]:
return rec_ternary_search(SCREAMING_SNAKE_CASE__ , one_third - 1 , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
elif array[two_third] < target:
return rec_ternary_search(two_third + 1 , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
else:
return rec_ternary_search(one_third + 1 , two_third - 1 , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
else:
return -1
if __name__ == "__main__":
import doctest
doctest.testmod()
__snake_case = input("""Enter numbers separated by comma:\n""").strip()
__snake_case = [int(item.strip()) for item in user_input.split(""",""")]
assert collection == sorted(collection), f"List must be ordered.\n{collection}."
__snake_case = int(input("""Enter the number to be found in the list:\n""").strip())
__snake_case = ite_ternary_search(collection, target)
__snake_case = rec_ternary_search(0, len(collection) - 1, collection, target)
if resulta != -1:
print(f'''Iterative search: {target} found at positions: {resulta}''')
print(f'''Recursive search: {target} found at positions: {resulta}''')
else:
print("""Not found""")
| 658 | 0 |
import string
def __lowercase( UpperCAmelCase__ ):
"""simple docstring"""
for key in range(len(string.ascii_uppercase ) ):
lowerCamelCase = ''''''
for symbol in message:
if symbol in string.ascii_uppercase:
lowerCamelCase = string.ascii_uppercase.find(SCREAMING_SNAKE_CASE__ )
lowerCamelCase = num - key
if num < 0:
lowerCamelCase = num + len(string.ascii_uppercase )
lowerCamelCase = translated + string.ascii_uppercase[num]
else:
lowerCamelCase = translated + symbol
print(F"""Decryption using Key #{key}: {translated}""" )
def __lowercase( ):
"""simple docstring"""
lowerCamelCase = input("Encrypted message: " )
lowerCamelCase = message.upper()
decrypt(SCREAMING_SNAKE_CASE__ )
if __name__ == "__main__":
import doctest
doctest.testmod()
main() | 623 |
def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list ):
_enforce_args(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
if n == 0:
return 0
UpperCamelCase :Union[str, Any] = float('''-inf''' )
for i in range(1 , n + 1 ):
UpperCamelCase :str = max(
SCREAMING_SNAKE_CASE__ , prices[i - 1] + naive_cut_rod_recursive(n - i , SCREAMING_SNAKE_CASE__ ) )
return max_revue
def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list ):
_enforce_args(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
UpperCamelCase :Dict = [float('''-inf''' ) for _ in range(n + 1 )]
return _top_down_cut_rod_recursive(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list , SCREAMING_SNAKE_CASE__ : list ):
if max_rev[n] >= 0:
return max_rev[n]
elif n == 0:
return 0
else:
UpperCamelCase :Dict = float('''-inf''' )
for i in range(1 , n + 1 ):
UpperCamelCase :Union[str, Any] = max(
SCREAMING_SNAKE_CASE__ , prices[i - 1] + _top_down_cut_rod_recursive(n - i , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , )
UpperCamelCase :str = max_revenue
return max_rev[n]
def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list ):
_enforce_args(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
# length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of
# length 0.
UpperCamelCase :List[str] = [float('''-inf''' ) for _ in range(n + 1 )]
UpperCamelCase :Dict = 0
for i in range(1 , n + 1 ):
UpperCamelCase :Optional[Any] = max_rev[i]
for j in range(1 , i + 1 ):
UpperCamelCase :Optional[Any] = max(SCREAMING_SNAKE_CASE__ , prices[j - 1] + max_rev[i - j] )
UpperCamelCase :Tuple = max_revenue_i
return max_rev[n]
def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list ):
if n < 0:
UpperCamelCase :Any = F'''n must be greater than or equal to 0. Got n = {n}'''
raise ValueError(SCREAMING_SNAKE_CASE__ )
if n > len(SCREAMING_SNAKE_CASE__ ):
UpperCamelCase :Union[str, Any] = (
'''Each integral piece of rod must have a corresponding price. '''
F'''Got n = {n} but length of prices = {len(SCREAMING_SNAKE_CASE__ )}'''
)
raise ValueError(SCREAMING_SNAKE_CASE__ )
def _A ( ):
UpperCamelCase :Dict = [6, 10, 12, 15, 20, 23]
UpperCamelCase :List[str] = len(SCREAMING_SNAKE_CASE__ )
# the best revenue comes from cutting the rod into 6 pieces, each
# of length 1 resulting in a revenue of 6 * 6 = 36.
UpperCamelCase :str = 36
UpperCamelCase :int = top_down_cut_rod(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
UpperCamelCase :Union[str, Any] = bottom_up_cut_rod(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
UpperCamelCase :str = naive_cut_rod_recursive(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
assert expected_max_revenue == max_rev_top_down
assert max_rev_top_down == max_rev_bottom_up
assert max_rev_bottom_up == max_rev_naive
if __name__ == "__main__":
main()
| 658 | 0 |
'''simple docstring'''
def __UpperCAmelCase ( SCREAMING_SNAKE_CASE__: Dict, SCREAMING_SNAKE_CASE__: Optional[Any] ) -> List[Any]:
"""simple docstring"""
__a = [0 for i in range(r + 1 )]
# nc0 = 1
__a = 1
for i in range(1, n + 1 ):
# to compute current row from previous row.
__a = min(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ )
while j > 0:
c[j] += c[j - 1]
j -= 1
return c[r]
print(binomial_coefficient(n=10, r=5)) | 448 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices
__snake_case = logging.get_logger(__name__)
__snake_case = {
"""microsoft/focalnet-tiny""": """https://huggingface.co/microsoft/focalnet-tiny/resolve/main/config.json""",
}
class UpperCAmelCase_ ( lowercase, lowercase ):
"""simple docstring"""
UpperCamelCase_ : int ='focalnet'
def __init__( self , SCREAMING_SNAKE_CASE_=224 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=96 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=[192, 384, 768, 768] , SCREAMING_SNAKE_CASE_=[2, 2, 6, 2] , SCREAMING_SNAKE_CASE_=[2, 2, 2, 2] , SCREAMING_SNAKE_CASE_=[3, 3, 3, 3] , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=4.0 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=1e-4 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=1e-5 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ , ) -> Dict:
super().__init__(**SCREAMING_SNAKE_CASE_ )
UpperCamelCase :List[Any] = image_size
UpperCamelCase :Dict = patch_size
UpperCamelCase :Tuple = num_channels
UpperCamelCase :int = embed_dim
UpperCamelCase :Optional[Any] = use_conv_embed
UpperCamelCase :str = hidden_sizes
UpperCamelCase :str = depths
UpperCamelCase :Optional[int] = focal_levels
UpperCamelCase :Tuple = focal_windows
UpperCamelCase :Optional[int] = hidden_act
UpperCamelCase :Optional[int] = mlp_ratio
UpperCamelCase :Optional[Any] = hidden_dropout_prob
UpperCamelCase :int = drop_path_rate
UpperCamelCase :Dict = use_layerscale
UpperCamelCase :List[str] = layerscale_value
UpperCamelCase :Tuple = use_post_layernorm
UpperCamelCase :int = use_post_layernorm_in_modulation
UpperCamelCase :str = normalize_modulator
UpperCamelCase :Any = initializer_range
UpperCamelCase :Optional[Any] = layer_norm_eps
UpperCamelCase :Dict = encoder_stride
UpperCamelCase :int = ['''stem'''] + [F'''stage{idx}''' for idx in range(1 , len(self.depths ) + 1 )]
UpperCamelCase , UpperCamelCase :int = get_aligned_output_features_output_indices(
out_features=SCREAMING_SNAKE_CASE_ , out_indices=SCREAMING_SNAKE_CASE_ , stage_names=self.stage_names )
| 658 | 0 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
UpperCamelCase = logging.get_logger(__name__)
UpperCamelCase = {
'uclanlp/visualbert-vqa': 'https://huggingface.co/uclanlp/visualbert-vqa/resolve/main/config.json',
'uclanlp/visualbert-vqa-pre': 'https://huggingface.co/uclanlp/visualbert-vqa-pre/resolve/main/config.json',
'uclanlp/visualbert-vqa-coco-pre': (
'https://huggingface.co/uclanlp/visualbert-vqa-coco-pre/resolve/main/config.json'
),
'uclanlp/visualbert-vcr': 'https://huggingface.co/uclanlp/visualbert-vcr/resolve/main/config.json',
'uclanlp/visualbert-vcr-pre': 'https://huggingface.co/uclanlp/visualbert-vcr-pre/resolve/main/config.json',
'uclanlp/visualbert-vcr-coco-pre': (
'https://huggingface.co/uclanlp/visualbert-vcr-coco-pre/resolve/main/config.json'
),
'uclanlp/visualbert-nlvr2': 'https://huggingface.co/uclanlp/visualbert-nlvr2/resolve/main/config.json',
'uclanlp/visualbert-nlvr2-pre': 'https://huggingface.co/uclanlp/visualbert-nlvr2-pre/resolve/main/config.json',
'uclanlp/visualbert-nlvr2-coco-pre': (
'https://huggingface.co/uclanlp/visualbert-nlvr2-coco-pre/resolve/main/config.json'
)
# See all VisualBERT models at https://huggingface.co/models?filter=visual_bert
}
class _A ( UpperCAmelCase_ ):
lowercase_ : Any = 'visual_bert'
def __init__( self : int , lowerCamelCase__ : Any=3_05_22 , lowerCamelCase__ : Union[str, Any]=7_68 , lowerCamelCase__ : List[str]=5_12 , lowerCamelCase__ : Optional[Any]=12 , lowerCamelCase__ : Any=12 , lowerCamelCase__ : List[Any]=30_72 , lowerCamelCase__ : Union[str, Any]="gelu" , lowerCamelCase__ : List[str]=0.1 , lowerCamelCase__ : Dict=0.1 , lowerCamelCase__ : List[Any]=5_12 , lowerCamelCase__ : Union[str, Any]=2 , lowerCamelCase__ : Dict=0.02 , lowerCamelCase__ : Union[str, Any]=1e-12 , lowerCamelCase__ : Dict=False , lowerCamelCase__ : int=True , lowerCamelCase__ : Dict=1 , lowerCamelCase__ : Tuple=0 , lowerCamelCase__ : int=2 , **lowerCamelCase__ : List[Any] , ):
"""simple docstring"""
super().__init__(pad_token_id=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
__UpperCamelCase : Optional[int] = vocab_size
__UpperCamelCase : Tuple = max_position_embeddings
__UpperCamelCase : Optional[Any] = hidden_size
__UpperCamelCase : Any = visual_embedding_dim
__UpperCamelCase : Tuple = num_hidden_layers
__UpperCamelCase : Optional[int] = num_attention_heads
__UpperCamelCase : Optional[Any] = intermediate_size
__UpperCamelCase : Union[str, Any] = hidden_act
__UpperCamelCase : List[Any] = hidden_dropout_prob
__UpperCamelCase : List[Any] = attention_probs_dropout_prob
__UpperCamelCase : List[str] = initializer_range
__UpperCamelCase : Optional[Any] = type_vocab_size
__UpperCamelCase : Optional[Any] = layer_norm_eps
__UpperCamelCase : Tuple = bypass_transformer
__UpperCamelCase : Dict = special_visual_initialize
| 269 |
import inspect
import unittest
from transformers import DPTConfig
from transformers.file_utils import is_torch_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from torch import nn
from transformers import MODEL_MAPPING, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel
from transformers.models.dpt.modeling_dpt import DPT_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
from PIL import Image
from transformers import DPTImageProcessor
class UpperCAmelCase_ :
"""simple docstring"""
def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=[0, 1, 2, 3] , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=37 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=[1, 384, 24, 24] , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=None , ) -> int:
UpperCamelCase :Union[str, Any] = parent
UpperCamelCase :Tuple = batch_size
UpperCamelCase :Optional[Any] = image_size
UpperCamelCase :Any = patch_size
UpperCamelCase :List[str] = num_channels
UpperCamelCase :int = is_training
UpperCamelCase :str = use_labels
UpperCamelCase :Optional[Any] = hidden_size
UpperCamelCase :int = num_hidden_layers
UpperCamelCase :List[Any] = backbone_out_indices
UpperCamelCase :str = num_attention_heads
UpperCamelCase :Tuple = intermediate_size
UpperCamelCase :Optional[int] = hidden_act
UpperCamelCase :List[Any] = hidden_dropout_prob
UpperCamelCase :List[str] = attention_probs_dropout_prob
UpperCamelCase :Union[str, Any] = initializer_range
UpperCamelCase :List[Any] = num_labels
UpperCamelCase :int = backbone_featmap_shape
UpperCamelCase :Any = scope
UpperCamelCase :int = is_hybrid
# sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token)
UpperCamelCase :Dict = (image_size // patch_size) ** 2
UpperCamelCase :List[str] = num_patches + 1
def UpperCAmelCase ( self ) -> Union[str, Any]:
UpperCamelCase :List[str] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
UpperCamelCase :Tuple = None
if self.use_labels:
UpperCamelCase :Union[str, Any] = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels )
UpperCamelCase :Optional[int] = self.get_config()
return config, pixel_values, labels
def UpperCAmelCase ( self ) -> Dict:
UpperCamelCase :Any = {
'''global_padding''': '''same''',
'''layer_type''': '''bottleneck''',
'''depths''': [3, 4, 9],
'''out_features''': ['''stage1''', '''stage2''', '''stage3'''],
'''embedding_dynamic_padding''': True,
'''hidden_sizes''': [96, 192, 384, 768],
'''num_groups''': 2,
}
return DPTConfig(
image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , backbone_out_indices=self.backbone_out_indices , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=SCREAMING_SNAKE_CASE_ , initializer_range=self.initializer_range , is_hybrid=self.is_hybrid , backbone_config=SCREAMING_SNAKE_CASE_ , backbone_featmap_shape=self.backbone_featmap_shape , )
def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Tuple:
UpperCamelCase :List[str] = DPTModel(config=SCREAMING_SNAKE_CASE_ )
model.to(SCREAMING_SNAKE_CASE_ )
model.eval()
UpperCamelCase :Dict = model(SCREAMING_SNAKE_CASE_ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> str:
UpperCamelCase :Optional[Any] = self.num_labels
UpperCamelCase :Optional[int] = DPTForDepthEstimation(SCREAMING_SNAKE_CASE_ )
model.to(SCREAMING_SNAKE_CASE_ )
model.eval()
UpperCamelCase :Dict = model(SCREAMING_SNAKE_CASE_ )
self.parent.assertEqual(result.predicted_depth.shape , (self.batch_size, self.image_size, self.image_size) )
def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Dict:
UpperCamelCase :Optional[int] = self.num_labels
UpperCamelCase :int = DPTForSemanticSegmentation(SCREAMING_SNAKE_CASE_ )
model.to(SCREAMING_SNAKE_CASE_ )
model.eval()
UpperCamelCase :Dict = model(SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ )
self.parent.assertEqual(
result.logits.shape , (self.batch_size, self.num_labels, self.image_size, self.image_size) )
def UpperCAmelCase ( self ) -> Dict:
UpperCamelCase :Dict = self.prepare_config_and_inputs()
UpperCamelCase , UpperCamelCase , UpperCamelCase :List[Any] = config_and_inputs
UpperCamelCase :List[Any] = {'''pixel_values''': pixel_values}
return config, inputs_dict
@require_torch
class UpperCAmelCase_ ( lowercase, lowercase, unittest.TestCase ):
"""simple docstring"""
UpperCamelCase_ : Tuple =(DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else ()
UpperCamelCase_ : Tuple =(
{
'depth-estimation': DPTForDepthEstimation,
'feature-extraction': DPTModel,
'image-segmentation': DPTForSemanticSegmentation,
}
if is_torch_available()
else {}
)
UpperCamelCase_ : Tuple =False
UpperCamelCase_ : List[Any] =False
UpperCamelCase_ : Tuple =False
def UpperCAmelCase ( self ) -> Dict:
UpperCamelCase :Union[str, Any] = DPTModelTester(self )
UpperCamelCase :List[Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , has_text_modality=SCREAMING_SNAKE_CASE_ , hidden_size=37 )
def UpperCAmelCase ( self ) -> Tuple:
self.config_tester.run_common_tests()
@unittest.skip(reason='''DPT does not use inputs_embeds''' )
def UpperCAmelCase ( self ) -> int:
pass
def UpperCAmelCase ( self ) -> List[Any]:
UpperCamelCase , UpperCamelCase :Tuple = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
UpperCamelCase :int = model_class(SCREAMING_SNAKE_CASE_ )
self.assertIsInstance(model.get_input_embeddings() , (nn.Module) )
UpperCamelCase :int = model.get_output_embeddings()
self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE_ , nn.Linear ) )
def UpperCAmelCase ( self ) -> Optional[int]:
UpperCamelCase , UpperCamelCase :Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
UpperCamelCase :List[Any] = model_class(SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Optional[int] = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
UpperCamelCase :Optional[int] = [*signature.parameters.keys()]
UpperCamelCase :Tuple = ['''pixel_values''']
self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self ) -> Optional[int]:
UpperCamelCase :Any = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self ) -> Optional[int]:
UpperCamelCase :Union[str, Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_depth_estimation(*SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self ) -> Any:
UpperCamelCase :Union[str, Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_semantic_segmentation(*SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self ) -> List[str]:
for model_class in self.all_model_classes:
if model_class.__name__ == "DPTForDepthEstimation":
continue
UpperCamelCase , UpperCamelCase :Tuple = self.model_tester.prepare_config_and_inputs_for_common()
UpperCamelCase :Any = True
if model_class in get_values(SCREAMING_SNAKE_CASE_ ):
continue
UpperCamelCase :Dict = model_class(SCREAMING_SNAKE_CASE_ )
model.to(SCREAMING_SNAKE_CASE_ )
model.train()
UpperCamelCase :str = self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , return_labels=SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Optional[Any] = model(**SCREAMING_SNAKE_CASE_ ).loss
loss.backward()
def UpperCAmelCase ( self ) -> Tuple:
for model_class in self.all_model_classes:
if model_class.__name__ == "DPTForDepthEstimation":
continue
UpperCamelCase , UpperCamelCase :Any = self.model_tester.prepare_config_and_inputs_for_common()
UpperCamelCase :Optional[Any] = False
UpperCamelCase :List[Any] = True
if model_class in get_values(SCREAMING_SNAKE_CASE_ ) or not model_class.supports_gradient_checkpointing:
continue
UpperCamelCase :Optional[Any] = model_class(SCREAMING_SNAKE_CASE_ )
model.to(SCREAMING_SNAKE_CASE_ )
model.gradient_checkpointing_enable()
model.train()
UpperCamelCase :Union[str, Any] = self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , return_labels=SCREAMING_SNAKE_CASE_ )
UpperCamelCase :List[str] = model(**SCREAMING_SNAKE_CASE_ ).loss
loss.backward()
def UpperCAmelCase ( self ) -> List[str]:
UpperCamelCase , UpperCamelCase :Dict = self.model_tester.prepare_config_and_inputs_for_common()
UpperCamelCase :Optional[int] = _config_zero_init(SCREAMING_SNAKE_CASE_ )
for model_class in self.all_model_classes:
UpperCamelCase :Union[str, Any] = model_class(config=SCREAMING_SNAKE_CASE_ )
# Skip the check for the backbone
UpperCamelCase :Optional[int] = []
for name, module in model.named_modules():
if module.__class__.__name__ == "DPTViTHybridEmbeddings":
UpperCamelCase :Union[str, Any] = [F'''{name}.{key}''' for key in module.state_dict().keys()]
break
for name, param in model.named_parameters():
if param.requires_grad:
if name in backbone_params:
continue
self.assertIn(
((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=F'''Parameter {name} of model {model_class} seems not properly initialized''' , )
@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' )
def UpperCAmelCase ( self ) -> Any:
pass
@slow
def UpperCAmelCase ( self ) -> Optional[Any]:
for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]:
UpperCamelCase :Any = DPTModel.from_pretrained(SCREAMING_SNAKE_CASE_ )
self.assertIsNotNone(SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self ) -> Optional[int]:
# We do this test only for DPTForDepthEstimation since it is the only model that uses readout_type
UpperCamelCase , UpperCamelCase :Tuple = self.model_tester.prepare_config_and_inputs_for_common()
UpperCamelCase :Union[str, Any] = '''add'''
with self.assertRaises(SCREAMING_SNAKE_CASE_ ):
UpperCamelCase :Dict = DPTForDepthEstimation(SCREAMING_SNAKE_CASE_ )
def _A ( ):
UpperCamelCase :Union[str, Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
return image
@require_torch
@require_vision
@slow
class UpperCAmelCase_ ( unittest.TestCase ):
"""simple docstring"""
def UpperCAmelCase ( self ) -> Optional[Any]:
UpperCamelCase :List[Any] = DPTImageProcessor.from_pretrained('''Intel/dpt-hybrid-midas''' )
UpperCamelCase :List[str] = DPTForDepthEstimation.from_pretrained('''Intel/dpt-hybrid-midas''' ).to(SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Tuple = prepare_img()
UpperCamelCase :List[str] = image_processor(images=SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' ).to(SCREAMING_SNAKE_CASE_ )
# forward pass
with torch.no_grad():
UpperCamelCase :int = model(**SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Union[str, Any] = outputs.predicted_depth
# verify the predicted depth
UpperCamelCase :int = torch.Size((1, 384, 384) )
self.assertEqual(predicted_depth.shape , SCREAMING_SNAKE_CASE_ )
UpperCamelCase :int = torch.tensor(
[[[5.6437, 5.6146, 5.6511], [5.4371, 5.5649, 5.5958], [5.5215, 5.5184, 5.5293]]] ).to(SCREAMING_SNAKE_CASE_ )
self.assertTrue(torch.allclose(outputs.predicted_depth[:3, :3, :3] / 100 , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) )
| 658 | 0 |
import html
from ...feature_extraction_utils import BatchFeature, FeatureExtractionMixin
from ...utils import is_bsa_available, logging, requires_backends
if is_bsa_available():
import bsa
from bsa import BeautifulSoup
a = logging.get_logger(__name__)
class _A ( __lowercase ):
def __init__( self , **_SCREAMING_SNAKE_CASE ):
requires_backends(self , ["""bs4"""] )
super().__init__(**SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self , _SCREAMING_SNAKE_CASE ):
_UpperCAmelCase = []
_UpperCAmelCase = []
_UpperCAmelCase = element if element.name else element.parent
for parent in child.parents: # type: bs4.element.Tag
_UpperCAmelCase = parent.find_all(child.name , recursive=SCREAMING_SNAKE_CASE_ )
xpath_tags.append(child.name )
xpath_subscripts.append(
0 if 1 == len(SCREAMING_SNAKE_CASE_ ) else next(i for i, s in enumerate(SCREAMING_SNAKE_CASE_ , 1 ) if s is child ) )
_UpperCAmelCase = parent
xpath_tags.reverse()
xpath_subscripts.reverse()
return xpath_tags, xpath_subscripts
def UpperCAmelCase ( self , _SCREAMING_SNAKE_CASE ):
_UpperCAmelCase = BeautifulSoup(SCREAMING_SNAKE_CASE_ , """html.parser""" )
_UpperCAmelCase = []
_UpperCAmelCase = []
_UpperCAmelCase = []
for element in html_code.descendants:
if type(SCREAMING_SNAKE_CASE_ ) == bsa.element.NavigableString:
if type(element.parent ) != bsa.element.Tag:
continue
_UpperCAmelCase = html.unescape(SCREAMING_SNAKE_CASE_ ).strip()
if not text_in_this_tag:
continue
all_doc_strings.append(SCREAMING_SNAKE_CASE_ )
_UpperCAmelCase = self.xpath_soup(SCREAMING_SNAKE_CASE_ )
stringaxtag_seq.append(SCREAMING_SNAKE_CASE_ )
stringaxsubs_seq.append(SCREAMING_SNAKE_CASE_ )
if len(SCREAMING_SNAKE_CASE_ ) != len(SCREAMING_SNAKE_CASE_ ):
raise ValueError("""Number of doc strings and xtags does not correspond""" )
if len(SCREAMING_SNAKE_CASE_ ) != len(SCREAMING_SNAKE_CASE_ ):
raise ValueError("""Number of doc strings and xsubs does not correspond""" )
return all_doc_strings, stringaxtag_seq, stringaxsubs_seq
def UpperCAmelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
_UpperCAmelCase = ''''''
for tagname, subs in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ):
xpath += F"/{tagname}"
if subs != 0:
xpath += F"[{subs}]"
return xpath
def __call__( self , _SCREAMING_SNAKE_CASE ):
_UpperCAmelCase = False
# Check that strings has a valid type
if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ):
_UpperCAmelCase = True
elif isinstance(SCREAMING_SNAKE_CASE_ , (list, tuple) ):
if len(SCREAMING_SNAKE_CASE_ ) == 0 or isinstance(html_strings[0] , SCREAMING_SNAKE_CASE_ ):
_UpperCAmelCase = True
if not valid_strings:
raise ValueError(
"""HTML strings must of type `str`, `List[str]` (batch of examples), """
F"but is of type {type(SCREAMING_SNAKE_CASE_ )}." )
_UpperCAmelCase = bool(isinstance(SCREAMING_SNAKE_CASE_ , (list, tuple) ) and (isinstance(html_strings[0] , SCREAMING_SNAKE_CASE_ )) )
if not is_batched:
_UpperCAmelCase = [html_strings]
# Get nodes + xpaths
_UpperCAmelCase = []
_UpperCAmelCase = []
for html_string in html_strings:
_UpperCAmelCase = self.get_three_from_single(SCREAMING_SNAKE_CASE_ )
nodes.append(SCREAMING_SNAKE_CASE_ )
_UpperCAmelCase = []
for node, tag_list, sub_list in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ):
_UpperCAmelCase = self.construct_xpath(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
xpath_strings.append(SCREAMING_SNAKE_CASE_ )
xpaths.append(SCREAMING_SNAKE_CASE_ )
# return as Dict
_UpperCAmelCase = {'''nodes''': nodes, '''xpaths''': xpaths}
_UpperCAmelCase = BatchFeature(data=SCREAMING_SNAKE_CASE_ , tensor_type=SCREAMING_SNAKE_CASE_ )
return encoded_inputs | 518 |
import argparse
import json
from pathlib import Path
import torch
import torchaudio
from datasets import load_dataset
from huggingface_hub import hf_hub_download
from transformers import ASTConfig, ASTFeatureExtractor, ASTForAudioClassification
from transformers.utils import logging
logging.set_verbosity_info()
__snake_case = logging.get_logger(__name__)
def _A ( SCREAMING_SNAKE_CASE__ : int ):
UpperCamelCase :Union[str, Any] = ASTConfig()
if "10-10" in model_name:
pass
elif "speech-commands" in model_name:
UpperCamelCase :Any = 128
elif "12-12" in model_name:
UpperCamelCase :Union[str, Any] = 12
UpperCamelCase :Any = 12
elif "14-14" in model_name:
UpperCamelCase :Optional[int] = 14
UpperCamelCase :List[str] = 14
elif "16-16" in model_name:
UpperCamelCase :List[Any] = 16
UpperCamelCase :Optional[Any] = 16
else:
raise ValueError('''Model not supported''' )
UpperCamelCase :Tuple = '''huggingface/label-files'''
if "speech-commands" in model_name:
UpperCamelCase :Optional[Any] = 35
UpperCamelCase :List[Any] = '''speech-commands-v2-id2label.json'''
else:
UpperCamelCase :Optional[int] = 527
UpperCamelCase :List[Any] = '''audioset-id2label.json'''
UpperCamelCase :Any = json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , repo_type='''dataset''' ) , '''r''' ) )
UpperCamelCase :List[str] = {int(SCREAMING_SNAKE_CASE__ ): v for k, v in idalabel.items()}
UpperCamelCase :List[Any] = idalabel
UpperCamelCase :List[Any] = {v: k for k, v in idalabel.items()}
return config
def _A ( SCREAMING_SNAKE_CASE__ : Optional[Any] ):
if "module.v" in name:
UpperCamelCase :Any = name.replace('''module.v''' , '''audio_spectrogram_transformer''' )
if "cls_token" in name:
UpperCamelCase :int = name.replace('''cls_token''' , '''embeddings.cls_token''' )
if "dist_token" in name:
UpperCamelCase :Tuple = name.replace('''dist_token''' , '''embeddings.distillation_token''' )
if "pos_embed" in name:
UpperCamelCase :Optional[int] = name.replace('''pos_embed''' , '''embeddings.position_embeddings''' )
if "patch_embed.proj" in name:
UpperCamelCase :str = name.replace('''patch_embed.proj''' , '''embeddings.patch_embeddings.projection''' )
# transformer blocks
if "blocks" in name:
UpperCamelCase :Any = name.replace('''blocks''' , '''encoder.layer''' )
if "attn.proj" in name:
UpperCamelCase :Union[str, Any] = name.replace('''attn.proj''' , '''attention.output.dense''' )
if "attn" in name:
UpperCamelCase :Union[str, Any] = name.replace('''attn''' , '''attention.self''' )
if "norm1" in name:
UpperCamelCase :str = name.replace('''norm1''' , '''layernorm_before''' )
if "norm2" in name:
UpperCamelCase :Tuple = name.replace('''norm2''' , '''layernorm_after''' )
if "mlp.fc1" in name:
UpperCamelCase :Dict = name.replace('''mlp.fc1''' , '''intermediate.dense''' )
if "mlp.fc2" in name:
UpperCamelCase :List[str] = name.replace('''mlp.fc2''' , '''output.dense''' )
# final layernorm
if "audio_spectrogram_transformer.norm" in name:
UpperCamelCase :Union[str, Any] = name.replace('''audio_spectrogram_transformer.norm''' , '''audio_spectrogram_transformer.layernorm''' )
# classifier head
if "module.mlp_head.0" in name:
UpperCamelCase :int = name.replace('''module.mlp_head.0''' , '''classifier.layernorm''' )
if "module.mlp_head.1" in name:
UpperCamelCase :Tuple = name.replace('''module.mlp_head.1''' , '''classifier.dense''' )
return name
def _A ( SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Any ):
for key in orig_state_dict.copy().keys():
UpperCamelCase :Dict = orig_state_dict.pop(SCREAMING_SNAKE_CASE__ )
if "qkv" in key:
UpperCamelCase :Any = key.split('''.''' )
UpperCamelCase :str = int(key_split[3] )
UpperCamelCase :Union[str, Any] = config.hidden_size
if "weight" in key:
UpperCamelCase :List[str] = val[:dim, :]
UpperCamelCase :Optional[Any] = val[dim : dim * 2, :]
UpperCamelCase :Optional[Any] = val[-dim:, :]
else:
UpperCamelCase :Dict = val[:dim]
UpperCamelCase :Optional[int] = val[dim : dim * 2]
UpperCamelCase :List[Any] = val[-dim:]
else:
UpperCamelCase :Union[str, Any] = val
return orig_state_dict
def _A ( SCREAMING_SNAKE_CASE__ : int ):
UpperCamelCase :List[str] = [
'''module.v.head.weight''',
'''module.v.head.bias''',
'''module.v.head_dist.weight''',
'''module.v.head_dist.bias''',
]
for k in ignore_keys:
state_dict.pop(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
@torch.no_grad()
def _A ( SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Any=False ):
UpperCamelCase :Optional[Any] = get_audio_spectrogram_transformer_config(SCREAMING_SNAKE_CASE__ )
UpperCamelCase :str = {
'''ast-finetuned-audioset-10-10-0.4593''': (
'''https://www.dropbox.com/s/ca0b1v2nlxzyeb4/audioset_10_10_0.4593.pth?dl=1'''
),
'''ast-finetuned-audioset-10-10-0.450''': (
'''https://www.dropbox.com/s/1tv0hovue1bxupk/audioset_10_10_0.4495.pth?dl=1'''
),
'''ast-finetuned-audioset-10-10-0.448''': (
'''https://www.dropbox.com/s/6u5sikl4b9wo4u5/audioset_10_10_0.4483.pth?dl=1'''
),
'''ast-finetuned-audioset-10-10-0.448-v2''': (
'''https://www.dropbox.com/s/kt6i0v9fvfm1mbq/audioset_10_10_0.4475.pth?dl=1'''
),
'''ast-finetuned-audioset-12-12-0.447''': (
'''https://www.dropbox.com/s/snfhx3tizr4nuc8/audioset_12_12_0.4467.pth?dl=1'''
),
'''ast-finetuned-audioset-14-14-0.443''': (
'''https://www.dropbox.com/s/z18s6pemtnxm4k7/audioset_14_14_0.4431.pth?dl=1'''
),
'''ast-finetuned-audioset-16-16-0.442''': (
'''https://www.dropbox.com/s/mdsa4t1xmcimia6/audioset_16_16_0.4422.pth?dl=1'''
),
'''ast-finetuned-speech-commands-v2''': (
'''https://www.dropbox.com/s/q0tbqpwv44pquwy/speechcommands_10_10_0.9812.pth?dl=1'''
),
}
# load original state_dict
UpperCamelCase :Optional[int] = model_name_to_url[model_name]
UpperCamelCase :Tuple = torch.hub.load_state_dict_from_url(SCREAMING_SNAKE_CASE__ , map_location='''cpu''' )
# remove some keys
remove_keys(SCREAMING_SNAKE_CASE__ )
# rename some keys
UpperCamelCase :Union[str, Any] = convert_state_dict(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
# load 🤗 model
UpperCamelCase :int = ASTForAudioClassification(SCREAMING_SNAKE_CASE__ )
model.eval()
model.load_state_dict(SCREAMING_SNAKE_CASE__ )
# verify outputs on dummy input
# source: https://github.com/YuanGongND/ast/blob/79e873b8a54d0a3b330dd522584ff2b9926cd581/src/run.py#L62
UpperCamelCase :Union[str, Any] = -4.2_67_73_93 if '''speech-commands''' not in model_name else -6.84_59_78
UpperCamelCase :List[str] = 4.5_68_99_74 if '''speech-commands''' not in model_name else 5.5_65_45_26
UpperCamelCase :Optional[Any] = 1024 if '''speech-commands''' not in model_name else 128
UpperCamelCase :int = ASTFeatureExtractor(mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ )
if "speech-commands" in model_name:
UpperCamelCase :Dict = load_dataset('''speech_commands''' , '''v0.02''' , split='''validation''' )
UpperCamelCase :List[Any] = dataset[0]['''audio''']['''array''']
else:
UpperCamelCase :List[Any] = hf_hub_download(
repo_id='''nielsr/audio-spectogram-transformer-checkpoint''' , filename='''sample_audio.flac''' , repo_type='''dataset''' , )
UpperCamelCase , UpperCamelCase :Dict = torchaudio.load(SCREAMING_SNAKE_CASE__ )
UpperCamelCase :List[str] = waveform.squeeze().numpy()
UpperCamelCase :Optional[int] = feature_extractor(SCREAMING_SNAKE_CASE__ , sampling_rate=16000 , return_tensors='''pt''' )
# forward pass
UpperCamelCase :List[str] = model(**SCREAMING_SNAKE_CASE__ )
UpperCamelCase :str = outputs.logits
if model_name == "ast-finetuned-audioset-10-10-0.4593":
UpperCamelCase :Tuple = torch.tensor([-0.87_60, -7.00_42, -8.66_02] )
elif model_name == "ast-finetuned-audioset-10-10-0.450":
UpperCamelCase :Union[str, Any] = torch.tensor([-1.19_86, -7.09_03, -8.27_18] )
elif model_name == "ast-finetuned-audioset-10-10-0.448":
UpperCamelCase :str = torch.tensor([-2.61_28, -8.00_80, -9.43_44] )
elif model_name == "ast-finetuned-audioset-10-10-0.448-v2":
UpperCamelCase :List[str] = torch.tensor([-1.50_80, -7.45_34, -8.89_17] )
elif model_name == "ast-finetuned-audioset-12-12-0.447":
UpperCamelCase :Dict = torch.tensor([-0.50_50, -6.58_33, -8.08_43] )
elif model_name == "ast-finetuned-audioset-14-14-0.443":
UpperCamelCase :List[str] = torch.tensor([-0.38_26, -7.03_36, -8.24_13] )
elif model_name == "ast-finetuned-audioset-16-16-0.442":
UpperCamelCase :Optional[int] = torch.tensor([-1.21_13, -6.91_01, -8.34_70] )
elif model_name == "ast-finetuned-speech-commands-v2":
UpperCamelCase :List[Any] = torch.tensor([6.15_89, -8.05_66, -8.79_84] )
else:
raise ValueError('''Unknown model name''' )
if not torch.allclose(logits[0, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ):
raise ValueError('''Logits don\'t match''' )
print('''Looks ok!''' )
if pytorch_dump_folder_path is not None:
Path(SCREAMING_SNAKE_CASE__ ).mkdir(exist_ok=SCREAMING_SNAKE_CASE__ )
print(F'''Saving model {model_name} to {pytorch_dump_folder_path}''' )
model.save_pretrained(SCREAMING_SNAKE_CASE__ )
print(F'''Saving feature extractor to {pytorch_dump_folder_path}''' )
feature_extractor.save_pretrained(SCREAMING_SNAKE_CASE__ )
if push_to_hub:
print('''Pushing model and feature extractor to the hub...''' )
model.push_to_hub(F'''MIT/{model_name}''' )
feature_extractor.push_to_hub(F'''MIT/{model_name}''' )
if __name__ == "__main__":
__snake_case = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"""--model_name""",
default="""ast-finetuned-audioset-10-10-0.4593""",
type=str,
help="""Name of the Audio Spectrogram Transformer model you'd like to convert.""",
)
parser.add_argument(
"""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory."""
)
parser.add_argument(
"""--push_to_hub""", action="""store_true""", help="""Whether or not to push the converted model to the 🤗 hub."""
)
__snake_case = parser.parse_args()
convert_audio_spectrogram_transformer_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
| 658 | 0 |
from __future__ import annotations
def _a ( a :list ) -> Tuple:
if not nums:
raise ValueError('''List is empty''' )
return sum(SCREAMING_SNAKE_CASE__ ) / len(SCREAMING_SNAKE_CASE__ )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 117 |
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_sentencepiece_available,
is_tokenizers_available,
is_torch_available,
)
__snake_case = {
"""configuration_llama""": ["""LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP""", """LlamaConfig"""],
}
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__snake_case = ["""LlamaTokenizer"""]
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__snake_case = ["""LlamaTokenizerFast"""]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__snake_case = [
"""LlamaForCausalLM""",
"""LlamaModel""",
"""LlamaPreTrainedModel""",
"""LlamaForSequenceClassification""",
]
if TYPE_CHECKING:
from .configuration_llama import LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP, LlamaConfig
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_llama import LlamaTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_llama_fast import LlamaTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_llama import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaPreTrainedModel
else:
import sys
__snake_case = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 658 | 0 |
__UpperCamelCase : Tuple = {
'Pillow': 'Pillow',
'accelerate': 'accelerate>=0.11.0',
'compel': 'compel==0.1.8',
'black': 'black~=23.1',
'datasets': 'datasets',
'filelock': 'filelock',
'flax': 'flax>=0.4.1',
'hf-doc-builder': 'hf-doc-builder>=0.3.0',
'huggingface-hub': 'huggingface-hub>=0.13.2',
'requests-mock': 'requests-mock==1.10.0',
'importlib_metadata': 'importlib_metadata',
'invisible-watermark': 'invisible-watermark',
'isort': 'isort>=5.5.4',
'jax': 'jax>=0.2.8,!=0.3.2',
'jaxlib': 'jaxlib>=0.1.65',
'Jinja2': 'Jinja2',
'k-diffusion': 'k-diffusion>=0.0.12',
'torchsde': 'torchsde',
'note_seq': 'note_seq',
'librosa': 'librosa',
'numpy': 'numpy',
'omegaconf': 'omegaconf',
'parameterized': 'parameterized',
'protobuf': 'protobuf>=3.20.3,<4',
'pytest': 'pytest',
'pytest-timeout': 'pytest-timeout',
'pytest-xdist': 'pytest-xdist',
'ruff': 'ruff>=0.0.241',
'safetensors': 'safetensors',
'sentencepiece': 'sentencepiece>=0.1.91,!=0.1.92',
'scipy': 'scipy',
'onnx': 'onnx',
'regex': 'regex!=2019.12.17',
'requests': 'requests',
'tensorboard': 'tensorboard',
'torch': 'torch>=1.4',
'torchvision': 'torchvision',
'transformers': 'transformers>=4.25.1',
'urllib3': 'urllib3<=2.0.0',
}
| 248 |
import math_equivalence # From: git+https://github.com/hendrycks/math.git
import datasets
__snake_case = """\
@article{hendrycksmath2021,
title={Measuring Mathematical Problem Solving With the MATH Dataset},
author={Dan Hendrycks
and Collin Burns
and Saurav Kadavath
and Akul Arora
and Steven Basart
and Eric Tang
and Dawn Song
and Jacob Steinhardt},
journal={arXiv preprint arXiv:2103.03874},
year={2021}
}
"""
__snake_case = """\
This metric is used to assess performance on the Mathematics Aptitude Test of Heuristics (MATH) dataset.
It first canonicalizes the inputs (e.g., converting \"1/2\" to \"\\frac{1}{2}\") and then computes accuracy.
"""
__snake_case = R"""
Calculates accuracy after canonicalizing inputs.
Args:
predictions: list of predictions to score. Each prediction
is a string that contains natural language and LaTex.
references: list of reference for each prediction. Each
reference is a string that contains natural language
and LaTex.
Returns:
accuracy: accuracy after canonicalizing inputs
(e.g., converting \"1/2\" to \"\\frac{1}{2}\")
Examples:
>>> metric = datasets.load_metric(\"competition_math\")
>>> results = metric.compute(references=[\"\\frac{1}{2}\"], predictions=[\"1/2\"])
>>> print(results)
{'accuracy': 1.0}
"""
@datasets.utils.file_utils.add_end_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION )
class UpperCAmelCase_ ( datasets.Metric ):
"""simple docstring"""
def UpperCAmelCase ( self ) -> Optional[Any]:
return datasets.MetricInfo(
description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(
{
'''predictions''': datasets.Value('''string''' ),
'''references''': datasets.Value('''string''' ),
} ) , homepage='''https://github.com/hendrycks/math''' , codebase_urls=['''https://github.com/hendrycks/math'''] , )
def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Any:
UpperCamelCase :Tuple = 0.0
for i, j in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ):
n_correct += 1.0 if math_equivalence.is_equiv(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else 0.0
UpperCamelCase :int = n_correct / len(SCREAMING_SNAKE_CASE_ )
return {
"accuracy": accuracy,
}
| 658 | 0 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
lowercase__ =logging.get_logger(__name__)
lowercase__ ={
'RWKV/rwkv-4-169m-pile': 'https://huggingface.co/RWKV/rwkv-4-169m-pile/resolve/main/config.json',
'RWKV/rwkv-4-430m-pile': 'https://huggingface.co/RWKV/rwkv-4-430m-pile/resolve/main/config.json',
'RWKV/rwkv-4-1b5-pile': 'https://huggingface.co/RWKV/rwkv-4-1b5-pile/resolve/main/config.json',
'RWKV/rwkv-4-3b-pile': 'https://huggingface.co/RWKV/rwkv-4-3b-pile/resolve/main/config.json',
'RWKV/rwkv-4-7b-pile': 'https://huggingface.co/RWKV/rwkv-4-7b-pile/resolve/main/config.json',
'RWKV/rwkv-4-14b-pile': 'https://huggingface.co/RWKV/rwkv-4-14b-pile/resolve/main/config.json',
'RWKV/rwkv-raven-1b5': 'https://huggingface.co/RWKV/rwkv-raven-1b5/resolve/main/config.json',
'RWKV/rwkv-raven-3b': 'https://huggingface.co/RWKV/rwkv-raven-3b/resolve/main/config.json',
'RWKV/rwkv-raven-7b': 'https://huggingface.co/RWKV/rwkv-raven-7b/resolve/main/config.json',
'RWKV/rwkv-raven-14b': 'https://huggingface.co/RWKV/rwkv-raven-14b/resolve/main/config.json',
}
class UpperCamelCase__ ( __lowercase ):
_SCREAMING_SNAKE_CASE : List[Any] = 'rwkv'
_SCREAMING_SNAKE_CASE : Any = {'max_position_embeddings': 'context_length'}
def __init__(self : List[str] , snake_case_ : Optional[int]=5_0_2_7_7 , snake_case_ : Any=1_0_2_4 , snake_case_ : List[str]=4_0_9_6 , snake_case_ : str=3_2 , snake_case_ : Any=None , snake_case_ : Dict=None , snake_case_ : str=1E-5 , snake_case_ : str=0 , snake_case_ : Union[str, Any]=0 , snake_case_ : Optional[Any]=6 , snake_case_ : Tuple=False , snake_case_ : Union[str, Any]=True , **snake_case_ : Optional[Any] , ):
__a : int = vocab_size
__a : List[Any] = context_length
__a : Dict = hidden_size
__a : Dict = num_hidden_layers
__a : Optional[Any] = attention_hidden_size if attention_hidden_size is not None else hidden_size
__a : Tuple = intermediate_size if intermediate_size is not None else 4 * hidden_size
__a : int = layer_norm_epsilon
__a : Union[str, Any] = rescale_every
__a : Optional[int] = use_cache
__a : List[Any] = bos_token_id
__a : List[str] = eos_token_id
super().__init__(
tie_word_embeddings=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
| 521 |
import argparse
import json
import logging
import os
import sys
from unittest.mock import patch
from transformers.testing_utils import TestCasePlus, get_gpu_count, slow
__snake_case = [
os.path.join(os.path.dirname(__file__), dirname)
for dirname in [
"""text-classification""",
"""language-modeling""",
"""summarization""",
"""token-classification""",
"""question-answering""",
]
]
sys.path.extend(SRC_DIRS)
if SRC_DIRS is not None:
import run_clm_flax
import run_flax_glue
import run_flax_ner
import run_mlm_flax
import run_qa
import run_summarization_flax
import run_ta_mlm_flax
logging.basicConfig(level=logging.DEBUG)
__snake_case = logging.getLogger()
def _A ( ):
UpperCamelCase :List[Any] = argparse.ArgumentParser()
parser.add_argument('''-f''' )
UpperCamelCase :Dict = parser.parse_args()
return args.f
def _A ( SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[int]="eval" ):
UpperCamelCase :Optional[Any] = os.path.join(SCREAMING_SNAKE_CASE__ , F'''{split}_results.json''' )
if os.path.exists(SCREAMING_SNAKE_CASE__ ):
with open(SCREAMING_SNAKE_CASE__ , '''r''' ) as f:
return json.load(SCREAMING_SNAKE_CASE__ )
raise ValueError(F'''can\'t find {path}''' )
__snake_case = logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)
class UpperCAmelCase_ ( lowercase ):
"""simple docstring"""
def UpperCAmelCase ( self ) -> List[Any]:
UpperCamelCase :Union[str, Any] = self.get_auto_remove_tmp_dir()
UpperCamelCase :Optional[Any] = F'''
run_glue.py
--model_name_or_path distilbert-base-uncased
--output_dir {tmp_dir}
--train_file ./tests/fixtures/tests_samples/MRPC/train.csv
--validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv
--per_device_train_batch_size=2
--per_device_eval_batch_size=1
--learning_rate=1e-4
--eval_steps=2
--warmup_steps=2
--seed=42
--max_seq_length=128
'''.split()
with patch.object(SCREAMING_SNAKE_CASE_ , '''argv''' , SCREAMING_SNAKE_CASE_ ):
run_flax_glue.main()
UpperCamelCase :Dict = get_results(SCREAMING_SNAKE_CASE_ )
self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75 )
@slow
def UpperCAmelCase ( self ) -> Union[str, Any]:
UpperCamelCase :int = self.get_auto_remove_tmp_dir()
UpperCamelCase :Optional[Any] = F'''
run_clm_flax.py
--model_name_or_path distilgpt2
--train_file ./tests/fixtures/sample_text.txt
--validation_file ./tests/fixtures/sample_text.txt
--do_train
--do_eval
--block_size 128
--per_device_train_batch_size 4
--per_device_eval_batch_size 4
--num_train_epochs 2
--logging_steps 2 --eval_steps 2
--output_dir {tmp_dir}
--overwrite_output_dir
'''.split()
with patch.object(SCREAMING_SNAKE_CASE_ , '''argv''' , SCREAMING_SNAKE_CASE_ ):
run_clm_flax.main()
UpperCamelCase :Any = get_results(SCREAMING_SNAKE_CASE_ )
self.assertLess(result['''eval_perplexity'''] , 100 )
@slow
def UpperCAmelCase ( self ) -> Tuple:
UpperCamelCase :Dict = self.get_auto_remove_tmp_dir()
UpperCamelCase :Any = F'''
run_summarization.py
--model_name_or_path t5-small
--train_file tests/fixtures/tests_samples/xsum/sample.json
--validation_file tests/fixtures/tests_samples/xsum/sample.json
--test_file tests/fixtures/tests_samples/xsum/sample.json
--output_dir {tmp_dir}
--overwrite_output_dir
--num_train_epochs=3
--warmup_steps=8
--do_train
--do_eval
--do_predict
--learning_rate=2e-4
--per_device_train_batch_size=2
--per_device_eval_batch_size=1
--predict_with_generate
'''.split()
with patch.object(SCREAMING_SNAKE_CASE_ , '''argv''' , SCREAMING_SNAKE_CASE_ ):
run_summarization_flax.main()
UpperCamelCase :str = get_results(SCREAMING_SNAKE_CASE_ , split='''test''' )
self.assertGreaterEqual(result['''test_rouge1'''] , 10 )
self.assertGreaterEqual(result['''test_rouge2'''] , 2 )
self.assertGreaterEqual(result['''test_rougeL'''] , 7 )
self.assertGreaterEqual(result['''test_rougeLsum'''] , 7 )
@slow
def UpperCAmelCase ( self ) -> Union[str, Any]:
UpperCamelCase :List[str] = self.get_auto_remove_tmp_dir()
UpperCamelCase :List[str] = F'''
run_mlm.py
--model_name_or_path distilroberta-base
--train_file ./tests/fixtures/sample_text.txt
--validation_file ./tests/fixtures/sample_text.txt
--output_dir {tmp_dir}
--overwrite_output_dir
--max_seq_length 128
--per_device_train_batch_size 4
--per_device_eval_batch_size 4
--logging_steps 2 --eval_steps 2
--do_train
--do_eval
--num_train_epochs=1
'''.split()
with patch.object(SCREAMING_SNAKE_CASE_ , '''argv''' , SCREAMING_SNAKE_CASE_ ):
run_mlm_flax.main()
UpperCamelCase :Dict = get_results(SCREAMING_SNAKE_CASE_ )
self.assertLess(result['''eval_perplexity'''] , 42 )
@slow
def UpperCAmelCase ( self ) -> Optional[int]:
UpperCamelCase :Optional[Any] = self.get_auto_remove_tmp_dir()
UpperCamelCase :int = F'''
run_t5_mlm_flax.py
--model_name_or_path t5-small
--train_file ./tests/fixtures/sample_text.txt
--validation_file ./tests/fixtures/sample_text.txt
--do_train
--do_eval
--max_seq_length 128
--per_device_train_batch_size 4
--per_device_eval_batch_size 4
--num_train_epochs 2
--logging_steps 2 --eval_steps 2
--output_dir {tmp_dir}
--overwrite_output_dir
'''.split()
with patch.object(SCREAMING_SNAKE_CASE_ , '''argv''' , SCREAMING_SNAKE_CASE_ ):
run_ta_mlm_flax.main()
UpperCamelCase :Any = get_results(SCREAMING_SNAKE_CASE_ )
self.assertGreaterEqual(result['''eval_accuracy'''] , 0.42 )
@slow
def UpperCAmelCase ( self ) -> Tuple:
# with so little data distributed training needs more epochs to get the score on par with 0/1 gpu
UpperCamelCase :Tuple = 7 if get_gpu_count() > 1 else 2
UpperCamelCase :int = self.get_auto_remove_tmp_dir()
UpperCamelCase :Optional[int] = F'''
run_flax_ner.py
--model_name_or_path bert-base-uncased
--train_file tests/fixtures/tests_samples/conll/sample.json
--validation_file tests/fixtures/tests_samples/conll/sample.json
--output_dir {tmp_dir}
--overwrite_output_dir
--do_train
--do_eval
--warmup_steps=2
--learning_rate=2e-4
--logging_steps 2 --eval_steps 2
--per_device_train_batch_size=2
--per_device_eval_batch_size=2
--num_train_epochs={epochs}
--seed 7
'''.split()
with patch.object(SCREAMING_SNAKE_CASE_ , '''argv''' , SCREAMING_SNAKE_CASE_ ):
run_flax_ner.main()
UpperCamelCase :Any = get_results(SCREAMING_SNAKE_CASE_ )
self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75 )
self.assertGreaterEqual(result['''eval_f1'''] , 0.3 )
@slow
def UpperCAmelCase ( self ) -> Any:
UpperCamelCase :List[str] = self.get_auto_remove_tmp_dir()
UpperCamelCase :Dict = F'''
run_qa.py
--model_name_or_path bert-base-uncased
--version_2_with_negative
--train_file tests/fixtures/tests_samples/SQUAD/sample.json
--validation_file tests/fixtures/tests_samples/SQUAD/sample.json
--output_dir {tmp_dir}
--overwrite_output_dir
--num_train_epochs=3
--warmup_steps=2
--do_train
--do_eval
--logging_steps 2 --eval_steps 2
--learning_rate=2e-4
--per_device_train_batch_size=2
--per_device_eval_batch_size=1
'''.split()
with patch.object(SCREAMING_SNAKE_CASE_ , '''argv''' , SCREAMING_SNAKE_CASE_ ):
run_qa.main()
UpperCamelCase :int = get_results(SCREAMING_SNAKE_CASE_ )
self.assertGreaterEqual(result['''eval_f1'''] , 30 )
self.assertGreaterEqual(result['''eval_exact'''] , 30 )
| 658 | 0 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available
UpperCAmelCase = {"""configuration_van""": ["""VAN_PRETRAINED_CONFIG_ARCHIVE_MAP""", """VanConfig"""]}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCAmelCase = [
"""VAN_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""VanForImageClassification""",
"""VanModel""",
"""VanPreTrainedModel""",
]
if TYPE_CHECKING:
from .configuration_van import VAN_PRETRAINED_CONFIG_ARCHIVE_MAP, VanConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_van import (
VAN_PRETRAINED_MODEL_ARCHIVE_LIST,
VanForImageClassification,
VanModel,
VanPreTrainedModel,
)
else:
import sys
UpperCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure)
| 535 |
from __future__ import annotations
from collections.abc import Callable
def _A ( SCREAMING_SNAKE_CASE__ : Callable[[int | float], int | float] , SCREAMING_SNAKE_CASE__ : int | float , SCREAMING_SNAKE_CASE__ : int | float , SCREAMING_SNAKE_CASE__ : int = 100 , ):
UpperCamelCase :Optional[Any] = x_start
UpperCamelCase :Any = fnc(SCREAMING_SNAKE_CASE__ )
UpperCamelCase :Optional[int] = 0.0
for _ in range(SCREAMING_SNAKE_CASE__ ):
# Approximates small segments of curve as linear and solve
# for trapezoidal area
UpperCamelCase :Any = (x_end - x_start) / steps + xa
UpperCamelCase :Dict = fnc(SCREAMING_SNAKE_CASE__ )
area += abs(fxa + fxa ) * (xa - xa) / 2
# Increment step
UpperCamelCase :Optional[int] = xa
UpperCamelCase :List[str] = fxa
return area
if __name__ == "__main__":
def _A ( SCREAMING_SNAKE_CASE__ : int ):
return x**3 + x**2
print("""f(x) = x^3 + x^2""")
print("""The area between the curve, x = -5, x = 5 and the x axis is:""")
__snake_case = 10
while i <= 10_00_00:
print(f'''with {i} steps: {trapezoidal_area(f, -5, 5, i)}''')
i *= 10
| 658 | 0 |
"""simple docstring"""
def __snake_case ( __A ,__A ) -> List[str]:
lowercase : Optional[int] = 1 # To kept the Calculated Value
# Since C(n, k) = C(n, n-k)
if k > (n - k):
lowercase : Optional[Any] = n - k
# Calculate C(n,k)
for i in range(SCREAMING_SNAKE_CASE__ ):
result *= n - i
result //= i + 1
return result
def __snake_case ( __A ) -> Optional[int]:
return binomial_coefficient(2 * node_count ,SCREAMING_SNAKE_CASE__ ) // (node_count + 1)
def __snake_case ( __A ) -> Any:
if n < 0:
raise ValueError("""factorial() not defined for negative values""" )
lowercase : Any = 1
for i in range(1 ,n + 1 ):
result *= i
return result
def __snake_case ( __A ) -> str:
return catalan_number(SCREAMING_SNAKE_CASE__ ) * factorial(SCREAMING_SNAKE_CASE__ )
if __name__ == "__main__":
lowerCAmelCase: Any =int(input("Enter the number of nodes: ").strip() or 0)
if node_count <= 0:
raise ValueError("We need some nodes to work with.")
print(
F'Given {node_count} nodes, there are {binary_tree_count(node_count)} '
F'binary trees and {catalan_number(node_count)} binary search trees.'
)
| 607 |
import torch
from diffusers import CMStochasticIterativeScheduler
from .test_schedulers import SchedulerCommonTest
class UpperCAmelCase_ ( lowercase ):
"""simple docstring"""
UpperCamelCase_ : Optional[int] =(CMStochasticIterativeScheduler,)
UpperCamelCase_ : Any =10
def UpperCAmelCase ( self , **SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]:
UpperCamelCase :str = {
'''num_train_timesteps''': 201,
'''sigma_min''': 0.002,
'''sigma_max''': 80.0,
}
config.update(**SCREAMING_SNAKE_CASE_ )
return config
def UpperCAmelCase ( self ) -> str:
UpperCamelCase :Optional[Any] = 10
UpperCamelCase :Optional[Any] = self.get_scheduler_config()
UpperCamelCase :Dict = self.scheduler_classes[0](**SCREAMING_SNAKE_CASE_ )
scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Any = scheduler.timesteps[0]
UpperCamelCase :Union[str, Any] = scheduler.timesteps[1]
UpperCamelCase :str = self.dummy_sample
UpperCamelCase :List[str] = 0.1 * sample
UpperCamelCase :List[str] = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).prev_sample
UpperCamelCase :str = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).prev_sample
self.assertEqual(output_a.shape , sample.shape )
self.assertEqual(output_a.shape , output_a.shape )
def UpperCAmelCase ( self ) -> List[str]:
for timesteps in [10, 50, 100, 1000]:
self.check_over_configs(num_train_timesteps=SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self ) -> Union[str, Any]:
for clip_denoised in [True, False]:
self.check_over_configs(clip_denoised=SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self ) -> List[Any]:
UpperCamelCase :List[Any] = self.scheduler_classes[0]
UpperCamelCase :List[Any] = self.get_scheduler_config()
UpperCamelCase :Optional[Any] = scheduler_class(**SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Dict = 1
scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Any = scheduler.timesteps
UpperCamelCase :Union[str, Any] = torch.manual_seed(0 )
UpperCamelCase :Union[str, Any] = self.dummy_model()
UpperCamelCase :List[Any] = self.dummy_sample_deter * scheduler.init_noise_sigma
for i, t in enumerate(SCREAMING_SNAKE_CASE_ ):
# 1. scale model input
UpperCamelCase :List[str] = scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# 2. predict noise residual
UpperCamelCase :Optional[int] = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# 3. predict previous sample x_t-1
UpperCamelCase :List[Any] = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ ).prev_sample
UpperCamelCase :Tuple = pred_prev_sample
UpperCamelCase :Any = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) )
UpperCamelCase :Union[str, Any] = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) )
assert abs(result_sum.item() - 192.7614 ) < 1e-2
assert abs(result_mean.item() - 0.2510 ) < 1e-3
def UpperCAmelCase ( self ) -> str:
UpperCamelCase :Dict = self.scheduler_classes[0]
UpperCamelCase :Optional[Any] = self.get_scheduler_config()
UpperCamelCase :Optional[Any] = scheduler_class(**SCREAMING_SNAKE_CASE_ )
UpperCamelCase :List[str] = [106, 0]
scheduler.set_timesteps(timesteps=SCREAMING_SNAKE_CASE_ )
UpperCamelCase :List[str] = scheduler.timesteps
UpperCamelCase :int = torch.manual_seed(0 )
UpperCamelCase :str = self.dummy_model()
UpperCamelCase :List[str] = self.dummy_sample_deter * scheduler.init_noise_sigma
for t in timesteps:
# 1. scale model input
UpperCamelCase :List[Any] = scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# 2. predict noise residual
UpperCamelCase :int = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# 3. predict previous sample x_t-1
UpperCamelCase :Optional[int] = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ ).prev_sample
UpperCamelCase :int = pred_prev_sample
UpperCamelCase :Tuple = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) )
UpperCamelCase :int = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) )
assert abs(result_sum.item() - 347.6357 ) < 1e-2
assert abs(result_mean.item() - 0.4527 ) < 1e-3
def UpperCAmelCase ( self ) -> Optional[Any]:
UpperCamelCase :List[str] = self.scheduler_classes[0]
UpperCamelCase :Tuple = self.get_scheduler_config()
UpperCamelCase :List[str] = scheduler_class(**SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Any = [39, 30, 12, 15, 0]
with self.assertRaises(SCREAMING_SNAKE_CASE_ , msg='''`timesteps` must be in descending order.''' ):
scheduler.set_timesteps(timesteps=SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self ) -> str:
UpperCamelCase :List[str] = self.scheduler_classes[0]
UpperCamelCase :List[Any] = self.get_scheduler_config()
UpperCamelCase :Optional[int] = scheduler_class(**SCREAMING_SNAKE_CASE_ )
UpperCamelCase :int = [39, 30, 12, 1, 0]
UpperCamelCase :Optional[Any] = len(SCREAMING_SNAKE_CASE_ )
with self.assertRaises(SCREAMING_SNAKE_CASE_ , msg='''Can only pass one of `num_inference_steps` or `timesteps`.''' ):
scheduler.set_timesteps(num_inference_steps=SCREAMING_SNAKE_CASE_ , timesteps=SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self ) -> str:
UpperCamelCase :Optional[int] = self.scheduler_classes[0]
UpperCamelCase :List[str] = self.get_scheduler_config()
UpperCamelCase :Dict = scheduler_class(**SCREAMING_SNAKE_CASE_ )
UpperCamelCase :List[Any] = [scheduler.config.num_train_timesteps]
with self.assertRaises(
SCREAMING_SNAKE_CASE_ , msg='''`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}''' , ):
scheduler.set_timesteps(timesteps=SCREAMING_SNAKE_CASE_ )
| 658 | 0 |
import argparse
import collections
import numpy as np
import torch
from flax import traverse_util
from tax import checkpoints
from transformers import MTaConfig, UMTaEncoderModel, UMTaForConditionalGeneration
from transformers.utils import logging
logging.set_verbosity_info()
def UpperCamelCase_ ( __a , __a , __a ) -> int:
return params[f'''{prefix}/{prefix}/relpos_bias/rel_embedding'''][:, i, :]
def UpperCamelCase_ ( __a , __a , __a , __a="attention" ) -> List[str]:
a__ : Union[str, Any] = np.ascontiguousarray(params[f'''{prefix}/{prefix}/{layer_name}/key/kernel'''][:, i, :, :] )
a__ : List[str] = k_tmp.reshape(k_tmp.shape[0] , k_tmp.shape[1] * k_tmp.shape[2] )
a__ : int = np.ascontiguousarray(params[f'''{prefix}/{prefix}/{layer_name}/out/kernel'''][:, i, :, :] )
a__ : List[str] = o_tmp.reshape(o_tmp.shape[0] * o_tmp.shape[1] , o_tmp.shape[2] )
a__ : int = np.ascontiguousarray(params[f'''{prefix}/{prefix}/{layer_name}/query/kernel'''][:, i, :, :] )
a__ : List[str] = q_tmp.reshape(q_tmp.shape[0] , q_tmp.shape[1] * q_tmp.shape[2] )
a__ : Tuple = np.ascontiguousarray(params[f'''{prefix}/{prefix}/{layer_name}/value/kernel'''][:, i, :, :] )
a__ : int = v_tmp.reshape(v_tmp.shape[0] , v_tmp.shape[1] * v_tmp.shape[2] )
return k, o, q, v
def UpperCamelCase_ ( __a , __a , __a , __a=False ) -> Any:
if split_mlp_wi:
a__ : Optional[int] = params[f'''{prefix}/{prefix}/mlp/wi_0/kernel'''][:, i, :]
a__ : str = params[f'''{prefix}/{prefix}/mlp/wi_1/kernel'''][:, i, :]
a__ : Tuple = (wi_a, wi_a)
else:
a__ : Tuple = params[f'''{prefix}/{prefix}/mlp/wi/kernel'''][:, i, :]
a__ : int = params[f'''{prefix}/{prefix}/mlp/wo/kernel'''][:, i, :]
return wi, wo
def UpperCamelCase_ ( __a , __a , __a , __a ) -> Tuple:
return params[f'''{prefix}/{prefix}/{layer_name}/scale'''][:, i]
def UpperCamelCase_ ( __a , *, __a , __a , __a = False ) -> List[str]:
a__ : str = traverse_util.flatten_dict(variables["target"] )
a__ : Dict = {'''/'''.join(SCREAMING_SNAKE_CASE__ ): v for k, v in old.items()}
# v1.1 models have a gated GeLU with wi_0 and wi_1 instead of wi
a__ : List[Any] = '''encoder/encoder/mlp/wi_0/kernel''' in old
print("Split MLP:" , SCREAMING_SNAKE_CASE__ )
a__ : Optional[int] = collections.OrderedDict()
# Shared embeddings.
a__ : Dict = old['''token_embedder/embedding''']
# Encoder.
for i in range(SCREAMING_SNAKE_CASE__ ):
# Block i, layer 0 (Self Attention).
a__ : List[str] = tax_layer_norm_lookup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , "encoder" , "pre_attention_layer_norm" )
a__ : List[str] = tax_attention_lookup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , "encoder" , "attention" )
a__ : Dict = layer_norm
a__ : Union[str, Any] = k.T
a__ : Optional[Any] = o.T
a__ : str = q.T
a__ : List[Any] = v.T
# Block i, layer 1 (MLP).
a__ : Dict = tax_layer_norm_lookup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , "encoder" , "pre_mlp_layer_norm" )
a__ : Optional[Any] = tax_mlp_lookup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , "encoder" , SCREAMING_SNAKE_CASE__ )
a__ : Union[str, Any] = layer_norm
if split_mlp_wi:
a__ : Any = wi[0].T
a__ : List[Any] = wi[1].T
else:
a__ : Any = wi.T
a__ : Tuple = wo.T
if scalable_attention:
# convert the rel_embedding of each layer
a__ : Dict = tax_relpos_bias_lookup(
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , "encoder" ).T
a__ : int = old['''encoder/encoder_norm/scale''']
if not scalable_attention:
a__ : Union[str, Any] = tax_relpos_bias_lookup(
SCREAMING_SNAKE_CASE__ , 0 , "encoder" ).T
a__ : int = tax_relpos_bias_lookup(
SCREAMING_SNAKE_CASE__ , 0 , "decoder" ).T
if not is_encoder_only:
# Decoder.
for i in range(SCREAMING_SNAKE_CASE__ ):
# Block i, layer 0 (Self Attention).
a__ : Optional[Any] = tax_layer_norm_lookup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , "decoder" , "pre_self_attention_layer_norm" )
a__ : Optional[Any] = tax_attention_lookup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , "decoder" , "self_attention" )
a__ : str = layer_norm
a__ : Any = k.T
a__ : Dict = o.T
a__ : int = q.T
a__ : Dict = v.T
# Block i, layer 1 (Cross Attention).
a__ : Tuple = tax_layer_norm_lookup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , "decoder" , "pre_cross_attention_layer_norm" )
a__ : str = tax_attention_lookup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , "decoder" , "encoder_decoder_attention" )
a__ : Dict = layer_norm
a__ : List[str] = k.T
a__ : Optional[Any] = o.T
a__ : str = q.T
a__ : int = v.T
# Block i, layer 2 (MLP).
a__ : Dict = tax_layer_norm_lookup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , "decoder" , "pre_mlp_layer_norm" )
a__ : Dict = tax_mlp_lookup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , "decoder" , SCREAMING_SNAKE_CASE__ )
a__ : Tuple = layer_norm
if split_mlp_wi:
a__ : Any = wi[0].T
a__ : int = wi[1].T
else:
a__ : Union[str, Any] = wi.T
a__ : Tuple = wo.T
if scalable_attention:
# convert the rel_embedding of each layer
a__ : List[Any] = tax_relpos_bias_lookup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , "decoder" ).T
a__ : Union[str, Any] = old['''decoder/decoder_norm/scale''']
# LM Head (only in v1.1 checkpoints, in v1.0 embeddings are used instead)
if "decoder/logits_dense/kernel" in old:
a__ : Optional[int] = old['''decoder/logits_dense/kernel'''].T
return new
def UpperCamelCase_ ( __a , __a ) -> Dict:
a__ : List[str] = collections.OrderedDict([(k, torch.from_numpy(v.copy() )) for (k, v) in converted_params.items()] )
# Add what is missing.
if "encoder.embed_tokens.weight" not in state_dict:
a__ : Tuple = state_dict['''shared.weight''']
if not is_encoder_only:
if "decoder.embed_tokens.weight" not in state_dict:
a__ : Optional[Any] = state_dict['''shared.weight''']
if "lm_head.weight" not in state_dict: # For old 1.0 models.
print("Using shared word embeddings as lm_head." )
a__ : Optional[int] = state_dict['''shared.weight''']
return state_dict
def UpperCamelCase_ ( __a , __a , __a , __a , __a ) -> str:
a__ : Optional[Any] = checkpoints.load_tax_checkpoint(SCREAMING_SNAKE_CASE__ )
a__ : Union[str, Any] = convert_tax_to_pytorch(
SCREAMING_SNAKE_CASE__ , num_layers=config.num_layers , is_encoder_only=SCREAMING_SNAKE_CASE__ , scalable_attention=SCREAMING_SNAKE_CASE__ )
a__ : Optional[int] = make_state_dict(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
model.load_state_dict(SCREAMING_SNAKE_CASE__ , strict=SCREAMING_SNAKE_CASE__ )
def UpperCamelCase_ ( __a , __a , __a , __a = False , __a = False , ) -> Any:
a__ : int = MTaConfig.from_json_file(SCREAMING_SNAKE_CASE__ )
print(f'''Building PyTorch model from configuration: {config}''' )
# Non-v1.1 checkpoints could also use T5Model, but this works for all.
# The v1.0 checkpoints will simply have an LM head that is the word embeddings.
if is_encoder_only:
a__ : Dict = UMTaEncoderModel(SCREAMING_SNAKE_CASE__ )
else:
a__ : str = UMTaForConditionalGeneration(SCREAMING_SNAKE_CASE__ )
# Load weights from tf checkpoint
load_tax_weights_in_ta(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
# Save pytorch-model
print(f'''Save PyTorch model to {pytorch_dump_path}''' )
model.save_pretrained(SCREAMING_SNAKE_CASE__ )
# Verify that we can load the checkpoint.
model.from_pretrained(SCREAMING_SNAKE_CASE__ )
print("Done" )
if __name__ == "__main__":
UpperCamelCase : str = argparse.ArgumentParser(description="""Converts a native T5X checkpoint into a PyTorch checkpoint.""")
# Required parameters
parser.add_argument(
"""--t5x_checkpoint_path""", default=None, type=str, required=True, help="""Path to the T5X checkpoint."""
)
parser.add_argument(
"""--config_file""",
default=None,
type=str,
required=True,
help="""The config json file corresponding to the pre-trained T5 model.\nThis specifies the model architecture.""",
)
parser.add_argument(
"""--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model."""
)
parser.add_argument(
"""--is_encoder_only""", action="""store_true""", help="""Check if the model is encoder-decoder model""", default=False
)
parser.add_argument(
"""--scalable_attention""",
action="""store_true""",
help="""Whether the model uses scaled attention (umt5 model)""",
default=False,
)
UpperCamelCase : Any = parser.parse_args()
convert_tax_checkpoint_to_pytorch(
args.tax_checkpoint_path,
args.config_file,
args.pytorch_dump_path,
args.is_encoder_only,
args.scalable_attention,
)
| 37 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available
__snake_case = {
"""configuration_groupvit""": [
"""GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP""",
"""GroupViTConfig""",
"""GroupViTOnnxConfig""",
"""GroupViTTextConfig""",
"""GroupViTVisionConfig""",
],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__snake_case = [
"""GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""GroupViTModel""",
"""GroupViTPreTrainedModel""",
"""GroupViTTextModel""",
"""GroupViTVisionModel""",
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__snake_case = [
"""TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""TFGroupViTModel""",
"""TFGroupViTPreTrainedModel""",
"""TFGroupViTTextModel""",
"""TFGroupViTVisionModel""",
]
if TYPE_CHECKING:
from .configuration_groupvit import (
GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP,
GroupViTConfig,
GroupViTOnnxConfig,
GroupViTTextConfig,
GroupViTVisionConfig,
)
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_groupvit import (
GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST,
GroupViTModel,
GroupViTPreTrainedModel,
GroupViTTextModel,
GroupViTVisionModel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_groupvit import (
TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST,
TFGroupViTModel,
TFGroupViTPreTrainedModel,
TFGroupViTTextModel,
TFGroupViTVisionModel,
)
else:
import sys
__snake_case = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 658 | 0 |
import os
import time
import warnings
from dataclasses import dataclass, field
from enum import Enum
from typing import List, Optional, Union
import torch
from filelock import FileLock
from torch.utils.data import Dataset
from ...tokenization_utils_base import PreTrainedTokenizerBase
from ...utils import logging
from ..processors.glue import glue_convert_examples_to_features, glue_output_modes, glue_processors
from ..processors.utils import InputFeatures
a__ = logging.get_logger(__name__)
@dataclass
class SCREAMING_SNAKE_CASE_ :
"""simple docstring"""
__magic_name__ : str = field(metadata={'help': 'The name of the task to train on: ' + ', '.join(glue_processors.keys() )} )
__magic_name__ : str = field(
metadata={'help': 'The input data dir. Should contain the .tsv files (or other data files) for the task.'} )
__magic_name__ : int = field(
default=128 , metadata={
'help': (
'The maximum total input sequence length after tokenization. Sequences longer '
'than this will be truncated, sequences shorter will be padded.'
)
} , )
__magic_name__ : bool = field(
default=_UpperCamelCase , metadata={'help': 'Overwrite the cached training and evaluation sets'} )
def lowerCamelCase__ ( self : Tuple ) -> Optional[int]:
"""simple docstring"""
__UpperCamelCase : List[str] = self.task_name.lower()
class SCREAMING_SNAKE_CASE_ ( _UpperCamelCase ):
"""simple docstring"""
__magic_name__ : str = 'train'
__magic_name__ : Tuple = 'dev'
__magic_name__ : int = 'test'
class SCREAMING_SNAKE_CASE_ ( _UpperCamelCase ):
"""simple docstring"""
__magic_name__ : GlueDataTrainingArguments
__magic_name__ : str
__magic_name__ : List[InputFeatures]
def __init__( self : Tuple , lowerCAmelCase : Optional[int] , lowerCAmelCase : Tuple , lowerCAmelCase : Dict = None , lowerCAmelCase : str = Split.train , lowerCAmelCase : List[Any] = None , ) -> List[Any]:
"""simple docstring"""
warnings.warn(
"""This dataset will be removed from the library soon, preprocessing should be handled with the 🤗 Datasets """
"""library. You can have a look at this example script for pointers: """
"""https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py""" , SCREAMING_SNAKE_CASE_ , )
__UpperCamelCase : Any = args
__UpperCamelCase : Optional[Any] = glue_processors[args.task_name]()
__UpperCamelCase : List[str] = glue_output_modes[args.task_name]
if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ):
try:
__UpperCamelCase : Union[str, Any] = Split[mode]
except KeyError:
raise KeyError("""mode is not a valid split name""" )
# Load data features from cache or dataset file
__UpperCamelCase : Union[str, Any] = os.path.join(
cache_dir if cache_dir is not None else args.data_dir , F'''cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{args.task_name}''' , )
__UpperCamelCase : List[str] = self.processor.get_labels()
if args.task_name in ["mnli", "mnli-mm"] and tokenizer.__class__.__name__ in (
"RobertaTokenizer",
"RobertaTokenizerFast",
"XLMRobertaTokenizer",
"BartTokenizer",
"BartTokenizerFast",
):
# HACK(label indices are swapped in RoBERTa pretrained model)
__UpperCamelCase : int = label_list[2], label_list[1]
__UpperCamelCase : Union[str, Any] = label_list
# Make sure only the first process in distributed training processes the dataset,
# and the others will use the cache.
__UpperCamelCase : Optional[Any] = cached_features_file + '''.lock'''
with FileLock(SCREAMING_SNAKE_CASE_ ):
if os.path.exists(SCREAMING_SNAKE_CASE_ ) and not args.overwrite_cache:
__UpperCamelCase : Union[str, Any] = time.time()
__UpperCamelCase : Union[str, Any] = torch.load(SCREAMING_SNAKE_CASE_ )
logger.info(
F'''Loading features from cached file {cached_features_file} [took %.3f s]''' , time.time() - start )
else:
logger.info(F'''Creating features from dataset file at {args.data_dir}''' )
if mode == Split.dev:
__UpperCamelCase : Tuple = self.processor.get_dev_examples(args.data_dir )
elif mode == Split.test:
__UpperCamelCase : Optional[Any] = self.processor.get_test_examples(args.data_dir )
else:
__UpperCamelCase : List[str] = self.processor.get_train_examples(args.data_dir )
if limit_length is not None:
__UpperCamelCase : Tuple = examples[:limit_length]
__UpperCamelCase : Dict = glue_convert_examples_to_features(
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , max_length=args.max_seq_length , label_list=SCREAMING_SNAKE_CASE_ , output_mode=self.output_mode , )
__UpperCamelCase : List[Any] = time.time()
torch.save(self.features , SCREAMING_SNAKE_CASE_ )
# ^ This seems to take a lot of time so I want to investigate why and how we can improve.
logger.info(
F'''Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]''' )
def __len__( self : Optional[Any] ) -> List[str]:
"""simple docstring"""
return len(self.features )
def __getitem__( self : List[Any] , lowerCAmelCase : List[str] ) -> InputFeatures:
"""simple docstring"""
return self.features[i]
def lowerCamelCase__ ( self : List[Any] ) -> Union[str, Any]:
"""simple docstring"""
return self.label_list
| 279 |
import unittest
from pathlib import Path
from tempfile import NamedTemporaryFile, TemporaryDirectory
from transformers import BertConfig, BertTokenizerFast, FeatureExtractionPipeline
from transformers.convert_graph_to_onnx import (
convert,
ensure_valid_input,
generate_identified_filename,
infer_shapes,
quantize,
)
from transformers.testing_utils import require_tf, require_tokenizers, require_torch, slow
class UpperCAmelCase_ :
"""simple docstring"""
def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> List[str]:
return None
class UpperCAmelCase_ :
"""simple docstring"""
def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Tuple:
return None
class UpperCAmelCase_ ( unittest.TestCase ):
"""simple docstring"""
UpperCamelCase_ : Any =[
# (model_name, model_kwargs)
('bert-base-cased', {}),
('gpt2', {'use_cache': False}), # We don't support exporting GPT2 past keys anymore
]
@require_tf
@slow
def UpperCAmelCase ( self ) -> List[Any]:
for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
self._test_export(SCREAMING_SNAKE_CASE_ , '''tf''' , 12 , **SCREAMING_SNAKE_CASE_ )
@require_torch
@slow
def UpperCAmelCase ( self ) -> Optional[int]:
for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
self._test_export(SCREAMING_SNAKE_CASE_ , '''pt''' , 12 , **SCREAMING_SNAKE_CASE_ )
@require_torch
@slow
def UpperCAmelCase ( self ) -> int:
from transformers import BertModel
UpperCamelCase :int = ['''[UNK]''', '''[SEP]''', '''[CLS]''', '''[PAD]''', '''[MASK]''', '''some''', '''other''', '''words''']
with NamedTemporaryFile(mode='''w+t''' ) as vocab_file:
vocab_file.write('''\n'''.join(SCREAMING_SNAKE_CASE_ ) )
vocab_file.flush()
UpperCamelCase :Tuple = BertTokenizerFast(vocab_file.name )
with TemporaryDirectory() as bert_save_dir:
UpperCamelCase :Union[str, Any] = BertModel(BertConfig(vocab_size=len(SCREAMING_SNAKE_CASE_ ) ) )
model.save_pretrained(SCREAMING_SNAKE_CASE_ )
self._test_export(SCREAMING_SNAKE_CASE_ , '''pt''' , 12 , SCREAMING_SNAKE_CASE_ )
@require_tf
@slow
def UpperCAmelCase ( self ) -> str:
for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
UpperCamelCase :Tuple = self._test_export(SCREAMING_SNAKE_CASE_ , '''tf''' , 12 , **SCREAMING_SNAKE_CASE_ )
UpperCamelCase :List[Any] = quantize(Path(SCREAMING_SNAKE_CASE_ ) )
# Ensure the actual quantized model is not bigger than the original one
if quantized_path.stat().st_size >= Path(SCREAMING_SNAKE_CASE_ ).stat().st_size:
self.fail('''Quantized model is bigger than initial ONNX model''' )
@require_torch
@slow
def UpperCAmelCase ( self ) -> Optional[Any]:
for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
UpperCamelCase :str = self._test_export(SCREAMING_SNAKE_CASE_ , '''pt''' , 12 , **SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Any = quantize(SCREAMING_SNAKE_CASE_ )
# Ensure the actual quantized model is not bigger than the original one
if quantized_path.stat().st_size >= Path(SCREAMING_SNAKE_CASE_ ).stat().st_size:
self.fail('''Quantized model is bigger than initial ONNX model''' )
def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ ) -> Optional[Any]:
try:
# Compute path
with TemporaryDirectory() as tempdir:
UpperCamelCase :Union[str, Any] = Path(SCREAMING_SNAKE_CASE_ ).joinpath('''model.onnx''' )
# Remove folder if exists
if path.parent.exists():
path.parent.rmdir()
# Export
convert(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
return path
except Exception as e:
self.fail(SCREAMING_SNAKE_CASE_ )
@require_torch
@require_tokenizers
@slow
def UpperCAmelCase ( self ) -> List[str]:
from transformers import BertModel
UpperCamelCase :List[Any] = BertModel(BertConfig.from_pretrained('''lysandre/tiny-bert-random''' ) )
UpperCamelCase :int = BertTokenizerFast.from_pretrained('''lysandre/tiny-bert-random''' )
self._test_infer_dynamic_axis(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , '''pt''' )
@require_tf
@require_tokenizers
@slow
def UpperCAmelCase ( self ) -> List[Any]:
from transformers import TFBertModel
UpperCamelCase :Optional[Any] = TFBertModel(BertConfig.from_pretrained('''lysandre/tiny-bert-random''' ) )
UpperCamelCase :Optional[Any] = BertTokenizerFast.from_pretrained('''lysandre/tiny-bert-random''' )
self._test_infer_dynamic_axis(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , '''tf''' )
def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]:
UpperCamelCase :Tuple = FeatureExtractionPipeline(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Any = ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''output_0''', '''output_1''']
UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :List[Any] = infer_shapes(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# Assert all variables are present
self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , len(SCREAMING_SNAKE_CASE_ ) )
self.assertTrue(all(var_name in shapes for var_name in variable_names ) )
self.assertSequenceEqual(variable_names[:3] , SCREAMING_SNAKE_CASE_ )
self.assertSequenceEqual(variable_names[3:] , SCREAMING_SNAKE_CASE_ )
# Assert inputs are {0: batch, 1: sequence}
for var_name in ["input_ids", "token_type_ids", "attention_mask"]:
self.assertDictEqual(shapes[var_name] , {0: '''batch''', 1: '''sequence'''} )
# Assert outputs are {0: batch, 1: sequence} and {0: batch}
self.assertDictEqual(shapes['''output_0'''] , {0: '''batch''', 1: '''sequence'''} )
self.assertDictEqual(shapes['''output_1'''] , {0: '''batch'''} )
def UpperCAmelCase ( self ) -> int:
UpperCamelCase :int = ['''input_ids''', '''attention_mask''', '''token_type_ids''']
UpperCamelCase :Tuple = {'''input_ids''': [1, 2, 3, 4], '''attention_mask''': [0, 0, 0, 0], '''token_type_ids''': [1, 1, 1, 1]}
UpperCamelCase , UpperCamelCase :Any = ensure_valid_input(FuncContiguousArgs() , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# Should have exactly the same number of args (all are valid)
self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 3 )
# Should have exactly the same input names
self.assertEqual(set(SCREAMING_SNAKE_CASE_ ) , set(SCREAMING_SNAKE_CASE_ ) )
# Parameter should be reordered according to their respective place in the function:
# (input_ids, token_type_ids, attention_mask)
self.assertEqual(SCREAMING_SNAKE_CASE_ , (tokens['''input_ids'''], tokens['''token_type_ids'''], tokens['''attention_mask''']) )
# Generated args are interleaved with another args (for instance parameter "past" in GPT2)
UpperCamelCase , UpperCamelCase :Tuple = ensure_valid_input(FuncNonContiguousArgs() , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# Should have exactly the one arg (all before the one not provided "some_other_args")
self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 1 )
self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 1 )
# Should have only "input_ids"
self.assertEqual(inputs_args[0] , tokens['''input_ids'''] )
self.assertEqual(ordered_input_names[0] , '''input_ids''' )
def UpperCAmelCase ( self ) -> Union[str, Any]:
UpperCamelCase :str = generate_identified_filename(Path('''/home/something/my_fake_model.onnx''' ) , '''-test''' )
self.assertEqual('''/home/something/my_fake_model-test.onnx''' , generated.as_posix() )
| 658 | 0 |
import copy
from typing import Any, Dict, List, Optional, Union
import numpy as np
import torch
from ...audio_utils import mel_filter_bank, spectrogram, window_function
from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
from ...feature_extraction_utils import BatchFeature
from ...utils import TensorType, logging
a_ : List[str] = logging.get_logger(__name__)
class lowerCamelCase__ ( UpperCAmelCase_):
"""simple docstring"""
_A = ['input_features', 'is_longer']
def __init__(self , __a=64 , __a=4_80_00 , __a=4_80 , __a=10 , __a=10_24 , __a=0.0 , __a=False , __a = 0 , __a = 1_40_00 , __a = None , __a = "fusion" , __a = "repeatpad" , **__a , ):
'''simple docstring'''
super().__init__(
feature_size=SCREAMING_SNAKE_CASE_ , sampling_rate=SCREAMING_SNAKE_CASE_ , padding_value=SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , )
lowerCamelCase = top_db
lowerCamelCase = truncation
lowerCamelCase = padding
lowerCamelCase = fft_window_size
lowerCamelCase = (fft_window_size >> 1) + 1
lowerCamelCase = hop_length
lowerCamelCase = max_length_s
lowerCamelCase = max_length_s * sampling_rate
lowerCamelCase = sampling_rate
lowerCamelCase = frequency_min
lowerCamelCase = frequency_max
lowerCamelCase = mel_filter_bank(
num_frequency_bins=self.nb_frequency_bins , num_mel_filters=SCREAMING_SNAKE_CASE_ , min_frequency=SCREAMING_SNAKE_CASE_ , max_frequency=SCREAMING_SNAKE_CASE_ , sampling_rate=SCREAMING_SNAKE_CASE_ , norm=SCREAMING_SNAKE_CASE_ , mel_scale="htk" , )
lowerCamelCase = mel_filter_bank(
num_frequency_bins=self.nb_frequency_bins , num_mel_filters=SCREAMING_SNAKE_CASE_ , min_frequency=SCREAMING_SNAKE_CASE_ , max_frequency=SCREAMING_SNAKE_CASE_ , sampling_rate=SCREAMING_SNAKE_CASE_ , norm="slaney" , mel_scale="slaney" , )
def _a (self ):
'''simple docstring'''
lowerCamelCase = copy.deepcopy(self.__dict__ )
lowerCamelCase = self.__class__.__name__
if "mel_filters" in output:
del output["mel_filters"]
if "mel_filters_slaney" in output:
del output["mel_filters_slaney"]
return output
def _a (self , __a , __a = None ):
'''simple docstring'''
lowerCamelCase = spectrogram(
SCREAMING_SNAKE_CASE_ , window_function(self.fft_window_size , "hann" ) , frame_length=self.fft_window_size , hop_length=self.hop_length , power=2.0 , mel_filters=SCREAMING_SNAKE_CASE_ , log_mel="dB" , )
return log_mel_spectrogram.T
def _a (self , __a , __a , __a ):
'''simple docstring'''
lowerCamelCase = np.array_split(list(range(0 , total_frames - chunk_frames + 1 ) ) , 3 )
if len(ranges[1] ) == 0:
# if the audio is too short, we just use the first chunk
lowerCamelCase = [0]
if len(ranges[2] ) == 0:
# if the audio is too short, we just use the first chunk
lowerCamelCase = [0]
# randomly choose index for each part
lowerCamelCase = np.random.choice(ranges[0] )
lowerCamelCase = np.random.choice(ranges[1] )
lowerCamelCase = np.random.choice(ranges[2] )
lowerCamelCase = mel[idx_front : idx_front + chunk_frames, :]
lowerCamelCase = mel[idx_middle : idx_middle + chunk_frames, :]
lowerCamelCase = mel[idx_back : idx_back + chunk_frames, :]
lowerCamelCase = torch.tensor(mel[None, None, :] )
lowerCamelCase = torch.nn.functional.interpolate(
SCREAMING_SNAKE_CASE_ , size=[chunk_frames, 64] , mode="bilinear" , align_corners=SCREAMING_SNAKE_CASE_ )
lowerCamelCase = mel_shrink[0][0].numpy()
lowerCamelCase = np.stack([mel_shrink, mel_chunk_front, mel_chunk_middle, mel_chunk_back] , axis=0 )
return mel_fusion
def _a (self , __a , __a , __a , __a ):
'''simple docstring'''
if waveform.shape[0] > max_length:
if truncation == "rand_trunc":
lowerCamelCase = True
# random crop to max_length (for compatibility) -> this should be handled by self.pad
lowerCamelCase = len(SCREAMING_SNAKE_CASE_ ) - max_length
lowerCamelCase = np.random.randint(0 , overflow + 1 )
lowerCamelCase = waveform[idx : idx + max_length]
lowerCamelCase = self._np_extract_fbank_features(SCREAMING_SNAKE_CASE_ , self.mel_filters_slaney )[None, :]
elif truncation == "fusion":
lowerCamelCase = self._np_extract_fbank_features(SCREAMING_SNAKE_CASE_ , self.mel_filters )
lowerCamelCase = max_length // self.hop_length + 1 # the +1 related to how the spectrogram is computed
lowerCamelCase = mel.shape[0]
if chunk_frames == total_frames:
# there is a corner case where the audio length is larger than max_length but smaller than max_length+hop_length.
# In this case, we just use the whole audio.
lowerCamelCase = np.stack([mel, mel, mel, mel] , axis=0 )
lowerCamelCase = False
else:
lowerCamelCase = self._random_mel_fusion(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
lowerCamelCase = True
else:
raise NotImplementedError(F"""data_truncating {truncation} not implemented""" )
else:
lowerCamelCase = False
# only use repeat as a new possible value for padding. you repeat the audio before applying the usual max_length padding
if waveform.shape[0] < max_length:
if padding == "repeat":
lowerCamelCase = int(max_length / len(SCREAMING_SNAKE_CASE_ ) )
lowerCamelCase = np.stack(np.tile(SCREAMING_SNAKE_CASE_ , n_repeat + 1 ) )[:max_length]
if padding == "repeatpad":
lowerCamelCase = int(max_length / len(SCREAMING_SNAKE_CASE_ ) )
lowerCamelCase = np.stack(np.tile(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) )
lowerCamelCase = np.pad(SCREAMING_SNAKE_CASE_ , (0, max_length - waveform.shape[0]) , mode="constant" , constant_values=0 )
if truncation == "fusion":
lowerCamelCase = self._np_extract_fbank_features(SCREAMING_SNAKE_CASE_ , self.mel_filters )
lowerCamelCase = np.stack([input_mel, input_mel, input_mel, input_mel] , axis=0 )
else:
lowerCamelCase = self._np_extract_fbank_features(SCREAMING_SNAKE_CASE_ , self.mel_filters_slaney )[None, :]
return input_mel, longer
def __call__(self , __a , __a = None , __a = None , __a = None , __a = None , __a = None , **__a , ):
'''simple docstring'''
lowerCamelCase = truncation if truncation is not None else self.truncation
lowerCamelCase = padding if padding else self.padding
if sampling_rate is not None:
if sampling_rate != self.sampling_rate:
raise ValueError(
F"""The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a"""
F""" sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input"""
F""" was sampled with {self.sampling_rate} and not {sampling_rate}.""" )
else:
logger.warning(
"It is strongly recommended to pass the `sampling_rate` argument to this function. "
"Failing to do so can result in silent errors that might be hard to debug." )
lowerCamelCase = isinstance(SCREAMING_SNAKE_CASE_ , np.ndarray ) and len(raw_speech.shape ) > 1
if is_batched_numpy and len(raw_speech.shape ) > 2:
raise ValueError(F"""Only mono-channel audio is supported for input to {self}""" )
lowerCamelCase = is_batched_numpy or (
isinstance(SCREAMING_SNAKE_CASE_ , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) ))
)
if is_batched:
lowerCamelCase = [np.asarray(SCREAMING_SNAKE_CASE_ , dtype=np.floataa ) for speech in raw_speech]
elif not is_batched and not isinstance(SCREAMING_SNAKE_CASE_ , np.ndarray ):
lowerCamelCase = np.asarray(SCREAMING_SNAKE_CASE_ , dtype=np.floataa )
elif isinstance(SCREAMING_SNAKE_CASE_ , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ):
lowerCamelCase = raw_speech.astype(np.floataa )
# always return batch
if not is_batched:
lowerCamelCase = [np.asarray(SCREAMING_SNAKE_CASE_ )]
# convert to mel spectrogram, truncate and pad if needed.
lowerCamelCase = [
self._get_input_mel(SCREAMING_SNAKE_CASE_ , max_length if max_length else self.nb_max_samples , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
for waveform in raw_speech
]
lowerCamelCase = []
lowerCamelCase = []
for mel, longer in padded_inputs:
input_mel.append(SCREAMING_SNAKE_CASE_ )
is_longer.append(SCREAMING_SNAKE_CASE_ )
if truncation == "fusion" and sum(SCREAMING_SNAKE_CASE_ ) == 0:
# if no audio is longer than 10s, then randomly select one audio to be longer
lowerCamelCase = np.random.randint(0 , len(SCREAMING_SNAKE_CASE_ ) )
lowerCamelCase = True
if isinstance(input_mel[0] , SCREAMING_SNAKE_CASE_ ):
lowerCamelCase = [np.asarray(SCREAMING_SNAKE_CASE_ , dtype=np.floataa ) for feature in input_mel]
# is_longer is a list of bool
lowerCamelCase = [[longer] for longer in is_longer]
lowerCamelCase = {'''input_features''': input_mel, '''is_longer''': is_longer}
lowerCamelCase = BatchFeature(SCREAMING_SNAKE_CASE_ )
if return_tensors is not None:
lowerCamelCase = input_features.convert_to_tensors(SCREAMING_SNAKE_CASE_ )
return input_features | 623 |
import os
import shutil
import tempfile
from unittest import TestCase
from unittest.mock import patch
import numpy as np
from datasets import Dataset
from transformers.models.realm.configuration_realm import RealmConfig
from transformers.models.realm.retrieval_realm import _REALM_BLOCK_RECORDS_FILENAME, RealmRetriever
from transformers.models.realm.tokenization_realm import VOCAB_FILES_NAMES, RealmTokenizer
class UpperCAmelCase_ ( lowercase ):
"""simple docstring"""
def UpperCAmelCase ( self ) -> Tuple:
UpperCamelCase :Union[str, Any] = tempfile.mkdtemp()
UpperCamelCase :List[str] = 5
# Realm tok
UpperCamelCase :List[Any] = [
'''[UNK]''',
'''[CLS]''',
'''[SEP]''',
'''[PAD]''',
'''[MASK]''',
'''test''',
'''question''',
'''this''',
'''is''',
'''the''',
'''first''',
'''second''',
'''third''',
'''fourth''',
'''fifth''',
'''record''',
'''want''',
'''##want''',
'''##ed''',
'''wa''',
'''un''',
'''runn''',
'''##ing''',
''',''',
'''low''',
'''lowest''',
]
UpperCamelCase :Dict = os.path.join(self.tmpdirname , '''realm_tokenizer''' )
os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Union[str, Any] = os.path.join(SCREAMING_SNAKE_CASE_ , VOCAB_FILES_NAMES['''vocab_file'''] )
with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer:
vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) )
UpperCamelCase :Any = os.path.join(self.tmpdirname , '''realm_block_records''' )
os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self ) -> RealmTokenizer:
return RealmTokenizer.from_pretrained(os.path.join(self.tmpdirname , '''realm_tokenizer''' ) )
def UpperCAmelCase ( self ) -> List[Any]:
shutil.rmtree(self.tmpdirname )
def UpperCAmelCase ( self ) -> str:
UpperCamelCase :Union[str, Any] = RealmConfig(num_block_records=self.num_block_records )
return config
def UpperCAmelCase ( self ) -> List[str]:
UpperCamelCase :Tuple = Dataset.from_dict(
{
'''id''': ['''0''', '''1'''],
'''question''': ['''foo''', '''bar'''],
'''answers''': [['''Foo''', '''Bar'''], ['''Bar''']],
} )
return dataset
def UpperCAmelCase ( self ) -> str:
UpperCamelCase :Optional[Any] = np.array(
[
b'''This is the first record''',
b'''This is the second record''',
b'''This is the third record''',
b'''This is the fourth record''',
b'''This is the fifth record''',
b'''This is a longer longer longer record''',
] , dtype=SCREAMING_SNAKE_CASE_ , )
return block_records
def UpperCAmelCase ( self ) -> Union[str, Any]:
UpperCamelCase :Optional[int] = RealmRetriever(
block_records=self.get_dummy_block_records() , tokenizer=self.get_tokenizer() , )
return retriever
def UpperCAmelCase ( self ) -> Tuple:
UpperCamelCase :Optional[Any] = self.get_config()
UpperCamelCase :str = self.get_dummy_retriever()
UpperCamelCase :int = retriever.tokenizer
UpperCamelCase :Optional[Any] = np.array([0, 3] , dtype='''long''' )
UpperCamelCase :Optional[Any] = tokenizer(['''Test question'''] ).input_ids
UpperCamelCase :Tuple = tokenizer(
['''the fourth'''] , add_special_tokens=SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , ).input_ids
UpperCamelCase :Optional[Any] = config.reader_seq_len
UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :str = retriever(
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , answer_ids=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , return_tensors='''np''' )
self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 2 )
self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 2 )
self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 2 )
self.assertEqual(concat_inputs.input_ids.shape , (2, 10) )
self.assertEqual(concat_inputs.attention_mask.shape , (2, 10) )
self.assertEqual(concat_inputs.token_type_ids.shape , (2, 10) )
self.assertEqual(concat_inputs.special_tokens_mask.shape , (2, 10) )
self.assertEqual(
tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[0] ) , ['''[CLS]''', '''test''', '''question''', '''[SEP]''', '''this''', '''is''', '''the''', '''first''', '''record''', '''[SEP]'''] , )
self.assertEqual(
tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[1] ) , ['''[CLS]''', '''test''', '''question''', '''[SEP]''', '''this''', '''is''', '''the''', '''fourth''', '''record''', '''[SEP]'''] , )
def UpperCAmelCase ( self ) -> int:
UpperCamelCase :Union[str, Any] = self.get_config()
UpperCamelCase :Union[str, Any] = self.get_dummy_retriever()
UpperCamelCase :Dict = retriever.tokenizer
UpperCamelCase :str = np.array([0, 3, 5] , dtype='''long''' )
UpperCamelCase :List[str] = tokenizer(['''Test question'''] ).input_ids
UpperCamelCase :Optional[Any] = tokenizer(
['''the fourth''', '''longer longer'''] , add_special_tokens=SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , ).input_ids
UpperCamelCase :Any = config.reader_seq_len
UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :Any = retriever(
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , answer_ids=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , return_tensors='''np''' )
self.assertEqual([False, True, True] , SCREAMING_SNAKE_CASE_ )
self.assertEqual([[-1, -1, -1], [6, -1, -1], [6, 7, 8]] , SCREAMING_SNAKE_CASE_ )
self.assertEqual([[-1, -1, -1], [7, -1, -1], [7, 8, 9]] , SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self ) -> Optional[Any]:
UpperCamelCase :str = self.get_dummy_retriever()
retriever.save_pretrained(os.path.join(self.tmpdirname , '''realm_block_records''' ) )
# Test local path
UpperCamelCase :List[str] = retriever.from_pretrained(os.path.join(self.tmpdirname , '''realm_block_records''' ) )
self.assertEqual(retriever.block_records[0] , b'''This is the first record''' )
# Test mocked remote path
with patch('''transformers.models.realm.retrieval_realm.hf_hub_download''' ) as mock_hf_hub_download:
UpperCamelCase :Tuple = os.path.join(
os.path.join(self.tmpdirname , '''realm_block_records''' ) , _REALM_BLOCK_RECORDS_FILENAME )
UpperCamelCase :List[Any] = RealmRetriever.from_pretrained('''google/realm-cc-news-pretrained-openqa''' )
self.assertEqual(retriever.block_records[0] , b'''This is the first record''' )
| 658 | 0 |
'''simple docstring'''
import numpy as np
from cva import COLOR_BGR2GRAY, CV_8UC3, cvtColor, filteraD, imread, imshow, waitKey
def __UpperCAmelCase ( SCREAMING_SNAKE_CASE__: int, SCREAMING_SNAKE_CASE__: int, SCREAMING_SNAKE_CASE__: int, SCREAMING_SNAKE_CASE__: int, SCREAMING_SNAKE_CASE__: int, SCREAMING_SNAKE_CASE__: int ) -> Dict:
"""simple docstring"""
# prepare kernel
# the kernel size have to be odd
if (ksize % 2) == 0:
__a = ksize + 1
__a = np.zeros((ksize, ksize), dtype=np.floataa )
# each value
for y in range(SCREAMING_SNAKE_CASE__ ):
for x in range(SCREAMING_SNAKE_CASE__ ):
# distance from center
__a = x - ksize // 2
__a = y - ksize // 2
# degree to radiant
__a = theta / 180 * np.pi
__a = np.cos(_theta )
__a = np.sin(_theta )
# get kernel x
__a = cos_theta * px + sin_theta * py
# get kernel y
__a = -sin_theta * px + cos_theta * py
# fill kernel
__a = np.exp(
-(_x**2 + gamma**2 * _y**2) / (2 * sigma**2) ) * np.cos(2 * np.pi * _x / lambd + psi )
return gabor
if __name__ == "__main__":
import doctest
doctest.testmod()
# read original image
__UpperCamelCase : Union[str, Any] = imread("""../image_data/lena.jpg""")
# turn image in gray scale value
__UpperCamelCase : List[str] = cvtColor(img, COLOR_BGR2GRAY)
# Apply multiple Kernel to detect edges
__UpperCamelCase : List[Any] = np.zeros(gray.shape[:2])
for theta in [0, 30, 60, 90, 120, 150]:
__UpperCamelCase : List[Any] = gabor_filter_kernel(10, 8, theta, 10, 0, 0)
out += filteraD(gray, CV_8UC3, kernel_aa)
__UpperCamelCase : Any = out / out.max() * 255
__UpperCamelCase : Any = out.astype(np.uinta)
imshow("""Original""", gray)
imshow("""Gabor filter with 20x20 mask and 6 directions""", out)
waitKey(0) | 448 |
import inspect
import unittest
from huggingface_hub import hf_hub_download
from transformers import ASTConfig
from transformers.testing_utils import require_torch, require_torchaudio, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_torchaudio_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from torch import nn
from transformers import ASTForAudioClassification, ASTModel
from transformers.models.audio_spectrogram_transformer.modeling_audio_spectrogram_transformer import (
AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
)
if is_torchaudio_available():
import torchaudio
from transformers import ASTFeatureExtractor
class UpperCAmelCase_ :
"""simple docstring"""
def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=24 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=37 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=10 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=2 , ) -> Optional[Any]:
UpperCamelCase :int = parent
UpperCamelCase :List[Any] = batch_size
UpperCamelCase :List[Any] = patch_size
UpperCamelCase :Optional[int] = max_length
UpperCamelCase :Union[str, Any] = num_mel_bins
UpperCamelCase :Optional[int] = is_training
UpperCamelCase :Dict = use_labels
UpperCamelCase :Dict = hidden_size
UpperCamelCase :Optional[int] = num_hidden_layers
UpperCamelCase :str = num_attention_heads
UpperCamelCase :Optional[int] = intermediate_size
UpperCamelCase :List[str] = hidden_act
UpperCamelCase :List[str] = hidden_dropout_prob
UpperCamelCase :List[Any] = attention_probs_dropout_prob
UpperCamelCase :str = type_sequence_label_size
UpperCamelCase :List[Any] = initializer_range
UpperCamelCase :Union[str, Any] = scope
UpperCamelCase :List[Any] = frequency_stride
UpperCamelCase :Tuple = time_stride
# in AST, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens)
UpperCamelCase :List[Any] = (self.num_mel_bins - self.patch_size) // self.frequency_stride + 1
UpperCamelCase :List[str] = (self.max_length - self.patch_size) // self.time_stride + 1
UpperCamelCase :Tuple = frequency_out_dimension * time_out_dimension
UpperCamelCase :Optional[int] = num_patches + 2
def UpperCAmelCase ( self ) -> Any:
UpperCamelCase :Tuple = floats_tensor([self.batch_size, self.max_length, self.num_mel_bins] )
UpperCamelCase :Tuple = None
if self.use_labels:
UpperCamelCase :List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size )
UpperCamelCase :str = self.get_config()
return config, input_values, labels
def UpperCAmelCase ( self ) -> List[Any]:
return ASTConfig(
patch_size=self.patch_size , max_length=self.max_length , num_mel_bins=self.num_mel_bins , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=SCREAMING_SNAKE_CASE_ , initializer_range=self.initializer_range , frequency_stride=self.frequency_stride , time_stride=self.time_stride , )
def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Optional[int]:
UpperCamelCase :Optional[Any] = ASTModel(config=SCREAMING_SNAKE_CASE_ )
model.to(SCREAMING_SNAKE_CASE_ )
model.eval()
UpperCamelCase :Tuple = model(SCREAMING_SNAKE_CASE_ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def UpperCAmelCase ( self ) -> Dict:
UpperCamelCase :List[Any] = self.prepare_config_and_inputs()
(
(
UpperCamelCase
) , (
UpperCamelCase
) , (
UpperCamelCase
) ,
) :Union[str, Any] = config_and_inputs
UpperCamelCase :List[Any] = {'''input_values''': input_values}
return config, inputs_dict
@require_torch
class UpperCAmelCase_ ( lowercase, lowercase, unittest.TestCase ):
"""simple docstring"""
UpperCamelCase_ : Optional[int] =(
(
ASTModel,
ASTForAudioClassification,
)
if is_torch_available()
else ()
)
UpperCamelCase_ : Any =(
{'audio-classification': ASTForAudioClassification, 'feature-extraction': ASTModel}
if is_torch_available()
else {}
)
UpperCamelCase_ : Optional[int] =False
UpperCamelCase_ : List[Any] =False
UpperCamelCase_ : Optional[Any] =False
UpperCamelCase_ : Dict =False
def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> List[str]:
if pipeline_test_casse_name == "AudioClassificationPipelineTests":
return True
return False
def UpperCAmelCase ( self ) -> Dict:
UpperCamelCase :List[Any] = ASTModelTester(self )
UpperCamelCase :Dict = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , has_text_modality=SCREAMING_SNAKE_CASE_ , hidden_size=37 )
def UpperCAmelCase ( self ) -> Any:
self.config_tester.run_common_tests()
@unittest.skip(reason='''AST does not use inputs_embeds''' )
def UpperCAmelCase ( self ) -> str:
pass
def UpperCAmelCase ( self ) -> int:
UpperCamelCase , UpperCamelCase :List[Any] = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
UpperCamelCase :Dict = model_class(SCREAMING_SNAKE_CASE_ )
self.assertIsInstance(model.get_input_embeddings() , (nn.Module) )
UpperCamelCase :Optional[int] = model.get_output_embeddings()
self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE_ , nn.Linear ) )
def UpperCAmelCase ( self ) -> Tuple:
UpperCamelCase , UpperCamelCase :int = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
UpperCamelCase :Dict = model_class(SCREAMING_SNAKE_CASE_ )
UpperCamelCase :List[str] = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
UpperCamelCase :Any = [*signature.parameters.keys()]
UpperCamelCase :Optional[int] = ['''input_values''']
self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self ) -> List[Any]:
UpperCamelCase :Optional[int] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ )
@slow
def UpperCAmelCase ( self ) -> Optional[int]:
for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
UpperCamelCase :Union[str, Any] = ASTModel.from_pretrained(SCREAMING_SNAKE_CASE_ )
self.assertIsNotNone(SCREAMING_SNAKE_CASE_ )
def _A ( ):
UpperCamelCase :Any = hf_hub_download(
repo_id='''nielsr/audio-spectogram-transformer-checkpoint''' , filename='''sample_audio.flac''' , repo_type='''dataset''' )
UpperCamelCase , UpperCamelCase :Any = torchaudio.load(SCREAMING_SNAKE_CASE__ )
return audio, sampling_rate
@require_torch
@require_torchaudio
class UpperCAmelCase_ ( unittest.TestCase ):
"""simple docstring"""
@cached_property
def UpperCAmelCase ( self ) -> Tuple:
return (
ASTFeatureExtractor.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593''' )
if is_torchaudio_available()
else None
)
@slow
def UpperCAmelCase ( self ) -> str:
UpperCamelCase :Union[str, Any] = self.default_feature_extractor
UpperCamelCase :Union[str, Any] = ASTForAudioClassification.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593''' ).to(SCREAMING_SNAKE_CASE_ )
UpperCamelCase :str = self.default_feature_extractor
UpperCamelCase , UpperCamelCase :Dict = prepare_audio()
UpperCamelCase :Dict = audio.squeeze().numpy()
UpperCamelCase :int = feature_extractor(SCREAMING_SNAKE_CASE_ , sampling_rate=SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' ).to(SCREAMING_SNAKE_CASE_ )
# forward pass
with torch.no_grad():
UpperCamelCase :Union[str, Any] = model(**SCREAMING_SNAKE_CASE_ )
# verify the logits
UpperCamelCase :List[Any] = torch.Size((1, 527) )
self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE_ )
UpperCamelCase :int = torch.tensor([-0.8760, -7.0042, -8.6602] ).to(SCREAMING_SNAKE_CASE_ )
self.assertTrue(torch.allclose(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) )
| 658 | 0 |
import enum
import warnings
from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING
from ..utils import add_end_docstrings, is_tf_available
from .base import PIPELINE_INIT_ARGS, Pipeline
if is_tf_available():
import tensorflow as tf
class _A ( enum.Enum ):
lowercase_ : int = 0
lowercase_ : Optional[int] = 1
lowercase_ : Dict = 2
@add_end_docstrings(UpperCAmelCase_ )
class _A ( UpperCAmelCase_ ):
lowercase_ : Optional[Any] = '\n In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The\n voice of Nicholas\'s young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western\n Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision\n and denounces one of the men as a horse thief. Although his father initially slaps him for making such an\n accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of\n the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop,\n begging for his blessing. <eod> </s> <eos>\n '
def __init__( self : Dict , *lowerCamelCase__ : int , **lowerCamelCase__ : Any ):
"""simple docstring"""
super().__init__(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
self.check_model_type(
TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == """tf""" else MODEL_FOR_CAUSAL_LM_MAPPING )
if "prefix" not in self._preprocess_params:
# This is very specific. The logic is quite complex and needs to be done
# as a "default".
# It also defines both some preprocess_kwargs and generate_kwargs
# which is why we cannot put them in their respective methods.
__UpperCamelCase : Dict = None
if self.model.config.prefix is not None:
__UpperCamelCase : List[Any] = self.model.config.prefix
if prefix is None and self.model.__class__.__name__ in [
"XLNetLMHeadModel",
"TransfoXLLMHeadModel",
"TFXLNetLMHeadModel",
"TFTransfoXLLMHeadModel",
]:
# For XLNet and TransformerXL we add an article to the prompt to give more state to the model.
__UpperCamelCase : Optional[int] = self.XL_PREFIX
if prefix is not None:
# Recalculate some generate_kwargs linked to prefix.
__UpperCamelCase : Union[str, Any] = self._sanitize_parameters(prefix=SCREAMING_SNAKE_CASE_ , **self._forward_params )
__UpperCamelCase : Optional[Any] = {**self._preprocess_params, **preprocess_params}
__UpperCamelCase : List[str] = {**self._forward_params, **forward_params}
def a ( self : Dict , lowerCamelCase__ : Optional[int]=None , lowerCamelCase__ : Any=None , lowerCamelCase__ : str=None , lowerCamelCase__ : Any=None , lowerCamelCase__ : int=None , lowerCamelCase__ : Optional[Any]=None , lowerCamelCase__ : int=None , lowerCamelCase__ : Union[str, Any]=None , **lowerCamelCase__ : List[Any] , ):
"""simple docstring"""
__UpperCamelCase : Optional[int] = {}
if prefix is not None:
__UpperCamelCase : Tuple = prefix
if prefix:
__UpperCamelCase : List[Any] = self.tokenizer(
SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , return_tensors=self.framework )
__UpperCamelCase : List[str] = prefix_inputs['''input_ids'''].shape[-1]
if handle_long_generation is not None:
if handle_long_generation not in {"hole"}:
raise ValueError(
f'{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected'
""" [None, \'hole\']""" )
__UpperCamelCase : Any = handle_long_generation
preprocess_params.update(SCREAMING_SNAKE_CASE_ )
__UpperCamelCase : List[str] = generate_kwargs
__UpperCamelCase : int = {}
if return_full_text is not None and return_type is None:
if return_text is not None:
raise ValueError("""`return_text` is mutually exclusive with `return_full_text`""" )
if return_tensors is not None:
raise ValueError("""`return_full_text` is mutually exclusive with `return_tensors`""" )
__UpperCamelCase : Optional[int] = ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT
if return_tensors is not None and return_type is None:
if return_text is not None:
raise ValueError("""`return_text` is mutually exclusive with `return_tensors`""" )
__UpperCamelCase : Tuple = ReturnType.TENSORS
if return_type is not None:
__UpperCamelCase : Any = return_type
if clean_up_tokenization_spaces is not None:
__UpperCamelCase : Optional[int] = clean_up_tokenization_spaces
if stop_sequence is not None:
__UpperCamelCase : Optional[Any] = self.tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ )
if len(SCREAMING_SNAKE_CASE_ ) > 1:
warnings.warn(
"""Stopping on a multiple token sequence is not yet supported on transformers. The first token of"""
""" the stop sequence will be used as the stop sequence string in the interim.""" )
__UpperCamelCase : Any = stop_sequence_ids[0]
return preprocess_params, forward_params, postprocess_params
def a ( self : Dict , *lowerCamelCase__ : Union[str, Any] , **lowerCamelCase__ : int ):
"""simple docstring"""
if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]:
kwargs.update({"""add_space_before_punct_symbol""": True} )
return super()._parse_and_tokenize(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
def __call__( self : List[Any] , lowerCamelCase__ : Optional[int] , **lowerCamelCase__ : Tuple ):
"""simple docstring"""
return super().__call__(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
def a ( self : Dict , lowerCamelCase__ : Tuple , lowerCamelCase__ : Any="" , lowerCamelCase__ : Tuple=None , **lowerCamelCase__ : Optional[Any] ):
"""simple docstring"""
__UpperCamelCase : Union[str, Any] = self.tokenizer(
prefix + prompt_text , padding=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , return_tensors=self.framework )
__UpperCamelCase : Dict = prompt_text
if handle_long_generation == "hole":
__UpperCamelCase : List[Any] = inputs['''input_ids'''].shape[-1]
if "max_new_tokens" in generate_kwargs:
__UpperCamelCase : str = generate_kwargs['''max_new_tokens''']
else:
__UpperCamelCase : Tuple = generate_kwargs.get("""max_length""" , self.model.config.max_length ) - cur_len
if new_tokens < 0:
raise ValueError("""We cannot infer how many new tokens are expected""" )
if cur_len + new_tokens > self.tokenizer.model_max_length:
__UpperCamelCase : Any = self.tokenizer.model_max_length - new_tokens
if keep_length <= 0:
raise ValueError(
"""We cannot use `hole` to handle this generation the number of desired tokens exceeds the"""
""" models max length""" )
__UpperCamelCase : Union[str, Any] = inputs['''input_ids'''][:, -keep_length:]
if "attention_mask" in inputs:
__UpperCamelCase : List[str] = inputs['''attention_mask'''][:, -keep_length:]
return inputs
def a ( self : Optional[int] , lowerCamelCase__ : Optional[Any] , **lowerCamelCase__ : Any ):
"""simple docstring"""
__UpperCamelCase : str = model_inputs['''input_ids''']
__UpperCamelCase : List[Any] = model_inputs.get("""attention_mask""" , SCREAMING_SNAKE_CASE_ )
# Allow empty prompts
if input_ids.shape[1] == 0:
__UpperCamelCase : str = None
__UpperCamelCase : List[Any] = None
__UpperCamelCase : Optional[Any] = 1
else:
__UpperCamelCase : Tuple = input_ids.shape[0]
__UpperCamelCase : List[Any] = model_inputs.pop("""prompt_text""" )
# If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying
# generate_kwargs, as some of the parameterization may come from the initialization of the pipeline.
__UpperCamelCase : int = generate_kwargs.pop("""prefix_length""" , 0 )
if prefix_length > 0:
__UpperCamelCase : Optional[Any] = '''max_new_tokens''' in generate_kwargs or (
'''generation_config''' in generate_kwargs
and generate_kwargs['''generation_config'''].max_new_tokens is not None
)
if not has_max_new_tokens:
__UpperCamelCase : List[str] = generate_kwargs.get("""max_length""" ) or self.model.config.max_length
generate_kwargs["max_length"] += prefix_length
__UpperCamelCase : str = '''min_new_tokens''' in generate_kwargs or (
'''generation_config''' in generate_kwargs
and generate_kwargs['''generation_config'''].min_new_tokens is not None
)
if not has_min_new_tokens and "min_length" in generate_kwargs:
generate_kwargs["min_length"] += prefix_length
# BS x SL
__UpperCamelCase : List[Any] = self.model.generate(input_ids=SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
__UpperCamelCase : Tuple = generated_sequence.shape[0]
if self.framework == "pt":
__UpperCamelCase : List[str] = generated_sequence.reshape(SCREAMING_SNAKE_CASE_ , out_b // in_b , *generated_sequence.shape[1:] )
elif self.framework == "tf":
__UpperCamelCase : List[Any] = tf.reshape(SCREAMING_SNAKE_CASE_ , (in_b, out_b // in_b, *generated_sequence.shape[1:]) )
return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text}
def a ( self : str , lowerCamelCase__ : Dict , lowerCamelCase__ : str=ReturnType.FULL_TEXT , lowerCamelCase__ : int=True ):
"""simple docstring"""
__UpperCamelCase : Dict = model_outputs['''generated_sequence'''][0]
__UpperCamelCase : Tuple = model_outputs['''input_ids''']
__UpperCamelCase : List[str] = model_outputs['''prompt_text''']
__UpperCamelCase : Tuple = generated_sequence.numpy().tolist()
__UpperCamelCase : Tuple = []
for sequence in generated_sequence:
if return_type == ReturnType.TENSORS:
__UpperCamelCase : List[str] = {'''generated_token_ids''': sequence}
elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}:
# Decode text
__UpperCamelCase : List[Any] = self.tokenizer.decode(
SCREAMING_SNAKE_CASE_ , skip_special_tokens=SCREAMING_SNAKE_CASE_ , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE_ , )
# Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used
if input_ids is None:
__UpperCamelCase : Union[str, Any] = 0
else:
__UpperCamelCase : Optional[int] = len(
self.tokenizer.decode(
input_ids[0] , skip_special_tokens=SCREAMING_SNAKE_CASE_ , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE_ , ) )
if return_type == ReturnType.FULL_TEXT:
__UpperCamelCase : Optional[int] = prompt_text + text[prompt_length:]
else:
__UpperCamelCase : Union[str, Any] = text[prompt_length:]
__UpperCamelCase : List[Any] = {'''generated_text''': all_text}
records.append(SCREAMING_SNAKE_CASE_ )
return records
| 269 |
import inspect
from typing import Optional, Union
import numpy as np
import PIL
import torch
from torch.nn import functional as F
from torchvision import transforms
from transformers import CLIPFeatureExtractor, CLIPModel, CLIPTextModel, CLIPTokenizer
from diffusers import (
AutoencoderKL,
DDIMScheduler,
DiffusionPipeline,
DPMSolverMultistepScheduler,
LMSDiscreteScheduler,
PNDMScheduler,
UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput
from diffusers.utils import (
PIL_INTERPOLATION,
randn_tensor,
)
def _A ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ):
if isinstance(SCREAMING_SNAKE_CASE__ , torch.Tensor ):
return image
elif isinstance(SCREAMING_SNAKE_CASE__ , PIL.Image.Image ):
UpperCamelCase :Dict = [image]
if isinstance(image[0] , PIL.Image.Image ):
UpperCamelCase :Any = [np.array(i.resize((w, h) , resample=PIL_INTERPOLATION['''lanczos'''] ) )[None, :] for i in image]
UpperCamelCase :int = np.concatenate(SCREAMING_SNAKE_CASE__ , axis=0 )
UpperCamelCase :Optional[Any] = np.array(SCREAMING_SNAKE_CASE__ ).astype(np.floataa ) / 2_55.0
UpperCamelCase :List[str] = image.transpose(0 , 3 , 1 , 2 )
UpperCamelCase :Tuple = 2.0 * image - 1.0
UpperCamelCase :Any = torch.from_numpy(SCREAMING_SNAKE_CASE__ )
elif isinstance(image[0] , torch.Tensor ):
UpperCamelCase :str = torch.cat(SCREAMING_SNAKE_CASE__ , dim=0 )
return image
def _A ( SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : int=0.99_95 ):
if not isinstance(SCREAMING_SNAKE_CASE__ , np.ndarray ):
UpperCamelCase :int = True
UpperCamelCase :Dict = va.device
UpperCamelCase :List[Any] = va.cpu().numpy()
UpperCamelCase :str = va.cpu().numpy()
UpperCamelCase :Dict = np.sum(va * va / (np.linalg.norm(SCREAMING_SNAKE_CASE__ ) * np.linalg.norm(SCREAMING_SNAKE_CASE__ )) )
if np.abs(SCREAMING_SNAKE_CASE__ ) > DOT_THRESHOLD:
UpperCamelCase :Any = (1 - t) * va + t * va
else:
UpperCamelCase :Union[str, Any] = np.arccos(SCREAMING_SNAKE_CASE__ )
UpperCamelCase :List[str] = np.sin(SCREAMING_SNAKE_CASE__ )
UpperCamelCase :Union[str, Any] = theta_a * t
UpperCamelCase :str = np.sin(SCREAMING_SNAKE_CASE__ )
UpperCamelCase :Tuple = np.sin(theta_a - theta_t ) / sin_theta_a
UpperCamelCase :List[Any] = sin_theta_t / sin_theta_a
UpperCamelCase :Union[str, Any] = sa * va + sa * va
if inputs_are_torch:
UpperCamelCase :Dict = torch.from_numpy(SCREAMING_SNAKE_CASE__ ).to(SCREAMING_SNAKE_CASE__ )
return va
def _A ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Tuple ):
UpperCamelCase :int = F.normalize(SCREAMING_SNAKE_CASE__ , dim=-1 )
UpperCamelCase :int = F.normalize(SCREAMING_SNAKE_CASE__ , dim=-1 )
return (x - y).norm(dim=-1 ).div(2 ).arcsin().pow(2 ).mul(2 )
def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Any ):
for param in model.parameters():
UpperCamelCase :Any = value
class UpperCAmelCase_ ( lowercase ):
"""simple docstring"""
def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , ) -> str:
super().__init__()
self.register_modules(
vae=SCREAMING_SNAKE_CASE_ , text_encoder=SCREAMING_SNAKE_CASE_ , clip_model=SCREAMING_SNAKE_CASE_ , tokenizer=SCREAMING_SNAKE_CASE_ , unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ , feature_extractor=SCREAMING_SNAKE_CASE_ , coca_model=SCREAMING_SNAKE_CASE_ , coca_tokenizer=SCREAMING_SNAKE_CASE_ , coca_transform=SCREAMING_SNAKE_CASE_ , )
UpperCamelCase :Union[str, Any] = (
feature_extractor.size
if isinstance(feature_extractor.size , SCREAMING_SNAKE_CASE_ )
else feature_extractor.size['''shortest_edge''']
)
UpperCamelCase :Any = transforms.Normalize(mean=feature_extractor.image_mean , std=feature_extractor.image_std )
set_requires_grad(self.text_encoder , SCREAMING_SNAKE_CASE_ )
set_requires_grad(self.clip_model , SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ = "auto" ) -> Tuple:
if slice_size == "auto":
# half the attention head size is usually a good trade-off between
# speed and memory
UpperCamelCase :Tuple = self.unet.config.attention_head_dim // 2
self.unet.set_attention_slice(SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self ) -> int:
self.enable_attention_slicing(SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self ) -> str:
set_requires_grad(self.vae , SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self ) -> Union[str, Any]:
set_requires_grad(self.vae , SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self ) -> int:
set_requires_grad(self.unet , SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self ) -> str:
set_requires_grad(self.unet , SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Any:
# get the original timestep using init_timestep
UpperCamelCase :Union[str, Any] = min(int(num_inference_steps * strength ) , SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Optional[Any] = max(num_inference_steps - init_timestep , 0 )
UpperCamelCase :Optional[Any] = self.scheduler.timesteps[t_start:]
return timesteps, num_inference_steps - t_start
def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None ) -> int:
if not isinstance(SCREAMING_SNAKE_CASE_ , torch.Tensor ):
raise ValueError(F'''`image` has to be of type `torch.Tensor` but is {type(SCREAMING_SNAKE_CASE_ )}''' )
UpperCamelCase :Tuple = image.to(device=SCREAMING_SNAKE_CASE_ , dtype=SCREAMING_SNAKE_CASE_ )
if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ):
UpperCamelCase :int = [
self.vae.encode(image[i : i + 1] ).latent_dist.sample(generator[i] ) for i in range(SCREAMING_SNAKE_CASE_ )
]
UpperCamelCase :List[str] = torch.cat(SCREAMING_SNAKE_CASE_ , dim=0 )
else:
UpperCamelCase :Any = self.vae.encode(SCREAMING_SNAKE_CASE_ ).latent_dist.sample(SCREAMING_SNAKE_CASE_ )
# Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor
UpperCamelCase :List[str] = 0.1_8215 * init_latents
UpperCamelCase :Optional[Any] = init_latents.repeat_interleave(SCREAMING_SNAKE_CASE_ , dim=0 )
UpperCamelCase :List[Any] = randn_tensor(init_latents.shape , generator=SCREAMING_SNAKE_CASE_ , device=SCREAMING_SNAKE_CASE_ , dtype=SCREAMING_SNAKE_CASE_ )
# get latents
UpperCamelCase :Optional[Any] = self.scheduler.add_noise(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
UpperCamelCase :str = init_latents
return latents
def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ ) -> List[str]:
UpperCamelCase :List[str] = self.coca_transform(SCREAMING_SNAKE_CASE_ ).unsqueeze(0 )
with torch.no_grad(), torch.cuda.amp.autocast():
UpperCamelCase :Any = self.coca_model.generate(transformed_image.to(device=self.device , dtype=self.coca_model.dtype ) )
UpperCamelCase :List[Any] = self.coca_tokenizer.decode(generated[0].cpu().numpy() )
return generated.split('''<end_of_text>''' )[0].replace('''<start_of_text>''' , '''''' ).rstrip(''' .,''' )
def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> List[Any]:
UpperCamelCase :str = self.feature_extractor.preprocess(SCREAMING_SNAKE_CASE_ )
UpperCamelCase :List[str] = torch.from_numpy(clip_image_input['''pixel_values'''][0] ).unsqueeze(0 ).to(self.device ).half()
UpperCamelCase :int = self.clip_model.get_image_features(SCREAMING_SNAKE_CASE_ )
UpperCamelCase :str = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Union[str, Any] = image_embeddings_clip.repeat_interleave(SCREAMING_SNAKE_CASE_ , dim=0 )
return image_embeddings_clip
@torch.enable_grad()
def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ) -> Optional[int]:
UpperCamelCase :List[str] = latents.detach().requires_grad_()
UpperCamelCase :List[str] = self.scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# predict the noise residual
UpperCamelCase :List[Any] = self.unet(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ ).sample
if isinstance(self.scheduler , (PNDMScheduler, DDIMScheduler, DPMSolverMultistepScheduler) ):
UpperCamelCase :List[str] = self.scheduler.alphas_cumprod[timestep]
UpperCamelCase :Optional[int] = 1 - alpha_prod_t
# compute predicted original sample from predicted noise also called
# "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
UpperCamelCase :List[Any] = (latents - beta_prod_t ** 0.5 * noise_pred) / alpha_prod_t ** 0.5
UpperCamelCase :int = torch.sqrt(SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Tuple = pred_original_sample * (fac) + latents * (1 - fac)
elif isinstance(self.scheduler , SCREAMING_SNAKE_CASE_ ):
UpperCamelCase :str = self.scheduler.sigmas[index]
UpperCamelCase :Union[str, Any] = latents - sigma * noise_pred
else:
raise ValueError(F'''scheduler type {type(self.scheduler )} not supported''' )
# Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor
UpperCamelCase :int = 1 / 0.1_8215 * sample
UpperCamelCase :List[Any] = self.vae.decode(SCREAMING_SNAKE_CASE_ ).sample
UpperCamelCase :str = (image / 2 + 0.5).clamp(0 , 1 )
UpperCamelCase :List[str] = transforms.Resize(self.feature_extractor_size )(SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Any = self.normalize(SCREAMING_SNAKE_CASE_ ).to(latents.dtype )
UpperCamelCase :List[Any] = self.clip_model.get_image_features(SCREAMING_SNAKE_CASE_ )
UpperCamelCase :str = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Union[str, Any] = spherical_dist_loss(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).mean() * clip_guidance_scale
UpperCamelCase :Union[str, Any] = -torch.autograd.grad(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )[0]
if isinstance(self.scheduler , SCREAMING_SNAKE_CASE_ ):
UpperCamelCase :Dict = latents.detach() + grads * (sigma**2)
UpperCamelCase :Optional[Any] = noise_pred_original
else:
UpperCamelCase :List[str] = noise_pred_original - torch.sqrt(SCREAMING_SNAKE_CASE_ ) * grads
return noise_pred, latents
@torch.no_grad()
def __call__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 512 , SCREAMING_SNAKE_CASE_ = 512 , SCREAMING_SNAKE_CASE_ = 0.6 , SCREAMING_SNAKE_CASE_ = 50 , SCREAMING_SNAKE_CASE_ = 7.5 , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = 100 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "pil" , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = 0.8 , SCREAMING_SNAKE_CASE_ = 0.1 , SCREAMING_SNAKE_CASE_ = 0.1 , ) -> Dict:
if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) and len(SCREAMING_SNAKE_CASE_ ) != batch_size:
raise ValueError(F'''You have passed {batch_size} batch_size, but only {len(SCREAMING_SNAKE_CASE_ )} generators.''' )
if height % 8 != 0 or width % 8 != 0:
raise ValueError(F'''`height` and `width` have to be divisible by 8 but are {height} and {width}.''' )
if isinstance(SCREAMING_SNAKE_CASE_ , torch.Generator ) and batch_size > 1:
UpperCamelCase :Optional[int] = [generator] + [None] * (batch_size - 1)
UpperCamelCase :Tuple = [
('''model''', self.coca_model is None),
('''tokenizer''', self.coca_tokenizer is None),
('''transform''', self.coca_transform is None),
]
UpperCamelCase :Union[str, Any] = [x[0] for x in coca_is_none if x[1]]
UpperCamelCase :Dict = ''', '''.join(SCREAMING_SNAKE_CASE_ )
# generate prompts with coca model if prompt is None
if content_prompt is None:
if len(SCREAMING_SNAKE_CASE_ ):
raise ValueError(
F'''Content prompt is None and CoCa [{coca_is_none_str}] is None.'''
F'''Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.''' )
UpperCamelCase :Any = self.get_image_description(SCREAMING_SNAKE_CASE_ )
if style_prompt is None:
if len(SCREAMING_SNAKE_CASE_ ):
raise ValueError(
F'''Style prompt is None and CoCa [{coca_is_none_str}] is None.'''
F''' Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.''' )
UpperCamelCase :str = self.get_image_description(SCREAMING_SNAKE_CASE_ )
# get prompt text embeddings for content and style
UpperCamelCase :List[Any] = self.tokenizer(
SCREAMING_SNAKE_CASE_ , padding='''max_length''' , max_length=self.tokenizer.model_max_length , truncation=SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' , )
UpperCamelCase :Dict = self.text_encoder(content_text_input.input_ids.to(self.device ) )[0]
UpperCamelCase :List[Any] = self.tokenizer(
SCREAMING_SNAKE_CASE_ , padding='''max_length''' , max_length=self.tokenizer.model_max_length , truncation=SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' , )
UpperCamelCase :Tuple = self.text_encoder(style_text_input.input_ids.to(self.device ) )[0]
UpperCamelCase :Dict = slerp(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# duplicate text embeddings for each generation per prompt
UpperCamelCase :Union[str, Any] = text_embeddings.repeat_interleave(SCREAMING_SNAKE_CASE_ , dim=0 )
# set timesteps
UpperCamelCase :str = '''offset''' in set(inspect.signature(self.scheduler.set_timesteps ).parameters.keys() )
UpperCamelCase :List[str] = {}
if accepts_offset:
UpperCamelCase :Tuple = 1
self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
# Some schedulers like PNDM have timesteps as arrays
# It's more optimized to move all timesteps to correct device beforehand
self.scheduler.timesteps.to(self.device )
UpperCamelCase , UpperCamelCase :Tuple = self.get_timesteps(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , self.device )
UpperCamelCase :Any = timesteps[:1].repeat(SCREAMING_SNAKE_CASE_ )
# Preprocess image
UpperCamelCase :Union[str, Any] = preprocess(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Optional[Any] = self.prepare_latents(
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , text_embeddings.dtype , self.device , SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Dict = preprocess(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Optional[Any] = self.prepare_latents(
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , text_embeddings.dtype , self.device , SCREAMING_SNAKE_CASE_ )
UpperCamelCase :str = slerp(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
if clip_guidance_scale > 0:
UpperCamelCase :Dict = self.get_clip_image_embeddings(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Optional[int] = self.get_clip_image_embeddings(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Optional[Any] = slerp(
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
# corresponds to doing no classifier free guidance.
UpperCamelCase :Optional[int] = guidance_scale > 1.0
# get unconditional embeddings for classifier free guidance
if do_classifier_free_guidance:
UpperCamelCase :Any = content_text_input.input_ids.shape[-1]
UpperCamelCase :Any = self.tokenizer([''''''] , padding='''max_length''' , max_length=SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' )
UpperCamelCase :Optional[Any] = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0]
# duplicate unconditional embeddings for each generation per prompt
UpperCamelCase :Optional[int] = uncond_embeddings.repeat_interleave(SCREAMING_SNAKE_CASE_ , dim=0 )
# For classifier free guidance, we need to do two forward passes.
# Here we concatenate the unconditional and text embeddings into a single batch
# to avoid doing two forward passes
UpperCamelCase :str = torch.cat([uncond_embeddings, text_embeddings] )
# get the initial random noise unless the user supplied it
# Unlike in other pipelines, latents need to be generated in the target device
# for 1-to-1 results reproducibility with the CompVis implementation.
# However this currently doesn't work in `mps`.
UpperCamelCase :Any = (batch_size, self.unet.config.in_channels, height // 8, width // 8)
UpperCamelCase :int = text_embeddings.dtype
if latents is None:
if self.device.type == "mps":
# randn does not work reproducibly on mps
UpperCamelCase :List[str] = torch.randn(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device='''cpu''' , dtype=SCREAMING_SNAKE_CASE_ ).to(
self.device )
else:
UpperCamelCase :int = torch.randn(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device=self.device , dtype=SCREAMING_SNAKE_CASE_ )
else:
if latents.shape != latents_shape:
raise ValueError(F'''Unexpected latents shape, got {latents.shape}, expected {latents_shape}''' )
UpperCamelCase :str = latents.to(self.device )
# scale the initial noise by the standard deviation required by the scheduler
UpperCamelCase :Union[str, Any] = latents * self.scheduler.init_noise_sigma
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
# and should be between [0, 1]
UpperCamelCase :Optional[int] = '''eta''' in set(inspect.signature(self.scheduler.step ).parameters.keys() )
UpperCamelCase :Dict = {}
if accepts_eta:
UpperCamelCase :int = eta
# check if the scheduler accepts generator
UpperCamelCase :Optional[int] = '''generator''' in set(inspect.signature(self.scheduler.step ).parameters.keys() )
if accepts_generator:
UpperCamelCase :List[str] = generator
with self.progress_bar(total=SCREAMING_SNAKE_CASE_ ):
for i, t in enumerate(SCREAMING_SNAKE_CASE_ ):
# expand the latents if we are doing classifier free guidance
UpperCamelCase :Optional[int] = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents
UpperCamelCase :List[Any] = self.scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# predict the noise residual
UpperCamelCase :List[str] = self.unet(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ ).sample
# perform classifier free guidance
if do_classifier_free_guidance:
UpperCamelCase , UpperCamelCase :Any = noise_pred.chunk(2 )
UpperCamelCase :Optional[Any] = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
# perform clip guidance
if clip_guidance_scale > 0:
UpperCamelCase :int = (
text_embeddings.chunk(2 )[1] if do_classifier_free_guidance else text_embeddings
)
UpperCamelCase , UpperCamelCase :str = self.cond_fn(
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , )
# compute the previous noisy sample x_t -> x_t-1
UpperCamelCase :List[str] = self.scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample
# Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor
UpperCamelCase :List[Any] = 1 / 0.1_8215 * latents
UpperCamelCase :Optional[Any] = self.vae.decode(SCREAMING_SNAKE_CASE_ ).sample
UpperCamelCase :str = (image / 2 + 0.5).clamp(0 , 1 )
UpperCamelCase :Dict = image.cpu().permute(0 , 2 , 3 , 1 ).numpy()
if output_type == "pil":
UpperCamelCase :List[str] = self.numpy_to_pil(SCREAMING_SNAKE_CASE_ )
if not return_dict:
return (image, None)
return StableDiffusionPipelineOutput(images=SCREAMING_SNAKE_CASE_ , nsfw_content_detected=SCREAMING_SNAKE_CASE_ )
| 658 | 0 |
import unittest
from pathlib import Path
from tempfile import NamedTemporaryFile, TemporaryDirectory
from transformers import BertConfig, BertTokenizerFast, FeatureExtractionPipeline
from transformers.convert_graph_to_onnx import (
convert,
ensure_valid_input,
generate_identified_filename,
infer_shapes,
quantize,
)
from transformers.testing_utils import require_tf, require_tokenizers, require_torch, slow
class _A :
def UpperCAmelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
return None
class _A :
def UpperCAmelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
return None
class _A ( unittest.TestCase ):
__a = [
# (model_name, model_kwargs)
('bert-base-cased', {}),
('gpt2', {'use_cache': False}), # We don't support exporting GPT2 past keys anymore
]
@require_tf
@slow
def UpperCAmelCase ( self ):
for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
self._test_export(SCREAMING_SNAKE_CASE_ , """tf""" , 12 , **SCREAMING_SNAKE_CASE_ )
@require_torch
@slow
def UpperCAmelCase ( self ):
for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
self._test_export(SCREAMING_SNAKE_CASE_ , """pt""" , 12 , **SCREAMING_SNAKE_CASE_ )
@require_torch
@slow
def UpperCAmelCase ( self ):
from transformers import BertModel
_UpperCAmelCase = ['''[UNK]''', '''[SEP]''', '''[CLS]''', '''[PAD]''', '''[MASK]''', '''some''', '''other''', '''words''']
with NamedTemporaryFile(mode="""w+t""" ) as vocab_file:
vocab_file.write("""\n""".join(SCREAMING_SNAKE_CASE_ ) )
vocab_file.flush()
_UpperCAmelCase = BertTokenizerFast(vocab_file.name )
with TemporaryDirectory() as bert_save_dir:
_UpperCAmelCase = BertModel(BertConfig(vocab_size=len(SCREAMING_SNAKE_CASE_ ) ) )
model.save_pretrained(SCREAMING_SNAKE_CASE_ )
self._test_export(SCREAMING_SNAKE_CASE_ , """pt""" , 12 , SCREAMING_SNAKE_CASE_ )
@require_tf
@slow
def UpperCAmelCase ( self ):
for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
_UpperCAmelCase = self._test_export(SCREAMING_SNAKE_CASE_ , """tf""" , 12 , **SCREAMING_SNAKE_CASE_ )
_UpperCAmelCase = quantize(Path(SCREAMING_SNAKE_CASE_ ) )
# Ensure the actual quantized model is not bigger than the original one
if quantized_path.stat().st_size >= Path(SCREAMING_SNAKE_CASE_ ).stat().st_size:
self.fail("""Quantized model is bigger than initial ONNX model""" )
@require_torch
@slow
def UpperCAmelCase ( self ):
for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
_UpperCAmelCase = self._test_export(SCREAMING_SNAKE_CASE_ , """pt""" , 12 , **SCREAMING_SNAKE_CASE_ )
_UpperCAmelCase = quantize(SCREAMING_SNAKE_CASE_ )
# Ensure the actual quantized model is not bigger than the original one
if quantized_path.stat().st_size >= Path(SCREAMING_SNAKE_CASE_ ).stat().st_size:
self.fail("""Quantized model is bigger than initial ONNX model""" )
def UpperCAmelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE ):
try:
# Compute path
with TemporaryDirectory() as tempdir:
_UpperCAmelCase = Path(SCREAMING_SNAKE_CASE_ ).joinpath("""model.onnx""" )
# Remove folder if exists
if path.parent.exists():
path.parent.rmdir()
# Export
convert(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
return path
except Exception as e:
self.fail(SCREAMING_SNAKE_CASE_ )
@require_torch
@require_tokenizers
@slow
def UpperCAmelCase ( self ):
from transformers import BertModel
_UpperCAmelCase = BertModel(BertConfig.from_pretrained("""lysandre/tiny-bert-random""" ) )
_UpperCAmelCase = BertTokenizerFast.from_pretrained("""lysandre/tiny-bert-random""" )
self._test_infer_dynamic_axis(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , """pt""" )
@require_tf
@require_tokenizers
@slow
def UpperCAmelCase ( self ):
from transformers import TFBertModel
_UpperCAmelCase = TFBertModel(BertConfig.from_pretrained("""lysandre/tiny-bert-random""" ) )
_UpperCAmelCase = BertTokenizerFast.from_pretrained("""lysandre/tiny-bert-random""" )
self._test_infer_dynamic_axis(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , """tf""" )
def UpperCAmelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
_UpperCAmelCase = FeatureExtractionPipeline(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
_UpperCAmelCase = ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''output_0''', '''output_1''']
_UpperCAmelCase = infer_shapes(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# Assert all variables are present
self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , len(SCREAMING_SNAKE_CASE_ ) )
self.assertTrue(all(var_name in shapes for var_name in variable_names ) )
self.assertSequenceEqual(variable_names[:3] , SCREAMING_SNAKE_CASE_ )
self.assertSequenceEqual(variable_names[3:] , SCREAMING_SNAKE_CASE_ )
# Assert inputs are {0: batch, 1: sequence}
for var_name in ["input_ids", "token_type_ids", "attention_mask"]:
self.assertDictEqual(shapes[var_name] , {0: """batch""", 1: """sequence"""} )
# Assert outputs are {0: batch, 1: sequence} and {0: batch}
self.assertDictEqual(shapes["""output_0"""] , {0: """batch""", 1: """sequence"""} )
self.assertDictEqual(shapes["""output_1"""] , {0: """batch"""} )
def UpperCAmelCase ( self ):
_UpperCAmelCase = ['''input_ids''', '''attention_mask''', '''token_type_ids''']
_UpperCAmelCase = {'''input_ids''': [1, 2, 3, 4], '''attention_mask''': [0, 0, 0, 0], '''token_type_ids''': [1, 1, 1, 1]}
_UpperCAmelCase = ensure_valid_input(FuncContiguousArgs() , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# Should have exactly the same number of args (all are valid)
self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 3 )
# Should have exactly the same input names
self.assertEqual(set(SCREAMING_SNAKE_CASE_ ) , set(SCREAMING_SNAKE_CASE_ ) )
# Parameter should be reordered according to their respective place in the function:
# (input_ids, token_type_ids, attention_mask)
self.assertEqual(SCREAMING_SNAKE_CASE_ , (tokens["""input_ids"""], tokens["""token_type_ids"""], tokens["""attention_mask"""]) )
# Generated args are interleaved with another args (for instance parameter "past" in GPT2)
_UpperCAmelCase = ensure_valid_input(FuncNonContiguousArgs() , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# Should have exactly the one arg (all before the one not provided "some_other_args")
self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 1 )
self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 1 )
# Should have only "input_ids"
self.assertEqual(inputs_args[0] , tokens["""input_ids"""] )
self.assertEqual(ordered_input_names[0] , """input_ids""" )
def UpperCAmelCase ( self ):
_UpperCAmelCase = generate_identified_filename(Path("""/home/something/my_fake_model.onnx""" ) , """-test""" )
self.assertEqual("""/home/something/my_fake_model-test.onnx""" , generated.as_posix() ) | 518 |
from __future__ import annotations
def _A ( SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : int ):
UpperCamelCase :list[list[int]] = []
UpperCamelCase :list[int] = []
UpperCamelCase :List[str] = 0
UpperCamelCase :Any = sum(SCREAMING_SNAKE_CASE__ )
create_state_space_tree(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
return result
def _A ( SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : list[list[int]] , SCREAMING_SNAKE_CASE__ : int , ):
if sum(SCREAMING_SNAKE_CASE__ ) > max_sum or (remaining_nums_sum + sum(SCREAMING_SNAKE_CASE__ )) < max_sum:
return
if sum(SCREAMING_SNAKE_CASE__ ) == max_sum:
result.append(SCREAMING_SNAKE_CASE__ )
return
for index in range(SCREAMING_SNAKE_CASE__ , len(SCREAMING_SNAKE_CASE__ ) ):
create_state_space_tree(
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , index + 1 , [*path, nums[index]] , SCREAMING_SNAKE_CASE__ , remaining_nums_sum - nums[index] , )
__snake_case = [3, 34, 4, 12, 5, 2]
__snake_case = 9
__snake_case = generate_sum_of_subsets_soln(nums, max_sum)
print(*result)
| 658 | 0 |
import math
def _a ( a :int ) -> int:
assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and (
number >= 0
), "'number' must been an int and positive"
if 1 < number < 4:
# 2 and 3 are primes
return True
elif number < 2 or not number % 2:
# Negatives, 0, 1 and all even numbers are not primes
return False
a = range(3 , int(math.sqrt(SCREAMING_SNAKE_CASE__ ) + 1 ) , 2 )
return not any(not number % i for i in odd_numbers )
def _a ( a :Any , a :Any=1 , **a :Dict ) -> List[str]:
a = factor * value
a = value
while not is_prime(SCREAMING_SNAKE_CASE__ ):
value += 1 if not ("desc" in kwargs and kwargs["desc"] is True) else -1
if value == first_value_val:
return next_prime(value + 1 , **SCREAMING_SNAKE_CASE__ )
return value
| 117 |
def _A ( SCREAMING_SNAKE_CASE__ : int ):
if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
raise ValueError('''check_bouncy() accepts only integer arguments''' )
UpperCamelCase :int = str(SCREAMING_SNAKE_CASE__ )
UpperCamelCase :Optional[Any] = ''''''.join(sorted(SCREAMING_SNAKE_CASE__ ) )
return sorted_str_n != str_n and sorted_str_n[::-1] != str_n
def _A ( SCREAMING_SNAKE_CASE__ : float = 99 ):
if not 0 < percent < 100:
raise ValueError('''solution() only accepts values from 0 to 100''' )
UpperCamelCase :Tuple = 0
UpperCamelCase :str = 1
while True:
if check_bouncy(SCREAMING_SNAKE_CASE__ ):
bouncy_num += 1
if (bouncy_num / num) * 100 >= percent:
return num
num += 1
if __name__ == "__main__":
from doctest import testmod
testmod()
print(f'''{solution(99)}''')
| 658 | 0 |
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_sentencepiece_available,
is_tokenizers_available,
is_torch_available,
)
__UpperCamelCase : Tuple = {'configuration_reformer': ['REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ReformerConfig']}
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__UpperCamelCase : Tuple = ['ReformerTokenizer']
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__UpperCamelCase : Optional[int] = ['ReformerTokenizerFast']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__UpperCamelCase : Union[str, Any] = [
'REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST',
'ReformerAttention',
'ReformerForMaskedLM',
'ReformerForQuestionAnswering',
'ReformerForSequenceClassification',
'ReformerLayer',
'ReformerModel',
'ReformerModelWithLMHead',
'ReformerPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_reformer import REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, ReformerConfig
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_reformer import ReformerTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_reformer_fast import ReformerTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_reformer import (
REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
ReformerAttention,
ReformerForMaskedLM,
ReformerForQuestionAnswering,
ReformerForSequenceClassification,
ReformerLayer,
ReformerModel,
ReformerModelWithLMHead,
ReformerPreTrainedModel,
)
else:
import sys
__UpperCamelCase : List[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 248 |
def _A ( SCREAMING_SNAKE_CASE__ : str ):
UpperCamelCase :Union[str, Any] = hex_num.strip()
if not hex_num:
raise ValueError('''No value was passed to the function''' )
UpperCamelCase :str = hex_num[0] == '''-'''
if is_negative:
UpperCamelCase :Union[str, Any] = hex_num[1:]
try:
UpperCamelCase :Optional[Any] = int(SCREAMING_SNAKE_CASE__ , 16 )
except ValueError:
raise ValueError('''Invalid value was passed to the function''' )
UpperCamelCase :Dict = ''''''
while int_num > 0:
UpperCamelCase :Tuple = str(int_num % 2 ) + bin_str
int_num >>= 1
return int(('''-''' + bin_str) if is_negative else bin_str )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 658 | 0 |
def __UpperCamelCase ( lowerCAmelCase__ : int = 1_0 , lowerCAmelCase__ : int = 2_2 ):
__a : Union[str, Any] = range(1 , SCREAMING_SNAKE_CASE__ )
__a : Dict = range(1 , SCREAMING_SNAKE_CASE__ )
return sum(
1 for power in powers for base in bases if len(str(base**power ) ) == power )
if __name__ == "__main__":
print(F"""{solution(10, 22) = }""")
| 521 |
from __future__ import annotations
def _A ( SCREAMING_SNAKE_CASE__ : tuple[int, int] , SCREAMING_SNAKE_CASE__ : int ):
UpperCamelCase , UpperCamelCase :List[Any] = position
UpperCamelCase :Any = [
(y + 1, x + 2),
(y - 1, x + 2),
(y + 1, x - 2),
(y - 1, x - 2),
(y + 2, x + 1),
(y + 2, x - 1),
(y - 2, x + 1),
(y - 2, x - 1),
]
UpperCamelCase :Dict = []
for position in positions:
UpperCamelCase , UpperCamelCase :str = position
if 0 <= y_test < n and 0 <= x_test < n:
permissible_positions.append(SCREAMING_SNAKE_CASE__ )
return permissible_positions
def _A ( SCREAMING_SNAKE_CASE__ : list[list[int]] ):
return not any(elem == 0 for row in board for elem in row )
def _A ( SCREAMING_SNAKE_CASE__ : list[list[int]] , SCREAMING_SNAKE_CASE__ : tuple[int, int] , SCREAMING_SNAKE_CASE__ : int ):
if is_complete(SCREAMING_SNAKE_CASE__ ):
return True
for position in get_valid_pos(SCREAMING_SNAKE_CASE__ , len(SCREAMING_SNAKE_CASE__ ) ):
UpperCamelCase , UpperCamelCase :Optional[int] = position
if board[y][x] == 0:
UpperCamelCase :Any = curr + 1
if open_knight_tour_helper(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , curr + 1 ):
return True
UpperCamelCase :Union[str, Any] = 0
return False
def _A ( SCREAMING_SNAKE_CASE__ : int ):
UpperCamelCase :List[Any] = [[0 for i in range(SCREAMING_SNAKE_CASE__ )] for j in range(SCREAMING_SNAKE_CASE__ )]
for i in range(SCREAMING_SNAKE_CASE__ ):
for j in range(SCREAMING_SNAKE_CASE__ ):
UpperCamelCase :Tuple = 1
if open_knight_tour_helper(SCREAMING_SNAKE_CASE__ , (i, j) , 1 ):
return board
UpperCamelCase :str = 0
UpperCamelCase :List[Any] = F'''Open Kight Tour cannot be performed on a board of size {n}'''
raise ValueError(SCREAMING_SNAKE_CASE__ )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 658 | 0 |
"""simple docstring"""
import argparse
from collections import defaultdict
import yaml
UpperCAmelCase = """docs/source/en/_toctree.yml"""
def __magic_name__ ( _lowerCamelCase: str ) -> Optional[int]:
'''simple docstring'''
lowerCAmelCase = defaultdict(SCREAMING_SNAKE_CASE__ )
for doc in model_doc:
counts[doc["local"]] += 1
lowerCAmelCase = [key for key, value in counts.items() if value > 1]
lowerCAmelCase = []
for duplicate_key in duplicates:
lowerCAmelCase = list({doc['''title'''] for doc in model_doc if doc['''local'''] == duplicate_key} )
if len(SCREAMING_SNAKE_CASE__ ) > 1:
raise ValueError(
F"""{duplicate_key} is present several times in the documentation table of content at """
'''`docs/source/en/_toctree.yml` with different *Title* values. Choose one of those and remove the '''
'''others.''' )
# Only add this once
new_doc.append({'''local''': duplicate_key, '''title''': titles[0]} )
# Add none duplicate-keys
new_doc.extend([doc for doc in model_doc if counts[doc['''local''']] == 1] )
# Sort
return sorted(SCREAMING_SNAKE_CASE__, key=lambda _lowerCamelCase : s["title"].lower() )
def __magic_name__ ( _lowerCamelCase: str=False ) -> str:
'''simple docstring'''
with open(SCREAMING_SNAKE_CASE__, encoding='''utf-8''' ) as f:
lowerCAmelCase = yaml.safe_load(f.read() )
# Get to the API doc
lowerCAmelCase = 0
while content[api_idx]["title"] != "API":
api_idx += 1
lowerCAmelCase = content[api_idx]['''sections''']
# Then to the model doc
lowerCAmelCase = 0
while api_doc[model_idx]["title"] != "Models":
model_idx += 1
lowerCAmelCase = api_doc[model_idx]['''sections''']
lowerCAmelCase = [(idx, section) for idx, section in enumerate(SCREAMING_SNAKE_CASE__ ) if '''sections''' in section]
lowerCAmelCase = False
for idx, modality_doc in modalities_docs:
lowerCAmelCase = modality_doc['''sections''']
lowerCAmelCase = clean_model_doc_toc(SCREAMING_SNAKE_CASE__ )
if old_modality_doc != new_modality_doc:
lowerCAmelCase = True
if overwrite:
lowerCAmelCase = new_modality_doc
if diff:
if overwrite:
lowerCAmelCase = model_doc
lowerCAmelCase = api_doc
with open(SCREAMING_SNAKE_CASE__, '''w''', encoding='''utf-8''' ) as f:
f.write(yaml.dump(SCREAMING_SNAKE_CASE__, allow_unicode=SCREAMING_SNAKE_CASE__ ) )
else:
raise ValueError(
'''The model doc part of the table of content is not properly sorted, run `make style` to fix this.''' )
if __name__ == "__main__":
UpperCAmelCase = argparse.ArgumentParser()
parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""")
UpperCAmelCase = parser.parse_args()
check_model_doc(args.fix_and_overwrite)
| 535 |
import copy
import tempfile
import unittest
from huggingface_hub import HfFolder, delete_repo
from parameterized import parameterized
from requests.exceptions import HTTPError
from transformers import AutoConfig, GenerationConfig
from transformers.testing_utils import TOKEN, USER, is_staging_test
class UpperCAmelCase_ ( unittest.TestCase ):
"""simple docstring"""
@parameterized.expand([(None,), ('''foo.json''',)] )
def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ ) -> List[str]:
UpperCamelCase :int = GenerationConfig(
do_sample=SCREAMING_SNAKE_CASE_ , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , )
with tempfile.TemporaryDirectory() as tmp_dir:
config.save_pretrained(SCREAMING_SNAKE_CASE_ , config_name=SCREAMING_SNAKE_CASE_ )
UpperCamelCase :str = GenerationConfig.from_pretrained(SCREAMING_SNAKE_CASE_ , config_name=SCREAMING_SNAKE_CASE_ )
# Checks parameters that were specified
self.assertEqual(loaded_config.do_sample , SCREAMING_SNAKE_CASE_ )
self.assertEqual(loaded_config.temperature , 0.7 )
self.assertEqual(loaded_config.length_penalty , 1.0 )
self.assertEqual(loaded_config.bad_words_ids , [[1, 2, 3], [4, 5]] )
# Checks parameters that were not specified (defaults)
self.assertEqual(loaded_config.top_k , 50 )
self.assertEqual(loaded_config.max_length , 20 )
self.assertEqual(loaded_config.max_time , SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self ) -> str:
UpperCamelCase :Optional[Any] = AutoConfig.from_pretrained('''gpt2''' )
UpperCamelCase :Union[str, Any] = GenerationConfig.from_model_config(SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Optional[Any] = GenerationConfig()
# The generation config has loaded a few non-default parameters from the model config
self.assertNotEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# One of those parameters is eos_token_id -- check if it matches
self.assertNotEqual(generation_config_from_model.eos_token_id , default_generation_config.eos_token_id )
self.assertEqual(generation_config_from_model.eos_token_id , model_config.eos_token_id )
def UpperCAmelCase ( self ) -> Dict:
UpperCamelCase :List[str] = GenerationConfig()
UpperCamelCase :List[str] = {
'''max_new_tokens''': 1024,
'''foo''': '''bar''',
}
UpperCamelCase :Dict = copy.deepcopy(SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Any = generation_config.update(**SCREAMING_SNAKE_CASE_ )
# update_kwargs was not modified (no side effects)
self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# update_kwargs was used to update the config on valid attributes
self.assertEqual(generation_config.max_new_tokens , 1024 )
# `.update()` returns a dictionary of unused kwargs
self.assertEqual(SCREAMING_SNAKE_CASE_ , {'''foo''': '''bar'''} )
def UpperCAmelCase ( self ) -> Optional[Any]:
UpperCamelCase :List[Any] = GenerationConfig()
UpperCamelCase :Tuple = '''bar'''
with tempfile.TemporaryDirectory('''test-generation-config''' ) as tmp_dir:
generation_config.save_pretrained(SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Any = GenerationConfig.from_pretrained(SCREAMING_SNAKE_CASE_ )
# update_kwargs was used to update the config on valid attributes
self.assertEqual(new_config.foo , '''bar''' )
UpperCamelCase :Union[str, Any] = GenerationConfig.from_model_config(SCREAMING_SNAKE_CASE_ )
assert not hasattr(SCREAMING_SNAKE_CASE_ , '''foo''' ) # no new kwargs should be initialized if from config
def UpperCAmelCase ( self ) -> Any:
UpperCamelCase :Dict = GenerationConfig()
self.assertEqual(default_config.temperature , 1.0 )
self.assertEqual(default_config.do_sample , SCREAMING_SNAKE_CASE_ )
self.assertEqual(default_config.num_beams , 1 )
UpperCamelCase :Tuple = GenerationConfig(
do_sample=SCREAMING_SNAKE_CASE_ , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , )
self.assertEqual(config.temperature , 0.7 )
self.assertEqual(config.do_sample , SCREAMING_SNAKE_CASE_ )
self.assertEqual(config.num_beams , 1 )
with tempfile.TemporaryDirectory() as tmp_dir:
config.save_pretrained(SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Tuple = GenerationConfig.from_pretrained(SCREAMING_SNAKE_CASE_ , temperature=1.0 )
self.assertEqual(loaded_config.temperature , 1.0 )
self.assertEqual(loaded_config.do_sample , SCREAMING_SNAKE_CASE_ )
self.assertEqual(loaded_config.num_beams , 1 ) # default value
@is_staging_test
class UpperCAmelCase_ ( unittest.TestCase ):
"""simple docstring"""
@classmethod
def UpperCAmelCase ( cls ) -> Optional[Any]:
UpperCamelCase :List[str] = TOKEN
HfFolder.save_token(SCREAMING_SNAKE_CASE_ )
@classmethod
def UpperCAmelCase ( cls ) -> Union[str, Any]:
try:
delete_repo(token=cls._token , repo_id='''test-generation-config''' )
except HTTPError:
pass
try:
delete_repo(token=cls._token , repo_id='''valid_org/test-generation-config-org''' )
except HTTPError:
pass
def UpperCAmelCase ( self ) -> Any:
UpperCamelCase :Optional[Any] = GenerationConfig(
do_sample=SCREAMING_SNAKE_CASE_ , temperature=0.7 , length_penalty=1.0 , )
config.push_to_hub('''test-generation-config''' , use_auth_token=self._token )
UpperCamelCase :List[Any] = GenerationConfig.from_pretrained(F'''{USER}/test-generation-config''' )
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(SCREAMING_SNAKE_CASE_ , getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) )
# Reset repo
delete_repo(token=self._token , repo_id='''test-generation-config''' )
# Push to hub via save_pretrained
with tempfile.TemporaryDirectory() as tmp_dir:
config.save_pretrained(
SCREAMING_SNAKE_CASE_ , repo_id='''test-generation-config''' , push_to_hub=SCREAMING_SNAKE_CASE_ , use_auth_token=self._token )
UpperCamelCase :Any = GenerationConfig.from_pretrained(F'''{USER}/test-generation-config''' )
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(SCREAMING_SNAKE_CASE_ , getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) )
def UpperCAmelCase ( self ) -> Union[str, Any]:
UpperCamelCase :List[str] = GenerationConfig(
do_sample=SCREAMING_SNAKE_CASE_ , temperature=0.7 , length_penalty=1.0 , )
config.push_to_hub('''valid_org/test-generation-config-org''' , use_auth_token=self._token )
UpperCamelCase :Any = GenerationConfig.from_pretrained('''valid_org/test-generation-config-org''' )
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(SCREAMING_SNAKE_CASE_ , getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) )
# Reset repo
delete_repo(token=self._token , repo_id='''valid_org/test-generation-config-org''' )
# Push to hub via save_pretrained
with tempfile.TemporaryDirectory() as tmp_dir:
config.save_pretrained(
SCREAMING_SNAKE_CASE_ , repo_id='''valid_org/test-generation-config-org''' , push_to_hub=SCREAMING_SNAKE_CASE_ , use_auth_token=self._token )
UpperCamelCase :Tuple = GenerationConfig.from_pretrained('''valid_org/test-generation-config-org''' )
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(SCREAMING_SNAKE_CASE_ , getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) )
| 658 | 0 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_tf_available,
is_tokenizers_available,
is_torch_available,
is_vision_available,
)
lowerCAmelCase: int ={
"configuration_layoutlmv3": [
"LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP",
"LayoutLMv3Config",
"LayoutLMv3OnnxConfig",
],
"processing_layoutlmv3": ["LayoutLMv3Processor"],
"tokenization_layoutlmv3": ["LayoutLMv3Tokenizer"],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowerCAmelCase: List[Any] =["LayoutLMv3TokenizerFast"]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowerCAmelCase: Any =[
"LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST",
"LayoutLMv3ForQuestionAnswering",
"LayoutLMv3ForSequenceClassification",
"LayoutLMv3ForTokenClassification",
"LayoutLMv3Model",
"LayoutLMv3PreTrainedModel",
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowerCAmelCase: Dict =[
"TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST",
"TFLayoutLMv3ForQuestionAnswering",
"TFLayoutLMv3ForSequenceClassification",
"TFLayoutLMv3ForTokenClassification",
"TFLayoutLMv3Model",
"TFLayoutLMv3PreTrainedModel",
]
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowerCAmelCase: Dict =["LayoutLMv3FeatureExtractor"]
lowerCAmelCase: Union[str, Any] =["LayoutLMv3ImageProcessor"]
if TYPE_CHECKING:
from .configuration_layoutlmva import (
LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP,
LayoutLMvaConfig,
LayoutLMvaOnnxConfig,
)
from .processing_layoutlmva import LayoutLMvaProcessor
from .tokenization_layoutlmva import LayoutLMvaTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_layoutlmva_fast import LayoutLMvaTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_layoutlmva import (
LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST,
LayoutLMvaForQuestionAnswering,
LayoutLMvaForSequenceClassification,
LayoutLMvaForTokenClassification,
LayoutLMvaModel,
LayoutLMvaPreTrainedModel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_layoutlmva import (
TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST,
TFLayoutLMvaForQuestionAnswering,
TFLayoutLMvaForSequenceClassification,
TFLayoutLMvaForTokenClassification,
TFLayoutLMvaModel,
TFLayoutLMvaPreTrainedModel,
)
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_layoutlmva import LayoutLMvaFeatureExtractor
from .image_processing_layoutlmva import LayoutLMvaImageProcessor
else:
import sys
lowerCAmelCase: Optional[Any] =_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 607 |
def _A ( SCREAMING_SNAKE_CASE__ : int ):
if length <= 0 or not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
raise ValueError('''Length must be a positive integer.''' )
return [n * (2 * n - 1) for n in range(SCREAMING_SNAKE_CASE__ )]
if __name__ == "__main__":
print(hexagonal_numbers(length=5))
print(hexagonal_numbers(length=10))
| 658 | 0 |
import os
from shutil import copyfile
from typing import List, Optional, Tuple
import sentencepiece as spm
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
UpperCamelCase : Optional[int] = logging.get_logger(__name__)
UpperCamelCase : Optional[int] = {"""vocab_file""": """sentencepiece.model"""}
UpperCamelCase : str = {
"""vocab_file""": {
"""google/rembert""": """https://huggingface.co/google/rembert/resolve/main/sentencepiece.model""",
},
}
UpperCamelCase : Tuple = {
"""google/rembert""": 256,
}
class A__ ( A__ ):
"""simple docstring"""
_lowercase = VOCAB_FILES_NAMES
_lowercase = PRETRAINED_VOCAB_FILES_MAP
_lowercase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
def __init__( self : List[str] , lowerCamelCase__ : str , lowerCamelCase__ : Optional[int]=False , lowerCamelCase__ : Any=True , lowerCamelCase__ : Any=True , lowerCamelCase__ : Union[str, Any]="[CLS]" , lowerCamelCase__ : Optional[int]="[SEP]" , lowerCamelCase__ : Any="[UNK]" , lowerCamelCase__ : Dict="[SEP]" , lowerCamelCase__ : Any="[PAD]" , lowerCamelCase__ : List[Any]="[CLS]" , lowerCamelCase__ : Tuple="[MASK]" , **lowerCamelCase__ : List[str] , ):
super().__init__(
do_lower_case=SCREAMING_SNAKE_CASE_ , remove_space=SCREAMING_SNAKE_CASE_ , keep_accents=SCREAMING_SNAKE_CASE_ , bos_token=SCREAMING_SNAKE_CASE_ , eos_token=SCREAMING_SNAKE_CASE_ , unk_token=SCREAMING_SNAKE_CASE_ , sep_token=SCREAMING_SNAKE_CASE_ , pad_token=SCREAMING_SNAKE_CASE_ , cls_token=SCREAMING_SNAKE_CASE_ , mask_token=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , )
a__ : List[str] = do_lower_case
a__ : Any = remove_space
a__ : Dict = keep_accents
a__ : int = vocab_file
a__ : List[Any] = spm.SentencePieceProcessor()
self.sp_model.Load(SCREAMING_SNAKE_CASE_ )
@property
def _UpperCamelCase( self : str ):
return len(self.sp_model )
def _UpperCamelCase( self : str ):
a__ : Optional[Any] = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE_ ): i for i in range(self.vocab_size )}
vocab.update(self.added_tokens_encoder )
return vocab
def __getstate__( self : int ):
a__ : Optional[int] = self.__dict__.copy()
a__ : List[Any] = None
return state
def __setstate__( self : Dict , lowerCamelCase__ : Union[str, Any] ):
a__ : str = d
a__ : Optional[Any] = spm.SentencePieceProcessor()
self.sp_model.Load(self.vocab_file )
def _UpperCamelCase( self : str , lowerCamelCase__ : int , lowerCamelCase__ : str=False ):
a__ : Optional[Any] = self.sp_model.EncodeAsPieces(SCREAMING_SNAKE_CASE_ )
return pieces
def _UpperCamelCase( self : List[str] , lowerCamelCase__ : str ):
return self.sp_model.PieceToId(SCREAMING_SNAKE_CASE_ )
def _UpperCamelCase( self : Optional[int] , lowerCamelCase__ : int ):
return self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE_ )
def _UpperCamelCase( self : Union[str, Any] , lowerCamelCase__ : List[str] ):
a__ : Optional[Any] = self.sp_model.decode_pieces(SCREAMING_SNAKE_CASE_ )
return out_string
def _UpperCamelCase( self : int , lowerCamelCase__ : int , lowerCamelCase__ : List[str] = None ):
a__ : int = [self.sep_token_id]
a__ : Union[str, Any] = [self.cls_token_id]
if token_ids_a is None:
return cls + token_ids_a + sep
return cls + token_ids_a + sep + token_ids_a + sep
def _UpperCamelCase( self : List[str] , lowerCamelCase__ : str , lowerCamelCase__ : Any = None , lowerCamelCase__ : Optional[int] = False ):
if already_has_special_tokens:
if token_ids_a is not None:
raise ValueError(
"You should not supply a second sequence if the provided sequence of "
"ids is already formatted with special tokens for the model." )
return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a]
if token_ids_a is not None:
return [1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1]
return [1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1]
def _UpperCamelCase( self : Tuple , lowerCamelCase__ : Tuple , lowerCamelCase__ : Optional[int] = None ):
a__ : Any = [self.sep_token_id]
a__ : int = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1]
def _UpperCamelCase( self : Dict , lowerCamelCase__ : List[Any] , lowerCamelCase__ : List[str] = None ):
if not os.path.isdir(SCREAMING_SNAKE_CASE_ ):
logger.error("Vocabulary path ({}) should be a directory".format(SCREAMING_SNAKE_CASE_ ) )
return
a__ : Tuple = os.path.join(
SCREAMING_SNAKE_CASE_ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] )
if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE_ ):
copyfile(self.vocab_file , SCREAMING_SNAKE_CASE_ )
return (out_vocab_file,)
| 37 |
# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer
from .base import PipelineTool
__snake_case = {
"""Acehnese Arabic""": """ace_Arab""",
"""Acehnese Latin""": """ace_Latn""",
"""Mesopotamian Arabic""": """acm_Arab""",
"""Ta'izzi-Adeni Arabic""": """acq_Arab""",
"""Tunisian Arabic""": """aeb_Arab""",
"""Afrikaans""": """afr_Latn""",
"""South Levantine Arabic""": """ajp_Arab""",
"""Akan""": """aka_Latn""",
"""Amharic""": """amh_Ethi""",
"""North Levantine Arabic""": """apc_Arab""",
"""Modern Standard Arabic""": """arb_Arab""",
"""Modern Standard Arabic Romanized""": """arb_Latn""",
"""Najdi Arabic""": """ars_Arab""",
"""Moroccan Arabic""": """ary_Arab""",
"""Egyptian Arabic""": """arz_Arab""",
"""Assamese""": """asm_Beng""",
"""Asturian""": """ast_Latn""",
"""Awadhi""": """awa_Deva""",
"""Central Aymara""": """ayr_Latn""",
"""South Azerbaijani""": """azb_Arab""",
"""North Azerbaijani""": """azj_Latn""",
"""Bashkir""": """bak_Cyrl""",
"""Bambara""": """bam_Latn""",
"""Balinese""": """ban_Latn""",
"""Belarusian""": """bel_Cyrl""",
"""Bemba""": """bem_Latn""",
"""Bengali""": """ben_Beng""",
"""Bhojpuri""": """bho_Deva""",
"""Banjar Arabic""": """bjn_Arab""",
"""Banjar Latin""": """bjn_Latn""",
"""Standard Tibetan""": """bod_Tibt""",
"""Bosnian""": """bos_Latn""",
"""Buginese""": """bug_Latn""",
"""Bulgarian""": """bul_Cyrl""",
"""Catalan""": """cat_Latn""",
"""Cebuano""": """ceb_Latn""",
"""Czech""": """ces_Latn""",
"""Chokwe""": """cjk_Latn""",
"""Central Kurdish""": """ckb_Arab""",
"""Crimean Tatar""": """crh_Latn""",
"""Welsh""": """cym_Latn""",
"""Danish""": """dan_Latn""",
"""German""": """deu_Latn""",
"""Southwestern Dinka""": """dik_Latn""",
"""Dyula""": """dyu_Latn""",
"""Dzongkha""": """dzo_Tibt""",
"""Greek""": """ell_Grek""",
"""English""": """eng_Latn""",
"""Esperanto""": """epo_Latn""",
"""Estonian""": """est_Latn""",
"""Basque""": """eus_Latn""",
"""Ewe""": """ewe_Latn""",
"""Faroese""": """fao_Latn""",
"""Fijian""": """fij_Latn""",
"""Finnish""": """fin_Latn""",
"""Fon""": """fon_Latn""",
"""French""": """fra_Latn""",
"""Friulian""": """fur_Latn""",
"""Nigerian Fulfulde""": """fuv_Latn""",
"""Scottish Gaelic""": """gla_Latn""",
"""Irish""": """gle_Latn""",
"""Galician""": """glg_Latn""",
"""Guarani""": """grn_Latn""",
"""Gujarati""": """guj_Gujr""",
"""Haitian Creole""": """hat_Latn""",
"""Hausa""": """hau_Latn""",
"""Hebrew""": """heb_Hebr""",
"""Hindi""": """hin_Deva""",
"""Chhattisgarhi""": """hne_Deva""",
"""Croatian""": """hrv_Latn""",
"""Hungarian""": """hun_Latn""",
"""Armenian""": """hye_Armn""",
"""Igbo""": """ibo_Latn""",
"""Ilocano""": """ilo_Latn""",
"""Indonesian""": """ind_Latn""",
"""Icelandic""": """isl_Latn""",
"""Italian""": """ita_Latn""",
"""Javanese""": """jav_Latn""",
"""Japanese""": """jpn_Jpan""",
"""Kabyle""": """kab_Latn""",
"""Jingpho""": """kac_Latn""",
"""Kamba""": """kam_Latn""",
"""Kannada""": """kan_Knda""",
"""Kashmiri Arabic""": """kas_Arab""",
"""Kashmiri Devanagari""": """kas_Deva""",
"""Georgian""": """kat_Geor""",
"""Central Kanuri Arabic""": """knc_Arab""",
"""Central Kanuri Latin""": """knc_Latn""",
"""Kazakh""": """kaz_Cyrl""",
"""Kabiyè""": """kbp_Latn""",
"""Kabuverdianu""": """kea_Latn""",
"""Khmer""": """khm_Khmr""",
"""Kikuyu""": """kik_Latn""",
"""Kinyarwanda""": """kin_Latn""",
"""Kyrgyz""": """kir_Cyrl""",
"""Kimbundu""": """kmb_Latn""",
"""Northern Kurdish""": """kmr_Latn""",
"""Kikongo""": """kon_Latn""",
"""Korean""": """kor_Hang""",
"""Lao""": """lao_Laoo""",
"""Ligurian""": """lij_Latn""",
"""Limburgish""": """lim_Latn""",
"""Lingala""": """lin_Latn""",
"""Lithuanian""": """lit_Latn""",
"""Lombard""": """lmo_Latn""",
"""Latgalian""": """ltg_Latn""",
"""Luxembourgish""": """ltz_Latn""",
"""Luba-Kasai""": """lua_Latn""",
"""Ganda""": """lug_Latn""",
"""Luo""": """luo_Latn""",
"""Mizo""": """lus_Latn""",
"""Standard Latvian""": """lvs_Latn""",
"""Magahi""": """mag_Deva""",
"""Maithili""": """mai_Deva""",
"""Malayalam""": """mal_Mlym""",
"""Marathi""": """mar_Deva""",
"""Minangkabau Arabic """: """min_Arab""",
"""Minangkabau Latin""": """min_Latn""",
"""Macedonian""": """mkd_Cyrl""",
"""Plateau Malagasy""": """plt_Latn""",
"""Maltese""": """mlt_Latn""",
"""Meitei Bengali""": """mni_Beng""",
"""Halh Mongolian""": """khk_Cyrl""",
"""Mossi""": """mos_Latn""",
"""Maori""": """mri_Latn""",
"""Burmese""": """mya_Mymr""",
"""Dutch""": """nld_Latn""",
"""Norwegian Nynorsk""": """nno_Latn""",
"""Norwegian Bokmål""": """nob_Latn""",
"""Nepali""": """npi_Deva""",
"""Northern Sotho""": """nso_Latn""",
"""Nuer""": """nus_Latn""",
"""Nyanja""": """nya_Latn""",
"""Occitan""": """oci_Latn""",
"""West Central Oromo""": """gaz_Latn""",
"""Odia""": """ory_Orya""",
"""Pangasinan""": """pag_Latn""",
"""Eastern Panjabi""": """pan_Guru""",
"""Papiamento""": """pap_Latn""",
"""Western Persian""": """pes_Arab""",
"""Polish""": """pol_Latn""",
"""Portuguese""": """por_Latn""",
"""Dari""": """prs_Arab""",
"""Southern Pashto""": """pbt_Arab""",
"""Ayacucho Quechua""": """quy_Latn""",
"""Romanian""": """ron_Latn""",
"""Rundi""": """run_Latn""",
"""Russian""": """rus_Cyrl""",
"""Sango""": """sag_Latn""",
"""Sanskrit""": """san_Deva""",
"""Santali""": """sat_Olck""",
"""Sicilian""": """scn_Latn""",
"""Shan""": """shn_Mymr""",
"""Sinhala""": """sin_Sinh""",
"""Slovak""": """slk_Latn""",
"""Slovenian""": """slv_Latn""",
"""Samoan""": """smo_Latn""",
"""Shona""": """sna_Latn""",
"""Sindhi""": """snd_Arab""",
"""Somali""": """som_Latn""",
"""Southern Sotho""": """sot_Latn""",
"""Spanish""": """spa_Latn""",
"""Tosk Albanian""": """als_Latn""",
"""Sardinian""": """srd_Latn""",
"""Serbian""": """srp_Cyrl""",
"""Swati""": """ssw_Latn""",
"""Sundanese""": """sun_Latn""",
"""Swedish""": """swe_Latn""",
"""Swahili""": """swh_Latn""",
"""Silesian""": """szl_Latn""",
"""Tamil""": """tam_Taml""",
"""Tatar""": """tat_Cyrl""",
"""Telugu""": """tel_Telu""",
"""Tajik""": """tgk_Cyrl""",
"""Tagalog""": """tgl_Latn""",
"""Thai""": """tha_Thai""",
"""Tigrinya""": """tir_Ethi""",
"""Tamasheq Latin""": """taq_Latn""",
"""Tamasheq Tifinagh""": """taq_Tfng""",
"""Tok Pisin""": """tpi_Latn""",
"""Tswana""": """tsn_Latn""",
"""Tsonga""": """tso_Latn""",
"""Turkmen""": """tuk_Latn""",
"""Tumbuka""": """tum_Latn""",
"""Turkish""": """tur_Latn""",
"""Twi""": """twi_Latn""",
"""Central Atlas Tamazight""": """tzm_Tfng""",
"""Uyghur""": """uig_Arab""",
"""Ukrainian""": """ukr_Cyrl""",
"""Umbundu""": """umb_Latn""",
"""Urdu""": """urd_Arab""",
"""Northern Uzbek""": """uzn_Latn""",
"""Venetian""": """vec_Latn""",
"""Vietnamese""": """vie_Latn""",
"""Waray""": """war_Latn""",
"""Wolof""": """wol_Latn""",
"""Xhosa""": """xho_Latn""",
"""Eastern Yiddish""": """ydd_Hebr""",
"""Yoruba""": """yor_Latn""",
"""Yue Chinese""": """yue_Hant""",
"""Chinese Simplified""": """zho_Hans""",
"""Chinese Traditional""": """zho_Hant""",
"""Standard Malay""": """zsm_Latn""",
"""Zulu""": """zul_Latn""",
}
class UpperCAmelCase_ ( lowercase ):
"""simple docstring"""
UpperCamelCase_ : Optional[Any] ='facebook/nllb-200-distilled-600M'
UpperCamelCase_ : Optional[Any] =(
'This is a tool that translates text from a language to another. It takes three inputs: `text`, which should '
'be the text to translate, `src_lang`, which should be the language of the text to translate and `tgt_lang`, '
'which should be the language for the desired ouput language. Both `src_lang` and `tgt_lang` are written in '
'plain English, such as \'Romanian\', or \'Albanian\'. It returns the text translated in `tgt_lang`.'
)
UpperCamelCase_ : Dict ='translator'
UpperCamelCase_ : Any =AutoTokenizer
UpperCamelCase_ : Optional[Any] =AutoModelForSeqaSeqLM
UpperCamelCase_ : List[Any] =LANGUAGE_CODES
UpperCamelCase_ : int =['text', 'text', 'text']
UpperCamelCase_ : Union[str, Any] =['text']
def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> str:
if src_lang not in self.lang_to_code:
raise ValueError(F'''{src_lang} is not a supported language.''' )
if tgt_lang not in self.lang_to_code:
raise ValueError(F'''{tgt_lang} is not a supported language.''' )
UpperCamelCase :Optional[int] = self.lang_to_code[src_lang]
UpperCamelCase :Union[str, Any] = self.lang_to_code[tgt_lang]
return self.pre_processor._build_translation_inputs(
SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' , src_lang=SCREAMING_SNAKE_CASE_ , tgt_lang=SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ ) -> Optional[Any]:
return self.model.generate(**SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ ) -> int:
return self.post_processor.decode(outputs[0].tolist() , skip_special_tokens=SCREAMING_SNAKE_CASE_ )
| 658 | 0 |
from typing import Dict, List, Optional
from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging
a__ = logging.get_logger(__name__)
a__ = {
'''nielsr/canine-s''': 2048,
}
# Unicode defines 1,114,112 total “codepoints”
a__ = 111_4112
# Below: Constants defining canonical codepoints for special, pseudo-characters.
# Copied from https://github.com/google-research/language/blob/master/language/canine/special_codepoints.py
a__ = 0
a__ = 0xe000
a__ = 0xe001
a__ = 0xe002
a__ = 0xe003
a__ = 0xe004
# Maps special codepoints to human-readable names.
a__ = {
# Special symbols are represented using codepoints values that are valid,
# but designated as "Private Use", meaning that they will never be assigned
# characters by the Unicode Consortium, and are thus safe for use here.
#
# NOTE: Do *NOT* add any sort of [UNK_CHAR] here. They are explicitly
# excluded and should fail with a hard error.
CLS: '''[CLS]''',
SEP: '''[SEP]''',
BOS: '''[BOS]''',
MASK: '''[MASK]''',
PAD: '''[PAD]''',
RESERVED: '''[RESERVED]''',
}
# Maps special codepoint human-readable names to their codepoint values.
a__ = {name: codepoint for codepoint, name in SPECIAL_CODEPOINTS.items()}
class SCREAMING_SNAKE_CASE_ ( _UpperCamelCase ):
"""simple docstring"""
__magic_name__ : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
def __init__( self : Tuple , lowerCAmelCase : Tuple=chr(SCREAMING_SNAKE_CASE_ ) , lowerCAmelCase : List[Any]=chr(SCREAMING_SNAKE_CASE_ ) , lowerCAmelCase : Union[str, Any]=chr(SCREAMING_SNAKE_CASE_ ) , lowerCAmelCase : Optional[int]=chr(SCREAMING_SNAKE_CASE_ ) , lowerCAmelCase : Any=chr(SCREAMING_SNAKE_CASE_ ) , lowerCAmelCase : Optional[int]=chr(SCREAMING_SNAKE_CASE_ ) , lowerCAmelCase : Optional[Any]=False , lowerCAmelCase : Optional[Any]=2048 , **lowerCAmelCase : List[str] , ) -> List[str]:
"""simple docstring"""
__UpperCamelCase : Optional[int] = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else bos_token
__UpperCamelCase : Any = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else eos_token
__UpperCamelCase : Optional[int] = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else sep_token
__UpperCamelCase : int = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else cls_token
__UpperCamelCase : Tuple = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else pad_token
# Mask token behave like a normal word, i.e. include the space before it
__UpperCamelCase : Union[str, Any] = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else mask_token
super().__init__(
bos_token=SCREAMING_SNAKE_CASE_ , eos_token=SCREAMING_SNAKE_CASE_ , sep_token=SCREAMING_SNAKE_CASE_ , cls_token=SCREAMING_SNAKE_CASE_ , pad_token=SCREAMING_SNAKE_CASE_ , mask_token=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , model_max_length=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , )
# Creates a mapping for looking up the IDs of special symbols.
__UpperCamelCase : Dict[str, int] = {}
for codepoint, name in SPECIAL_CODEPOINTS.items():
__UpperCamelCase : int = codepoint
# Creates a mapping for looking up the string forms of special symbol IDs.
__UpperCamelCase : Dict[int, str] = {
codepoint: name for name, codepoint in self._special_codepoints.items()
}
__UpperCamelCase : Tuple = UNICODE_VOCAB_SIZE
__UpperCamelCase : Union[str, Any] = len(self._special_codepoints )
@property
def lowerCamelCase__ ( self : List[str] ) -> int:
"""simple docstring"""
return self._unicode_vocab_size
def lowerCamelCase__ ( self : int , lowerCAmelCase : Optional[int] ) -> List[str]:
"""simple docstring"""
return list(SCREAMING_SNAKE_CASE_ )
def lowerCamelCase__ ( self : List[str] , lowerCAmelCase : Dict ) -> int:
"""simple docstring"""
try:
return ord(SCREAMING_SNAKE_CASE_ )
except TypeError:
raise ValueError(F'''invalid token: \'{token}\'''' )
def lowerCamelCase__ ( self : int , lowerCAmelCase : int ) -> str:
"""simple docstring"""
try:
if index in SPECIAL_CODEPOINTS:
return SPECIAL_CODEPOINTS[index]
return chr(SCREAMING_SNAKE_CASE_ )
except TypeError:
raise ValueError(F'''invalid id: {index}''' )
def lowerCamelCase__ ( self : List[str] , lowerCAmelCase : Dict ) -> List[Any]:
"""simple docstring"""
return "".join(SCREAMING_SNAKE_CASE_ )
def lowerCamelCase__ ( self : str , lowerCAmelCase : List[Any] , lowerCAmelCase : Optional[int] = None ) -> List[int]:
"""simple docstring"""
__UpperCamelCase : Dict = [self.sep_token_id]
__UpperCamelCase : Union[str, Any] = [self.cls_token_id]
__UpperCamelCase : Optional[Any] = cls + token_ids_a + sep
if token_ids_a is not None:
result += token_ids_a + sep
return result
def lowerCamelCase__ ( self : str , lowerCAmelCase : List[str] , lowerCAmelCase : Dict = None , lowerCAmelCase : Union[str, Any] = False ) -> List[int]:
"""simple docstring"""
if already_has_special_tokens:
return super().get_special_tokens_mask(
token_ids_a=SCREAMING_SNAKE_CASE_ , token_ids_a=SCREAMING_SNAKE_CASE_ , already_has_special_tokens=SCREAMING_SNAKE_CASE_ )
__UpperCamelCase : Union[str, Any] = [1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1]
if token_ids_a is not None:
result += ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1]
return result
def lowerCamelCase__ ( self : List[Any] , lowerCAmelCase : Optional[Any] , lowerCAmelCase : int = None ) -> List[int]:
"""simple docstring"""
__UpperCamelCase : int = [self.sep_token_id]
__UpperCamelCase : List[str] = [self.cls_token_id]
__UpperCamelCase : Optional[int] = len(cls + token_ids_a + sep ) * [0]
if token_ids_a is not None:
result += len(token_ids_a + sep ) * [1]
return result
def lowerCamelCase__ ( self : Union[str, Any] , lowerCAmelCase : int , lowerCAmelCase : Optional[Any] = None ) -> Optional[Any]:
"""simple docstring"""
return ()
| 279 |
from __future__ import annotations
# This is the precision for this function which can be altered.
# It is recommended for users to keep this number greater than or equal to 10.
__snake_case = 10
def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : int ):
for i in range(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
if array[i] == target:
return i
return -1
def _A ( SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : int ):
UpperCamelCase :Tuple = 0
UpperCamelCase :Dict = len(SCREAMING_SNAKE_CASE__ )
while left <= right:
if right - left < precision:
return lin_search(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
UpperCamelCase :Union[str, Any] = (left + right) // 3 + 1
UpperCamelCase :str = 2 * (left + right) // 3 + 1
if array[one_third] == target:
return one_third
elif array[two_third] == target:
return two_third
elif target < array[one_third]:
UpperCamelCase :int = one_third - 1
elif array[two_third] < target:
UpperCamelCase :Any = two_third + 1
else:
UpperCamelCase :Any = one_third + 1
UpperCamelCase :int = two_third - 1
else:
return -1
def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : int ):
if left < right:
if right - left < precision:
return lin_search(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
UpperCamelCase :Optional[Any] = (left + right) // 3 + 1
UpperCamelCase :Tuple = 2 * (left + right) // 3 + 1
if array[one_third] == target:
return one_third
elif array[two_third] == target:
return two_third
elif target < array[one_third]:
return rec_ternary_search(SCREAMING_SNAKE_CASE__ , one_third - 1 , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
elif array[two_third] < target:
return rec_ternary_search(two_third + 1 , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
else:
return rec_ternary_search(one_third + 1 , two_third - 1 , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
else:
return -1
if __name__ == "__main__":
import doctest
doctest.testmod()
__snake_case = input("""Enter numbers separated by comma:\n""").strip()
__snake_case = [int(item.strip()) for item in user_input.split(""",""")]
assert collection == sorted(collection), f"List must be ordered.\n{collection}."
__snake_case = int(input("""Enter the number to be found in the list:\n""").strip())
__snake_case = ite_ternary_search(collection, target)
__snake_case = rec_ternary_search(0, len(collection) - 1, collection, target)
if resulta != -1:
print(f'''Iterative search: {target} found at positions: {resulta}''')
print(f'''Recursive search: {target} found at positions: {resulta}''')
else:
print("""Not found""")
| 658 | 0 |
import argparse
import re
import torch
from CLAP import create_model
from transformers import AutoFeatureExtractor, ClapConfig, ClapModel
a_ : Any = {
'text_branch': 'text_model',
'audio_branch': 'audio_model.audio_encoder',
'attn': 'attention.self',
'self.proj': 'output.dense',
'attention.self_mask': 'attn_mask',
'mlp.fc1': 'intermediate.dense',
'mlp.fc2': 'output.dense',
'norm1': 'layernorm_before',
'norm2': 'layernorm_after',
'bn0': 'batch_norm',
}
a_ : Tuple = AutoFeatureExtractor.from_pretrained('laion/clap-htsat-unfused', truncation='rand_trunc')
def __lowercase( UpperCAmelCase__ , UpperCAmelCase__=False ):
"""simple docstring"""
lowerCamelCase = create_model(
"HTSAT-tiny" , "roberta" , SCREAMING_SNAKE_CASE__ , precision="fp32" , device="cuda:0" if torch.cuda.is_available() else "cpu" , enable_fusion=SCREAMING_SNAKE_CASE__ , fusion_type="aff_2d" if enable_fusion else None , )
return model, model_cfg
def __lowercase( UpperCAmelCase__ ):
"""simple docstring"""
lowerCamelCase = {}
lowerCamelCase = R'''.*sequential.(\d+).*'''
lowerCamelCase = R'''.*_projection.(\d+).*'''
for key, value in state_dict.items():
# check if any key needs to be modified
for key_to_modify, new_key in KEYS_TO_MODIFY_MAPPING.items():
if key_to_modify in key:
lowerCamelCase = key.replace(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
if re.match(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
# replace sequential layers with list
lowerCamelCase = re.match(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ).group(1 )
lowerCamelCase = key.replace(F"""sequential.{sequential_layer}.""" , F"""layers.{int(SCREAMING_SNAKE_CASE__ )//3}.linear.""" )
elif re.match(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
lowerCamelCase = int(re.match(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ).group(1 ) )
# Because in CLAP they use `nn.Sequential`...
lowerCamelCase = 1 if projecton_layer == 0 else 2
lowerCamelCase = key.replace(F"""_projection.{projecton_layer}.""" , F"""_projection.linear{transformers_projection_layer}.""" )
if "audio" and "qkv" in key:
# split qkv into query key and value
lowerCamelCase = value
lowerCamelCase = mixed_qkv.size(0 ) // 3
lowerCamelCase = mixed_qkv[:qkv_dim]
lowerCamelCase = mixed_qkv[qkv_dim : qkv_dim * 2]
lowerCamelCase = mixed_qkv[qkv_dim * 2 :]
lowerCamelCase = query_layer
lowerCamelCase = key_layer
lowerCamelCase = value_layer
else:
lowerCamelCase = value
return model_state_dict
def __lowercase( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__=False ):
"""simple docstring"""
lowerCamelCase = init_clap(SCREAMING_SNAKE_CASE__ , enable_fusion=SCREAMING_SNAKE_CASE__ )
clap_model.eval()
lowerCamelCase = clap_model.state_dict()
lowerCamelCase = rename_state_dict(SCREAMING_SNAKE_CASE__ )
lowerCamelCase = ClapConfig()
lowerCamelCase = enable_fusion
lowerCamelCase = ClapModel(SCREAMING_SNAKE_CASE__ )
# ignore the spectrogram embedding layer
model.load_state_dict(SCREAMING_SNAKE_CASE__ , strict=SCREAMING_SNAKE_CASE__ )
model.save_pretrained(SCREAMING_SNAKE_CASE__ )
transformers_config.save_pretrained(SCREAMING_SNAKE_CASE__ )
if __name__ == "__main__":
a_ : List[Any] = argparse.ArgumentParser()
parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.')
parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint')
parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert')
parser.add_argument('--enable_fusion', action='store_true', help='Whether to enable fusion or not')
a_ : Any = parser.parse_args()
convert_clap_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.enable_fusion) | 623 |
def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list ):
_enforce_args(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
if n == 0:
return 0
UpperCamelCase :Union[str, Any] = float('''-inf''' )
for i in range(1 , n + 1 ):
UpperCamelCase :str = max(
SCREAMING_SNAKE_CASE__ , prices[i - 1] + naive_cut_rod_recursive(n - i , SCREAMING_SNAKE_CASE__ ) )
return max_revue
def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list ):
_enforce_args(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
UpperCamelCase :Dict = [float('''-inf''' ) for _ in range(n + 1 )]
return _top_down_cut_rod_recursive(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list , SCREAMING_SNAKE_CASE__ : list ):
if max_rev[n] >= 0:
return max_rev[n]
elif n == 0:
return 0
else:
UpperCamelCase :Dict = float('''-inf''' )
for i in range(1 , n + 1 ):
UpperCamelCase :Union[str, Any] = max(
SCREAMING_SNAKE_CASE__ , prices[i - 1] + _top_down_cut_rod_recursive(n - i , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , )
UpperCamelCase :str = max_revenue
return max_rev[n]
def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list ):
_enforce_args(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
# length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of
# length 0.
UpperCamelCase :List[str] = [float('''-inf''' ) for _ in range(n + 1 )]
UpperCamelCase :Dict = 0
for i in range(1 , n + 1 ):
UpperCamelCase :Optional[Any] = max_rev[i]
for j in range(1 , i + 1 ):
UpperCamelCase :Optional[Any] = max(SCREAMING_SNAKE_CASE__ , prices[j - 1] + max_rev[i - j] )
UpperCamelCase :Tuple = max_revenue_i
return max_rev[n]
def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list ):
if n < 0:
UpperCamelCase :Any = F'''n must be greater than or equal to 0. Got n = {n}'''
raise ValueError(SCREAMING_SNAKE_CASE__ )
if n > len(SCREAMING_SNAKE_CASE__ ):
UpperCamelCase :Union[str, Any] = (
'''Each integral piece of rod must have a corresponding price. '''
F'''Got n = {n} but length of prices = {len(SCREAMING_SNAKE_CASE__ )}'''
)
raise ValueError(SCREAMING_SNAKE_CASE__ )
def _A ( ):
UpperCamelCase :Dict = [6, 10, 12, 15, 20, 23]
UpperCamelCase :List[str] = len(SCREAMING_SNAKE_CASE__ )
# the best revenue comes from cutting the rod into 6 pieces, each
# of length 1 resulting in a revenue of 6 * 6 = 36.
UpperCamelCase :str = 36
UpperCamelCase :int = top_down_cut_rod(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
UpperCamelCase :Union[str, Any] = bottom_up_cut_rod(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
UpperCamelCase :str = naive_cut_rod_recursive(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
assert expected_max_revenue == max_rev_top_down
assert max_rev_top_down == max_rev_bottom_up
assert max_rev_bottom_up == max_rev_naive
if __name__ == "__main__":
main()
| 658 | 0 |
'''simple docstring'''
import argparse
import torch
from transformers import FunnelBaseModel, FunnelConfig, FunnelModel, load_tf_weights_in_funnel
from transformers.utils import logging
logging.set_verbosity_info()
def __UpperCAmelCase ( SCREAMING_SNAKE_CASE__: Optional[int], SCREAMING_SNAKE_CASE__: Dict, SCREAMING_SNAKE_CASE__: List[str], SCREAMING_SNAKE_CASE__: Union[str, Any] ) -> Tuple:
"""simple docstring"""
# Initialise PyTorch model
__a = FunnelConfig.from_json_file(SCREAMING_SNAKE_CASE__ )
print(f"""Building PyTorch model from configuration: {config}""" )
__a = FunnelBaseModel(SCREAMING_SNAKE_CASE__ ) if base_model else FunnelModel(SCREAMING_SNAKE_CASE__ )
# Load weights from tf checkpoint
load_tf_weights_in_funnel(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ )
# Save pytorch-model
print(f"""Save PyTorch model to {pytorch_dump_path}""" )
torch.save(model.state_dict(), SCREAMING_SNAKE_CASE__ )
if __name__ == "__main__":
__UpperCamelCase : Optional[int] = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"""--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path."""
)
parser.add_argument(
"""--config_file""",
default=None,
type=str,
required=True,
help="""The config json file corresponding to the pre-trained model. \nThis specifies the model architecture.""",
)
parser.add_argument(
"""--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model."""
)
parser.add_argument(
"""--base_model""", action="""store_true""", help="""Whether you want just the base model (no decoder) or not."""
)
__UpperCamelCase : Tuple = parser.parse_args()
convert_tf_checkpoint_to_pytorch(
args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path, args.base_model
) | 448 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices
__snake_case = logging.get_logger(__name__)
__snake_case = {
"""microsoft/focalnet-tiny""": """https://huggingface.co/microsoft/focalnet-tiny/resolve/main/config.json""",
}
class UpperCAmelCase_ ( lowercase, lowercase ):
"""simple docstring"""
UpperCamelCase_ : int ='focalnet'
def __init__( self , SCREAMING_SNAKE_CASE_=224 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=96 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=[192, 384, 768, 768] , SCREAMING_SNAKE_CASE_=[2, 2, 6, 2] , SCREAMING_SNAKE_CASE_=[2, 2, 2, 2] , SCREAMING_SNAKE_CASE_=[3, 3, 3, 3] , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=4.0 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=1e-4 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=1e-5 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ , ) -> Dict:
super().__init__(**SCREAMING_SNAKE_CASE_ )
UpperCamelCase :List[Any] = image_size
UpperCamelCase :Dict = patch_size
UpperCamelCase :Tuple = num_channels
UpperCamelCase :int = embed_dim
UpperCamelCase :Optional[Any] = use_conv_embed
UpperCamelCase :str = hidden_sizes
UpperCamelCase :str = depths
UpperCamelCase :Optional[int] = focal_levels
UpperCamelCase :Tuple = focal_windows
UpperCamelCase :Optional[int] = hidden_act
UpperCamelCase :Optional[int] = mlp_ratio
UpperCamelCase :Optional[Any] = hidden_dropout_prob
UpperCamelCase :int = drop_path_rate
UpperCamelCase :Dict = use_layerscale
UpperCamelCase :List[str] = layerscale_value
UpperCamelCase :Tuple = use_post_layernorm
UpperCamelCase :int = use_post_layernorm_in_modulation
UpperCamelCase :str = normalize_modulator
UpperCamelCase :Any = initializer_range
UpperCamelCase :Optional[Any] = layer_norm_eps
UpperCamelCase :Dict = encoder_stride
UpperCamelCase :int = ['''stem'''] + [F'''stage{idx}''' for idx in range(1 , len(self.depths ) + 1 )]
UpperCamelCase , UpperCamelCase :int = get_aligned_output_features_output_indices(
out_features=SCREAMING_SNAKE_CASE_ , out_indices=SCREAMING_SNAKE_CASE_ , stage_names=self.stage_names )
| 658 | 0 |
import argparse
import logging
import os
import time
import timeit
import datasets
import numpy as np
import pycuda.autoinit # noqa: F401
import pycuda.driver as cuda
import tensorrt as trt
import torch
from absl import logging as absl_logging
from accelerate import Accelerator
from datasets import load_dataset, load_metric
from torch.utils.data import DataLoader
from utils_qa import postprocess_qa_predictions
import transformers
from transformers import AutoTokenizer, EvalPrediction, default_data_collator, set_seed
from transformers.trainer_pt_utils import nested_concat, nested_truncate
UpperCamelCase = trt.Logger(trt.Logger.WARNING)
UpperCamelCase = absl_logging.get_absl_logger()
absl_logger.setLevel(logging.WARNING)
UpperCamelCase = logging.getLogger(__name__)
UpperCamelCase = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'--onnx_model_path',
default=None,
type=str,
required=True,
help='Path to ONNX model: ',
)
parser.add_argument(
'--output_dir',
default=None,
type=str,
required=True,
help='The output directory where the model checkpoints and predictions will be written.',
)
# Other parameters
parser.add_argument(
'--tokenizer_name',
default='',
type=str,
required=True,
help='Pretrained tokenizer name or path if not the same as model_name',
)
parser.add_argument(
'--version_2_with_negative',
action='store_true',
help='If true, the SQuAD examples contain some that do not have an answer.',
)
parser.add_argument(
'--null_score_diff_threshold',
type=float,
default=0.0,
help='If null_score - best_non_null is greater than the threshold predict null.',
)
parser.add_argument(
'--max_seq_length',
default=384,
type=int,
help=(
'The maximum total input sequence length after WordPiece tokenization. Sequences '
'longer than this will be truncated, and sequences shorter than this will be padded.'
),
)
parser.add_argument(
'--doc_stride',
default=128,
type=int,
help='When splitting up a long document into chunks, how much stride to take between chunks.',
)
parser.add_argument('--per_device_eval_batch_size', default=8, type=int, help='Batch size per GPU/CPU for evaluation.')
parser.add_argument(
'--n_best_size',
default=20,
type=int,
help='The total number of n-best predictions to generate in the nbest_predictions.json output file.',
)
parser.add_argument(
'--max_answer_length',
default=30,
type=int,
help=(
'The maximum length of an answer that can be generated. This is needed because the start '
'and end predictions are not conditioned on one another.'
),
)
parser.add_argument('--seed', type=int, default=42, help='random seed for initialization')
parser.add_argument(
'--dataset_name',
type=str,
default=None,
required=True,
help='The name of the dataset to use (via the datasets library).',
)
parser.add_argument(
'--dataset_config_name',
type=str,
default=None,
help='The configuration name of the dataset to use (via the datasets library).',
)
parser.add_argument(
'--preprocessing_num_workers', type=int, default=4, help='A csv or a json file containing the training data.'
)
parser.add_argument('--overwrite_cache', action='store_true', help='Overwrite the cached training and evaluation sets')
parser.add_argument(
'--fp16',
action='store_true',
help='Whether to use 16-bit (mixed) precision instead of 32-bit',
)
parser.add_argument(
'--int8',
action='store_true',
help='Whether to use INT8',
)
UpperCamelCase = parser.parse_args()
if args.tokenizer_name:
UpperCamelCase = AutoTokenizer.from_pretrained(args.tokenizer_name, use_fast=True)
else:
raise ValueError(
'You are instantiating a new tokenizer from scratch. This is not supported by this script.'
'You can do it from another script, save it, and load it from here, using --tokenizer_name.'
)
logger.info('Training/evaluation parameters %s', args)
UpperCamelCase = args.per_device_eval_batch_size
UpperCamelCase = (args.eval_batch_size, args.max_seq_length)
# TRT Engine properties
UpperCamelCase = True
UpperCamelCase = 'temp_engine/bert-fp32.engine'
if args.fpaa:
UpperCamelCase = 'temp_engine/bert-fp16.engine'
if args.inta:
UpperCamelCase = 'temp_engine/bert-int8.engine'
# import ONNX file
if not os.path.exists('temp_engine'):
os.makedirs('temp_engine')
UpperCamelCase = 1 << (int)(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)
with trt.Builder(TRT_LOGGER) as builder, builder.create_network(EXPLICIT_BATCH) as network, trt.OnnxParser(
network, TRT_LOGGER
) as parser:
with open(args.onnx_model_path, 'rb') as model:
if not parser.parse(model.read()):
for error in range(parser.num_errors):
print(parser.get_error(error))
# Query input names and shapes from parsed TensorRT network
UpperCamelCase = [network.get_input(i) for i in range(network.num_inputs)]
UpperCamelCase = [_input.name for _input in network_inputs] # ex: ["actual_input1"]
with builder.create_builder_config() as config:
UpperCamelCase = 1 << 50
if STRICT_TYPES:
config.set_flag(trt.BuilderFlag.STRICT_TYPES)
if args.fpaa:
config.set_flag(trt.BuilderFlag.FPaa)
if args.inta:
config.set_flag(trt.BuilderFlag.INTa)
UpperCamelCase = builder.create_optimization_profile()
config.add_optimization_profile(profile)
for i in range(len(input_names)):
profile.set_shape(input_names[i], INPUT_SHAPE, INPUT_SHAPE, INPUT_SHAPE)
UpperCamelCase = builder.build_engine(network, config)
# serialize_engine and store in file (can be directly loaded and deserialized):
with open(engine_name, 'wb') as f:
f.write(engine.serialize())
def __lowerCamelCase ( __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : List[Any] , __lowerCAmelCase : int , __lowerCAmelCase : Tuple , __lowerCAmelCase : int , __lowerCAmelCase : Any , __lowerCAmelCase : Tuple , __lowerCAmelCase : str ) -> List[str]:
__UpperCamelCase : Tuple = np.asarray(inputs["""input_ids"""] , dtype=np.intaa )
__UpperCamelCase : Optional[int] = np.asarray(inputs["""attention_mask"""] , dtype=np.intaa )
__UpperCamelCase : Optional[Any] = np.asarray(inputs["""token_type_ids"""] , dtype=np.intaa )
# Copy inputs
cuda.memcpy_htod_async(d_inputs[0] , input_ids.ravel() , SCREAMING_SNAKE_CASE__ )
cuda.memcpy_htod_async(d_inputs[1] , attention_mask.ravel() , SCREAMING_SNAKE_CASE__ )
cuda.memcpy_htod_async(d_inputs[2] , token_type_ids.ravel() , SCREAMING_SNAKE_CASE__ )
# start time
__UpperCamelCase : Optional[Any] = time.time()
# Run inference
context.execute_async(
bindings=[int(SCREAMING_SNAKE_CASE__ ) for d_inp in d_inputs] + [int(SCREAMING_SNAKE_CASE__ ), int(SCREAMING_SNAKE_CASE__ )] , stream_handle=stream.handle )
# Transfer predictions back from GPU
cuda.memcpy_dtoh_async(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
cuda.memcpy_dtoh_async(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
# Synchronize the stream and take time
stream.synchronize()
# end time
__UpperCamelCase : int = time.time()
__UpperCamelCase : str = end_time - start_time
__UpperCamelCase : str = (h_outputa, h_outputa)
# print(outputs)
return outputs, infer_time
# Initialize the accelerator. We will let the accelerator handle device placement for us in this example.
UpperCamelCase = Accelerator()
# Make one log on every process with the configuration for debugging.
logging.basicConfig(
format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',
datefmt='%m/%d/%Y %H:%M:%S',
level=logging.INFO,
)
# Setup logging, we only want one process per machine to log things on the screen.
# accelerator.is_local_main_process is only True for one process per machine.
logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR)
if accelerator.is_local_main_process:
datasets.utils.logging.set_verbosity_warning()
transformers.utils.logging.set_verbosity_info()
else:
datasets.utils.logging.set_verbosity_error()
transformers.utils.logging.set_verbosity_error()
# If passed along, set the training seed now.
if args.seed is not None:
set_seed(args.seed)
# Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
# or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
# (the dataset will be downloaded automatically from the datasets Hub).
#
# For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
# 'text' is found. You can easily tweak this behavior (see below).
if args.dataset_name is not None:
# Downloading and loading a dataset from the hub.
UpperCamelCase = load_dataset(args.dataset_name, args.dataset_config_name)
else:
raise ValueError('Evaluation requires a dataset name')
# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
# https://huggingface.co/docs/datasets/loading_datasets.html.
# Preprocessing the datasets.
# Preprocessing is slighlty different for training and evaluation.
UpperCamelCase = raw_datasets['validation'].column_names
UpperCamelCase = 'question' if 'question' in column_names else column_names[0]
UpperCamelCase = 'context' if 'context' in column_names else column_names[1]
UpperCamelCase = 'answers' if 'answers' in column_names else column_names[2]
# Padding side determines if we do (question|context) or (context|question).
UpperCamelCase = tokenizer.padding_side == 'right'
if args.max_seq_length > tokenizer.model_max_length:
logger.warning(
F"""The max_seq_length passed ({args.max_seq_length}) is larger than the maximum length for the"""
F"""model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}."""
)
UpperCamelCase = min(args.max_seq_length, tokenizer.model_max_length)
def __lowerCamelCase ( __lowerCAmelCase : Union[str, Any] ) -> Optional[Any]:
# Some of the questions have lots of whitespace on the left, which is not useful and will make the
# truncation of the context fail (the tokenized question will take a lots of space). So we remove that
# left whitespace
__UpperCamelCase : Tuple = [q.lstrip() for q in examples[question_column_name]]
# Tokenize our examples with truncation and maybe padding, but keep the overflows using a stride. This results
# in one example possible giving several features when a context is long, each of those features having a
# context that overlaps a bit the context of the previous feature.
__UpperCamelCase : List[str] = tokenizer(
examples[question_column_name if pad_on_right else context_column_name] , examples[context_column_name if pad_on_right else question_column_name] , truncation="""only_second""" if pad_on_right else """only_first""" , max_length=SCREAMING_SNAKE_CASE__ , stride=args.doc_stride , return_overflowing_tokens=SCREAMING_SNAKE_CASE__ , return_offsets_mapping=SCREAMING_SNAKE_CASE__ , padding="""max_length""" , )
# Since one example might give us several features if it has a long context, we need a map from a feature to
# its corresponding example. This key gives us just that.
__UpperCamelCase : str = tokenized_examples.pop("""overflow_to_sample_mapping""" )
# For evaluation, we will need to convert our predictions to substrings of the context, so we keep the
# corresponding example_id and we will store the offset mappings.
__UpperCamelCase : Any = []
for i in range(len(tokenized_examples["""input_ids"""] ) ):
# Grab the sequence corresponding to that example (to know what is the context and what is the question).
__UpperCamelCase : List[Any] = tokenized_examples.sequence_ids(SCREAMING_SNAKE_CASE__ )
__UpperCamelCase : List[Any] = 1 if pad_on_right else 0
# One example can give several spans, this is the index of the example containing this span of text.
__UpperCamelCase : List[Any] = sample_mapping[i]
tokenized_examples["example_id"].append(examples["""id"""][sample_index] )
# Set to None the offset_mapping that are not part of the context so it's easy to determine if a token
# position is part of the context or not.
__UpperCamelCase : Optional[Any] = [
(o if sequence_ids[k] == context_index else None)
for k, o in enumerate(tokenized_examples["""offset_mapping"""][i] )
]
return tokenized_examples
UpperCamelCase = raw_datasets['validation']
# Validation Feature Creation
UpperCamelCase = eval_examples.map(
prepare_validation_features,
batched=True,
num_proc=args.preprocessing_num_workers,
remove_columns=column_names,
load_from_cache_file=not args.overwrite_cache,
desc='Running tokenizer on validation dataset',
)
UpperCamelCase = default_data_collator
UpperCamelCase = eval_dataset.remove_columns(['example_id', 'offset_mapping'])
UpperCamelCase = DataLoader(
eval_dataset_for_model, collate_fn=data_collator, batch_size=args.per_device_eval_batch_size
)
def __lowerCamelCase ( __lowerCAmelCase : Tuple , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : int , __lowerCAmelCase : Union[str, Any]="eval" ) -> Any:
# Post-processing: we match the start logits and end logits to answers in the original context.
__UpperCamelCase : Optional[int] = postprocess_qa_predictions(
examples=SCREAMING_SNAKE_CASE__ , features=SCREAMING_SNAKE_CASE__ , predictions=SCREAMING_SNAKE_CASE__ , version_2_with_negative=args.version_2_with_negative , n_best_size=args.n_best_size , max_answer_length=args.max_answer_length , null_score_diff_threshold=args.null_score_diff_threshold , output_dir=args.output_dir , prefix=SCREAMING_SNAKE_CASE__ , )
# Format the result to the format the metric expects.
if args.version_2_with_negative:
__UpperCamelCase : List[str] = [
{'''id''': k, '''prediction_text''': v, '''no_answer_probability''': 0.0} for k, v in predictions.items()
]
else:
__UpperCamelCase : int = [{'''id''': k, '''prediction_text''': v} for k, v in predictions.items()]
__UpperCamelCase : List[Any] = [{'''id''': ex['''id'''], '''answers''': ex[answer_column_name]} for ex in examples]
return EvalPrediction(predictions=SCREAMING_SNAKE_CASE__ , label_ids=SCREAMING_SNAKE_CASE__ )
UpperCamelCase = load_metric('squad_v2' if args.version_2_with_negative else 'squad')
# Evaluation!
logger.info('Loading ONNX model %s for evaluation', args.onnx_model_path)
with open(engine_name, 'rb') as f, trt.Runtime(TRT_LOGGER) as runtime, runtime.deserialize_cuda_engine(
f.read()
) as engine, engine.create_execution_context() as context:
# setup for TRT inferrence
for i in range(len(input_names)):
context.set_binding_shape(i, INPUT_SHAPE)
assert context.all_binding_shapes_specified
def __lowerCamelCase ( __lowerCAmelCase : Any ) -> Any:
return trt.volume(engine.get_binding_shape(SCREAMING_SNAKE_CASE__ ) ) * engine.get_binding_dtype(SCREAMING_SNAKE_CASE__ ).itemsize
# Allocate device memory for inputs and outputs.
UpperCamelCase = [cuda.mem_alloc(binding_nbytes(binding)) for binding in engine if engine.binding_is_input(binding)]
# Allocate output buffer
UpperCamelCase = cuda.pagelocked_empty(tuple(context.get_binding_shape(3)), dtype=np.floataa)
UpperCamelCase = cuda.pagelocked_empty(tuple(context.get_binding_shape(4)), dtype=np.floataa)
UpperCamelCase = cuda.mem_alloc(h_outputa.nbytes)
UpperCamelCase = cuda.mem_alloc(h_outputa.nbytes)
# Create a stream in which to copy inputs/outputs and run inference.
UpperCamelCase = cuda.Stream()
# Evaluation
logger.info('***** Running Evaluation *****')
logger.info(F""" Num examples = {len(eval_dataset)}""")
logger.info(F""" Batch size = {args.per_device_eval_batch_size}""")
UpperCamelCase = 0.0
UpperCamelCase = 0
UpperCamelCase = timeit.default_timer()
UpperCamelCase = None
for step, batch in enumerate(eval_dataloader):
UpperCamelCase , UpperCamelCase = model_infer(batch, context, d_inputs, h_outputa, h_outputa, d_outputa, d_outputa, stream)
total_time += infer_time
niter += 1
UpperCamelCase , UpperCamelCase = outputs
UpperCamelCase = torch.tensor(start_logits)
UpperCamelCase = torch.tensor(end_logits)
# necessary to pad predictions and labels for being gathered
UpperCamelCase = accelerator.pad_across_processes(start_logits, dim=1, pad_index=-100)
UpperCamelCase = accelerator.pad_across_processes(end_logits, dim=1, pad_index=-100)
UpperCamelCase = (accelerator.gather(start_logits).cpu().numpy(), accelerator.gather(end_logits).cpu().numpy())
UpperCamelCase = logits if all_preds is None else nested_concat(all_preds, logits, padding_index=-100)
if all_preds is not None:
UpperCamelCase = nested_truncate(all_preds, len(eval_dataset))
UpperCamelCase = timeit.default_timer() - start_time
logger.info(' Evaluation done in total %f secs (%f sec per example)', evalTime, evalTime / len(eval_dataset))
# Inference time from TRT
logger.info('Average Inference Time = {:.3f} ms'.format(total_time * 1000 / niter))
logger.info('Total Inference Time = {:.3f} ms'.format(total_time * 1000))
logger.info('Total Number of Inference = %d', niter)
UpperCamelCase = post_processing_function(eval_examples, eval_dataset, all_preds)
UpperCamelCase = metric.compute(predictions=prediction.predictions, references=prediction.label_ids)
logger.info(F"""Evaluation metrics: {eval_metric}""")
| 269 |
import inspect
import unittest
from transformers import DPTConfig
from transformers.file_utils import is_torch_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from torch import nn
from transformers import MODEL_MAPPING, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel
from transformers.models.dpt.modeling_dpt import DPT_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
from PIL import Image
from transformers import DPTImageProcessor
class UpperCAmelCase_ :
"""simple docstring"""
def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=[0, 1, 2, 3] , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=37 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=[1, 384, 24, 24] , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=None , ) -> int:
UpperCamelCase :Union[str, Any] = parent
UpperCamelCase :Tuple = batch_size
UpperCamelCase :Optional[Any] = image_size
UpperCamelCase :Any = patch_size
UpperCamelCase :List[str] = num_channels
UpperCamelCase :int = is_training
UpperCamelCase :str = use_labels
UpperCamelCase :Optional[Any] = hidden_size
UpperCamelCase :int = num_hidden_layers
UpperCamelCase :List[Any] = backbone_out_indices
UpperCamelCase :str = num_attention_heads
UpperCamelCase :Tuple = intermediate_size
UpperCamelCase :Optional[int] = hidden_act
UpperCamelCase :List[Any] = hidden_dropout_prob
UpperCamelCase :List[str] = attention_probs_dropout_prob
UpperCamelCase :Union[str, Any] = initializer_range
UpperCamelCase :List[Any] = num_labels
UpperCamelCase :int = backbone_featmap_shape
UpperCamelCase :Any = scope
UpperCamelCase :int = is_hybrid
# sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token)
UpperCamelCase :Dict = (image_size // patch_size) ** 2
UpperCamelCase :List[str] = num_patches + 1
def UpperCAmelCase ( self ) -> Union[str, Any]:
UpperCamelCase :List[str] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
UpperCamelCase :Tuple = None
if self.use_labels:
UpperCamelCase :Union[str, Any] = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels )
UpperCamelCase :Optional[int] = self.get_config()
return config, pixel_values, labels
def UpperCAmelCase ( self ) -> Dict:
UpperCamelCase :Any = {
'''global_padding''': '''same''',
'''layer_type''': '''bottleneck''',
'''depths''': [3, 4, 9],
'''out_features''': ['''stage1''', '''stage2''', '''stage3'''],
'''embedding_dynamic_padding''': True,
'''hidden_sizes''': [96, 192, 384, 768],
'''num_groups''': 2,
}
return DPTConfig(
image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , backbone_out_indices=self.backbone_out_indices , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=SCREAMING_SNAKE_CASE_ , initializer_range=self.initializer_range , is_hybrid=self.is_hybrid , backbone_config=SCREAMING_SNAKE_CASE_ , backbone_featmap_shape=self.backbone_featmap_shape , )
def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Tuple:
UpperCamelCase :List[str] = DPTModel(config=SCREAMING_SNAKE_CASE_ )
model.to(SCREAMING_SNAKE_CASE_ )
model.eval()
UpperCamelCase :Dict = model(SCREAMING_SNAKE_CASE_ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> str:
UpperCamelCase :Optional[Any] = self.num_labels
UpperCamelCase :Optional[int] = DPTForDepthEstimation(SCREAMING_SNAKE_CASE_ )
model.to(SCREAMING_SNAKE_CASE_ )
model.eval()
UpperCamelCase :Dict = model(SCREAMING_SNAKE_CASE_ )
self.parent.assertEqual(result.predicted_depth.shape , (self.batch_size, self.image_size, self.image_size) )
def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Dict:
UpperCamelCase :Optional[int] = self.num_labels
UpperCamelCase :int = DPTForSemanticSegmentation(SCREAMING_SNAKE_CASE_ )
model.to(SCREAMING_SNAKE_CASE_ )
model.eval()
UpperCamelCase :Dict = model(SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ )
self.parent.assertEqual(
result.logits.shape , (self.batch_size, self.num_labels, self.image_size, self.image_size) )
def UpperCAmelCase ( self ) -> Dict:
UpperCamelCase :Dict = self.prepare_config_and_inputs()
UpperCamelCase , UpperCamelCase , UpperCamelCase :List[Any] = config_and_inputs
UpperCamelCase :List[Any] = {'''pixel_values''': pixel_values}
return config, inputs_dict
@require_torch
class UpperCAmelCase_ ( lowercase, lowercase, unittest.TestCase ):
"""simple docstring"""
UpperCamelCase_ : Tuple =(DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else ()
UpperCamelCase_ : Tuple =(
{
'depth-estimation': DPTForDepthEstimation,
'feature-extraction': DPTModel,
'image-segmentation': DPTForSemanticSegmentation,
}
if is_torch_available()
else {}
)
UpperCamelCase_ : Tuple =False
UpperCamelCase_ : List[Any] =False
UpperCamelCase_ : Tuple =False
def UpperCAmelCase ( self ) -> Dict:
UpperCamelCase :Union[str, Any] = DPTModelTester(self )
UpperCamelCase :List[Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , has_text_modality=SCREAMING_SNAKE_CASE_ , hidden_size=37 )
def UpperCAmelCase ( self ) -> Tuple:
self.config_tester.run_common_tests()
@unittest.skip(reason='''DPT does not use inputs_embeds''' )
def UpperCAmelCase ( self ) -> int:
pass
def UpperCAmelCase ( self ) -> List[Any]:
UpperCamelCase , UpperCamelCase :Tuple = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
UpperCamelCase :int = model_class(SCREAMING_SNAKE_CASE_ )
self.assertIsInstance(model.get_input_embeddings() , (nn.Module) )
UpperCamelCase :int = model.get_output_embeddings()
self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE_ , nn.Linear ) )
def UpperCAmelCase ( self ) -> Optional[int]:
UpperCamelCase , UpperCamelCase :Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
UpperCamelCase :List[Any] = model_class(SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Optional[int] = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
UpperCamelCase :Optional[int] = [*signature.parameters.keys()]
UpperCamelCase :Tuple = ['''pixel_values''']
self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self ) -> Optional[int]:
UpperCamelCase :Any = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self ) -> Optional[int]:
UpperCamelCase :Union[str, Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_depth_estimation(*SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self ) -> Any:
UpperCamelCase :Union[str, Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_semantic_segmentation(*SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self ) -> List[str]:
for model_class in self.all_model_classes:
if model_class.__name__ == "DPTForDepthEstimation":
continue
UpperCamelCase , UpperCamelCase :Tuple = self.model_tester.prepare_config_and_inputs_for_common()
UpperCamelCase :Any = True
if model_class in get_values(SCREAMING_SNAKE_CASE_ ):
continue
UpperCamelCase :Dict = model_class(SCREAMING_SNAKE_CASE_ )
model.to(SCREAMING_SNAKE_CASE_ )
model.train()
UpperCamelCase :str = self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , return_labels=SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Optional[Any] = model(**SCREAMING_SNAKE_CASE_ ).loss
loss.backward()
def UpperCAmelCase ( self ) -> Tuple:
for model_class in self.all_model_classes:
if model_class.__name__ == "DPTForDepthEstimation":
continue
UpperCamelCase , UpperCamelCase :Any = self.model_tester.prepare_config_and_inputs_for_common()
UpperCamelCase :Optional[Any] = False
UpperCamelCase :List[Any] = True
if model_class in get_values(SCREAMING_SNAKE_CASE_ ) or not model_class.supports_gradient_checkpointing:
continue
UpperCamelCase :Optional[Any] = model_class(SCREAMING_SNAKE_CASE_ )
model.to(SCREAMING_SNAKE_CASE_ )
model.gradient_checkpointing_enable()
model.train()
UpperCamelCase :Union[str, Any] = self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , return_labels=SCREAMING_SNAKE_CASE_ )
UpperCamelCase :List[str] = model(**SCREAMING_SNAKE_CASE_ ).loss
loss.backward()
def UpperCAmelCase ( self ) -> List[str]:
UpperCamelCase , UpperCamelCase :Dict = self.model_tester.prepare_config_and_inputs_for_common()
UpperCamelCase :Optional[int] = _config_zero_init(SCREAMING_SNAKE_CASE_ )
for model_class in self.all_model_classes:
UpperCamelCase :Union[str, Any] = model_class(config=SCREAMING_SNAKE_CASE_ )
# Skip the check for the backbone
UpperCamelCase :Optional[int] = []
for name, module in model.named_modules():
if module.__class__.__name__ == "DPTViTHybridEmbeddings":
UpperCamelCase :Union[str, Any] = [F'''{name}.{key}''' for key in module.state_dict().keys()]
break
for name, param in model.named_parameters():
if param.requires_grad:
if name in backbone_params:
continue
self.assertIn(
((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=F'''Parameter {name} of model {model_class} seems not properly initialized''' , )
@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' )
def UpperCAmelCase ( self ) -> Any:
pass
@slow
def UpperCAmelCase ( self ) -> Optional[Any]:
for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]:
UpperCamelCase :Any = DPTModel.from_pretrained(SCREAMING_SNAKE_CASE_ )
self.assertIsNotNone(SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self ) -> Optional[int]:
# We do this test only for DPTForDepthEstimation since it is the only model that uses readout_type
UpperCamelCase , UpperCamelCase :Tuple = self.model_tester.prepare_config_and_inputs_for_common()
UpperCamelCase :Union[str, Any] = '''add'''
with self.assertRaises(SCREAMING_SNAKE_CASE_ ):
UpperCamelCase :Dict = DPTForDepthEstimation(SCREAMING_SNAKE_CASE_ )
def _A ( ):
UpperCamelCase :Union[str, Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
return image
@require_torch
@require_vision
@slow
class UpperCAmelCase_ ( unittest.TestCase ):
"""simple docstring"""
def UpperCAmelCase ( self ) -> Optional[Any]:
UpperCamelCase :List[Any] = DPTImageProcessor.from_pretrained('''Intel/dpt-hybrid-midas''' )
UpperCamelCase :List[str] = DPTForDepthEstimation.from_pretrained('''Intel/dpt-hybrid-midas''' ).to(SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Tuple = prepare_img()
UpperCamelCase :List[str] = image_processor(images=SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' ).to(SCREAMING_SNAKE_CASE_ )
# forward pass
with torch.no_grad():
UpperCamelCase :int = model(**SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Union[str, Any] = outputs.predicted_depth
# verify the predicted depth
UpperCamelCase :int = torch.Size((1, 384, 384) )
self.assertEqual(predicted_depth.shape , SCREAMING_SNAKE_CASE_ )
UpperCamelCase :int = torch.tensor(
[[[5.6437, 5.6146, 5.6511], [5.4371, 5.5649, 5.5958], [5.5215, 5.5184, 5.5293]]] ).to(SCREAMING_SNAKE_CASE_ )
self.assertTrue(torch.allclose(outputs.predicted_depth[:3, :3, :3] / 100 , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) )
| 658 | 0 |
import tempfile
import torch
from diffusers import IPNDMScheduler
from .test_schedulers import SchedulerCommonTest
class _A ( __lowercase ):
__a = (IPNDMScheduler,)
__a = (('num_inference_steps', 50),)
def UpperCAmelCase ( self , **_SCREAMING_SNAKE_CASE ):
_UpperCAmelCase = {'''num_train_timesteps''': 1000}
config.update(**SCREAMING_SNAKE_CASE_ )
return config
def UpperCAmelCase ( self , _SCREAMING_SNAKE_CASE=0 , **_SCREAMING_SNAKE_CASE ):
_UpperCAmelCase = dict(self.forward_default_kwargs )
_UpperCAmelCase = kwargs.pop("""num_inference_steps""" , SCREAMING_SNAKE_CASE_ )
_UpperCAmelCase = self.dummy_sample
_UpperCAmelCase = 0.1 * sample
_UpperCAmelCase = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05]
for scheduler_class in self.scheduler_classes:
_UpperCAmelCase = self.get_scheduler_config(**SCREAMING_SNAKE_CASE_ )
_UpperCAmelCase = scheduler_class(**SCREAMING_SNAKE_CASE_ )
scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ )
# copy over dummy past residuals
_UpperCAmelCase = dummy_past_residuals[:]
if time_step is None:
_UpperCAmelCase = scheduler.timesteps[len(scheduler.timesteps ) // 2]
with tempfile.TemporaryDirectory() as tmpdirname:
scheduler.save_config(SCREAMING_SNAKE_CASE_ )
_UpperCAmelCase = scheduler_class.from_pretrained(SCREAMING_SNAKE_CASE_ )
new_scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ )
# copy over dummy past residuals
_UpperCAmelCase = dummy_past_residuals[:]
_UpperCAmelCase = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample
_UpperCAmelCase = new_scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample
assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical"
_UpperCAmelCase = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample
_UpperCAmelCase = new_scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample
assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical"
def UpperCAmelCase ( self ):
pass
def UpperCAmelCase ( self , _SCREAMING_SNAKE_CASE=0 , **_SCREAMING_SNAKE_CASE ):
_UpperCAmelCase = dict(self.forward_default_kwargs )
_UpperCAmelCase = kwargs.pop("""num_inference_steps""" , SCREAMING_SNAKE_CASE_ )
_UpperCAmelCase = self.dummy_sample
_UpperCAmelCase = 0.1 * sample
_UpperCAmelCase = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05]
for scheduler_class in self.scheduler_classes:
_UpperCAmelCase = self.get_scheduler_config()
_UpperCAmelCase = scheduler_class(**SCREAMING_SNAKE_CASE_ )
scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ )
# copy over dummy past residuals (must be after setting timesteps)
_UpperCAmelCase = dummy_past_residuals[:]
if time_step is None:
_UpperCAmelCase = scheduler.timesteps[len(scheduler.timesteps ) // 2]
with tempfile.TemporaryDirectory() as tmpdirname:
scheduler.save_config(SCREAMING_SNAKE_CASE_ )
_UpperCAmelCase = scheduler_class.from_pretrained(SCREAMING_SNAKE_CASE_ )
# copy over dummy past residuals
new_scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ )
# copy over dummy past residual (must be after setting timesteps)
_UpperCAmelCase = dummy_past_residuals[:]
_UpperCAmelCase = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample
_UpperCAmelCase = new_scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample
assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical"
_UpperCAmelCase = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample
_UpperCAmelCase = new_scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample
assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical"
def UpperCAmelCase ( self , **_SCREAMING_SNAKE_CASE ):
_UpperCAmelCase = self.scheduler_classes[0]
_UpperCAmelCase = self.get_scheduler_config(**SCREAMING_SNAKE_CASE_ )
_UpperCAmelCase = scheduler_class(**SCREAMING_SNAKE_CASE_ )
_UpperCAmelCase = 10
_UpperCAmelCase = self.dummy_model()
_UpperCAmelCase = self.dummy_sample_deter
scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ )
for i, t in enumerate(scheduler.timesteps ):
_UpperCAmelCase = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
_UpperCAmelCase = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).prev_sample
for i, t in enumerate(scheduler.timesteps ):
_UpperCAmelCase = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
_UpperCAmelCase = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).prev_sample
return sample
def UpperCAmelCase ( self ):
_UpperCAmelCase = dict(self.forward_default_kwargs )
_UpperCAmelCase = kwargs.pop("""num_inference_steps""" , SCREAMING_SNAKE_CASE_ )
for scheduler_class in self.scheduler_classes:
_UpperCAmelCase = self.get_scheduler_config()
_UpperCAmelCase = scheduler_class(**SCREAMING_SNAKE_CASE_ )
_UpperCAmelCase = self.dummy_sample
_UpperCAmelCase = 0.1 * sample
if num_inference_steps is not None and hasattr(SCREAMING_SNAKE_CASE_ , """set_timesteps""" ):
scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ )
elif num_inference_steps is not None and not hasattr(SCREAMING_SNAKE_CASE_ , """set_timesteps""" ):
_UpperCAmelCase = num_inference_steps
# copy over dummy past residuals (must be done after set_timesteps)
_UpperCAmelCase = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05]
_UpperCAmelCase = dummy_past_residuals[:]
_UpperCAmelCase = scheduler.timesteps[5]
_UpperCAmelCase = scheduler.timesteps[6]
_UpperCAmelCase = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample
_UpperCAmelCase = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample
self.assertEqual(output_a.shape , sample.shape )
self.assertEqual(output_a.shape , output_a.shape )
_UpperCAmelCase = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample
_UpperCAmelCase = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample
self.assertEqual(output_a.shape , sample.shape )
self.assertEqual(output_a.shape , output_a.shape )
def UpperCAmelCase ( self ):
for timesteps in [100, 1000]:
self.check_over_configs(num_train_timesteps=SCREAMING_SNAKE_CASE_ , time_step=SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self ):
for t, num_inference_steps in zip([1, 5, 10] , [10, 50, 100] ):
self.check_over_forward(num_inference_steps=SCREAMING_SNAKE_CASE_ , time_step=SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self ):
_UpperCAmelCase = self.full_loop()
_UpperCAmelCase = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) )
assert abs(result_mean.item() - 254_0529 ) < 10 | 518 |
import argparse
import json
from pathlib import Path
import torch
import torchaudio
from datasets import load_dataset
from huggingface_hub import hf_hub_download
from transformers import ASTConfig, ASTFeatureExtractor, ASTForAudioClassification
from transformers.utils import logging
logging.set_verbosity_info()
__snake_case = logging.get_logger(__name__)
def _A ( SCREAMING_SNAKE_CASE__ : int ):
UpperCamelCase :Union[str, Any] = ASTConfig()
if "10-10" in model_name:
pass
elif "speech-commands" in model_name:
UpperCamelCase :Any = 128
elif "12-12" in model_name:
UpperCamelCase :Union[str, Any] = 12
UpperCamelCase :Any = 12
elif "14-14" in model_name:
UpperCamelCase :Optional[int] = 14
UpperCamelCase :List[str] = 14
elif "16-16" in model_name:
UpperCamelCase :List[Any] = 16
UpperCamelCase :Optional[Any] = 16
else:
raise ValueError('''Model not supported''' )
UpperCamelCase :Tuple = '''huggingface/label-files'''
if "speech-commands" in model_name:
UpperCamelCase :Optional[Any] = 35
UpperCamelCase :List[Any] = '''speech-commands-v2-id2label.json'''
else:
UpperCamelCase :Optional[int] = 527
UpperCamelCase :List[Any] = '''audioset-id2label.json'''
UpperCamelCase :Any = json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , repo_type='''dataset''' ) , '''r''' ) )
UpperCamelCase :List[str] = {int(SCREAMING_SNAKE_CASE__ ): v for k, v in idalabel.items()}
UpperCamelCase :List[Any] = idalabel
UpperCamelCase :List[Any] = {v: k for k, v in idalabel.items()}
return config
def _A ( SCREAMING_SNAKE_CASE__ : Optional[Any] ):
if "module.v" in name:
UpperCamelCase :Any = name.replace('''module.v''' , '''audio_spectrogram_transformer''' )
if "cls_token" in name:
UpperCamelCase :int = name.replace('''cls_token''' , '''embeddings.cls_token''' )
if "dist_token" in name:
UpperCamelCase :Tuple = name.replace('''dist_token''' , '''embeddings.distillation_token''' )
if "pos_embed" in name:
UpperCamelCase :Optional[int] = name.replace('''pos_embed''' , '''embeddings.position_embeddings''' )
if "patch_embed.proj" in name:
UpperCamelCase :str = name.replace('''patch_embed.proj''' , '''embeddings.patch_embeddings.projection''' )
# transformer blocks
if "blocks" in name:
UpperCamelCase :Any = name.replace('''blocks''' , '''encoder.layer''' )
if "attn.proj" in name:
UpperCamelCase :Union[str, Any] = name.replace('''attn.proj''' , '''attention.output.dense''' )
if "attn" in name:
UpperCamelCase :Union[str, Any] = name.replace('''attn''' , '''attention.self''' )
if "norm1" in name:
UpperCamelCase :str = name.replace('''norm1''' , '''layernorm_before''' )
if "norm2" in name:
UpperCamelCase :Tuple = name.replace('''norm2''' , '''layernorm_after''' )
if "mlp.fc1" in name:
UpperCamelCase :Dict = name.replace('''mlp.fc1''' , '''intermediate.dense''' )
if "mlp.fc2" in name:
UpperCamelCase :List[str] = name.replace('''mlp.fc2''' , '''output.dense''' )
# final layernorm
if "audio_spectrogram_transformer.norm" in name:
UpperCamelCase :Union[str, Any] = name.replace('''audio_spectrogram_transformer.norm''' , '''audio_spectrogram_transformer.layernorm''' )
# classifier head
if "module.mlp_head.0" in name:
UpperCamelCase :int = name.replace('''module.mlp_head.0''' , '''classifier.layernorm''' )
if "module.mlp_head.1" in name:
UpperCamelCase :Tuple = name.replace('''module.mlp_head.1''' , '''classifier.dense''' )
return name
def _A ( SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Any ):
for key in orig_state_dict.copy().keys():
UpperCamelCase :Dict = orig_state_dict.pop(SCREAMING_SNAKE_CASE__ )
if "qkv" in key:
UpperCamelCase :Any = key.split('''.''' )
UpperCamelCase :str = int(key_split[3] )
UpperCamelCase :Union[str, Any] = config.hidden_size
if "weight" in key:
UpperCamelCase :List[str] = val[:dim, :]
UpperCamelCase :Optional[Any] = val[dim : dim * 2, :]
UpperCamelCase :Optional[Any] = val[-dim:, :]
else:
UpperCamelCase :Dict = val[:dim]
UpperCamelCase :Optional[int] = val[dim : dim * 2]
UpperCamelCase :List[Any] = val[-dim:]
else:
UpperCamelCase :Union[str, Any] = val
return orig_state_dict
def _A ( SCREAMING_SNAKE_CASE__ : int ):
UpperCamelCase :List[str] = [
'''module.v.head.weight''',
'''module.v.head.bias''',
'''module.v.head_dist.weight''',
'''module.v.head_dist.bias''',
]
for k in ignore_keys:
state_dict.pop(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
@torch.no_grad()
def _A ( SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Any=False ):
UpperCamelCase :Optional[Any] = get_audio_spectrogram_transformer_config(SCREAMING_SNAKE_CASE__ )
UpperCamelCase :str = {
'''ast-finetuned-audioset-10-10-0.4593''': (
'''https://www.dropbox.com/s/ca0b1v2nlxzyeb4/audioset_10_10_0.4593.pth?dl=1'''
),
'''ast-finetuned-audioset-10-10-0.450''': (
'''https://www.dropbox.com/s/1tv0hovue1bxupk/audioset_10_10_0.4495.pth?dl=1'''
),
'''ast-finetuned-audioset-10-10-0.448''': (
'''https://www.dropbox.com/s/6u5sikl4b9wo4u5/audioset_10_10_0.4483.pth?dl=1'''
),
'''ast-finetuned-audioset-10-10-0.448-v2''': (
'''https://www.dropbox.com/s/kt6i0v9fvfm1mbq/audioset_10_10_0.4475.pth?dl=1'''
),
'''ast-finetuned-audioset-12-12-0.447''': (
'''https://www.dropbox.com/s/snfhx3tizr4nuc8/audioset_12_12_0.4467.pth?dl=1'''
),
'''ast-finetuned-audioset-14-14-0.443''': (
'''https://www.dropbox.com/s/z18s6pemtnxm4k7/audioset_14_14_0.4431.pth?dl=1'''
),
'''ast-finetuned-audioset-16-16-0.442''': (
'''https://www.dropbox.com/s/mdsa4t1xmcimia6/audioset_16_16_0.4422.pth?dl=1'''
),
'''ast-finetuned-speech-commands-v2''': (
'''https://www.dropbox.com/s/q0tbqpwv44pquwy/speechcommands_10_10_0.9812.pth?dl=1'''
),
}
# load original state_dict
UpperCamelCase :Optional[int] = model_name_to_url[model_name]
UpperCamelCase :Tuple = torch.hub.load_state_dict_from_url(SCREAMING_SNAKE_CASE__ , map_location='''cpu''' )
# remove some keys
remove_keys(SCREAMING_SNAKE_CASE__ )
# rename some keys
UpperCamelCase :Union[str, Any] = convert_state_dict(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
# load 🤗 model
UpperCamelCase :int = ASTForAudioClassification(SCREAMING_SNAKE_CASE__ )
model.eval()
model.load_state_dict(SCREAMING_SNAKE_CASE__ )
# verify outputs on dummy input
# source: https://github.com/YuanGongND/ast/blob/79e873b8a54d0a3b330dd522584ff2b9926cd581/src/run.py#L62
UpperCamelCase :Union[str, Any] = -4.2_67_73_93 if '''speech-commands''' not in model_name else -6.84_59_78
UpperCamelCase :List[str] = 4.5_68_99_74 if '''speech-commands''' not in model_name else 5.5_65_45_26
UpperCamelCase :Optional[Any] = 1024 if '''speech-commands''' not in model_name else 128
UpperCamelCase :int = ASTFeatureExtractor(mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ )
if "speech-commands" in model_name:
UpperCamelCase :Dict = load_dataset('''speech_commands''' , '''v0.02''' , split='''validation''' )
UpperCamelCase :List[Any] = dataset[0]['''audio''']['''array''']
else:
UpperCamelCase :List[Any] = hf_hub_download(
repo_id='''nielsr/audio-spectogram-transformer-checkpoint''' , filename='''sample_audio.flac''' , repo_type='''dataset''' , )
UpperCamelCase , UpperCamelCase :Dict = torchaudio.load(SCREAMING_SNAKE_CASE__ )
UpperCamelCase :List[str] = waveform.squeeze().numpy()
UpperCamelCase :Optional[int] = feature_extractor(SCREAMING_SNAKE_CASE__ , sampling_rate=16000 , return_tensors='''pt''' )
# forward pass
UpperCamelCase :List[str] = model(**SCREAMING_SNAKE_CASE__ )
UpperCamelCase :str = outputs.logits
if model_name == "ast-finetuned-audioset-10-10-0.4593":
UpperCamelCase :Tuple = torch.tensor([-0.87_60, -7.00_42, -8.66_02] )
elif model_name == "ast-finetuned-audioset-10-10-0.450":
UpperCamelCase :Union[str, Any] = torch.tensor([-1.19_86, -7.09_03, -8.27_18] )
elif model_name == "ast-finetuned-audioset-10-10-0.448":
UpperCamelCase :str = torch.tensor([-2.61_28, -8.00_80, -9.43_44] )
elif model_name == "ast-finetuned-audioset-10-10-0.448-v2":
UpperCamelCase :List[str] = torch.tensor([-1.50_80, -7.45_34, -8.89_17] )
elif model_name == "ast-finetuned-audioset-12-12-0.447":
UpperCamelCase :Dict = torch.tensor([-0.50_50, -6.58_33, -8.08_43] )
elif model_name == "ast-finetuned-audioset-14-14-0.443":
UpperCamelCase :List[str] = torch.tensor([-0.38_26, -7.03_36, -8.24_13] )
elif model_name == "ast-finetuned-audioset-16-16-0.442":
UpperCamelCase :Optional[int] = torch.tensor([-1.21_13, -6.91_01, -8.34_70] )
elif model_name == "ast-finetuned-speech-commands-v2":
UpperCamelCase :List[Any] = torch.tensor([6.15_89, -8.05_66, -8.79_84] )
else:
raise ValueError('''Unknown model name''' )
if not torch.allclose(logits[0, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ):
raise ValueError('''Logits don\'t match''' )
print('''Looks ok!''' )
if pytorch_dump_folder_path is not None:
Path(SCREAMING_SNAKE_CASE__ ).mkdir(exist_ok=SCREAMING_SNAKE_CASE__ )
print(F'''Saving model {model_name} to {pytorch_dump_folder_path}''' )
model.save_pretrained(SCREAMING_SNAKE_CASE__ )
print(F'''Saving feature extractor to {pytorch_dump_folder_path}''' )
feature_extractor.save_pretrained(SCREAMING_SNAKE_CASE__ )
if push_to_hub:
print('''Pushing model and feature extractor to the hub...''' )
model.push_to_hub(F'''MIT/{model_name}''' )
feature_extractor.push_to_hub(F'''MIT/{model_name}''' )
if __name__ == "__main__":
__snake_case = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"""--model_name""",
default="""ast-finetuned-audioset-10-10-0.4593""",
type=str,
help="""Name of the Audio Spectrogram Transformer model you'd like to convert.""",
)
parser.add_argument(
"""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory."""
)
parser.add_argument(
"""--push_to_hub""", action="""store_true""", help="""Whether or not to push the converted model to the 🤗 hub."""
)
__snake_case = parser.parse_args()
convert_audio_spectrogram_transformer_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
| 658 | 0 |
from __future__ import annotations
from fractions import Fraction
from math import gcd, sqrt
def _a ( a :int ) -> Tuple:
a = int(number**0.5 )
return number == sq * sq
def _a ( a :int , a :int , a :int , a :int , a :int , a :int ) -> Tuple:
a = x_num * y_den * z_den + y_num * x_den * z_den + z_num * x_den * y_den
a = x_den * y_den * z_den
a = gcd(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
top //= hcf
bottom //= hcf
return top, bottom
def _a ( a :int = 35 ) -> Tuple:
a = set()
a = 42
a = Fraction(0 )
a = 42
for x_num in range(1 , order + 1 ):
for x_den in range(x_num + 1 , order + 1 ):
for y_num in range(1 , order + 1 ):
for y_den in range(y_num + 1 , order + 1 ):
# n=1
a = x_num * y_den + x_den * y_num
a = x_den * y_den
a = gcd(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
z_num //= hcf
z_den //= hcf
if 0 < z_num < z_den <= order:
a = add_three(
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
unique_s.add(SCREAMING_SNAKE_CASE__ )
# n=2
a = (
x_num * x_num * y_den * y_den + x_den * x_den * y_num * y_num
)
a = x_den * x_den * y_den * y_den
if is_sq(SCREAMING_SNAKE_CASE__ ) and is_sq(SCREAMING_SNAKE_CASE__ ):
a = int(sqrt(SCREAMING_SNAKE_CASE__ ) )
a = int(sqrt(SCREAMING_SNAKE_CASE__ ) )
a = gcd(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
z_num //= hcf
z_den //= hcf
if 0 < z_num < z_den <= order:
a = add_three(
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
unique_s.add(SCREAMING_SNAKE_CASE__ )
# n=-1
a = x_num * y_num
a = x_den * y_num + x_num * y_den
a = gcd(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
z_num //= hcf
z_den //= hcf
if 0 < z_num < z_den <= order:
a = add_three(
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
unique_s.add(SCREAMING_SNAKE_CASE__ )
# n=2
a = x_num * x_num * y_num * y_num
a = (
x_den * x_den * y_num * y_num + x_num * x_num * y_den * y_den
)
if is_sq(SCREAMING_SNAKE_CASE__ ) and is_sq(SCREAMING_SNAKE_CASE__ ):
a = int(sqrt(SCREAMING_SNAKE_CASE__ ) )
a = int(sqrt(SCREAMING_SNAKE_CASE__ ) )
a = gcd(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
z_num //= hcf
z_den //= hcf
if 0 < z_num < z_den <= order:
a = add_three(
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
unique_s.add(SCREAMING_SNAKE_CASE__ )
for num, den in unique_s:
total += Fraction(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
return total.denominator + total.numerator
if __name__ == "__main__":
print(f"""{solution() = }""")
| 117 |
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_sentencepiece_available,
is_tokenizers_available,
is_torch_available,
)
__snake_case = {
"""configuration_llama""": ["""LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP""", """LlamaConfig"""],
}
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__snake_case = ["""LlamaTokenizer"""]
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__snake_case = ["""LlamaTokenizerFast"""]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__snake_case = [
"""LlamaForCausalLM""",
"""LlamaModel""",
"""LlamaPreTrainedModel""",
"""LlamaForSequenceClassification""",
]
if TYPE_CHECKING:
from .configuration_llama import LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP, LlamaConfig
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_llama import LlamaTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_llama_fast import LlamaTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_llama import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaPreTrainedModel
else:
import sys
__snake_case = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 658 | 0 |
import os
import shutil
import tempfile
from unittest import TestCase
from unittest.mock import patch
import numpy as np
from datasets import Dataset
from transformers.models.realm.configuration_realm import RealmConfig
from transformers.models.realm.retrieval_realm import _REALM_BLOCK_RECORDS_FILENAME, RealmRetriever
from transformers.models.realm.tokenization_realm import VOCAB_FILES_NAMES, RealmTokenizer
class lowercase__ ( UpperCamelCase_):
def __A ( self : Tuple ):
'''simple docstring'''
SCREAMING_SNAKE_CASE : Union[str, Any] = tempfile.mkdtemp()
SCREAMING_SNAKE_CASE : List[str] = 5
# Realm tok
SCREAMING_SNAKE_CASE : List[Any] = [
'''[UNK]''',
'''[CLS]''',
'''[SEP]''',
'''[PAD]''',
'''[MASK]''',
'''test''',
'''question''',
'''this''',
'''is''',
'''the''',
'''first''',
'''second''',
'''third''',
'''fourth''',
'''fifth''',
'''record''',
'''want''',
'''##want''',
'''##ed''',
'''wa''',
'''un''',
'''runn''',
'''##ing''',
''',''',
'''low''',
'''lowest''',
]
SCREAMING_SNAKE_CASE : Dict = os.path.join(self.tmpdirname , '''realm_tokenizer''' )
os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ )
SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.join(SCREAMING_SNAKE_CASE_ , VOCAB_FILES_NAMES['''vocab_file'''] )
with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer:
vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) )
SCREAMING_SNAKE_CASE : Any = os.path.join(self.tmpdirname , '''realm_block_records''' )
os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ )
def __A ( self : List[str] ):
'''simple docstring'''
return RealmTokenizer.from_pretrained(os.path.join(self.tmpdirname , '''realm_tokenizer''' ) )
def __A ( self : Optional[int] ):
'''simple docstring'''
shutil.rmtree(self.tmpdirname )
def __A ( self : List[Any] ):
'''simple docstring'''
SCREAMING_SNAKE_CASE : Union[str, Any] = RealmConfig(num_block_records=self.num_block_records )
return config
def __A ( self : List[Any] ):
'''simple docstring'''
SCREAMING_SNAKE_CASE : Tuple = Dataset.from_dict(
{
'''id''': ['''0''', '''1'''],
'''question''': ['''foo''', '''bar'''],
'''answers''': [['''Foo''', '''Bar'''], ['''Bar''']],
} )
return dataset
def __A ( self : str ):
'''simple docstring'''
SCREAMING_SNAKE_CASE : Optional[Any] = np.array(
[
B'''This is the first record''',
B'''This is the second record''',
B'''This is the third record''',
B'''This is the fourth record''',
B'''This is the fifth record''',
B'''This is a longer longer longer record''',
] , dtype=SCREAMING_SNAKE_CASE_ , )
return block_records
def __A ( self : List[str] ):
'''simple docstring'''
SCREAMING_SNAKE_CASE : Optional[int] = RealmRetriever(
block_records=self.get_dummy_block_records() , tokenizer=self.get_tokenizer() , )
return retriever
def __A ( self : int ):
'''simple docstring'''
SCREAMING_SNAKE_CASE : Optional[Any] = self.get_config()
SCREAMING_SNAKE_CASE : str = self.get_dummy_retriever()
SCREAMING_SNAKE_CASE : int = retriever.tokenizer
SCREAMING_SNAKE_CASE : Optional[Any] = np.array([0, 3] , dtype='''long''' )
SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer(['''Test question'''] ).input_ids
SCREAMING_SNAKE_CASE : Tuple = tokenizer(
['''the fourth'''] , add_special_tokens=SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , ).input_ids
SCREAMING_SNAKE_CASE : Optional[Any] = config.reader_seq_len
SCREAMING_SNAKE_CASE : str = retriever(
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , answer_ids=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , return_tensors='''np''' )
self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 2 )
self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 2 )
self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 2 )
self.assertEqual(concat_inputs.input_ids.shape , (2, 10) )
self.assertEqual(concat_inputs.attention_mask.shape , (2, 10) )
self.assertEqual(concat_inputs.token_type_ids.shape , (2, 10) )
self.assertEqual(concat_inputs.special_tokens_mask.shape , (2, 10) )
self.assertEqual(
tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[0] ) , ['''[CLS]''', '''test''', '''question''', '''[SEP]''', '''this''', '''is''', '''the''', '''first''', '''record''', '''[SEP]'''] , )
self.assertEqual(
tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[1] ) , ['''[CLS]''', '''test''', '''question''', '''[SEP]''', '''this''', '''is''', '''the''', '''fourth''', '''record''', '''[SEP]'''] , )
def __A ( self : Union[str, Any] ):
'''simple docstring'''
SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_config()
SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_dummy_retriever()
SCREAMING_SNAKE_CASE : Dict = retriever.tokenizer
SCREAMING_SNAKE_CASE : str = np.array([0, 3, 5] , dtype='''long''' )
SCREAMING_SNAKE_CASE : List[str] = tokenizer(['''Test question'''] ).input_ids
SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer(
['''the fourth''', '''longer longer'''] , add_special_tokens=SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , ).input_ids
SCREAMING_SNAKE_CASE : Any = config.reader_seq_len
SCREAMING_SNAKE_CASE : Any = retriever(
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , answer_ids=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , return_tensors='''np''' )
self.assertEqual([False, True, True] , SCREAMING_SNAKE_CASE_ )
self.assertEqual([[-1, -1, -1], [6, -1, -1], [6, 7, 8]] , SCREAMING_SNAKE_CASE_ )
self.assertEqual([[-1, -1, -1], [7, -1, -1], [7, 8, 9]] , SCREAMING_SNAKE_CASE_ )
def __A ( self : Optional[Any] ):
'''simple docstring'''
SCREAMING_SNAKE_CASE : str = self.get_dummy_retriever()
retriever.save_pretrained(os.path.join(self.tmpdirname , '''realm_block_records''' ) )
# Test local path
SCREAMING_SNAKE_CASE : List[str] = retriever.from_pretrained(os.path.join(self.tmpdirname , '''realm_block_records''' ) )
self.assertEqual(retriever.block_records[0] , B'''This is the first record''' )
# Test mocked remote path
with patch('''transformers.models.realm.retrieval_realm.hf_hub_download''' ) as mock_hf_hub_download:
SCREAMING_SNAKE_CASE : Tuple = os.path.join(
os.path.join(self.tmpdirname , '''realm_block_records''' ) , _REALM_BLOCK_RECORDS_FILENAME )
SCREAMING_SNAKE_CASE : List[Any] = RealmRetriever.from_pretrained('''google/realm-cc-news-pretrained-openqa''' )
self.assertEqual(retriever.block_records[0] , B'''This is the first record''' )
| 248 |
import math_equivalence # From: git+https://github.com/hendrycks/math.git
import datasets
__snake_case = """\
@article{hendrycksmath2021,
title={Measuring Mathematical Problem Solving With the MATH Dataset},
author={Dan Hendrycks
and Collin Burns
and Saurav Kadavath
and Akul Arora
and Steven Basart
and Eric Tang
and Dawn Song
and Jacob Steinhardt},
journal={arXiv preprint arXiv:2103.03874},
year={2021}
}
"""
__snake_case = """\
This metric is used to assess performance on the Mathematics Aptitude Test of Heuristics (MATH) dataset.
It first canonicalizes the inputs (e.g., converting \"1/2\" to \"\\frac{1}{2}\") and then computes accuracy.
"""
__snake_case = R"""
Calculates accuracy after canonicalizing inputs.
Args:
predictions: list of predictions to score. Each prediction
is a string that contains natural language and LaTex.
references: list of reference for each prediction. Each
reference is a string that contains natural language
and LaTex.
Returns:
accuracy: accuracy after canonicalizing inputs
(e.g., converting \"1/2\" to \"\\frac{1}{2}\")
Examples:
>>> metric = datasets.load_metric(\"competition_math\")
>>> results = metric.compute(references=[\"\\frac{1}{2}\"], predictions=[\"1/2\"])
>>> print(results)
{'accuracy': 1.0}
"""
@datasets.utils.file_utils.add_end_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION )
class UpperCAmelCase_ ( datasets.Metric ):
"""simple docstring"""
def UpperCAmelCase ( self ) -> Optional[Any]:
return datasets.MetricInfo(
description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(
{
'''predictions''': datasets.Value('''string''' ),
'''references''': datasets.Value('''string''' ),
} ) , homepage='''https://github.com/hendrycks/math''' , codebase_urls=['''https://github.com/hendrycks/math'''] , )
def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Any:
UpperCamelCase :Tuple = 0.0
for i, j in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ):
n_correct += 1.0 if math_equivalence.is_equiv(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else 0.0
UpperCamelCase :int = n_correct / len(SCREAMING_SNAKE_CASE_ )
return {
"accuracy": accuracy,
}
| 658 | 0 |
def __UpperCamelCase ( lowerCAmelCase__ : list ):
if len(SCREAMING_SNAKE_CASE__ ) <= 1:
return [tuple(SCREAMING_SNAKE_CASE__ )]
__a : int = []
def generate(lowerCAmelCase__ : int , lowerCAmelCase__ : list ):
__a : Optional[Any] = [0] * n
res.append(tuple(SCREAMING_SNAKE_CASE__ ) )
__a : Optional[int] = 0
while i < n:
if c[i] < i:
if i % 2 == 0:
__a : Optional[int] = arr[i], arr[0]
else:
__a : int = arr[i], arr[c[i]]
res.append(tuple(SCREAMING_SNAKE_CASE__ ) )
c[i] += 1
__a : List[str] = 0
else:
__a : Tuple = 0
i += 1
generate(len(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ )
return res
if __name__ == "__main__":
lowercase__ =input('Enter numbers separated by a comma:\n').strip()
lowercase__ =[int(item) for item in user_input.split(',')]
print(heaps(arr))
| 521 |
import argparse
import json
import logging
import os
import sys
from unittest.mock import patch
from transformers.testing_utils import TestCasePlus, get_gpu_count, slow
__snake_case = [
os.path.join(os.path.dirname(__file__), dirname)
for dirname in [
"""text-classification""",
"""language-modeling""",
"""summarization""",
"""token-classification""",
"""question-answering""",
]
]
sys.path.extend(SRC_DIRS)
if SRC_DIRS is not None:
import run_clm_flax
import run_flax_glue
import run_flax_ner
import run_mlm_flax
import run_qa
import run_summarization_flax
import run_ta_mlm_flax
logging.basicConfig(level=logging.DEBUG)
__snake_case = logging.getLogger()
def _A ( ):
UpperCamelCase :List[Any] = argparse.ArgumentParser()
parser.add_argument('''-f''' )
UpperCamelCase :Dict = parser.parse_args()
return args.f
def _A ( SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[int]="eval" ):
UpperCamelCase :Optional[Any] = os.path.join(SCREAMING_SNAKE_CASE__ , F'''{split}_results.json''' )
if os.path.exists(SCREAMING_SNAKE_CASE__ ):
with open(SCREAMING_SNAKE_CASE__ , '''r''' ) as f:
return json.load(SCREAMING_SNAKE_CASE__ )
raise ValueError(F'''can\'t find {path}''' )
__snake_case = logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)
class UpperCAmelCase_ ( lowercase ):
"""simple docstring"""
def UpperCAmelCase ( self ) -> List[Any]:
UpperCamelCase :Union[str, Any] = self.get_auto_remove_tmp_dir()
UpperCamelCase :Optional[Any] = F'''
run_glue.py
--model_name_or_path distilbert-base-uncased
--output_dir {tmp_dir}
--train_file ./tests/fixtures/tests_samples/MRPC/train.csv
--validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv
--per_device_train_batch_size=2
--per_device_eval_batch_size=1
--learning_rate=1e-4
--eval_steps=2
--warmup_steps=2
--seed=42
--max_seq_length=128
'''.split()
with patch.object(SCREAMING_SNAKE_CASE_ , '''argv''' , SCREAMING_SNAKE_CASE_ ):
run_flax_glue.main()
UpperCamelCase :Dict = get_results(SCREAMING_SNAKE_CASE_ )
self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75 )
@slow
def UpperCAmelCase ( self ) -> Union[str, Any]:
UpperCamelCase :int = self.get_auto_remove_tmp_dir()
UpperCamelCase :Optional[Any] = F'''
run_clm_flax.py
--model_name_or_path distilgpt2
--train_file ./tests/fixtures/sample_text.txt
--validation_file ./tests/fixtures/sample_text.txt
--do_train
--do_eval
--block_size 128
--per_device_train_batch_size 4
--per_device_eval_batch_size 4
--num_train_epochs 2
--logging_steps 2 --eval_steps 2
--output_dir {tmp_dir}
--overwrite_output_dir
'''.split()
with patch.object(SCREAMING_SNAKE_CASE_ , '''argv''' , SCREAMING_SNAKE_CASE_ ):
run_clm_flax.main()
UpperCamelCase :Any = get_results(SCREAMING_SNAKE_CASE_ )
self.assertLess(result['''eval_perplexity'''] , 100 )
@slow
def UpperCAmelCase ( self ) -> Tuple:
UpperCamelCase :Dict = self.get_auto_remove_tmp_dir()
UpperCamelCase :Any = F'''
run_summarization.py
--model_name_or_path t5-small
--train_file tests/fixtures/tests_samples/xsum/sample.json
--validation_file tests/fixtures/tests_samples/xsum/sample.json
--test_file tests/fixtures/tests_samples/xsum/sample.json
--output_dir {tmp_dir}
--overwrite_output_dir
--num_train_epochs=3
--warmup_steps=8
--do_train
--do_eval
--do_predict
--learning_rate=2e-4
--per_device_train_batch_size=2
--per_device_eval_batch_size=1
--predict_with_generate
'''.split()
with patch.object(SCREAMING_SNAKE_CASE_ , '''argv''' , SCREAMING_SNAKE_CASE_ ):
run_summarization_flax.main()
UpperCamelCase :str = get_results(SCREAMING_SNAKE_CASE_ , split='''test''' )
self.assertGreaterEqual(result['''test_rouge1'''] , 10 )
self.assertGreaterEqual(result['''test_rouge2'''] , 2 )
self.assertGreaterEqual(result['''test_rougeL'''] , 7 )
self.assertGreaterEqual(result['''test_rougeLsum'''] , 7 )
@slow
def UpperCAmelCase ( self ) -> Union[str, Any]:
UpperCamelCase :List[str] = self.get_auto_remove_tmp_dir()
UpperCamelCase :List[str] = F'''
run_mlm.py
--model_name_or_path distilroberta-base
--train_file ./tests/fixtures/sample_text.txt
--validation_file ./tests/fixtures/sample_text.txt
--output_dir {tmp_dir}
--overwrite_output_dir
--max_seq_length 128
--per_device_train_batch_size 4
--per_device_eval_batch_size 4
--logging_steps 2 --eval_steps 2
--do_train
--do_eval
--num_train_epochs=1
'''.split()
with patch.object(SCREAMING_SNAKE_CASE_ , '''argv''' , SCREAMING_SNAKE_CASE_ ):
run_mlm_flax.main()
UpperCamelCase :Dict = get_results(SCREAMING_SNAKE_CASE_ )
self.assertLess(result['''eval_perplexity'''] , 42 )
@slow
def UpperCAmelCase ( self ) -> Optional[int]:
UpperCamelCase :Optional[Any] = self.get_auto_remove_tmp_dir()
UpperCamelCase :int = F'''
run_t5_mlm_flax.py
--model_name_or_path t5-small
--train_file ./tests/fixtures/sample_text.txt
--validation_file ./tests/fixtures/sample_text.txt
--do_train
--do_eval
--max_seq_length 128
--per_device_train_batch_size 4
--per_device_eval_batch_size 4
--num_train_epochs 2
--logging_steps 2 --eval_steps 2
--output_dir {tmp_dir}
--overwrite_output_dir
'''.split()
with patch.object(SCREAMING_SNAKE_CASE_ , '''argv''' , SCREAMING_SNAKE_CASE_ ):
run_ta_mlm_flax.main()
UpperCamelCase :Any = get_results(SCREAMING_SNAKE_CASE_ )
self.assertGreaterEqual(result['''eval_accuracy'''] , 0.42 )
@slow
def UpperCAmelCase ( self ) -> Tuple:
# with so little data distributed training needs more epochs to get the score on par with 0/1 gpu
UpperCamelCase :Tuple = 7 if get_gpu_count() > 1 else 2
UpperCamelCase :int = self.get_auto_remove_tmp_dir()
UpperCamelCase :Optional[int] = F'''
run_flax_ner.py
--model_name_or_path bert-base-uncased
--train_file tests/fixtures/tests_samples/conll/sample.json
--validation_file tests/fixtures/tests_samples/conll/sample.json
--output_dir {tmp_dir}
--overwrite_output_dir
--do_train
--do_eval
--warmup_steps=2
--learning_rate=2e-4
--logging_steps 2 --eval_steps 2
--per_device_train_batch_size=2
--per_device_eval_batch_size=2
--num_train_epochs={epochs}
--seed 7
'''.split()
with patch.object(SCREAMING_SNAKE_CASE_ , '''argv''' , SCREAMING_SNAKE_CASE_ ):
run_flax_ner.main()
UpperCamelCase :Any = get_results(SCREAMING_SNAKE_CASE_ )
self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75 )
self.assertGreaterEqual(result['''eval_f1'''] , 0.3 )
@slow
def UpperCAmelCase ( self ) -> Any:
UpperCamelCase :List[str] = self.get_auto_remove_tmp_dir()
UpperCamelCase :Dict = F'''
run_qa.py
--model_name_or_path bert-base-uncased
--version_2_with_negative
--train_file tests/fixtures/tests_samples/SQUAD/sample.json
--validation_file tests/fixtures/tests_samples/SQUAD/sample.json
--output_dir {tmp_dir}
--overwrite_output_dir
--num_train_epochs=3
--warmup_steps=2
--do_train
--do_eval
--logging_steps 2 --eval_steps 2
--learning_rate=2e-4
--per_device_train_batch_size=2
--per_device_eval_batch_size=1
'''.split()
with patch.object(SCREAMING_SNAKE_CASE_ , '''argv''' , SCREAMING_SNAKE_CASE_ ):
run_qa.main()
UpperCamelCase :int = get_results(SCREAMING_SNAKE_CASE_ )
self.assertGreaterEqual(result['''eval_f1'''] , 30 )
self.assertGreaterEqual(result['''eval_exact'''] , 30 )
| 658 | 0 |
"""simple docstring"""
def __magic_name__ ( _lowerCamelCase: int ) -> int:
'''simple docstring'''
if number > 0:
raise ValueError('''input must be a negative integer''' )
lowerCAmelCase = len(bin(SCREAMING_SNAKE_CASE__ )[3:] )
lowerCAmelCase = bin(abs(SCREAMING_SNAKE_CASE__ ) - (1 << binary_number_length) )[3:]
lowerCAmelCase = (
(
'''1'''
+ '''0''' * (binary_number_length - len(SCREAMING_SNAKE_CASE__ ))
+ twos_complement_number
)
if number < 0
else '''0'''
)
return "0b" + twos_complement_number
if __name__ == "__main__":
import doctest
doctest.testmod()
| 535 |
from __future__ import annotations
from collections.abc import Callable
def _A ( SCREAMING_SNAKE_CASE__ : Callable[[int | float], int | float] , SCREAMING_SNAKE_CASE__ : int | float , SCREAMING_SNAKE_CASE__ : int | float , SCREAMING_SNAKE_CASE__ : int = 100 , ):
UpperCamelCase :Optional[Any] = x_start
UpperCamelCase :Any = fnc(SCREAMING_SNAKE_CASE__ )
UpperCamelCase :Optional[int] = 0.0
for _ in range(SCREAMING_SNAKE_CASE__ ):
# Approximates small segments of curve as linear and solve
# for trapezoidal area
UpperCamelCase :Any = (x_end - x_start) / steps + xa
UpperCamelCase :Dict = fnc(SCREAMING_SNAKE_CASE__ )
area += abs(fxa + fxa ) * (xa - xa) / 2
# Increment step
UpperCamelCase :Optional[int] = xa
UpperCamelCase :List[str] = fxa
return area
if __name__ == "__main__":
def _A ( SCREAMING_SNAKE_CASE__ : int ):
return x**3 + x**2
print("""f(x) = x^3 + x^2""")
print("""The area between the curve, x = -5, x = 5 and the x axis is:""")
__snake_case = 10
while i <= 10_00_00:
print(f'''with {i} steps: {trapezoidal_area(f, -5, 5, i)}''')
i *= 10
| 658 | 0 |
"""simple docstring"""
def __snake_case ( __A ,__A ) -> Optional[int]:
return x if y == 0 else greatest_common_divisor(SCREAMING_SNAKE_CASE__ ,x % y )
def __snake_case ( __A ,__A ) -> List[Any]:
return (x * y) // greatest_common_divisor(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ )
def __snake_case ( __A = 20 ) -> Dict:
lowercase : str = 1
for i in range(1 ,n + 1 ):
lowercase : str = lcm(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ )
return g
if __name__ == "__main__":
print(F'{solution() = }')
| 607 |
import torch
from diffusers import CMStochasticIterativeScheduler
from .test_schedulers import SchedulerCommonTest
class UpperCAmelCase_ ( lowercase ):
"""simple docstring"""
UpperCamelCase_ : Optional[int] =(CMStochasticIterativeScheduler,)
UpperCamelCase_ : Any =10
def UpperCAmelCase ( self , **SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]:
UpperCamelCase :str = {
'''num_train_timesteps''': 201,
'''sigma_min''': 0.002,
'''sigma_max''': 80.0,
}
config.update(**SCREAMING_SNAKE_CASE_ )
return config
def UpperCAmelCase ( self ) -> str:
UpperCamelCase :Optional[Any] = 10
UpperCamelCase :Optional[Any] = self.get_scheduler_config()
UpperCamelCase :Dict = self.scheduler_classes[0](**SCREAMING_SNAKE_CASE_ )
scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Any = scheduler.timesteps[0]
UpperCamelCase :Union[str, Any] = scheduler.timesteps[1]
UpperCamelCase :str = self.dummy_sample
UpperCamelCase :List[str] = 0.1 * sample
UpperCamelCase :List[str] = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).prev_sample
UpperCamelCase :str = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).prev_sample
self.assertEqual(output_a.shape , sample.shape )
self.assertEqual(output_a.shape , output_a.shape )
def UpperCAmelCase ( self ) -> List[str]:
for timesteps in [10, 50, 100, 1000]:
self.check_over_configs(num_train_timesteps=SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self ) -> Union[str, Any]:
for clip_denoised in [True, False]:
self.check_over_configs(clip_denoised=SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self ) -> List[Any]:
UpperCamelCase :List[Any] = self.scheduler_classes[0]
UpperCamelCase :List[Any] = self.get_scheduler_config()
UpperCamelCase :Optional[Any] = scheduler_class(**SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Dict = 1
scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Any = scheduler.timesteps
UpperCamelCase :Union[str, Any] = torch.manual_seed(0 )
UpperCamelCase :Union[str, Any] = self.dummy_model()
UpperCamelCase :List[Any] = self.dummy_sample_deter * scheduler.init_noise_sigma
for i, t in enumerate(SCREAMING_SNAKE_CASE_ ):
# 1. scale model input
UpperCamelCase :List[str] = scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# 2. predict noise residual
UpperCamelCase :Optional[int] = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# 3. predict previous sample x_t-1
UpperCamelCase :List[Any] = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ ).prev_sample
UpperCamelCase :Tuple = pred_prev_sample
UpperCamelCase :Any = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) )
UpperCamelCase :Union[str, Any] = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) )
assert abs(result_sum.item() - 192.7614 ) < 1e-2
assert abs(result_mean.item() - 0.2510 ) < 1e-3
def UpperCAmelCase ( self ) -> str:
UpperCamelCase :Dict = self.scheduler_classes[0]
UpperCamelCase :Optional[Any] = self.get_scheduler_config()
UpperCamelCase :Optional[Any] = scheduler_class(**SCREAMING_SNAKE_CASE_ )
UpperCamelCase :List[str] = [106, 0]
scheduler.set_timesteps(timesteps=SCREAMING_SNAKE_CASE_ )
UpperCamelCase :List[str] = scheduler.timesteps
UpperCamelCase :int = torch.manual_seed(0 )
UpperCamelCase :str = self.dummy_model()
UpperCamelCase :List[str] = self.dummy_sample_deter * scheduler.init_noise_sigma
for t in timesteps:
# 1. scale model input
UpperCamelCase :List[Any] = scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# 2. predict noise residual
UpperCamelCase :int = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# 3. predict previous sample x_t-1
UpperCamelCase :Optional[int] = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ ).prev_sample
UpperCamelCase :int = pred_prev_sample
UpperCamelCase :Tuple = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) )
UpperCamelCase :int = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) )
assert abs(result_sum.item() - 347.6357 ) < 1e-2
assert abs(result_mean.item() - 0.4527 ) < 1e-3
def UpperCAmelCase ( self ) -> Optional[Any]:
UpperCamelCase :List[str] = self.scheduler_classes[0]
UpperCamelCase :Tuple = self.get_scheduler_config()
UpperCamelCase :List[str] = scheduler_class(**SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Any = [39, 30, 12, 15, 0]
with self.assertRaises(SCREAMING_SNAKE_CASE_ , msg='''`timesteps` must be in descending order.''' ):
scheduler.set_timesteps(timesteps=SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self ) -> str:
UpperCamelCase :List[str] = self.scheduler_classes[0]
UpperCamelCase :List[Any] = self.get_scheduler_config()
UpperCamelCase :Optional[int] = scheduler_class(**SCREAMING_SNAKE_CASE_ )
UpperCamelCase :int = [39, 30, 12, 1, 0]
UpperCamelCase :Optional[Any] = len(SCREAMING_SNAKE_CASE_ )
with self.assertRaises(SCREAMING_SNAKE_CASE_ , msg='''Can only pass one of `num_inference_steps` or `timesteps`.''' ):
scheduler.set_timesteps(num_inference_steps=SCREAMING_SNAKE_CASE_ , timesteps=SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self ) -> str:
UpperCamelCase :Optional[int] = self.scheduler_classes[0]
UpperCamelCase :List[str] = self.get_scheduler_config()
UpperCamelCase :Dict = scheduler_class(**SCREAMING_SNAKE_CASE_ )
UpperCamelCase :List[Any] = [scheduler.config.num_train_timesteps]
with self.assertRaises(
SCREAMING_SNAKE_CASE_ , msg='''`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}''' , ):
scheduler.set_timesteps(timesteps=SCREAMING_SNAKE_CASE_ )
| 658 | 0 |
import random
def UpperCamelCase_ ( __a , __a , __a ) -> Union[str, Any]:
a__ : Dict = a[left_index]
a__ : Optional[int] = left_index + 1
for j in range(left_index + 1 , SCREAMING_SNAKE_CASE__ ):
if a[j] < pivot:
a__ : Optional[int] = a[i], a[j]
i += 1
a__ : str = a[i - 1], a[left_index]
return i - 1
def UpperCamelCase_ ( __a , __a , __a ) -> str:
if left < right:
a__ : List[str] = random.randint(SCREAMING_SNAKE_CASE__ , right - 1 )
a__ : List[Any] = (
a[left],
a[pivot],
) # switches the pivot with the left most bound
a__ : Dict = partition(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
quick_sort_random(
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # recursive quicksort to the left of the pivot point
quick_sort_random(
SCREAMING_SNAKE_CASE__ , pivot_index + 1 , SCREAMING_SNAKE_CASE__ ) # recursive quicksort to the right of the pivot point
def UpperCamelCase_ ( ) -> List[Any]:
a__ : Any = input("Enter numbers separated by a comma:\n" ).strip()
a__ : int = [int(SCREAMING_SNAKE_CASE__ ) for item in user_input.split("," )]
quick_sort_random(SCREAMING_SNAKE_CASE__ , 0 , len(SCREAMING_SNAKE_CASE__ ) )
print(SCREAMING_SNAKE_CASE__ )
if __name__ == "__main__":
main()
| 37 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available
__snake_case = {
"""configuration_groupvit""": [
"""GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP""",
"""GroupViTConfig""",
"""GroupViTOnnxConfig""",
"""GroupViTTextConfig""",
"""GroupViTVisionConfig""",
],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__snake_case = [
"""GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""GroupViTModel""",
"""GroupViTPreTrainedModel""",
"""GroupViTTextModel""",
"""GroupViTVisionModel""",
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__snake_case = [
"""TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""TFGroupViTModel""",
"""TFGroupViTPreTrainedModel""",
"""TFGroupViTTextModel""",
"""TFGroupViTVisionModel""",
]
if TYPE_CHECKING:
from .configuration_groupvit import (
GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP,
GroupViTConfig,
GroupViTOnnxConfig,
GroupViTTextConfig,
GroupViTVisionConfig,
)
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_groupvit import (
GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST,
GroupViTModel,
GroupViTPreTrainedModel,
GroupViTTextModel,
GroupViTVisionModel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_groupvit import (
TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST,
TFGroupViTModel,
TFGroupViTPreTrainedModel,
TFGroupViTTextModel,
TFGroupViTVisionModel,
)
else:
import sys
__snake_case = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 658 | 0 |
import warnings
from ...utils import logging
from .image_processing_poolformer import PoolFormerImageProcessor
a__ = logging.get_logger(__name__)
class SCREAMING_SNAKE_CASE_ ( _UpperCamelCase ):
"""simple docstring"""
def __init__( self : int , *lowerCAmelCase : List[str] , **lowerCAmelCase : Union[str, Any] ) -> None:
"""simple docstring"""
warnings.warn(
"""The class PoolFormerFeatureExtractor is deprecated and will be removed in version 5 of Transformers."""
""" Please use PoolFormerImageProcessor instead.""" , SCREAMING_SNAKE_CASE_ , )
super().__init__(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
| 279 |
import unittest
from pathlib import Path
from tempfile import NamedTemporaryFile, TemporaryDirectory
from transformers import BertConfig, BertTokenizerFast, FeatureExtractionPipeline
from transformers.convert_graph_to_onnx import (
convert,
ensure_valid_input,
generate_identified_filename,
infer_shapes,
quantize,
)
from transformers.testing_utils import require_tf, require_tokenizers, require_torch, slow
class UpperCAmelCase_ :
"""simple docstring"""
def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> List[str]:
return None
class UpperCAmelCase_ :
"""simple docstring"""
def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Tuple:
return None
class UpperCAmelCase_ ( unittest.TestCase ):
"""simple docstring"""
UpperCamelCase_ : Any =[
# (model_name, model_kwargs)
('bert-base-cased', {}),
('gpt2', {'use_cache': False}), # We don't support exporting GPT2 past keys anymore
]
@require_tf
@slow
def UpperCAmelCase ( self ) -> List[Any]:
for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
self._test_export(SCREAMING_SNAKE_CASE_ , '''tf''' , 12 , **SCREAMING_SNAKE_CASE_ )
@require_torch
@slow
def UpperCAmelCase ( self ) -> Optional[int]:
for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
self._test_export(SCREAMING_SNAKE_CASE_ , '''pt''' , 12 , **SCREAMING_SNAKE_CASE_ )
@require_torch
@slow
def UpperCAmelCase ( self ) -> int:
from transformers import BertModel
UpperCamelCase :int = ['''[UNK]''', '''[SEP]''', '''[CLS]''', '''[PAD]''', '''[MASK]''', '''some''', '''other''', '''words''']
with NamedTemporaryFile(mode='''w+t''' ) as vocab_file:
vocab_file.write('''\n'''.join(SCREAMING_SNAKE_CASE_ ) )
vocab_file.flush()
UpperCamelCase :Tuple = BertTokenizerFast(vocab_file.name )
with TemporaryDirectory() as bert_save_dir:
UpperCamelCase :Union[str, Any] = BertModel(BertConfig(vocab_size=len(SCREAMING_SNAKE_CASE_ ) ) )
model.save_pretrained(SCREAMING_SNAKE_CASE_ )
self._test_export(SCREAMING_SNAKE_CASE_ , '''pt''' , 12 , SCREAMING_SNAKE_CASE_ )
@require_tf
@slow
def UpperCAmelCase ( self ) -> str:
for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
UpperCamelCase :Tuple = self._test_export(SCREAMING_SNAKE_CASE_ , '''tf''' , 12 , **SCREAMING_SNAKE_CASE_ )
UpperCamelCase :List[Any] = quantize(Path(SCREAMING_SNAKE_CASE_ ) )
# Ensure the actual quantized model is not bigger than the original one
if quantized_path.stat().st_size >= Path(SCREAMING_SNAKE_CASE_ ).stat().st_size:
self.fail('''Quantized model is bigger than initial ONNX model''' )
@require_torch
@slow
def UpperCAmelCase ( self ) -> Optional[Any]:
for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
UpperCamelCase :str = self._test_export(SCREAMING_SNAKE_CASE_ , '''pt''' , 12 , **SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Any = quantize(SCREAMING_SNAKE_CASE_ )
# Ensure the actual quantized model is not bigger than the original one
if quantized_path.stat().st_size >= Path(SCREAMING_SNAKE_CASE_ ).stat().st_size:
self.fail('''Quantized model is bigger than initial ONNX model''' )
def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ ) -> Optional[Any]:
try:
# Compute path
with TemporaryDirectory() as tempdir:
UpperCamelCase :Union[str, Any] = Path(SCREAMING_SNAKE_CASE_ ).joinpath('''model.onnx''' )
# Remove folder if exists
if path.parent.exists():
path.parent.rmdir()
# Export
convert(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
return path
except Exception as e:
self.fail(SCREAMING_SNAKE_CASE_ )
@require_torch
@require_tokenizers
@slow
def UpperCAmelCase ( self ) -> List[str]:
from transformers import BertModel
UpperCamelCase :List[Any] = BertModel(BertConfig.from_pretrained('''lysandre/tiny-bert-random''' ) )
UpperCamelCase :int = BertTokenizerFast.from_pretrained('''lysandre/tiny-bert-random''' )
self._test_infer_dynamic_axis(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , '''pt''' )
@require_tf
@require_tokenizers
@slow
def UpperCAmelCase ( self ) -> List[Any]:
from transformers import TFBertModel
UpperCamelCase :Optional[Any] = TFBertModel(BertConfig.from_pretrained('''lysandre/tiny-bert-random''' ) )
UpperCamelCase :Optional[Any] = BertTokenizerFast.from_pretrained('''lysandre/tiny-bert-random''' )
self._test_infer_dynamic_axis(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , '''tf''' )
def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]:
UpperCamelCase :Tuple = FeatureExtractionPipeline(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Any = ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''output_0''', '''output_1''']
UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :List[Any] = infer_shapes(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# Assert all variables are present
self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , len(SCREAMING_SNAKE_CASE_ ) )
self.assertTrue(all(var_name in shapes for var_name in variable_names ) )
self.assertSequenceEqual(variable_names[:3] , SCREAMING_SNAKE_CASE_ )
self.assertSequenceEqual(variable_names[3:] , SCREAMING_SNAKE_CASE_ )
# Assert inputs are {0: batch, 1: sequence}
for var_name in ["input_ids", "token_type_ids", "attention_mask"]:
self.assertDictEqual(shapes[var_name] , {0: '''batch''', 1: '''sequence'''} )
# Assert outputs are {0: batch, 1: sequence} and {0: batch}
self.assertDictEqual(shapes['''output_0'''] , {0: '''batch''', 1: '''sequence'''} )
self.assertDictEqual(shapes['''output_1'''] , {0: '''batch'''} )
def UpperCAmelCase ( self ) -> int:
UpperCamelCase :int = ['''input_ids''', '''attention_mask''', '''token_type_ids''']
UpperCamelCase :Tuple = {'''input_ids''': [1, 2, 3, 4], '''attention_mask''': [0, 0, 0, 0], '''token_type_ids''': [1, 1, 1, 1]}
UpperCamelCase , UpperCamelCase :Any = ensure_valid_input(FuncContiguousArgs() , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# Should have exactly the same number of args (all are valid)
self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 3 )
# Should have exactly the same input names
self.assertEqual(set(SCREAMING_SNAKE_CASE_ ) , set(SCREAMING_SNAKE_CASE_ ) )
# Parameter should be reordered according to their respective place in the function:
# (input_ids, token_type_ids, attention_mask)
self.assertEqual(SCREAMING_SNAKE_CASE_ , (tokens['''input_ids'''], tokens['''token_type_ids'''], tokens['''attention_mask''']) )
# Generated args are interleaved with another args (for instance parameter "past" in GPT2)
UpperCamelCase , UpperCamelCase :Tuple = ensure_valid_input(FuncNonContiguousArgs() , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# Should have exactly the one arg (all before the one not provided "some_other_args")
self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 1 )
self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 1 )
# Should have only "input_ids"
self.assertEqual(inputs_args[0] , tokens['''input_ids'''] )
self.assertEqual(ordered_input_names[0] , '''input_ids''' )
def UpperCAmelCase ( self ) -> Union[str, Any]:
UpperCamelCase :str = generate_identified_filename(Path('''/home/something/my_fake_model.onnx''' ) , '''-test''' )
self.assertEqual('''/home/something/my_fake_model-test.onnx''' , generated.as_posix() )
| 658 | 0 |
import argparse
import pickle
import numpy as np
import torch
from torch import nn
from transformers import ReformerConfig, ReformerModelWithLMHead
from transformers.utils import logging
logging.set_verbosity_info()
def __lowercase( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__=None ):
"""simple docstring"""
assert torch_layer.weight.shape == weight.shape, F"""{torch_layer} layer.weight does not match"""
lowerCamelCase = nn.Parameter(SCREAMING_SNAKE_CASE__ )
if bias is not None:
assert torch_layer.bias.shape == bias.shape, F"""{torch_layer} layer.bias does not match"""
lowerCamelCase = nn.Parameter(SCREAMING_SNAKE_CASE__ )
def __lowercase( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ):
"""simple docstring"""
lowerCamelCase = np.asarray(weights[0] )
lowerCamelCase = np.asarray(weights[1] )
lowerCamelCase = np.asarray(weights[2] )
set_param(
torch_layer.self_attention.query_key , torch.tensor(SCREAMING_SNAKE_CASE__ ).transpose(1 , 2 ).contiguous().view(-1 , SCREAMING_SNAKE_CASE__ ) , )
set_param(
torch_layer.self_attention.value , torch.tensor(SCREAMING_SNAKE_CASE__ ).transpose(1 , 2 ).contiguous().view(-1 , SCREAMING_SNAKE_CASE__ ) , )
set_param(
torch_layer.output.dense , torch.tensor(SCREAMING_SNAKE_CASE__ ).view(-1 , SCREAMING_SNAKE_CASE__ ).contiguous().transpose(0 , 1 ) , )
def __lowercase( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ):
"""simple docstring"""
lowerCamelCase = np.asarray(weights[0] )
lowerCamelCase = np.asarray(weights[1] )
lowerCamelCase = np.asarray(weights[2] )
lowerCamelCase = np.asarray(weights[3] )
set_param(
torch_layer.self_attention.query , torch.tensor(SCREAMING_SNAKE_CASE__ ).transpose(1 , 2 ).contiguous().view(-1 , SCREAMING_SNAKE_CASE__ ) , )
set_param(
torch_layer.self_attention.key , torch.tensor(SCREAMING_SNAKE_CASE__ ).transpose(1 , 2 ).contiguous().view(-1 , SCREAMING_SNAKE_CASE__ ) , )
set_param(
torch_layer.self_attention.value , torch.tensor(SCREAMING_SNAKE_CASE__ ).transpose(1 , 2 ).contiguous().view(-1 , SCREAMING_SNAKE_CASE__ ) , )
set_param(
torch_layer.output.dense , torch.tensor(SCREAMING_SNAKE_CASE__ ).view(-1 , SCREAMING_SNAKE_CASE__ ).contiguous().transpose(0 , 1 ) , )
def __lowercase( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ):
"""simple docstring"""
lowerCamelCase = weights[0][0][0]
lowerCamelCase = np.asarray(layer_norm_a[0] )
lowerCamelCase = np.asarray(layer_norm_a[1] )
set_param(
torch_block.attention.layer_norm , torch.tensor(SCREAMING_SNAKE_CASE__ ) , torch.tensor(SCREAMING_SNAKE_CASE__ ) , )
# lsh weights + output
lowerCamelCase = weights[0][1]
if len(SCREAMING_SNAKE_CASE__ ) < 4:
set_layer_weights_in_torch_lsh(SCREAMING_SNAKE_CASE__ , torch_block.attention , SCREAMING_SNAKE_CASE__ )
else:
set_layer_weights_in_torch_local(SCREAMING_SNAKE_CASE__ , torch_block.attention , SCREAMING_SNAKE_CASE__ )
# intermediate weighs
lowerCamelCase = weights[2][0][1][2]
# Chunked Feed Forward
if len(SCREAMING_SNAKE_CASE__ ) == 4:
lowerCamelCase = intermediate_weights[2]
# layernorm 2
lowerCamelCase = np.asarray(intermediate_weights[0][0] )
lowerCamelCase = np.asarray(intermediate_weights[0][1] )
set_param(
torch_block.feed_forward.layer_norm , torch.tensor(SCREAMING_SNAKE_CASE__ ) , torch.tensor(SCREAMING_SNAKE_CASE__ ) , )
# intermediate dense
lowerCamelCase = np.asarray(intermediate_weights[1][0] )
lowerCamelCase = np.asarray(intermediate_weights[1][1] )
set_param(
torch_block.feed_forward.dense.dense , torch.tensor(SCREAMING_SNAKE_CASE__ ).transpose(0 , 1 ).contiguous() , torch.tensor(SCREAMING_SNAKE_CASE__ ) , )
# intermediate out
lowerCamelCase = np.asarray(intermediate_weights[4][0] )
lowerCamelCase = np.asarray(intermediate_weights[4][1] )
set_param(
torch_block.feed_forward.output.dense , torch.tensor(SCREAMING_SNAKE_CASE__ ).transpose(0 , 1 ).contiguous() , torch.tensor(SCREAMING_SNAKE_CASE__ ) , )
def __lowercase( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ):
"""simple docstring"""
lowerCamelCase = torch_model.reformer
# word embeds
lowerCamelCase = np.asarray(weights[1] )
set_param(
torch_model_reformer.embeddings.word_embeddings , torch.tensor(SCREAMING_SNAKE_CASE__ ) , )
if isinstance(weights[3] , SCREAMING_SNAKE_CASE__ ):
lowerCamelCase = torch_model_reformer.embeddings.position_embeddings
for emb_idx in range(len(position_embeddings.weights ) ):
lowerCamelCase = np.asarray(weights[3][emb_idx][0] )
assert (
position_embeddings.weights[emb_idx].shape == emb_weights.shape
), F"""{position_embeddings[emb_idx]} emb does not match"""
lowerCamelCase = nn.Parameter(torch.tensor(SCREAMING_SNAKE_CASE__ ) )
lowerCamelCase = weights[5]
assert len(torch_model_reformer.encoder.layers ) * 4 == len(
SCREAMING_SNAKE_CASE__ ), "HF and trax model do not have the same number of layers"
for layer_idx, layer in enumerate(torch_model_reformer.encoder.layers ):
lowerCamelCase = trax_layer_weights[4 * layer_idx : 4 * (layer_idx + 1)]
set_block_weights_in_torch(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
# output layer norm
lowerCamelCase = np.asarray(weights[7][0] )
lowerCamelCase = np.asarray(weights[7][1] )
set_param(
torch_model_reformer.encoder.layer_norm , torch.tensor(SCREAMING_SNAKE_CASE__ ) , torch.tensor(SCREAMING_SNAKE_CASE__ ) , )
# output embeddings
lowerCamelCase = np.asarray(weights[9][0] )
lowerCamelCase = np.asarray(weights[9][1] )
set_param(
torch_model.lm_head.decoder , torch.tensor(SCREAMING_SNAKE_CASE__ ).transpose(0 , 1 ).contiguous() , torch.tensor(SCREAMING_SNAKE_CASE__ ) , )
def __lowercase( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ):
"""simple docstring"""
lowerCamelCase = ReformerConfig.from_json_file(SCREAMING_SNAKE_CASE__ )
print(F"""Building PyTorch model from configuration: {config}""" )
lowerCamelCase = ReformerModelWithLMHead(SCREAMING_SNAKE_CASE__ )
with open(SCREAMING_SNAKE_CASE__ , "rb" ) as f:
lowerCamelCase = pickle.load(SCREAMING_SNAKE_CASE__ )['''weights''']
set_model_weights_in_torch(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , config.hidden_size )
# Save pytorch-model
print(F"""Save PyTorch model to {pytorch_dump_path}""" )
torch.save(model.state_dict() , SCREAMING_SNAKE_CASE__ )
if __name__ == "__main__":
a_ : Dict = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'--trax_model_pkl_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.'
)
parser.add_argument(
'--config_file',
default=None,
type=str,
required=True,
help=(
'The config json file corresponding to the pre-trained Reformer model. \n'
'This specifies the model architecture.'
),
)
parser.add_argument(
'--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.'
)
a_ : Any = parser.parse_args()
convert_trax_checkpoint_to_pytorch(args.trax_model_pkl_path, args.config_file, args.pytorch_dump_path) | 623 |
import os
import shutil
import tempfile
from unittest import TestCase
from unittest.mock import patch
import numpy as np
from datasets import Dataset
from transformers.models.realm.configuration_realm import RealmConfig
from transformers.models.realm.retrieval_realm import _REALM_BLOCK_RECORDS_FILENAME, RealmRetriever
from transformers.models.realm.tokenization_realm import VOCAB_FILES_NAMES, RealmTokenizer
class UpperCAmelCase_ ( lowercase ):
"""simple docstring"""
def UpperCAmelCase ( self ) -> Tuple:
UpperCamelCase :Union[str, Any] = tempfile.mkdtemp()
UpperCamelCase :List[str] = 5
# Realm tok
UpperCamelCase :List[Any] = [
'''[UNK]''',
'''[CLS]''',
'''[SEP]''',
'''[PAD]''',
'''[MASK]''',
'''test''',
'''question''',
'''this''',
'''is''',
'''the''',
'''first''',
'''second''',
'''third''',
'''fourth''',
'''fifth''',
'''record''',
'''want''',
'''##want''',
'''##ed''',
'''wa''',
'''un''',
'''runn''',
'''##ing''',
''',''',
'''low''',
'''lowest''',
]
UpperCamelCase :Dict = os.path.join(self.tmpdirname , '''realm_tokenizer''' )
os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Union[str, Any] = os.path.join(SCREAMING_SNAKE_CASE_ , VOCAB_FILES_NAMES['''vocab_file'''] )
with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer:
vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) )
UpperCamelCase :Any = os.path.join(self.tmpdirname , '''realm_block_records''' )
os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self ) -> RealmTokenizer:
return RealmTokenizer.from_pretrained(os.path.join(self.tmpdirname , '''realm_tokenizer''' ) )
def UpperCAmelCase ( self ) -> List[Any]:
shutil.rmtree(self.tmpdirname )
def UpperCAmelCase ( self ) -> str:
UpperCamelCase :Union[str, Any] = RealmConfig(num_block_records=self.num_block_records )
return config
def UpperCAmelCase ( self ) -> List[str]:
UpperCamelCase :Tuple = Dataset.from_dict(
{
'''id''': ['''0''', '''1'''],
'''question''': ['''foo''', '''bar'''],
'''answers''': [['''Foo''', '''Bar'''], ['''Bar''']],
} )
return dataset
def UpperCAmelCase ( self ) -> str:
UpperCamelCase :Optional[Any] = np.array(
[
b'''This is the first record''',
b'''This is the second record''',
b'''This is the third record''',
b'''This is the fourth record''',
b'''This is the fifth record''',
b'''This is a longer longer longer record''',
] , dtype=SCREAMING_SNAKE_CASE_ , )
return block_records
def UpperCAmelCase ( self ) -> Union[str, Any]:
UpperCamelCase :Optional[int] = RealmRetriever(
block_records=self.get_dummy_block_records() , tokenizer=self.get_tokenizer() , )
return retriever
def UpperCAmelCase ( self ) -> Tuple:
UpperCamelCase :Optional[Any] = self.get_config()
UpperCamelCase :str = self.get_dummy_retriever()
UpperCamelCase :int = retriever.tokenizer
UpperCamelCase :Optional[Any] = np.array([0, 3] , dtype='''long''' )
UpperCamelCase :Optional[Any] = tokenizer(['''Test question'''] ).input_ids
UpperCamelCase :Tuple = tokenizer(
['''the fourth'''] , add_special_tokens=SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , ).input_ids
UpperCamelCase :Optional[Any] = config.reader_seq_len
UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :str = retriever(
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , answer_ids=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , return_tensors='''np''' )
self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 2 )
self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 2 )
self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 2 )
self.assertEqual(concat_inputs.input_ids.shape , (2, 10) )
self.assertEqual(concat_inputs.attention_mask.shape , (2, 10) )
self.assertEqual(concat_inputs.token_type_ids.shape , (2, 10) )
self.assertEqual(concat_inputs.special_tokens_mask.shape , (2, 10) )
self.assertEqual(
tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[0] ) , ['''[CLS]''', '''test''', '''question''', '''[SEP]''', '''this''', '''is''', '''the''', '''first''', '''record''', '''[SEP]'''] , )
self.assertEqual(
tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[1] ) , ['''[CLS]''', '''test''', '''question''', '''[SEP]''', '''this''', '''is''', '''the''', '''fourth''', '''record''', '''[SEP]'''] , )
def UpperCAmelCase ( self ) -> int:
UpperCamelCase :Union[str, Any] = self.get_config()
UpperCamelCase :Union[str, Any] = self.get_dummy_retriever()
UpperCamelCase :Dict = retriever.tokenizer
UpperCamelCase :str = np.array([0, 3, 5] , dtype='''long''' )
UpperCamelCase :List[str] = tokenizer(['''Test question'''] ).input_ids
UpperCamelCase :Optional[Any] = tokenizer(
['''the fourth''', '''longer longer'''] , add_special_tokens=SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , ).input_ids
UpperCamelCase :Any = config.reader_seq_len
UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :Any = retriever(
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , answer_ids=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , return_tensors='''np''' )
self.assertEqual([False, True, True] , SCREAMING_SNAKE_CASE_ )
self.assertEqual([[-1, -1, -1], [6, -1, -1], [6, 7, 8]] , SCREAMING_SNAKE_CASE_ )
self.assertEqual([[-1, -1, -1], [7, -1, -1], [7, 8, 9]] , SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self ) -> Optional[Any]:
UpperCamelCase :str = self.get_dummy_retriever()
retriever.save_pretrained(os.path.join(self.tmpdirname , '''realm_block_records''' ) )
# Test local path
UpperCamelCase :List[str] = retriever.from_pretrained(os.path.join(self.tmpdirname , '''realm_block_records''' ) )
self.assertEqual(retriever.block_records[0] , b'''This is the first record''' )
# Test mocked remote path
with patch('''transformers.models.realm.retrieval_realm.hf_hub_download''' ) as mock_hf_hub_download:
UpperCamelCase :Tuple = os.path.join(
os.path.join(self.tmpdirname , '''realm_block_records''' ) , _REALM_BLOCK_RECORDS_FILENAME )
UpperCamelCase :List[Any] = RealmRetriever.from_pretrained('''google/realm-cc-news-pretrained-openqa''' )
self.assertEqual(retriever.block_records[0] , b'''This is the first record''' )
| 658 | 0 |
'''simple docstring'''
from datetime import datetime
import requests
def __UpperCAmelCase ( SCREAMING_SNAKE_CASE__: str ) -> List[Any]:
"""simple docstring"""
__a = '''https://downloadgram.net/wp-json/wppress/video-downloader/video?url='''
__a = requests.get(base_url + url ).json()[0]['''urls'''][0]['''src''']
return requests.get(SCREAMING_SNAKE_CASE__ ).content
if __name__ == "__main__":
__UpperCamelCase : Dict = input("""Enter Video/IGTV url: """).strip()
__UpperCamelCase : List[Any] = f"""{datetime.now():%Y-%m-%d_%H:%M:%S}.mp4"""
with open(file_name, """wb""") as fp:
fp.write(download_video(url))
print(f"""Done. Video saved to disk as {file_name}.""") | 448 |
import inspect
import unittest
from huggingface_hub import hf_hub_download
from transformers import ASTConfig
from transformers.testing_utils import require_torch, require_torchaudio, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_torchaudio_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from torch import nn
from transformers import ASTForAudioClassification, ASTModel
from transformers.models.audio_spectrogram_transformer.modeling_audio_spectrogram_transformer import (
AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
)
if is_torchaudio_available():
import torchaudio
from transformers import ASTFeatureExtractor
class UpperCAmelCase_ :
"""simple docstring"""
def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=24 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=37 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=10 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=2 , ) -> Optional[Any]:
UpperCamelCase :int = parent
UpperCamelCase :List[Any] = batch_size
UpperCamelCase :List[Any] = patch_size
UpperCamelCase :Optional[int] = max_length
UpperCamelCase :Union[str, Any] = num_mel_bins
UpperCamelCase :Optional[int] = is_training
UpperCamelCase :Dict = use_labels
UpperCamelCase :Dict = hidden_size
UpperCamelCase :Optional[int] = num_hidden_layers
UpperCamelCase :str = num_attention_heads
UpperCamelCase :Optional[int] = intermediate_size
UpperCamelCase :List[str] = hidden_act
UpperCamelCase :List[str] = hidden_dropout_prob
UpperCamelCase :List[Any] = attention_probs_dropout_prob
UpperCamelCase :str = type_sequence_label_size
UpperCamelCase :List[Any] = initializer_range
UpperCamelCase :Union[str, Any] = scope
UpperCamelCase :List[Any] = frequency_stride
UpperCamelCase :Tuple = time_stride
# in AST, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens)
UpperCamelCase :List[Any] = (self.num_mel_bins - self.patch_size) // self.frequency_stride + 1
UpperCamelCase :List[str] = (self.max_length - self.patch_size) // self.time_stride + 1
UpperCamelCase :Tuple = frequency_out_dimension * time_out_dimension
UpperCamelCase :Optional[int] = num_patches + 2
def UpperCAmelCase ( self ) -> Any:
UpperCamelCase :Tuple = floats_tensor([self.batch_size, self.max_length, self.num_mel_bins] )
UpperCamelCase :Tuple = None
if self.use_labels:
UpperCamelCase :List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size )
UpperCamelCase :str = self.get_config()
return config, input_values, labels
def UpperCAmelCase ( self ) -> List[Any]:
return ASTConfig(
patch_size=self.patch_size , max_length=self.max_length , num_mel_bins=self.num_mel_bins , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=SCREAMING_SNAKE_CASE_ , initializer_range=self.initializer_range , frequency_stride=self.frequency_stride , time_stride=self.time_stride , )
def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Optional[int]:
UpperCamelCase :Optional[Any] = ASTModel(config=SCREAMING_SNAKE_CASE_ )
model.to(SCREAMING_SNAKE_CASE_ )
model.eval()
UpperCamelCase :Tuple = model(SCREAMING_SNAKE_CASE_ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def UpperCAmelCase ( self ) -> Dict:
UpperCamelCase :List[Any] = self.prepare_config_and_inputs()
(
(
UpperCamelCase
) , (
UpperCamelCase
) , (
UpperCamelCase
) ,
) :Union[str, Any] = config_and_inputs
UpperCamelCase :List[Any] = {'''input_values''': input_values}
return config, inputs_dict
@require_torch
class UpperCAmelCase_ ( lowercase, lowercase, unittest.TestCase ):
"""simple docstring"""
UpperCamelCase_ : Optional[int] =(
(
ASTModel,
ASTForAudioClassification,
)
if is_torch_available()
else ()
)
UpperCamelCase_ : Any =(
{'audio-classification': ASTForAudioClassification, 'feature-extraction': ASTModel}
if is_torch_available()
else {}
)
UpperCamelCase_ : Optional[int] =False
UpperCamelCase_ : List[Any] =False
UpperCamelCase_ : Optional[Any] =False
UpperCamelCase_ : Dict =False
def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> List[str]:
if pipeline_test_casse_name == "AudioClassificationPipelineTests":
return True
return False
def UpperCAmelCase ( self ) -> Dict:
UpperCamelCase :List[Any] = ASTModelTester(self )
UpperCamelCase :Dict = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , has_text_modality=SCREAMING_SNAKE_CASE_ , hidden_size=37 )
def UpperCAmelCase ( self ) -> Any:
self.config_tester.run_common_tests()
@unittest.skip(reason='''AST does not use inputs_embeds''' )
def UpperCAmelCase ( self ) -> str:
pass
def UpperCAmelCase ( self ) -> int:
UpperCamelCase , UpperCamelCase :List[Any] = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
UpperCamelCase :Dict = model_class(SCREAMING_SNAKE_CASE_ )
self.assertIsInstance(model.get_input_embeddings() , (nn.Module) )
UpperCamelCase :Optional[int] = model.get_output_embeddings()
self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE_ , nn.Linear ) )
def UpperCAmelCase ( self ) -> Tuple:
UpperCamelCase , UpperCamelCase :int = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
UpperCamelCase :Dict = model_class(SCREAMING_SNAKE_CASE_ )
UpperCamelCase :List[str] = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
UpperCamelCase :Any = [*signature.parameters.keys()]
UpperCamelCase :Optional[int] = ['''input_values''']
self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self ) -> List[Any]:
UpperCamelCase :Optional[int] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ )
@slow
def UpperCAmelCase ( self ) -> Optional[int]:
for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
UpperCamelCase :Union[str, Any] = ASTModel.from_pretrained(SCREAMING_SNAKE_CASE_ )
self.assertIsNotNone(SCREAMING_SNAKE_CASE_ )
def _A ( ):
UpperCamelCase :Any = hf_hub_download(
repo_id='''nielsr/audio-spectogram-transformer-checkpoint''' , filename='''sample_audio.flac''' , repo_type='''dataset''' )
UpperCamelCase , UpperCamelCase :Any = torchaudio.load(SCREAMING_SNAKE_CASE__ )
return audio, sampling_rate
@require_torch
@require_torchaudio
class UpperCAmelCase_ ( unittest.TestCase ):
"""simple docstring"""
@cached_property
def UpperCAmelCase ( self ) -> Tuple:
return (
ASTFeatureExtractor.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593''' )
if is_torchaudio_available()
else None
)
@slow
def UpperCAmelCase ( self ) -> str:
UpperCamelCase :Union[str, Any] = self.default_feature_extractor
UpperCamelCase :Union[str, Any] = ASTForAudioClassification.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593''' ).to(SCREAMING_SNAKE_CASE_ )
UpperCamelCase :str = self.default_feature_extractor
UpperCamelCase , UpperCamelCase :Dict = prepare_audio()
UpperCamelCase :Dict = audio.squeeze().numpy()
UpperCamelCase :int = feature_extractor(SCREAMING_SNAKE_CASE_ , sampling_rate=SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' ).to(SCREAMING_SNAKE_CASE_ )
# forward pass
with torch.no_grad():
UpperCamelCase :Union[str, Any] = model(**SCREAMING_SNAKE_CASE_ )
# verify the logits
UpperCamelCase :List[Any] = torch.Size((1, 527) )
self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE_ )
UpperCamelCase :int = torch.tensor([-0.8760, -7.0042, -8.6602] ).to(SCREAMING_SNAKE_CASE_ )
self.assertTrue(torch.allclose(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) )
| 658 | 0 |
import inspect
from typing import Optional, Union
import numpy as np
import PIL
import torch
from torch.nn import functional as F
from torchvision import transforms
from transformers import CLIPFeatureExtractor, CLIPModel, CLIPTextModel, CLIPTokenizer
from diffusers import (
AutoencoderKL,
DDIMScheduler,
DiffusionPipeline,
DPMSolverMultistepScheduler,
LMSDiscreteScheduler,
PNDMScheduler,
UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput
from diffusers.utils import (
PIL_INTERPOLATION,
randn_tensor,
)
def __lowerCamelCase ( __lowerCAmelCase : Tuple , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Optional[Any] ) -> Optional[int]:
if isinstance(SCREAMING_SNAKE_CASE__ , torch.Tensor ):
return image
elif isinstance(SCREAMING_SNAKE_CASE__ , PIL.Image.Image ):
__UpperCamelCase : Dict = [image]
if isinstance(image[0] , PIL.Image.Image ):
__UpperCamelCase : Any = [np.array(i.resize((w, h) , resample=PIL_INTERPOLATION["""lanczos"""] ) )[None, :] for i in image]
__UpperCamelCase : int = np.concatenate(SCREAMING_SNAKE_CASE__ , axis=0 )
__UpperCamelCase : Optional[Any] = np.array(SCREAMING_SNAKE_CASE__ ).astype(np.floataa ) / 255.0
__UpperCamelCase : List[str] = image.transpose(0 , 3 , 1 , 2 )
__UpperCamelCase : Tuple = 2.0 * image - 1.0
__UpperCamelCase : Any = torch.from_numpy(SCREAMING_SNAKE_CASE__ )
elif isinstance(image[0] , torch.Tensor ):
__UpperCamelCase : str = torch.cat(SCREAMING_SNAKE_CASE__ , dim=0 )
return image
def __lowerCamelCase ( __lowerCAmelCase : Any , __lowerCAmelCase : Any , __lowerCAmelCase : Tuple , __lowerCAmelCase : int=0.9995 ) -> Tuple:
if not isinstance(SCREAMING_SNAKE_CASE__ , np.ndarray ):
__UpperCamelCase : int = True
__UpperCamelCase : Dict = va.device
__UpperCamelCase : List[Any] = va.cpu().numpy()
__UpperCamelCase : str = va.cpu().numpy()
__UpperCamelCase : Dict = np.sum(va * va / (np.linalg.norm(SCREAMING_SNAKE_CASE__ ) * np.linalg.norm(SCREAMING_SNAKE_CASE__ )) )
if np.abs(SCREAMING_SNAKE_CASE__ ) > DOT_THRESHOLD:
__UpperCamelCase : Any = (1 - t) * va + t * va
else:
__UpperCamelCase : Union[str, Any] = np.arccos(SCREAMING_SNAKE_CASE__ )
__UpperCamelCase : List[str] = np.sin(SCREAMING_SNAKE_CASE__ )
__UpperCamelCase : Union[str, Any] = theta_a * t
__UpperCamelCase : str = np.sin(SCREAMING_SNAKE_CASE__ )
__UpperCamelCase : Tuple = np.sin(theta_a - theta_t ) / sin_theta_a
__UpperCamelCase : List[Any] = sin_theta_t / sin_theta_a
__UpperCamelCase : Union[str, Any] = sa * va + sa * va
if inputs_are_torch:
__UpperCamelCase : Dict = torch.from_numpy(SCREAMING_SNAKE_CASE__ ).to(SCREAMING_SNAKE_CASE__ )
return va
def __lowerCamelCase ( __lowerCAmelCase : str , __lowerCAmelCase : Tuple ) -> List[str]:
__UpperCamelCase : int = F.normalize(SCREAMING_SNAKE_CASE__ , dim=-1 )
__UpperCamelCase : int = F.normalize(SCREAMING_SNAKE_CASE__ , dim=-1 )
return (x - y).norm(dim=-1 ).div(2 ).arcsin().pow(2 ).mul(2 )
def __lowerCamelCase ( __lowerCAmelCase : int , __lowerCAmelCase : Any ) -> List[Any]:
for param in model.parameters():
__UpperCamelCase : Any = value
class _A ( UpperCAmelCase_ ):
def __init__( self : Any , lowerCamelCase__ : Union[str, Any] , lowerCamelCase__ : List[Any] , lowerCamelCase__ : Union[str, Any] , lowerCamelCase__ : int , lowerCamelCase__ : int , lowerCamelCase__ : Tuple , lowerCamelCase__ : Tuple , lowerCamelCase__ : Union[str, Any]=None , lowerCamelCase__ : Optional[int]=None , lowerCamelCase__ : Tuple=None , ):
"""simple docstring"""
super().__init__()
self.register_modules(
vae=SCREAMING_SNAKE_CASE_ , text_encoder=SCREAMING_SNAKE_CASE_ , clip_model=SCREAMING_SNAKE_CASE_ , tokenizer=SCREAMING_SNAKE_CASE_ , unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ , feature_extractor=SCREAMING_SNAKE_CASE_ , coca_model=SCREAMING_SNAKE_CASE_ , coca_tokenizer=SCREAMING_SNAKE_CASE_ , coca_transform=SCREAMING_SNAKE_CASE_ , )
__UpperCamelCase : Union[str, Any] = (
feature_extractor.size
if isinstance(feature_extractor.size , SCREAMING_SNAKE_CASE_ )
else feature_extractor.size['''shortest_edge''']
)
__UpperCamelCase : Any = transforms.Normalize(mean=feature_extractor.image_mean , std=feature_extractor.image_std )
set_requires_grad(self.text_encoder , SCREAMING_SNAKE_CASE_ )
set_requires_grad(self.clip_model , SCREAMING_SNAKE_CASE_ )
def a ( self : Dict , lowerCamelCase__ : Optional[Any] = "auto" ):
"""simple docstring"""
if slice_size == "auto":
# half the attention head size is usually a good trade-off between
# speed and memory
__UpperCamelCase : Tuple = self.unet.config.attention_head_dim // 2
self.unet.set_attention_slice(SCREAMING_SNAKE_CASE_ )
def a ( self : Tuple ):
"""simple docstring"""
self.enable_attention_slicing(SCREAMING_SNAKE_CASE_ )
def a ( self : Optional[int] ):
"""simple docstring"""
set_requires_grad(self.vae , SCREAMING_SNAKE_CASE_ )
def a ( self : Optional[Any] ):
"""simple docstring"""
set_requires_grad(self.vae , SCREAMING_SNAKE_CASE_ )
def a ( self : Optional[Any] ):
"""simple docstring"""
set_requires_grad(self.unet , SCREAMING_SNAKE_CASE_ )
def a ( self : Union[str, Any] ):
"""simple docstring"""
set_requires_grad(self.unet , SCREAMING_SNAKE_CASE_ )
def a ( self : str , lowerCamelCase__ : Optional[int] , lowerCamelCase__ : int , lowerCamelCase__ : Union[str, Any] ):
"""simple docstring"""
__UpperCamelCase : Union[str, Any] = min(int(num_inference_steps * strength ) , SCREAMING_SNAKE_CASE_ )
__UpperCamelCase : Optional[Any] = max(num_inference_steps - init_timestep , 0 )
__UpperCamelCase : Optional[Any] = self.scheduler.timesteps[t_start:]
return timesteps, num_inference_steps - t_start
def a ( self : List[Any] , lowerCamelCase__ : str , lowerCamelCase__ : Any , lowerCamelCase__ : Tuple , lowerCamelCase__ : Optional[Any] , lowerCamelCase__ : Any , lowerCamelCase__ : Dict=None ):
"""simple docstring"""
if not isinstance(SCREAMING_SNAKE_CASE_ , torch.Tensor ):
raise ValueError(f'`image` has to be of type `torch.Tensor` but is {type(SCREAMING_SNAKE_CASE_ )}' )
__UpperCamelCase : Tuple = image.to(device=SCREAMING_SNAKE_CASE_ , dtype=SCREAMING_SNAKE_CASE_ )
if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ):
__UpperCamelCase : int = [
self.vae.encode(image[i : i + 1] ).latent_dist.sample(generator[i] ) for i in range(SCREAMING_SNAKE_CASE_ )
]
__UpperCamelCase : List[str] = torch.cat(SCREAMING_SNAKE_CASE_ , dim=0 )
else:
__UpperCamelCase : Any = self.vae.encode(SCREAMING_SNAKE_CASE_ ).latent_dist.sample(SCREAMING_SNAKE_CASE_ )
# Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor
__UpperCamelCase : List[str] = 0.1_8215 * init_latents
__UpperCamelCase : Optional[Any] = init_latents.repeat_interleave(SCREAMING_SNAKE_CASE_ , dim=0 )
__UpperCamelCase : List[Any] = randn_tensor(init_latents.shape , generator=SCREAMING_SNAKE_CASE_ , device=SCREAMING_SNAKE_CASE_ , dtype=SCREAMING_SNAKE_CASE_ )
# get latents
__UpperCamelCase : Optional[Any] = self.scheduler.add_noise(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
__UpperCamelCase : str = init_latents
return latents
def a ( self : int , lowerCamelCase__ : Optional[int] ):
"""simple docstring"""
__UpperCamelCase : List[str] = self.coca_transform(SCREAMING_SNAKE_CASE_ ).unsqueeze(0 )
with torch.no_grad(), torch.cuda.amp.autocast():
__UpperCamelCase : Any = self.coca_model.generate(transformed_image.to(device=self.device , dtype=self.coca_model.dtype ) )
__UpperCamelCase : List[Any] = self.coca_tokenizer.decode(generated[0].cpu().numpy() )
return generated.split("""<end_of_text>""" )[0].replace("""<start_of_text>""" , """""" ).rstrip(""" .,""" )
def a ( self : Optional[Any] , lowerCamelCase__ : str , lowerCamelCase__ : List[str] ):
"""simple docstring"""
__UpperCamelCase : str = self.feature_extractor.preprocess(SCREAMING_SNAKE_CASE_ )
__UpperCamelCase : List[str] = torch.from_numpy(clip_image_input["""pixel_values"""][0] ).unsqueeze(0 ).to(self.device ).half()
__UpperCamelCase : int = self.clip_model.get_image_features(SCREAMING_SNAKE_CASE_ )
__UpperCamelCase : str = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=SCREAMING_SNAKE_CASE_ )
__UpperCamelCase : Union[str, Any] = image_embeddings_clip.repeat_interleave(SCREAMING_SNAKE_CASE_ , dim=0 )
return image_embeddings_clip
@torch.enable_grad()
def a ( self : str , lowerCamelCase__ : Optional[int] , lowerCamelCase__ : Union[str, Any] , lowerCamelCase__ : Dict , lowerCamelCase__ : Tuple , lowerCamelCase__ : List[str] , lowerCamelCase__ : Optional[Any] , lowerCamelCase__ : str , ):
"""simple docstring"""
__UpperCamelCase : List[str] = latents.detach().requires_grad_()
__UpperCamelCase : List[str] = self.scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# predict the noise residual
__UpperCamelCase : List[Any] = self.unet(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ ).sample
if isinstance(self.scheduler , (PNDMScheduler, DDIMScheduler, DPMSolverMultistepScheduler) ):
__UpperCamelCase : List[str] = self.scheduler.alphas_cumprod[timestep]
__UpperCamelCase : Optional[int] = 1 - alpha_prod_t
# compute predicted original sample from predicted noise also called
# "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
__UpperCamelCase : List[Any] = (latents - beta_prod_t ** 0.5 * noise_pred) / alpha_prod_t ** 0.5
__UpperCamelCase : int = torch.sqrt(SCREAMING_SNAKE_CASE_ )
__UpperCamelCase : Tuple = pred_original_sample * (fac) + latents * (1 - fac)
elif isinstance(self.scheduler , SCREAMING_SNAKE_CASE_ ):
__UpperCamelCase : str = self.scheduler.sigmas[index]
__UpperCamelCase : Union[str, Any] = latents - sigma * noise_pred
else:
raise ValueError(f'scheduler type {type(self.scheduler )} not supported' )
# Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor
__UpperCamelCase : int = 1 / 0.1_8215 * sample
__UpperCamelCase : List[Any] = self.vae.decode(SCREAMING_SNAKE_CASE_ ).sample
__UpperCamelCase : str = (image / 2 + 0.5).clamp(0 , 1 )
__UpperCamelCase : List[str] = transforms.Resize(self.feature_extractor_size )(SCREAMING_SNAKE_CASE_ )
__UpperCamelCase : Any = self.normalize(SCREAMING_SNAKE_CASE_ ).to(latents.dtype )
__UpperCamelCase : List[Any] = self.clip_model.get_image_features(SCREAMING_SNAKE_CASE_ )
__UpperCamelCase : str = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=SCREAMING_SNAKE_CASE_ )
__UpperCamelCase : Union[str, Any] = spherical_dist_loss(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).mean() * clip_guidance_scale
__UpperCamelCase : Union[str, Any] = -torch.autograd.grad(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )[0]
if isinstance(self.scheduler , SCREAMING_SNAKE_CASE_ ):
__UpperCamelCase : Dict = latents.detach() + grads * (sigma**2)
__UpperCamelCase : Optional[Any] = noise_pred_original
else:
__UpperCamelCase : List[str] = noise_pred_original - torch.sqrt(SCREAMING_SNAKE_CASE_ ) * grads
return noise_pred, latents
@torch.no_grad()
def __call__( self : Optional[Any] , lowerCamelCase__ : Any , lowerCamelCase__ : Any , lowerCamelCase__ : Optional[Any] = None , lowerCamelCase__ : str = None , lowerCamelCase__ : Union[str, Any] = 5_12 , lowerCamelCase__ : Optional[Any] = 5_12 , lowerCamelCase__ : Tuple = 0.6 , lowerCamelCase__ : Tuple = 50 , lowerCamelCase__ : List[str] = 7.5 , lowerCamelCase__ : str = 1 , lowerCamelCase__ : List[str] = 0.0 , lowerCamelCase__ : Tuple = 1_00 , lowerCamelCase__ : Any = None , lowerCamelCase__ : List[Any] = "pil" , lowerCamelCase__ : Tuple = True , lowerCamelCase__ : Union[str, Any] = 0.8 , lowerCamelCase__ : Any = 0.1 , lowerCamelCase__ : List[str] = 0.1 , ):
"""simple docstring"""
if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) and len(SCREAMING_SNAKE_CASE_ ) != batch_size:
raise ValueError(f'You have passed {batch_size} batch_size, but only {len(SCREAMING_SNAKE_CASE_ )} generators.' )
if height % 8 != 0 or width % 8 != 0:
raise ValueError(f'`height` and `width` have to be divisible by 8 but are {height} and {width}.' )
if isinstance(SCREAMING_SNAKE_CASE_ , torch.Generator ) and batch_size > 1:
__UpperCamelCase : Optional[int] = [generator] + [None] * (batch_size - 1)
__UpperCamelCase : Tuple = [
('''model''', self.coca_model is None),
('''tokenizer''', self.coca_tokenizer is None),
('''transform''', self.coca_transform is None),
]
__UpperCamelCase : Union[str, Any] = [x[0] for x in coca_is_none if x[1]]
__UpperCamelCase : Dict = ''', '''.join(SCREAMING_SNAKE_CASE_ )
# generate prompts with coca model if prompt is None
if content_prompt is None:
if len(SCREAMING_SNAKE_CASE_ ):
raise ValueError(
f'Content prompt is None and CoCa [{coca_is_none_str}] is None.'
f'Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.' )
__UpperCamelCase : Any = self.get_image_description(SCREAMING_SNAKE_CASE_ )
if style_prompt is None:
if len(SCREAMING_SNAKE_CASE_ ):
raise ValueError(
f'Style prompt is None and CoCa [{coca_is_none_str}] is None.'
f' Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.' )
__UpperCamelCase : str = self.get_image_description(SCREAMING_SNAKE_CASE_ )
# get prompt text embeddings for content and style
__UpperCamelCase : List[Any] = self.tokenizer(
SCREAMING_SNAKE_CASE_ , padding="""max_length""" , max_length=self.tokenizer.model_max_length , truncation=SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" , )
__UpperCamelCase : Dict = self.text_encoder(content_text_input.input_ids.to(self.device ) )[0]
__UpperCamelCase : List[Any] = self.tokenizer(
SCREAMING_SNAKE_CASE_ , padding="""max_length""" , max_length=self.tokenizer.model_max_length , truncation=SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" , )
__UpperCamelCase : Tuple = self.text_encoder(style_text_input.input_ids.to(self.device ) )[0]
__UpperCamelCase : Dict = slerp(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# duplicate text embeddings for each generation per prompt
__UpperCamelCase : Union[str, Any] = text_embeddings.repeat_interleave(SCREAMING_SNAKE_CASE_ , dim=0 )
# set timesteps
__UpperCamelCase : str = '''offset''' in set(inspect.signature(self.scheduler.set_timesteps ).parameters.keys() )
__UpperCamelCase : List[str] = {}
if accepts_offset:
__UpperCamelCase : Tuple = 1
self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
# Some schedulers like PNDM have timesteps as arrays
# It's more optimized to move all timesteps to correct device beforehand
self.scheduler.timesteps.to(self.device )
__UpperCamelCase : Tuple = self.get_timesteps(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , self.device )
__UpperCamelCase : Any = timesteps[:1].repeat(SCREAMING_SNAKE_CASE_ )
# Preprocess image
__UpperCamelCase : Union[str, Any] = preprocess(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
__UpperCamelCase : Optional[Any] = self.prepare_latents(
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , text_embeddings.dtype , self.device , SCREAMING_SNAKE_CASE_ )
__UpperCamelCase : Dict = preprocess(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
__UpperCamelCase : Optional[Any] = self.prepare_latents(
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , text_embeddings.dtype , self.device , SCREAMING_SNAKE_CASE_ )
__UpperCamelCase : str = slerp(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
if clip_guidance_scale > 0:
__UpperCamelCase : Dict = self.get_clip_image_embeddings(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
__UpperCamelCase : Optional[int] = self.get_clip_image_embeddings(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
__UpperCamelCase : Optional[Any] = slerp(
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
# corresponds to doing no classifier free guidance.
__UpperCamelCase : Optional[int] = guidance_scale > 1.0
# get unconditional embeddings for classifier free guidance
if do_classifier_free_guidance:
__UpperCamelCase : Any = content_text_input.input_ids.shape[-1]
__UpperCamelCase : Any = self.tokenizer([""""""] , padding="""max_length""" , max_length=SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" )
__UpperCamelCase : Optional[Any] = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0]
# duplicate unconditional embeddings for each generation per prompt
__UpperCamelCase : Optional[int] = uncond_embeddings.repeat_interleave(SCREAMING_SNAKE_CASE_ , dim=0 )
# For classifier free guidance, we need to do two forward passes.
# Here we concatenate the unconditional and text embeddings into a single batch
# to avoid doing two forward passes
__UpperCamelCase : str = torch.cat([uncond_embeddings, text_embeddings] )
# get the initial random noise unless the user supplied it
# Unlike in other pipelines, latents need to be generated in the target device
# for 1-to-1 results reproducibility with the CompVis implementation.
# However this currently doesn't work in `mps`.
__UpperCamelCase : Any = (batch_size, self.unet.config.in_channels, height // 8, width // 8)
__UpperCamelCase : int = text_embeddings.dtype
if latents is None:
if self.device.type == "mps":
# randn does not work reproducibly on mps
__UpperCamelCase : List[str] = torch.randn(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device="""cpu""" , dtype=SCREAMING_SNAKE_CASE_ ).to(
self.device )
else:
__UpperCamelCase : int = torch.randn(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device=self.device , dtype=SCREAMING_SNAKE_CASE_ )
else:
if latents.shape != latents_shape:
raise ValueError(f'Unexpected latents shape, got {latents.shape}, expected {latents_shape}' )
__UpperCamelCase : str = latents.to(self.device )
# scale the initial noise by the standard deviation required by the scheduler
__UpperCamelCase : Union[str, Any] = latents * self.scheduler.init_noise_sigma
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
# and should be between [0, 1]
__UpperCamelCase : Optional[int] = '''eta''' in set(inspect.signature(self.scheduler.step ).parameters.keys() )
__UpperCamelCase : Dict = {}
if accepts_eta:
__UpperCamelCase : int = eta
# check if the scheduler accepts generator
__UpperCamelCase : Optional[int] = '''generator''' in set(inspect.signature(self.scheduler.step ).parameters.keys() )
if accepts_generator:
__UpperCamelCase : List[str] = generator
with self.progress_bar(total=SCREAMING_SNAKE_CASE_ ):
for i, t in enumerate(SCREAMING_SNAKE_CASE_ ):
# expand the latents if we are doing classifier free guidance
__UpperCamelCase : Optional[int] = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents
__UpperCamelCase : List[Any] = self.scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# predict the noise residual
__UpperCamelCase : List[str] = self.unet(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ ).sample
# perform classifier free guidance
if do_classifier_free_guidance:
__UpperCamelCase : Any = noise_pred.chunk(2 )
__UpperCamelCase : Optional[Any] = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
# perform clip guidance
if clip_guidance_scale > 0:
__UpperCamelCase : int = (
text_embeddings.chunk(2 )[1] if do_classifier_free_guidance else text_embeddings
)
__UpperCamelCase : str = self.cond_fn(
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , )
# compute the previous noisy sample x_t -> x_t-1
__UpperCamelCase : List[str] = self.scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample
# Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor
__UpperCamelCase : List[Any] = 1 / 0.1_8215 * latents
__UpperCamelCase : Optional[Any] = self.vae.decode(SCREAMING_SNAKE_CASE_ ).sample
__UpperCamelCase : str = (image / 2 + 0.5).clamp(0 , 1 )
__UpperCamelCase : Dict = image.cpu().permute(0 , 2 , 3 , 1 ).numpy()
if output_type == "pil":
__UpperCamelCase : List[str] = self.numpy_to_pil(SCREAMING_SNAKE_CASE_ )
if not return_dict:
return (image, None)
return StableDiffusionPipelineOutput(images=SCREAMING_SNAKE_CASE_ , nsfw_content_detected=SCREAMING_SNAKE_CASE_ )
| 269 |
import inspect
from typing import Optional, Union
import numpy as np
import PIL
import torch
from torch.nn import functional as F
from torchvision import transforms
from transformers import CLIPFeatureExtractor, CLIPModel, CLIPTextModel, CLIPTokenizer
from diffusers import (
AutoencoderKL,
DDIMScheduler,
DiffusionPipeline,
DPMSolverMultistepScheduler,
LMSDiscreteScheduler,
PNDMScheduler,
UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput
from diffusers.utils import (
PIL_INTERPOLATION,
randn_tensor,
)
def _A ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ):
if isinstance(SCREAMING_SNAKE_CASE__ , torch.Tensor ):
return image
elif isinstance(SCREAMING_SNAKE_CASE__ , PIL.Image.Image ):
UpperCamelCase :Dict = [image]
if isinstance(image[0] , PIL.Image.Image ):
UpperCamelCase :Any = [np.array(i.resize((w, h) , resample=PIL_INTERPOLATION['''lanczos'''] ) )[None, :] for i in image]
UpperCamelCase :int = np.concatenate(SCREAMING_SNAKE_CASE__ , axis=0 )
UpperCamelCase :Optional[Any] = np.array(SCREAMING_SNAKE_CASE__ ).astype(np.floataa ) / 2_55.0
UpperCamelCase :List[str] = image.transpose(0 , 3 , 1 , 2 )
UpperCamelCase :Tuple = 2.0 * image - 1.0
UpperCamelCase :Any = torch.from_numpy(SCREAMING_SNAKE_CASE__ )
elif isinstance(image[0] , torch.Tensor ):
UpperCamelCase :str = torch.cat(SCREAMING_SNAKE_CASE__ , dim=0 )
return image
def _A ( SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : int=0.99_95 ):
if not isinstance(SCREAMING_SNAKE_CASE__ , np.ndarray ):
UpperCamelCase :int = True
UpperCamelCase :Dict = va.device
UpperCamelCase :List[Any] = va.cpu().numpy()
UpperCamelCase :str = va.cpu().numpy()
UpperCamelCase :Dict = np.sum(va * va / (np.linalg.norm(SCREAMING_SNAKE_CASE__ ) * np.linalg.norm(SCREAMING_SNAKE_CASE__ )) )
if np.abs(SCREAMING_SNAKE_CASE__ ) > DOT_THRESHOLD:
UpperCamelCase :Any = (1 - t) * va + t * va
else:
UpperCamelCase :Union[str, Any] = np.arccos(SCREAMING_SNAKE_CASE__ )
UpperCamelCase :List[str] = np.sin(SCREAMING_SNAKE_CASE__ )
UpperCamelCase :Union[str, Any] = theta_a * t
UpperCamelCase :str = np.sin(SCREAMING_SNAKE_CASE__ )
UpperCamelCase :Tuple = np.sin(theta_a - theta_t ) / sin_theta_a
UpperCamelCase :List[Any] = sin_theta_t / sin_theta_a
UpperCamelCase :Union[str, Any] = sa * va + sa * va
if inputs_are_torch:
UpperCamelCase :Dict = torch.from_numpy(SCREAMING_SNAKE_CASE__ ).to(SCREAMING_SNAKE_CASE__ )
return va
def _A ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Tuple ):
UpperCamelCase :int = F.normalize(SCREAMING_SNAKE_CASE__ , dim=-1 )
UpperCamelCase :int = F.normalize(SCREAMING_SNAKE_CASE__ , dim=-1 )
return (x - y).norm(dim=-1 ).div(2 ).arcsin().pow(2 ).mul(2 )
def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Any ):
for param in model.parameters():
UpperCamelCase :Any = value
class UpperCAmelCase_ ( lowercase ):
"""simple docstring"""
def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , ) -> str:
super().__init__()
self.register_modules(
vae=SCREAMING_SNAKE_CASE_ , text_encoder=SCREAMING_SNAKE_CASE_ , clip_model=SCREAMING_SNAKE_CASE_ , tokenizer=SCREAMING_SNAKE_CASE_ , unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ , feature_extractor=SCREAMING_SNAKE_CASE_ , coca_model=SCREAMING_SNAKE_CASE_ , coca_tokenizer=SCREAMING_SNAKE_CASE_ , coca_transform=SCREAMING_SNAKE_CASE_ , )
UpperCamelCase :Union[str, Any] = (
feature_extractor.size
if isinstance(feature_extractor.size , SCREAMING_SNAKE_CASE_ )
else feature_extractor.size['''shortest_edge''']
)
UpperCamelCase :Any = transforms.Normalize(mean=feature_extractor.image_mean , std=feature_extractor.image_std )
set_requires_grad(self.text_encoder , SCREAMING_SNAKE_CASE_ )
set_requires_grad(self.clip_model , SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ = "auto" ) -> Tuple:
if slice_size == "auto":
# half the attention head size is usually a good trade-off between
# speed and memory
UpperCamelCase :Tuple = self.unet.config.attention_head_dim // 2
self.unet.set_attention_slice(SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self ) -> int:
self.enable_attention_slicing(SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self ) -> str:
set_requires_grad(self.vae , SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self ) -> Union[str, Any]:
set_requires_grad(self.vae , SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self ) -> int:
set_requires_grad(self.unet , SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self ) -> str:
set_requires_grad(self.unet , SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Any:
# get the original timestep using init_timestep
UpperCamelCase :Union[str, Any] = min(int(num_inference_steps * strength ) , SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Optional[Any] = max(num_inference_steps - init_timestep , 0 )
UpperCamelCase :Optional[Any] = self.scheduler.timesteps[t_start:]
return timesteps, num_inference_steps - t_start
def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None ) -> int:
if not isinstance(SCREAMING_SNAKE_CASE_ , torch.Tensor ):
raise ValueError(F'''`image` has to be of type `torch.Tensor` but is {type(SCREAMING_SNAKE_CASE_ )}''' )
UpperCamelCase :Tuple = image.to(device=SCREAMING_SNAKE_CASE_ , dtype=SCREAMING_SNAKE_CASE_ )
if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ):
UpperCamelCase :int = [
self.vae.encode(image[i : i + 1] ).latent_dist.sample(generator[i] ) for i in range(SCREAMING_SNAKE_CASE_ )
]
UpperCamelCase :List[str] = torch.cat(SCREAMING_SNAKE_CASE_ , dim=0 )
else:
UpperCamelCase :Any = self.vae.encode(SCREAMING_SNAKE_CASE_ ).latent_dist.sample(SCREAMING_SNAKE_CASE_ )
# Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor
UpperCamelCase :List[str] = 0.1_8215 * init_latents
UpperCamelCase :Optional[Any] = init_latents.repeat_interleave(SCREAMING_SNAKE_CASE_ , dim=0 )
UpperCamelCase :List[Any] = randn_tensor(init_latents.shape , generator=SCREAMING_SNAKE_CASE_ , device=SCREAMING_SNAKE_CASE_ , dtype=SCREAMING_SNAKE_CASE_ )
# get latents
UpperCamelCase :Optional[Any] = self.scheduler.add_noise(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
UpperCamelCase :str = init_latents
return latents
def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ ) -> List[str]:
UpperCamelCase :List[str] = self.coca_transform(SCREAMING_SNAKE_CASE_ ).unsqueeze(0 )
with torch.no_grad(), torch.cuda.amp.autocast():
UpperCamelCase :Any = self.coca_model.generate(transformed_image.to(device=self.device , dtype=self.coca_model.dtype ) )
UpperCamelCase :List[Any] = self.coca_tokenizer.decode(generated[0].cpu().numpy() )
return generated.split('''<end_of_text>''' )[0].replace('''<start_of_text>''' , '''''' ).rstrip(''' .,''' )
def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> List[Any]:
UpperCamelCase :str = self.feature_extractor.preprocess(SCREAMING_SNAKE_CASE_ )
UpperCamelCase :List[str] = torch.from_numpy(clip_image_input['''pixel_values'''][0] ).unsqueeze(0 ).to(self.device ).half()
UpperCamelCase :int = self.clip_model.get_image_features(SCREAMING_SNAKE_CASE_ )
UpperCamelCase :str = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Union[str, Any] = image_embeddings_clip.repeat_interleave(SCREAMING_SNAKE_CASE_ , dim=0 )
return image_embeddings_clip
@torch.enable_grad()
def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ) -> Optional[int]:
UpperCamelCase :List[str] = latents.detach().requires_grad_()
UpperCamelCase :List[str] = self.scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# predict the noise residual
UpperCamelCase :List[Any] = self.unet(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ ).sample
if isinstance(self.scheduler , (PNDMScheduler, DDIMScheduler, DPMSolverMultistepScheduler) ):
UpperCamelCase :List[str] = self.scheduler.alphas_cumprod[timestep]
UpperCamelCase :Optional[int] = 1 - alpha_prod_t
# compute predicted original sample from predicted noise also called
# "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
UpperCamelCase :List[Any] = (latents - beta_prod_t ** 0.5 * noise_pred) / alpha_prod_t ** 0.5
UpperCamelCase :int = torch.sqrt(SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Tuple = pred_original_sample * (fac) + latents * (1 - fac)
elif isinstance(self.scheduler , SCREAMING_SNAKE_CASE_ ):
UpperCamelCase :str = self.scheduler.sigmas[index]
UpperCamelCase :Union[str, Any] = latents - sigma * noise_pred
else:
raise ValueError(F'''scheduler type {type(self.scheduler )} not supported''' )
# Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor
UpperCamelCase :int = 1 / 0.1_8215 * sample
UpperCamelCase :List[Any] = self.vae.decode(SCREAMING_SNAKE_CASE_ ).sample
UpperCamelCase :str = (image / 2 + 0.5).clamp(0 , 1 )
UpperCamelCase :List[str] = transforms.Resize(self.feature_extractor_size )(SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Any = self.normalize(SCREAMING_SNAKE_CASE_ ).to(latents.dtype )
UpperCamelCase :List[Any] = self.clip_model.get_image_features(SCREAMING_SNAKE_CASE_ )
UpperCamelCase :str = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Union[str, Any] = spherical_dist_loss(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).mean() * clip_guidance_scale
UpperCamelCase :Union[str, Any] = -torch.autograd.grad(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )[0]
if isinstance(self.scheduler , SCREAMING_SNAKE_CASE_ ):
UpperCamelCase :Dict = latents.detach() + grads * (sigma**2)
UpperCamelCase :Optional[Any] = noise_pred_original
else:
UpperCamelCase :List[str] = noise_pred_original - torch.sqrt(SCREAMING_SNAKE_CASE_ ) * grads
return noise_pred, latents
@torch.no_grad()
def __call__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 512 , SCREAMING_SNAKE_CASE_ = 512 , SCREAMING_SNAKE_CASE_ = 0.6 , SCREAMING_SNAKE_CASE_ = 50 , SCREAMING_SNAKE_CASE_ = 7.5 , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = 100 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "pil" , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = 0.8 , SCREAMING_SNAKE_CASE_ = 0.1 , SCREAMING_SNAKE_CASE_ = 0.1 , ) -> Dict:
if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) and len(SCREAMING_SNAKE_CASE_ ) != batch_size:
raise ValueError(F'''You have passed {batch_size} batch_size, but only {len(SCREAMING_SNAKE_CASE_ )} generators.''' )
if height % 8 != 0 or width % 8 != 0:
raise ValueError(F'''`height` and `width` have to be divisible by 8 but are {height} and {width}.''' )
if isinstance(SCREAMING_SNAKE_CASE_ , torch.Generator ) and batch_size > 1:
UpperCamelCase :Optional[int] = [generator] + [None] * (batch_size - 1)
UpperCamelCase :Tuple = [
('''model''', self.coca_model is None),
('''tokenizer''', self.coca_tokenizer is None),
('''transform''', self.coca_transform is None),
]
UpperCamelCase :Union[str, Any] = [x[0] for x in coca_is_none if x[1]]
UpperCamelCase :Dict = ''', '''.join(SCREAMING_SNAKE_CASE_ )
# generate prompts with coca model if prompt is None
if content_prompt is None:
if len(SCREAMING_SNAKE_CASE_ ):
raise ValueError(
F'''Content prompt is None and CoCa [{coca_is_none_str}] is None.'''
F'''Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.''' )
UpperCamelCase :Any = self.get_image_description(SCREAMING_SNAKE_CASE_ )
if style_prompt is None:
if len(SCREAMING_SNAKE_CASE_ ):
raise ValueError(
F'''Style prompt is None and CoCa [{coca_is_none_str}] is None.'''
F''' Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.''' )
UpperCamelCase :str = self.get_image_description(SCREAMING_SNAKE_CASE_ )
# get prompt text embeddings for content and style
UpperCamelCase :List[Any] = self.tokenizer(
SCREAMING_SNAKE_CASE_ , padding='''max_length''' , max_length=self.tokenizer.model_max_length , truncation=SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' , )
UpperCamelCase :Dict = self.text_encoder(content_text_input.input_ids.to(self.device ) )[0]
UpperCamelCase :List[Any] = self.tokenizer(
SCREAMING_SNAKE_CASE_ , padding='''max_length''' , max_length=self.tokenizer.model_max_length , truncation=SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' , )
UpperCamelCase :Tuple = self.text_encoder(style_text_input.input_ids.to(self.device ) )[0]
UpperCamelCase :Dict = slerp(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# duplicate text embeddings for each generation per prompt
UpperCamelCase :Union[str, Any] = text_embeddings.repeat_interleave(SCREAMING_SNAKE_CASE_ , dim=0 )
# set timesteps
UpperCamelCase :str = '''offset''' in set(inspect.signature(self.scheduler.set_timesteps ).parameters.keys() )
UpperCamelCase :List[str] = {}
if accepts_offset:
UpperCamelCase :Tuple = 1
self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
# Some schedulers like PNDM have timesteps as arrays
# It's more optimized to move all timesteps to correct device beforehand
self.scheduler.timesteps.to(self.device )
UpperCamelCase , UpperCamelCase :Tuple = self.get_timesteps(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , self.device )
UpperCamelCase :Any = timesteps[:1].repeat(SCREAMING_SNAKE_CASE_ )
# Preprocess image
UpperCamelCase :Union[str, Any] = preprocess(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Optional[Any] = self.prepare_latents(
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , text_embeddings.dtype , self.device , SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Dict = preprocess(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Optional[Any] = self.prepare_latents(
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , text_embeddings.dtype , self.device , SCREAMING_SNAKE_CASE_ )
UpperCamelCase :str = slerp(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
if clip_guidance_scale > 0:
UpperCamelCase :Dict = self.get_clip_image_embeddings(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Optional[int] = self.get_clip_image_embeddings(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Optional[Any] = slerp(
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
# corresponds to doing no classifier free guidance.
UpperCamelCase :Optional[int] = guidance_scale > 1.0
# get unconditional embeddings for classifier free guidance
if do_classifier_free_guidance:
UpperCamelCase :Any = content_text_input.input_ids.shape[-1]
UpperCamelCase :Any = self.tokenizer([''''''] , padding='''max_length''' , max_length=SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' )
UpperCamelCase :Optional[Any] = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0]
# duplicate unconditional embeddings for each generation per prompt
UpperCamelCase :Optional[int] = uncond_embeddings.repeat_interleave(SCREAMING_SNAKE_CASE_ , dim=0 )
# For classifier free guidance, we need to do two forward passes.
# Here we concatenate the unconditional and text embeddings into a single batch
# to avoid doing two forward passes
UpperCamelCase :str = torch.cat([uncond_embeddings, text_embeddings] )
# get the initial random noise unless the user supplied it
# Unlike in other pipelines, latents need to be generated in the target device
# for 1-to-1 results reproducibility with the CompVis implementation.
# However this currently doesn't work in `mps`.
UpperCamelCase :Any = (batch_size, self.unet.config.in_channels, height // 8, width // 8)
UpperCamelCase :int = text_embeddings.dtype
if latents is None:
if self.device.type == "mps":
# randn does not work reproducibly on mps
UpperCamelCase :List[str] = torch.randn(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device='''cpu''' , dtype=SCREAMING_SNAKE_CASE_ ).to(
self.device )
else:
UpperCamelCase :int = torch.randn(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device=self.device , dtype=SCREAMING_SNAKE_CASE_ )
else:
if latents.shape != latents_shape:
raise ValueError(F'''Unexpected latents shape, got {latents.shape}, expected {latents_shape}''' )
UpperCamelCase :str = latents.to(self.device )
# scale the initial noise by the standard deviation required by the scheduler
UpperCamelCase :Union[str, Any] = latents * self.scheduler.init_noise_sigma
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
# and should be between [0, 1]
UpperCamelCase :Optional[int] = '''eta''' in set(inspect.signature(self.scheduler.step ).parameters.keys() )
UpperCamelCase :Dict = {}
if accepts_eta:
UpperCamelCase :int = eta
# check if the scheduler accepts generator
UpperCamelCase :Optional[int] = '''generator''' in set(inspect.signature(self.scheduler.step ).parameters.keys() )
if accepts_generator:
UpperCamelCase :List[str] = generator
with self.progress_bar(total=SCREAMING_SNAKE_CASE_ ):
for i, t in enumerate(SCREAMING_SNAKE_CASE_ ):
# expand the latents if we are doing classifier free guidance
UpperCamelCase :Optional[int] = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents
UpperCamelCase :List[Any] = self.scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# predict the noise residual
UpperCamelCase :List[str] = self.unet(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ ).sample
# perform classifier free guidance
if do_classifier_free_guidance:
UpperCamelCase , UpperCamelCase :Any = noise_pred.chunk(2 )
UpperCamelCase :Optional[Any] = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
# perform clip guidance
if clip_guidance_scale > 0:
UpperCamelCase :int = (
text_embeddings.chunk(2 )[1] if do_classifier_free_guidance else text_embeddings
)
UpperCamelCase , UpperCamelCase :str = self.cond_fn(
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , )
# compute the previous noisy sample x_t -> x_t-1
UpperCamelCase :List[str] = self.scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample
# Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor
UpperCamelCase :List[Any] = 1 / 0.1_8215 * latents
UpperCamelCase :Optional[Any] = self.vae.decode(SCREAMING_SNAKE_CASE_ ).sample
UpperCamelCase :str = (image / 2 + 0.5).clamp(0 , 1 )
UpperCamelCase :Dict = image.cpu().permute(0 , 2 , 3 , 1 ).numpy()
if output_type == "pil":
UpperCamelCase :List[str] = self.numpy_to_pil(SCREAMING_SNAKE_CASE_ )
if not return_dict:
return (image, None)
return StableDiffusionPipelineOutput(images=SCREAMING_SNAKE_CASE_ , nsfw_content_detected=SCREAMING_SNAKE_CASE_ )
| 658 | 0 |
import argparse
import torch
from torch import nn
from transformers import SpeechaTextConfig, SpeechaTextForConditionalGeneration
def _SCREAMING_SNAKE_CASE ( snake_case ) -> List[Any]:
_UpperCAmelCase = [
'''encoder.version''',
'''decoder.version''',
'''model.encoder.version''',
'''model.decoder.version''',
'''decoder.output_projection.weight''',
'''_float_tensor''',
'''encoder.embed_positions._float_tensor''',
'''decoder.embed_positions._float_tensor''',
]
for k in ignore_keys:
state_dict.pop(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
def _SCREAMING_SNAKE_CASE ( snake_case ) -> Tuple:
_UpperCAmelCase = list(s_dict.keys() )
for key in keys:
if "transformer_layers" in key:
_UpperCAmelCase = s_dict.pop(SCREAMING_SNAKE_CASE__ )
elif "subsample" in key:
_UpperCAmelCase = s_dict.pop(SCREAMING_SNAKE_CASE__ )
def _SCREAMING_SNAKE_CASE ( snake_case ) -> Optional[Any]:
_UpperCAmelCase = emb.weight.shape
_UpperCAmelCase = nn.Linear(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , bias=SCREAMING_SNAKE_CASE__ )
_UpperCAmelCase = emb.weight.data
return lin_layer
def _SCREAMING_SNAKE_CASE ( snake_case , snake_case ) -> Optional[Any]:
_UpperCAmelCase = torch.load(SCREAMING_SNAKE_CASE__ , map_location="""cpu""" )
_UpperCAmelCase = mam_aaa['''args''']
_UpperCAmelCase = mam_aaa['''model''']
_UpperCAmelCase = state_dict['''decoder.output_projection.weight''']
remove_ignore_keys_(SCREAMING_SNAKE_CASE__ )
rename_keys(SCREAMING_SNAKE_CASE__ )
_UpperCAmelCase = state_dict['''decoder.embed_tokens.weight'''].shape[0]
_UpperCAmelCase = args.share_decoder_input_output_embed
_UpperCAmelCase = [int(SCREAMING_SNAKE_CASE__ ) for i in args.conv_kernel_sizes.split(""",""" )]
_UpperCAmelCase = SpeechaTextConfig(
vocab_size=SCREAMING_SNAKE_CASE__ , max_source_positions=args.max_source_positions , max_target_positions=args.max_target_positions , encoder_layers=args.encoder_layers , decoder_layers=args.decoder_layers , encoder_attention_heads=args.encoder_attention_heads , decoder_attention_heads=args.decoder_attention_heads , encoder_ffn_dim=args.encoder_ffn_embed_dim , decoder_ffn_dim=args.decoder_ffn_embed_dim , d_model=args.encoder_embed_dim , dropout=args.dropout , attention_dropout=args.attention_dropout , activation_dropout=args.activation_dropout , activation_function="""relu""" , num_conv_layers=len(SCREAMING_SNAKE_CASE__ ) , conv_channels=args.conv_channels , conv_kernel_sizes=SCREAMING_SNAKE_CASE__ , input_feat_per_channel=args.input_feat_per_channel , input_channels=args.input_channels , tie_word_embeddings=SCREAMING_SNAKE_CASE__ , num_beams=5 , max_length=2_0_0 , use_cache=SCREAMING_SNAKE_CASE__ , decoder_start_token_id=2 , early_stopping=SCREAMING_SNAKE_CASE__ , )
_UpperCAmelCase = SpeechaTextForConditionalGeneration(SCREAMING_SNAKE_CASE__ )
_UpperCAmelCase = model.model.load_state_dict(SCREAMING_SNAKE_CASE__ , strict=SCREAMING_SNAKE_CASE__ )
if len(SCREAMING_SNAKE_CASE__ ) > 0 and not set(SCREAMING_SNAKE_CASE__ ) <= {
"encoder.embed_positions.weights",
"decoder.embed_positions.weights",
}:
raise ValueError(
"""Only `encoder.embed_positions.weights` and `decoder.embed_positions.weights` are allowed to be missing,"""
f" but all the following weights are missing {missing}" )
if tie_embeds:
_UpperCAmelCase = make_linear_from_emb(model.model.decoder.embed_tokens )
else:
_UpperCAmelCase = lm_head_weights
model.save_pretrained(SCREAMING_SNAKE_CASE__ )
if __name__ == "__main__":
a = argparse.ArgumentParser()
# Required parameters
parser.add_argument("--fairseq_path", type=str, help="Path to the fairseq model (.pt) file.")
parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.")
a = parser.parse_args()
convert_fairseq_sat_checkpoint_to_tfms(args.fairseq_path, args.pytorch_dump_folder_path) | 518 |
from __future__ import annotations
def _A ( SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : int ):
UpperCamelCase :list[list[int]] = []
UpperCamelCase :list[int] = []
UpperCamelCase :List[str] = 0
UpperCamelCase :Any = sum(SCREAMING_SNAKE_CASE__ )
create_state_space_tree(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
return result
def _A ( SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : list[list[int]] , SCREAMING_SNAKE_CASE__ : int , ):
if sum(SCREAMING_SNAKE_CASE__ ) > max_sum or (remaining_nums_sum + sum(SCREAMING_SNAKE_CASE__ )) < max_sum:
return
if sum(SCREAMING_SNAKE_CASE__ ) == max_sum:
result.append(SCREAMING_SNAKE_CASE__ )
return
for index in range(SCREAMING_SNAKE_CASE__ , len(SCREAMING_SNAKE_CASE__ ) ):
create_state_space_tree(
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , index + 1 , [*path, nums[index]] , SCREAMING_SNAKE_CASE__ , remaining_nums_sum - nums[index] , )
__snake_case = [3, 34, 4, 12, 5, 2]
__snake_case = 9
__snake_case = generate_sum_of_subsets_soln(nums, max_sum)
print(*result)
| 658 | 0 |
from __future__ import annotations
def _a ( a :tuple[int, int] , a :int ) -> str:
a = position
a = [
(y + 1, x + 2),
(y - 1, x + 2),
(y + 1, x - 2),
(y - 1, x - 2),
(y + 2, x + 1),
(y + 2, x - 1),
(y - 2, x + 1),
(y - 2, x - 1),
]
a = []
for position in positions:
a = position
if 0 <= y_test < n and 0 <= x_test < n:
permissible_positions.append(SCREAMING_SNAKE_CASE__ )
return permissible_positions
def _a ( a :list[list[int]] ) -> Union[str, Any]:
return not any(elem == 0 for row in board for elem in row )
def _a ( a :list[list[int]] , a :tuple[int, int] , a :int ) -> Any:
if is_complete(SCREAMING_SNAKE_CASE__ ):
return True
for position in get_valid_pos(SCREAMING_SNAKE_CASE__ , len(SCREAMING_SNAKE_CASE__ ) ):
a = position
if board[y][x] == 0:
a = curr + 1
if open_knight_tour_helper(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , curr + 1 ):
return True
a = 0
return False
def _a ( a :int ) -> Dict:
a = [[0 for i in range(SCREAMING_SNAKE_CASE__ )] for j in range(SCREAMING_SNAKE_CASE__ )]
for i in range(SCREAMING_SNAKE_CASE__ ):
for j in range(SCREAMING_SNAKE_CASE__ ):
a = 1
if open_knight_tour_helper(SCREAMING_SNAKE_CASE__ , (i, j) , 1 ):
return board
a = 0
a = F"""Open Kight Tour cannot be performed on a board of size {n}"""
raise ValueError(SCREAMING_SNAKE_CASE__ )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 117 |
def _A ( SCREAMING_SNAKE_CASE__ : int ):
if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
raise ValueError('''check_bouncy() accepts only integer arguments''' )
UpperCamelCase :int = str(SCREAMING_SNAKE_CASE__ )
UpperCamelCase :Optional[Any] = ''''''.join(sorted(SCREAMING_SNAKE_CASE__ ) )
return sorted_str_n != str_n and sorted_str_n[::-1] != str_n
def _A ( SCREAMING_SNAKE_CASE__ : float = 99 ):
if not 0 < percent < 100:
raise ValueError('''solution() only accepts values from 0 to 100''' )
UpperCamelCase :Tuple = 0
UpperCamelCase :str = 1
while True:
if check_bouncy(SCREAMING_SNAKE_CASE__ ):
bouncy_num += 1
if (bouncy_num / num) * 100 >= percent:
return num
num += 1
if __name__ == "__main__":
from doctest import testmod
testmod()
print(f'''{solution(99)}''')
| 658 | 0 |
import gc
import tempfile
import unittest
import numpy as np
import torch
from diffusers import VersatileDiffusionTextToImagePipeline
from diffusers.utils.testing_utils import nightly, require_torch_gpu, torch_device
__UpperCamelCase : str = False
class lowercase__ ( unittest.TestCase):
pass
@nightly
@require_torch_gpu
class lowercase__ ( unittest.TestCase):
def __A ( self : Optional[int] ):
'''simple docstring'''
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def __A ( self : int ):
'''simple docstring'''
SCREAMING_SNAKE_CASE : Any = VersatileDiffusionTextToImagePipeline.from_pretrained('''shi-labs/versatile-diffusion''' )
# remove text_unet
pipe.remove_unused_weights()
pipe.to(SCREAMING_SNAKE_CASE_ )
pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ )
SCREAMING_SNAKE_CASE : str = '''A painting of a squirrel eating a burger '''
SCREAMING_SNAKE_CASE : Tuple = torch.manual_seed(0 )
SCREAMING_SNAKE_CASE : Dict = pipe(
prompt=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , guidance_scale=7.5 , num_inference_steps=2 , output_type='''numpy''' ).images
with tempfile.TemporaryDirectory() as tmpdirname:
pipe.save_pretrained(SCREAMING_SNAKE_CASE_ )
SCREAMING_SNAKE_CASE : Any = VersatileDiffusionTextToImagePipeline.from_pretrained(SCREAMING_SNAKE_CASE_ )
pipe.to(SCREAMING_SNAKE_CASE_ )
pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ )
SCREAMING_SNAKE_CASE : Union[str, Any] = generator.manual_seed(0 )
SCREAMING_SNAKE_CASE : Tuple = pipe(
prompt=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , guidance_scale=7.5 , num_inference_steps=2 , output_type='''numpy''' ).images
assert np.abs(image - new_image ).sum() < 1E-5, "Models don't have the same forward pass"
def __A ( self : int ):
'''simple docstring'''
SCREAMING_SNAKE_CASE : Optional[int] = VersatileDiffusionTextToImagePipeline.from_pretrained(
'''shi-labs/versatile-diffusion''' , torch_dtype=torch.floataa )
pipe.to(SCREAMING_SNAKE_CASE_ )
pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ )
SCREAMING_SNAKE_CASE : Optional[int] = '''A painting of a squirrel eating a burger '''
SCREAMING_SNAKE_CASE : List[Any] = torch.manual_seed(0 )
SCREAMING_SNAKE_CASE : Dict = pipe(
prompt=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , guidance_scale=7.5 , num_inference_steps=50 , output_type='''numpy''' ).images
SCREAMING_SNAKE_CASE : Tuple = image[0, 253:256, 253:256, -1]
assert image.shape == (1, 512, 512, 3)
SCREAMING_SNAKE_CASE : Union[str, Any] = np.array([0.3367, 0.3169, 0.2656, 0.3870, 0.4790, 0.3796, 0.4009, 0.4878, 0.4778] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
| 248 |
def _A ( SCREAMING_SNAKE_CASE__ : str ):
UpperCamelCase :Union[str, Any] = hex_num.strip()
if not hex_num:
raise ValueError('''No value was passed to the function''' )
UpperCamelCase :str = hex_num[0] == '''-'''
if is_negative:
UpperCamelCase :Union[str, Any] = hex_num[1:]
try:
UpperCamelCase :Optional[Any] = int(SCREAMING_SNAKE_CASE__ , 16 )
except ValueError:
raise ValueError('''Invalid value was passed to the function''' )
UpperCamelCase :Dict = ''''''
while int_num > 0:
UpperCamelCase :Tuple = str(int_num % 2 ) + bin_str
int_num >>= 1
return int(('''-''' + bin_str) if is_negative else bin_str )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 658 | 0 |
import inspect
import unittest
from transformers import ViTHybridConfig
from transformers.testing_utils import require_accelerate, require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from torch import nn
from transformers import ViTHybridForImageClassification, ViTHybridImageProcessor, ViTHybridModel
from transformers.models.vit_hybrid.modeling_vit_hybrid import VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
from PIL import Image
class UpperCamelCase__ :
def __init__(self : List[str] , snake_case_ : str , snake_case_ : int=1_3 , snake_case_ : Dict=6_4 , snake_case_ : Union[str, Any]=2 , snake_case_ : Dict=3 , snake_case_ : Union[str, Any]=True , snake_case_ : List[str]=True , snake_case_ : List[str]=3_2 , snake_case_ : Union[str, Any]=5 , snake_case_ : int=4 , snake_case_ : Any=3_7 , snake_case_ : List[str]="gelu" , snake_case_ : str=0.1 , snake_case_ : Union[str, Any]=0.1 , snake_case_ : Union[str, Any]=1_0 , snake_case_ : Optional[int]=0.02 , snake_case_ : Tuple=[1, 1_6, 4, 4] , snake_case_ : Optional[Any]=None , ):
__a : List[Any] = parent
__a : Union[str, Any] = batch_size
__a : Union[str, Any] = image_size
__a : Dict = patch_size
__a : str = num_channels
__a : Optional[int] = is_training
__a : Any = use_labels
__a : Any = hidden_size
__a : Dict = num_hidden_layers
__a : Union[str, Any] = num_attention_heads
__a : Dict = intermediate_size
__a : Tuple = hidden_act
__a : Optional[Any] = hidden_dropout_prob
__a : List[str] = attention_probs_dropout_prob
__a : Union[str, Any] = type_sequence_label_size
__a : List[Any] = initializer_range
__a : Union[str, Any] = scope
__a : str = backbone_featmap_shape
# in ViT hybrid, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
# the number of patches is based on the feature map of the backbone, which by default uses an output stride
# of 32, which means that the feature map has a spatial resolution of 1/32 of the input image size
__a : Any = (self.image_size // 3_2) ** 2
__a : List[str] = num_patches + 1
def lowerCAmelCase (self : Tuple ):
__a : Optional[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
__a : Tuple = None
if self.use_labels:
__a : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size )
__a : List[str] = self.get_config()
return config, pixel_values, labels
def lowerCAmelCase (self : int ):
__a : Optional[Any] = {
'''global_padding''': '''same''',
'''layer_type''': '''bottleneck''',
'''depths''': [3, 4, 9],
'''out_features''': ['''stage1''', '''stage2''', '''stage3'''],
'''embedding_dynamic_padding''': True,
'''hidden_sizes''': [4, 8, 1_6, 3_2],
'''num_groups''': 2,
}
return ViTHybridConfig(
image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=SCREAMING_SNAKE_CASE_ , initializer_range=self.initializer_range , backbone_featmap_shape=self.backbone_featmap_shape , backbone_config=SCREAMING_SNAKE_CASE_ , )
def lowerCAmelCase (self : Optional[Any] , snake_case_ : Optional[Any] , snake_case_ : int , snake_case_ : Dict ):
__a : Union[str, Any] = ViTHybridModel(config=SCREAMING_SNAKE_CASE_ )
model.to(SCREAMING_SNAKE_CASE_ )
model.eval()
__a : List[str] = model(SCREAMING_SNAKE_CASE_ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def lowerCAmelCase (self : List[Any] , snake_case_ : Union[str, Any] , snake_case_ : Any , snake_case_ : str ):
__a : Any = self.type_sequence_label_size
__a : int = ViTHybridForImageClassification(SCREAMING_SNAKE_CASE_ )
model.to(SCREAMING_SNAKE_CASE_ )
model.eval()
__a : Optional[Any] = model(SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) )
def lowerCAmelCase (self : List[str] ):
__a : Optional[int] = self.prepare_config_and_inputs()
__a : List[str] = config_and_inputs
__a : Optional[Any] = {'''pixel_values''': pixel_values}
return config, inputs_dict
@require_torch
class UpperCamelCase__ ( __lowercase ,__lowercase ,unittest.TestCase ):
_SCREAMING_SNAKE_CASE : Tuple = (ViTHybridModel, ViTHybridForImageClassification) if is_torch_available() else ()
_SCREAMING_SNAKE_CASE : Optional[Any] = (
{'feature-extraction': ViTHybridModel, 'image-classification': ViTHybridForImageClassification}
if is_torch_available()
else {}
)
_SCREAMING_SNAKE_CASE : Optional[Any] = False
_SCREAMING_SNAKE_CASE : Dict = False
_SCREAMING_SNAKE_CASE : Optional[int] = False
def lowerCAmelCase (self : Optional[Any] ):
__a : List[str] = ViTHybridModelTester(self )
__a : Optional[int] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , has_text_modality=SCREAMING_SNAKE_CASE_ , hidden_size=3_7 )
def lowerCAmelCase (self : int ):
self.config_tester.run_common_tests()
@unittest.skip(reason='''ViT does not use inputs_embeds''' )
def lowerCAmelCase (self : List[Any] ):
pass
def lowerCAmelCase (self : Union[str, Any] ):
__a : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__a : Optional[Any] = model_class(SCREAMING_SNAKE_CASE_ )
self.assertIsInstance(model.get_input_embeddings() , (nn.Module) )
__a : str = model.get_output_embeddings()
self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE_ , nn.Linear ) )
def lowerCAmelCase (self : Tuple ):
__a : Tuple = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__a : List[str] = model_class(SCREAMING_SNAKE_CASE_ )
__a : Union[str, Any] = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
__a : Optional[Any] = [*signature.parameters.keys()]
__a : str = ['''pixel_values''']
self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE_ )
def lowerCAmelCase (self : Optional[Any] ):
__a : Dict = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ )
def lowerCAmelCase (self : Union[str, Any] ):
__a : Tuple = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE_ )
def lowerCAmelCase (self : Optional[int] ):
__a : List[Any] = self.model_tester.prepare_config_and_inputs_for_common()
__a : List[str] = _config_zero_init(SCREAMING_SNAKE_CASE_ )
for model_class in self.all_model_classes:
__a : Union[str, Any] = model_class(config=SCREAMING_SNAKE_CASE_ )
# Skip the check for the backbone
for name, module in model.named_modules():
if module.__class__.__name__ == "ViTHybridPatchEmbeddings":
__a : Tuple = [f"{name}.{key}" for key in module.state_dict().keys()]
break
for name, param in model.named_parameters():
if param.requires_grad:
if name in backbone_params:
continue
self.assertIn(
((param.data.mean() * 1E9).round() / 1E9).item() , [0.0, 1.0] , msg=f"Parameter {name} of model {model_class} seems not properly initialized" , )
@slow
def lowerCAmelCase (self : List[Any] ):
for model_name in VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
__a : List[str] = ViTHybridModel.from_pretrained(SCREAMING_SNAKE_CASE_ )
self.assertIsNotNone(SCREAMING_SNAKE_CASE_ )
def __UpperCamelCase ( ):
__a : Tuple = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
return image
@require_torch
@require_vision
class UpperCamelCase__ ( unittest.TestCase ):
@cached_property
def lowerCAmelCase (self : Dict ):
return (
ViTHybridImageProcessor.from_pretrained(VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[0] )
if is_vision_available()
else None
)
@slow
def lowerCAmelCase (self : str ):
__a : Optional[Any] = ViTHybridForImageClassification.from_pretrained(VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to(
SCREAMING_SNAKE_CASE_ )
__a : Optional[int] = self.default_image_processor
__a : str = prepare_img()
__a : int = image_processor(images=SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' ).to(SCREAMING_SNAKE_CASE_ )
# forward pass
with torch.no_grad():
__a : Optional[int] = model(**SCREAMING_SNAKE_CASE_ )
# verify the logits
__a : Union[str, Any] = torch.Size((1, 1_0_0_0) )
self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE_ )
__a : str = torch.tensor([-1.9090, -0.4993, -0.2389] ).to(SCREAMING_SNAKE_CASE_ )
self.assertTrue(torch.allclose(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE_ , atol=1E-4 ) )
@slow
@require_accelerate
def lowerCAmelCase (self : Dict ):
__a : List[Any] = ViTHybridImageProcessor.from_pretrained('''google/vit-hybrid-base-bit-384''' )
__a : Optional[Any] = ViTHybridForImageClassification.from_pretrained('''google/vit-hybrid-base-bit-384''' , device_map='''auto''' )
__a : Union[str, Any] = prepare_img()
__a : Optional[int] = image_processor(images=SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' )
__a : int = model(**SCREAMING_SNAKE_CASE_ )
__a : Optional[Any] = outputs.logits
# model predicts one of the 1000 ImageNet classes
__a : List[Any] = logits.argmax(-1 ).item()
self.assertTrue(model.config.idalabel[predicted_class_idx] , '''tabby, tabby cat''' )
| 521 |
from __future__ import annotations
def _A ( SCREAMING_SNAKE_CASE__ : tuple[int, int] , SCREAMING_SNAKE_CASE__ : int ):
UpperCamelCase , UpperCamelCase :List[Any] = position
UpperCamelCase :Any = [
(y + 1, x + 2),
(y - 1, x + 2),
(y + 1, x - 2),
(y - 1, x - 2),
(y + 2, x + 1),
(y + 2, x - 1),
(y - 2, x + 1),
(y - 2, x - 1),
]
UpperCamelCase :Dict = []
for position in positions:
UpperCamelCase , UpperCamelCase :str = position
if 0 <= y_test < n and 0 <= x_test < n:
permissible_positions.append(SCREAMING_SNAKE_CASE__ )
return permissible_positions
def _A ( SCREAMING_SNAKE_CASE__ : list[list[int]] ):
return not any(elem == 0 for row in board for elem in row )
def _A ( SCREAMING_SNAKE_CASE__ : list[list[int]] , SCREAMING_SNAKE_CASE__ : tuple[int, int] , SCREAMING_SNAKE_CASE__ : int ):
if is_complete(SCREAMING_SNAKE_CASE__ ):
return True
for position in get_valid_pos(SCREAMING_SNAKE_CASE__ , len(SCREAMING_SNAKE_CASE__ ) ):
UpperCamelCase , UpperCamelCase :Optional[int] = position
if board[y][x] == 0:
UpperCamelCase :Any = curr + 1
if open_knight_tour_helper(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , curr + 1 ):
return True
UpperCamelCase :Union[str, Any] = 0
return False
def _A ( SCREAMING_SNAKE_CASE__ : int ):
UpperCamelCase :List[Any] = [[0 for i in range(SCREAMING_SNAKE_CASE__ )] for j in range(SCREAMING_SNAKE_CASE__ )]
for i in range(SCREAMING_SNAKE_CASE__ ):
for j in range(SCREAMING_SNAKE_CASE__ ):
UpperCamelCase :Tuple = 1
if open_knight_tour_helper(SCREAMING_SNAKE_CASE__ , (i, j) , 1 ):
return board
UpperCamelCase :str = 0
UpperCamelCase :List[Any] = F'''Open Kight Tour cannot be performed on a board of size {n}'''
raise ValueError(SCREAMING_SNAKE_CASE__ )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 658 | 0 |
"""simple docstring"""
import argparse
import json
import logging
import os
import sys
from unittest.mock import patch
from transformers.testing_utils import TestCasePlus, get_gpu_count, slow
UpperCAmelCase = [
os.path.join(os.path.dirname(__file__), dirname)
for dirname in [
"""text-classification""",
"""language-modeling""",
"""summarization""",
"""token-classification""",
"""question-answering""",
]
]
sys.path.extend(SRC_DIRS)
if SRC_DIRS is not None:
import run_clm_flax
import run_flax_glue
import run_flax_ner
import run_mlm_flax
import run_qa
import run_summarization_flax
import run_ta_mlm_flax
logging.basicConfig(level=logging.DEBUG)
UpperCAmelCase = logging.getLogger()
def __magic_name__ ( ) -> Any:
'''simple docstring'''
lowerCAmelCase = argparse.ArgumentParser()
parser.add_argument('''-f''' )
lowerCAmelCase = parser.parse_args()
return args.f
def __magic_name__ ( _lowerCamelCase: Optional[int], _lowerCamelCase: Optional[int]="eval" ) -> Dict:
'''simple docstring'''
lowerCAmelCase = os.path.join(SCREAMING_SNAKE_CASE__, F"""{split}_results.json""" )
if os.path.exists(SCREAMING_SNAKE_CASE__ ):
with open(SCREAMING_SNAKE_CASE__, '''r''' ) as f:
return json.load(SCREAMING_SNAKE_CASE__ )
raise ValueError(F"""can\'t find {path}""" )
UpperCAmelCase = logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)
class lowercase ( lowercase__ ):
def UpperCAmelCase (self : str ) -> List[Any]:
"""simple docstring"""
lowerCAmelCase = self.get_auto_remove_tmp_dir()
lowerCAmelCase = F"""
run_glue.py
--model_name_or_path distilbert-base-uncased
--output_dir {tmp_dir}
--train_file ./tests/fixtures/tests_samples/MRPC/train.csv
--validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv
--per_device_train_batch_size=2
--per_device_eval_batch_size=1
--learning_rate=1e-4
--eval_steps=2
--warmup_steps=2
--seed=42
--max_seq_length=128
""".split()
with patch.object(SCREAMING_SNAKE_CASE_ ,'''argv''' ,SCREAMING_SNAKE_CASE_ ):
run_flax_glue.main()
lowerCAmelCase = get_results(SCREAMING_SNAKE_CASE_ )
self.assertGreaterEqual(result['''eval_accuracy'''] ,0.75 )
@slow
def UpperCAmelCase (self : Optional[Any] ) -> Union[str, Any]:
"""simple docstring"""
lowerCAmelCase = self.get_auto_remove_tmp_dir()
lowerCAmelCase = F"""
run_clm_flax.py
--model_name_or_path distilgpt2
--train_file ./tests/fixtures/sample_text.txt
--validation_file ./tests/fixtures/sample_text.txt
--do_train
--do_eval
--block_size 128
--per_device_train_batch_size 4
--per_device_eval_batch_size 4
--num_train_epochs 2
--logging_steps 2 --eval_steps 2
--output_dir {tmp_dir}
--overwrite_output_dir
""".split()
with patch.object(SCREAMING_SNAKE_CASE_ ,'''argv''' ,SCREAMING_SNAKE_CASE_ ):
run_clm_flax.main()
lowerCAmelCase = get_results(SCREAMING_SNAKE_CASE_ )
self.assertLess(result['''eval_perplexity'''] ,100 )
@slow
def UpperCAmelCase (self : Optional[int] ) -> Tuple:
"""simple docstring"""
lowerCAmelCase = self.get_auto_remove_tmp_dir()
lowerCAmelCase = F"""
run_summarization.py
--model_name_or_path t5-small
--train_file tests/fixtures/tests_samples/xsum/sample.json
--validation_file tests/fixtures/tests_samples/xsum/sample.json
--test_file tests/fixtures/tests_samples/xsum/sample.json
--output_dir {tmp_dir}
--overwrite_output_dir
--num_train_epochs=3
--warmup_steps=8
--do_train
--do_eval
--do_predict
--learning_rate=2e-4
--per_device_train_batch_size=2
--per_device_eval_batch_size=1
--predict_with_generate
""".split()
with patch.object(SCREAMING_SNAKE_CASE_ ,'''argv''' ,SCREAMING_SNAKE_CASE_ ):
run_summarization_flax.main()
lowerCAmelCase = get_results(SCREAMING_SNAKE_CASE_ ,split='''test''' )
self.assertGreaterEqual(result['''test_rouge1'''] ,10 )
self.assertGreaterEqual(result['''test_rouge2'''] ,2 )
self.assertGreaterEqual(result['''test_rougeL'''] ,7 )
self.assertGreaterEqual(result['''test_rougeLsum'''] ,7 )
@slow
def UpperCAmelCase (self : Optional[int] ) -> Union[str, Any]:
"""simple docstring"""
lowerCAmelCase = self.get_auto_remove_tmp_dir()
lowerCAmelCase = F"""
run_mlm.py
--model_name_or_path distilroberta-base
--train_file ./tests/fixtures/sample_text.txt
--validation_file ./tests/fixtures/sample_text.txt
--output_dir {tmp_dir}
--overwrite_output_dir
--max_seq_length 128
--per_device_train_batch_size 4
--per_device_eval_batch_size 4
--logging_steps 2 --eval_steps 2
--do_train
--do_eval
--num_train_epochs=1
""".split()
with patch.object(SCREAMING_SNAKE_CASE_ ,'''argv''' ,SCREAMING_SNAKE_CASE_ ):
run_mlm_flax.main()
lowerCAmelCase = get_results(SCREAMING_SNAKE_CASE_ )
self.assertLess(result['''eval_perplexity'''] ,42 )
@slow
def UpperCAmelCase (self : Dict ) -> Optional[int]:
"""simple docstring"""
lowerCAmelCase = self.get_auto_remove_tmp_dir()
lowerCAmelCase = F"""
run_t5_mlm_flax.py
--model_name_or_path t5-small
--train_file ./tests/fixtures/sample_text.txt
--validation_file ./tests/fixtures/sample_text.txt
--do_train
--do_eval
--max_seq_length 128
--per_device_train_batch_size 4
--per_device_eval_batch_size 4
--num_train_epochs 2
--logging_steps 2 --eval_steps 2
--output_dir {tmp_dir}
--overwrite_output_dir
""".split()
with patch.object(SCREAMING_SNAKE_CASE_ ,'''argv''' ,SCREAMING_SNAKE_CASE_ ):
run_ta_mlm_flax.main()
lowerCAmelCase = get_results(SCREAMING_SNAKE_CASE_ )
self.assertGreaterEqual(result['''eval_accuracy'''] ,0.42 )
@slow
def UpperCAmelCase (self : Dict ) -> Tuple:
"""simple docstring"""
lowerCAmelCase = 7 if get_gpu_count() > 1 else 2
lowerCAmelCase = self.get_auto_remove_tmp_dir()
lowerCAmelCase = F"""
run_flax_ner.py
--model_name_or_path bert-base-uncased
--train_file tests/fixtures/tests_samples/conll/sample.json
--validation_file tests/fixtures/tests_samples/conll/sample.json
--output_dir {tmp_dir}
--overwrite_output_dir
--do_train
--do_eval
--warmup_steps=2
--learning_rate=2e-4
--logging_steps 2 --eval_steps 2
--per_device_train_batch_size=2
--per_device_eval_batch_size=2
--num_train_epochs={epochs}
--seed 7
""".split()
with patch.object(SCREAMING_SNAKE_CASE_ ,'''argv''' ,SCREAMING_SNAKE_CASE_ ):
run_flax_ner.main()
lowerCAmelCase = get_results(SCREAMING_SNAKE_CASE_ )
self.assertGreaterEqual(result['''eval_accuracy'''] ,0.75 )
self.assertGreaterEqual(result['''eval_f1'''] ,0.3 )
@slow
def UpperCAmelCase (self : List[str] ) -> Any:
"""simple docstring"""
lowerCAmelCase = self.get_auto_remove_tmp_dir()
lowerCAmelCase = F"""
run_qa.py
--model_name_or_path bert-base-uncased
--version_2_with_negative
--train_file tests/fixtures/tests_samples/SQUAD/sample.json
--validation_file tests/fixtures/tests_samples/SQUAD/sample.json
--output_dir {tmp_dir}
--overwrite_output_dir
--num_train_epochs=3
--warmup_steps=2
--do_train
--do_eval
--logging_steps 2 --eval_steps 2
--learning_rate=2e-4
--per_device_train_batch_size=2
--per_device_eval_batch_size=1
""".split()
with patch.object(SCREAMING_SNAKE_CASE_ ,'''argv''' ,SCREAMING_SNAKE_CASE_ ):
run_qa.main()
lowerCAmelCase = get_results(SCREAMING_SNAKE_CASE_ )
self.assertGreaterEqual(result['''eval_f1'''] ,30 )
self.assertGreaterEqual(result['''eval_exact'''] ,30 )
| 535 |
import copy
import tempfile
import unittest
from huggingface_hub import HfFolder, delete_repo
from parameterized import parameterized
from requests.exceptions import HTTPError
from transformers import AutoConfig, GenerationConfig
from transformers.testing_utils import TOKEN, USER, is_staging_test
class UpperCAmelCase_ ( unittest.TestCase ):
"""simple docstring"""
@parameterized.expand([(None,), ('''foo.json''',)] )
def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ ) -> List[str]:
UpperCamelCase :int = GenerationConfig(
do_sample=SCREAMING_SNAKE_CASE_ , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , )
with tempfile.TemporaryDirectory() as tmp_dir:
config.save_pretrained(SCREAMING_SNAKE_CASE_ , config_name=SCREAMING_SNAKE_CASE_ )
UpperCamelCase :str = GenerationConfig.from_pretrained(SCREAMING_SNAKE_CASE_ , config_name=SCREAMING_SNAKE_CASE_ )
# Checks parameters that were specified
self.assertEqual(loaded_config.do_sample , SCREAMING_SNAKE_CASE_ )
self.assertEqual(loaded_config.temperature , 0.7 )
self.assertEqual(loaded_config.length_penalty , 1.0 )
self.assertEqual(loaded_config.bad_words_ids , [[1, 2, 3], [4, 5]] )
# Checks parameters that were not specified (defaults)
self.assertEqual(loaded_config.top_k , 50 )
self.assertEqual(loaded_config.max_length , 20 )
self.assertEqual(loaded_config.max_time , SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self ) -> str:
UpperCamelCase :Optional[Any] = AutoConfig.from_pretrained('''gpt2''' )
UpperCamelCase :Union[str, Any] = GenerationConfig.from_model_config(SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Optional[Any] = GenerationConfig()
# The generation config has loaded a few non-default parameters from the model config
self.assertNotEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# One of those parameters is eos_token_id -- check if it matches
self.assertNotEqual(generation_config_from_model.eos_token_id , default_generation_config.eos_token_id )
self.assertEqual(generation_config_from_model.eos_token_id , model_config.eos_token_id )
def UpperCAmelCase ( self ) -> Dict:
UpperCamelCase :List[str] = GenerationConfig()
UpperCamelCase :List[str] = {
'''max_new_tokens''': 1024,
'''foo''': '''bar''',
}
UpperCamelCase :Dict = copy.deepcopy(SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Any = generation_config.update(**SCREAMING_SNAKE_CASE_ )
# update_kwargs was not modified (no side effects)
self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# update_kwargs was used to update the config on valid attributes
self.assertEqual(generation_config.max_new_tokens , 1024 )
# `.update()` returns a dictionary of unused kwargs
self.assertEqual(SCREAMING_SNAKE_CASE_ , {'''foo''': '''bar'''} )
def UpperCAmelCase ( self ) -> Optional[Any]:
UpperCamelCase :List[Any] = GenerationConfig()
UpperCamelCase :Tuple = '''bar'''
with tempfile.TemporaryDirectory('''test-generation-config''' ) as tmp_dir:
generation_config.save_pretrained(SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Any = GenerationConfig.from_pretrained(SCREAMING_SNAKE_CASE_ )
# update_kwargs was used to update the config on valid attributes
self.assertEqual(new_config.foo , '''bar''' )
UpperCamelCase :Union[str, Any] = GenerationConfig.from_model_config(SCREAMING_SNAKE_CASE_ )
assert not hasattr(SCREAMING_SNAKE_CASE_ , '''foo''' ) # no new kwargs should be initialized if from config
def UpperCAmelCase ( self ) -> Any:
UpperCamelCase :Dict = GenerationConfig()
self.assertEqual(default_config.temperature , 1.0 )
self.assertEqual(default_config.do_sample , SCREAMING_SNAKE_CASE_ )
self.assertEqual(default_config.num_beams , 1 )
UpperCamelCase :Tuple = GenerationConfig(
do_sample=SCREAMING_SNAKE_CASE_ , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , )
self.assertEqual(config.temperature , 0.7 )
self.assertEqual(config.do_sample , SCREAMING_SNAKE_CASE_ )
self.assertEqual(config.num_beams , 1 )
with tempfile.TemporaryDirectory() as tmp_dir:
config.save_pretrained(SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Tuple = GenerationConfig.from_pretrained(SCREAMING_SNAKE_CASE_ , temperature=1.0 )
self.assertEqual(loaded_config.temperature , 1.0 )
self.assertEqual(loaded_config.do_sample , SCREAMING_SNAKE_CASE_ )
self.assertEqual(loaded_config.num_beams , 1 ) # default value
@is_staging_test
class UpperCAmelCase_ ( unittest.TestCase ):
"""simple docstring"""
@classmethod
def UpperCAmelCase ( cls ) -> Optional[Any]:
UpperCamelCase :List[str] = TOKEN
HfFolder.save_token(SCREAMING_SNAKE_CASE_ )
@classmethod
def UpperCAmelCase ( cls ) -> Union[str, Any]:
try:
delete_repo(token=cls._token , repo_id='''test-generation-config''' )
except HTTPError:
pass
try:
delete_repo(token=cls._token , repo_id='''valid_org/test-generation-config-org''' )
except HTTPError:
pass
def UpperCAmelCase ( self ) -> Any:
UpperCamelCase :Optional[Any] = GenerationConfig(
do_sample=SCREAMING_SNAKE_CASE_ , temperature=0.7 , length_penalty=1.0 , )
config.push_to_hub('''test-generation-config''' , use_auth_token=self._token )
UpperCamelCase :List[Any] = GenerationConfig.from_pretrained(F'''{USER}/test-generation-config''' )
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(SCREAMING_SNAKE_CASE_ , getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) )
# Reset repo
delete_repo(token=self._token , repo_id='''test-generation-config''' )
# Push to hub via save_pretrained
with tempfile.TemporaryDirectory() as tmp_dir:
config.save_pretrained(
SCREAMING_SNAKE_CASE_ , repo_id='''test-generation-config''' , push_to_hub=SCREAMING_SNAKE_CASE_ , use_auth_token=self._token )
UpperCamelCase :Any = GenerationConfig.from_pretrained(F'''{USER}/test-generation-config''' )
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(SCREAMING_SNAKE_CASE_ , getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) )
def UpperCAmelCase ( self ) -> Union[str, Any]:
UpperCamelCase :List[str] = GenerationConfig(
do_sample=SCREAMING_SNAKE_CASE_ , temperature=0.7 , length_penalty=1.0 , )
config.push_to_hub('''valid_org/test-generation-config-org''' , use_auth_token=self._token )
UpperCamelCase :Any = GenerationConfig.from_pretrained('''valid_org/test-generation-config-org''' )
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(SCREAMING_SNAKE_CASE_ , getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) )
# Reset repo
delete_repo(token=self._token , repo_id='''valid_org/test-generation-config-org''' )
# Push to hub via save_pretrained
with tempfile.TemporaryDirectory() as tmp_dir:
config.save_pretrained(
SCREAMING_SNAKE_CASE_ , repo_id='''valid_org/test-generation-config-org''' , push_to_hub=SCREAMING_SNAKE_CASE_ , use_auth_token=self._token )
UpperCamelCase :Tuple = GenerationConfig.from_pretrained('''valid_org/test-generation-config-org''' )
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(SCREAMING_SNAKE_CASE_ , getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) )
| 658 | 0 |
"""simple docstring"""
from collections import OrderedDict
from typing import Any, List, Mapping, Optional
from ... import PreTrainedTokenizer, TensorType, is_torch_available
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfigWithPast, PatchingSpec
from ...utils import logging
lowerCAmelCase: Dict =logging.get_logger(__name__)
lowerCAmelCase: str ={
"EleutherAI/gpt-j-6B": "https://huggingface.co/EleutherAI/gpt-j-6B/resolve/main/config.json",
# See all GPT-J models at https://huggingface.co/models?filter=gpt_j
}
class lowerCamelCase__ ( __UpperCamelCase ):
__UpperCAmelCase = 'gptj'
__UpperCAmelCase = {
'max_position_embeddings': 'n_positions',
'hidden_size': 'n_embd',
'num_attention_heads': 'n_head',
'num_hidden_layers': 'n_layer',
}
def __init__( self , snake_case=5_0_4_0_0 , snake_case=2_0_4_8 , snake_case=4_0_9_6 , snake_case=2_8 , snake_case=1_6 , snake_case=6_4 , snake_case=None , snake_case="gelu_new" , snake_case=0.0 , snake_case=0.0 , snake_case=0.0 , snake_case=1E-5 , snake_case=0.02 , snake_case=True , snake_case=5_0_2_5_6 , snake_case=5_0_2_5_6 , snake_case=False , **snake_case , ) -> Union[str, Any]:
"""simple docstring"""
lowercase : Optional[int] = vocab_size
lowercase : List[Any] = n_positions
lowercase : Union[str, Any] = n_embd
lowercase : Optional[int] = n_layer
lowercase : Any = n_head
lowercase : Any = n_inner
lowercase : List[Any] = rotary_dim
lowercase : List[str] = activation_function
lowercase : Any = resid_pdrop
lowercase : List[Any] = embd_pdrop
lowercase : List[Any] = attn_pdrop
lowercase : Optional[Any] = layer_norm_epsilon
lowercase : int = initializer_range
lowercase : Optional[Any] = use_cache
lowercase : Tuple = bos_token_id
lowercase : int = eos_token_id
super().__init__(
bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , tie_word_embeddings=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
class lowerCamelCase__ ( __UpperCamelCase ):
def __init__( self , snake_case , snake_case = "default" , snake_case = None , snake_case = False , ) -> List[Any]:
"""simple docstring"""
super().__init__(SCREAMING_SNAKE_CASE_ , task=SCREAMING_SNAKE_CASE_ , patching_specs=SCREAMING_SNAKE_CASE_ , use_past=SCREAMING_SNAKE_CASE_ )
if not getattr(self._config , """pad_token_id""" , SCREAMING_SNAKE_CASE_ ):
# TODO: how to do that better?
lowercase : List[Any] = 0
@property
def _UpperCAmelCase ( self ) -> Mapping[str, Mapping[int, str]]:
"""simple docstring"""
lowercase : Optional[Any] = OrderedDict({"""input_ids""": {0: """batch""", 1: """sequence"""}} )
if self.use_past:
self.fill_with_past_key_values_(SCREAMING_SNAKE_CASE_ , direction="""inputs""" )
lowercase : str = {0: '''batch''', 1: '''past_sequence + sequence'''}
else:
lowercase : List[Any] = {0: '''batch''', 1: '''sequence'''}
return common_inputs
@property
def _UpperCAmelCase ( self ) -> int:
"""simple docstring"""
return self._config.n_layer
@property
def _UpperCAmelCase ( self ) -> int:
"""simple docstring"""
return self._config.n_head
def _UpperCAmelCase ( self , snake_case , snake_case = -1 , snake_case = -1 , snake_case = False , snake_case = None , ) -> Mapping[str, Any]:
"""simple docstring"""
lowercase : Any = super(SCREAMING_SNAKE_CASE_ , self ).generate_dummy_inputs(
SCREAMING_SNAKE_CASE_ , batch_size=SCREAMING_SNAKE_CASE_ , seq_length=SCREAMING_SNAKE_CASE_ , is_pair=SCREAMING_SNAKE_CASE_ , framework=SCREAMING_SNAKE_CASE_ )
# We need to order the input in the way they appears in the forward()
lowercase : Tuple = OrderedDict({"""input_ids""": common_inputs["""input_ids"""]} )
# Need to add the past_keys
if self.use_past:
if not is_torch_available():
raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed.""" )
else:
import torch
lowercase : List[Any] = common_inputs['''input_ids'''].shape
# Not using the same length for past_key_values
lowercase : Union[str, Any] = seqlen + 2
lowercase : Union[str, Any] = (
batch,
self.num_attention_heads,
past_key_values_length,
self._config.hidden_size // self.num_attention_heads,
)
lowercase : Optional[Any] = [
(torch.zeros(SCREAMING_SNAKE_CASE_ ), torch.zeros(SCREAMING_SNAKE_CASE_ )) for _ in range(self.num_layers )
]
lowercase : Union[str, Any] = common_inputs['''attention_mask''']
if self.use_past:
lowercase : List[Any] = ordered_inputs['''attention_mask'''].dtype
lowercase : List[Any] = torch.cat(
[ordered_inputs["""attention_mask"""], torch.ones(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , dtype=SCREAMING_SNAKE_CASE_ )] , dim=1 )
return ordered_inputs
@property
def _UpperCAmelCase ( self ) -> int:
"""simple docstring"""
return 1_3
| 607 |
def _A ( SCREAMING_SNAKE_CASE__ : int ):
if length <= 0 or not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
raise ValueError('''Length must be a positive integer.''' )
return [n * (2 * n - 1) for n in range(SCREAMING_SNAKE_CASE__ )]
if __name__ == "__main__":
print(hexagonal_numbers(length=5))
print(hexagonal_numbers(length=10))
| 658 | 0 |
from typing import List, Optional, Union
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType
class A__ ( A__ ):
"""simple docstring"""
_lowercase = ['image_processor', 'tokenizer']
_lowercase = 'BridgeTowerImageProcessor'
_lowercase = ('RobertaTokenizer', 'RobertaTokenizerFast')
def __init__( self : Optional[int] , lowerCamelCase__ : Dict , lowerCamelCase__ : Optional[int] ):
super().__init__(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
def __call__( self : Any , lowerCamelCase__ : List[str] , lowerCamelCase__ : Tuple = None , lowerCamelCase__ : List[str] = True , lowerCamelCase__ : Optional[int] = False , lowerCamelCase__ : Any = None , lowerCamelCase__ : Dict = None , lowerCamelCase__ : int = 0 , lowerCamelCase__ : int = None , lowerCamelCase__ : Union[str, Any] = None , lowerCamelCase__ : Optional[Any] = None , lowerCamelCase__ : str = False , lowerCamelCase__ : Union[str, Any] = False , lowerCamelCase__ : Dict = False , lowerCamelCase__ : int = False , lowerCamelCase__ : Tuple = True , lowerCamelCase__ : Any = None , **lowerCamelCase__ : Tuple , ):
a__ : Dict = self.tokenizer(
text=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , stride=SCREAMING_SNAKE_CASE_ , pad_to_multiple_of=SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , return_overflowing_tokens=SCREAMING_SNAKE_CASE_ , return_special_tokens_mask=SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , return_length=SCREAMING_SNAKE_CASE_ , verbose=SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , )
# add pixel_values + pixel_mask
a__ : List[str] = self.image_processor(
SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ , do_normalize=SCREAMING_SNAKE_CASE_ , do_center_crop=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
encoding.update(SCREAMING_SNAKE_CASE_ )
return encoding
def _UpperCamelCase( self : int , *lowerCamelCase__ : Optional[Any] , **lowerCamelCase__ : Optional[int] ):
return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
def _UpperCamelCase( self : Tuple , *lowerCamelCase__ : Optional[Any] , **lowerCamelCase__ : List[Any] ):
return self.tokenizer.decode(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
@property
def _UpperCamelCase( self : Dict ):
a__ : List[Any] = self.tokenizer.model_input_names
a__ : int = self.image_processor.model_input_names
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
| 37 |
# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer
from .base import PipelineTool
__snake_case = {
"""Acehnese Arabic""": """ace_Arab""",
"""Acehnese Latin""": """ace_Latn""",
"""Mesopotamian Arabic""": """acm_Arab""",
"""Ta'izzi-Adeni Arabic""": """acq_Arab""",
"""Tunisian Arabic""": """aeb_Arab""",
"""Afrikaans""": """afr_Latn""",
"""South Levantine Arabic""": """ajp_Arab""",
"""Akan""": """aka_Latn""",
"""Amharic""": """amh_Ethi""",
"""North Levantine Arabic""": """apc_Arab""",
"""Modern Standard Arabic""": """arb_Arab""",
"""Modern Standard Arabic Romanized""": """arb_Latn""",
"""Najdi Arabic""": """ars_Arab""",
"""Moroccan Arabic""": """ary_Arab""",
"""Egyptian Arabic""": """arz_Arab""",
"""Assamese""": """asm_Beng""",
"""Asturian""": """ast_Latn""",
"""Awadhi""": """awa_Deva""",
"""Central Aymara""": """ayr_Latn""",
"""South Azerbaijani""": """azb_Arab""",
"""North Azerbaijani""": """azj_Latn""",
"""Bashkir""": """bak_Cyrl""",
"""Bambara""": """bam_Latn""",
"""Balinese""": """ban_Latn""",
"""Belarusian""": """bel_Cyrl""",
"""Bemba""": """bem_Latn""",
"""Bengali""": """ben_Beng""",
"""Bhojpuri""": """bho_Deva""",
"""Banjar Arabic""": """bjn_Arab""",
"""Banjar Latin""": """bjn_Latn""",
"""Standard Tibetan""": """bod_Tibt""",
"""Bosnian""": """bos_Latn""",
"""Buginese""": """bug_Latn""",
"""Bulgarian""": """bul_Cyrl""",
"""Catalan""": """cat_Latn""",
"""Cebuano""": """ceb_Latn""",
"""Czech""": """ces_Latn""",
"""Chokwe""": """cjk_Latn""",
"""Central Kurdish""": """ckb_Arab""",
"""Crimean Tatar""": """crh_Latn""",
"""Welsh""": """cym_Latn""",
"""Danish""": """dan_Latn""",
"""German""": """deu_Latn""",
"""Southwestern Dinka""": """dik_Latn""",
"""Dyula""": """dyu_Latn""",
"""Dzongkha""": """dzo_Tibt""",
"""Greek""": """ell_Grek""",
"""English""": """eng_Latn""",
"""Esperanto""": """epo_Latn""",
"""Estonian""": """est_Latn""",
"""Basque""": """eus_Latn""",
"""Ewe""": """ewe_Latn""",
"""Faroese""": """fao_Latn""",
"""Fijian""": """fij_Latn""",
"""Finnish""": """fin_Latn""",
"""Fon""": """fon_Latn""",
"""French""": """fra_Latn""",
"""Friulian""": """fur_Latn""",
"""Nigerian Fulfulde""": """fuv_Latn""",
"""Scottish Gaelic""": """gla_Latn""",
"""Irish""": """gle_Latn""",
"""Galician""": """glg_Latn""",
"""Guarani""": """grn_Latn""",
"""Gujarati""": """guj_Gujr""",
"""Haitian Creole""": """hat_Latn""",
"""Hausa""": """hau_Latn""",
"""Hebrew""": """heb_Hebr""",
"""Hindi""": """hin_Deva""",
"""Chhattisgarhi""": """hne_Deva""",
"""Croatian""": """hrv_Latn""",
"""Hungarian""": """hun_Latn""",
"""Armenian""": """hye_Armn""",
"""Igbo""": """ibo_Latn""",
"""Ilocano""": """ilo_Latn""",
"""Indonesian""": """ind_Latn""",
"""Icelandic""": """isl_Latn""",
"""Italian""": """ita_Latn""",
"""Javanese""": """jav_Latn""",
"""Japanese""": """jpn_Jpan""",
"""Kabyle""": """kab_Latn""",
"""Jingpho""": """kac_Latn""",
"""Kamba""": """kam_Latn""",
"""Kannada""": """kan_Knda""",
"""Kashmiri Arabic""": """kas_Arab""",
"""Kashmiri Devanagari""": """kas_Deva""",
"""Georgian""": """kat_Geor""",
"""Central Kanuri Arabic""": """knc_Arab""",
"""Central Kanuri Latin""": """knc_Latn""",
"""Kazakh""": """kaz_Cyrl""",
"""Kabiyè""": """kbp_Latn""",
"""Kabuverdianu""": """kea_Latn""",
"""Khmer""": """khm_Khmr""",
"""Kikuyu""": """kik_Latn""",
"""Kinyarwanda""": """kin_Latn""",
"""Kyrgyz""": """kir_Cyrl""",
"""Kimbundu""": """kmb_Latn""",
"""Northern Kurdish""": """kmr_Latn""",
"""Kikongo""": """kon_Latn""",
"""Korean""": """kor_Hang""",
"""Lao""": """lao_Laoo""",
"""Ligurian""": """lij_Latn""",
"""Limburgish""": """lim_Latn""",
"""Lingala""": """lin_Latn""",
"""Lithuanian""": """lit_Latn""",
"""Lombard""": """lmo_Latn""",
"""Latgalian""": """ltg_Latn""",
"""Luxembourgish""": """ltz_Latn""",
"""Luba-Kasai""": """lua_Latn""",
"""Ganda""": """lug_Latn""",
"""Luo""": """luo_Latn""",
"""Mizo""": """lus_Latn""",
"""Standard Latvian""": """lvs_Latn""",
"""Magahi""": """mag_Deva""",
"""Maithili""": """mai_Deva""",
"""Malayalam""": """mal_Mlym""",
"""Marathi""": """mar_Deva""",
"""Minangkabau Arabic """: """min_Arab""",
"""Minangkabau Latin""": """min_Latn""",
"""Macedonian""": """mkd_Cyrl""",
"""Plateau Malagasy""": """plt_Latn""",
"""Maltese""": """mlt_Latn""",
"""Meitei Bengali""": """mni_Beng""",
"""Halh Mongolian""": """khk_Cyrl""",
"""Mossi""": """mos_Latn""",
"""Maori""": """mri_Latn""",
"""Burmese""": """mya_Mymr""",
"""Dutch""": """nld_Latn""",
"""Norwegian Nynorsk""": """nno_Latn""",
"""Norwegian Bokmål""": """nob_Latn""",
"""Nepali""": """npi_Deva""",
"""Northern Sotho""": """nso_Latn""",
"""Nuer""": """nus_Latn""",
"""Nyanja""": """nya_Latn""",
"""Occitan""": """oci_Latn""",
"""West Central Oromo""": """gaz_Latn""",
"""Odia""": """ory_Orya""",
"""Pangasinan""": """pag_Latn""",
"""Eastern Panjabi""": """pan_Guru""",
"""Papiamento""": """pap_Latn""",
"""Western Persian""": """pes_Arab""",
"""Polish""": """pol_Latn""",
"""Portuguese""": """por_Latn""",
"""Dari""": """prs_Arab""",
"""Southern Pashto""": """pbt_Arab""",
"""Ayacucho Quechua""": """quy_Latn""",
"""Romanian""": """ron_Latn""",
"""Rundi""": """run_Latn""",
"""Russian""": """rus_Cyrl""",
"""Sango""": """sag_Latn""",
"""Sanskrit""": """san_Deva""",
"""Santali""": """sat_Olck""",
"""Sicilian""": """scn_Latn""",
"""Shan""": """shn_Mymr""",
"""Sinhala""": """sin_Sinh""",
"""Slovak""": """slk_Latn""",
"""Slovenian""": """slv_Latn""",
"""Samoan""": """smo_Latn""",
"""Shona""": """sna_Latn""",
"""Sindhi""": """snd_Arab""",
"""Somali""": """som_Latn""",
"""Southern Sotho""": """sot_Latn""",
"""Spanish""": """spa_Latn""",
"""Tosk Albanian""": """als_Latn""",
"""Sardinian""": """srd_Latn""",
"""Serbian""": """srp_Cyrl""",
"""Swati""": """ssw_Latn""",
"""Sundanese""": """sun_Latn""",
"""Swedish""": """swe_Latn""",
"""Swahili""": """swh_Latn""",
"""Silesian""": """szl_Latn""",
"""Tamil""": """tam_Taml""",
"""Tatar""": """tat_Cyrl""",
"""Telugu""": """tel_Telu""",
"""Tajik""": """tgk_Cyrl""",
"""Tagalog""": """tgl_Latn""",
"""Thai""": """tha_Thai""",
"""Tigrinya""": """tir_Ethi""",
"""Tamasheq Latin""": """taq_Latn""",
"""Tamasheq Tifinagh""": """taq_Tfng""",
"""Tok Pisin""": """tpi_Latn""",
"""Tswana""": """tsn_Latn""",
"""Tsonga""": """tso_Latn""",
"""Turkmen""": """tuk_Latn""",
"""Tumbuka""": """tum_Latn""",
"""Turkish""": """tur_Latn""",
"""Twi""": """twi_Latn""",
"""Central Atlas Tamazight""": """tzm_Tfng""",
"""Uyghur""": """uig_Arab""",
"""Ukrainian""": """ukr_Cyrl""",
"""Umbundu""": """umb_Latn""",
"""Urdu""": """urd_Arab""",
"""Northern Uzbek""": """uzn_Latn""",
"""Venetian""": """vec_Latn""",
"""Vietnamese""": """vie_Latn""",
"""Waray""": """war_Latn""",
"""Wolof""": """wol_Latn""",
"""Xhosa""": """xho_Latn""",
"""Eastern Yiddish""": """ydd_Hebr""",
"""Yoruba""": """yor_Latn""",
"""Yue Chinese""": """yue_Hant""",
"""Chinese Simplified""": """zho_Hans""",
"""Chinese Traditional""": """zho_Hant""",
"""Standard Malay""": """zsm_Latn""",
"""Zulu""": """zul_Latn""",
}
class UpperCAmelCase_ ( lowercase ):
"""simple docstring"""
UpperCamelCase_ : Optional[Any] ='facebook/nllb-200-distilled-600M'
UpperCamelCase_ : Optional[Any] =(
'This is a tool that translates text from a language to another. It takes three inputs: `text`, which should '
'be the text to translate, `src_lang`, which should be the language of the text to translate and `tgt_lang`, '
'which should be the language for the desired ouput language. Both `src_lang` and `tgt_lang` are written in '
'plain English, such as \'Romanian\', or \'Albanian\'. It returns the text translated in `tgt_lang`.'
)
UpperCamelCase_ : Dict ='translator'
UpperCamelCase_ : Any =AutoTokenizer
UpperCamelCase_ : Optional[Any] =AutoModelForSeqaSeqLM
UpperCamelCase_ : List[Any] =LANGUAGE_CODES
UpperCamelCase_ : int =['text', 'text', 'text']
UpperCamelCase_ : Union[str, Any] =['text']
def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> str:
if src_lang not in self.lang_to_code:
raise ValueError(F'''{src_lang} is not a supported language.''' )
if tgt_lang not in self.lang_to_code:
raise ValueError(F'''{tgt_lang} is not a supported language.''' )
UpperCamelCase :Optional[int] = self.lang_to_code[src_lang]
UpperCamelCase :Union[str, Any] = self.lang_to_code[tgt_lang]
return self.pre_processor._build_translation_inputs(
SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' , src_lang=SCREAMING_SNAKE_CASE_ , tgt_lang=SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ ) -> Optional[Any]:
return self.model.generate(**SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ ) -> int:
return self.post_processor.decode(outputs[0].tolist() , skip_special_tokens=SCREAMING_SNAKE_CASE_ )
| 658 | 0 |
from random import shuffle
import tensorflow as tf
from numpy import array
def A__ (snake_case : Union[str, Any] , snake_case : Union[str, Any] ) -> List[str]:
__UpperCamelCase : Optional[Any] = int(SCREAMING_SNAKE_CASE__ )
assert noofclusters < len(SCREAMING_SNAKE_CASE__ )
# Find out the dimensionality
__UpperCamelCase : List[Any] = len(vectors[0] )
# Will help select random centroids from among the available vectors
__UpperCamelCase : Tuple = list(range(len(SCREAMING_SNAKE_CASE__ ) ) )
shuffle(SCREAMING_SNAKE_CASE__ )
# GRAPH OF COMPUTATION
# We initialize a new graph and set it as the default during each run
# of this algorithm. This ensures that as this function is called
# multiple times, the default graph doesn't keep getting crowded with
# unused ops and Variables from previous function calls.
__UpperCamelCase : Any = tf.Graph()
with graph.as_default():
# SESSION OF COMPUTATION
__UpperCamelCase : int = tf.Session()
##CONSTRUCTING THE ELEMENTS OF COMPUTATION
##First lets ensure we have a Variable vector for each centroid,
##initialized to one of the vectors from the available data points
__UpperCamelCase : Any = [
tf.Variable(vectors[vector_indices[i]] ) for i in range(SCREAMING_SNAKE_CASE__ )
]
##These nodes will assign the centroid Variables the appropriate
##values
__UpperCamelCase : Any = tf.placeholder("""float64""" , [dim] )
__UpperCamelCase : Dict = []
for centroid in centroids:
cent_assigns.append(tf.assign(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) )
##Variables for cluster assignments of individual vectors(initialized
##to 0 at first)
__UpperCamelCase : int = [tf.Variable(0 ) for i in range(len(SCREAMING_SNAKE_CASE__ ) )]
##These nodes will assign an assignment Variable the appropriate
##value
__UpperCamelCase : Union[str, Any] = tf.placeholder("""int32""" )
__UpperCamelCase : Optional[Any] = []
for assignment in assignments:
cluster_assigns.append(tf.assign(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) )
##Now lets construct the node that will compute the mean
# The placeholder for the input
__UpperCamelCase : List[str] = tf.placeholder("""float""" , [None, dim] )
# The Node/op takes the input and computes a mean along the 0th
# dimension, i.e. the list of input vectors
__UpperCamelCase : Optional[Any] = tf.reduce_mean(SCREAMING_SNAKE_CASE__ , 0 )
##Node for computing Euclidean distances
# Placeholders for input
__UpperCamelCase : Optional[Any] = tf.placeholder("""float""" , [dim] )
__UpperCamelCase : Any = tf.placeholder("""float""" , [dim] )
__UpperCamelCase : List[Any] = tf.sqrt(tf.reduce_sum(tf.pow(tf.sub(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , 2 ) ) )
##This node will figure out which cluster to assign a vector to,
##based on Euclidean distances of the vector from the centroids.
# Placeholder for input
__UpperCamelCase : Dict = tf.placeholder("""float""" , [noofclusters] )
__UpperCamelCase : List[Any] = tf.argmin(SCREAMING_SNAKE_CASE__ , 0 )
##INITIALIZING STATE VARIABLES
##This will help initialization of all Variables defined with respect
##to the graph. The Variable-initializer should be defined after
##all the Variables have been constructed, so that each of them
##will be included in the initialization.
__UpperCamelCase : str = tf.initialize_all_variables()
# Initialize all variables
sess.run(SCREAMING_SNAKE_CASE__ )
##CLUSTERING ITERATIONS
# Now perform the Expectation-Maximization steps of K-Means clustering
# iterations. To keep things simple, we will only do a set number of
# iterations, instead of using a Stopping Criterion.
__UpperCamelCase : List[str] = 1_00
for _ in range(SCREAMING_SNAKE_CASE__ ):
##EXPECTATION STEP
##Based on the centroid locations till last iteration, compute
##the _expected_ centroid assignments.
# Iterate over each vector
for vector_n in range(len(SCREAMING_SNAKE_CASE__ ) ):
__UpperCamelCase : str = vectors[vector_n]
# Compute Euclidean distance between this vector and each
# centroid. Remember that this list cannot be named
#'centroid_distances', since that is the input to the
# cluster assignment node.
__UpperCamelCase : Any = [
sess.run(SCREAMING_SNAKE_CASE__ , feed_dict={va: vect, va: sess.run(SCREAMING_SNAKE_CASE__ )} )
for centroid in centroids
]
# Now use the cluster assignment node, with the distances
# as the input
__UpperCamelCase : Optional[Any] = sess.run(
SCREAMING_SNAKE_CASE__ , feed_dict={centroid_distances: distances} )
# Now assign the value to the appropriate state variable
sess.run(
cluster_assigns[vector_n] , feed_dict={assignment_value: assignment} )
##MAXIMIZATION STEP
# Based on the expected state computed from the Expectation Step,
# compute the locations of the centroids so as to maximize the
# overall objective of minimizing within-cluster Sum-of-Squares
for cluster_n in range(SCREAMING_SNAKE_CASE__ ):
# Collect all the vectors assigned to this cluster
__UpperCamelCase : List[str] = [
vectors[i]
for i in range(len(SCREAMING_SNAKE_CASE__ ) )
if sess.run(assignments[i] ) == cluster_n
]
# Compute new centroid location
__UpperCamelCase : List[Any] = sess.run(
SCREAMING_SNAKE_CASE__ , feed_dict={mean_input: array(SCREAMING_SNAKE_CASE__ )} )
# Assign value to appropriate variable
sess.run(
cent_assigns[cluster_n] , feed_dict={centroid_value: new_location} )
# Return centroids and assignments
__UpperCamelCase : Optional[int] = sess.run(SCREAMING_SNAKE_CASE__ )
__UpperCamelCase : Tuple = sess.run(SCREAMING_SNAKE_CASE__ )
return centroids, assignments
| 279 |
from __future__ import annotations
# This is the precision for this function which can be altered.
# It is recommended for users to keep this number greater than or equal to 10.
__snake_case = 10
def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : int ):
for i in range(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
if array[i] == target:
return i
return -1
def _A ( SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : int ):
UpperCamelCase :Tuple = 0
UpperCamelCase :Dict = len(SCREAMING_SNAKE_CASE__ )
while left <= right:
if right - left < precision:
return lin_search(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
UpperCamelCase :Union[str, Any] = (left + right) // 3 + 1
UpperCamelCase :str = 2 * (left + right) // 3 + 1
if array[one_third] == target:
return one_third
elif array[two_third] == target:
return two_third
elif target < array[one_third]:
UpperCamelCase :int = one_third - 1
elif array[two_third] < target:
UpperCamelCase :Any = two_third + 1
else:
UpperCamelCase :Any = one_third + 1
UpperCamelCase :int = two_third - 1
else:
return -1
def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : int ):
if left < right:
if right - left < precision:
return lin_search(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
UpperCamelCase :Optional[Any] = (left + right) // 3 + 1
UpperCamelCase :Tuple = 2 * (left + right) // 3 + 1
if array[one_third] == target:
return one_third
elif array[two_third] == target:
return two_third
elif target < array[one_third]:
return rec_ternary_search(SCREAMING_SNAKE_CASE__ , one_third - 1 , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
elif array[two_third] < target:
return rec_ternary_search(two_third + 1 , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
else:
return rec_ternary_search(one_third + 1 , two_third - 1 , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
else:
return -1
if __name__ == "__main__":
import doctest
doctest.testmod()
__snake_case = input("""Enter numbers separated by comma:\n""").strip()
__snake_case = [int(item.strip()) for item in user_input.split(""",""")]
assert collection == sorted(collection), f"List must be ordered.\n{collection}."
__snake_case = int(input("""Enter the number to be found in the list:\n""").strip())
__snake_case = ite_ternary_search(collection, target)
__snake_case = rec_ternary_search(0, len(collection) - 1, collection, target)
if resulta != -1:
print(f'''Iterative search: {target} found at positions: {resulta}''')
print(f'''Recursive search: {target} found at positions: {resulta}''')
else:
print("""Not found""")
| 658 | 0 |
from __future__ import annotations
from collections.abc import Callable
def __lowercase( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ = 100 , ):
"""simple docstring"""
lowerCamelCase = x_start
lowerCamelCase = fnc(SCREAMING_SNAKE_CASE__ )
lowerCamelCase = 0.0
for _ in range(SCREAMING_SNAKE_CASE__ ):
# Approximates small segments of curve as linear and solve
# for trapezoidal area
lowerCamelCase = (x_end - x_start) / steps + xa
lowerCamelCase = fnc(SCREAMING_SNAKE_CASE__ )
area += abs(fxa + fxa ) * (xa - xa) / 2
# Increment step
lowerCamelCase = xa
lowerCamelCase = fxa
return area
if __name__ == "__main__":
def __lowercase( UpperCAmelCase__ ):
"""simple docstring"""
return x**3 + x**2
print('f(x) = x^3 + x^2')
print('The area between the curve, x = -5, x = 5 and the x axis is:')
a_ : List[str] = 1_0
while i <= 1_0_0_0_0_0:
print(f"""with {i} steps: {trapezoidal_area(f, -5, 5, i)}""")
i *= 1_0 | 623 |
def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list ):
_enforce_args(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
if n == 0:
return 0
UpperCamelCase :Union[str, Any] = float('''-inf''' )
for i in range(1 , n + 1 ):
UpperCamelCase :str = max(
SCREAMING_SNAKE_CASE__ , prices[i - 1] + naive_cut_rod_recursive(n - i , SCREAMING_SNAKE_CASE__ ) )
return max_revue
def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list ):
_enforce_args(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
UpperCamelCase :Dict = [float('''-inf''' ) for _ in range(n + 1 )]
return _top_down_cut_rod_recursive(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list , SCREAMING_SNAKE_CASE__ : list ):
if max_rev[n] >= 0:
return max_rev[n]
elif n == 0:
return 0
else:
UpperCamelCase :Dict = float('''-inf''' )
for i in range(1 , n + 1 ):
UpperCamelCase :Union[str, Any] = max(
SCREAMING_SNAKE_CASE__ , prices[i - 1] + _top_down_cut_rod_recursive(n - i , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , )
UpperCamelCase :str = max_revenue
return max_rev[n]
def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list ):
_enforce_args(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
# length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of
# length 0.
UpperCamelCase :List[str] = [float('''-inf''' ) for _ in range(n + 1 )]
UpperCamelCase :Dict = 0
for i in range(1 , n + 1 ):
UpperCamelCase :Optional[Any] = max_rev[i]
for j in range(1 , i + 1 ):
UpperCamelCase :Optional[Any] = max(SCREAMING_SNAKE_CASE__ , prices[j - 1] + max_rev[i - j] )
UpperCamelCase :Tuple = max_revenue_i
return max_rev[n]
def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list ):
if n < 0:
UpperCamelCase :Any = F'''n must be greater than or equal to 0. Got n = {n}'''
raise ValueError(SCREAMING_SNAKE_CASE__ )
if n > len(SCREAMING_SNAKE_CASE__ ):
UpperCamelCase :Union[str, Any] = (
'''Each integral piece of rod must have a corresponding price. '''
F'''Got n = {n} but length of prices = {len(SCREAMING_SNAKE_CASE__ )}'''
)
raise ValueError(SCREAMING_SNAKE_CASE__ )
def _A ( ):
UpperCamelCase :Dict = [6, 10, 12, 15, 20, 23]
UpperCamelCase :List[str] = len(SCREAMING_SNAKE_CASE__ )
# the best revenue comes from cutting the rod into 6 pieces, each
# of length 1 resulting in a revenue of 6 * 6 = 36.
UpperCamelCase :str = 36
UpperCamelCase :int = top_down_cut_rod(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
UpperCamelCase :Union[str, Any] = bottom_up_cut_rod(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
UpperCamelCase :str = naive_cut_rod_recursive(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
assert expected_max_revenue == max_rev_top_down
assert max_rev_top_down == max_rev_bottom_up
assert max_rev_bottom_up == max_rev_naive
if __name__ == "__main__":
main()
| 658 | 0 |
'''simple docstring'''
def __UpperCAmelCase ( SCREAMING_SNAKE_CASE__: Optional[Any], SCREAMING_SNAKE_CASE__: Any, SCREAMING_SNAKE_CASE__: str=False ) -> Tuple:
"""simple docstring"""
if isinstance(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) and isinstance(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ):
__a = len(set_a.intersection(SCREAMING_SNAKE_CASE__ ) )
if alternative_union:
__a = len(SCREAMING_SNAKE_CASE__ ) + len(SCREAMING_SNAKE_CASE__ )
else:
__a = len(set_a.union(SCREAMING_SNAKE_CASE__ ) )
return intersection / union
if isinstance(SCREAMING_SNAKE_CASE__, (list, tuple) ) and isinstance(SCREAMING_SNAKE_CASE__, (list, tuple) ):
__a = [element for element in set_a if element in set_b]
if alternative_union:
__a = len(SCREAMING_SNAKE_CASE__ ) + len(SCREAMING_SNAKE_CASE__ )
return len(SCREAMING_SNAKE_CASE__ ) / union
else:
__a = set_a + [element for element in set_b if element not in set_a]
return len(SCREAMING_SNAKE_CASE__ ) / len(SCREAMING_SNAKE_CASE__ )
return len(SCREAMING_SNAKE_CASE__ ) / len(SCREAMING_SNAKE_CASE__ )
return None
if __name__ == "__main__":
__UpperCamelCase : List[Any] = {"""a""", """b""", """c""", """d""", """e"""}
__UpperCamelCase : Optional[int] = {"""c""", """d""", """e""", """f""", """h""", """i"""}
print(jaccard_similarity(set_a, set_b)) | 448 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices
__snake_case = logging.get_logger(__name__)
__snake_case = {
"""microsoft/focalnet-tiny""": """https://huggingface.co/microsoft/focalnet-tiny/resolve/main/config.json""",
}
class UpperCAmelCase_ ( lowercase, lowercase ):
"""simple docstring"""
UpperCamelCase_ : int ='focalnet'
def __init__( self , SCREAMING_SNAKE_CASE_=224 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=96 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=[192, 384, 768, 768] , SCREAMING_SNAKE_CASE_=[2, 2, 6, 2] , SCREAMING_SNAKE_CASE_=[2, 2, 2, 2] , SCREAMING_SNAKE_CASE_=[3, 3, 3, 3] , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=4.0 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=1e-4 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=1e-5 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ , ) -> Dict:
super().__init__(**SCREAMING_SNAKE_CASE_ )
UpperCamelCase :List[Any] = image_size
UpperCamelCase :Dict = patch_size
UpperCamelCase :Tuple = num_channels
UpperCamelCase :int = embed_dim
UpperCamelCase :Optional[Any] = use_conv_embed
UpperCamelCase :str = hidden_sizes
UpperCamelCase :str = depths
UpperCamelCase :Optional[int] = focal_levels
UpperCamelCase :Tuple = focal_windows
UpperCamelCase :Optional[int] = hidden_act
UpperCamelCase :Optional[int] = mlp_ratio
UpperCamelCase :Optional[Any] = hidden_dropout_prob
UpperCamelCase :int = drop_path_rate
UpperCamelCase :Dict = use_layerscale
UpperCamelCase :List[str] = layerscale_value
UpperCamelCase :Tuple = use_post_layernorm
UpperCamelCase :int = use_post_layernorm_in_modulation
UpperCamelCase :str = normalize_modulator
UpperCamelCase :Any = initializer_range
UpperCamelCase :Optional[Any] = layer_norm_eps
UpperCamelCase :Dict = encoder_stride
UpperCamelCase :int = ['''stem'''] + [F'''stage{idx}''' for idx in range(1 , len(self.depths ) + 1 )]
UpperCamelCase , UpperCamelCase :int = get_aligned_output_features_output_indices(
out_features=SCREAMING_SNAKE_CASE_ , out_indices=SCREAMING_SNAKE_CASE_ , stage_names=self.stage_names )
| 658 | 0 |
def __lowerCamelCase ( __lowerCAmelCase : int ) -> Optional[int]:
if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
raise ValueError("""check_bouncy() accepts only integer arguments""" )
__UpperCamelCase : int = str(SCREAMING_SNAKE_CASE__ )
__UpperCamelCase : Optional[Any] = ''''''.join(sorted(SCREAMING_SNAKE_CASE__ ) )
return sorted_str_n != str_n and sorted_str_n[::-1] != str_n
def __lowerCamelCase ( __lowerCAmelCase : float = 99 ) -> Any:
if not 0 < percent < 100:
raise ValueError("""solution() only accepts values from 0 to 100""" )
__UpperCamelCase : Tuple = 0
__UpperCamelCase : str = 1
while True:
if check_bouncy(SCREAMING_SNAKE_CASE__ ):
bouncy_num += 1
if (bouncy_num / num) * 100 >= percent:
return num
num += 1
if __name__ == "__main__":
from doctest import testmod
testmod()
print(F"""{solution(99)}""")
| 269 |
import inspect
import unittest
from transformers import DPTConfig
from transformers.file_utils import is_torch_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from torch import nn
from transformers import MODEL_MAPPING, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel
from transformers.models.dpt.modeling_dpt import DPT_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
from PIL import Image
from transformers import DPTImageProcessor
class UpperCAmelCase_ :
"""simple docstring"""
def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=[0, 1, 2, 3] , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=37 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=[1, 384, 24, 24] , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=None , ) -> int:
UpperCamelCase :Union[str, Any] = parent
UpperCamelCase :Tuple = batch_size
UpperCamelCase :Optional[Any] = image_size
UpperCamelCase :Any = patch_size
UpperCamelCase :List[str] = num_channels
UpperCamelCase :int = is_training
UpperCamelCase :str = use_labels
UpperCamelCase :Optional[Any] = hidden_size
UpperCamelCase :int = num_hidden_layers
UpperCamelCase :List[Any] = backbone_out_indices
UpperCamelCase :str = num_attention_heads
UpperCamelCase :Tuple = intermediate_size
UpperCamelCase :Optional[int] = hidden_act
UpperCamelCase :List[Any] = hidden_dropout_prob
UpperCamelCase :List[str] = attention_probs_dropout_prob
UpperCamelCase :Union[str, Any] = initializer_range
UpperCamelCase :List[Any] = num_labels
UpperCamelCase :int = backbone_featmap_shape
UpperCamelCase :Any = scope
UpperCamelCase :int = is_hybrid
# sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token)
UpperCamelCase :Dict = (image_size // patch_size) ** 2
UpperCamelCase :List[str] = num_patches + 1
def UpperCAmelCase ( self ) -> Union[str, Any]:
UpperCamelCase :List[str] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
UpperCamelCase :Tuple = None
if self.use_labels:
UpperCamelCase :Union[str, Any] = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels )
UpperCamelCase :Optional[int] = self.get_config()
return config, pixel_values, labels
def UpperCAmelCase ( self ) -> Dict:
UpperCamelCase :Any = {
'''global_padding''': '''same''',
'''layer_type''': '''bottleneck''',
'''depths''': [3, 4, 9],
'''out_features''': ['''stage1''', '''stage2''', '''stage3'''],
'''embedding_dynamic_padding''': True,
'''hidden_sizes''': [96, 192, 384, 768],
'''num_groups''': 2,
}
return DPTConfig(
image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , backbone_out_indices=self.backbone_out_indices , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=SCREAMING_SNAKE_CASE_ , initializer_range=self.initializer_range , is_hybrid=self.is_hybrid , backbone_config=SCREAMING_SNAKE_CASE_ , backbone_featmap_shape=self.backbone_featmap_shape , )
def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Tuple:
UpperCamelCase :List[str] = DPTModel(config=SCREAMING_SNAKE_CASE_ )
model.to(SCREAMING_SNAKE_CASE_ )
model.eval()
UpperCamelCase :Dict = model(SCREAMING_SNAKE_CASE_ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> str:
UpperCamelCase :Optional[Any] = self.num_labels
UpperCamelCase :Optional[int] = DPTForDepthEstimation(SCREAMING_SNAKE_CASE_ )
model.to(SCREAMING_SNAKE_CASE_ )
model.eval()
UpperCamelCase :Dict = model(SCREAMING_SNAKE_CASE_ )
self.parent.assertEqual(result.predicted_depth.shape , (self.batch_size, self.image_size, self.image_size) )
def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Dict:
UpperCamelCase :Optional[int] = self.num_labels
UpperCamelCase :int = DPTForSemanticSegmentation(SCREAMING_SNAKE_CASE_ )
model.to(SCREAMING_SNAKE_CASE_ )
model.eval()
UpperCamelCase :Dict = model(SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ )
self.parent.assertEqual(
result.logits.shape , (self.batch_size, self.num_labels, self.image_size, self.image_size) )
def UpperCAmelCase ( self ) -> Dict:
UpperCamelCase :Dict = self.prepare_config_and_inputs()
UpperCamelCase , UpperCamelCase , UpperCamelCase :List[Any] = config_and_inputs
UpperCamelCase :List[Any] = {'''pixel_values''': pixel_values}
return config, inputs_dict
@require_torch
class UpperCAmelCase_ ( lowercase, lowercase, unittest.TestCase ):
"""simple docstring"""
UpperCamelCase_ : Tuple =(DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else ()
UpperCamelCase_ : Tuple =(
{
'depth-estimation': DPTForDepthEstimation,
'feature-extraction': DPTModel,
'image-segmentation': DPTForSemanticSegmentation,
}
if is_torch_available()
else {}
)
UpperCamelCase_ : Tuple =False
UpperCamelCase_ : List[Any] =False
UpperCamelCase_ : Tuple =False
def UpperCAmelCase ( self ) -> Dict:
UpperCamelCase :Union[str, Any] = DPTModelTester(self )
UpperCamelCase :List[Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , has_text_modality=SCREAMING_SNAKE_CASE_ , hidden_size=37 )
def UpperCAmelCase ( self ) -> Tuple:
self.config_tester.run_common_tests()
@unittest.skip(reason='''DPT does not use inputs_embeds''' )
def UpperCAmelCase ( self ) -> int:
pass
def UpperCAmelCase ( self ) -> List[Any]:
UpperCamelCase , UpperCamelCase :Tuple = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
UpperCamelCase :int = model_class(SCREAMING_SNAKE_CASE_ )
self.assertIsInstance(model.get_input_embeddings() , (nn.Module) )
UpperCamelCase :int = model.get_output_embeddings()
self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE_ , nn.Linear ) )
def UpperCAmelCase ( self ) -> Optional[int]:
UpperCamelCase , UpperCamelCase :Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
UpperCamelCase :List[Any] = model_class(SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Optional[int] = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
UpperCamelCase :Optional[int] = [*signature.parameters.keys()]
UpperCamelCase :Tuple = ['''pixel_values''']
self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self ) -> Optional[int]:
UpperCamelCase :Any = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self ) -> Optional[int]:
UpperCamelCase :Union[str, Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_depth_estimation(*SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self ) -> Any:
UpperCamelCase :Union[str, Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_semantic_segmentation(*SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self ) -> List[str]:
for model_class in self.all_model_classes:
if model_class.__name__ == "DPTForDepthEstimation":
continue
UpperCamelCase , UpperCamelCase :Tuple = self.model_tester.prepare_config_and_inputs_for_common()
UpperCamelCase :Any = True
if model_class in get_values(SCREAMING_SNAKE_CASE_ ):
continue
UpperCamelCase :Dict = model_class(SCREAMING_SNAKE_CASE_ )
model.to(SCREAMING_SNAKE_CASE_ )
model.train()
UpperCamelCase :str = self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , return_labels=SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Optional[Any] = model(**SCREAMING_SNAKE_CASE_ ).loss
loss.backward()
def UpperCAmelCase ( self ) -> Tuple:
for model_class in self.all_model_classes:
if model_class.__name__ == "DPTForDepthEstimation":
continue
UpperCamelCase , UpperCamelCase :Any = self.model_tester.prepare_config_and_inputs_for_common()
UpperCamelCase :Optional[Any] = False
UpperCamelCase :List[Any] = True
if model_class in get_values(SCREAMING_SNAKE_CASE_ ) or not model_class.supports_gradient_checkpointing:
continue
UpperCamelCase :Optional[Any] = model_class(SCREAMING_SNAKE_CASE_ )
model.to(SCREAMING_SNAKE_CASE_ )
model.gradient_checkpointing_enable()
model.train()
UpperCamelCase :Union[str, Any] = self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , return_labels=SCREAMING_SNAKE_CASE_ )
UpperCamelCase :List[str] = model(**SCREAMING_SNAKE_CASE_ ).loss
loss.backward()
def UpperCAmelCase ( self ) -> List[str]:
UpperCamelCase , UpperCamelCase :Dict = self.model_tester.prepare_config_and_inputs_for_common()
UpperCamelCase :Optional[int] = _config_zero_init(SCREAMING_SNAKE_CASE_ )
for model_class in self.all_model_classes:
UpperCamelCase :Union[str, Any] = model_class(config=SCREAMING_SNAKE_CASE_ )
# Skip the check for the backbone
UpperCamelCase :Optional[int] = []
for name, module in model.named_modules():
if module.__class__.__name__ == "DPTViTHybridEmbeddings":
UpperCamelCase :Union[str, Any] = [F'''{name}.{key}''' for key in module.state_dict().keys()]
break
for name, param in model.named_parameters():
if param.requires_grad:
if name in backbone_params:
continue
self.assertIn(
((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=F'''Parameter {name} of model {model_class} seems not properly initialized''' , )
@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' )
def UpperCAmelCase ( self ) -> Any:
pass
@slow
def UpperCAmelCase ( self ) -> Optional[Any]:
for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]:
UpperCamelCase :Any = DPTModel.from_pretrained(SCREAMING_SNAKE_CASE_ )
self.assertIsNotNone(SCREAMING_SNAKE_CASE_ )
def UpperCAmelCase ( self ) -> Optional[int]:
# We do this test only for DPTForDepthEstimation since it is the only model that uses readout_type
UpperCamelCase , UpperCamelCase :Tuple = self.model_tester.prepare_config_and_inputs_for_common()
UpperCamelCase :Union[str, Any] = '''add'''
with self.assertRaises(SCREAMING_SNAKE_CASE_ ):
UpperCamelCase :Dict = DPTForDepthEstimation(SCREAMING_SNAKE_CASE_ )
def _A ( ):
UpperCamelCase :Union[str, Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
return image
@require_torch
@require_vision
@slow
class UpperCAmelCase_ ( unittest.TestCase ):
"""simple docstring"""
def UpperCAmelCase ( self ) -> Optional[Any]:
UpperCamelCase :List[Any] = DPTImageProcessor.from_pretrained('''Intel/dpt-hybrid-midas''' )
UpperCamelCase :List[str] = DPTForDepthEstimation.from_pretrained('''Intel/dpt-hybrid-midas''' ).to(SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Tuple = prepare_img()
UpperCamelCase :List[str] = image_processor(images=SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' ).to(SCREAMING_SNAKE_CASE_ )
# forward pass
with torch.no_grad():
UpperCamelCase :int = model(**SCREAMING_SNAKE_CASE_ )
UpperCamelCase :Union[str, Any] = outputs.predicted_depth
# verify the predicted depth
UpperCamelCase :int = torch.Size((1, 384, 384) )
self.assertEqual(predicted_depth.shape , SCREAMING_SNAKE_CASE_ )
UpperCamelCase :int = torch.tensor(
[[[5.6437, 5.6146, 5.6511], [5.4371, 5.5649, 5.5958], [5.5215, 5.5184, 5.5293]]] ).to(SCREAMING_SNAKE_CASE_ )
self.assertTrue(torch.allclose(outputs.predicted_depth[:3, :3, :3] / 100 , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) )
| 658 | 0 |
import os
# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_doctest_list.py
a = "."
if __name__ == "__main__":
a = os.path.join(REPO_PATH, "utils/documentation_tests.txt")
a = []
a = []
with open(doctest_file_path) as fp:
for line in fp:
a = line.strip()
a = os.path.join(REPO_PATH, line)
if not (os.path.isfile(path) or os.path.isdir(path)):
non_existent_paths.append(line)
all_paths.append(path)
if len(non_existent_paths) > 0:
a = "\n".join(non_existent_paths)
raise ValueError(F'`utils/documentation_tests.txt` contains non-existent paths:\n{non_existent_paths}')
if all_paths != sorted(all_paths):
raise ValueError("Files in `utils/documentation_tests.txt` are not in alphabetical order.") | 518 |
import argparse
import json
from pathlib import Path
import torch
import torchaudio
from datasets import load_dataset
from huggingface_hub import hf_hub_download
from transformers import ASTConfig, ASTFeatureExtractor, ASTForAudioClassification
from transformers.utils import logging
logging.set_verbosity_info()
__snake_case = logging.get_logger(__name__)
def _A ( SCREAMING_SNAKE_CASE__ : int ):
UpperCamelCase :Union[str, Any] = ASTConfig()
if "10-10" in model_name:
pass
elif "speech-commands" in model_name:
UpperCamelCase :Any = 128
elif "12-12" in model_name:
UpperCamelCase :Union[str, Any] = 12
UpperCamelCase :Any = 12
elif "14-14" in model_name:
UpperCamelCase :Optional[int] = 14
UpperCamelCase :List[str] = 14
elif "16-16" in model_name:
UpperCamelCase :List[Any] = 16
UpperCamelCase :Optional[Any] = 16
else:
raise ValueError('''Model not supported''' )
UpperCamelCase :Tuple = '''huggingface/label-files'''
if "speech-commands" in model_name:
UpperCamelCase :Optional[Any] = 35
UpperCamelCase :List[Any] = '''speech-commands-v2-id2label.json'''
else:
UpperCamelCase :Optional[int] = 527
UpperCamelCase :List[Any] = '''audioset-id2label.json'''
UpperCamelCase :Any = json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , repo_type='''dataset''' ) , '''r''' ) )
UpperCamelCase :List[str] = {int(SCREAMING_SNAKE_CASE__ ): v for k, v in idalabel.items()}
UpperCamelCase :List[Any] = idalabel
UpperCamelCase :List[Any] = {v: k for k, v in idalabel.items()}
return config
def _A ( SCREAMING_SNAKE_CASE__ : Optional[Any] ):
if "module.v" in name:
UpperCamelCase :Any = name.replace('''module.v''' , '''audio_spectrogram_transformer''' )
if "cls_token" in name:
UpperCamelCase :int = name.replace('''cls_token''' , '''embeddings.cls_token''' )
if "dist_token" in name:
UpperCamelCase :Tuple = name.replace('''dist_token''' , '''embeddings.distillation_token''' )
if "pos_embed" in name:
UpperCamelCase :Optional[int] = name.replace('''pos_embed''' , '''embeddings.position_embeddings''' )
if "patch_embed.proj" in name:
UpperCamelCase :str = name.replace('''patch_embed.proj''' , '''embeddings.patch_embeddings.projection''' )
# transformer blocks
if "blocks" in name:
UpperCamelCase :Any = name.replace('''blocks''' , '''encoder.layer''' )
if "attn.proj" in name:
UpperCamelCase :Union[str, Any] = name.replace('''attn.proj''' , '''attention.output.dense''' )
if "attn" in name:
UpperCamelCase :Union[str, Any] = name.replace('''attn''' , '''attention.self''' )
if "norm1" in name:
UpperCamelCase :str = name.replace('''norm1''' , '''layernorm_before''' )
if "norm2" in name:
UpperCamelCase :Tuple = name.replace('''norm2''' , '''layernorm_after''' )
if "mlp.fc1" in name:
UpperCamelCase :Dict = name.replace('''mlp.fc1''' , '''intermediate.dense''' )
if "mlp.fc2" in name:
UpperCamelCase :List[str] = name.replace('''mlp.fc2''' , '''output.dense''' )
# final layernorm
if "audio_spectrogram_transformer.norm" in name:
UpperCamelCase :Union[str, Any] = name.replace('''audio_spectrogram_transformer.norm''' , '''audio_spectrogram_transformer.layernorm''' )
# classifier head
if "module.mlp_head.0" in name:
UpperCamelCase :int = name.replace('''module.mlp_head.0''' , '''classifier.layernorm''' )
if "module.mlp_head.1" in name:
UpperCamelCase :Tuple = name.replace('''module.mlp_head.1''' , '''classifier.dense''' )
return name
def _A ( SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Any ):
for key in orig_state_dict.copy().keys():
UpperCamelCase :Dict = orig_state_dict.pop(SCREAMING_SNAKE_CASE__ )
if "qkv" in key:
UpperCamelCase :Any = key.split('''.''' )
UpperCamelCase :str = int(key_split[3] )
UpperCamelCase :Union[str, Any] = config.hidden_size
if "weight" in key:
UpperCamelCase :List[str] = val[:dim, :]
UpperCamelCase :Optional[Any] = val[dim : dim * 2, :]
UpperCamelCase :Optional[Any] = val[-dim:, :]
else:
UpperCamelCase :Dict = val[:dim]
UpperCamelCase :Optional[int] = val[dim : dim * 2]
UpperCamelCase :List[Any] = val[-dim:]
else:
UpperCamelCase :Union[str, Any] = val
return orig_state_dict
def _A ( SCREAMING_SNAKE_CASE__ : int ):
UpperCamelCase :List[str] = [
'''module.v.head.weight''',
'''module.v.head.bias''',
'''module.v.head_dist.weight''',
'''module.v.head_dist.bias''',
]
for k in ignore_keys:
state_dict.pop(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
@torch.no_grad()
def _A ( SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Any=False ):
UpperCamelCase :Optional[Any] = get_audio_spectrogram_transformer_config(SCREAMING_SNAKE_CASE__ )
UpperCamelCase :str = {
'''ast-finetuned-audioset-10-10-0.4593''': (
'''https://www.dropbox.com/s/ca0b1v2nlxzyeb4/audioset_10_10_0.4593.pth?dl=1'''
),
'''ast-finetuned-audioset-10-10-0.450''': (
'''https://www.dropbox.com/s/1tv0hovue1bxupk/audioset_10_10_0.4495.pth?dl=1'''
),
'''ast-finetuned-audioset-10-10-0.448''': (
'''https://www.dropbox.com/s/6u5sikl4b9wo4u5/audioset_10_10_0.4483.pth?dl=1'''
),
'''ast-finetuned-audioset-10-10-0.448-v2''': (
'''https://www.dropbox.com/s/kt6i0v9fvfm1mbq/audioset_10_10_0.4475.pth?dl=1'''
),
'''ast-finetuned-audioset-12-12-0.447''': (
'''https://www.dropbox.com/s/snfhx3tizr4nuc8/audioset_12_12_0.4467.pth?dl=1'''
),
'''ast-finetuned-audioset-14-14-0.443''': (
'''https://www.dropbox.com/s/z18s6pemtnxm4k7/audioset_14_14_0.4431.pth?dl=1'''
),
'''ast-finetuned-audioset-16-16-0.442''': (
'''https://www.dropbox.com/s/mdsa4t1xmcimia6/audioset_16_16_0.4422.pth?dl=1'''
),
'''ast-finetuned-speech-commands-v2''': (
'''https://www.dropbox.com/s/q0tbqpwv44pquwy/speechcommands_10_10_0.9812.pth?dl=1'''
),
}
# load original state_dict
UpperCamelCase :Optional[int] = model_name_to_url[model_name]
UpperCamelCase :Tuple = torch.hub.load_state_dict_from_url(SCREAMING_SNAKE_CASE__ , map_location='''cpu''' )
# remove some keys
remove_keys(SCREAMING_SNAKE_CASE__ )
# rename some keys
UpperCamelCase :Union[str, Any] = convert_state_dict(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
# load 🤗 model
UpperCamelCase :int = ASTForAudioClassification(SCREAMING_SNAKE_CASE__ )
model.eval()
model.load_state_dict(SCREAMING_SNAKE_CASE__ )
# verify outputs on dummy input
# source: https://github.com/YuanGongND/ast/blob/79e873b8a54d0a3b330dd522584ff2b9926cd581/src/run.py#L62
UpperCamelCase :Union[str, Any] = -4.2_67_73_93 if '''speech-commands''' not in model_name else -6.84_59_78
UpperCamelCase :List[str] = 4.5_68_99_74 if '''speech-commands''' not in model_name else 5.5_65_45_26
UpperCamelCase :Optional[Any] = 1024 if '''speech-commands''' not in model_name else 128
UpperCamelCase :int = ASTFeatureExtractor(mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ )
if "speech-commands" in model_name:
UpperCamelCase :Dict = load_dataset('''speech_commands''' , '''v0.02''' , split='''validation''' )
UpperCamelCase :List[Any] = dataset[0]['''audio''']['''array''']
else:
UpperCamelCase :List[Any] = hf_hub_download(
repo_id='''nielsr/audio-spectogram-transformer-checkpoint''' , filename='''sample_audio.flac''' , repo_type='''dataset''' , )
UpperCamelCase , UpperCamelCase :Dict = torchaudio.load(SCREAMING_SNAKE_CASE__ )
UpperCamelCase :List[str] = waveform.squeeze().numpy()
UpperCamelCase :Optional[int] = feature_extractor(SCREAMING_SNAKE_CASE__ , sampling_rate=16000 , return_tensors='''pt''' )
# forward pass
UpperCamelCase :List[str] = model(**SCREAMING_SNAKE_CASE__ )
UpperCamelCase :str = outputs.logits
if model_name == "ast-finetuned-audioset-10-10-0.4593":
UpperCamelCase :Tuple = torch.tensor([-0.87_60, -7.00_42, -8.66_02] )
elif model_name == "ast-finetuned-audioset-10-10-0.450":
UpperCamelCase :Union[str, Any] = torch.tensor([-1.19_86, -7.09_03, -8.27_18] )
elif model_name == "ast-finetuned-audioset-10-10-0.448":
UpperCamelCase :str = torch.tensor([-2.61_28, -8.00_80, -9.43_44] )
elif model_name == "ast-finetuned-audioset-10-10-0.448-v2":
UpperCamelCase :List[str] = torch.tensor([-1.50_80, -7.45_34, -8.89_17] )
elif model_name == "ast-finetuned-audioset-12-12-0.447":
UpperCamelCase :Dict = torch.tensor([-0.50_50, -6.58_33, -8.08_43] )
elif model_name == "ast-finetuned-audioset-14-14-0.443":
UpperCamelCase :List[str] = torch.tensor([-0.38_26, -7.03_36, -8.24_13] )
elif model_name == "ast-finetuned-audioset-16-16-0.442":
UpperCamelCase :Optional[int] = torch.tensor([-1.21_13, -6.91_01, -8.34_70] )
elif model_name == "ast-finetuned-speech-commands-v2":
UpperCamelCase :List[Any] = torch.tensor([6.15_89, -8.05_66, -8.79_84] )
else:
raise ValueError('''Unknown model name''' )
if not torch.allclose(logits[0, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ):
raise ValueError('''Logits don\'t match''' )
print('''Looks ok!''' )
if pytorch_dump_folder_path is not None:
Path(SCREAMING_SNAKE_CASE__ ).mkdir(exist_ok=SCREAMING_SNAKE_CASE__ )
print(F'''Saving model {model_name} to {pytorch_dump_folder_path}''' )
model.save_pretrained(SCREAMING_SNAKE_CASE__ )
print(F'''Saving feature extractor to {pytorch_dump_folder_path}''' )
feature_extractor.save_pretrained(SCREAMING_SNAKE_CASE__ )
if push_to_hub:
print('''Pushing model and feature extractor to the hub...''' )
model.push_to_hub(F'''MIT/{model_name}''' )
feature_extractor.push_to_hub(F'''MIT/{model_name}''' )
if __name__ == "__main__":
__snake_case = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"""--model_name""",
default="""ast-finetuned-audioset-10-10-0.4593""",
type=str,
help="""Name of the Audio Spectrogram Transformer model you'd like to convert.""",
)
parser.add_argument(
"""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory."""
)
parser.add_argument(
"""--push_to_hub""", action="""store_true""", help="""Whether or not to push the converted model to the 🤗 hub."""
)
__snake_case = parser.parse_args()
convert_audio_spectrogram_transformer_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
| 658 | 0 |
def _a ( a :str ) -> Union[str, Any]:
a = hex_num.strip()
if not hex_num:
raise ValueError('''No value was passed to the function''' )
a = hex_num[0] == '''-'''
if is_negative:
a = hex_num[1:]
try:
a = int(SCREAMING_SNAKE_CASE__ , 16 )
except ValueError:
raise ValueError('''Invalid value was passed to the function''' )
a = ''''''
while int_num > 0:
a = str(int_num % 2 ) + bin_str
int_num >>= 1
return int(('''-''' + bin_str) if is_negative else bin_str )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 117 |
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_sentencepiece_available,
is_tokenizers_available,
is_torch_available,
)
__snake_case = {
"""configuration_llama""": ["""LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP""", """LlamaConfig"""],
}
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__snake_case = ["""LlamaTokenizer"""]
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__snake_case = ["""LlamaTokenizerFast"""]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__snake_case = [
"""LlamaForCausalLM""",
"""LlamaModel""",
"""LlamaPreTrainedModel""",
"""LlamaForSequenceClassification""",
]
if TYPE_CHECKING:
from .configuration_llama import LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP, LlamaConfig
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_llama import LlamaTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_llama_fast import LlamaTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_llama import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaPreTrainedModel
else:
import sys
__snake_case = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 658 | 0 |
import os
from itertools import chain
from random import randrange, shuffle
import pytest
from .sola import PokerHand
_lowercase = (
'''4S 3H 2C 7S 5H''',
'''9D 8H 2C 6S 7H''',
'''2D 6D 9D TH 7D''',
'''TC 8C 2S JH 6C''',
'''JH 8S TH AH QH''',
'''TS KS 5S 9S AC''',
'''KD 6S 9D TH AD''',
'''KS 8D 4D 9S 4S''', # pair
'''8C 4S KH JS 4D''', # pair
'''QH 8H KD JH 8S''', # pair
'''KC 4H KS 2H 8D''', # pair
'''KD 4S KC 3H 8S''', # pair
'''AH 8S AS KC JH''', # pair
'''3H 4C 4H 3S 2H''', # 2 pairs
'''5S 5D 2C KH KH''', # 2 pairs
'''3C KH 5D 5S KH''', # 2 pairs
'''AS 3C KH AD KH''', # 2 pairs
'''7C 7S 3S 7H 5S''', # 3 of a kind
'''7C 7S KH 2H 7H''', # 3 of a kind
'''AC KH QH AH AS''', # 3 of a kind
'''2H 4D 3C AS 5S''', # straight (low ace)
'''3C 5C 4C 2C 6H''', # straight
'''6S 8S 7S 5H 9H''', # straight
'''JS QS 9H TS KH''', # straight
'''QC KH TS JS AH''', # straight (high ace)
'''8C 9C 5C 3C TC''', # flush
'''3S 8S 9S 5S KS''', # flush
'''4C 5C 9C 8C KC''', # flush
'''JH 8H AH KH QH''', # flush
'''3D 2H 3H 2C 2D''', # full house
'''2H 2C 3S 3H 3D''', # full house
'''KH KC 3S 3H 3D''', # full house
'''JC 6H JS JD JH''', # 4 of a kind
'''JC 7H JS JD JH''', # 4 of a kind
'''JC KH JS JD JH''', # 4 of a kind
'''2S AS 4S 5S 3S''', # straight flush (low ace)
'''2D 6D 3D 4D 5D''', # straight flush
'''5C 6C 3C 7C 4C''', # straight flush
'''JH 9H TH KH QH''', # straight flush
'''JH AH TH KH QH''', # royal flush (high ace straight flush)
)
_lowercase = (
('''2H 3H 4H 5H 6H''', '''KS AS TS QS JS''', '''Loss'''),
('''2H 3H 4H 5H 6H''', '''AS AD AC AH JD''', '''Win'''),
('''AS AH 2H AD AC''', '''JS JD JC JH 3D''', '''Win'''),
('''2S AH 2H AS AC''', '''JS JD JC JH AD''', '''Loss'''),
('''2S AH 2H AS AC''', '''2H 3H 5H 6H 7H''', '''Win'''),
('''AS 3S 4S 8S 2S''', '''2H 3H 5H 6H 7H''', '''Win'''),
('''2H 3H 5H 6H 7H''', '''2S 3H 4H 5S 6C''', '''Win'''),
('''2S 3H 4H 5S 6C''', '''3D 4C 5H 6H 2S''', '''Tie'''),
('''2S 3H 4H 5S 6C''', '''AH AC 5H 6H AS''', '''Win'''),
('''2S 2H 4H 5S 4C''', '''AH AC 5H 6H AS''', '''Loss'''),
('''2S 2H 4H 5S 4C''', '''AH AC 5H 6H 7S''', '''Win'''),
('''6S AD 7H 4S AS''', '''AH AC 5H 6H 7S''', '''Loss'''),
('''2S AH 4H 5S KC''', '''AH AC 5H 6H 7S''', '''Loss'''),
('''2S 3H 6H 7S 9C''', '''7H 3C TH 6H 9S''', '''Loss'''),
('''4S 5H 6H TS AC''', '''3S 5H 6H TS AC''', '''Win'''),
('''2S AH 4H 5S 6C''', '''AD 4C 5H 6H 2C''', '''Tie'''),
('''AS AH 3H AD AC''', '''AS AH 2H AD AC''', '''Win'''),
('''AH AC 5H 5C QS''', '''AH AC 5H 5C KS''', '''Loss'''),
('''AH AC 5H 5C QS''', '''KH KC 5H 5C QS''', '''Win'''),
('''7C 7S KH 2H 7H''', '''3C 3S AH 2H 3H''', '''Win'''),
('''3C 3S AH 2H 3H''', '''7C 7S KH 2H 7H''', '''Loss'''),
('''6H 5H 4H 3H 2H''', '''5H 4H 3H 2H AH''', '''Win'''),
('''5H 4H 3H 2H AH''', '''5H 4H 3H 2H AH''', '''Tie'''),
('''5H 4H 3H 2H AH''', '''6H 5H 4H 3H 2H''', '''Loss'''),
('''AH AD KS KC AC''', '''AH KD KH AC KC''', '''Win'''),
('''2H 4D 3C AS 5S''', '''2H 4D 3C 6S 5S''', '''Loss'''),
('''2H 3S 3C 3H 2S''', '''3S 3C 2S 2H 2D''', '''Win'''),
('''4D 6D 5D 2D JH''', '''3S 8S 3H TC KH''', '''Loss'''),
('''4S 6C 8S 3S 7S''', '''AD KS 2D 7D 7C''', '''Loss'''),
('''6S 4C 7H 8C 3H''', '''5H JC AH 9D 9C''', '''Loss'''),
('''9D 9H JH TC QH''', '''3C 2S JS 5C 7H''', '''Win'''),
('''2H TC 8S AD 9S''', '''4H TS 7H 2C 5C''', '''Win'''),
('''9D 3S 2C 7S 7C''', '''JC TD 3C TC 9H''', '''Loss'''),
)
_lowercase = (
('''2H 3H 4H 5H 6H''', True),
('''AS AH 2H AD AC''', False),
('''2H 3H 5H 6H 7H''', True),
('''KS AS TS QS JS''', True),
('''8H 9H QS JS TH''', False),
('''AS 3S 4S 8S 2S''', True),
)
_lowercase = (
('''2H 3H 4H 5H 6H''', True),
('''AS AH 2H AD AC''', False),
('''2H 3H 5H 6H 7H''', False),
('''KS AS TS QS JS''', True),
('''8H 9H QS JS TH''', True),
)
_lowercase = (
('''2H 4D 3C AS 5S''', True, [5, 4, 3, 2, 14]),
('''2H 5D 3C AS 5S''', False, [14, 5, 5, 3, 2]),
('''JH QD KC AS TS''', False, [14, 13, 12, 11, 10]),
('''9D 3S 2C 7S 7C''', False, [9, 7, 7, 3, 2]),
)
_lowercase = (
('''JH AH TH KH QH''', 0),
('''JH 9H TH KH QH''', 0),
('''JC KH JS JD JH''', 7),
('''KH KC 3S 3H 3D''', 6),
('''8C 9C 5C 3C TC''', 0),
('''JS QS 9H TS KH''', 0),
('''7C 7S KH 2H 7H''', 3),
('''3C KH 5D 5S KH''', 2),
('''QH 8H KD JH 8S''', 1),
('''2D 6D 9D TH 7D''', 0),
)
_lowercase = (
('''JH AH TH KH QH''', 23),
('''JH 9H TH KH QH''', 22),
('''JC KH JS JD JH''', 21),
('''KH KC 3S 3H 3D''', 20),
('''8C 9C 5C 3C TC''', 19),
('''JS QS 9H TS KH''', 18),
('''7C 7S KH 2H 7H''', 17),
('''3C KH 5D 5S KH''', 16),
('''QH 8H KD JH 8S''', 15),
('''2D 6D 9D TH 7D''', 14),
)
def UpperCamelCase ( ):
lowerCAmelCase_ , lowerCAmelCase_ : List[Any] = randrange(len(snake_case__)), randrange(len(snake_case__))
lowerCAmelCase_ : Union[str, Any] = ["Loss", "Tie", "Win"][(play >= oppo) + (play > oppo)]
lowerCAmelCase_ , lowerCAmelCase_ : Tuple = SORTED_HANDS[play], SORTED_HANDS[oppo]
return hand, other, expected
def UpperCamelCase ( snake_case__ = 1_00):
return (generate_random_hand() for _ in range(snake_case__))
@pytest.mark.parametrize("hand, expected" , snake_case__)
def UpperCamelCase ( snake_case__ , snake_case__):
assert PokerHand(snake_case__)._is_flush() == expected
@pytest.mark.parametrize("hand, expected" , snake_case__)
def UpperCamelCase ( snake_case__ , snake_case__):
assert PokerHand(snake_case__)._is_straight() == expected
@pytest.mark.parametrize("hand, expected, card_values" , snake_case__)
def UpperCamelCase ( snake_case__ , snake_case__ , snake_case__):
lowerCAmelCase_ : str = PokerHand(snake_case__)
assert player._is_five_high_straight() == expected
assert player._card_values == card_values
@pytest.mark.parametrize("hand, expected" , snake_case__)
def UpperCamelCase ( snake_case__ , snake_case__):
assert PokerHand(snake_case__)._is_same_kind() == expected
@pytest.mark.parametrize("hand, expected" , snake_case__)
def UpperCamelCase ( snake_case__ , snake_case__):
assert PokerHand(snake_case__)._hand_type == expected
@pytest.mark.parametrize("hand, other, expected" , snake_case__)
def UpperCamelCase ( snake_case__ , snake_case__ , snake_case__):
assert PokerHand(snake_case__).compare_with(PokerHand(snake_case__)) == expected
@pytest.mark.parametrize("hand, other, expected" , generate_random_hands())
def UpperCamelCase ( snake_case__ , snake_case__ , snake_case__):
assert PokerHand(snake_case__).compare_with(PokerHand(snake_case__)) == expected
def UpperCamelCase ( ):
lowerCAmelCase_ : List[Any] = [PokerHand(snake_case__) for hand in SORTED_HANDS]
lowerCAmelCase_ : List[str] = poker_hands.copy()
shuffle(snake_case__)
lowerCAmelCase_ : str = chain(sorted(snake_case__))
for index, hand in enumerate(snake_case__):
assert hand == poker_hands[index]
def UpperCamelCase ( ):
# Test that five high straights are compared correctly.
lowerCAmelCase_ : Union[str, Any] = [PokerHand("2D AC 3H 4H 5S"), PokerHand("2S 3H 4H 5S 6C")]
pokerhands.sort(reverse=snake_case__)
assert pokerhands[0].__str__() == "2S 3H 4H 5S 6C"
def UpperCamelCase ( ):
# Multiple calls to five_high_straight function should still return True
# and shouldn't mutate the list in every call other than the first.
lowerCAmelCase_ : Optional[Any] = PokerHand("2C 4S AS 3D 5C")
lowerCAmelCase_ : Optional[int] = True
lowerCAmelCase_ : Optional[Any] = [5, 4, 3, 2, 14]
for _ in range(10):
assert pokerhand._is_five_high_straight() == expected
assert pokerhand._card_values == expected_card_values
def UpperCamelCase ( ):
# Problem number 54 from Project Euler
# Testing from poker_hands.txt file
lowerCAmelCase_ : Optional[Any] = 0
lowerCAmelCase_ : str = os.path.abspath(os.path.dirname(snake_case__))
lowerCAmelCase_ : Optional[Any] = os.path.join(snake_case__ , "poker_hands.txt")
with open(snake_case__) as file_hand:
for line in file_hand:
lowerCAmelCase_ : Dict = line[:14].strip()
lowerCAmelCase_ : List[str] = line[15:].strip()
lowerCAmelCase_ , lowerCAmelCase_ : List[Any] = PokerHand(snake_case__), PokerHand(snake_case__)
lowerCAmelCase_ : List[Any] = player.compare_with(snake_case__)
if output == "Win":
answer += 1
assert answer == 3_76
| 659 |
from collections import defaultdict
from pathlib import Path
import pandas as pd
from rouge_cli import calculate_rouge_path
from utils import calculate_rouge
_lowercase = [
'''Prosecutor: "No videos were used in the crash investigation" German papers say they saw a cell phone video of the'''
''' final seconds on board Flight 9525. The Germanwings co-pilot says he had a "previous episode of severe'''
''' depression\" German airline confirms it knew of Andreas Lubitz\'s depression years before he took control.''',
'''The Palestinian Authority officially becomes the 123rd member of the International Criminal Court. The formal'''
''' accession was marked with a ceremony at The Hague, in the Netherlands. The Palestinians signed the ICC\'s'''
''' founding Rome Statute in January. Israel and the United States opposed the Palestinians\' efforts to join the'''
''' body.''',
'''Amnesty International releases its annual report on the death penalty. The report catalogs the use of'''
''' state-sanctioned killing as a punitive measure across the globe. At least 607 people were executed around the'''
''' world in 2014, compared to 778 in 2013. The U.S. remains one of the worst offenders for imposing capital'''
''' punishment.''',
]
_lowercase = [
'''Marseille prosecutor says "so far no videos were used in the crash investigation" despite media reports .'''
''' Journalists at Bild and Paris Match are "very confident" the video clip is real, an editor says . Andreas Lubitz'''
''' had informed his Lufthansa training school of an episode of severe depression, airline says .''',
'''Membership gives the ICC jurisdiction over alleged crimes committed in Palestinian territories since last June .'''
''' Israel and the United States opposed the move, which could open the door to war crimes investigations against'''
''' Israelis .''',
'''Amnesty\'s annual death penalty report catalogs encouraging signs, but setbacks in numbers of those sentenced to'''
''' death . Organization claims that governments around the world are using the threat of terrorism to advance'''
''' executions . The number of executions worldwide has gone down by almost 22% compared with 2013, but death'''
''' sentences up by 28% .''',
]
def UpperCamelCase ( ):
lowerCAmelCase_ : Any = calculate_rouge(snake_case__ , snake_case__ , bootstrap_aggregation=snake_case__ , rouge_keys=["rouge2", "rougeL"])
assert isinstance(snake_case__ , snake_case__)
lowerCAmelCase_ : str = calculate_rouge(snake_case__ , snake_case__ , bootstrap_aggregation=snake_case__ , rouge_keys=["rouge2"])
assert (
pd.DataFrame(no_aggregation["rouge2"]).fmeasure.mean()
== pd.DataFrame(no_aggregation_just_ra["rouge2"]).fmeasure.mean()
)
def UpperCamelCase ( ):
lowerCAmelCase_ : str = "rougeLsum"
lowerCAmelCase_ : Any = calculate_rouge(snake_case__ , snake_case__ , newline_sep=snake_case__ , rouge_keys=[k])[k]
lowerCAmelCase_ : List[Any] = calculate_rouge(snake_case__ , snake_case__ , newline_sep=snake_case__ , rouge_keys=[k])[k]
assert score > score_no_sep
def UpperCamelCase ( ):
lowerCAmelCase_ : int = ["rouge1", "rouge2", "rougeL"]
lowerCAmelCase_ : List[Any] = calculate_rouge(snake_case__ , snake_case__ , newline_sep=snake_case__ , rouge_keys=snake_case__)
lowerCAmelCase_ : List[Any] = calculate_rouge(snake_case__ , snake_case__ , newline_sep=snake_case__ , rouge_keys=snake_case__)
assert score_sep == score_no_sep
def UpperCamelCase ( ):
lowerCAmelCase_ : List[str] = [
"Her older sister, Margot Frank, died in 1945, a month earlier than previously thought.",
"Marseille prosecutor says \"so far no videos were used in the crash investigation\" despite media reports .",
]
lowerCAmelCase_ : Dict = [
"Margot Frank, died in 1945, a month earlier than previously thought.",
"Prosecutor: \"No videos were used in the crash investigation\" German papers say they saw a cell phone video of"
" the final seconds on board Flight 9525.",
]
assert calculate_rouge(snake_case__ , snake_case__ , newline_sep=snake_case__) == calculate_rouge(snake_case__ , snake_case__ , newline_sep=snake_case__)
def UpperCamelCase ( ):
lowerCAmelCase_ : Optional[int] = [
"\" \"a person who has such a video needs to immediately give it to the investigators,\" prosecutor says .<n> \"it is a very disturbing scene,\" editor-in-chief of bild online tells \"erin burnett: outfront\" "
]
lowerCAmelCase_ : Any = [
" Marseille prosecutor says \"so far no videos were used in the crash investigation\" despite media reports . Journalists at Bild and Paris Match are \"very confident\" the video clip is real, an editor says . Andreas Lubitz had informed his Lufthansa training school of an episode of severe depression, airline says ."
]
lowerCAmelCase_ : Any = calculate_rouge(snake_case__ , snake_case__ , rouge_keys=["rougeLsum"] , newline_sep=snake_case__)["rougeLsum"]
lowerCAmelCase_ : Any = calculate_rouge(snake_case__ , snake_case__ , rouge_keys=["rougeLsum"])["rougeLsum"]
assert new_score > prev_score
def UpperCamelCase ( ):
lowerCAmelCase_ : int = Path("examples/seq2seq/test_data/wmt_en_ro")
lowerCAmelCase_ : Dict = calculate_rouge_path(data_dir.joinpath("test.source") , data_dir.joinpath("test.target"))
assert isinstance(snake_case__ , snake_case__)
lowerCAmelCase_ : Any = calculate_rouge_path(
data_dir.joinpath("test.source") , data_dir.joinpath("test.target") , bootstrap_aggregation=snake_case__)
assert isinstance(snake_case__ , snake_case__)
| 659 | 1 |
import argparse
import json
from pathlib import Path
import requests
import torch
from huggingface_hub import cached_download, hf_hub_download, hf_hub_url
from PIL import Image
from transformers import DetaConfig, DetaForObjectDetection, DetaImageProcessor, SwinConfig
from transformers.utils import logging
logging.set_verbosity_info()
_lowercase = logging.get_logger(__name__)
def UpperCamelCase ( snake_case__):
lowerCAmelCase_ : Union[str, Any] = SwinConfig(
embed_dim=1_92 , depths=(2, 2, 18, 2) , num_heads=(6, 12, 24, 48) , window_size=12 , out_features=["stage2", "stage3", "stage4"] , )
lowerCAmelCase_ : List[str] = DetaConfig(
backbone_config=snake_case__ , num_queries=9_00 , encoder_ffn_dim=20_48 , decoder_ffn_dim=20_48 , num_feature_levels=5 , assign_first_stage=snake_case__ , with_box_refine=snake_case__ , two_stage=snake_case__ , )
# set labels
lowerCAmelCase_ : int = "huggingface/label-files"
if "o365" in model_name:
lowerCAmelCase_ : List[str] = 3_66
lowerCAmelCase_ : Optional[int] = "object365-id2label.json"
else:
lowerCAmelCase_ : Any = 91
lowerCAmelCase_ : Union[str, Any] = "coco-detection-id2label.json"
lowerCAmelCase_ : Union[str, Any] = num_labels
lowerCAmelCase_ : int = json.load(open(cached_download(hf_hub_url(snake_case__ , snake_case__ , repo_type="dataset")) , "r"))
lowerCAmelCase_ : List[str] = {int(snake_case__): v for k, v in idalabel.items()}
lowerCAmelCase_ : List[str] = idalabel
lowerCAmelCase_ : str = {v: k for k, v in idalabel.items()}
return config
def UpperCamelCase ( snake_case__):
lowerCAmelCase_ : Any = []
# stem
# fmt: off
rename_keys.append(("backbone.0.body.patch_embed.proj.weight", "model.backbone.model.embeddings.patch_embeddings.projection.weight"))
rename_keys.append(("backbone.0.body.patch_embed.proj.bias", "model.backbone.model.embeddings.patch_embeddings.projection.bias"))
rename_keys.append(("backbone.0.body.patch_embed.norm.weight", "model.backbone.model.embeddings.norm.weight"))
rename_keys.append(("backbone.0.body.patch_embed.norm.bias", "model.backbone.model.embeddings.norm.bias"))
# stages
for i in range(len(config.backbone_config.depths)):
for j in range(config.backbone_config.depths[i]):
rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.norm1.weight''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_before.weight'''))
rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.norm1.bias''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_before.bias'''))
rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.attn.relative_position_bias_table''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_bias_table'''))
rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.attn.relative_position_index''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_index'''))
rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.attn.proj.weight''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.weight'''))
rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.attn.proj.bias''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.bias'''))
rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.norm2.weight''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_after.weight'''))
rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.norm2.bias''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_after.bias'''))
rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.mlp.fc1.weight''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.weight'''))
rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.mlp.fc1.bias''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.bias'''))
rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.mlp.fc2.weight''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.output.dense.weight'''))
rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.mlp.fc2.bias''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.output.dense.bias'''))
if i < 3:
rename_keys.append((F'''backbone.0.body.layers.{i}.downsample.reduction.weight''', F'''model.backbone.model.encoder.layers.{i}.downsample.reduction.weight'''))
rename_keys.append((F'''backbone.0.body.layers.{i}.downsample.norm.weight''', F'''model.backbone.model.encoder.layers.{i}.downsample.norm.weight'''))
rename_keys.append((F'''backbone.0.body.layers.{i}.downsample.norm.bias''', F'''model.backbone.model.encoder.layers.{i}.downsample.norm.bias'''))
rename_keys.append(("backbone.0.body.norm1.weight", "model.backbone.model.hidden_states_norms.stage2.weight"))
rename_keys.append(("backbone.0.body.norm1.bias", "model.backbone.model.hidden_states_norms.stage2.bias"))
rename_keys.append(("backbone.0.body.norm2.weight", "model.backbone.model.hidden_states_norms.stage3.weight"))
rename_keys.append(("backbone.0.body.norm2.bias", "model.backbone.model.hidden_states_norms.stage3.bias"))
rename_keys.append(("backbone.0.body.norm3.weight", "model.backbone.model.hidden_states_norms.stage4.weight"))
rename_keys.append(("backbone.0.body.norm3.bias", "model.backbone.model.hidden_states_norms.stage4.bias"))
# transformer encoder
for i in range(config.encoder_layers):
rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.sampling_offsets.weight''', F'''model.encoder.layers.{i}.self_attn.sampling_offsets.weight'''))
rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.sampling_offsets.bias''', F'''model.encoder.layers.{i}.self_attn.sampling_offsets.bias'''))
rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.attention_weights.weight''', F'''model.encoder.layers.{i}.self_attn.attention_weights.weight'''))
rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.attention_weights.bias''', F'''model.encoder.layers.{i}.self_attn.attention_weights.bias'''))
rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.value_proj.weight''', F'''model.encoder.layers.{i}.self_attn.value_proj.weight'''))
rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.value_proj.bias''', F'''model.encoder.layers.{i}.self_attn.value_proj.bias'''))
rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.output_proj.weight''', F'''model.encoder.layers.{i}.self_attn.output_proj.weight'''))
rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.output_proj.bias''', F'''model.encoder.layers.{i}.self_attn.output_proj.bias'''))
rename_keys.append((F'''transformer.encoder.layers.{i}.norm1.weight''', F'''model.encoder.layers.{i}.self_attn_layer_norm.weight'''))
rename_keys.append((F'''transformer.encoder.layers.{i}.norm1.bias''', F'''model.encoder.layers.{i}.self_attn_layer_norm.bias'''))
rename_keys.append((F'''transformer.encoder.layers.{i}.linear1.weight''', F'''model.encoder.layers.{i}.fc1.weight'''))
rename_keys.append((F'''transformer.encoder.layers.{i}.linear1.bias''', F'''model.encoder.layers.{i}.fc1.bias'''))
rename_keys.append((F'''transformer.encoder.layers.{i}.linear2.weight''', F'''model.encoder.layers.{i}.fc2.weight'''))
rename_keys.append((F'''transformer.encoder.layers.{i}.linear2.bias''', F'''model.encoder.layers.{i}.fc2.bias'''))
rename_keys.append((F'''transformer.encoder.layers.{i}.norm2.weight''', F'''model.encoder.layers.{i}.final_layer_norm.weight'''))
rename_keys.append((F'''transformer.encoder.layers.{i}.norm2.bias''', F'''model.encoder.layers.{i}.final_layer_norm.bias'''))
# transformer decoder
for i in range(config.decoder_layers):
rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.sampling_offsets.weight''', F'''model.decoder.layers.{i}.encoder_attn.sampling_offsets.weight'''))
rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.sampling_offsets.bias''', F'''model.decoder.layers.{i}.encoder_attn.sampling_offsets.bias'''))
rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.attention_weights.weight''', F'''model.decoder.layers.{i}.encoder_attn.attention_weights.weight'''))
rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.attention_weights.bias''', F'''model.decoder.layers.{i}.encoder_attn.attention_weights.bias'''))
rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.value_proj.weight''', F'''model.decoder.layers.{i}.encoder_attn.value_proj.weight'''))
rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.value_proj.bias''', F'''model.decoder.layers.{i}.encoder_attn.value_proj.bias'''))
rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.output_proj.weight''', F'''model.decoder.layers.{i}.encoder_attn.output_proj.weight'''))
rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.output_proj.bias''', F'''model.decoder.layers.{i}.encoder_attn.output_proj.bias'''))
rename_keys.append((F'''transformer.decoder.layers.{i}.norm1.weight''', F'''model.decoder.layers.{i}.encoder_attn_layer_norm.weight'''))
rename_keys.append((F'''transformer.decoder.layers.{i}.norm1.bias''', F'''model.decoder.layers.{i}.encoder_attn_layer_norm.bias'''))
rename_keys.append((F'''transformer.decoder.layers.{i}.self_attn.out_proj.weight''', F'''model.decoder.layers.{i}.self_attn.out_proj.weight'''))
rename_keys.append((F'''transformer.decoder.layers.{i}.self_attn.out_proj.bias''', F'''model.decoder.layers.{i}.self_attn.out_proj.bias'''))
rename_keys.append((F'''transformer.decoder.layers.{i}.norm2.weight''', F'''model.decoder.layers.{i}.self_attn_layer_norm.weight'''))
rename_keys.append((F'''transformer.decoder.layers.{i}.norm2.bias''', F'''model.decoder.layers.{i}.self_attn_layer_norm.bias'''))
rename_keys.append((F'''transformer.decoder.layers.{i}.linear1.weight''', F'''model.decoder.layers.{i}.fc1.weight'''))
rename_keys.append((F'''transformer.decoder.layers.{i}.linear1.bias''', F'''model.decoder.layers.{i}.fc1.bias'''))
rename_keys.append((F'''transformer.decoder.layers.{i}.linear2.weight''', F'''model.decoder.layers.{i}.fc2.weight'''))
rename_keys.append((F'''transformer.decoder.layers.{i}.linear2.bias''', F'''model.decoder.layers.{i}.fc2.bias'''))
rename_keys.append((F'''transformer.decoder.layers.{i}.norm3.weight''', F'''model.decoder.layers.{i}.final_layer_norm.weight'''))
rename_keys.append((F'''transformer.decoder.layers.{i}.norm3.bias''', F'''model.decoder.layers.{i}.final_layer_norm.bias'''))
# fmt: on
return rename_keys
def UpperCamelCase ( snake_case__ , snake_case__ , snake_case__):
lowerCAmelCase_ : str = dct.pop(snake_case__)
lowerCAmelCase_ : List[Any] = val
def UpperCamelCase ( snake_case__ , snake_case__):
lowerCAmelCase_ : Any = [int(backbone_config.embed_dim * 2**i) for i in range(len(backbone_config.depths))]
for i in range(len(backbone_config.depths)):
lowerCAmelCase_ : Optional[int] = num_features[i]
for j in range(backbone_config.depths[i]):
# fmt: off
# read in weights + bias of input projection layer (in original implementation, this is a single matrix + bias)
lowerCAmelCase_ : Any = state_dict.pop(F'''backbone.0.body.layers.{i}.blocks.{j}.attn.qkv.weight''')
lowerCAmelCase_ : List[Any] = state_dict.pop(F'''backbone.0.body.layers.{i}.blocks.{j}.attn.qkv.bias''')
# next, add query, keys and values (in that order) to the state dict
lowerCAmelCase_ : Union[str, Any] = in_proj_weight[:dim, :]
lowerCAmelCase_ : Tuple = in_proj_bias[: dim]
lowerCAmelCase_ : Optional[int] = in_proj_weight[
dim : dim * 2, :
]
lowerCAmelCase_ : str = in_proj_bias[
dim : dim * 2
]
lowerCAmelCase_ : int = in_proj_weight[
-dim :, :
]
lowerCAmelCase_ : Dict = in_proj_bias[-dim :]
# fmt: on
def UpperCamelCase ( snake_case__ , snake_case__):
# transformer decoder self-attention layers
lowerCAmelCase_ : Union[str, Any] = config.d_model
for i in range(config.decoder_layers):
# read in weights + bias of input projection layer of self-attention
lowerCAmelCase_ : Union[str, Any] = state_dict.pop(F'''transformer.decoder.layers.{i}.self_attn.in_proj_weight''')
lowerCAmelCase_ : List[Any] = state_dict.pop(F'''transformer.decoder.layers.{i}.self_attn.in_proj_bias''')
# next, add query, keys and values (in that order) to the state dict
lowerCAmelCase_ : Optional[int] = in_proj_weight[:hidden_size, :]
lowerCAmelCase_ : str = in_proj_bias[:hidden_size]
lowerCAmelCase_ : Optional[int] = in_proj_weight[
hidden_size : hidden_size * 2, :
]
lowerCAmelCase_ : Union[str, Any] = in_proj_bias[hidden_size : hidden_size * 2]
lowerCAmelCase_ : str = in_proj_weight[-hidden_size:, :]
lowerCAmelCase_ : str = in_proj_bias[-hidden_size:]
def UpperCamelCase ( ):
lowerCAmelCase_ : Tuple = "http://images.cocodataset.org/val2017/000000039769.jpg"
lowerCAmelCase_ : Tuple = Image.open(requests.get(snake_case__ , stream=snake_case__).raw)
return im
@torch.no_grad()
def UpperCamelCase ( snake_case__ , snake_case__ , snake_case__):
lowerCAmelCase_ : Dict = get_deta_config(snake_case__)
# load original state dict
if model_name == "deta-swin-large":
lowerCAmelCase_ : List[Any] = hf_hub_download(repo_id="nielsr/deta-checkpoints" , filename="adet_swin_ft.pth")
elif model_name == "deta-swin-large-o365":
lowerCAmelCase_ : List[Any] = hf_hub_download(repo_id="jozhang97/deta-swin-l-o365" , filename="deta_swin_pt_o365.pth")
else:
raise ValueError(F'''Model name {model_name} not supported''')
lowerCAmelCase_ : str = torch.load(snake_case__ , map_location="cpu")["model"]
# original state dict
for name, param in state_dict.items():
print(snake_case__ , param.shape)
# rename keys
lowerCAmelCase_ : Dict = create_rename_keys(snake_case__)
for src, dest in rename_keys:
rename_key(snake_case__ , snake_case__ , snake_case__)
read_in_swin_q_k_v(snake_case__ , config.backbone_config)
read_in_decoder_q_k_v(snake_case__ , snake_case__)
# fix some prefixes
for key in state_dict.copy().keys():
if "transformer.decoder.class_embed" in key or "transformer.decoder.bbox_embed" in key:
lowerCAmelCase_ : int = state_dict.pop(snake_case__)
lowerCAmelCase_ : List[Any] = val
if "input_proj" in key:
lowerCAmelCase_ : Any = state_dict.pop(snake_case__)
lowerCAmelCase_ : Tuple = val
if "level_embed" in key or "pos_trans" in key or "pix_trans" in key or "enc_output" in key:
lowerCAmelCase_ : Tuple = state_dict.pop(snake_case__)
lowerCAmelCase_ : int = val
# finally, create HuggingFace model and load state dict
lowerCAmelCase_ : Any = DetaForObjectDetection(snake_case__)
model.load_state_dict(snake_case__)
model.eval()
lowerCAmelCase_ : int = "cuda" if torch.cuda.is_available() else "cpu"
model.to(snake_case__)
# load image processor
lowerCAmelCase_ : List[Any] = DetaImageProcessor(format="coco_detection")
# verify our conversion on image
lowerCAmelCase_ : Optional[int] = prepare_img()
lowerCAmelCase_ : Optional[int] = processor(images=snake_case__ , return_tensors="pt")
lowerCAmelCase_ : Any = encoding["pixel_values"]
lowerCAmelCase_ : int = model(pixel_values.to(snake_case__))
# verify logits
print("Logits:" , outputs.logits[0, :3, :3])
print("Boxes:" , outputs.pred_boxes[0, :3, :3])
if model_name == "deta-swin-large":
lowerCAmelCase_ : Union[str, Any] = torch.tensor(
[[-7.6_308, -2.8_485, -5.3_737], [-7.2_037, -4.5_505, -4.8_027], [-7.2_943, -4.2_611, -4.6_617]])
lowerCAmelCase_ : List[Any] = torch.tensor([[0.4_987, 0.4_969, 0.9_999], [0.2_549, 0.5_498, 0.4_805], [0.5_498, 0.2_757, 0.0_569]])
elif model_name == "deta-swin-large-o365":
lowerCAmelCase_ : List[Any] = torch.tensor(
[[-8.0_122, -3.5_720, -4.9_717], [-8.1_547, -3.6_886, -4.6_389], [-7.6_610, -3.6_194, -5.0_134]])
lowerCAmelCase_ : Optional[int] = torch.tensor([[0.2_523, 0.5_549, 0.4_881], [0.7_715, 0.4_149, 0.4_601], [0.5_503, 0.2_753, 0.0_575]])
assert torch.allclose(outputs.logits[0, :3, :3] , expected_logits.to(snake_case__) , atol=1e-4)
assert torch.allclose(outputs.pred_boxes[0, :3, :3] , expected_boxes.to(snake_case__) , atol=1e-4)
print("Everything ok!")
if pytorch_dump_folder_path:
# Save model and processor
logger.info(F'''Saving PyTorch model and processor to {pytorch_dump_folder_path}...''')
Path(snake_case__).mkdir(exist_ok=snake_case__)
model.save_pretrained(snake_case__)
processor.save_pretrained(snake_case__)
# Push to hub
if push_to_hub:
print("Pushing model and processor to hub...")
model.push_to_hub(F'''jozhang97/{model_name}''')
processor.push_to_hub(F'''jozhang97/{model_name}''')
if __name__ == "__main__":
_lowercase = argparse.ArgumentParser()
parser.add_argument(
'''--model_name''',
type=str,
default='''deta-swin-large''',
choices=['''deta-swin-large''', '''deta-swin-large-o365'''],
help='''Name of the model you\'d like to convert.''',
)
parser.add_argument(
'''--pytorch_dump_folder_path''',
default=None,
type=str,
help='''Path to the folder to output PyTorch model.''',
)
parser.add_argument(
'''--push_to_hub''', action='''store_true''', help='''Whether or not to push the converted model to the 🤗 hub.'''
)
_lowercase = parser.parse_args()
convert_deta_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
| 659 |
import json
import os
import unittest
from transformers import BatchEncoding, LEDTokenizer, LEDTokenizerFast
from transformers.models.led.tokenization_led import VOCAB_FILES_NAMES
from transformers.testing_utils import require_tokenizers, require_torch
from transformers.utils import cached_property
from ...test_tokenization_common import TokenizerTesterMixin
@require_tokenizers
class __snake_case ( snake_case__ , unittest.TestCase ):
"""simple docstring"""
UpperCamelCase_ = LEDTokenizer
UpperCamelCase_ = LEDTokenizerFast
UpperCamelCase_ = True
def UpperCAmelCase_ ( self : List[Any] ) -> Optional[int]:
'''simple docstring'''
super().setUp()
lowerCAmelCase_ : Union[str, Any] = [
"l",
"o",
"w",
"e",
"r",
"s",
"t",
"i",
"d",
"n",
"\u0120",
"\u0120l",
"\u0120n",
"\u0120lo",
"\u0120low",
"er",
"\u0120lowest",
"\u0120newer",
"\u0120wider",
"<unk>",
]
lowerCAmelCase_ : Tuple = dict(zip(lowerCAmelCase__ ,range(len(lowerCAmelCase__ ) ) ) )
lowerCAmelCase_ : int = ["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""]
lowerCAmelCase_ : Union[str, Any] = {"unk_token": "<unk>"}
lowerCAmelCase_ : List[Any] = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES["vocab_file"] )
lowerCAmelCase_ : Any = 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(lowerCAmelCase__ ) + "\n" )
with open(self.merges_file ,"w" ,encoding="utf-8" ) as fp:
fp.write("\n".join(lowerCAmelCase__ ) )
def UpperCAmelCase_ ( self : List[Any] ,**lowerCAmelCase__ : int ) -> Tuple:
'''simple docstring'''
kwargs.update(self.special_tokens_map )
return self.tokenizer_class.from_pretrained(self.tmpdirname ,**lowerCAmelCase__ )
def UpperCAmelCase_ ( self : Union[str, Any] ,**lowerCAmelCase__ : Optional[int] ) -> List[Any]:
'''simple docstring'''
kwargs.update(self.special_tokens_map )
return self.rust_tokenizer_class.from_pretrained(self.tmpdirname ,**lowerCAmelCase__ )
def UpperCAmelCase_ ( self : str ,lowerCAmelCase__ : int ) -> List[str]:
'''simple docstring'''
return "lower newer", "lower newer"
@cached_property
def UpperCAmelCase_ ( self : int ) -> Union[str, Any]:
'''simple docstring'''
return LEDTokenizer.from_pretrained("allenai/led-base-16384" )
@cached_property
def UpperCAmelCase_ ( self : List[str] ) -> Dict:
'''simple docstring'''
return LEDTokenizerFast.from_pretrained("allenai/led-base-16384" )
@require_torch
def UpperCAmelCase_ ( self : int ) -> Optional[int]:
'''simple docstring'''
lowerCAmelCase_ : Union[str, Any] = ["A long paragraph for summarization.", "Another paragraph for summarization."]
lowerCAmelCase_ : int = [0, 2_50, 2_51, 1_78_18, 13, 3_91_86, 19_38, 4, 2]
for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
lowerCAmelCase_ : Any = tokenizer(lowerCAmelCase__ ,max_length=len(lowerCAmelCase__ ) ,padding=lowerCAmelCase__ ,return_tensors="pt" )
self.assertIsInstance(lowerCAmelCase__ ,lowerCAmelCase__ )
self.assertEqual((2, 9) ,batch.input_ids.shape )
self.assertEqual((2, 9) ,batch.attention_mask.shape )
lowerCAmelCase_ : int = batch.input_ids.tolist()[0]
self.assertListEqual(lowerCAmelCase__ ,lowerCAmelCase__ )
@require_torch
def UpperCAmelCase_ ( self : Dict ) -> Any:
'''simple docstring'''
lowerCAmelCase_ : int = ["A long paragraph for summarization.", "Another paragraph for summarization."]
for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
lowerCAmelCase_ : Optional[Any] = tokenizer(lowerCAmelCase__ ,padding=lowerCAmelCase__ ,return_tensors="pt" )
self.assertIn("input_ids" ,lowerCAmelCase__ )
self.assertIn("attention_mask" ,lowerCAmelCase__ )
self.assertNotIn("labels" ,lowerCAmelCase__ )
self.assertNotIn("decoder_attention_mask" ,lowerCAmelCase__ )
@require_torch
def UpperCAmelCase_ ( self : Union[str, Any] ) -> Optional[int]:
'''simple docstring'''
lowerCAmelCase_ : int = [
"Summary of the text.",
"Another summary.",
]
for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
lowerCAmelCase_ : Optional[int] = tokenizer(text_target=lowerCAmelCase__ ,max_length=32 ,padding="max_length" ,return_tensors="pt" )
self.assertEqual(32 ,targets["input_ids"].shape[1] )
@require_torch
def UpperCAmelCase_ ( self : Tuple ) -> List[str]:
'''simple docstring'''
for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
lowerCAmelCase_ : Tuple = tokenizer(
["I am a small frog" * 10_24, "I am a small frog"] ,padding=lowerCAmelCase__ ,truncation=lowerCAmelCase__ ,return_tensors="pt" )
self.assertIsInstance(lowerCAmelCase__ ,lowerCAmelCase__ )
self.assertEqual(batch.input_ids.shape ,(2, 51_22) )
@require_torch
def UpperCAmelCase_ ( self : List[str] ) -> Union[str, Any]:
'''simple docstring'''
lowerCAmelCase_ : Tuple = ["A long paragraph for summarization."]
lowerCAmelCase_ : Dict = [
"Summary of the text.",
]
for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
lowerCAmelCase_ : Optional[Any] = tokenizer(lowerCAmelCase__ ,return_tensors="pt" )
lowerCAmelCase_ : Optional[Any] = tokenizer(text_target=lowerCAmelCase__ ,return_tensors="pt" )
lowerCAmelCase_ : List[str] = inputs["input_ids"]
lowerCAmelCase_ : Any = targets["input_ids"]
self.assertTrue((input_ids[:, 0] == tokenizer.bos_token_id).all().item() )
self.assertTrue((labels[:, 0] == tokenizer.bos_token_id).all().item() )
self.assertTrue((input_ids[:, -1] == tokenizer.eos_token_id).all().item() )
self.assertTrue((labels[:, -1] == tokenizer.eos_token_id).all().item() )
@require_torch
def UpperCAmelCase_ ( self : str ) -> Tuple:
'''simple docstring'''
for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
lowerCAmelCase_ : str = ["Summary of the text.", "Another summary."]
lowerCAmelCase_ : str = [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, -1, -1]]
lowerCAmelCase_ : List[Any] = tokenizer(lowerCAmelCase__ ,padding=lowerCAmelCase__ )
lowerCAmelCase_ : Optional[int] = [[0] * len(lowerCAmelCase__ ) for x in encoded_output["input_ids"]]
lowerCAmelCase_ : Optional[int] = tokenizer.pad(lowerCAmelCase__ )
self.assertSequenceEqual(outputs["global_attention_mask"] ,lowerCAmelCase__ )
def UpperCAmelCase_ ( self : Union[str, Any] ) -> Dict:
'''simple docstring'''
pass
def UpperCAmelCase_ ( self : str ) -> Union[str, Any]:
'''simple docstring'''
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ):
lowerCAmelCase_ : Dict = self.rust_tokenizer_class.from_pretrained(lowerCAmelCase__ ,**lowerCAmelCase__ )
lowerCAmelCase_ : Tuple = self.tokenizer_class.from_pretrained(lowerCAmelCase__ ,**lowerCAmelCase__ )
lowerCAmelCase_ : Dict = "A, <mask> AllenNLP sentence."
lowerCAmelCase_ : Tuple = tokenizer_r.encode_plus(lowerCAmelCase__ ,add_special_tokens=lowerCAmelCase__ ,return_token_type_ids=lowerCAmelCase__ )
lowerCAmelCase_ : int = tokenizer_p.encode_plus(lowerCAmelCase__ ,add_special_tokens=lowerCAmelCase__ ,return_token_type_ids=lowerCAmelCase__ )
self.assertEqual(sum(tokens_r["token_type_ids"] ) ,sum(tokens_p["token_type_ids"] ) )
self.assertEqual(
sum(tokens_r["attention_mask"] ) / len(tokens_r["attention_mask"] ) ,sum(tokens_p["attention_mask"] ) / len(tokens_p["attention_mask"] ) ,)
lowerCAmelCase_ : Any = tokenizer_r.convert_ids_to_tokens(tokens_r["input_ids"] )
lowerCAmelCase_ : Union[str, Any] = tokenizer_p.convert_ids_to_tokens(tokens_p["input_ids"] )
self.assertSequenceEqual(tokens_p["input_ids"] ,[0, 2_50, 6, 5_02_64, 38_23, 4_87, 2_19_92, 36_45, 4, 2] )
self.assertSequenceEqual(tokens_r["input_ids"] ,[0, 2_50, 6, 5_02_64, 38_23, 4_87, 2_19_92, 36_45, 4, 2] )
self.assertSequenceEqual(
lowerCAmelCase__ ,["<s>", "A", ",", "<mask>", "ĠAllen", "N", "LP", "Ġsentence", ".", "</s>"] )
self.assertSequenceEqual(
lowerCAmelCase__ ,["<s>", "A", ",", "<mask>", "ĠAllen", "N", "LP", "Ġsentence", ".", "</s>"] )
| 659 | 1 |
import io
import os
import unicodedata
from typing import Any, Dict, List, Optional, Tuple
import sentencepiece as spm
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
_lowercase = logging.get_logger(__name__)
_lowercase = '''▁'''
_lowercase = {'''vocab_file''': '''vocab.txt''', '''sentencepiece_model_ckpt''': '''sentencepiece.bpe.model'''}
_lowercase = {
'''sentencepiece_model_file''': '''sentencepiece.bpe.model''',
'''vocab_file''': '''vocab.txt''',
}
_lowercase = {
'''vocab_file''': {
'''ernie-m-base''': '''https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/vocab.txt''',
'''ernie-m-large''': '''https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/vocab.txt''',
},
'''sentencepiece_model_file''': {
'''ernie-m-base''': '''https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/sentencepiece.bpe.model''',
'''ernie-m-large''': '''https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/sentencepiece.bpe.model''',
},
}
_lowercase = {
'''ernie-m-base''': 514,
'''ernie-m-large''': 514,
}
_lowercase = {
'''ernie-m-base''': {'''do_lower_case''': False},
'''ernie-m-large''': {'''do_lower_case''': False},
}
class __snake_case ( snake_case__ ):
"""simple docstring"""
UpperCamelCase_ = ["input_ids"]
UpperCamelCase_ = VOCAB_FILES_NAMES
UpperCamelCase_ = PRETRAINED_INIT_CONFIGURATION
UpperCamelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
UpperCamelCase_ = PRETRAINED_VOCAB_FILES_MAP
UpperCamelCase_ = RESOURCE_FILES_NAMES
def __init__( self : str ,lowerCAmelCase__ : Union[str, Any] ,lowerCAmelCase__ : int=None ,lowerCAmelCase__ : Optional[int]=False ,lowerCAmelCase__ : Optional[Any]="utf8" ,lowerCAmelCase__ : Union[str, Any]="[UNK]" ,lowerCAmelCase__ : Optional[Any]="[SEP]" ,lowerCAmelCase__ : Tuple="[PAD]" ,lowerCAmelCase__ : Union[str, Any]="[CLS]" ,lowerCAmelCase__ : Dict="[MASK]" ,lowerCAmelCase__ : Optional[Dict[str, Any]] = None ,**lowerCAmelCase__ : Optional[Any] ,) -> None:
'''simple docstring'''
lowerCAmelCase_ : int = {} if sp_model_kwargs is None else sp_model_kwargs
super().__init__(
do_lower_case=lowerCAmelCase__ ,unk_token=lowerCAmelCase__ ,sep_token=lowerCAmelCase__ ,pad_token=lowerCAmelCase__ ,cls_token=lowerCAmelCase__ ,mask_token=lowerCAmelCase__ ,vocab_file=lowerCAmelCase__ ,encoding=lowerCAmelCase__ ,sp_model_kwargs=self.sp_model_kwargs ,**lowerCAmelCase__ ,)
lowerCAmelCase_ : int = do_lower_case
lowerCAmelCase_ : List[str] = sentencepiece_model_ckpt
lowerCAmelCase_ : List[str] = spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(lowerCAmelCase__ )
# to mimic paddlenlp.transformers.ernie_m.tokenizer.ErnieMTokenizer functioning
if vocab_file is not None:
lowerCAmelCase_ : Optional[Any] = self.load_vocab(filepath=lowerCAmelCase__ )
else:
lowerCAmelCase_ : Tuple = {self.sp_model.id_to_piece(lowerCAmelCase__ ): id for id in range(self.sp_model.get_piece_size() )}
lowerCAmelCase_ : Dict = {v: k for k, v in self.vocab.items()}
def UpperCAmelCase_ ( self : List[Any] ,lowerCAmelCase__ : Any ) -> Tuple:
'''simple docstring'''
if text is None:
return None
lowerCAmelCase_ : Dict = self.tokenize(lowerCAmelCase__ )
lowerCAmelCase_ , lowerCAmelCase_ : int = "", []
for i, ch in enumerate(lowerCAmelCase__ ):
if ch in self.SP_CHAR_MAPPING:
lowerCAmelCase_ : Optional[int] = self.SP_CHAR_MAPPING.get(lowerCAmelCase__ )
else:
lowerCAmelCase_ : str = unicodedata.normalize("NFKC" ,lowerCAmelCase__ )
if self.is_whitespace(lowerCAmelCase__ ):
continue
normalized_text += ch
char_mapping.extend([i] * len(lowerCAmelCase__ ) )
lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ : Any = normalized_text, [], 0
if self.do_lower_case:
lowerCAmelCase_ : Optional[Any] = text.lower()
for token in split_tokens:
if token[:1] == "▁":
lowerCAmelCase_ : str = token[1:]
lowerCAmelCase_ : Tuple = text[offset:].index(lowerCAmelCase__ ) + offset
lowerCAmelCase_ : List[str] = start + len(lowerCAmelCase__ )
token_mapping.append((char_mapping[start], char_mapping[end - 1] + 1) )
lowerCAmelCase_ : Any = end
return token_mapping
@property
def UpperCAmelCase_ ( self : List[Any] ) -> Optional[Any]:
'''simple docstring'''
return len(self.vocab )
def UpperCAmelCase_ ( self : Optional[Any] ) -> Any:
'''simple docstring'''
return dict(self.vocab ,**self.added_tokens_encoder )
def __getstate__( self : Optional[int] ) -> List[str]:
'''simple docstring'''
lowerCAmelCase_ : Optional[int] = self.__dict__.copy()
lowerCAmelCase_ : Optional[int] = None
return state
def __setstate__( self : Optional[int] ,lowerCAmelCase__ : List[Any] ) -> Any:
'''simple docstring'''
lowerCAmelCase_ : Optional[int] = d
# for backward compatibility
if not hasattr(self ,"sp_model_kwargs" ):
lowerCAmelCase_ : str = {}
lowerCAmelCase_ : int = spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(self.sentencepiece_model_ckpt )
def UpperCAmelCase_ ( self : int ,lowerCAmelCase__ : List[str] ) -> Optional[Any]:
'''simple docstring'''
return "".join((self.SP_CHAR_MAPPING.get(lowerCAmelCase__ ,lowerCAmelCase__ ) for c in text) )
def UpperCAmelCase_ ( self : Optional[Any] ,lowerCAmelCase__ : Optional[Any] ,lowerCAmelCase__ : List[Any]=False ,lowerCAmelCase__ : Optional[Any]=64 ,lowerCAmelCase__ : Any=0.1 ) -> int:
'''simple docstring'''
if self.sp_model_kwargs.get("enable_sampling" ) is True:
lowerCAmelCase_ : Union[str, Any] = True
if self.sp_model_kwargs.get("alpha" ) is not None:
lowerCAmelCase_ : Union[str, Any] = self.sp_model_kwargs.get("alpha" )
if self.sp_model_kwargs.get("nbest_size" ) is not None:
lowerCAmelCase_ : List[Any] = self.sp_model_kwargs.get("nbest_size" )
if not enable_sampling:
lowerCAmelCase_ : str = self.sp_model.EncodeAsPieces(lowerCAmelCase__ )
else:
lowerCAmelCase_ : Dict = self.sp_model.SampleEncodeAsPieces(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ )
lowerCAmelCase_ : Union[str, Any] = []
for pi, piece in enumerate(lowerCAmelCase__ ):
if piece == SPIECE_UNDERLINE:
if not pieces[pi + 1].startswith(lowerCAmelCase__ ) and pi != 0:
new_pieces.append(lowerCAmelCase__ )
continue
else:
continue
lowerCAmelCase_ : List[Any] = 0
for i, chunk in enumerate(lowerCAmelCase__ ):
if chunk == SPIECE_UNDERLINE:
continue
if self.is_ch_char(lowerCAmelCase__ ) or self.is_punct(lowerCAmelCase__ ):
if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE:
new_pieces.append(piece[lst_i:i] )
new_pieces.append(lowerCAmelCase__ )
lowerCAmelCase_ : Optional[Any] = i + 1
elif chunk.isdigit() and i > 0 and not piece[i - 1].isdigit():
if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE:
new_pieces.append(piece[lst_i:i] )
lowerCAmelCase_ : int = i
elif not chunk.isdigit() and i > 0 and piece[i - 1].isdigit():
if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE:
new_pieces.append(piece[lst_i:i] )
lowerCAmelCase_ : Dict = i
if len(lowerCAmelCase__ ) > lst_i:
new_pieces.append(piece[lst_i:] )
return new_pieces
def UpperCAmelCase_ ( self : Dict ,lowerCAmelCase__ : List[Any] ) -> Tuple:
'''simple docstring'''
lowerCAmelCase_ : Any = "".join(lowerCAmelCase__ ).replace(lowerCAmelCase__ ," " ).strip()
return out_string
def UpperCAmelCase_ ( self : Optional[int] ,lowerCAmelCase__ : Union[str, Any] ) -> Tuple:
'''simple docstring'''
lowerCAmelCase_ : Tuple = self.convert_ids_to_tokens(lowerCAmelCase__ )
lowerCAmelCase_ : Dict = "".join(lowerCAmelCase__ ).replace(lowerCAmelCase__ ," " ).strip()
return out_string
def UpperCAmelCase_ ( self : Tuple ,lowerCAmelCase__ : Any ) -> Any:
'''simple docstring'''
return self.vocab.get(lowerCAmelCase__ ,self.vocab.get(self.unk_token ) )
def UpperCAmelCase_ ( self : Union[str, Any] ,lowerCAmelCase__ : Any ) -> List[Any]:
'''simple docstring'''
return self.reverse_vocab.get(lowerCAmelCase__ ,self.unk_token )
def UpperCAmelCase_ ( self : Optional[int] ,lowerCAmelCase__ : Optional[Any] ,lowerCAmelCase__ : int=None ) -> Dict:
'''simple docstring'''
if token_ids_a is None:
return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
lowerCAmelCase_ : List[str] = [self.cls_token_id]
lowerCAmelCase_ : Optional[int] = [self.sep_token_id]
return _cls + token_ids_a + _sep + _sep + token_ids_a + _sep
def UpperCAmelCase_ ( self : Any ,lowerCAmelCase__ : int ,lowerCAmelCase__ : Optional[int]=None ) -> int:
'''simple docstring'''
if offset_mapping_a is None:
return [(0, 0)] + offset_mapping_a + [(0, 0)]
return [(0, 0)] + offset_mapping_a + [(0, 0), (0, 0)] + offset_mapping_a + [(0, 0)]
def UpperCAmelCase_ ( self : Tuple ,lowerCAmelCase__ : Any ,lowerCAmelCase__ : Tuple=None ,lowerCAmelCase__ : List[Any]=False ) -> Union[str, Any]:
'''simple docstring'''
if already_has_special_tokens:
if token_ids_a is not None:
raise ValueError(
"You should not supply a second sequence if the provided sequence of "
"ids is already formatted with special tokens for the model." )
return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a]
if token_ids_a is not None:
return [1] + ([0] * len(lowerCAmelCase__ )) + [1, 1] + ([0] * len(lowerCAmelCase__ )) + [1]
return [1] + ([0] * len(lowerCAmelCase__ )) + [1]
def UpperCAmelCase_ ( self : str ,lowerCAmelCase__ : List[int] ,lowerCAmelCase__ : Optional[List[int]] = None ) -> List[int]:
'''simple docstring'''
if token_ids_a is None:
# [CLS] X [SEP]
return (len(lowerCAmelCase__ ) + 2) * [0]
# [CLS] A [SEP] [SEP] B [SEP]
return [0] * (len(lowerCAmelCase__ ) + 1) + [1] * (len(lowerCAmelCase__ ) + 3)
def UpperCAmelCase_ ( self : Dict ,lowerCAmelCase__ : List[str] ) -> Optional[Any]:
'''simple docstring'''
if "\u4e00" <= char <= "\u9fff":
return True
return False
def UpperCAmelCase_ ( self : str ,lowerCAmelCase__ : List[str] ) -> Any:
'''simple docstring'''
if ("a" <= char <= "z") or ("A" <= char <= "Z"):
return True
return False
def UpperCAmelCase_ ( self : List[str] ,lowerCAmelCase__ : int ) -> Any:
'''simple docstring'''
if char in ",;:.?!~,;:。?!《》【】":
return True
return False
def UpperCAmelCase_ ( self : Optional[int] ,lowerCAmelCase__ : int ) -> Any:
'''simple docstring'''
if char == " " or char == "\t" or char == "\n" or char == "\r":
return True
if len(lowerCAmelCase__ ) == 1:
lowerCAmelCase_ : Tuple = unicodedata.category(lowerCAmelCase__ )
if cat == "Zs":
return True
return False
def UpperCAmelCase_ ( self : Optional[int] ,lowerCAmelCase__ : Optional[Any] ) -> Union[str, Any]:
'''simple docstring'''
lowerCAmelCase_ : Tuple = {}
with io.open(lowerCAmelCase__ ,"r" ,encoding="utf-8" ) as f:
for index, line in enumerate(lowerCAmelCase__ ):
lowerCAmelCase_ : Dict = line.rstrip("\n" )
lowerCAmelCase_ : str = int(lowerCAmelCase__ )
return token_to_idx
def UpperCAmelCase_ ( self : Tuple ,lowerCAmelCase__ : str ,lowerCAmelCase__ : Optional[str] = None ) -> Tuple[str]:
'''simple docstring'''
lowerCAmelCase_ : Dict = 0
if os.path.isdir(lowerCAmelCase__ ):
lowerCAmelCase_ : str = os.path.join(
lowerCAmelCase__ ,(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] )
else:
lowerCAmelCase_ : Tuple = (filename_prefix + "-" if filename_prefix else "") + save_directory
with open(lowerCAmelCase__ ,"w" ,encoding="utf-8" ) as writer:
for token, token_index in sorted(self.vocab.items() ,key=lambda lowerCAmelCase__ : kv[1] ):
if index != token_index:
logger.warning(
f'''Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive.'''
" Please check that the vocabulary is not corrupted!" )
lowerCAmelCase_ : Optional[Any] = token_index
writer.write(token + "\n" )
index += 1
lowerCAmelCase_ : List[Any] = os.path.join(lowerCAmelCase__ ,"sentencepiece.bpe.model" )
with open(lowerCAmelCase__ ,"wb" ) as fi:
lowerCAmelCase_ : Optional[Any] = self.sp_model.serialized_model_proto()
fi.write(lowerCAmelCase__ )
return (vocab_file,)
| 659 |
from ....configuration_utils import PretrainedConfig
from ....utils import logging
_lowercase = logging.get_logger(__name__)
_lowercase = {
'''Visual-Attention-Network/van-base''': (
'''https://huggingface.co/Visual-Attention-Network/van-base/blob/main/config.json'''
),
}
class __snake_case ( snake_case__ ):
"""simple docstring"""
UpperCamelCase_ = 'van'
def __init__( self : List[str] ,lowerCAmelCase__ : int=2_24 ,lowerCAmelCase__ : Optional[int]=3 ,lowerCAmelCase__ : Dict=[7, 3, 3, 3] ,lowerCAmelCase__ : List[str]=[4, 2, 2, 2] ,lowerCAmelCase__ : Union[str, Any]=[64, 1_28, 3_20, 5_12] ,lowerCAmelCase__ : Union[str, Any]=[3, 3, 12, 3] ,lowerCAmelCase__ : Any=[8, 8, 4, 4] ,lowerCAmelCase__ : Optional[int]="gelu" ,lowerCAmelCase__ : List[str]=0.02 ,lowerCAmelCase__ : Optional[Any]=1e-6 ,lowerCAmelCase__ : Dict=1e-2 ,lowerCAmelCase__ : Union[str, Any]=0.0 ,lowerCAmelCase__ : Optional[Any]=0.0 ,**lowerCAmelCase__ : List[str] ,) -> Tuple:
'''simple docstring'''
super().__init__(**lowerCAmelCase__ )
lowerCAmelCase_ : Optional[int] = image_size
lowerCAmelCase_ : List[str] = num_channels
lowerCAmelCase_ : str = patch_sizes
lowerCAmelCase_ : Optional[Any] = strides
lowerCAmelCase_ : List[Any] = hidden_sizes
lowerCAmelCase_ : int = depths
lowerCAmelCase_ : int = mlp_ratios
lowerCAmelCase_ : str = hidden_act
lowerCAmelCase_ : List[str] = initializer_range
lowerCAmelCase_ : Dict = layer_norm_eps
lowerCAmelCase_ : str = layer_scale_init_value
lowerCAmelCase_ : Tuple = drop_path_rate
lowerCAmelCase_ : Dict = dropout_rate
| 659 | 1 |
def UpperCamelCase ( snake_case__):
lowerCAmelCase_ : Dict = abs(snake_case__)
lowerCAmelCase_ : Optional[int] = 0
while n > 0:
res += n % 10
n //= 10
return res
def UpperCamelCase ( snake_case__):
lowerCAmelCase_ : List[str] = abs(snake_case__)
return n if n < 10 else n % 10 + sum_of_digits(n // 10)
def UpperCamelCase ( snake_case__):
return sum(int(snake_case__) for c in str(abs(snake_case__)))
def UpperCamelCase ( ):
from collections.abc import Callable
from timeit import timeit
def benchmark_a_function(snake_case__ , snake_case__) -> None:
lowerCAmelCase_ : List[str] = F'''{func.__name__}({value})'''
lowerCAmelCase_ : Optional[Any] = timeit(F'''__main__.{call}''' , setup="import __main__")
print(F'''{call:56} = {func(snake_case__)} -- {timing:.4f} seconds''')
for value in (26_21_44, 11_25_89_99_06_84_26_24, 1_26_76_50_60_02_28_22_94_01_49_67_03_20_53_76):
for func in (sum_of_digits, sum_of_digits_recursion, sum_of_digits_compact):
benchmark_a_function(snake_case__ , snake_case__)
print()
if __name__ == "__main__":
import doctest
doctest.testmod()
benchmark()
| 659 |
from math import factorial
def UpperCamelCase ( snake_case__ , snake_case__):
# If either of the conditions are true, the function is being asked
# to calculate a factorial of a negative number, which is not possible
if n < k or k < 0:
raise ValueError("Please enter positive integers for n and k where n >= k")
return factorial(snake_case__) // (factorial(snake_case__) * factorial(n - k))
if __name__ == "__main__":
print(
'''The number of five-card hands possible from a standard''',
f"fifty-two card deck is: {combinations(52, 5)}\n",
)
print(
'''If a class of 40 students must be arranged into groups of''',
f"4 for group projects, there are {combinations(40, 4)} ways",
'''to arrange them.\n''',
)
print(
'''If 10 teams are competing in a Formula One race, there''',
f"are {combinations(10, 3)} ways that first, second and",
'''third place can be awarded.''',
)
| 659 | 1 |
import argparse
from pathlib import Path
import torch
from transformers import OPTConfig, OPTModel
from transformers.utils import logging
logging.set_verbosity_info()
_lowercase = logging.get_logger(__name__)
def UpperCamelCase ( snake_case__):
lowerCAmelCase_ : List[Any] = torch.load(snake_case__ , map_location="cpu")
if "model" in sd.keys():
lowerCAmelCase_ : Any = torch.load(snake_case__ , map_location="cpu")["model"]
# pop unnecessary weights
lowerCAmelCase_ : int = [
"decoder.version",
"decoder.output_projection.weight",
]
for key in keys_to_delete:
if key in sd:
sd.pop(snake_case__)
lowerCAmelCase_ : Dict = {
"decoder.project_in_dim.weight": "decoder.project_in.weight",
"decoder.project_out_dim.weight": "decoder.project_out.weight",
"decoder.layer_norm.weight": "decoder.final_layer_norm.weight",
"decoder.layer_norm.bias": "decoder.final_layer_norm.bias",
}
for old_key, new_key in keys_to_rename.items():
if old_key in sd:
lowerCAmelCase_ : Dict = sd.pop(snake_case__)
lowerCAmelCase_ : Union[str, Any] = list(sd.keys())
for key in keys:
if ".qkv_proj." in key:
lowerCAmelCase_ : int = sd[key]
# We split QKV in separate Q,K,V
lowerCAmelCase_ : int = key.replace(".qkv_proj." , ".q_proj.")
lowerCAmelCase_ : List[str] = key.replace(".qkv_proj." , ".k_proj.")
lowerCAmelCase_ : Tuple = key.replace(".qkv_proj." , ".v_proj.")
lowerCAmelCase_ : Any = value.shape[0]
assert depth % 3 == 0
# `SequeuceParallelTransformerBlock` has QKV weight is separated in K,V,Q despite the naming:
# https://cs.github.com/facebookresearch/metaseq/blob/51871bd73cd04c038f239ea2a26db1d7f6b37927/metaseq/modules/sequence_parallel_transformer_layer.py#L97
lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ : Optional[Any] = torch.split(snake_case__ , depth // 3 , dim=0)
lowerCAmelCase_ : Any = q
lowerCAmelCase_ : int = k
lowerCAmelCase_ : Any = v
del sd[key]
return sd
@torch.no_grad()
def UpperCamelCase ( snake_case__ , snake_case__ , snake_case__=None):
lowerCAmelCase_ : Optional[int] = load_checkpoint(snake_case__)
if config is not None:
lowerCAmelCase_ : List[Any] = OPTConfig.from_pretrained(snake_case__)
else:
lowerCAmelCase_ : List[str] = OPTConfig()
lowerCAmelCase_ : Optional[Any] = OPTModel(snake_case__).half().eval()
model.load_state_dict(snake_case__)
# Check results
Path(snake_case__).mkdir(exist_ok=snake_case__)
model.save_pretrained(snake_case__)
if __name__ == "__main__":
_lowercase = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'''--fairseq_path''',
type=str,
help=(
'''path to fairseq checkpoint in correct format. You can find all checkpoints in the correct format here:'''
''' https://huggingface.co/models?other=opt_metasq'''
),
)
parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''')
parser.add_argument('''--hf_config''', default=None, type=str, help='''Define HF config.''')
_lowercase = parser.parse_args()
convert_opt_checkpoint(args.fairseq_path, args.pytorch_dump_folder_path, config=args.hf_config)
| 659 |
import argparse
import json
from tqdm import tqdm
def UpperCamelCase ( ):
lowerCAmelCase_ : Any = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--src_path" , type=snake_case__ , default="biencoder-nq-dev.json" , help="Path to raw DPR training data" , )
parser.add_argument(
"--evaluation_set" , type=snake_case__ , help="where to store parsed evaluation_set file" , )
parser.add_argument(
"--gold_data_path" , type=snake_case__ , help="where to store parsed gold_data_path file" , )
lowerCAmelCase_ : Dict = parser.parse_args()
with open(args.src_path , "r") as src_file, open(args.evaluation_set , "w") as eval_file, open(
args.gold_data_path , "w") as gold_file:
lowerCAmelCase_ : Optional[int] = json.load(snake_case__)
for dpr_record in tqdm(snake_case__):
lowerCAmelCase_ : str = dpr_record["question"]
lowerCAmelCase_ : Dict = [context["title"] for context in dpr_record["positive_ctxs"]]
eval_file.write(question + "\n")
gold_file.write("\t".join(snake_case__) + "\n")
if __name__ == "__main__":
main()
| 659 | 1 |
import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple
import sentencepiece as spm
from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging
_lowercase = logging.get_logger(__name__)
_lowercase = {'''vocab_file''': '''sentencepiece.bpe.model'''}
_lowercase = {
'''vocab_file''': {
'''moussaKam/mbarthez''': '''https://huggingface.co/moussaKam/mbarthez/resolve/main/sentencepiece.bpe.model''',
'''moussaKam/barthez''': '''https://huggingface.co/moussaKam/barthez/resolve/main/sentencepiece.bpe.model''',
'''moussaKam/barthez-orangesum-title''': (
'''https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/sentencepiece.bpe.model'''
),
},
}
_lowercase = {
'''moussaKam/mbarthez''': 1024,
'''moussaKam/barthez''': 1024,
'''moussaKam/barthez-orangesum-title''': 1024,
}
_lowercase = '''▁'''
class __snake_case ( snake_case__ ):
"""simple docstring"""
UpperCamelCase_ = VOCAB_FILES_NAMES
UpperCamelCase_ = PRETRAINED_VOCAB_FILES_MAP
UpperCamelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
UpperCamelCase_ = ['input_ids', 'attention_mask']
def __init__( self : Optional[Any] ,lowerCAmelCase__ : List[str] ,lowerCAmelCase__ : Union[str, Any]="<s>" ,lowerCAmelCase__ : Dict="</s>" ,lowerCAmelCase__ : List[Any]="</s>" ,lowerCAmelCase__ : int="<s>" ,lowerCAmelCase__ : Dict="<unk>" ,lowerCAmelCase__ : Dict="<pad>" ,lowerCAmelCase__ : List[str]="<mask>" ,lowerCAmelCase__ : Optional[Dict[str, Any]] = None ,**lowerCAmelCase__ : Tuple ,) -> None:
'''simple docstring'''
lowerCAmelCase_ : int = AddedToken(lowerCAmelCase__ ,lstrip=lowerCAmelCase__ ,rstrip=lowerCAmelCase__ ) if isinstance(lowerCAmelCase__ ,lowerCAmelCase__ ) else mask_token
lowerCAmelCase_ : str = {} if sp_model_kwargs is None else sp_model_kwargs
super().__init__(
bos_token=lowerCAmelCase__ ,eos_token=lowerCAmelCase__ ,unk_token=lowerCAmelCase__ ,sep_token=lowerCAmelCase__ ,cls_token=lowerCAmelCase__ ,pad_token=lowerCAmelCase__ ,mask_token=lowerCAmelCase__ ,sp_model_kwargs=self.sp_model_kwargs ,**lowerCAmelCase__ ,)
lowerCAmelCase_ : Optional[int] = vocab_file
lowerCAmelCase_ : Any = spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(str(lowerCAmelCase__ ) )
lowerCAmelCase_ : List[str] = {"<s>": 0, "<pad>": 1, "</s>": 2, "<unk>": 3}
lowerCAmelCase_ : List[Any] = len(self.sp_model ) - 1
lowerCAmelCase_ : Optional[int] = {v: k for k, v in self.fairseq_tokens_to_ids.items()}
def UpperCAmelCase_ ( self : List[Any] ,lowerCAmelCase__ : List[int] ,lowerCAmelCase__ : Optional[List[int]] = None ) -> List[int]:
'''simple docstring'''
if token_ids_a is None:
return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
lowerCAmelCase_ : Union[str, Any] = [self.cls_token_id]
lowerCAmelCase_ : int = [self.sep_token_id]
return cls + token_ids_a + sep + sep + token_ids_a + sep
def UpperCAmelCase_ ( self : List[Any] ,lowerCAmelCase__ : List[int] ,lowerCAmelCase__ : Optional[List[int]] = None ,lowerCAmelCase__ : bool = False ) -> List[int]:
'''simple docstring'''
if already_has_special_tokens:
return super().get_special_tokens_mask(
token_ids_a=lowerCAmelCase__ ,token_ids_a=lowerCAmelCase__ ,already_has_special_tokens=lowerCAmelCase__ )
if token_ids_a is None:
return [1] + ([0] * len(lowerCAmelCase__ )) + [1]
return [1] + ([0] * len(lowerCAmelCase__ )) + [1, 1] + ([0] * len(lowerCAmelCase__ )) + [1]
def UpperCAmelCase_ ( self : Dict ,lowerCAmelCase__ : List[int] ,lowerCAmelCase__ : Optional[List[int]] = None ) -> List[int]:
'''simple docstring'''
lowerCAmelCase_ : Union[str, Any] = [self.sep_token_id]
lowerCAmelCase_ : int = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
@property
def UpperCAmelCase_ ( self : Optional[int] ) -> Union[str, Any]:
'''simple docstring'''
return len(self.sp_model )
def UpperCAmelCase_ ( self : Optional[int] ) -> int:
'''simple docstring'''
lowerCAmelCase_ : int = {self.convert_ids_to_tokens(lowerCAmelCase__ ): i for i in range(self.vocab_size )}
vocab.update(self.added_tokens_encoder )
return vocab
def UpperCAmelCase_ ( self : str ,lowerCAmelCase__ : str ) -> List[str]:
'''simple docstring'''
return self.sp_model.encode(lowerCAmelCase__ ,out_type=lowerCAmelCase__ )
def UpperCAmelCase_ ( self : int ,lowerCAmelCase__ : str ) -> Tuple:
'''simple docstring'''
if token in self.fairseq_tokens_to_ids:
return self.fairseq_tokens_to_ids[token]
lowerCAmelCase_ : Tuple = self.sp_model.PieceToId(lowerCAmelCase__ )
return spm_id if spm_id else self.unk_token_id
def UpperCAmelCase_ ( self : Optional[Any] ,lowerCAmelCase__ : Optional[int] ) -> int:
'''simple docstring'''
if index in self.fairseq_ids_to_tokens:
return self.fairseq_ids_to_tokens[index]
return self.sp_model.IdToPiece(lowerCAmelCase__ )
def UpperCAmelCase_ ( self : List[Any] ,lowerCAmelCase__ : Tuple ) -> Optional[int]:
'''simple docstring'''
lowerCAmelCase_ : Optional[Any] = []
lowerCAmelCase_ : Optional[int] = ""
lowerCAmelCase_ : Optional[Any] = False
for token in tokens:
# make sure that special tokens are not decoded using sentencepiece model
if token in self.all_special_tokens:
if not prev_is_special:
out_string += " "
out_string += self.sp_model.decode(lowerCAmelCase__ ) + token
lowerCAmelCase_ : str = True
lowerCAmelCase_ : List[str] = []
else:
current_sub_tokens.append(lowerCAmelCase__ )
lowerCAmelCase_ : Optional[int] = False
out_string += self.sp_model.decode(lowerCAmelCase__ )
return out_string.strip()
def __getstate__( self : int ) -> Any:
'''simple docstring'''
lowerCAmelCase_ : Any = self.__dict__.copy()
lowerCAmelCase_ : Tuple = None
return state
def __setstate__( self : List[Any] ,lowerCAmelCase__ : Optional[Any] ) -> Any:
'''simple docstring'''
lowerCAmelCase_ : int = d
# for backward compatibility
if not hasattr(self ,"sp_model_kwargs" ):
lowerCAmelCase_ : Any = {}
lowerCAmelCase_ : int = spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(self.vocab_file )
def UpperCAmelCase_ ( self : List[Any] ,lowerCAmelCase__ : str ,lowerCAmelCase__ : Optional[str] = None ) -> Tuple[str]:
'''simple docstring'''
if not os.path.isdir(lowerCAmelCase__ ):
logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' )
return
lowerCAmelCase_ : Union[str, Any] = os.path.join(
lowerCAmelCase__ ,(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] )
if os.path.abspath(self.vocab_file ) != os.path.abspath(lowerCAmelCase__ ) and os.path.isfile(self.vocab_file ):
copyfile(self.vocab_file ,lowerCAmelCase__ )
elif not os.path.isfile(self.vocab_file ):
with open(lowerCAmelCase__ ,"wb" ) as fi:
lowerCAmelCase_ : List[str] = self.sp_model.serialized_model_proto()
fi.write(lowerCAmelCase__ )
return (out_vocab_file,)
| 659 |
from collections.abc import Sequence
def UpperCamelCase ( snake_case__ = None):
if nums is None or not nums:
raise ValueError("Input sequence should not be empty")
lowerCAmelCase_ : Dict = nums[0]
for i in range(1 , len(snake_case__)):
lowerCAmelCase_ : Optional[int] = nums[i]
lowerCAmelCase_ : Optional[int] = max(snake_case__ , ans + num , snake_case__)
return ans
if __name__ == "__main__":
import doctest
doctest.testmod()
# Try on a sample input from the user
_lowercase = int(input('''Enter number of elements : ''').strip())
_lowercase = list(map(int, input('''\nEnter the numbers : ''').strip().split()))[:n]
print(max_subsequence_sum(array))
| 659 | 1 |
import tempfile
import torch
from diffusers import (
DEISMultistepScheduler,
DPMSolverMultistepScheduler,
DPMSolverSinglestepScheduler,
UniPCMultistepScheduler,
)
from .test_schedulers import SchedulerCommonTest
class __snake_case ( snake_case__ ):
"""simple docstring"""
UpperCamelCase_ = (DPMSolverSinglestepScheduler,)
UpperCamelCase_ = (('num_inference_steps', 2_5),)
def UpperCAmelCase_ ( self : Dict ,**lowerCAmelCase__ : Any ) -> Dict:
'''simple docstring'''
lowerCAmelCase_ : List[Any] = {
"num_train_timesteps": 10_00,
"beta_start": 0.0_001,
"beta_end": 0.02,
"beta_schedule": "linear",
"solver_order": 2,
"prediction_type": "epsilon",
"thresholding": False,
"sample_max_value": 1.0,
"algorithm_type": "dpmsolver++",
"solver_type": "midpoint",
"lambda_min_clipped": -float("inf" ),
"variance_type": None,
}
config.update(**lowerCAmelCase__ )
return config
def UpperCAmelCase_ ( self : Optional[Any] ,lowerCAmelCase__ : str=0 ,**lowerCAmelCase__ : int ) -> List[str]:
'''simple docstring'''
lowerCAmelCase_ : Tuple = dict(self.forward_default_kwargs )
lowerCAmelCase_ : List[Any] = kwargs.pop("num_inference_steps" ,lowerCAmelCase__ )
lowerCAmelCase_ : int = self.dummy_sample
lowerCAmelCase_ : Any = 0.1 * sample
lowerCAmelCase_ : int = [residual + 0.2, residual + 0.15, residual + 0.10]
for scheduler_class in self.scheduler_classes:
lowerCAmelCase_ : Optional[Any] = self.get_scheduler_config(**lowerCAmelCase__ )
lowerCAmelCase_ : Tuple = scheduler_class(**lowerCAmelCase__ )
scheduler.set_timesteps(lowerCAmelCase__ )
# copy over dummy past residuals
lowerCAmelCase_ : Tuple = dummy_past_residuals[: scheduler.config.solver_order]
with tempfile.TemporaryDirectory() as tmpdirname:
scheduler.save_config(lowerCAmelCase__ )
lowerCAmelCase_ : Any = scheduler_class.from_pretrained(lowerCAmelCase__ )
new_scheduler.set_timesteps(lowerCAmelCase__ )
# copy over dummy past residuals
lowerCAmelCase_ : List[str] = dummy_past_residuals[: new_scheduler.config.solver_order]
lowerCAmelCase_ , lowerCAmelCase_ : List[str] = sample, sample
for t in range(lowerCAmelCase__ ,time_step + scheduler.config.solver_order + 1 ):
lowerCAmelCase_ : Dict = scheduler.step(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,**lowerCAmelCase__ ).prev_sample
lowerCAmelCase_ : int = new_scheduler.step(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,**lowerCAmelCase__ ).prev_sample
assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical"
def UpperCAmelCase_ ( self : List[str] ) -> str:
'''simple docstring'''
pass
def UpperCAmelCase_ ( self : int ,lowerCAmelCase__ : List[Any]=0 ,**lowerCAmelCase__ : List[Any] ) -> Optional[int]:
'''simple docstring'''
lowerCAmelCase_ : Union[str, Any] = dict(self.forward_default_kwargs )
lowerCAmelCase_ : Union[str, Any] = kwargs.pop("num_inference_steps" ,lowerCAmelCase__ )
lowerCAmelCase_ : Tuple = self.dummy_sample
lowerCAmelCase_ : List[Any] = 0.1 * sample
lowerCAmelCase_ : List[Any] = [residual + 0.2, residual + 0.15, residual + 0.10]
for scheduler_class in self.scheduler_classes:
lowerCAmelCase_ : str = self.get_scheduler_config()
lowerCAmelCase_ : Optional[int] = scheduler_class(**lowerCAmelCase__ )
scheduler.set_timesteps(lowerCAmelCase__ )
# copy over dummy past residuals (must be after setting timesteps)
lowerCAmelCase_ : Optional[Any] = dummy_past_residuals[: scheduler.config.solver_order]
with tempfile.TemporaryDirectory() as tmpdirname:
scheduler.save_config(lowerCAmelCase__ )
lowerCAmelCase_ : Optional[Any] = scheduler_class.from_pretrained(lowerCAmelCase__ )
# copy over dummy past residuals
new_scheduler.set_timesteps(lowerCAmelCase__ )
# copy over dummy past residual (must be after setting timesteps)
lowerCAmelCase_ : Optional[Any] = dummy_past_residuals[: new_scheduler.config.solver_order]
lowerCAmelCase_ : Tuple = scheduler.step(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,**lowerCAmelCase__ ).prev_sample
lowerCAmelCase_ : Dict = new_scheduler.step(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,**lowerCAmelCase__ ).prev_sample
assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical"
def UpperCAmelCase_ ( self : Any ,lowerCAmelCase__ : List[Any]=None ,**lowerCAmelCase__ : str ) -> int:
'''simple docstring'''
if scheduler is None:
lowerCAmelCase_ : Optional[int] = self.scheduler_classes[0]
lowerCAmelCase_ : int = self.get_scheduler_config(**lowerCAmelCase__ )
lowerCAmelCase_ : Union[str, Any] = scheduler_class(**lowerCAmelCase__ )
lowerCAmelCase_ : Optional[int] = self.scheduler_classes[0]
lowerCAmelCase_ : List[Any] = self.get_scheduler_config(**lowerCAmelCase__ )
lowerCAmelCase_ : List[str] = scheduler_class(**lowerCAmelCase__ )
lowerCAmelCase_ : Any = 10
lowerCAmelCase_ : Optional[int] = self.dummy_model()
lowerCAmelCase_ : Optional[Any] = self.dummy_sample_deter
scheduler.set_timesteps(lowerCAmelCase__ )
for i, t in enumerate(scheduler.timesteps ):
lowerCAmelCase_ : Any = model(lowerCAmelCase__ ,lowerCAmelCase__ )
lowerCAmelCase_ : str = scheduler.step(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ).prev_sample
return sample
def UpperCAmelCase_ ( self : Dict ) -> List[str]:
'''simple docstring'''
lowerCAmelCase_ : List[Any] = DPMSolverSinglestepScheduler(**self.get_scheduler_config() )
lowerCAmelCase_ : Optional[int] = 50
lowerCAmelCase_ : Optional[Any] = self.dummy_model()
lowerCAmelCase_ : str = self.dummy_sample_deter
scheduler.set_timesteps(lowerCAmelCase__ )
# make sure that the first t is uneven
for i, t in enumerate(scheduler.timesteps[3:] ):
lowerCAmelCase_ : Optional[int] = model(lowerCAmelCase__ ,lowerCAmelCase__ )
lowerCAmelCase_ : Any = scheduler.step(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ).prev_sample
lowerCAmelCase_ : List[str] = torch.mean(torch.abs(lowerCAmelCase__ ) )
assert abs(result_mean.item() - 0.2_574 ) < 1e-3
def UpperCAmelCase_ ( self : List[str] ) -> Any:
'''simple docstring'''
for timesteps in [25, 50, 1_00, 9_99, 10_00]:
self.check_over_configs(num_train_timesteps=lowerCAmelCase__ )
def UpperCAmelCase_ ( self : str ) -> Union[str, Any]:
'''simple docstring'''
lowerCAmelCase_ : int = DPMSolverSinglestepScheduler(**self.get_scheduler_config() )
lowerCAmelCase_ : Optional[int] = self.full_loop(scheduler=lowerCAmelCase__ )
lowerCAmelCase_ : int = torch.mean(torch.abs(lowerCAmelCase__ ) )
assert abs(result_mean.item() - 0.2_791 ) < 1e-3
lowerCAmelCase_ : Tuple = DEISMultistepScheduler.from_config(scheduler.config )
lowerCAmelCase_ : List[str] = DPMSolverMultistepScheduler.from_config(scheduler.config )
lowerCAmelCase_ : List[Any] = UniPCMultistepScheduler.from_config(scheduler.config )
lowerCAmelCase_ : Tuple = DPMSolverSinglestepScheduler.from_config(scheduler.config )
lowerCAmelCase_ : str = self.full_loop(scheduler=lowerCAmelCase__ )
lowerCAmelCase_ : Dict = torch.mean(torch.abs(lowerCAmelCase__ ) )
assert abs(result_mean.item() - 0.2_791 ) < 1e-3
def UpperCAmelCase_ ( self : List[str] ) -> Union[str, Any]:
'''simple docstring'''
self.check_over_configs(thresholding=lowerCAmelCase__ )
for order in [1, 2, 3]:
for solver_type in ["midpoint", "heun"]:
for threshold in [0.5, 1.0, 2.0]:
for prediction_type in ["epsilon", "sample"]:
self.check_over_configs(
thresholding=lowerCAmelCase__ ,prediction_type=lowerCAmelCase__ ,sample_max_value=lowerCAmelCase__ ,algorithm_type="dpmsolver++" ,solver_order=lowerCAmelCase__ ,solver_type=lowerCAmelCase__ ,)
def UpperCAmelCase_ ( self : Optional[Any] ) -> List[Any]:
'''simple docstring'''
for prediction_type in ["epsilon", "v_prediction"]:
self.check_over_configs(prediction_type=lowerCAmelCase__ )
def UpperCAmelCase_ ( self : Union[str, Any] ) -> Union[str, Any]:
'''simple docstring'''
for algorithm_type in ["dpmsolver", "dpmsolver++"]:
for solver_type in ["midpoint", "heun"]:
for order in [1, 2, 3]:
for prediction_type in ["epsilon", "sample"]:
self.check_over_configs(
solver_order=lowerCAmelCase__ ,solver_type=lowerCAmelCase__ ,prediction_type=lowerCAmelCase__ ,algorithm_type=lowerCAmelCase__ ,)
lowerCAmelCase_ : Dict = self.full_loop(
solver_order=lowerCAmelCase__ ,solver_type=lowerCAmelCase__ ,prediction_type=lowerCAmelCase__ ,algorithm_type=lowerCAmelCase__ ,)
assert not torch.isnan(lowerCAmelCase__ ).any(), "Samples have nan numbers"
def UpperCAmelCase_ ( self : Optional[int] ) -> List[Any]:
'''simple docstring'''
self.check_over_configs(lower_order_final=lowerCAmelCase__ )
self.check_over_configs(lower_order_final=lowerCAmelCase__ )
def UpperCAmelCase_ ( self : Optional[Any] ) -> Union[str, Any]:
'''simple docstring'''
self.check_over_configs(lambda_min_clipped=-float("inf" ) )
self.check_over_configs(lambda_min_clipped=-5.1 )
def UpperCAmelCase_ ( self : int ) -> Union[str, Any]:
'''simple docstring'''
self.check_over_configs(variance_type=lowerCAmelCase__ )
self.check_over_configs(variance_type="learned_range" )
def UpperCAmelCase_ ( self : Optional[Any] ) -> int:
'''simple docstring'''
for num_inference_steps in [1, 2, 3, 5, 10, 50, 1_00, 9_99, 10_00]:
self.check_over_forward(num_inference_steps=lowerCAmelCase__ ,time_step=0 )
def UpperCAmelCase_ ( self : int ) -> Optional[Any]:
'''simple docstring'''
lowerCAmelCase_ : Dict = self.full_loop()
lowerCAmelCase_ : int = torch.mean(torch.abs(lowerCAmelCase__ ) )
assert abs(result_mean.item() - 0.2_791 ) < 1e-3
def UpperCAmelCase_ ( self : int ) -> int:
'''simple docstring'''
lowerCAmelCase_ : List[Any] = self.full_loop(use_karras_sigmas=lowerCAmelCase__ )
lowerCAmelCase_ : List[Any] = torch.mean(torch.abs(lowerCAmelCase__ ) )
assert abs(result_mean.item() - 0.2_248 ) < 1e-3
def UpperCAmelCase_ ( self : Optional[int] ) -> Tuple:
'''simple docstring'''
lowerCAmelCase_ : Tuple = self.full_loop(prediction_type="v_prediction" )
lowerCAmelCase_ : List[str] = torch.mean(torch.abs(lowerCAmelCase__ ) )
assert abs(result_mean.item() - 0.1_453 ) < 1e-3
def UpperCAmelCase_ ( self : List[Any] ) -> List[Any]:
'''simple docstring'''
lowerCAmelCase_ : int = self.full_loop(prediction_type="v_prediction" ,use_karras_sigmas=lowerCAmelCase__ )
lowerCAmelCase_ : Optional[int] = torch.mean(torch.abs(lowerCAmelCase__ ) )
assert abs(result_mean.item() - 0.0_649 ) < 1e-3
def UpperCAmelCase_ ( self : Optional[int] ) -> List[Any]:
'''simple docstring'''
lowerCAmelCase_ : str = self.scheduler_classes[0]
lowerCAmelCase_ : Union[str, Any] = self.get_scheduler_config(thresholding=lowerCAmelCase__ ,dynamic_thresholding_ratio=0 )
lowerCAmelCase_ : List[Any] = scheduler_class(**lowerCAmelCase__ )
lowerCAmelCase_ : Optional[int] = 10
lowerCAmelCase_ : List[Any] = self.dummy_model()
lowerCAmelCase_ : str = self.dummy_sample_deter.half()
scheduler.set_timesteps(lowerCAmelCase__ )
for i, t in enumerate(scheduler.timesteps ):
lowerCAmelCase_ : int = model(lowerCAmelCase__ ,lowerCAmelCase__ )
lowerCAmelCase_ : Optional[int] = scheduler.step(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ).prev_sample
assert sample.dtype == torch.floataa
| 659 |
from typing import TYPE_CHECKING
from ....utils import _LazyModule
_lowercase = {'''tokenization_tapex''': ['''TapexTokenizer''']}
if TYPE_CHECKING:
from .tokenization_tapex import TapexTokenizer
else:
import sys
_lowercase = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
| 659 | 1 |
from __future__ import annotations
from collections.abc import Callable
_lowercase = list[list[float | int]]
def UpperCamelCase ( snake_case__ , snake_case__):
lowerCAmelCase_ : int = len(snake_case__)
lowerCAmelCase_ : Matrix = [[0 for _ in range(size + 1)] for _ in range(snake_case__)]
lowerCAmelCase_ : int
lowerCAmelCase_ : int
lowerCAmelCase_ : int
lowerCAmelCase_ : int
lowerCAmelCase_ : int
lowerCAmelCase_ : float
for row in range(snake_case__):
for col in range(snake_case__):
lowerCAmelCase_ : Optional[Any] = matrix[row][col]
lowerCAmelCase_ : Any = vector[row][0]
lowerCAmelCase_ : List[Any] = 0
lowerCAmelCase_ : Optional[Any] = 0
while row < size and col < size:
# pivoting
lowerCAmelCase_ : List[str] = max((abs(augmented[rowa][col]), rowa) for rowa in range(snake_case__ , snake_case__))[
1
]
if augmented[pivot_row][col] == 0:
col += 1
continue
else:
lowerCAmelCase_ , lowerCAmelCase_ : Optional[int] = augmented[pivot_row], augmented[row]
for rowa in range(row + 1 , snake_case__):
lowerCAmelCase_ : Optional[int] = augmented[rowa][col] / augmented[row][col]
lowerCAmelCase_ : Dict = 0
for cola in range(col + 1 , size + 1):
augmented[rowa][cola] -= augmented[row][cola] * ratio
row += 1
col += 1
# back substitution
for col in range(1 , snake_case__):
for row in range(snake_case__):
lowerCAmelCase_ : Any = augmented[row][col] / augmented[col][col]
for cola in range(snake_case__ , size + 1):
augmented[row][cola] -= augmented[col][cola] * ratio
# round to get rid of numbers like 2.000000000000004
return [
[round(augmented[row][size] / augmented[row][row] , 10)] for row in range(snake_case__)
]
def UpperCamelCase ( snake_case__):
lowerCAmelCase_ : int = len(snake_case__)
lowerCAmelCase_ : Matrix = [[0 for _ in range(snake_case__)] for _ in range(snake_case__)]
lowerCAmelCase_ : Matrix = [[0] for _ in range(snake_case__)]
lowerCAmelCase_ : Matrix
lowerCAmelCase_ : int
lowerCAmelCase_ : int
lowerCAmelCase_ : int
for x_val, y_val in enumerate(snake_case__):
for col in range(snake_case__):
lowerCAmelCase_ : Union[str, Any] = (x_val + 1) ** (size - col - 1)
lowerCAmelCase_ : Tuple = y_val
lowerCAmelCase_ : Optional[int] = solve(snake_case__ , snake_case__)
def interpolated_func(snake_case__) -> int:
return sum(
round(coeffs[x_val][0]) * (var ** (size - x_val - 1))
for x_val in range(snake_case__))
return interpolated_func
def UpperCamelCase ( snake_case__):
return (
1
- variable
+ variable**2
- variable**3
+ variable**4
- variable**5
+ variable**6
- variable**7
+ variable**8
- variable**9
+ variable**10
)
def UpperCamelCase ( snake_case__ = question_function , snake_case__ = 10):
lowerCAmelCase_ : list[int] = [func(snake_case__) for x_val in range(1 , order + 1)]
lowerCAmelCase_ : list[Callable[[int], int]] = [
interpolate(data_points[:max_coeff]) for max_coeff in range(1 , order + 1)
]
lowerCAmelCase_ : int = 0
lowerCAmelCase_ : Callable[[int], int]
lowerCAmelCase_ : int
for poly in polynomials:
lowerCAmelCase_ : List[Any] = 1
while func(snake_case__) == poly(snake_case__):
x_val += 1
ret += poly(snake_case__)
return ret
if __name__ == "__main__":
print(f"{solution() = }")
| 659 |
import argparse
import glob
import importlib.util
import os
import re
import black
from doc_builder.style_doc import style_docstrings_in_code
# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_copies.py
_lowercase = '''src/diffusers'''
_lowercase = '''.'''
# This is to make sure the diffusers module imported is the one in the repo.
_lowercase = importlib.util.spec_from_file_location(
'''diffusers''',
os.path.join(DIFFUSERS_PATH, '''__init__.py'''),
submodule_search_locations=[DIFFUSERS_PATH],
)
_lowercase = spec.loader.load_module()
def UpperCamelCase ( snake_case__ , snake_case__):
return line.startswith(snake_case__) or len(snake_case__) <= 1 or re.search(R"^\s*\)(\s*->.*:|:)\s*$" , snake_case__) is not None
def UpperCamelCase ( snake_case__):
lowerCAmelCase_ : Tuple = object_name.split(".")
lowerCAmelCase_ : Union[str, Any] = 0
# First let's find the module where our object lives.
lowerCAmelCase_ : Union[str, Any] = parts[i]
while i < len(snake_case__) and not os.path.isfile(os.path.join(snake_case__ , F'''{module}.py''')):
i += 1
if i < len(snake_case__):
lowerCAmelCase_ : Dict = os.path.join(snake_case__ , parts[i])
if i >= len(snake_case__):
raise ValueError(F'''`object_name` should begin with the name of a module of diffusers but got {object_name}.''')
with open(os.path.join(snake_case__ , F'''{module}.py''') , "r" , encoding="utf-8" , newline="\n") as f:
lowerCAmelCase_ : Optional[Any] = f.readlines()
# Now let's find the class / func in the code!
lowerCAmelCase_ : Union[str, Any] = ""
lowerCAmelCase_ : int = 0
for name in parts[i + 1 :]:
while (
line_index < len(snake_case__) and re.search(RF'''^{indent}(class|def)\s+{name}(\(|\:)''' , lines[line_index]) is None
):
line_index += 1
indent += " "
line_index += 1
if line_index >= len(snake_case__):
raise ValueError(F''' {object_name} does not match any function or class in {module}.''')
# We found the beginning of the class / func, now let's find the end (when the indent diminishes).
lowerCAmelCase_ : Union[str, Any] = line_index
while line_index < len(snake_case__) and _should_continue(lines[line_index] , snake_case__):
line_index += 1
# Clean up empty lines at the end (if any).
while len(lines[line_index - 1]) <= 1:
line_index -= 1
lowerCAmelCase_ : List[str] = lines[start_index:line_index]
return "".join(snake_case__)
_lowercase = re.compile(r'''^(\s*)#\s*Copied from\s+diffusers\.(\S+\.\S+)\s*($|\S.*$)''')
_lowercase = re.compile(r'''^\s*(\S+)->(\S+)(\s+.*|$)''')
_lowercase = re.compile(r'''<FILL\s+[^>]*>''')
def UpperCamelCase ( snake_case__):
lowerCAmelCase_ : Any = code.split("\n")
lowerCAmelCase_ : Any = 0
while idx < len(snake_case__) and len(lines[idx]) == 0:
idx += 1
if idx < len(snake_case__):
return re.search(R"^(\s*)\S" , lines[idx]).groups()[0]
return ""
def UpperCamelCase ( snake_case__):
lowerCAmelCase_ : Dict = len(get_indent(snake_case__)) > 0
if has_indent:
lowerCAmelCase_ : Dict = F'''class Bla:\n{code}'''
lowerCAmelCase_ : Optional[int] = black.Mode(target_versions={black.TargetVersion.PYaa} , line_length=1_19 , preview=snake_case__)
lowerCAmelCase_ : Optional[Any] = black.format_str(snake_case__ , mode=snake_case__)
lowerCAmelCase_ , lowerCAmelCase_ : List[Any] = style_docstrings_in_code(snake_case__)
return result[len("class Bla:\n") :] if has_indent else result
def UpperCamelCase ( snake_case__ , snake_case__=False):
with open(snake_case__ , "r" , encoding="utf-8" , newline="\n") as f:
lowerCAmelCase_ : Tuple = f.readlines()
lowerCAmelCase_ : Tuple = []
lowerCAmelCase_ : Union[str, Any] = 0
# Not a for loop cause `lines` is going to change (if `overwrite=True`).
while line_index < len(snake_case__):
lowerCAmelCase_ : Optional[int] = _re_copy_warning.search(lines[line_index])
if search is None:
line_index += 1
continue
# There is some copied code here, let's retrieve the original.
lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ : str = search.groups()
lowerCAmelCase_ : int = find_code_in_diffusers(snake_case__)
lowerCAmelCase_ : Dict = get_indent(snake_case__)
lowerCAmelCase_ : Union[str, Any] = line_index + 1 if indent == theoretical_indent else line_index + 2
lowerCAmelCase_ : str = theoretical_indent
lowerCAmelCase_ : Union[str, Any] = start_index
# Loop to check the observed code, stop when indentation diminishes or if we see a End copy comment.
lowerCAmelCase_ : Optional[int] = True
while line_index < len(snake_case__) and should_continue:
line_index += 1
if line_index >= len(snake_case__):
break
lowerCAmelCase_ : Dict = lines[line_index]
lowerCAmelCase_ : List[str] = _should_continue(snake_case__ , snake_case__) and re.search(F'''^{indent}# End copy''' , snake_case__) is None
# Clean up empty lines at the end (if any).
while len(lines[line_index - 1]) <= 1:
line_index -= 1
lowerCAmelCase_ : Dict = lines[start_index:line_index]
lowerCAmelCase_ : Optional[int] = "".join(snake_case__)
# Remove any nested `Copied from` comments to avoid circular copies
lowerCAmelCase_ : List[Any] = [line for line in theoretical_code.split("\n") if _re_copy_warning.search(snake_case__) is None]
lowerCAmelCase_ : Optional[Any] = "\n".join(snake_case__)
# Before comparing, use the `replace_pattern` on the original code.
if len(snake_case__) > 0:
lowerCAmelCase_ : List[str] = replace_pattern.replace("with" , "").split(",")
lowerCAmelCase_ : Tuple = [_re_replace_pattern.search(snake_case__) for p in patterns]
for pattern in patterns:
if pattern is None:
continue
lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ : List[str] = pattern.groups()
lowerCAmelCase_ : int = re.sub(snake_case__ , snake_case__ , snake_case__)
if option.strip() == "all-casing":
lowerCAmelCase_ : List[str] = re.sub(obja.lower() , obja.lower() , snake_case__)
lowerCAmelCase_ : int = re.sub(obja.upper() , obja.upper() , snake_case__)
# Blackify after replacement. To be able to do that, we need the header (class or function definition)
# from the previous line
lowerCAmelCase_ : List[Any] = blackify(lines[start_index - 1] + theoretical_code)
lowerCAmelCase_ : Union[str, Any] = theoretical_code[len(lines[start_index - 1]) :]
# Test for a diff and act accordingly.
if observed_code != theoretical_code:
diffs.append([object_name, start_index])
if overwrite:
lowerCAmelCase_ : List[Any] = lines[:start_index] + [theoretical_code] + lines[line_index:]
lowerCAmelCase_ : Union[str, Any] = start_index + 1
if overwrite and len(snake_case__) > 0:
# Warn the user a file has been modified.
print(F'''Detected changes, rewriting {filename}.''')
with open(snake_case__ , "w" , encoding="utf-8" , newline="\n") as f:
f.writelines(snake_case__)
return diffs
def UpperCamelCase ( snake_case__ = False):
lowerCAmelCase_ : Tuple = glob.glob(os.path.join(snake_case__ , "**/*.py") , recursive=snake_case__)
lowerCAmelCase_ : int = []
for filename in all_files:
lowerCAmelCase_ : Union[str, Any] = is_copy_consistent(snake_case__ , snake_case__)
diffs += [F'''- {filename}: copy does not match {d[0]} at line {d[1]}''' for d in new_diffs]
if not overwrite and len(snake_case__) > 0:
lowerCAmelCase_ : Optional[Any] = "\n".join(snake_case__)
raise Exception(
"Found the following copy inconsistencies:\n"
+ diff
+ "\nRun `make fix-copies` or `python utils/check_copies.py --fix_and_overwrite` to fix them.")
if __name__ == "__main__":
_lowercase = argparse.ArgumentParser()
parser.add_argument('''--fix_and_overwrite''', action='''store_true''', help='''Whether to fix inconsistencies.''')
_lowercase = parser.parse_args()
check_copies(args.fix_and_overwrite)
| 659 | 1 |
# A Bipartite Graph is a graph whose vertices can be divided into two independent sets,
# U and V such that every edge (u, v) either connects a vertex from U to V or a vertex
# from V to U. In other words, for every edge (u, v), either u belongs to U and v to V,
# or u belongs to V and v to U. We can also say that there is no edge that connects
# vertices of same set.
def UpperCamelCase ( snake_case__):
lowerCAmelCase_ : List[str] = [False] * len(snake_case__)
lowerCAmelCase_ : Optional[int] = [-1] * len(snake_case__)
def dfs(snake_case__ , snake_case__):
lowerCAmelCase_ : List[str] = True
lowerCAmelCase_ : List[str] = c
for u in graph[v]:
if not visited[u]:
dfs(snake_case__ , 1 - c)
for i in range(len(snake_case__)):
if not visited[i]:
dfs(snake_case__ , 0)
for i in range(len(snake_case__)):
for j in graph[i]:
if color[i] == color[j]:
return False
return True
# Adjacency list of graph
_lowercase = {0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2], 4: []}
print(check_bipartite_dfs(graph))
| 659 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
_lowercase = logging.get_logger(__name__)
_lowercase = {
'''microsoft/swinv2-tiny-patch4-window8-256''': (
'''https://huggingface.co/microsoft/swinv2-tiny-patch4-window8-256/resolve/main/config.json'''
),
}
class __snake_case ( snake_case__ ):
"""simple docstring"""
UpperCamelCase_ = 'swinv2'
UpperCamelCase_ = {
'num_attention_heads': 'num_heads',
'num_hidden_layers': 'num_layers',
}
def __init__( self : List[Any] ,lowerCAmelCase__ : Optional[int]=2_24 ,lowerCAmelCase__ : Dict=4 ,lowerCAmelCase__ : Dict=3 ,lowerCAmelCase__ : List[Any]=96 ,lowerCAmelCase__ : Optional[Any]=[2, 2, 6, 2] ,lowerCAmelCase__ : Optional[Any]=[3, 6, 12, 24] ,lowerCAmelCase__ : Optional[int]=7 ,lowerCAmelCase__ : Dict=4.0 ,lowerCAmelCase__ : Dict=True ,lowerCAmelCase__ : str=0.0 ,lowerCAmelCase__ : Tuple=0.0 ,lowerCAmelCase__ : str=0.1 ,lowerCAmelCase__ : List[str]="gelu" ,lowerCAmelCase__ : Union[str, Any]=False ,lowerCAmelCase__ : Dict=0.02 ,lowerCAmelCase__ : int=1e-5 ,lowerCAmelCase__ : List[str]=32 ,**lowerCAmelCase__ : Tuple ,) -> List[str]:
'''simple docstring'''
super().__init__(**lowerCAmelCase__ )
lowerCAmelCase_ : Optional[int] = image_size
lowerCAmelCase_ : List[Any] = patch_size
lowerCAmelCase_ : Dict = num_channels
lowerCAmelCase_ : Optional[int] = embed_dim
lowerCAmelCase_ : Optional[Any] = depths
lowerCAmelCase_ : Any = len(lowerCAmelCase__ )
lowerCAmelCase_ : str = num_heads
lowerCAmelCase_ : List[str] = window_size
lowerCAmelCase_ : List[str] = mlp_ratio
lowerCAmelCase_ : Dict = qkv_bias
lowerCAmelCase_ : str = hidden_dropout_prob
lowerCAmelCase_ : str = attention_probs_dropout_prob
lowerCAmelCase_ : Union[str, Any] = drop_path_rate
lowerCAmelCase_ : List[Any] = hidden_act
lowerCAmelCase_ : Any = use_absolute_embeddings
lowerCAmelCase_ : List[str] = layer_norm_eps
lowerCAmelCase_ : int = initializer_range
lowerCAmelCase_ : Union[str, Any] = encoder_stride
# we set the hidden_size attribute in order to make Swinv2 work with VisionEncoderDecoderModel
# this indicates the channel dimension after the last stage of the model
lowerCAmelCase_ : Tuple = int(embed_dim * 2 ** (len(lowerCAmelCase__ ) - 1) )
lowerCAmelCase_ : str = (0, 0, 0, 0)
| 659 | 1 |
from collections.abc import Generator
from math import sin
def UpperCamelCase ( snake_case__):
if len(snake_case__) != 32:
raise ValueError("Input must be of length 32")
lowerCAmelCase_ : Tuple = b""
for i in [3, 2, 1, 0]:
little_endian += string_aa[8 * i : 8 * i + 8]
return little_endian
def UpperCamelCase ( snake_case__):
if i < 0:
raise ValueError("Input must be non-negative")
lowerCAmelCase_ : List[str] = format(snake_case__ , "08x")[-8:]
lowerCAmelCase_ : Any = b""
for i in [3, 2, 1, 0]:
little_endian_hex += hex_rep[2 * i : 2 * i + 2].encode("utf-8")
return little_endian_hex
def UpperCamelCase ( snake_case__):
lowerCAmelCase_ : Union[str, Any] = b""
for char in message:
bit_string += format(snake_case__ , "08b").encode("utf-8")
lowerCAmelCase_ : Optional[int] = format(len(snake_case__) , "064b").encode("utf-8")
# Pad bit_string to a multiple of 512 chars
bit_string += b"1"
while len(snake_case__) % 5_12 != 4_48:
bit_string += b"0"
bit_string += to_little_endian(start_len[32:]) + to_little_endian(start_len[:32])
return bit_string
def UpperCamelCase ( snake_case__):
if len(snake_case__) % 5_12 != 0:
raise ValueError("Input must have length that's a multiple of 512")
for pos in range(0 , len(snake_case__) , 5_12):
lowerCAmelCase_ : List[str] = bit_string[pos : pos + 5_12]
lowerCAmelCase_ : Union[str, Any] = []
for i in range(0 , 5_12 , 32):
block_words.append(int(to_little_endian(block[i : i + 32]) , 2))
yield block_words
def UpperCamelCase ( snake_case__):
if i < 0:
raise ValueError("Input must be non-negative")
lowerCAmelCase_ : Dict = format(snake_case__ , "032b")
lowerCAmelCase_ : str = ""
for c in i_str:
new_str += "1" if c == "0" else "0"
return int(snake_case__ , 2)
def UpperCamelCase ( snake_case__ , snake_case__):
return (a + b) % 2**32
def UpperCamelCase ( snake_case__ , snake_case__):
if i < 0:
raise ValueError("Input must be non-negative")
if shift < 0:
raise ValueError("Shift must be non-negative")
return ((i << shift) ^ (i >> (32 - shift))) % 2**32
def UpperCamelCase ( snake_case__):
lowerCAmelCase_ : Optional[Any] = preprocess(snake_case__)
lowerCAmelCase_ : Optional[Any] = [int(2**32 * abs(sin(i + 1))) for i in range(64)]
# Starting states
lowerCAmelCase_ : List[str] = 0x67_45_23_01
lowerCAmelCase_ : Union[str, Any] = 0xef_cd_ab_89
lowerCAmelCase_ : List[Any] = 0x98_ba_dc_fe
lowerCAmelCase_ : Tuple = 0x10_32_54_76
lowerCAmelCase_ : Any = [
7,
12,
17,
22,
7,
12,
17,
22,
7,
12,
17,
22,
7,
12,
17,
22,
5,
9,
14,
20,
5,
9,
14,
20,
5,
9,
14,
20,
5,
9,
14,
20,
4,
11,
16,
23,
4,
11,
16,
23,
4,
11,
16,
23,
4,
11,
16,
23,
6,
10,
15,
21,
6,
10,
15,
21,
6,
10,
15,
21,
6,
10,
15,
21,
]
# Process bit string in chunks, each with 16 32-char words
for block_words in get_block_words(snake_case__):
lowerCAmelCase_ : Optional[int] = aa
lowerCAmelCase_ : List[str] = ba
lowerCAmelCase_ : Any = ca
lowerCAmelCase_ : Union[str, Any] = da
# Hash current chunk
for i in range(64):
if i <= 15:
# f = (b & c) | (not_32(b) & d) # Alternate definition for f
lowerCAmelCase_ : Any = d ^ (b & (c ^ d))
lowerCAmelCase_ : Dict = i
elif i <= 31:
# f = (d & b) | (not_32(d) & c) # Alternate definition for f
lowerCAmelCase_ : Any = c ^ (d & (b ^ c))
lowerCAmelCase_ : List[str] = (5 * i + 1) % 16
elif i <= 47:
lowerCAmelCase_ : int = b ^ c ^ d
lowerCAmelCase_ : Optional[Any] = (3 * i + 5) % 16
else:
lowerCAmelCase_ : List[Any] = c ^ (b | not_aa(snake_case__))
lowerCAmelCase_ : List[Any] = (7 * i) % 16
lowerCAmelCase_ : Optional[Any] = (f + a + added_consts[i] + block_words[g]) % 2**32
lowerCAmelCase_ : Optional[Any] = d
lowerCAmelCase_ : Dict = c
lowerCAmelCase_ : List[str] = b
lowerCAmelCase_ : Any = sum_aa(snake_case__ , left_rotate_aa(snake_case__ , shift_amounts[i]))
# Add hashed chunk to running total
lowerCAmelCase_ : Dict = sum_aa(snake_case__ , snake_case__)
lowerCAmelCase_ : str = sum_aa(snake_case__ , snake_case__)
lowerCAmelCase_ : Optional[int] = sum_aa(snake_case__ , snake_case__)
lowerCAmelCase_ : int = sum_aa(snake_case__ , snake_case__)
lowerCAmelCase_ : Union[str, Any] = reformat_hex(snake_case__) + reformat_hex(snake_case__) + reformat_hex(snake_case__) + reformat_hex(snake_case__)
return digest
if __name__ == "__main__":
import doctest
doctest.testmod()
| 659 |
from typing import List, Optional, Union
import numpy as np
from ....audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function
from ....feature_extraction_sequence_utils import SequenceFeatureExtractor
from ....feature_extraction_utils import BatchFeature
from ....file_utils import PaddingStrategy, TensorType
from ....utils import logging
_lowercase = logging.get_logger(__name__)
class __snake_case ( snake_case__ ):
"""simple docstring"""
UpperCamelCase_ = ['input_features', 'attention_mask']
def __init__( self : Optional[Any] ,lowerCAmelCase__ : Any=80 ,lowerCAmelCase__ : Optional[Any]=1_60_00 ,lowerCAmelCase__ : List[str]=0.0 ,lowerCAmelCase__ : Tuple=10 ,lowerCAmelCase__ : Optional[Any]=25 ,lowerCAmelCase__ : Any="hamming_window" ,lowerCAmelCase__ : List[str]=32_768.0 ,lowerCAmelCase__ : Union[str, Any]=0.97 ,lowerCAmelCase__ : Any=1.0 ,lowerCAmelCase__ : str=True ,lowerCAmelCase__ : int=True ,lowerCAmelCase__ : Tuple=False ,**lowerCAmelCase__ : Optional[int] ,) -> Optional[Any]:
'''simple docstring'''
super().__init__(feature_size=lowerCAmelCase__ ,sampling_rate=lowerCAmelCase__ ,padding_value=lowerCAmelCase__ ,**lowerCAmelCase__ )
lowerCAmelCase_ : Optional[int] = feature_size
lowerCAmelCase_ : List[Any] = sampling_rate
lowerCAmelCase_ : Union[str, Any] = padding_value
lowerCAmelCase_ : str = hop_length
lowerCAmelCase_ : str = win_length
lowerCAmelCase_ : str = frame_signal_scale
lowerCAmelCase_ : Any = preemphasis_coeff
lowerCAmelCase_ : Optional[Any] = mel_floor
lowerCAmelCase_ : List[str] = normalize_means
lowerCAmelCase_ : Optional[Any] = normalize_vars
lowerCAmelCase_ : Dict = win_function
lowerCAmelCase_ : List[Any] = return_attention_mask
lowerCAmelCase_ : Tuple = win_length * sampling_rate // 10_00
lowerCAmelCase_ : str = hop_length * sampling_rate // 10_00
lowerCAmelCase_ : Dict = optimal_fft_length(self.sample_size )
lowerCAmelCase_ : Optional[int] = (self.n_fft // 2) + 1
def UpperCAmelCase_ ( self : List[Any] ,lowerCAmelCase__ : np.array ) -> np.ndarray:
'''simple docstring'''
if self.win_function == "hamming_window":
lowerCAmelCase_ : int = window_function(window_length=self.sample_size ,name=self.win_function ,periodic=lowerCAmelCase__ )
else:
lowerCAmelCase_ : Tuple = window_function(window_length=self.sample_size ,name=self.win_function )
lowerCAmelCase_ : List[str] = mel_filter_bank(
num_frequency_bins=self.n_freqs ,num_mel_filters=self.feature_size ,min_frequency=0.0 ,max_frequency=self.sampling_rate / 2.0 ,sampling_rate=self.sampling_rate ,)
lowerCAmelCase_ : Any = spectrogram(
one_waveform * self.frame_signal_scale ,window=lowerCAmelCase__ ,frame_length=self.sample_size ,hop_length=self.sample_stride ,fft_length=self.n_fft ,center=lowerCAmelCase__ ,preemphasis=self.preemphasis_coeff ,mel_filters=lowerCAmelCase__ ,mel_floor=self.mel_floor ,log_mel="log" ,)
return msfc_features.T
def UpperCAmelCase_ ( self : int ,lowerCAmelCase__ : List[Any] ,lowerCAmelCase__ : Optional[Any] ,lowerCAmelCase__ : Tuple ) -> Optional[Any]:
'''simple docstring'''
if self.normalize_means:
lowerCAmelCase_ : Optional[int] = x[:input_length].mean(axis=0 )
lowerCAmelCase_ : List[str] = np.subtract(lowerCAmelCase__ ,lowerCAmelCase__ )
if self.normalize_vars:
lowerCAmelCase_ : Optional[Any] = x[:input_length].std(axis=0 )
lowerCAmelCase_ : Tuple = np.divide(lowerCAmelCase__ ,lowerCAmelCase__ )
if input_length < x.shape[0]:
lowerCAmelCase_ : int = padding_value
# make sure array is in float32
lowerCAmelCase_ : Any = x.astype(np.floataa )
return x
def UpperCAmelCase_ ( self : List[Any] ,lowerCAmelCase__ : List[np.ndarray] ,lowerCAmelCase__ : Optional[np.ndarray] = None ) -> List[np.ndarray]:
'''simple docstring'''
lowerCAmelCase_ : List[Any] = attention_mask.sum(-1 ) if attention_mask is not None else [x.shape[0] for x in input_features]
return [self._normalize_one(lowerCAmelCase__ ,lowerCAmelCase__ ,self.padding_value ) for x, n in zip(lowerCAmelCase__ ,lowerCAmelCase__ )]
def __call__( self : int ,lowerCAmelCase__ : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] ,lowerCAmelCase__ : Union[bool, str, PaddingStrategy] = False ,lowerCAmelCase__ : Optional[int] = None ,lowerCAmelCase__ : bool = False ,lowerCAmelCase__ : Optional[int] = None ,lowerCAmelCase__ : Optional[bool] = None ,lowerCAmelCase__ : Optional[Union[str, TensorType]] = None ,lowerCAmelCase__ : Optional[int] = None ,**lowerCAmelCase__ : Union[str, Any] ,) -> BatchFeature:
'''simple docstring'''
if sampling_rate is not None:
if sampling_rate != self.sampling_rate:
raise ValueError(
f'''The model corresponding to this feature extractor: {self} was trained using a sampling rate of'''
f''' {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with'''
f''' {self.sampling_rate} and not {sampling_rate}.''' )
else:
logger.warning(
"It is strongly recommended to pass the ``sampling_rate`` argument to this function. "
"Failing to do so can result in silent errors that might be hard to debug." )
lowerCAmelCase_ : List[Any] = isinstance(lowerCAmelCase__ ,np.ndarray ) and len(raw_speech.shape ) > 1
if is_batched_numpy and len(raw_speech.shape ) > 2:
raise ValueError(f'''Only mono-channel audio is supported for input to {self}''' )
lowerCAmelCase_ : str = is_batched_numpy or (
isinstance(lowerCAmelCase__ ,(list, tuple) ) and (isinstance(raw_speech[0] ,(np.ndarray, tuple, list) ))
)
if is_batched:
lowerCAmelCase_ : Tuple = [np.asarray(lowerCAmelCase__ ,dtype=np.floataa ) for speech in raw_speech]
elif not is_batched and not isinstance(lowerCAmelCase__ ,np.ndarray ):
lowerCAmelCase_ : int = np.asarray(lowerCAmelCase__ ,dtype=np.floataa )
elif isinstance(lowerCAmelCase__ ,np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ):
lowerCAmelCase_ : Union[str, Any] = raw_speech.astype(np.floataa )
# always return batch
if not is_batched:
lowerCAmelCase_ : Optional[int] = [raw_speech]
# extract fbank features
lowerCAmelCase_ : Dict = [self._extract_mfsc_features(lowerCAmelCase__ ) for one_waveform in raw_speech]
# convert into correct format for padding
lowerCAmelCase_ : int = BatchFeature({"input_features": features} )
lowerCAmelCase_ : Union[str, Any] = self.pad(
lowerCAmelCase__ ,padding=lowerCAmelCase__ ,max_length=lowerCAmelCase__ ,truncation=lowerCAmelCase__ ,pad_to_multiple_of=lowerCAmelCase__ ,return_attention_mask=lowerCAmelCase__ ,**lowerCAmelCase__ ,)
# make sure list is in array format
lowerCAmelCase_ : Optional[Any] = padded_inputs.get("input_features" )
if isinstance(input_features[0] ,lowerCAmelCase__ ):
lowerCAmelCase_ : Optional[int] = [np.asarray(lowerCAmelCase__ ,dtype=np.floataa ) for feature in input_features]
lowerCAmelCase_ : List[Any] = padded_inputs.get("attention_mask" )
if attention_mask is not None:
lowerCAmelCase_ : Dict = [np.asarray(lowerCAmelCase__ ,dtype=np.intaa ) for array in attention_mask]
if self.normalize_means or self.normalize_vars:
lowerCAmelCase_ : Dict = (
np.array(lowerCAmelCase__ ,dtype=np.intaa )
if self._get_padding_strategies(lowerCAmelCase__ ,max_length=lowerCAmelCase__ ) is not PaddingStrategy.DO_NOT_PAD
and padding
else None
)
lowerCAmelCase_ : List[str] = self.normalize(
padded_inputs["input_features"] ,attention_mask=lowerCAmelCase__ )
if return_tensors is not None:
lowerCAmelCase_ : Dict = padded_inputs.convert_to_tensors(lowerCAmelCase__ )
return padded_inputs
| 659 | 1 |
import sys
from typing import Tuple
import numpy as np
import torch
from PIL import Image
from torch import nn
from transformers.image_utils import PILImageResampling
from utils import img_tensorize
class __snake_case :
"""simple docstring"""
def __init__( self : List[str] ,lowerCAmelCase__ : List[str] ,lowerCAmelCase__ : Optional[int]=sys.maxsize ) -> List[Any]:
'''simple docstring'''
lowerCAmelCase_ : int = "bilinear"
lowerCAmelCase_ : str = max_size
lowerCAmelCase_ : Any = short_edge_length
def __call__( self : Union[str, Any] ,lowerCAmelCase__ : Tuple ) -> Any:
'''simple docstring'''
lowerCAmelCase_ : List[str] = []
for img in imgs:
lowerCAmelCase_ , lowerCAmelCase_ : str = img.shape[:2]
# later: provide list and randomly choose index for resize
lowerCAmelCase_ : Any = np.random.randint(self.short_edge_length[0] ,self.short_edge_length[1] + 1 )
if size == 0:
return img
lowerCAmelCase_ : List[Any] = size * 1.0 / min(lowerCAmelCase__ ,lowerCAmelCase__ )
if h < w:
lowerCAmelCase_ , lowerCAmelCase_ : List[str] = size, scale * w
else:
lowerCAmelCase_ , lowerCAmelCase_ : Optional[int] = scale * h, size
if max(lowerCAmelCase__ ,lowerCAmelCase__ ) > self.max_size:
lowerCAmelCase_ : Optional[Any] = self.max_size * 1.0 / max(lowerCAmelCase__ ,lowerCAmelCase__ )
lowerCAmelCase_ : str = newh * scale
lowerCAmelCase_ : Tuple = neww * scale
lowerCAmelCase_ : Dict = int(neww + 0.5 )
lowerCAmelCase_ : Any = int(newh + 0.5 )
if img.dtype == np.uinta:
lowerCAmelCase_ : Optional[int] = Image.fromarray(lowerCAmelCase__ )
lowerCAmelCase_ : Tuple = pil_image.resize((neww, newh) ,PILImageResampling.BILINEAR )
lowerCAmelCase_ : int = np.asarray(lowerCAmelCase__ )
else:
lowerCAmelCase_ : Tuple = img.permute(2 ,0 ,1 ).unsqueeze(0 ) # 3, 0, 1) # hw(c) -> nchw
lowerCAmelCase_ : Union[str, Any] = nn.functional.interpolate(
lowerCAmelCase__ ,(newh, neww) ,mode=self.interp_method ,align_corners=lowerCAmelCase__ ).squeeze(0 )
img_augs.append(lowerCAmelCase__ )
return img_augs
class __snake_case :
"""simple docstring"""
def __init__( self : Dict ,lowerCAmelCase__ : str ) -> Dict:
'''simple docstring'''
lowerCAmelCase_ : Optional[Any] = ResizeShortestEdge([cfg.INPUT.MIN_SIZE_TEST, cfg.INPUT.MIN_SIZE_TEST] ,cfg.INPUT.MAX_SIZE_TEST )
lowerCAmelCase_ : Union[str, Any] = cfg.INPUT.FORMAT
lowerCAmelCase_ : Dict = cfg.SIZE_DIVISIBILITY
lowerCAmelCase_ : List[Any] = cfg.PAD_VALUE
lowerCAmelCase_ : str = cfg.INPUT.MAX_SIZE_TEST
lowerCAmelCase_ : Any = cfg.MODEL.DEVICE
lowerCAmelCase_ : Tuple = torch.tensor(cfg.MODEL.PIXEL_STD ).to(self.device ).view(len(cfg.MODEL.PIXEL_STD ) ,1 ,1 )
lowerCAmelCase_ : int = torch.tensor(cfg.MODEL.PIXEL_MEAN ).to(self.device ).view(len(cfg.MODEL.PIXEL_STD ) ,1 ,1 )
lowerCAmelCase_ : List[str] = lambda lowerCAmelCase__ : (x - self.pixel_mean) / self.pixel_std
def UpperCAmelCase_ ( self : int ,lowerCAmelCase__ : Tuple ) -> List[str]:
'''simple docstring'''
lowerCAmelCase_ : str = tuple(max(lowerCAmelCase__ ) for s in zip(*[img.shape for img in images] ) )
lowerCAmelCase_ : Optional[int] = [im.shape[-2:] for im in images]
lowerCAmelCase_ : Dict = [
nn.functional.pad(
lowerCAmelCase__ ,[0, max_size[-1] - size[1], 0, max_size[-2] - size[0]] ,value=self.pad_value ,)
for size, im in zip(lowerCAmelCase__ ,lowerCAmelCase__ )
]
return torch.stack(lowerCAmelCase__ ), torch.tensor(lowerCAmelCase__ )
def __call__( self : Union[str, Any] ,lowerCAmelCase__ : List[str] ,lowerCAmelCase__ : str=False ) -> Any:
'''simple docstring'''
with torch.no_grad():
if not isinstance(lowerCAmelCase__ ,lowerCAmelCase__ ):
lowerCAmelCase_ : Optional[int] = [images]
if single_image:
assert len(lowerCAmelCase__ ) == 1
for i in range(len(lowerCAmelCase__ ) ):
if isinstance(images[i] ,torch.Tensor ):
images.insert(lowerCAmelCase__ ,images.pop(lowerCAmelCase__ ).to(self.device ).float() )
elif not isinstance(images[i] ,torch.Tensor ):
images.insert(
lowerCAmelCase__ ,torch.as_tensor(img_tensorize(images.pop(lowerCAmelCase__ ) ,input_format=self.input_format ) )
.to(self.device )
.float() ,)
# resize smallest edge
lowerCAmelCase_ : Tuple = torch.tensor([im.shape[:2] for im in images] )
lowerCAmelCase_ : List[Any] = self.aug(lowerCAmelCase__ )
# transpose images and convert to torch tensors
# images = [torch.as_tensor(i.astype("float32")).permute(2, 0, 1).to(self.device) for i in images]
# now normalize before pad to avoid useless arithmetic
lowerCAmelCase_ : Any = [self.normalizer(lowerCAmelCase__ ) for x in images]
# now pad them to do the following operations
lowerCAmelCase_ , lowerCAmelCase_ : Union[str, Any] = self.pad(lowerCAmelCase__ )
# Normalize
if self.size_divisibility > 0:
raise NotImplementedError()
# pad
lowerCAmelCase_ : Optional[int] = torch.true_divide(lowerCAmelCase__ ,lowerCAmelCase__ )
if single_image:
return images[0], sizes[0], scales_yx[0]
else:
return images, sizes, scales_yx
def UpperCamelCase ( snake_case__ , snake_case__):
boxes[:, 0::2] *= scale_yx[:, 1]
boxes[:, 1::2] *= scale_yx[:, 0]
return boxes
def UpperCamelCase ( snake_case__ , snake_case__):
assert torch.isfinite(snake_case__).all(), "Box tensor contains infinite or NaN!"
lowerCAmelCase_ , lowerCAmelCase_ : List[str] = box_size
tensor[:, 0].clamp_(min=0 , max=snake_case__)
tensor[:, 1].clamp_(min=0 , max=snake_case__)
tensor[:, 2].clamp_(min=0 , max=snake_case__)
tensor[:, 3].clamp_(min=0 , max=snake_case__)
| 659 |
from __future__ import annotations
# This is the precision for this function which can be altered.
# It is recommended for users to keep this number greater than or equal to 10.
_lowercase = 10
def UpperCamelCase ( snake_case__ , snake_case__ , snake_case__ , snake_case__):
for i in range(snake_case__ , snake_case__):
if array[i] == target:
return i
return -1
def UpperCamelCase ( snake_case__ , snake_case__):
lowerCAmelCase_ : List[str] = 0
lowerCAmelCase_ : Tuple = len(snake_case__)
while left <= right:
if right - left < precision:
return lin_search(snake_case__ , snake_case__ , snake_case__ , snake_case__)
lowerCAmelCase_ : List[str] = (left + right) // 3 + 1
lowerCAmelCase_ : Tuple = 2 * (left + right) // 3 + 1
if array[one_third] == target:
return one_third
elif array[two_third] == target:
return two_third
elif target < array[one_third]:
lowerCAmelCase_ : str = one_third - 1
elif array[two_third] < target:
lowerCAmelCase_ : Any = two_third + 1
else:
lowerCAmelCase_ : List[str] = one_third + 1
lowerCAmelCase_ : Tuple = two_third - 1
else:
return -1
def UpperCamelCase ( snake_case__ , snake_case__ , snake_case__ , snake_case__):
if left < right:
if right - left < precision:
return lin_search(snake_case__ , snake_case__ , snake_case__ , snake_case__)
lowerCAmelCase_ : Dict = (left + right) // 3 + 1
lowerCAmelCase_ : List[Any] = 2 * (left + right) // 3 + 1
if array[one_third] == target:
return one_third
elif array[two_third] == target:
return two_third
elif target < array[one_third]:
return rec_ternary_search(snake_case__ , one_third - 1 , snake_case__ , snake_case__)
elif array[two_third] < target:
return rec_ternary_search(two_third + 1 , snake_case__ , snake_case__ , snake_case__)
else:
return rec_ternary_search(one_third + 1 , two_third - 1 , snake_case__ , snake_case__)
else:
return -1
if __name__ == "__main__":
import doctest
doctest.testmod()
_lowercase = input('''Enter numbers separated by comma:\n''').strip()
_lowercase = [int(item.strip()) for item in user_input.split(''',''')]
assert collection == sorted(collection), f"List must be ordered.\n{collection}."
_lowercase = int(input('''Enter the number to be found in the list:\n''').strip())
_lowercase = ite_ternary_search(collection, target)
_lowercase = rec_ternary_search(0, len(collection) - 1, collection, target)
if resulta != -1:
print(f"Iterative search: {target} found at positions: {resulta}")
print(f"Recursive search: {target} found at positions: {resulta}")
else:
print('''Not found''')
| 659 | 1 |
import argparse
import json
from dataclasses import dataclass, field
from functools import partial
from pathlib import Path
from typing import List
import timm
import torch
import torch.nn as nn
from huggingface_hub import hf_hub_download
from torch import Tensor
from transformers import AutoImageProcessor, ResNetConfig, ResNetForImageClassification
from transformers.utils import logging
logging.set_verbosity_info()
_lowercase = logging.get_logger()
@dataclass
class __snake_case :
"""simple docstring"""
UpperCamelCase_ = 42
UpperCamelCase_ = field(default_factory=snake_case__ )
UpperCamelCase_ = field(default_factory=snake_case__ )
def UpperCAmelCase_ ( self : List[str] ,lowerCAmelCase__ : Tuple ,lowerCAmelCase__ : Tensor ,lowerCAmelCase__ : Tensor ) -> str:
'''simple docstring'''
lowerCAmelCase_ : Dict = len(list(m.modules() ) ) == 1 or isinstance(lowerCAmelCase__ ,nn.Convad ) or isinstance(lowerCAmelCase__ ,nn.BatchNormad )
if has_not_submodules:
self.traced.append(lowerCAmelCase__ )
def __call__( self : List[str] ,lowerCAmelCase__ : Tensor ) -> List[Any]:
'''simple docstring'''
for m in self.module.modules():
self.handles.append(m.register_forward_hook(self._forward_hook ) )
self.module(lowerCAmelCase__ )
[x.remove() for x in self.handles]
return self
@property
def UpperCAmelCase_ ( self : Union[str, Any] ) -> Union[str, Any]:
'''simple docstring'''
return list(filter(lambda lowerCAmelCase__ : len(list(x.state_dict().keys() ) ) > 0 ,self.traced ) )
@dataclass
class __snake_case :
"""simple docstring"""
UpperCamelCase_ = 42
UpperCamelCase_ = 42
UpperCamelCase_ = 0
UpperCamelCase_ = field(default_factory=snake_case__ )
UpperCamelCase_ = field(default_factory=snake_case__ )
def __call__( self : List[str] ,lowerCAmelCase__ : Tensor ) -> Union[str, Any]:
'''simple docstring'''
lowerCAmelCase_ : Dict = Tracker(self.dest )(lowerCAmelCase__ ).parametrized
lowerCAmelCase_ : int = Tracker(self.src )(lowerCAmelCase__ ).parametrized
lowerCAmelCase_ : Union[str, Any] = list(filter(lambda lowerCAmelCase__ : type(lowerCAmelCase__ ) not in self.src_skip ,lowerCAmelCase__ ) )
lowerCAmelCase_ : Optional[int] = list(filter(lambda lowerCAmelCase__ : type(lowerCAmelCase__ ) not in self.dest_skip ,lowerCAmelCase__ ) )
if len(lowerCAmelCase__ ) != len(lowerCAmelCase__ ):
raise Exception(
f'''Numbers of operations are different. Source module has {len(lowerCAmelCase__ )} operations while'''
f''' destination module has {len(lowerCAmelCase__ )}.''' )
for dest_m, src_m in zip(lowerCAmelCase__ ,lowerCAmelCase__ ):
dest_m.load_state_dict(src_m.state_dict() )
if self.verbose == 1:
print(f'''Transfered from={src_m} to={dest_m}''' )
def UpperCamelCase ( snake_case__ , snake_case__ , snake_case__ , snake_case__ = True):
print(F'''Converting {name}...''')
with torch.no_grad():
lowerCAmelCase_ : Optional[int] = timm.create_model(snake_case__ , pretrained=snake_case__).eval()
lowerCAmelCase_ : Any = ResNetForImageClassification(snake_case__).eval()
lowerCAmelCase_ : List[Any] = ModuleTransfer(src=snake_case__ , dest=snake_case__)
lowerCAmelCase_ : str = torch.randn((1, 3, 2_24, 2_24))
module_transfer(snake_case__)
assert torch.allclose(from_model(snake_case__) , our_model(snake_case__).logits), "The model logits don't match the original one."
lowerCAmelCase_ : Dict = F'''resnet{"-".join(name.split("resnet"))}'''
print(snake_case__)
if push_to_hub:
our_model.push_to_hub(
repo_path_or_name=save_directory / checkpoint_name , commit_message="Add model" , use_temp_dir=snake_case__ , )
# we can use the convnext one
lowerCAmelCase_ : Dict = AutoImageProcessor.from_pretrained("facebook/convnext-base-224-22k-1k")
image_processor.push_to_hub(
repo_path_or_name=save_directory / checkpoint_name , commit_message="Add image processor" , use_temp_dir=snake_case__ , )
print(F'''Pushed {checkpoint_name}''')
def UpperCamelCase ( snake_case__ , snake_case__ = None , snake_case__ = True):
lowerCAmelCase_ : Tuple = "imagenet-1k-id2label.json"
lowerCAmelCase_ : Dict = 10_00
lowerCAmelCase_ : Tuple = (1, num_labels)
lowerCAmelCase_ : List[Any] = "huggingface/label-files"
lowerCAmelCase_ : Optional[Any] = num_labels
lowerCAmelCase_ : Any = json.load(open(hf_hub_download(snake_case__ , snake_case__ , repo_type="dataset") , "r"))
lowerCAmelCase_ : Optional[int] = {int(snake_case__): v for k, v in idalabel.items()}
lowerCAmelCase_ : List[str] = idalabel
lowerCAmelCase_ : List[str] = {v: k for k, v in idalabel.items()}
lowerCAmelCase_ : Tuple = partial(snake_case__ , num_labels=snake_case__ , idalabel=snake_case__ , labelaid=snake_case__)
lowerCAmelCase_ : Optional[int] = {
"resnet18": ImageNetPreTrainedConfig(
depths=[2, 2, 2, 2] , hidden_sizes=[64, 1_28, 2_56, 5_12] , layer_type="basic"),
"resnet26": ImageNetPreTrainedConfig(
depths=[2, 2, 2, 2] , hidden_sizes=[2_56, 5_12, 10_24, 20_48] , layer_type="bottleneck"),
"resnet34": ImageNetPreTrainedConfig(
depths=[3, 4, 6, 3] , hidden_sizes=[64, 1_28, 2_56, 5_12] , layer_type="basic"),
"resnet50": ImageNetPreTrainedConfig(
depths=[3, 4, 6, 3] , hidden_sizes=[2_56, 5_12, 10_24, 20_48] , layer_type="bottleneck"),
"resnet101": ImageNetPreTrainedConfig(
depths=[3, 4, 23, 3] , hidden_sizes=[2_56, 5_12, 10_24, 20_48] , layer_type="bottleneck"),
"resnet152": ImageNetPreTrainedConfig(
depths=[3, 8, 36, 3] , hidden_sizes=[2_56, 5_12, 10_24, 20_48] , layer_type="bottleneck"),
}
if model_name:
convert_weight_and_push(snake_case__ , names_to_config[model_name] , snake_case__ , snake_case__)
else:
for model_name, config in names_to_config.items():
convert_weight_and_push(snake_case__ , snake_case__ , snake_case__ , snake_case__)
return config, expected_shape
if __name__ == "__main__":
_lowercase = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'''--model_name''',
default=None,
type=str,
help=(
'''The name of the model you wish to convert, it must be one of the supported resnet* architecture,'''
''' currently: resnet18,26,34,50,101,152. If `None`, all of them will the converted.'''
),
)
parser.add_argument(
'''--pytorch_dump_folder_path''',
default=None,
type=Path,
required=True,
help='''Path to the output PyTorch model directory.''',
)
parser.add_argument(
'''--push_to_hub''',
default=True,
type=bool,
required=False,
help='''If True, push model and image processor to the hub.''',
)
_lowercase = parser.parse_args()
_lowercase = args.pytorch_dump_folder_path
pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True)
convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
| 659 |
from typing import List, Optional
from tokenizers import ByteLevelBPETokenizer
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_blenderbot_small import BlenderbotSmallTokenizer
_lowercase = logging.get_logger(__name__)
_lowercase = {
'''vocab_file''': '''vocab.json''',
'''merges_file''': '''merges.txt''',
'''tokenizer_config_file''': '''tokenizer_config.json''',
}
_lowercase = {
'''vocab_file''': {
'''facebook/blenderbot_small-90M''': '''https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/vocab.json'''
},
'''merges_file''': {
'''facebook/blenderbot_small-90M''': '''https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/merges.txt'''
},
'''tokenizer_config_file''': {
'''facebook/blenderbot_small-90M''': (
'''https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/tokenizer_config.json'''
)
},
}
_lowercase = {
'''facebook/blenderbot_small-90M''': 512,
}
class __snake_case ( snake_case__ ):
"""simple docstring"""
UpperCamelCase_ = VOCAB_FILES_NAMES
UpperCamelCase_ = PRETRAINED_VOCAB_FILES_MAP
UpperCamelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
UpperCamelCase_ = BlenderbotSmallTokenizer
def __init__( self : Optional[int] ,lowerCAmelCase__ : Optional[int]=None ,lowerCAmelCase__ : Union[str, Any]=None ,lowerCAmelCase__ : Any="<|endoftext|>" ,lowerCAmelCase__ : int="<|endoftext|>" ,lowerCAmelCase__ : Optional[Any]="<|endoftext|>" ,lowerCAmelCase__ : Union[str, Any]=False ,lowerCAmelCase__ : Optional[Any]=True ,**lowerCAmelCase__ : Union[str, Any] ,) -> str:
'''simple docstring'''
super().__init__(
ByteLevelBPETokenizer(
vocab=lowerCAmelCase__ ,merges=lowerCAmelCase__ ,add_prefix_space=lowerCAmelCase__ ,trim_offsets=lowerCAmelCase__ ,) ,bos_token=lowerCAmelCase__ ,eos_token=lowerCAmelCase__ ,unk_token=lowerCAmelCase__ ,**lowerCAmelCase__ ,)
lowerCAmelCase_ : Dict = add_prefix_space
def UpperCAmelCase_ ( self : int ,lowerCAmelCase__ : List[str] ,lowerCAmelCase__ : Tuple=None ) -> Optional[int]:
'''simple docstring'''
lowerCAmelCase_ : str = [self.bos_token_id] + token_ids_a + [self.eos_token_id]
if token_ids_a is None:
return output
return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id]
def UpperCAmelCase_ ( self : int ,lowerCAmelCase__ : List[int] ,lowerCAmelCase__ : Optional[List[int]] = None ) -> List[int]:
'''simple docstring'''
lowerCAmelCase_ : Dict = [self.sep_token_id]
lowerCAmelCase_ : Optional[Any] = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
| 659 | 1 |
def UpperCamelCase ( snake_case__ = 4_00_00_00):
lowerCAmelCase_ : str = [0, 1]
lowerCAmelCase_ : Optional[int] = 0
while fib[i] <= n:
fib.append(fib[i] + fib[i + 1])
if fib[i + 2] > n:
break
i += 1
lowerCAmelCase_ : Any = 0
for j in range(len(snake_case__) - 1):
if fib[j] % 2 == 0:
total += fib[j]
return total
if __name__ == "__main__":
print(f"{solution() = }")
| 659 |
from collections.abc import Generator
from math import sin
def UpperCamelCase ( snake_case__):
if len(snake_case__) != 32:
raise ValueError("Input must be of length 32")
lowerCAmelCase_ : Tuple = b""
for i in [3, 2, 1, 0]:
little_endian += string_aa[8 * i : 8 * i + 8]
return little_endian
def UpperCamelCase ( snake_case__):
if i < 0:
raise ValueError("Input must be non-negative")
lowerCAmelCase_ : List[str] = format(snake_case__ , "08x")[-8:]
lowerCAmelCase_ : Any = b""
for i in [3, 2, 1, 0]:
little_endian_hex += hex_rep[2 * i : 2 * i + 2].encode("utf-8")
return little_endian_hex
def UpperCamelCase ( snake_case__):
lowerCAmelCase_ : Union[str, Any] = b""
for char in message:
bit_string += format(snake_case__ , "08b").encode("utf-8")
lowerCAmelCase_ : Optional[int] = format(len(snake_case__) , "064b").encode("utf-8")
# Pad bit_string to a multiple of 512 chars
bit_string += b"1"
while len(snake_case__) % 5_12 != 4_48:
bit_string += b"0"
bit_string += to_little_endian(start_len[32:]) + to_little_endian(start_len[:32])
return bit_string
def UpperCamelCase ( snake_case__):
if len(snake_case__) % 5_12 != 0:
raise ValueError("Input must have length that's a multiple of 512")
for pos in range(0 , len(snake_case__) , 5_12):
lowerCAmelCase_ : List[str] = bit_string[pos : pos + 5_12]
lowerCAmelCase_ : Union[str, Any] = []
for i in range(0 , 5_12 , 32):
block_words.append(int(to_little_endian(block[i : i + 32]) , 2))
yield block_words
def UpperCamelCase ( snake_case__):
if i < 0:
raise ValueError("Input must be non-negative")
lowerCAmelCase_ : Dict = format(snake_case__ , "032b")
lowerCAmelCase_ : str = ""
for c in i_str:
new_str += "1" if c == "0" else "0"
return int(snake_case__ , 2)
def UpperCamelCase ( snake_case__ , snake_case__):
return (a + b) % 2**32
def UpperCamelCase ( snake_case__ , snake_case__):
if i < 0:
raise ValueError("Input must be non-negative")
if shift < 0:
raise ValueError("Shift must be non-negative")
return ((i << shift) ^ (i >> (32 - shift))) % 2**32
def UpperCamelCase ( snake_case__):
lowerCAmelCase_ : Optional[Any] = preprocess(snake_case__)
lowerCAmelCase_ : Optional[Any] = [int(2**32 * abs(sin(i + 1))) for i in range(64)]
# Starting states
lowerCAmelCase_ : List[str] = 0x67_45_23_01
lowerCAmelCase_ : Union[str, Any] = 0xef_cd_ab_89
lowerCAmelCase_ : List[Any] = 0x98_ba_dc_fe
lowerCAmelCase_ : Tuple = 0x10_32_54_76
lowerCAmelCase_ : Any = [
7,
12,
17,
22,
7,
12,
17,
22,
7,
12,
17,
22,
7,
12,
17,
22,
5,
9,
14,
20,
5,
9,
14,
20,
5,
9,
14,
20,
5,
9,
14,
20,
4,
11,
16,
23,
4,
11,
16,
23,
4,
11,
16,
23,
4,
11,
16,
23,
6,
10,
15,
21,
6,
10,
15,
21,
6,
10,
15,
21,
6,
10,
15,
21,
]
# Process bit string in chunks, each with 16 32-char words
for block_words in get_block_words(snake_case__):
lowerCAmelCase_ : Optional[int] = aa
lowerCAmelCase_ : List[str] = ba
lowerCAmelCase_ : Any = ca
lowerCAmelCase_ : Union[str, Any] = da
# Hash current chunk
for i in range(64):
if i <= 15:
# f = (b & c) | (not_32(b) & d) # Alternate definition for f
lowerCAmelCase_ : Any = d ^ (b & (c ^ d))
lowerCAmelCase_ : Dict = i
elif i <= 31:
# f = (d & b) | (not_32(d) & c) # Alternate definition for f
lowerCAmelCase_ : Any = c ^ (d & (b ^ c))
lowerCAmelCase_ : List[str] = (5 * i + 1) % 16
elif i <= 47:
lowerCAmelCase_ : int = b ^ c ^ d
lowerCAmelCase_ : Optional[Any] = (3 * i + 5) % 16
else:
lowerCAmelCase_ : List[Any] = c ^ (b | not_aa(snake_case__))
lowerCAmelCase_ : List[Any] = (7 * i) % 16
lowerCAmelCase_ : Optional[Any] = (f + a + added_consts[i] + block_words[g]) % 2**32
lowerCAmelCase_ : Optional[Any] = d
lowerCAmelCase_ : Dict = c
lowerCAmelCase_ : List[str] = b
lowerCAmelCase_ : Any = sum_aa(snake_case__ , left_rotate_aa(snake_case__ , shift_amounts[i]))
# Add hashed chunk to running total
lowerCAmelCase_ : Dict = sum_aa(snake_case__ , snake_case__)
lowerCAmelCase_ : str = sum_aa(snake_case__ , snake_case__)
lowerCAmelCase_ : Optional[int] = sum_aa(snake_case__ , snake_case__)
lowerCAmelCase_ : int = sum_aa(snake_case__ , snake_case__)
lowerCAmelCase_ : Union[str, Any] = reformat_hex(snake_case__) + reformat_hex(snake_case__) + reformat_hex(snake_case__) + reformat_hex(snake_case__)
return digest
if __name__ == "__main__":
import doctest
doctest.testmod()
| 659 | 1 |
from __future__ import annotations
from typing import Any
def UpperCamelCase ( snake_case__):
create_state_space_tree(snake_case__ , [] , 0)
def UpperCamelCase ( snake_case__ , snake_case__ , snake_case__):
if index == len(snake_case__):
print(snake_case__)
return
create_state_space_tree(snake_case__ , snake_case__ , index + 1)
current_subsequence.append(sequence[index])
create_state_space_tree(snake_case__ , snake_case__ , index + 1)
current_subsequence.pop()
if __name__ == "__main__":
_lowercase = [3, 1, 2, 4]
generate_all_subsequences(seq)
seq.clear()
seq.extend(['''A''', '''B''', '''C'''])
generate_all_subsequences(seq)
| 659 |
import logging
import sys
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Union
import librosa
import torch
from datasets import DatasetDict, load_dataset
from packaging import version
from torch import nn
from transformers import (
HfArgumentParser,
Trainer,
TrainingArguments,
WavaVecaConfig,
WavaVecaFeatureExtractor,
WavaVecaForPreTraining,
is_apex_available,
trainer_utils,
)
from transformers.models.wavaveca.modeling_wavaveca import _compute_mask_indices
if is_apex_available():
from apex import amp
if version.parse(version.parse(torch.__version__).base_version) >= version.parse('''1.6'''):
_lowercase = True
from torch.cuda.amp import autocast
_lowercase = logging.getLogger(__name__)
@dataclass
class __snake_case :
"""simple docstring"""
UpperCamelCase_ = field(
metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'} )
UpperCamelCase_ = field(
default=snake_case__ , metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'} , )
UpperCamelCase_ = field(
default=snake_case__ , metadata={'help': 'Whether to freeze the feature extractor layers of the model.'} )
UpperCamelCase_ = field(
default=snake_case__ , metadata={'help': 'Whether to log verbose messages or not.'} , )
UpperCamelCase_ = field(
default=2.0 , metadata={'help': 'Maximum temperature for gumbel softmax.'} )
UpperCamelCase_ = field(
default=0.5 , metadata={'help': 'Minimum temperature for gumbel softmax.'} )
UpperCamelCase_ = field(
default=0.99_99_95 , metadata={'help': 'Decay of gumbel temperature during training.'} )
def UpperCamelCase ( snake_case__ , snake_case__):
logging.basicConfig(
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , handlers=[logging.StreamHandler(sys.stdout)] , )
lowerCAmelCase_ : str = logging.WARNING
if model_args.verbose_logging:
lowerCAmelCase_ : int = logging.DEBUG
elif trainer_utils.is_main_process(training_args.local_rank):
lowerCAmelCase_ : Any = logging.INFO
logger.setLevel(snake_case__)
@dataclass
class __snake_case :
"""simple docstring"""
UpperCamelCase_ = field(
default=snake_case__ , metadata={'help': 'The name of the dataset to use (via the datasets library).'} )
UpperCamelCase_ = field(
default=snake_case__ , metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'} )
UpperCamelCase_ = field(
default='train' , metadata={
'help': 'The name of the training data set split to use (via the datasets library). Defaults to \'train\''
} , )
UpperCamelCase_ = field(
default='validation' , metadata={
'help': (
'The name of the validation data set split to use (via the datasets library). Defaults to \'validation\''
)
} , )
UpperCamelCase_ = field(
default='file' , metadata={'help': 'Column in the dataset that contains speech file path. Defaults to \'file\''} , )
UpperCamelCase_ = field(
default=snake_case__ , metadata={'help': 'Overwrite the cached preprocessed datasets or not.'} )
UpperCamelCase_ = field(
default=1 , metadata={
'help': 'The percentage of the train set used as validation set in case there\'s no validation split'
} , )
UpperCamelCase_ = field(
default=snake_case__ , metadata={'help': 'The number of processes to use for the preprocessing.'} , )
UpperCamelCase_ = field(
default=20.0 , metadata={'help': 'Filter audio files that are longer than `max_duration_in_seconds` seconds'} )
@dataclass
class __snake_case :
"""simple docstring"""
UpperCamelCase_ = 42
UpperCamelCase_ = 42
UpperCamelCase_ = "longest"
UpperCamelCase_ = None
UpperCamelCase_ = None
def __call__( self : str ,lowerCAmelCase__ : List[Dict[str, Union[List[int], torch.Tensor]]] ) -> Dict[str, torch.Tensor]:
'''simple docstring'''
lowerCAmelCase_ : Tuple = self.feature_extractor.pad(
lowerCAmelCase__ ,max_length=self.max_length ,padding=self.padding ,pad_to_multiple_of=self.pad_to_multiple_of ,return_tensors="pt" ,)
lowerCAmelCase_ : Union[str, Any] = self.model._get_feat_extract_output_lengths(batch["input_values"].shape[-1] )
lowerCAmelCase_ : List[str] = batch["input_values"].shape[0]
# make sure that no loss is computed on padded inputs
if batch["attention_mask"] is not None:
# compute real output lengths according to convolution formula
lowerCAmelCase_ : Tuple = self.model._get_feat_extract_output_lengths(batch["attention_mask"].sum(-1 ) ).to(
torch.long )
lowerCAmelCase_ : Optional[Any] = torch.zeros(
(batch_size, mask_indices_seq_length) ,dtype=torch.long ,device=batch["input_values"].device )
# these two operations makes sure that all values
# before the output lengths indices are attended to
lowerCAmelCase_ : Tuple = 1
lowerCAmelCase_ : int = attention_mask.flip([-1] ).cumsum(-1 ).flip([-1] ).bool()
# sample randomly masked indices
lowerCAmelCase_ : str = _compute_mask_indices(
(batch_size, mask_indices_seq_length) ,self.model.config.mask_time_prob ,self.model.config.mask_time_length ,attention_mask=lowerCAmelCase__ ,min_masks=2 ,)
return batch
class __snake_case ( snake_case__ ):
"""simple docstring"""
def __init__( self : List[str] ,*lowerCAmelCase__ : Optional[int] ,lowerCAmelCase__ : Tuple=1 ,lowerCAmelCase__ : Optional[int]=0 ,lowerCAmelCase__ : Optional[Any]=1.0 ,**lowerCAmelCase__ : Any ) -> str:
'''simple docstring'''
super().__init__(*lowerCAmelCase__ ,**lowerCAmelCase__ )
lowerCAmelCase_ : Tuple = 0
lowerCAmelCase_ : int = max_gumbel_temp
lowerCAmelCase_ : Union[str, Any] = min_gumbel_temp
lowerCAmelCase_ : str = gumbel_temp_decay
def UpperCAmelCase_ ( self : Tuple ,lowerCAmelCase__ : nn.Module ,lowerCAmelCase__ : Dict[str, Union[torch.Tensor, Any]] ) -> torch.Tensor:
'''simple docstring'''
model.train()
lowerCAmelCase_ : str = self._prepare_inputs(lowerCAmelCase__ )
if self.use_amp:
with autocast():
lowerCAmelCase_ : List[Any] = self.compute_loss(lowerCAmelCase__ ,lowerCAmelCase__ )
else:
lowerCAmelCase_ : List[Any] = self.compute_loss(lowerCAmelCase__ ,lowerCAmelCase__ )
if self.args.n_gpu > 1 or self.deepspeed:
if model.module.config.ctc_loss_reduction == "mean":
lowerCAmelCase_ : List[Any] = loss.mean()
elif model.module.config.ctc_loss_reduction == "sum":
lowerCAmelCase_ : Optional[Any] = loss.sum() / (inputs["mask_time_indices"]).sum()
else:
raise ValueError(f'''{model.config.ctc_loss_reduction} is not valid. Choose one of [\'mean\', \'sum\']''' )
if self.args.gradient_accumulation_steps > 1:
lowerCAmelCase_ : int = loss / self.args.gradient_accumulation_steps
if self.use_amp:
self.scaler.scale(lowerCAmelCase__ ).backward()
elif self.use_apex:
with amp.scale_loss(lowerCAmelCase__ ,self.optimizer ) as scaled_loss:
scaled_loss.backward()
elif self.deepspeed:
self.deepspeed.backward(lowerCAmelCase__ )
else:
loss.backward()
self.num_update_step += 1
# make sure gumbel softmax temperature is decayed
if self.args.n_gpu > 1 or self.deepspeed:
model.module.set_gumbel_temperature(
max(self.max_gumbel_temp * self.gumbel_temp_decay**self.num_update_step ,self.min_gumbel_temp ) )
else:
model.set_gumbel_temperature(
max(self.max_gumbel_temp * self.gumbel_temp_decay**self.num_update_step ,self.min_gumbel_temp ) )
return loss.detach()
def UpperCamelCase ( ):
# See all possible arguments in src/transformers/training_args.py
# or by passing the --help flag to this script.
# We now keep distinct sets of args, for a cleaner separation of concerns.
lowerCAmelCase_ : Tuple = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ : Dict = parser.parse_args_into_dataclasses()
configure_logger(snake_case__ , snake_case__)
# Downloading and loading a dataset from the hub.
lowerCAmelCase_ : List[str] = load_dataset(data_args.dataset_name , data_args.dataset_config_name , cache_dir=model_args.cache_dir)
if "validation" not in datasets.keys():
# make sure only "validation" and "train" keys remain"
lowerCAmelCase_ : Any = DatasetDict()
lowerCAmelCase_ : Union[str, Any] = load_dataset(
data_args.dataset_name , data_args.dataset_config_name , split=F'''{data_args.train_split_name}[:{data_args.validation_split_percentage}%]''' , cache_dir=model_args.cache_dir , )
lowerCAmelCase_ : List[str] = load_dataset(
data_args.dataset_name , data_args.dataset_config_name , split=F'''{data_args.train_split_name}[{data_args.validation_split_percentage}%:]''' , cache_dir=model_args.cache_dir , )
else:
# make sure only "validation" and "train" keys remain"
lowerCAmelCase_ : Union[str, Any] = DatasetDict()
lowerCAmelCase_ : int = load_dataset(
data_args.dataset_name , data_args.dataset_config_name , split="validation" , cache_dir=model_args.cache_dir , )
lowerCAmelCase_ : Any = load_dataset(
data_args.dataset_name , data_args.dataset_config_name , split=F'''{data_args.train_split_name}''' , cache_dir=model_args.cache_dir , )
# only normalized-inputs-training is supported
lowerCAmelCase_ : Dict = WavaVecaFeatureExtractor.from_pretrained(
model_args.model_name_or_path , cache_dir=model_args.cache_dir , do_normalize=snake_case__)
def prepare_dataset(snake_case__):
# check that all files have the correct sampling rate
lowerCAmelCase_ , lowerCAmelCase_ : str = librosa.load(batch[data_args.speech_file_column] , sr=feature_extractor.sampling_rate)
return batch
# load audio files into numpy arrays
lowerCAmelCase_ : int = datasets.map(
snake_case__ , num_proc=data_args.preprocessing_num_workers , remove_columns=datasets["train"].column_names)
# filter audio files that are too long
lowerCAmelCase_ : int = vectorized_datasets.filter(
lambda snake_case__: len(data["speech"]) < int(data_args.max_duration_in_seconds * feature_extractor.sampling_rate))
def normalize(snake_case__):
return feature_extractor(batch["speech"] , sampling_rate=feature_extractor.sampling_rate)
# normalize and transform to `BatchFeatures`
lowerCAmelCase_ : str = vectorized_datasets.map(
snake_case__ , batched=snake_case__ , num_proc=data_args.preprocessing_num_workers , load_from_cache_file=not data_args.overwrite_cache , remove_columns=vectorized_datasets["train"].column_names , )
# pretraining is only supported for "newer" stable layer norm architecture
# apply_spec_augment has to be True, mask_feature_prob has to be 0.0
lowerCAmelCase_ : Optional[Any] = WavaVecaConfig.from_pretrained(
model_args.model_name_or_path , cache_dir=model_args.cache_dir , gradient_checkpointing=training_args.gradient_checkpointing , )
if not config.do_stable_layer_norm or config.feat_extract_norm != "layer":
raise ValueError(
"PreTraining is only supported for ``config.do_stable_layer_norm=True`` and"
" ``config.feat_extract_norm='layer'")
lowerCAmelCase_ : Dict = WavaVecaForPreTraining(snake_case__)
lowerCAmelCase_ : int = DataCollatorForWavaVecaPretraining(model=snake_case__ , feature_extractor=snake_case__)
lowerCAmelCase_ : List[Any] = WavaVecaPreTrainer(
model=snake_case__ , data_collator=snake_case__ , args=snake_case__ , train_dataset=vectorized_datasets["train"] , eval_dataset=vectorized_datasets["validation"] , tokenizer=snake_case__ , max_gumbel_temp=model_args.max_gumbel_temperature , min_gumbel_temp=model_args.min_gumbel_temperature , gumbel_temp_decay=model_args.gumbel_temperature_decay , )
trainer.train()
if __name__ == "__main__":
main()
| 659 | 1 |
import logging
import re
import pytorch_quantization
import pytorch_quantization.nn as quant_nn
import torch
from pytorch_quantization import calib
from pytorch_quantization.tensor_quant import QuantDescriptor
_lowercase = logging.getLogger(__name__)
_lowercase = 50 # max width of layer names
_lowercase = 70 # max width of quantizer names
def UpperCamelCase ( snake_case__):
lowerCAmelCase_ : Dict = parser.add_argument_group("quant_trainer arguments")
group.add_argument("--wprec" , type=snake_case__ , default=8 , help="weight precision")
group.add_argument("--aprec" , type=snake_case__ , default=8 , help="activation precision")
group.add_argument("--quant-per-tensor" , action="store_true" , help="per tensor weight scaling")
group.add_argument("--quant-disable" , action="store_true" , help="disable all quantizers")
group.add_argument("--quant-disable-embeddings" , action="store_true" , help="disable all embeddings quantizers")
group.add_argument("--quant-disable-keyword" , type=snake_case__ , nargs="+" , help="disable quantizers by keyword")
group.add_argument("--quant-disable-layer-module" , type=snake_case__ , help="disable quantizers by keyword under layer.")
group.add_argument("--quant-enable-layer-module" , type=snake_case__ , help="enable quantizers by keyword under layer")
group.add_argument("--calibrator" , default="max" , help="which quantization range calibrator to use")
group.add_argument("--percentile" , default=snake_case__ , type=snake_case__ , help="percentile for PercentileCalibrator")
group.add_argument("--fuse-qkv" , action="store_true" , help="use the same scale factor for qkv")
group.add_argument("--clip-gelu" , metavar="N" , type=snake_case__ , help="clip gelu output maximum value to N")
group.add_argument(
"--recalibrate-weights" , action="store_true" , help=(
"recalibrate weight amaxes by taking the max of the weights."
" amaxes will be computed with the current quantization granularity (axis)."
) , )
def UpperCamelCase ( snake_case__):
if args.calibrator == "max":
lowerCAmelCase_ : List[Any] = "max"
elif args.calibrator == "percentile":
if args.percentile is None:
raise ValueError("Specify --percentile when using percentile calibrator")
lowerCAmelCase_ : Tuple = "histogram"
elif args.calibrator == "mse":
lowerCAmelCase_ : Dict = "histogram"
else:
raise ValueError(F'''Invalid calibrator {args.calibrator}''')
lowerCAmelCase_ : Optional[Any] = QuantDescriptor(num_bits=args.aprec , calib_method=snake_case__)
lowerCAmelCase_ : Tuple = QuantDescriptor(num_bits=args.wprec , axis=(None if args.quant_per_tensor else (0,)))
quant_nn.QuantLinear.set_default_quant_desc_input(snake_case__)
quant_nn.QuantLinear.set_default_quant_desc_weight(snake_case__)
def UpperCamelCase ( snake_case__ , snake_case__ , snake_case__=False , snake_case__=False):
logger.info("Configuring Model for Quantization")
logger.info(F'''using quantization package {pytorch_quantization.__file__}''')
if not calib:
if args.quant_disable_embeddings:
set_quantizer_by_name(snake_case__ , ["embeddings"] , which="weight" , _disabled=snake_case__)
if args.quant_disable:
set_quantizer_by_name(snake_case__ , [""] , _disabled=snake_case__)
if args.quant_disable_keyword:
set_quantizer_by_name(snake_case__ , args.quant_disable_keyword , _disabled=snake_case__)
if args.quant_disable_layer_module:
set_quantizer_by_name(snake_case__ , [R"layer.\d+." + args.quant_disable_layer_module] , _disabled=snake_case__)
if args.quant_enable_layer_module:
set_quantizer_by_name(snake_case__ , [R"layer.\d+." + args.quant_enable_layer_module] , _disabled=snake_case__)
if args.recalibrate_weights:
recalibrate_weights(snake_case__)
if args.fuse_qkv:
fuse_qkv(snake_case__ , snake_case__)
if args.clip_gelu:
clip_gelu(snake_case__ , args.clip_gelu)
# if args.local_rank in [-1, 0] and not calib:
print_quant_summary(snake_case__)
def UpperCamelCase ( snake_case__):
logger.info("Enabling Calibration")
for name, module in model.named_modules():
if name.endswith("_quantizer"):
if module._calibrator is not None:
module.disable_quant()
module.enable_calib()
else:
module.disable()
logger.info(F'''{name:80}: {module}''')
def UpperCamelCase ( snake_case__ , snake_case__):
logger.info("Loading calibrated amax")
for name, module in model.named_modules():
if name.endswith("_quantizer"):
if module._calibrator is not None:
if isinstance(module._calibrator , calib.MaxCalibrator):
module.load_calib_amax()
else:
module.load_calib_amax("percentile" , percentile=args.percentile)
module.enable_quant()
module.disable_calib()
else:
module.enable()
model.cuda()
print_quant_summary(snake_case__)
def UpperCamelCase ( snake_case__ , snake_case__):
def fusea(snake_case__ , snake_case__ , snake_case__):
for mod in [qq, qk, qv]:
if not hasattr(snake_case__ , "_amax"):
print(" WARNING: NO AMAX BUFFER")
return
lowerCAmelCase_ : List[Any] = qq._amax.detach().item()
lowerCAmelCase_ : Optional[Any] = qk._amax.detach().item()
lowerCAmelCase_ : Optional[int] = qv._amax.detach().item()
lowerCAmelCase_ : List[Any] = max(snake_case__ , snake_case__ , snake_case__)
qq._amax.fill_(snake_case__)
qk._amax.fill_(snake_case__)
qv._amax.fill_(snake_case__)
logger.info(F''' q={q:5.2f} k={k:5.2f} v={v:5.2f} -> {amax:5.2f}''')
for name, mod in model.named_modules():
if name.endswith(".attention.self"):
logger.info(F'''FUSE_QKV: {name:{name_width}}''')
fusea(mod.matmul_q_input_quantizer , mod.matmul_k_input_quantizer , mod.matmul_v_input_quantizer)
if args.quant_per_tensor:
fusea(mod.query._weight_quantizer , mod.key._weight_quantizer , mod.value._weight_quantizer)
def UpperCamelCase ( snake_case__ , snake_case__):
for name, mod in model.named_modules():
if name.endswith(".output.dense") and not name.endswith("attention.output.dense"):
lowerCAmelCase_ : Optional[Any] = mod._input_quantizer._amax.data.detach().item()
mod._input_quantizer._amax.data.detach().clamp_(max=snake_case__)
lowerCAmelCase_ : Tuple = mod._input_quantizer._amax.data.detach().item()
logger.info(F'''CLIP_GELU: {name:{name_width}} amax: {amax_init:5.2f} -> {amax:5.2f}''')
def UpperCamelCase ( snake_case__):
for name, mod in model.named_modules():
if hasattr(snake_case__ , "_weight_quantizer") and mod._weight_quantizer.axis is not None:
lowerCAmelCase_ : Optional[Any] = mod.weight.shape[0]
lowerCAmelCase_ : str = mod._weight_quantizer._amax.detach()
lowerCAmelCase_ : Any = torch.ones(snake_case__ , dtype=amax.dtype , device=amax.device) * amax
print(F'''expanding {name} {amax} -> {mod._weight_quantizer._amax}''')
def UpperCamelCase ( snake_case__):
for name, mod in model.named_modules():
if hasattr(snake_case__ , "_weight_quantizer"):
if not hasattr(mod.weight_quantizer , "_amax"):
print("RECALIB: {name:{name_width}} WARNING: NO AMAX BUFFER")
continue
# determine which axes to reduce across
# e.g. a 4D tensor quantized per axis 0 should reduce over (1,2,3)
lowerCAmelCase_ : Any = set() if mod._weight_quantizer.axis is None else set(mod._weight_quantizer.axis)
lowerCAmelCase_ : List[Any] = set(range(len(mod.weight.size()))) - axis_set
lowerCAmelCase_ : Tuple = pytorch_quantization.utils.reduce_amax(mod.weight , axis=snake_case__ , keepdims=snake_case__).detach()
logger.info(F'''RECALIB: {name:{name_width}} {mod._weight_quantizer._amax.flatten()} -> {amax.flatten()}''')
lowerCAmelCase_ : Tuple = amax
def UpperCamelCase ( snake_case__ , snake_case__=25 , snake_case__=1_80 , snake_case__=None):
if ignore is None:
lowerCAmelCase_ : Dict = []
elif not isinstance(snake_case__ , snake_case__):
lowerCAmelCase_ : List[str] = [ignore]
lowerCAmelCase_ : List[Any] = 0
for name, mod in model.named_modules():
if not hasattr(snake_case__ , "weight"):
continue
lowerCAmelCase_ : Any = max(snake_case__ , len(snake_case__))
for name, mod in model.named_modules():
lowerCAmelCase_ : int = getattr(snake_case__ , "_input_quantizer" , snake_case__)
lowerCAmelCase_ : Tuple = getattr(snake_case__ , "_weight_quantizer" , snake_case__)
if not hasattr(snake_case__ , "weight"):
continue
if type(snake_case__) in ignore:
continue
if [True for s in ignore if type(snake_case__) is str and s in name]:
continue
lowerCAmelCase_ : List[Any] = F'''Act:{input_q.extra_repr()}'''
lowerCAmelCase_ : Tuple = F'''Wgt:{weight_q.extra_repr()}'''
lowerCAmelCase_ : Optional[Any] = F'''{name:{name_width}} {act_str} {wgt_str}'''
if len(snake_case__) <= line_width:
logger.info(snake_case__)
else:
logger.info(F'''{name:{name_width}} {act_str}''')
logger.info(F'''{" ":{name_width}} {wgt_str}''')
def UpperCamelCase ( snake_case__):
lowerCAmelCase_ : Any = 0
for name, mod in model.named_modules():
if isinstance(snake_case__ , pytorch_quantization.nn.TensorQuantizer):
print(F'''{name:80} {mod}''')
count += 1
print(F'''{count} TensorQuantizers found in model''')
def UpperCamelCase ( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__):
lowerCAmelCase_ : Tuple = getattr(snake_case__ , snake_case__ , snake_case__)
if quantizer_mod is not None:
assert hasattr(snake_case__ , snake_case__)
setattr(snake_case__ , snake_case__ , snake_case__)
else:
logger.warning(F'''{name} has no {quantizer}''')
def UpperCamelCase ( snake_case__ , snake_case__ , snake_case__="both" , **snake_case__):
lowerCAmelCase_ : str = F'''Warning: changing {which} quantizers of {name:{qname_width}}'''
for k, v in kwargs.items():
s += F''' {k}={v}'''
if which in ["input", "both"]:
set_quantizer(snake_case__ , snake_case__ , "_input_quantizer" , snake_case__ , snake_case__)
if which in ["weight", "both"]:
set_quantizer(snake_case__ , snake_case__ , "_weight_quantizer" , snake_case__ , snake_case__)
logger.info(snake_case__)
def UpperCamelCase ( snake_case__ , snake_case__ , **snake_case__):
for name, mod in model.named_modules():
if hasattr(snake_case__ , "_input_quantizer") or hasattr(snake_case__ , "_weight_quantizer"):
for n in names:
if re.search(snake_case__ , snake_case__):
set_quantizers(snake_case__ , snake_case__ , **snake_case__)
elif name.endswith("_quantizer"):
for n in names:
if re.search(snake_case__ , snake_case__):
lowerCAmelCase_ : str = F'''Warning: changing {name:{name_width}}'''
for k, v in kwargs.items():
s += F''' {k}={v}'''
setattr(snake_case__ , snake_case__ , snake_case__)
logger.info(snake_case__)
| 659 |
from __future__ import annotations
from collections.abc import Callable
def UpperCamelCase ( snake_case__ , snake_case__ , snake_case__ , snake_case__ = 1_00 , ):
lowerCAmelCase_ : Any = x_start
lowerCAmelCase_ : Optional[Any] = fnc(snake_case__)
lowerCAmelCase_ : Union[str, Any] = 0.0
for _ in range(snake_case__):
# Approximates small segments of curve as linear and solve
# for trapezoidal area
lowerCAmelCase_ : Any = (x_end - x_start) / steps + xa
lowerCAmelCase_ : Dict = fnc(snake_case__)
area += abs(fxa + fxa) * (xa - xa) / 2
# Increment step
lowerCAmelCase_ : int = xa
lowerCAmelCase_ : str = fxa
return area
if __name__ == "__main__":
def UpperCamelCase ( snake_case__):
return x**3 + x**2
print('''f(x) = x^3 + x^2''')
print('''The area between the curve, x = -5, x = 5 and the x axis is:''')
_lowercase = 10
while i <= 100000:
print(f"with {i} steps: {trapezoidal_area(f, -5, 5, i)}")
i *= 10
| 659 | 1 |
import os
from shutil import copyfile
from typing import List, Optional, Tuple
from tokenizers import processors
from ...tokenization_utils import AddedToken, BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import is_sentencepiece_available, logging
if is_sentencepiece_available():
from .tokenization_nllb import NllbTokenizer
else:
_lowercase = None
_lowercase = logging.get_logger(__name__)
_lowercase = {'''vocab_file''': '''sentencepiece.bpe.model''', '''tokenizer_file''': '''tokenizer.json'''}
_lowercase = {
'''vocab_file''': {
'''facebook/nllb-200-distilled-600M''': (
'''https://huggingface.co/facebook/nllb-200-distilled-600M/resolve/main/sentencepiece.bpe.model'''
),
},
'''tokenizer_file''': {
'''facebook/nllb-200-distilled-600M''': (
'''https://huggingface.co/facebook/nllb-200-distilled-600M/resolve/main/tokenizer.json'''
),
},
}
_lowercase = {
'''facebook/nllb-large-en-ro''': 1024,
'''facebook/nllb-200-distilled-600M''': 1024,
}
# fmt: off
_lowercase = ['''ace_Arab''', '''ace_Latn''', '''acm_Arab''', '''acq_Arab''', '''aeb_Arab''', '''afr_Latn''', '''ajp_Arab''', '''aka_Latn''', '''amh_Ethi''', '''apc_Arab''', '''arb_Arab''', '''ars_Arab''', '''ary_Arab''', '''arz_Arab''', '''asm_Beng''', '''ast_Latn''', '''awa_Deva''', '''ayr_Latn''', '''azb_Arab''', '''azj_Latn''', '''bak_Cyrl''', '''bam_Latn''', '''ban_Latn''', '''bel_Cyrl''', '''bem_Latn''', '''ben_Beng''', '''bho_Deva''', '''bjn_Arab''', '''bjn_Latn''', '''bod_Tibt''', '''bos_Latn''', '''bug_Latn''', '''bul_Cyrl''', '''cat_Latn''', '''ceb_Latn''', '''ces_Latn''', '''cjk_Latn''', '''ckb_Arab''', '''crh_Latn''', '''cym_Latn''', '''dan_Latn''', '''deu_Latn''', '''dik_Latn''', '''dyu_Latn''', '''dzo_Tibt''', '''ell_Grek''', '''eng_Latn''', '''epo_Latn''', '''est_Latn''', '''eus_Latn''', '''ewe_Latn''', '''fao_Latn''', '''pes_Arab''', '''fij_Latn''', '''fin_Latn''', '''fon_Latn''', '''fra_Latn''', '''fur_Latn''', '''fuv_Latn''', '''gla_Latn''', '''gle_Latn''', '''glg_Latn''', '''grn_Latn''', '''guj_Gujr''', '''hat_Latn''', '''hau_Latn''', '''heb_Hebr''', '''hin_Deva''', '''hne_Deva''', '''hrv_Latn''', '''hun_Latn''', '''hye_Armn''', '''ibo_Latn''', '''ilo_Latn''', '''ind_Latn''', '''isl_Latn''', '''ita_Latn''', '''jav_Latn''', '''jpn_Jpan''', '''kab_Latn''', '''kac_Latn''', '''kam_Latn''', '''kan_Knda''', '''kas_Arab''', '''kas_Deva''', '''kat_Geor''', '''knc_Arab''', '''knc_Latn''', '''kaz_Cyrl''', '''kbp_Latn''', '''kea_Latn''', '''khm_Khmr''', '''kik_Latn''', '''kin_Latn''', '''kir_Cyrl''', '''kmb_Latn''', '''kon_Latn''', '''kor_Hang''', '''kmr_Latn''', '''lao_Laoo''', '''lvs_Latn''', '''lij_Latn''', '''lim_Latn''', '''lin_Latn''', '''lit_Latn''', '''lmo_Latn''', '''ltg_Latn''', '''ltz_Latn''', '''lua_Latn''', '''lug_Latn''', '''luo_Latn''', '''lus_Latn''', '''mag_Deva''', '''mai_Deva''', '''mal_Mlym''', '''mar_Deva''', '''min_Latn''', '''mkd_Cyrl''', '''plt_Latn''', '''mlt_Latn''', '''mni_Beng''', '''khk_Cyrl''', '''mos_Latn''', '''mri_Latn''', '''zsm_Latn''', '''mya_Mymr''', '''nld_Latn''', '''nno_Latn''', '''nob_Latn''', '''npi_Deva''', '''nso_Latn''', '''nus_Latn''', '''nya_Latn''', '''oci_Latn''', '''gaz_Latn''', '''ory_Orya''', '''pag_Latn''', '''pan_Guru''', '''pap_Latn''', '''pol_Latn''', '''por_Latn''', '''prs_Arab''', '''pbt_Arab''', '''quy_Latn''', '''ron_Latn''', '''run_Latn''', '''rus_Cyrl''', '''sag_Latn''', '''san_Deva''', '''sat_Beng''', '''scn_Latn''', '''shn_Mymr''', '''sin_Sinh''', '''slk_Latn''', '''slv_Latn''', '''smo_Latn''', '''sna_Latn''', '''snd_Arab''', '''som_Latn''', '''sot_Latn''', '''spa_Latn''', '''als_Latn''', '''srd_Latn''', '''srp_Cyrl''', '''ssw_Latn''', '''sun_Latn''', '''swe_Latn''', '''swh_Latn''', '''szl_Latn''', '''tam_Taml''', '''tat_Cyrl''', '''tel_Telu''', '''tgk_Cyrl''', '''tgl_Latn''', '''tha_Thai''', '''tir_Ethi''', '''taq_Latn''', '''taq_Tfng''', '''tpi_Latn''', '''tsn_Latn''', '''tso_Latn''', '''tuk_Latn''', '''tum_Latn''', '''tur_Latn''', '''twi_Latn''', '''tzm_Tfng''', '''uig_Arab''', '''ukr_Cyrl''', '''umb_Latn''', '''urd_Arab''', '''uzn_Latn''', '''vec_Latn''', '''vie_Latn''', '''war_Latn''', '''wol_Latn''', '''xho_Latn''', '''ydd_Hebr''', '''yor_Latn''', '''yue_Hant''', '''zho_Hans''', '''zho_Hant''', '''zul_Latn''']
class __snake_case ( snake_case__ ):
"""simple docstring"""
UpperCamelCase_ = VOCAB_FILES_NAMES
UpperCamelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
UpperCamelCase_ = PRETRAINED_VOCAB_FILES_MAP
UpperCamelCase_ = ['input_ids', 'attention_mask']
UpperCamelCase_ = NllbTokenizer
UpperCamelCase_ = []
UpperCamelCase_ = []
def __init__( self : Tuple ,lowerCAmelCase__ : Dict=None ,lowerCAmelCase__ : Dict=None ,lowerCAmelCase__ : str="<s>" ,lowerCAmelCase__ : Dict="</s>" ,lowerCAmelCase__ : List[Any]="</s>" ,lowerCAmelCase__ : str="<s>" ,lowerCAmelCase__ : List[str]="<unk>" ,lowerCAmelCase__ : List[str]="<pad>" ,lowerCAmelCase__ : Optional[Any]="<mask>" ,lowerCAmelCase__ : List[str]=None ,lowerCAmelCase__ : Union[str, Any]=None ,lowerCAmelCase__ : Union[str, Any]=None ,lowerCAmelCase__ : Tuple=False ,**lowerCAmelCase__ : int ,) -> str:
'''simple docstring'''
lowerCAmelCase_ : int = AddedToken(lowerCAmelCase__ ,lstrip=lowerCAmelCase__ ,rstrip=lowerCAmelCase__ ) if isinstance(lowerCAmelCase__ ,lowerCAmelCase__ ) else mask_token
lowerCAmelCase_ : Optional[int] = legacy_behaviour
super().__init__(
vocab_file=lowerCAmelCase__ ,tokenizer_file=lowerCAmelCase__ ,bos_token=lowerCAmelCase__ ,eos_token=lowerCAmelCase__ ,sep_token=lowerCAmelCase__ ,cls_token=lowerCAmelCase__ ,unk_token=lowerCAmelCase__ ,pad_token=lowerCAmelCase__ ,mask_token=lowerCAmelCase__ ,src_lang=lowerCAmelCase__ ,tgt_lang=lowerCAmelCase__ ,additional_special_tokens=lowerCAmelCase__ ,legacy_behaviour=lowerCAmelCase__ ,**lowerCAmelCase__ ,)
lowerCAmelCase_ : Dict = vocab_file
lowerCAmelCase_ : str = False if not self.vocab_file else True
lowerCAmelCase_ : Union[str, Any] = FAIRSEQ_LANGUAGE_CODES.copy()
if additional_special_tokens is not None:
# Only add those special tokens if they are not already there.
_additional_special_tokens.extend(
[t for t in additional_special_tokens if t not in _additional_special_tokens] )
self.add_special_tokens({"additional_special_tokens": _additional_special_tokens} )
lowerCAmelCase_ : Any = {
lang_code: self.convert_tokens_to_ids(lowerCAmelCase__ ) for lang_code in FAIRSEQ_LANGUAGE_CODES
}
lowerCAmelCase_ : Union[str, Any] = src_lang if src_lang is not None else "eng_Latn"
lowerCAmelCase_ : int = self.convert_tokens_to_ids(self._src_lang )
lowerCAmelCase_ : int = tgt_lang
self.set_src_lang_special_tokens(self._src_lang )
@property
def UpperCAmelCase_ ( self : Optional[int] ) -> str:
'''simple docstring'''
return self._src_lang
@src_lang.setter
def UpperCAmelCase_ ( self : Union[str, Any] ,lowerCAmelCase__ : str ) -> None:
'''simple docstring'''
lowerCAmelCase_ : str = new_src_lang
self.set_src_lang_special_tokens(self._src_lang )
def UpperCAmelCase_ ( self : Union[str, Any] ,lowerCAmelCase__ : List[int] ,lowerCAmelCase__ : Optional[List[int]] = None ) -> List[int]:
'''simple docstring'''
if token_ids_a is None:
return self.prefix_tokens + token_ids_a + self.suffix_tokens
# We don't expect to process pairs, but leave the pair logic for API consistency
return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens
def UpperCAmelCase_ ( self : Tuple ,lowerCAmelCase__ : List[int] ,lowerCAmelCase__ : Optional[List[int]] = None ) -> List[int]:
'''simple docstring'''
lowerCAmelCase_ : Optional[Any] = [self.sep_token_id]
lowerCAmelCase_ : Optional[int] = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
def UpperCAmelCase_ ( self : Dict ,lowerCAmelCase__ : Tuple ,lowerCAmelCase__ : str ,lowerCAmelCase__ : Optional[str] ,lowerCAmelCase__ : Optional[str] ,**lowerCAmelCase__ : Optional[Any] ) -> Any:
'''simple docstring'''
if src_lang is None or tgt_lang is None:
raise ValueError("Translation requires a `src_lang` and a `tgt_lang` for this model" )
lowerCAmelCase_ : Tuple = src_lang
lowerCAmelCase_ : List[str] = self(lowerCAmelCase__ ,add_special_tokens=lowerCAmelCase__ ,return_tensors=lowerCAmelCase__ ,**lowerCAmelCase__ )
lowerCAmelCase_ : Any = self.convert_tokens_to_ids(lowerCAmelCase__ )
lowerCAmelCase_ : List[str] = tgt_lang_id
return inputs
def UpperCAmelCase_ ( self : Any ,lowerCAmelCase__ : List[str] ,lowerCAmelCase__ : str = "eng_Latn" ,lowerCAmelCase__ : Optional[List[str]] = None ,lowerCAmelCase__ : str = "fra_Latn" ,**lowerCAmelCase__ : Any ,) -> BatchEncoding:
'''simple docstring'''
lowerCAmelCase_ : List[Any] = src_lang
lowerCAmelCase_ : Optional[Any] = tgt_lang
return super().prepare_seqaseq_batch(lowerCAmelCase__ ,lowerCAmelCase__ ,**lowerCAmelCase__ )
def UpperCAmelCase_ ( self : Any ) -> Optional[Any]:
'''simple docstring'''
return self.set_src_lang_special_tokens(self.src_lang )
def UpperCAmelCase_ ( self : List[Any] ) -> List[str]:
'''simple docstring'''
return self.set_tgt_lang_special_tokens(self.tgt_lang )
def UpperCAmelCase_ ( self : Optional[Any] ,lowerCAmelCase__ : List[str] ) -> None:
'''simple docstring'''
lowerCAmelCase_ : List[Any] = self.convert_tokens_to_ids(lowerCAmelCase__ )
if self.legacy_behaviour:
lowerCAmelCase_ : Optional[int] = []
lowerCAmelCase_ : List[Any] = [self.eos_token_id, self.cur_lang_code]
else:
lowerCAmelCase_ : List[str] = [self.cur_lang_code]
lowerCAmelCase_ : int = [self.eos_token_id]
lowerCAmelCase_ : Dict = self.convert_ids_to_tokens(self.prefix_tokens )
lowerCAmelCase_ : Any = self.convert_ids_to_tokens(self.suffix_tokens )
lowerCAmelCase_ : Optional[int] = processors.TemplateProcessing(
single=prefix_tokens_str + ["$A"] + suffix_tokens_str ,pair=prefix_tokens_str + ["$A", "$B"] + suffix_tokens_str ,special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str ,self.prefix_tokens + self.suffix_tokens ) ) ,)
def UpperCAmelCase_ ( self : int ,lowerCAmelCase__ : str ) -> None:
'''simple docstring'''
lowerCAmelCase_ : Dict = self.convert_tokens_to_ids(lowerCAmelCase__ )
if self.legacy_behaviour:
lowerCAmelCase_ : str = []
lowerCAmelCase_ : List[Any] = [self.eos_token_id, self.cur_lang_code]
else:
lowerCAmelCase_ : List[Any] = [self.cur_lang_code]
lowerCAmelCase_ : Union[str, Any] = [self.eos_token_id]
lowerCAmelCase_ : str = self.convert_ids_to_tokens(self.prefix_tokens )
lowerCAmelCase_ : Optional[Any] = self.convert_ids_to_tokens(self.suffix_tokens )
lowerCAmelCase_ : int = processors.TemplateProcessing(
single=prefix_tokens_str + ["$A"] + suffix_tokens_str ,pair=prefix_tokens_str + ["$A", "$B"] + suffix_tokens_str ,special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str ,self.prefix_tokens + self.suffix_tokens ) ) ,)
def UpperCAmelCase_ ( self : Dict ,lowerCAmelCase__ : str ,lowerCAmelCase__ : Optional[str] = None ) -> Tuple[str]:
'''simple docstring'''
if not self.can_save_slow_tokenizer:
raise ValueError(
"Your fast tokenizer does not have the necessary information to save the vocabulary for a slow "
"tokenizer." )
if not os.path.isdir(lowerCAmelCase__ ):
logger.error(f'''Vocabulary path ({save_directory}) should be a directory.''' )
return
lowerCAmelCase_ : Union[str, Any] = os.path.join(
lowerCAmelCase__ ,(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] )
if os.path.abspath(self.vocab_file ) != os.path.abspath(lowerCAmelCase__ ):
copyfile(self.vocab_file ,lowerCAmelCase__ )
return (out_vocab_file,)
| 659 |
import gc
import unittest
import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer
from diffusers import (
AutoencoderKL,
DDIMScheduler,
PNDMScheduler,
StableDiffusionLDMaDPipeline,
UNetaDConditionModel,
)
from diffusers.utils import nightly, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu
from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
enable_full_determinism()
class __snake_case ( unittest.TestCase ):
"""simple docstring"""
UpperCamelCase_ = StableDiffusionLDMaDPipeline
UpperCamelCase_ = TEXT_TO_IMAGE_PARAMS
UpperCamelCase_ = TEXT_TO_IMAGE_BATCH_PARAMS
UpperCamelCase_ = TEXT_TO_IMAGE_IMAGE_PARAMS
def UpperCAmelCase_ ( self : Tuple ) -> str:
'''simple docstring'''
torch.manual_seed(0 )
lowerCAmelCase_ : Optional[Any] = UNetaDConditionModel(
block_out_channels=(32, 64) ,layers_per_block=2 ,sample_size=32 ,in_channels=4 ,out_channels=4 ,down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") ,up_block_types=("CrossAttnUpBlock2D", "UpBlock2D") ,cross_attention_dim=32 ,)
lowerCAmelCase_ : Any = DDIMScheduler(
beta_start=0.00_085 ,beta_end=0.012 ,beta_schedule="scaled_linear" ,clip_sample=lowerCAmelCase__ ,set_alpha_to_one=lowerCAmelCase__ ,)
torch.manual_seed(0 )
lowerCAmelCase_ : str = AutoencoderKL(
block_out_channels=[32, 64] ,in_channels=6 ,out_channels=6 ,down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] ,up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] ,latent_channels=4 ,)
torch.manual_seed(0 )
lowerCAmelCase_ : Optional[Any] = CLIPTextConfig(
bos_token_id=0 ,eos_token_id=2 ,hidden_size=32 ,intermediate_size=37 ,layer_norm_eps=1e-0_5 ,num_attention_heads=4 ,num_hidden_layers=5 ,pad_token_id=1 ,vocab_size=10_00 ,)
lowerCAmelCase_ : Optional[int] = CLIPTextModel(lowerCAmelCase__ )
lowerCAmelCase_ : Dict = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" )
lowerCAmelCase_ : List[Any] = {
"unet": unet,
"scheduler": scheduler,
"vae": vae,
"text_encoder": text_encoder,
"tokenizer": tokenizer,
"safety_checker": None,
"feature_extractor": None,
}
return components
def UpperCAmelCase_ ( self : Tuple ,lowerCAmelCase__ : List[Any] ,lowerCAmelCase__ : List[str]=0 ) -> Dict:
'''simple docstring'''
if str(lowerCAmelCase__ ).startswith("mps" ):
lowerCAmelCase_ : Optional[int] = torch.manual_seed(lowerCAmelCase__ )
else:
lowerCAmelCase_ : Dict = torch.Generator(device=lowerCAmelCase__ ).manual_seed(lowerCAmelCase__ )
lowerCAmelCase_ : str = {
"prompt": "A painting of a squirrel eating a burger",
"generator": generator,
"num_inference_steps": 2,
"guidance_scale": 6.0,
"output_type": "numpy",
}
return inputs
def UpperCAmelCase_ ( self : Any ) -> Optional[int]:
'''simple docstring'''
lowerCAmelCase_ : Dict = "cpu" # ensure determinism for the device-dependent torch.Generator
lowerCAmelCase_ : List[str] = self.get_dummy_components()
lowerCAmelCase_ : Union[str, Any] = StableDiffusionLDMaDPipeline(**lowerCAmelCase__ )
lowerCAmelCase_ : List[Any] = ldmad_pipe.to(lowerCAmelCase__ )
ldmad_pipe.set_progress_bar_config(disable=lowerCAmelCase__ )
lowerCAmelCase_ : Any = self.get_dummy_inputs(lowerCAmelCase__ )
lowerCAmelCase_ : Union[str, Any] = ldmad_pipe(**lowerCAmelCase__ )
lowerCAmelCase_ , lowerCAmelCase_ : Any = output.rgb, output.depth
lowerCAmelCase_ : Dict = rgb[0, -3:, -3:, -1]
lowerCAmelCase_ : Tuple = depth[0, -3:, -1]
assert rgb.shape == (1, 64, 64, 3)
assert depth.shape == (1, 64, 64)
lowerCAmelCase_ : Optional[Any] = np.array(
[0.37_338_176, 0.70_247, 0.74_203_193, 0.51_643_604, 0.58_256_793, 0.60_932_136, 0.4_181_095, 0.48_355_877, 0.46_535_262] )
lowerCAmelCase_ : Tuple = np.array([103.46_727, 85.812_004, 87.849_236] )
assert np.abs(image_slice_rgb.flatten() - expected_slice_rgb ).max() < 1e-2
assert np.abs(image_slice_depth.flatten() - expected_slice_depth ).max() < 1e-2
def UpperCAmelCase_ ( self : int ) -> Optional[int]:
'''simple docstring'''
lowerCAmelCase_ : Dict = self.get_dummy_components()
lowerCAmelCase_ : List[str] = StableDiffusionLDMaDPipeline(**lowerCAmelCase__ )
lowerCAmelCase_ : List[Any] = ldmad_pipe.to(lowerCAmelCase__ )
ldmad_pipe.set_progress_bar_config(disable=lowerCAmelCase__ )
lowerCAmelCase_ : Union[str, Any] = self.get_dummy_inputs(lowerCAmelCase__ )
lowerCAmelCase_ : str = 3 * [inputs["prompt"]]
# forward
lowerCAmelCase_ : Union[str, Any] = ldmad_pipe(**lowerCAmelCase__ )
lowerCAmelCase_ , lowerCAmelCase_ : Optional[Any] = output.rgb, output.depth
lowerCAmelCase_ : str = rgb_slice_a[0, -3:, -3:, -1]
lowerCAmelCase_ : List[str] = depth_slice_a[0, -3:, -1]
lowerCAmelCase_ : Union[str, Any] = self.get_dummy_inputs(lowerCAmelCase__ )
lowerCAmelCase_ : Tuple = 3 * [inputs.pop("prompt" )]
lowerCAmelCase_ : str = ldmad_pipe.tokenizer(
lowerCAmelCase__ ,padding="max_length" ,max_length=ldmad_pipe.tokenizer.model_max_length ,truncation=lowerCAmelCase__ ,return_tensors="pt" ,)
lowerCAmelCase_ : Union[str, Any] = text_inputs["input_ids"].to(lowerCAmelCase__ )
lowerCAmelCase_ : Optional[int] = ldmad_pipe.text_encoder(lowerCAmelCase__ )[0]
lowerCAmelCase_ : Optional[int] = prompt_embeds
# forward
lowerCAmelCase_ : str = ldmad_pipe(**lowerCAmelCase__ )
lowerCAmelCase_ , lowerCAmelCase_ : str = output.rgb, output.depth
lowerCAmelCase_ : Optional[Any] = rgb_slice_a[0, -3:, -3:, -1]
lowerCAmelCase_ : Tuple = depth_slice_a[0, -3:, -1]
assert np.abs(rgb_slice_a.flatten() - rgb_slice_a.flatten() ).max() < 1e-4
assert np.abs(depth_slice_a.flatten() - depth_slice_a.flatten() ).max() < 1e-4
def UpperCAmelCase_ ( self : Union[str, Any] ) -> Tuple:
'''simple docstring'''
lowerCAmelCase_ : Any = "cpu" # ensure determinism for the device-dependent torch.Generator
lowerCAmelCase_ : Optional[int] = self.get_dummy_components()
lowerCAmelCase_ : Dict = PNDMScheduler(skip_prk_steps=lowerCAmelCase__ )
lowerCAmelCase_ : Union[str, Any] = StableDiffusionLDMaDPipeline(**lowerCAmelCase__ )
lowerCAmelCase_ : Any = ldmad_pipe.to(lowerCAmelCase__ )
ldmad_pipe.set_progress_bar_config(disable=lowerCAmelCase__ )
lowerCAmelCase_ : List[str] = self.get_dummy_inputs(lowerCAmelCase__ )
lowerCAmelCase_ : List[Any] = "french fries"
lowerCAmelCase_ : Optional[int] = ldmad_pipe(**lowerCAmelCase__ ,negative_prompt=lowerCAmelCase__ )
lowerCAmelCase_ , lowerCAmelCase_ : Union[str, Any] = output.rgb, output.depth
lowerCAmelCase_ : Any = rgb[0, -3:, -3:, -1]
lowerCAmelCase_ : Tuple = depth[0, -3:, -1]
assert rgb.shape == (1, 64, 64, 3)
assert depth.shape == (1, 64, 64)
lowerCAmelCase_ : int = np.array(
[0.37_044, 0.71_811_503, 0.7_223_251, 0.48_603_675, 0.5_638_391, 0.6_364_948, 0.42_833_704, 0.4_901_315, 0.47_926_217] )
lowerCAmelCase_ : Union[str, Any] = np.array([107.84_738, 84.62_802, 89.962_135] )
assert np.abs(rgb_slice.flatten() - expected_slice_rgb ).max() < 1e-2
assert np.abs(depth_slice.flatten() - expected_slice_depth ).max() < 1e-2
@slow
@require_torch_gpu
class __snake_case ( unittest.TestCase ):
"""simple docstring"""
def UpperCAmelCase_ ( self : Tuple ) -> Union[str, Any]:
'''simple docstring'''
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def UpperCAmelCase_ ( self : Any ,lowerCAmelCase__ : Tuple ,lowerCAmelCase__ : Dict="cpu" ,lowerCAmelCase__ : Union[str, Any]=torch.floataa ,lowerCAmelCase__ : List[str]=0 ) -> int:
'''simple docstring'''
lowerCAmelCase_ : Any = torch.Generator(device=lowerCAmelCase__ ).manual_seed(lowerCAmelCase__ )
lowerCAmelCase_ : List[str] = np.random.RandomState(lowerCAmelCase__ ).standard_normal((1, 4, 64, 64) )
lowerCAmelCase_ : Optional[Any] = torch.from_numpy(lowerCAmelCase__ ).to(device=lowerCAmelCase__ ,dtype=lowerCAmelCase__ )
lowerCAmelCase_ : Union[str, Any] = {
"prompt": "a photograph of an astronaut riding a horse",
"latents": latents,
"generator": generator,
"num_inference_steps": 3,
"guidance_scale": 7.5,
"output_type": "numpy",
}
return inputs
def UpperCAmelCase_ ( self : List[Any] ) -> List[str]:
'''simple docstring'''
lowerCAmelCase_ : Optional[Any] = StableDiffusionLDMaDPipeline.from_pretrained("Intel/ldm3d" )
lowerCAmelCase_ : List[str] = ldmad_pipe.to(lowerCAmelCase__ )
ldmad_pipe.set_progress_bar_config(disable=lowerCAmelCase__ )
lowerCAmelCase_ : Dict = self.get_inputs(lowerCAmelCase__ )
lowerCAmelCase_ : List[str] = ldmad_pipe(**lowerCAmelCase__ )
lowerCAmelCase_ , lowerCAmelCase_ : Dict = output.rgb, output.depth
lowerCAmelCase_ : List[str] = rgb[0, -3:, -3:, -1].flatten()
lowerCAmelCase_ : Optional[int] = rgb[0, -3:, -1].flatten()
assert rgb.shape == (1, 5_12, 5_12, 3)
assert depth.shape == (1, 5_12, 5_12)
lowerCAmelCase_ : int = np.array(
[0.53_805_465, 0.56_707_305, 0.5_486_515, 0.57_012_236, 0.5_814_511, 0.56_253_487, 0.54_843_014, 0.55_092_263, 0.6_459_706] )
lowerCAmelCase_ : Optional[Any] = np.array(
[0.9_263_781, 0.6_678_672, 0.5_486_515, 0.92_202_145, 0.67_831_135, 0.56_253_487, 0.9_241_694, 0.7_551_478, 0.6_459_706] )
assert np.abs(rgb_slice - expected_slice_rgb ).max() < 3e-3
assert np.abs(depth_slice - expected_slice_depth ).max() < 3e-3
@nightly
@require_torch_gpu
class __snake_case ( unittest.TestCase ):
"""simple docstring"""
def UpperCAmelCase_ ( self : Tuple ) -> Union[str, Any]:
'''simple docstring'''
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def UpperCAmelCase_ ( self : Tuple ,lowerCAmelCase__ : Tuple ,lowerCAmelCase__ : Dict="cpu" ,lowerCAmelCase__ : List[str]=torch.floataa ,lowerCAmelCase__ : Optional[int]=0 ) -> int:
'''simple docstring'''
lowerCAmelCase_ : Dict = torch.Generator(device=lowerCAmelCase__ ).manual_seed(lowerCAmelCase__ )
lowerCAmelCase_ : Tuple = np.random.RandomState(lowerCAmelCase__ ).standard_normal((1, 4, 64, 64) )
lowerCAmelCase_ : Any = torch.from_numpy(lowerCAmelCase__ ).to(device=lowerCAmelCase__ ,dtype=lowerCAmelCase__ )
lowerCAmelCase_ : int = {
"prompt": "a photograph of an astronaut riding a horse",
"latents": latents,
"generator": generator,
"num_inference_steps": 50,
"guidance_scale": 7.5,
"output_type": "numpy",
}
return inputs
def UpperCAmelCase_ ( self : Dict ) -> int:
'''simple docstring'''
lowerCAmelCase_ : List[Any] = StableDiffusionLDMaDPipeline.from_pretrained("Intel/ldm3d" ).to(lowerCAmelCase__ )
ldmad_pipe.set_progress_bar_config(disable=lowerCAmelCase__ )
lowerCAmelCase_ : Union[str, Any] = self.get_inputs(lowerCAmelCase__ )
lowerCAmelCase_ : Union[str, Any] = ldmad_pipe(**lowerCAmelCase__ )
lowerCAmelCase_ , lowerCAmelCase_ : Any = output.rgb, output.depth
lowerCAmelCase_ : Dict = 0.495_586
lowerCAmelCase_ : Optional[Any] = 0.33_795_515
lowerCAmelCase_ : Any = 112.48_518
lowerCAmelCase_ : List[Any] = 98.489_746
assert np.abs(expected_rgb_mean - rgb.mean() ) < 1e-3
assert np.abs(expected_rgb_std - rgb.std() ) < 1e-3
assert np.abs(expected_depth_mean - depth.mean() ) < 1e-3
assert np.abs(expected_depth_std - depth.std() ) < 1e-3
def UpperCAmelCase_ ( self : Tuple ) -> List[str]:
'''simple docstring'''
lowerCAmelCase_ : int = StableDiffusionLDMaDPipeline.from_pretrained("Intel/ldm3d-4c" ).to(lowerCAmelCase__ )
ldmad_pipe.set_progress_bar_config(disable=lowerCAmelCase__ )
lowerCAmelCase_ : str = self.get_inputs(lowerCAmelCase__ )
lowerCAmelCase_ : Tuple = ldmad_pipe(**lowerCAmelCase__ )
lowerCAmelCase_ , lowerCAmelCase_ : Tuple = output.rgb, output.depth
lowerCAmelCase_ : List[str] = 0.4_194_127
lowerCAmelCase_ : List[str] = 0.35_375_586
lowerCAmelCase_ : str = 0.5_638_502
lowerCAmelCase_ : Optional[Any] = 0.34_686_103
assert rgb.shape == (1, 5_12, 5_12, 3)
assert depth.shape == (1, 5_12, 5_12, 1)
assert np.abs(expected_rgb_mean - rgb.mean() ) < 1e-3
assert np.abs(expected_rgb_std - rgb.std() ) < 1e-3
assert np.abs(expected_depth_mean - depth.mean() ) < 1e-3
assert np.abs(expected_depth_std - depth.std() ) < 1e-3
| 659 | 1 |
import gc
import unittest
import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer
from diffusers import (
AutoencoderKL,
DDIMScheduler,
PNDMScheduler,
StableDiffusionLDMaDPipeline,
UNetaDConditionModel,
)
from diffusers.utils import nightly, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu
from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
enable_full_determinism()
class __snake_case ( unittest.TestCase ):
"""simple docstring"""
UpperCamelCase_ = StableDiffusionLDMaDPipeline
UpperCamelCase_ = TEXT_TO_IMAGE_PARAMS
UpperCamelCase_ = TEXT_TO_IMAGE_BATCH_PARAMS
UpperCamelCase_ = TEXT_TO_IMAGE_IMAGE_PARAMS
def UpperCAmelCase_ ( self : Tuple ) -> str:
'''simple docstring'''
torch.manual_seed(0 )
lowerCAmelCase_ : Optional[Any] = UNetaDConditionModel(
block_out_channels=(32, 64) ,layers_per_block=2 ,sample_size=32 ,in_channels=4 ,out_channels=4 ,down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") ,up_block_types=("CrossAttnUpBlock2D", "UpBlock2D") ,cross_attention_dim=32 ,)
lowerCAmelCase_ : Any = DDIMScheduler(
beta_start=0.00_085 ,beta_end=0.012 ,beta_schedule="scaled_linear" ,clip_sample=lowerCAmelCase__ ,set_alpha_to_one=lowerCAmelCase__ ,)
torch.manual_seed(0 )
lowerCAmelCase_ : str = AutoencoderKL(
block_out_channels=[32, 64] ,in_channels=6 ,out_channels=6 ,down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] ,up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] ,latent_channels=4 ,)
torch.manual_seed(0 )
lowerCAmelCase_ : Optional[Any] = CLIPTextConfig(
bos_token_id=0 ,eos_token_id=2 ,hidden_size=32 ,intermediate_size=37 ,layer_norm_eps=1e-0_5 ,num_attention_heads=4 ,num_hidden_layers=5 ,pad_token_id=1 ,vocab_size=10_00 ,)
lowerCAmelCase_ : Optional[int] = CLIPTextModel(lowerCAmelCase__ )
lowerCAmelCase_ : Dict = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" )
lowerCAmelCase_ : List[Any] = {
"unet": unet,
"scheduler": scheduler,
"vae": vae,
"text_encoder": text_encoder,
"tokenizer": tokenizer,
"safety_checker": None,
"feature_extractor": None,
}
return components
def UpperCAmelCase_ ( self : Tuple ,lowerCAmelCase__ : List[Any] ,lowerCAmelCase__ : List[str]=0 ) -> Dict:
'''simple docstring'''
if str(lowerCAmelCase__ ).startswith("mps" ):
lowerCAmelCase_ : Optional[int] = torch.manual_seed(lowerCAmelCase__ )
else:
lowerCAmelCase_ : Dict = torch.Generator(device=lowerCAmelCase__ ).manual_seed(lowerCAmelCase__ )
lowerCAmelCase_ : str = {
"prompt": "A painting of a squirrel eating a burger",
"generator": generator,
"num_inference_steps": 2,
"guidance_scale": 6.0,
"output_type": "numpy",
}
return inputs
def UpperCAmelCase_ ( self : Any ) -> Optional[int]:
'''simple docstring'''
lowerCAmelCase_ : Dict = "cpu" # ensure determinism for the device-dependent torch.Generator
lowerCAmelCase_ : List[str] = self.get_dummy_components()
lowerCAmelCase_ : Union[str, Any] = StableDiffusionLDMaDPipeline(**lowerCAmelCase__ )
lowerCAmelCase_ : List[Any] = ldmad_pipe.to(lowerCAmelCase__ )
ldmad_pipe.set_progress_bar_config(disable=lowerCAmelCase__ )
lowerCAmelCase_ : Any = self.get_dummy_inputs(lowerCAmelCase__ )
lowerCAmelCase_ : Union[str, Any] = ldmad_pipe(**lowerCAmelCase__ )
lowerCAmelCase_ , lowerCAmelCase_ : Any = output.rgb, output.depth
lowerCAmelCase_ : Dict = rgb[0, -3:, -3:, -1]
lowerCAmelCase_ : Tuple = depth[0, -3:, -1]
assert rgb.shape == (1, 64, 64, 3)
assert depth.shape == (1, 64, 64)
lowerCAmelCase_ : Optional[Any] = np.array(
[0.37_338_176, 0.70_247, 0.74_203_193, 0.51_643_604, 0.58_256_793, 0.60_932_136, 0.4_181_095, 0.48_355_877, 0.46_535_262] )
lowerCAmelCase_ : Tuple = np.array([103.46_727, 85.812_004, 87.849_236] )
assert np.abs(image_slice_rgb.flatten() - expected_slice_rgb ).max() < 1e-2
assert np.abs(image_slice_depth.flatten() - expected_slice_depth ).max() < 1e-2
def UpperCAmelCase_ ( self : int ) -> Optional[int]:
'''simple docstring'''
lowerCAmelCase_ : Dict = self.get_dummy_components()
lowerCAmelCase_ : List[str] = StableDiffusionLDMaDPipeline(**lowerCAmelCase__ )
lowerCAmelCase_ : List[Any] = ldmad_pipe.to(lowerCAmelCase__ )
ldmad_pipe.set_progress_bar_config(disable=lowerCAmelCase__ )
lowerCAmelCase_ : Union[str, Any] = self.get_dummy_inputs(lowerCAmelCase__ )
lowerCAmelCase_ : str = 3 * [inputs["prompt"]]
# forward
lowerCAmelCase_ : Union[str, Any] = ldmad_pipe(**lowerCAmelCase__ )
lowerCAmelCase_ , lowerCAmelCase_ : Optional[Any] = output.rgb, output.depth
lowerCAmelCase_ : str = rgb_slice_a[0, -3:, -3:, -1]
lowerCAmelCase_ : List[str] = depth_slice_a[0, -3:, -1]
lowerCAmelCase_ : Union[str, Any] = self.get_dummy_inputs(lowerCAmelCase__ )
lowerCAmelCase_ : Tuple = 3 * [inputs.pop("prompt" )]
lowerCAmelCase_ : str = ldmad_pipe.tokenizer(
lowerCAmelCase__ ,padding="max_length" ,max_length=ldmad_pipe.tokenizer.model_max_length ,truncation=lowerCAmelCase__ ,return_tensors="pt" ,)
lowerCAmelCase_ : Union[str, Any] = text_inputs["input_ids"].to(lowerCAmelCase__ )
lowerCAmelCase_ : Optional[int] = ldmad_pipe.text_encoder(lowerCAmelCase__ )[0]
lowerCAmelCase_ : Optional[int] = prompt_embeds
# forward
lowerCAmelCase_ : str = ldmad_pipe(**lowerCAmelCase__ )
lowerCAmelCase_ , lowerCAmelCase_ : str = output.rgb, output.depth
lowerCAmelCase_ : Optional[Any] = rgb_slice_a[0, -3:, -3:, -1]
lowerCAmelCase_ : Tuple = depth_slice_a[0, -3:, -1]
assert np.abs(rgb_slice_a.flatten() - rgb_slice_a.flatten() ).max() < 1e-4
assert np.abs(depth_slice_a.flatten() - depth_slice_a.flatten() ).max() < 1e-4
def UpperCAmelCase_ ( self : Union[str, Any] ) -> Tuple:
'''simple docstring'''
lowerCAmelCase_ : Any = "cpu" # ensure determinism for the device-dependent torch.Generator
lowerCAmelCase_ : Optional[int] = self.get_dummy_components()
lowerCAmelCase_ : Dict = PNDMScheduler(skip_prk_steps=lowerCAmelCase__ )
lowerCAmelCase_ : Union[str, Any] = StableDiffusionLDMaDPipeline(**lowerCAmelCase__ )
lowerCAmelCase_ : Any = ldmad_pipe.to(lowerCAmelCase__ )
ldmad_pipe.set_progress_bar_config(disable=lowerCAmelCase__ )
lowerCAmelCase_ : List[str] = self.get_dummy_inputs(lowerCAmelCase__ )
lowerCAmelCase_ : List[Any] = "french fries"
lowerCAmelCase_ : Optional[int] = ldmad_pipe(**lowerCAmelCase__ ,negative_prompt=lowerCAmelCase__ )
lowerCAmelCase_ , lowerCAmelCase_ : Union[str, Any] = output.rgb, output.depth
lowerCAmelCase_ : Any = rgb[0, -3:, -3:, -1]
lowerCAmelCase_ : Tuple = depth[0, -3:, -1]
assert rgb.shape == (1, 64, 64, 3)
assert depth.shape == (1, 64, 64)
lowerCAmelCase_ : int = np.array(
[0.37_044, 0.71_811_503, 0.7_223_251, 0.48_603_675, 0.5_638_391, 0.6_364_948, 0.42_833_704, 0.4_901_315, 0.47_926_217] )
lowerCAmelCase_ : Union[str, Any] = np.array([107.84_738, 84.62_802, 89.962_135] )
assert np.abs(rgb_slice.flatten() - expected_slice_rgb ).max() < 1e-2
assert np.abs(depth_slice.flatten() - expected_slice_depth ).max() < 1e-2
@slow
@require_torch_gpu
class __snake_case ( unittest.TestCase ):
"""simple docstring"""
def UpperCAmelCase_ ( self : Tuple ) -> Union[str, Any]:
'''simple docstring'''
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def UpperCAmelCase_ ( self : Any ,lowerCAmelCase__ : Tuple ,lowerCAmelCase__ : Dict="cpu" ,lowerCAmelCase__ : Union[str, Any]=torch.floataa ,lowerCAmelCase__ : List[str]=0 ) -> int:
'''simple docstring'''
lowerCAmelCase_ : Any = torch.Generator(device=lowerCAmelCase__ ).manual_seed(lowerCAmelCase__ )
lowerCAmelCase_ : List[str] = np.random.RandomState(lowerCAmelCase__ ).standard_normal((1, 4, 64, 64) )
lowerCAmelCase_ : Optional[Any] = torch.from_numpy(lowerCAmelCase__ ).to(device=lowerCAmelCase__ ,dtype=lowerCAmelCase__ )
lowerCAmelCase_ : Union[str, Any] = {
"prompt": "a photograph of an astronaut riding a horse",
"latents": latents,
"generator": generator,
"num_inference_steps": 3,
"guidance_scale": 7.5,
"output_type": "numpy",
}
return inputs
def UpperCAmelCase_ ( self : List[Any] ) -> List[str]:
'''simple docstring'''
lowerCAmelCase_ : Optional[Any] = StableDiffusionLDMaDPipeline.from_pretrained("Intel/ldm3d" )
lowerCAmelCase_ : List[str] = ldmad_pipe.to(lowerCAmelCase__ )
ldmad_pipe.set_progress_bar_config(disable=lowerCAmelCase__ )
lowerCAmelCase_ : Dict = self.get_inputs(lowerCAmelCase__ )
lowerCAmelCase_ : List[str] = ldmad_pipe(**lowerCAmelCase__ )
lowerCAmelCase_ , lowerCAmelCase_ : Dict = output.rgb, output.depth
lowerCAmelCase_ : List[str] = rgb[0, -3:, -3:, -1].flatten()
lowerCAmelCase_ : Optional[int] = rgb[0, -3:, -1].flatten()
assert rgb.shape == (1, 5_12, 5_12, 3)
assert depth.shape == (1, 5_12, 5_12)
lowerCAmelCase_ : int = np.array(
[0.53_805_465, 0.56_707_305, 0.5_486_515, 0.57_012_236, 0.5_814_511, 0.56_253_487, 0.54_843_014, 0.55_092_263, 0.6_459_706] )
lowerCAmelCase_ : Optional[Any] = np.array(
[0.9_263_781, 0.6_678_672, 0.5_486_515, 0.92_202_145, 0.67_831_135, 0.56_253_487, 0.9_241_694, 0.7_551_478, 0.6_459_706] )
assert np.abs(rgb_slice - expected_slice_rgb ).max() < 3e-3
assert np.abs(depth_slice - expected_slice_depth ).max() < 3e-3
@nightly
@require_torch_gpu
class __snake_case ( unittest.TestCase ):
"""simple docstring"""
def UpperCAmelCase_ ( self : Tuple ) -> Union[str, Any]:
'''simple docstring'''
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def UpperCAmelCase_ ( self : Tuple ,lowerCAmelCase__ : Tuple ,lowerCAmelCase__ : Dict="cpu" ,lowerCAmelCase__ : List[str]=torch.floataa ,lowerCAmelCase__ : Optional[int]=0 ) -> int:
'''simple docstring'''
lowerCAmelCase_ : Dict = torch.Generator(device=lowerCAmelCase__ ).manual_seed(lowerCAmelCase__ )
lowerCAmelCase_ : Tuple = np.random.RandomState(lowerCAmelCase__ ).standard_normal((1, 4, 64, 64) )
lowerCAmelCase_ : Any = torch.from_numpy(lowerCAmelCase__ ).to(device=lowerCAmelCase__ ,dtype=lowerCAmelCase__ )
lowerCAmelCase_ : int = {
"prompt": "a photograph of an astronaut riding a horse",
"latents": latents,
"generator": generator,
"num_inference_steps": 50,
"guidance_scale": 7.5,
"output_type": "numpy",
}
return inputs
def UpperCAmelCase_ ( self : Dict ) -> int:
'''simple docstring'''
lowerCAmelCase_ : List[Any] = StableDiffusionLDMaDPipeline.from_pretrained("Intel/ldm3d" ).to(lowerCAmelCase__ )
ldmad_pipe.set_progress_bar_config(disable=lowerCAmelCase__ )
lowerCAmelCase_ : Union[str, Any] = self.get_inputs(lowerCAmelCase__ )
lowerCAmelCase_ : Union[str, Any] = ldmad_pipe(**lowerCAmelCase__ )
lowerCAmelCase_ , lowerCAmelCase_ : Any = output.rgb, output.depth
lowerCAmelCase_ : Dict = 0.495_586
lowerCAmelCase_ : Optional[Any] = 0.33_795_515
lowerCAmelCase_ : Any = 112.48_518
lowerCAmelCase_ : List[Any] = 98.489_746
assert np.abs(expected_rgb_mean - rgb.mean() ) < 1e-3
assert np.abs(expected_rgb_std - rgb.std() ) < 1e-3
assert np.abs(expected_depth_mean - depth.mean() ) < 1e-3
assert np.abs(expected_depth_std - depth.std() ) < 1e-3
def UpperCAmelCase_ ( self : Tuple ) -> List[str]:
'''simple docstring'''
lowerCAmelCase_ : int = StableDiffusionLDMaDPipeline.from_pretrained("Intel/ldm3d-4c" ).to(lowerCAmelCase__ )
ldmad_pipe.set_progress_bar_config(disable=lowerCAmelCase__ )
lowerCAmelCase_ : str = self.get_inputs(lowerCAmelCase__ )
lowerCAmelCase_ : Tuple = ldmad_pipe(**lowerCAmelCase__ )
lowerCAmelCase_ , lowerCAmelCase_ : Tuple = output.rgb, output.depth
lowerCAmelCase_ : List[str] = 0.4_194_127
lowerCAmelCase_ : List[str] = 0.35_375_586
lowerCAmelCase_ : str = 0.5_638_502
lowerCAmelCase_ : Optional[Any] = 0.34_686_103
assert rgb.shape == (1, 5_12, 5_12, 3)
assert depth.shape == (1, 5_12, 5_12, 1)
assert np.abs(expected_rgb_mean - rgb.mean() ) < 1e-3
assert np.abs(expected_rgb_std - rgb.std() ) < 1e-3
assert np.abs(expected_depth_mean - depth.mean() ) < 1e-3
assert np.abs(expected_depth_std - depth.std() ) < 1e-3
| 659 |
import argparse
import re
import numpy as np
import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from transformers import (
SamConfig,
SamImageProcessor,
SamModel,
SamProcessor,
SamVisionConfig,
)
_lowercase = {
'''iou_prediction_head.layers.0''': '''iou_prediction_head.proj_in''',
'''iou_prediction_head.layers.1''': '''iou_prediction_head.layers.0''',
'''iou_prediction_head.layers.2''': '''iou_prediction_head.proj_out''',
'''mask_decoder.output_upscaling.0''': '''mask_decoder.upscale_conv1''',
'''mask_decoder.output_upscaling.1''': '''mask_decoder.upscale_layer_norm''',
'''mask_decoder.output_upscaling.3''': '''mask_decoder.upscale_conv2''',
'''mask_downscaling.0''': '''mask_embed.conv1''',
'''mask_downscaling.1''': '''mask_embed.layer_norm1''',
'''mask_downscaling.3''': '''mask_embed.conv2''',
'''mask_downscaling.4''': '''mask_embed.layer_norm2''',
'''mask_downscaling.6''': '''mask_embed.conv3''',
'''point_embeddings''': '''point_embed''',
'''pe_layer.positional_encoding_gaussian_matrix''': '''shared_embedding.positional_embedding''',
'''image_encoder''': '''vision_encoder''',
'''neck.0''': '''neck.conv1''',
'''neck.1''': '''neck.layer_norm1''',
'''neck.2''': '''neck.conv2''',
'''neck.3''': '''neck.layer_norm2''',
'''patch_embed.proj''': '''patch_embed.projection''',
'''.norm''': '''.layer_norm''',
'''blocks''': '''layers''',
}
def UpperCamelCase ( snake_case__):
lowerCAmelCase_ : int = {}
state_dict.pop("pixel_mean" , snake_case__)
state_dict.pop("pixel_std" , snake_case__)
lowerCAmelCase_ : List[Any] = R".*.output_hypernetworks_mlps.(\d+).layers.(\d+).*"
for key, value in state_dict.items():
for key_to_modify, new_key in KEYS_TO_MODIFY_MAPPING.items():
if key_to_modify in key:
lowerCAmelCase_ : Dict = key.replace(snake_case__ , snake_case__)
if re.match(snake_case__ , snake_case__):
lowerCAmelCase_ : Any = int(re.match(snake_case__ , snake_case__).group(2))
if layer_nb == 0:
lowerCAmelCase_ : List[Any] = key.replace("layers.0" , "proj_in")
elif layer_nb == 1:
lowerCAmelCase_ : List[Any] = key.replace("layers.1" , "layers.0")
elif layer_nb == 2:
lowerCAmelCase_ : int = key.replace("layers.2" , "proj_out")
lowerCAmelCase_ : int = value
lowerCAmelCase_ : Optional[int] = model_state_dict[
"prompt_encoder.shared_embedding.positional_embedding"
]
return model_state_dict
def UpperCamelCase ( snake_case__ , snake_case__ , snake_case__ , snake_case__="ybelkada/segment-anything"):
lowerCAmelCase_ : Optional[int] = hf_hub_download(snake_case__ , F'''checkpoints/{model_name}.pth''')
if "sam_vit_b" in model_name:
lowerCAmelCase_ : Optional[Any] = SamConfig()
elif "sam_vit_l" in model_name:
lowerCAmelCase_ : Optional[int] = SamVisionConfig(
hidden_size=10_24 , num_hidden_layers=24 , num_attention_heads=16 , global_attn_indexes=[5, 11, 17, 23] , )
lowerCAmelCase_ : Union[str, Any] = SamConfig(
vision_config=snake_case__ , )
elif "sam_vit_h" in model_name:
lowerCAmelCase_ : Optional[Any] = SamVisionConfig(
hidden_size=12_80 , num_hidden_layers=32 , num_attention_heads=16 , global_attn_indexes=[7, 15, 23, 31] , )
lowerCAmelCase_ : Tuple = SamConfig(
vision_config=snake_case__ , )
lowerCAmelCase_ : Optional[Any] = torch.load(snake_case__ , map_location="cpu")
lowerCAmelCase_ : Union[str, Any] = replace_keys(snake_case__)
lowerCAmelCase_ : List[Any] = SamImageProcessor()
lowerCAmelCase_ : Any = SamProcessor(image_processor=snake_case__)
lowerCAmelCase_ : Any = SamModel(snake_case__)
hf_model.load_state_dict(snake_case__)
lowerCAmelCase_ : Dict = hf_model.to("cuda")
lowerCAmelCase_ : List[str] = "https://huggingface.co/ybelkada/segment-anything/resolve/main/assets/car.png"
lowerCAmelCase_ : List[Any] = Image.open(requests.get(snake_case__ , stream=snake_case__).raw).convert("RGB")
lowerCAmelCase_ : Optional[int] = [[[4_00, 6_50]]]
lowerCAmelCase_ : int = [[1]]
lowerCAmelCase_ : Optional[Any] = processor(images=np.array(snake_case__) , return_tensors="pt").to("cuda")
with torch.no_grad():
lowerCAmelCase_ : Optional[Any] = hf_model(**snake_case__)
lowerCAmelCase_ : Optional[int] = output.iou_scores.squeeze()
if model_name == "sam_vit_h_4b8939":
assert scores[-1].item() == 0.579_890_251_159_668
lowerCAmelCase_ : Any = processor(
images=np.array(snake_case__) , input_points=snake_case__ , input_labels=snake_case__ , return_tensors="pt").to("cuda")
with torch.no_grad():
lowerCAmelCase_ : Optional[Any] = hf_model(**snake_case__)
lowerCAmelCase_ : Union[str, Any] = output.iou_scores.squeeze()
assert scores[-1].item() == 0.9_712_603_092_193_604
lowerCAmelCase_ : Tuple = ((75, 2_75, 17_25, 8_50),)
lowerCAmelCase_ : Optional[Any] = processor(images=np.array(snake_case__) , input_boxes=snake_case__ , return_tensors="pt").to("cuda")
with torch.no_grad():
lowerCAmelCase_ : List[Any] = hf_model(**snake_case__)
lowerCAmelCase_ : str = output.iou_scores.squeeze()
assert scores[-1].item() == 0.8_686_015_605_926_514
# Test with 2 points and 1 image.
lowerCAmelCase_ : int = [[[4_00, 6_50], [8_00, 6_50]]]
lowerCAmelCase_ : Optional[Any] = [[1, 1]]
lowerCAmelCase_ : List[Any] = processor(
images=np.array(snake_case__) , input_points=snake_case__ , input_labels=snake_case__ , return_tensors="pt").to("cuda")
with torch.no_grad():
lowerCAmelCase_ : Tuple = hf_model(**snake_case__)
lowerCAmelCase_ : str = output.iou_scores.squeeze()
assert scores[-1].item() == 0.9_936_047_792_434_692
if __name__ == "__main__":
_lowercase = argparse.ArgumentParser()
_lowercase = ['''sam_vit_b_01ec64''', '''sam_vit_h_4b8939''', '''sam_vit_l_0b3195''']
parser.add_argument(
'''--model_name''',
default='''sam_vit_h_4b8939''',
choices=choices,
type=str,
help='''Path to hf config.json of model to convert''',
)
parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''')
parser.add_argument(
'''--push_to_hub''',
action='''store_true''',
help='''Whether to push the model and processor to the hub after converting''',
)
parser.add_argument(
'''--model_hub_id''',
default='''ybelkada/segment-anything''',
choices=choices,
type=str,
help='''Path to hf config.json of model to convert''',
)
_lowercase = parser.parse_args()
convert_sam_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub, args.model_hub_id)
| 659 | 1 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
_lowercase = {
'''configuration_clap''': [
'''CLAP_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''ClapAudioConfig''',
'''ClapConfig''',
'''ClapTextConfig''',
],
'''processing_clap''': ['''ClapProcessor'''],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowercase = [
'''CLAP_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''ClapModel''',
'''ClapPreTrainedModel''',
'''ClapTextModel''',
'''ClapTextModelWithProjection''',
'''ClapAudioModel''',
'''ClapAudioModelWithProjection''',
]
_lowercase = ['''ClapFeatureExtractor''']
if TYPE_CHECKING:
from .configuration_clap import (
CLAP_PRETRAINED_MODEL_ARCHIVE_LIST,
ClapAudioConfig,
ClapConfig,
ClapTextConfig,
)
from .processing_clap import ClapProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_clap import ClapFeatureExtractor
from .modeling_clap import (
CLAP_PRETRAINED_MODEL_ARCHIVE_LIST,
ClapAudioModel,
ClapAudioModelWithProjection,
ClapModel,
ClapPreTrainedModel,
ClapTextModel,
ClapTextModelWithProjection,
)
else:
import sys
_lowercase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 659 |
class __snake_case :
"""simple docstring"""
def __init__( self : Union[str, Any] ,lowerCAmelCase__ : str = "" ,lowerCAmelCase__ : bool = False ) -> None:
'''simple docstring'''
lowerCAmelCase_ : dict[str, RadixNode] = {}
# A node will be a leaf if the tree contains its word
lowerCAmelCase_ : Optional[int] = is_leaf
lowerCAmelCase_ : List[str] = prefix
def UpperCAmelCase_ ( self : List[str] ,lowerCAmelCase__ : str ) -> tuple[str, str, str]:
'''simple docstring'''
lowerCAmelCase_ : List[str] = 0
for q, w in zip(self.prefix ,lowerCAmelCase__ ):
if q != w:
break
x += 1
return self.prefix[:x], self.prefix[x:], word[x:]
def UpperCAmelCase_ ( self : Optional[Any] ,lowerCAmelCase__ : list[str] ) -> None:
'''simple docstring'''
for word in words:
self.insert(lowerCAmelCase__ )
def UpperCAmelCase_ ( self : List[Any] ,lowerCAmelCase__ : str ) -> None:
'''simple docstring'''
if self.prefix == word:
lowerCAmelCase_ : Optional[Any] = True
# Case 2: The node has no edges that have a prefix to the word
# Solution: We create an edge from the current node to a new one
# containing the word
elif word[0] not in self.nodes:
lowerCAmelCase_ : Optional[int] = RadixNode(prefix=lowerCAmelCase__ ,is_leaf=lowerCAmelCase__ )
else:
lowerCAmelCase_ : Optional[Any] = self.nodes[word[0]]
lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ : Any = incoming_node.match(
lowerCAmelCase__ )
# Case 3: The node prefix is equal to the matching
# Solution: We insert remaining word on the next node
if remaining_prefix == "":
self.nodes[matching_string[0]].insert(lowerCAmelCase__ )
# Case 4: The word is greater equal to the matching
# Solution: Create a node in between both nodes, change
# prefixes and add the new node for the remaining word
else:
lowerCAmelCase_ : Dict = remaining_prefix
lowerCAmelCase_ : str = self.nodes[matching_string[0]]
lowerCAmelCase_ : Dict = RadixNode(lowerCAmelCase__ ,lowerCAmelCase__ )
lowerCAmelCase_ : Any = aux_node
if remaining_word == "":
lowerCAmelCase_ : Optional[Any] = True
else:
self.nodes[matching_string[0]].insert(lowerCAmelCase__ )
def UpperCAmelCase_ ( self : Optional[Any] ,lowerCAmelCase__ : str ) -> bool:
'''simple docstring'''
lowerCAmelCase_ : List[str] = self.nodes.get(word[0] ,lowerCAmelCase__ )
if not incoming_node:
return False
else:
lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ : Optional[int] = incoming_node.match(
lowerCAmelCase__ )
# If there is remaining prefix, the word can't be on the tree
if remaining_prefix != "":
return False
# This applies when the word and the prefix are equal
elif remaining_word == "":
return incoming_node.is_leaf
# We have word remaining so we check the next node
else:
return incoming_node.find(lowerCAmelCase__ )
def UpperCAmelCase_ ( self : Tuple ,lowerCAmelCase__ : str ) -> bool:
'''simple docstring'''
lowerCAmelCase_ : int = self.nodes.get(word[0] ,lowerCAmelCase__ )
if not incoming_node:
return False
else:
lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ : List[Any] = incoming_node.match(
lowerCAmelCase__ )
# If there is remaining prefix, the word can't be on the tree
if remaining_prefix != "":
return False
# We have word remaining so we check the next node
elif remaining_word != "":
return incoming_node.delete(lowerCAmelCase__ )
else:
# If it is not a leaf, we don't have to delete
if not incoming_node.is_leaf:
return False
else:
# We delete the nodes if no edges go from it
if len(incoming_node.nodes ) == 0:
del self.nodes[word[0]]
# We merge the current node with its only child
if len(self.nodes ) == 1 and not self.is_leaf:
lowerCAmelCase_ : int = list(self.nodes.values() )[0]
lowerCAmelCase_ : List[Any] = merging_node.is_leaf
self.prefix += merging_node.prefix
lowerCAmelCase_ : int = merging_node.nodes
# If there is more than 1 edge, we just mark it as non-leaf
elif len(incoming_node.nodes ) > 1:
lowerCAmelCase_ : List[str] = False
# If there is 1 edge, we merge it with its child
else:
lowerCAmelCase_ : Union[str, Any] = list(incoming_node.nodes.values() )[0]
lowerCAmelCase_ : Optional[int] = merging_node.is_leaf
incoming_node.prefix += merging_node.prefix
lowerCAmelCase_ : List[str] = merging_node.nodes
return True
def UpperCAmelCase_ ( self : int ,lowerCAmelCase__ : int = 0 ) -> None:
'''simple docstring'''
if self.prefix != "":
print("-" * height ,self.prefix ," (leaf)" if self.is_leaf else "" )
for value in self.nodes.values():
value.print_tree(height + 1 )
def UpperCamelCase ( ):
lowerCAmelCase_ : List[Any] = "banana bananas bandana band apple all beast".split()
lowerCAmelCase_ : Optional[Any] = RadixNode()
root.insert_many(snake_case__)
assert all(root.find(snake_case__) for word in words)
assert not root.find("bandanas")
assert not root.find("apps")
root.delete("all")
assert not root.find("all")
root.delete("banana")
assert not root.find("banana")
assert root.find("bananas")
return True
def UpperCamelCase ( ):
assert test_trie()
def UpperCamelCase ( ):
lowerCAmelCase_ : str = RadixNode()
lowerCAmelCase_ : str = "banana bananas bandanas bandana band apple all beast".split()
root.insert_many(snake_case__)
print("Words:" , snake_case__)
print("Tree:")
root.print_tree()
if __name__ == "__main__":
main()
| 659 | 1 |
import secrets
from random import shuffle
from string import ascii_letters, ascii_lowercase, ascii_uppercase, digits, punctuation
def UpperCamelCase ( snake_case__ = 8):
lowerCAmelCase_ : List[str] = ascii_letters + digits + punctuation
return "".join(secrets.choice(snake_case__) for _ in range(snake_case__))
def UpperCamelCase ( snake_case__ , snake_case__):
# Password Generator = full boot with random_number, random_letters, and
# random_character FUNCTIONS
# Put your code here...
i -= len(snake_case__)
lowerCAmelCase_ : str = i // 3
lowerCAmelCase_ : List[Any] = i % 3
# chars = chars_incl + random_letters(ascii_letters, i / 3 + remainder) +
# random_number(digits, i / 3) + random_characters(punctuation, i / 3)
lowerCAmelCase_ : List[Any] = (
chars_incl
+ random(snake_case__ , quotient + remainder)
+ random(snake_case__ , snake_case__)
+ random(snake_case__ , snake_case__)
)
lowerCAmelCase_ : Optional[Any] = list(snake_case__)
shuffle(snake_case__)
return "".join(snake_case__)
# random is a generalised function for letters, characters and numbers
def UpperCamelCase ( snake_case__ , snake_case__):
return "".join(secrets.choice(snake_case__) for _ in range(snake_case__))
def UpperCamelCase ( snake_case__ , snake_case__):
pass # Put your code here...
def UpperCamelCase ( snake_case__ , snake_case__):
pass # Put your code here...
def UpperCamelCase ( snake_case__ , snake_case__):
pass # Put your code here...
def UpperCamelCase ( snake_case__ , snake_case__ = 8):
if len(snake_case__) < min_length:
# Your Password must be at least 8 characters long
return False
lowerCAmelCase_ : int = any(char in ascii_uppercase for char in password)
lowerCAmelCase_ : Any = any(char in ascii_lowercase for char in password)
lowerCAmelCase_ : str = any(char in digits for char in password)
lowerCAmelCase_ : Any = any(char in punctuation for char in password)
return upper and lower and num and spec_char
# Passwords should contain UPPERCASE, lowerase
# numbers, and special characters
def UpperCamelCase ( ):
lowerCAmelCase_ : Tuple = int(input("Please indicate the max length of your password: ").strip())
lowerCAmelCase_ : Optional[Any] = input(
"Please indicate the characters that must be in your password: ").strip()
print("Password generated:" , password_generator(snake_case__))
print(
"Alternative Password generated:" , alternative_password_generator(snake_case__ , snake_case__) , )
print("[If you are thinking of using this passsword, You better save it.]")
if __name__ == "__main__":
main()
| 659 |
from __future__ import annotations
import unittest
import numpy as np
from transformers import BlipTextConfig
from transformers.testing_utils import require_tf, slow
from transformers.utils import is_tf_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
if is_tf_available():
import tensorflow as tf
from transformers import TFBlipTextModel
from transformers.models.blip.modeling_tf_blip import TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST
class __snake_case :
"""simple docstring"""
def __init__( self : Tuple ,lowerCAmelCase__ : List[str] ,lowerCAmelCase__ : Optional[Any]=12 ,lowerCAmelCase__ : Union[str, Any]=7 ,lowerCAmelCase__ : Union[str, Any]=True ,lowerCAmelCase__ : List[str]=True ,lowerCAmelCase__ : Any=True ,lowerCAmelCase__ : Optional[Any]=99 ,lowerCAmelCase__ : List[str]=32 ,lowerCAmelCase__ : Dict=32 ,lowerCAmelCase__ : str=2 ,lowerCAmelCase__ : Optional[int]=4 ,lowerCAmelCase__ : str=37 ,lowerCAmelCase__ : Dict=0.1 ,lowerCAmelCase__ : List[str]=0.1 ,lowerCAmelCase__ : str=5_12 ,lowerCAmelCase__ : Union[str, Any]=0.02 ,lowerCAmelCase__ : Tuple=0 ,lowerCAmelCase__ : str=None ,) -> str:
'''simple docstring'''
lowerCAmelCase_ : int = parent
lowerCAmelCase_ : str = batch_size
lowerCAmelCase_ : int = seq_length
lowerCAmelCase_ : Union[str, Any] = is_training
lowerCAmelCase_ : int = use_input_mask
lowerCAmelCase_ : List[Any] = use_labels
lowerCAmelCase_ : Dict = vocab_size
lowerCAmelCase_ : Union[str, Any] = hidden_size
lowerCAmelCase_ : Union[str, Any] = projection_dim
lowerCAmelCase_ : List[Any] = num_hidden_layers
lowerCAmelCase_ : Any = num_attention_heads
lowerCAmelCase_ : List[Any] = intermediate_size
lowerCAmelCase_ : Any = dropout
lowerCAmelCase_ : Optional[int] = attention_dropout
lowerCAmelCase_ : int = max_position_embeddings
lowerCAmelCase_ : Optional[int] = initializer_range
lowerCAmelCase_ : Any = scope
lowerCAmelCase_ : Tuple = bos_token_id
def UpperCAmelCase_ ( self : str ) -> Tuple:
'''simple docstring'''
lowerCAmelCase_ : List[Any] = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size )
lowerCAmelCase_ : Dict = None
if self.use_input_mask:
lowerCAmelCase_ : List[Any] = random_attention_mask([self.batch_size, self.seq_length] )
if input_mask is not None:
lowerCAmelCase_ : List[Any] = input_mask.numpy()
lowerCAmelCase_ , lowerCAmelCase_ : str = input_mask.shape
lowerCAmelCase_ : Dict = np.random.randint(1 ,seq_length - 1 ,size=(batch_size,) )
for batch_idx, start_index in enumerate(lowerCAmelCase__ ):
lowerCAmelCase_ : Union[str, Any] = 1
lowerCAmelCase_ : Optional[Any] = 0
lowerCAmelCase_ : List[Any] = self.get_config()
return config, input_ids, tf.convert_to_tensor(lowerCAmelCase__ )
def UpperCAmelCase_ ( self : List[str] ) -> str:
'''simple docstring'''
return BlipTextConfig(
vocab_size=self.vocab_size ,hidden_size=self.hidden_size ,projection_dim=self.projection_dim ,num_hidden_layers=self.num_hidden_layers ,num_attention_heads=self.num_attention_heads ,intermediate_size=self.intermediate_size ,dropout=self.dropout ,attention_dropout=self.attention_dropout ,max_position_embeddings=self.max_position_embeddings ,initializer_range=self.initializer_range ,bos_token_id=self.bos_token_id ,)
def UpperCAmelCase_ ( self : Optional[Any] ,lowerCAmelCase__ : str ,lowerCAmelCase__ : Any ,lowerCAmelCase__ : Dict ) -> List[Any]:
'''simple docstring'''
lowerCAmelCase_ : List[Any] = TFBlipTextModel(config=lowerCAmelCase__ )
lowerCAmelCase_ : Optional[Any] = model(lowerCAmelCase__ ,attention_mask=lowerCAmelCase__ ,training=lowerCAmelCase__ )
lowerCAmelCase_ : str = model(lowerCAmelCase__ ,training=lowerCAmelCase__ )
self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) )
self.parent.assertEqual(result.pooler_output.shape ,(self.batch_size, self.hidden_size) )
def UpperCAmelCase_ ( self : Optional[int] ) -> int:
'''simple docstring'''
lowerCAmelCase_ : List[str] = self.prepare_config_and_inputs()
lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ : Dict = config_and_inputs
lowerCAmelCase_ : Tuple = {"input_ids": input_ids, "attention_mask": input_mask}
return config, inputs_dict
@require_tf
class __snake_case ( snake_case__ , unittest.TestCase ):
"""simple docstring"""
UpperCamelCase_ = (TFBlipTextModel,) if is_tf_available() else ()
UpperCamelCase_ = False
UpperCamelCase_ = False
UpperCamelCase_ = False
def UpperCAmelCase_ ( self : Optional[Any] ) -> str:
'''simple docstring'''
lowerCAmelCase_ : List[str] = BlipTextModelTester(self )
lowerCAmelCase_ : Tuple = ConfigTester(self ,config_class=lowerCAmelCase__ ,hidden_size=37 )
def UpperCAmelCase_ ( self : str ) -> Any:
'''simple docstring'''
self.config_tester.run_common_tests()
def UpperCAmelCase_ ( self : List[Any] ) -> Optional[Any]:
'''simple docstring'''
lowerCAmelCase_ : str = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*lowerCAmelCase__ )
def UpperCAmelCase_ ( self : Optional[int] ) -> Optional[Any]:
'''simple docstring'''
pass
def UpperCAmelCase_ ( self : Union[str, Any] ) -> Any:
'''simple docstring'''
pass
@unittest.skip(reason="Blip does not use inputs_embeds" )
def UpperCAmelCase_ ( self : Union[str, Any] ) -> Optional[int]:
'''simple docstring'''
pass
@unittest.skip(reason="BlipTextModel has no base class and is not available in MODEL_MAPPING" )
def UpperCAmelCase_ ( self : int ) -> Optional[Any]:
'''simple docstring'''
pass
@unittest.skip(reason="BlipTextModel has no base class and is not available in MODEL_MAPPING" )
def UpperCAmelCase_ ( self : Dict ) -> Union[str, Any]:
'''simple docstring'''
pass
@slow
def UpperCAmelCase_ ( self : Tuple ) -> Optional[Any]:
'''simple docstring'''
for model_name in TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
lowerCAmelCase_ : Tuple = TFBlipTextModel.from_pretrained(lowerCAmelCase__ )
self.assertIsNotNone(lowerCAmelCase__ )
def UpperCAmelCase_ ( self : Any ,lowerCAmelCase__ : str=True ) -> List[Any]:
'''simple docstring'''
super().test_pt_tf_model_equivalence(allow_missing_keys=lowerCAmelCase__ )
| 659 | 1 |
import os
import unittest
from transformers import MobileBertTokenizer, MobileBertTokenizerFast
from transformers.models.bert.tokenization_bert import (
VOCAB_FILES_NAMES,
BasicTokenizer,
WordpieceTokenizer,
_is_control,
_is_punctuation,
_is_whitespace,
)
from transformers.testing_utils import require_tokenizers, slow
from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english
@require_tokenizers
class __snake_case ( snake_case__ , unittest.TestCase ):
"""simple docstring"""
UpperCamelCase_ = MobileBertTokenizer
UpperCamelCase_ = MobileBertTokenizerFast
UpperCamelCase_ = True
UpperCamelCase_ = True
UpperCamelCase_ = filter_non_english
UpperCamelCase_ = 'google/mobilebert-uncased'
def UpperCAmelCase_ ( self : List[Any] ) -> str:
'''simple docstring'''
super().setUp()
lowerCAmelCase_ : List[str] = [
"[UNK]",
"[CLS]",
"[SEP]",
"[PAD]",
"[MASK]",
"want",
"##want",
"##ed",
"wa",
"un",
"runn",
"##ing",
",",
"low",
"lowest",
]
lowerCAmelCase_ : Optional[Any] = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES["vocab_file"] )
with open(self.vocab_file ,"w" ,encoding="utf-8" ) as vocab_writer:
vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) )
lowerCAmelCase_ : Optional[int] = [
(tokenizer_def[0], self.pre_trained_model_path, tokenizer_def[2]) # else the 'google/' prefix is stripped
for tokenizer_def in self.tokenizers_list
]
def UpperCAmelCase_ ( self : int ,lowerCAmelCase__ : List[str] ) -> int:
'''simple docstring'''
lowerCAmelCase_ : Optional[int] = "UNwant\u00E9d,running"
lowerCAmelCase_ : int = "unwanted, running"
return input_text, output_text
def UpperCAmelCase_ ( self : Tuple ) -> Any:
'''simple docstring'''
lowerCAmelCase_ : Tuple = self.tokenizer_class(self.vocab_file )
lowerCAmelCase_ : Optional[int] = tokenizer.tokenize("UNwant\u00E9d,running" )
self.assertListEqual(lowerCAmelCase__ ,["un", "##want", "##ed", ",", "runn", "##ing"] )
self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCAmelCase__ ) ,[9, 6, 7, 12, 10, 11] )
def UpperCAmelCase_ ( self : Optional[Any] ) -> int:
'''simple docstring'''
if not self.test_rust_tokenizer:
return
lowerCAmelCase_ : int = self.get_tokenizer()
lowerCAmelCase_ : List[Any] = self.get_rust_tokenizer()
lowerCAmelCase_ : Optional[Any] = "UNwant\u00E9d,running"
lowerCAmelCase_ : Dict = tokenizer.tokenize(lowerCAmelCase__ )
lowerCAmelCase_ : List[str] = rust_tokenizer.tokenize(lowerCAmelCase__ )
self.assertListEqual(lowerCAmelCase__ ,lowerCAmelCase__ )
lowerCAmelCase_ : Any = tokenizer.encode(lowerCAmelCase__ ,add_special_tokens=lowerCAmelCase__ )
lowerCAmelCase_ : Union[str, Any] = rust_tokenizer.encode(lowerCAmelCase__ ,add_special_tokens=lowerCAmelCase__ )
self.assertListEqual(lowerCAmelCase__ ,lowerCAmelCase__ )
lowerCAmelCase_ : Optional[Any] = self.get_rust_tokenizer()
lowerCAmelCase_ : Dict = tokenizer.encode(lowerCAmelCase__ )
lowerCAmelCase_ : Tuple = rust_tokenizer.encode(lowerCAmelCase__ )
self.assertListEqual(lowerCAmelCase__ ,lowerCAmelCase__ )
# With lower casing
lowerCAmelCase_ : Union[str, Any] = self.get_tokenizer(do_lower_case=lowerCAmelCase__ )
lowerCAmelCase_ : List[Any] = self.get_rust_tokenizer(do_lower_case=lowerCAmelCase__ )
lowerCAmelCase_ : List[str] = "UNwant\u00E9d,running"
lowerCAmelCase_ : Optional[Any] = tokenizer.tokenize(lowerCAmelCase__ )
lowerCAmelCase_ : Union[str, Any] = rust_tokenizer.tokenize(lowerCAmelCase__ )
self.assertListEqual(lowerCAmelCase__ ,lowerCAmelCase__ )
lowerCAmelCase_ : str = tokenizer.encode(lowerCAmelCase__ ,add_special_tokens=lowerCAmelCase__ )
lowerCAmelCase_ : int = rust_tokenizer.encode(lowerCAmelCase__ ,add_special_tokens=lowerCAmelCase__ )
self.assertListEqual(lowerCAmelCase__ ,lowerCAmelCase__ )
lowerCAmelCase_ : List[str] = self.get_rust_tokenizer()
lowerCAmelCase_ : List[str] = tokenizer.encode(lowerCAmelCase__ )
lowerCAmelCase_ : Optional[int] = rust_tokenizer.encode(lowerCAmelCase__ )
self.assertListEqual(lowerCAmelCase__ ,lowerCAmelCase__ )
def UpperCAmelCase_ ( self : Dict ) -> Union[str, Any]:
'''simple docstring'''
lowerCAmelCase_ : int = BasicTokenizer()
self.assertListEqual(tokenizer.tokenize("ah\u535A\u63A8zz" ) ,["ah", "\u535A", "\u63A8", "zz"] )
def UpperCAmelCase_ ( self : Union[str, Any] ) -> int:
'''simple docstring'''
lowerCAmelCase_ : int = BasicTokenizer(do_lower_case=lowerCAmelCase__ )
self.assertListEqual(
tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) ,["hello", "!", "how", "are", "you", "?"] )
self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) ,["hello"] )
def UpperCAmelCase_ ( self : List[Any] ) -> List[str]:
'''simple docstring'''
lowerCAmelCase_ : str = BasicTokenizer(do_lower_case=lowerCAmelCase__ ,strip_accents=lowerCAmelCase__ )
self.assertListEqual(
tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) ,["hällo", "!", "how", "are", "you", "?"] )
self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) ,["h\u00E9llo"] )
def UpperCAmelCase_ ( self : Optional[int] ) -> Union[str, Any]:
'''simple docstring'''
lowerCAmelCase_ : List[Any] = BasicTokenizer(do_lower_case=lowerCAmelCase__ ,strip_accents=lowerCAmelCase__ )
self.assertListEqual(
tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) ,["hallo", "!", "how", "are", "you", "?"] )
self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) ,["hello"] )
def UpperCAmelCase_ ( self : Dict ) -> Dict:
'''simple docstring'''
lowerCAmelCase_ : Tuple = BasicTokenizer(do_lower_case=lowerCAmelCase__ )
self.assertListEqual(
tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) ,["hallo", "!", "how", "are", "you", "?"] )
self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) ,["hello"] )
def UpperCAmelCase_ ( self : int ) -> str:
'''simple docstring'''
lowerCAmelCase_ : Optional[int] = BasicTokenizer(do_lower_case=lowerCAmelCase__ )
self.assertListEqual(
tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) ,["HeLLo", "!", "how", "Are", "yoU", "?"] )
def UpperCAmelCase_ ( self : Dict ) -> List[str]:
'''simple docstring'''
lowerCAmelCase_ : Any = BasicTokenizer(do_lower_case=lowerCAmelCase__ ,strip_accents=lowerCAmelCase__ )
self.assertListEqual(
tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) ,["HäLLo", "!", "how", "Are", "yoU", "?"] )
def UpperCAmelCase_ ( self : Dict ) -> Optional[int]:
'''simple docstring'''
lowerCAmelCase_ : Optional[int] = BasicTokenizer(do_lower_case=lowerCAmelCase__ ,strip_accents=lowerCAmelCase__ )
self.assertListEqual(
tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) ,["HaLLo", "!", "how", "Are", "yoU", "?"] )
def UpperCAmelCase_ ( self : Tuple ) -> List[Any]:
'''simple docstring'''
lowerCAmelCase_ : Optional[Any] = BasicTokenizer(do_lower_case=lowerCAmelCase__ ,never_split=["[UNK]"] )
self.assertListEqual(
tokenizer.tokenize(" \tHeLLo!how \n Are yoU? [UNK]" ) ,["HeLLo", "!", "how", "Are", "yoU", "?", "[UNK]"] )
def UpperCAmelCase_ ( self : Optional[int] ) -> str:
'''simple docstring'''
lowerCAmelCase_ : Optional[Any] = ["[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing"]
lowerCAmelCase_ : Dict = {}
for i, token in enumerate(lowerCAmelCase__ ):
lowerCAmelCase_ : str = i
lowerCAmelCase_ : Any = WordpieceTokenizer(vocab=lowerCAmelCase__ ,unk_token="[UNK]" )
self.assertListEqual(tokenizer.tokenize("" ) ,[] )
self.assertListEqual(tokenizer.tokenize("unwanted running" ) ,["un", "##want", "##ed", "runn", "##ing"] )
self.assertListEqual(tokenizer.tokenize("unwantedX running" ) ,["[UNK]", "runn", "##ing"] )
def UpperCAmelCase_ ( self : Optional[Any] ) -> List[Any]:
'''simple docstring'''
self.assertTrue(_is_whitespace(" " ) )
self.assertTrue(_is_whitespace("\t" ) )
self.assertTrue(_is_whitespace("\r" ) )
self.assertTrue(_is_whitespace("\n" ) )
self.assertTrue(_is_whitespace("\u00A0" ) )
self.assertFalse(_is_whitespace("A" ) )
self.assertFalse(_is_whitespace("-" ) )
def UpperCAmelCase_ ( self : Optional[Any] ) -> str:
'''simple docstring'''
self.assertTrue(_is_control("\u0005" ) )
self.assertFalse(_is_control("A" ) )
self.assertFalse(_is_control(" " ) )
self.assertFalse(_is_control("\t" ) )
self.assertFalse(_is_control("\r" ) )
def UpperCAmelCase_ ( self : Union[str, Any] ) -> Tuple:
'''simple docstring'''
self.assertTrue(_is_punctuation("-" ) )
self.assertTrue(_is_punctuation("$" ) )
self.assertTrue(_is_punctuation("`" ) )
self.assertTrue(_is_punctuation("." ) )
self.assertFalse(_is_punctuation("A" ) )
self.assertFalse(_is_punctuation(" " ) )
def UpperCAmelCase_ ( self : Union[str, Any] ) -> Union[str, Any]:
'''simple docstring'''
lowerCAmelCase_ : Any = self.get_tokenizer()
lowerCAmelCase_ : List[Any] = self.get_rust_tokenizer()
# Example taken from the issue https://github.com/huggingface/tokenizers/issues/340
self.assertListEqual([tokenizer.tokenize(lowerCAmelCase__ ) for t in ["Test", "\xad", "test"]] ,[["[UNK]"], [], ["[UNK]"]] )
self.assertListEqual(
[rust_tokenizer.tokenize(lowerCAmelCase__ ) for t in ["Test", "\xad", "test"]] ,[["[UNK]"], [], ["[UNK]"]] )
@slow
def UpperCAmelCase_ ( self : List[str] ) -> Optional[int]:
'''simple docstring'''
lowerCAmelCase_ : List[Any] = self.tokenizer_class.from_pretrained("google/mobilebert-uncased" )
lowerCAmelCase_ : Union[str, Any] = tokenizer.encode("sequence builders" ,add_special_tokens=lowerCAmelCase__ )
lowerCAmelCase_ : Any = tokenizer.encode("multi-sequence build" ,add_special_tokens=lowerCAmelCase__ )
lowerCAmelCase_ : Dict = tokenizer.build_inputs_with_special_tokens(lowerCAmelCase__ )
lowerCAmelCase_ : List[Any] = tokenizer.build_inputs_with_special_tokens(lowerCAmelCase__ ,lowerCAmelCase__ )
assert encoded_sentence == [1_01] + text + [1_02]
assert encoded_pair == [1_01] + text + [1_02] + text_a + [1_02]
def UpperCAmelCase_ ( self : str ) -> Dict:
'''simple docstring'''
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ):
lowerCAmelCase_ : Tuple = self.rust_tokenizer_class.from_pretrained(lowerCAmelCase__ ,**lowerCAmelCase__ )
lowerCAmelCase_ : List[str] = f'''A, naïve {tokenizer_r.mask_token} AllenNLP sentence.'''
lowerCAmelCase_ : str = tokenizer_r.encode_plus(
lowerCAmelCase__ ,return_attention_mask=lowerCAmelCase__ ,return_token_type_ids=lowerCAmelCase__ ,return_offsets_mapping=lowerCAmelCase__ ,add_special_tokens=lowerCAmelCase__ ,)
lowerCAmelCase_ : Dict = tokenizer_r.do_lower_case if hasattr(lowerCAmelCase__ ,"do_lower_case" ) else False
lowerCAmelCase_ : str = (
[
((0, 0), tokenizer_r.cls_token),
((0, 1), "A"),
((1, 2), ","),
((3, 5), "na"),
((5, 6), "##ï"),
((6, 8), "##ve"),
((9, 15), tokenizer_r.mask_token),
((16, 21), "Allen"),
((21, 23), "##NL"),
((23, 24), "##P"),
((25, 33), "sentence"),
((33, 34), "."),
((0, 0), tokenizer_r.sep_token),
]
if not do_lower_case
else [
((0, 0), tokenizer_r.cls_token),
((0, 1), "a"),
((1, 2), ","),
((3, 8), "naive"),
((9, 15), tokenizer_r.mask_token),
((16, 21), "allen"),
((21, 23), "##nl"),
((23, 24), "##p"),
((25, 33), "sentence"),
((33, 34), "."),
((0, 0), tokenizer_r.sep_token),
]
)
self.assertEqual(
[e[1] for e in expected_results] ,tokenizer_r.convert_ids_to_tokens(tokens["input_ids"] ) )
self.assertEqual([e[0] for e in expected_results] ,tokens["offset_mapping"] )
def UpperCAmelCase_ ( self : int ) -> int:
'''simple docstring'''
lowerCAmelCase_ : int = ["的", "人", "有"]
lowerCAmelCase_ : Optional[Any] = "".join(lowerCAmelCase__ )
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ):
lowerCAmelCase_ : List[Any] = True
lowerCAmelCase_ : Optional[Any] = self.tokenizer_class.from_pretrained(lowerCAmelCase__ ,**lowerCAmelCase__ )
lowerCAmelCase_ : List[str] = self.rust_tokenizer_class.from_pretrained(lowerCAmelCase__ ,**lowerCAmelCase__ )
lowerCAmelCase_ : str = tokenizer_p.encode(lowerCAmelCase__ ,add_special_tokens=lowerCAmelCase__ )
lowerCAmelCase_ : Union[str, Any] = tokenizer_r.encode(lowerCAmelCase__ ,add_special_tokens=lowerCAmelCase__ )
lowerCAmelCase_ : Dict = tokenizer_r.convert_ids_to_tokens(lowerCAmelCase__ )
lowerCAmelCase_ : List[Any] = tokenizer_p.convert_ids_to_tokens(lowerCAmelCase__ )
# it is expected that each Chinese character is not preceded by "##"
self.assertListEqual(lowerCAmelCase__ ,lowerCAmelCase__ )
self.assertListEqual(lowerCAmelCase__ ,lowerCAmelCase__ )
lowerCAmelCase_ : int = False
lowerCAmelCase_ : Optional[Any] = self.rust_tokenizer_class.from_pretrained(lowerCAmelCase__ ,**lowerCAmelCase__ )
lowerCAmelCase_ : Union[str, Any] = self.tokenizer_class.from_pretrained(lowerCAmelCase__ ,**lowerCAmelCase__ )
lowerCAmelCase_ : Tuple = tokenizer_r.encode(lowerCAmelCase__ ,add_special_tokens=lowerCAmelCase__ )
lowerCAmelCase_ : str = tokenizer_p.encode(lowerCAmelCase__ ,add_special_tokens=lowerCAmelCase__ )
lowerCAmelCase_ : Dict = tokenizer_r.convert_ids_to_tokens(lowerCAmelCase__ )
lowerCAmelCase_ : Union[str, Any] = tokenizer_p.convert_ids_to_tokens(lowerCAmelCase__ )
# it is expected that only the first Chinese character is not preceded by "##".
lowerCAmelCase_ : str = [
f'''##{token}''' if idx != 0 else token for idx, token in enumerate(lowerCAmelCase__ )
]
self.assertListEqual(lowerCAmelCase__ ,lowerCAmelCase__ )
self.assertListEqual(lowerCAmelCase__ ,lowerCAmelCase__ )
| 659 |
import json
import os
from functools import lru_cache
from typing import Dict, List, Optional, Tuple, Union
import regex as re
from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...tokenization_utils_base import BatchEncoding, EncodedInput
from ...utils import PaddingStrategy, logging
_lowercase = logging.get_logger(__name__)
_lowercase = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt'''}
# See all LED models at https://huggingface.co/models?filter=LED
_lowercase = {
'''vocab_file''': {
'''allenai/led-base-16384''': '''https://huggingface.co/allenai/led-base-16384/resolve/main/vocab.json''',
},
'''merges_file''': {
'''allenai/led-base-16384''': '''https://huggingface.co/allenai/led-base-16384/resolve/main/merges.txt''',
},
'''tokenizer_file''': {
'''allenai/led-base-16384''': '''https://huggingface.co/allenai/led-base-16384/resolve/main/tokenizer.json''',
},
}
_lowercase = {
'''allenai/led-base-16384''': 16384,
}
@lru_cache()
# Copied from transformers.models.bart.tokenization_bart.bytes_to_unicode
def UpperCamelCase ( ):
lowerCAmelCase_ : Optional[int] = (
list(range(ord("!") , ord("~") + 1)) + list(range(ord("¡") , ord("¬") + 1)) + list(range(ord("®") , ord("ÿ") + 1))
)
lowerCAmelCase_ : List[Any] = bs[:]
lowerCAmelCase_ : Optional[int] = 0
for b in range(2**8):
if b not in bs:
bs.append(snake_case__)
cs.append(2**8 + n)
n += 1
lowerCAmelCase_ : Tuple = [chr(snake_case__) for n in cs]
return dict(zip(snake_case__ , snake_case__))
def UpperCamelCase ( snake_case__):
lowerCAmelCase_ : str = set()
lowerCAmelCase_ : List[Any] = word[0]
for char in word[1:]:
pairs.add((prev_char, char))
lowerCAmelCase_ : Union[str, Any] = char
return pairs
class __snake_case ( snake_case__ ):
"""simple docstring"""
UpperCamelCase_ = VOCAB_FILES_NAMES
UpperCamelCase_ = PRETRAINED_VOCAB_FILES_MAP
UpperCamelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
UpperCamelCase_ = ['input_ids', 'attention_mask']
def __init__( self : int ,lowerCAmelCase__ : Tuple ,lowerCAmelCase__ : Any ,lowerCAmelCase__ : Tuple="replace" ,lowerCAmelCase__ : Optional[int]="<s>" ,lowerCAmelCase__ : Optional[int]="</s>" ,lowerCAmelCase__ : Tuple="</s>" ,lowerCAmelCase__ : int="<s>" ,lowerCAmelCase__ : Union[str, Any]="<unk>" ,lowerCAmelCase__ : str="<pad>" ,lowerCAmelCase__ : Tuple="<mask>" ,lowerCAmelCase__ : Optional[int]=False ,**lowerCAmelCase__ : Tuple ,) -> Any:
'''simple docstring'''
lowerCAmelCase_ : int = AddedToken(lowerCAmelCase__ ,lstrip=lowerCAmelCase__ ,rstrip=lowerCAmelCase__ ) if isinstance(lowerCAmelCase__ ,lowerCAmelCase__ ) else bos_token
lowerCAmelCase_ : int = AddedToken(lowerCAmelCase__ ,lstrip=lowerCAmelCase__ ,rstrip=lowerCAmelCase__ ) if isinstance(lowerCAmelCase__ ,lowerCAmelCase__ ) else eos_token
lowerCAmelCase_ : int = AddedToken(lowerCAmelCase__ ,lstrip=lowerCAmelCase__ ,rstrip=lowerCAmelCase__ ) if isinstance(lowerCAmelCase__ ,lowerCAmelCase__ ) else sep_token
lowerCAmelCase_ : Any = AddedToken(lowerCAmelCase__ ,lstrip=lowerCAmelCase__ ,rstrip=lowerCAmelCase__ ) if isinstance(lowerCAmelCase__ ,lowerCAmelCase__ ) else cls_token
lowerCAmelCase_ : Tuple = AddedToken(lowerCAmelCase__ ,lstrip=lowerCAmelCase__ ,rstrip=lowerCAmelCase__ ) if isinstance(lowerCAmelCase__ ,lowerCAmelCase__ ) else unk_token
lowerCAmelCase_ : Any = AddedToken(lowerCAmelCase__ ,lstrip=lowerCAmelCase__ ,rstrip=lowerCAmelCase__ ) if isinstance(lowerCAmelCase__ ,lowerCAmelCase__ ) else pad_token
# Mask token behave like a normal word, i.e. include the space before it
lowerCAmelCase_ : Optional[int] = AddedToken(lowerCAmelCase__ ,lstrip=lowerCAmelCase__ ,rstrip=lowerCAmelCase__ ) if isinstance(lowerCAmelCase__ ,lowerCAmelCase__ ) else mask_token
super().__init__(
errors=lowerCAmelCase__ ,bos_token=lowerCAmelCase__ ,eos_token=lowerCAmelCase__ ,unk_token=lowerCAmelCase__ ,sep_token=lowerCAmelCase__ ,cls_token=lowerCAmelCase__ ,pad_token=lowerCAmelCase__ ,mask_token=lowerCAmelCase__ ,add_prefix_space=lowerCAmelCase__ ,**lowerCAmelCase__ ,)
with open(lowerCAmelCase__ ,encoding="utf-8" ) as vocab_handle:
lowerCAmelCase_ : List[str] = json.load(lowerCAmelCase__ )
lowerCAmelCase_ : Optional[int] = {v: k for k, v in self.encoder.items()}
lowerCAmelCase_ : Optional[int] = errors # how to handle errors in decoding
lowerCAmelCase_ : Optional[int] = bytes_to_unicode()
lowerCAmelCase_ : str = {v: k for k, v in self.byte_encoder.items()}
with open(lowerCAmelCase__ ,encoding="utf-8" ) as merges_handle:
lowerCAmelCase_ : List[str] = merges_handle.read().split("\n" )[1:-1]
lowerCAmelCase_ : List[Any] = [tuple(merge.split() ) for merge in bpe_merges]
lowerCAmelCase_ : Union[str, Any] = dict(zip(lowerCAmelCase__ ,range(len(lowerCAmelCase__ ) ) ) )
lowerCAmelCase_ : Dict = {}
lowerCAmelCase_ : List[str] = add_prefix_space
# Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
lowerCAmelCase_ : Any = re.compile(R"'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+" )
@property
# Copied from transformers.models.bart.tokenization_bart.BartTokenizer.vocab_size
def UpperCAmelCase_ ( self : Dict ) -> Dict:
'''simple docstring'''
return len(self.encoder )
def UpperCAmelCase_ ( self : Dict ) -> str:
'''simple docstring'''
return dict(self.encoder ,**self.added_tokens_encoder )
def UpperCAmelCase_ ( self : Tuple ,lowerCAmelCase__ : Dict ) -> Dict:
'''simple docstring'''
if token in self.cache:
return self.cache[token]
lowerCAmelCase_ : Union[str, Any] = tuple(lowerCAmelCase__ )
lowerCAmelCase_ : str = get_pairs(lowerCAmelCase__ )
if not pairs:
return token
while True:
lowerCAmelCase_ : Optional[int] = min(lowerCAmelCase__ ,key=lambda lowerCAmelCase__ : self.bpe_ranks.get(lowerCAmelCase__ ,float("inf" ) ) )
if bigram not in self.bpe_ranks:
break
lowerCAmelCase_ , lowerCAmelCase_ : Optional[Any] = bigram
lowerCAmelCase_ : Tuple = []
lowerCAmelCase_ : str = 0
while i < len(lowerCAmelCase__ ):
try:
lowerCAmelCase_ : Union[str, Any] = word.index(lowerCAmelCase__ ,lowerCAmelCase__ )
except ValueError:
new_word.extend(word[i:] )
break
else:
new_word.extend(word[i:j] )
lowerCAmelCase_ : List[str] = j
if word[i] == first and i < len(lowerCAmelCase__ ) - 1 and word[i + 1] == second:
new_word.append(first + second )
i += 2
else:
new_word.append(word[i] )
i += 1
lowerCAmelCase_ : Optional[int] = tuple(lowerCAmelCase__ )
lowerCAmelCase_ : Tuple = new_word
if len(lowerCAmelCase__ ) == 1:
break
else:
lowerCAmelCase_ : Dict = get_pairs(lowerCAmelCase__ )
lowerCAmelCase_ : Optional[Any] = " ".join(lowerCAmelCase__ )
lowerCAmelCase_ : Optional[Any] = word
return word
def UpperCAmelCase_ ( self : List[str] ,lowerCAmelCase__ : Dict ) -> Optional[Any]:
'''simple docstring'''
lowerCAmelCase_ : Any = []
for token in re.findall(self.pat ,lowerCAmelCase__ ):
lowerCAmelCase_ : Optional[int] = "".join(
self.byte_encoder[b] for b in token.encode("utf-8" ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
bpe_tokens.extend(bpe_token for bpe_token in self.bpe(lowerCAmelCase__ ).split(" " ) )
return bpe_tokens
def UpperCAmelCase_ ( self : Union[str, Any] ,lowerCAmelCase__ : Union[str, Any] ) -> Tuple:
'''simple docstring'''
return self.encoder.get(lowerCAmelCase__ ,self.encoder.get(self.unk_token ) )
def UpperCAmelCase_ ( self : Tuple ,lowerCAmelCase__ : Union[str, Any] ) -> Optional[int]:
'''simple docstring'''
return self.decoder.get(lowerCAmelCase__ )
def UpperCAmelCase_ ( self : List[Any] ,lowerCAmelCase__ : List[Any] ) -> Any:
'''simple docstring'''
lowerCAmelCase_ : int = "".join(lowerCAmelCase__ )
lowerCAmelCase_ : Dict = bytearray([self.byte_decoder[c] for c in text] ).decode("utf-8" ,errors=self.errors )
return text
def UpperCAmelCase_ ( self : Tuple ,lowerCAmelCase__ : str ,lowerCAmelCase__ : Optional[str] = None ) -> Tuple[str]:
'''simple docstring'''
if not os.path.isdir(lowerCAmelCase__ ):
logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' )
return
lowerCAmelCase_ : Optional[int] = os.path.join(
lowerCAmelCase__ ,(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] )
lowerCAmelCase_ : List[str] = os.path.join(
lowerCAmelCase__ ,(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"] )
with open(lowerCAmelCase__ ,"w" ,encoding="utf-8" ) as f:
f.write(json.dumps(self.encoder ,indent=2 ,sort_keys=lowerCAmelCase__ ,ensure_ascii=lowerCAmelCase__ ) + "\n" )
lowerCAmelCase_ : Dict = 0
with open(lowerCAmelCase__ ,"w" ,encoding="utf-8" ) as writer:
writer.write("#version: 0.2\n" )
for bpe_tokens, token_index in sorted(self.bpe_ranks.items() ,key=lambda lowerCAmelCase__ : kv[1] ):
if index != token_index:
logger.warning(
f'''Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.'''
" Please check that the tokenizer is not corrupted!" )
lowerCAmelCase_ : List[Any] = token_index
writer.write(" ".join(lowerCAmelCase__ ) + "\n" )
index += 1
return vocab_file, merge_file
def UpperCAmelCase_ ( self : str ,lowerCAmelCase__ : List[int] ,lowerCAmelCase__ : Optional[List[int]] = None ) -> List[int]:
'''simple docstring'''
if token_ids_a is None:
return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
lowerCAmelCase_ : Union[str, Any] = [self.cls_token_id]
lowerCAmelCase_ : str = [self.sep_token_id]
return cls + token_ids_a + sep + sep + token_ids_a + sep
def UpperCAmelCase_ ( self : List[Any] ,lowerCAmelCase__ : List[int] ,lowerCAmelCase__ : Optional[List[int]] = None ,lowerCAmelCase__ : bool = False ) -> List[int]:
'''simple docstring'''
if already_has_special_tokens:
return super().get_special_tokens_mask(
token_ids_a=lowerCAmelCase__ ,token_ids_a=lowerCAmelCase__ ,already_has_special_tokens=lowerCAmelCase__ )
if token_ids_a is None:
return [1] + ([0] * len(lowerCAmelCase__ )) + [1]
return [1] + ([0] * len(lowerCAmelCase__ )) + [1, 1] + ([0] * len(lowerCAmelCase__ )) + [1]
def UpperCAmelCase_ ( self : List[Any] ,lowerCAmelCase__ : List[int] ,lowerCAmelCase__ : Optional[List[int]] = None ) -> List[int]:
'''simple docstring'''
lowerCAmelCase_ : Optional[int] = [self.sep_token_id]
lowerCAmelCase_ : Tuple = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
def UpperCAmelCase_ ( self : Union[str, Any] ,lowerCAmelCase__ : Union[str, Any] ,lowerCAmelCase__ : Optional[int]=False ,**lowerCAmelCase__ : str ) -> Union[str, Any]:
'''simple docstring'''
lowerCAmelCase_ : Optional[int] = kwargs.pop("add_prefix_space" ,self.add_prefix_space )
if (is_split_into_words or add_prefix_space) and (len(lowerCAmelCase__ ) > 0 and not text[0].isspace()):
lowerCAmelCase_ : List[str] = " " + text
return (text, kwargs)
def UpperCAmelCase_ ( self : List[str] ,lowerCAmelCase__ : Union[Dict[str, EncodedInput], BatchEncoding] ,lowerCAmelCase__ : Optional[int] = None ,lowerCAmelCase__ : PaddingStrategy = PaddingStrategy.DO_NOT_PAD ,lowerCAmelCase__ : Optional[int] = None ,lowerCAmelCase__ : Optional[bool] = None ,) -> dict:
'''simple docstring'''
lowerCAmelCase_ : int = super()._pad(
encoded_inputs=lowerCAmelCase__ ,max_length=lowerCAmelCase__ ,padding_strategy=lowerCAmelCase__ ,pad_to_multiple_of=lowerCAmelCase__ ,return_attention_mask=lowerCAmelCase__ ,)
# Load from model defaults
if return_attention_mask is None:
lowerCAmelCase_ : List[Any] = "attention_mask" in self.model_input_names
if return_attention_mask and "global_attention_mask" in encoded_inputs:
lowerCAmelCase_ : Dict = encoded_inputs[self.model_input_names[0]]
# `global_attention_mask` need to have the same length as other (sequential) inputs.
lowerCAmelCase_ : List[Any] = len(encoded_inputs["global_attention_mask"] ) != len(lowerCAmelCase__ )
if needs_to_be_padded:
lowerCAmelCase_ : Union[str, Any] = len(lowerCAmelCase__ ) - len(encoded_inputs["global_attention_mask"] )
if self.padding_side == "right":
# Use `-1` since `0` in `global_attention_mask` means `local attention` instead of `not to attend`
lowerCAmelCase_ : Optional[int] = (
encoded_inputs["global_attention_mask"] + [-1] * difference
)
elif self.padding_side == "left":
lowerCAmelCase_ : List[Any] = [-1] * difference + encoded_inputs[
"global_attention_mask"
]
else:
raise ValueError("Invalid padding strategy:" + str(self.padding_side ) )
return encoded_inputs
| 659 | 1 |
import logging
import os
import random
import sys
from dataclasses import dataclass, field
from typing import Optional
import datasets
import evaluate
import numpy as np
from datasets import load_dataset
import transformers
from transformers import (
AutoConfig,
AutoModelForSequenceClassification,
AutoTokenizer,
DataCollatorWithPadding,
EvalPrediction,
HfArgumentParser,
Trainer,
TrainingArguments,
default_data_collator,
set_seed,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version('''4.31.0''')
require_version('''datasets>=1.8.0''', '''To fix: pip install -r examples/pytorch/text-classification/requirements.txt''')
_lowercase = logging.getLogger(__name__)
@dataclass
class __snake_case :
"""simple docstring"""
UpperCamelCase_ = field(
default=1_2_8 , metadata={
'help': (
'The maximum total input sequence length after tokenization. Sequences longer '
'than this will be truncated, sequences shorter will be padded.'
)
} , )
UpperCamelCase_ = field(
default=snake_case__ , metadata={'help': 'Overwrite the cached preprocessed datasets or not.'} )
UpperCamelCase_ = field(
default=snake_case__ , metadata={
'help': (
'Whether to pad all samples to `max_seq_length`. '
'If False, will pad the samples dynamically when batching to the maximum length in the batch.'
)
} , )
UpperCamelCase_ = field(
default=snake_case__ , metadata={
'help': (
'For debugging purposes or quicker training, truncate the number of training examples to this '
'value if set.'
)
} , )
UpperCamelCase_ = field(
default=snake_case__ , metadata={
'help': (
'For debugging purposes or quicker training, truncate the number of evaluation examples to this '
'value if set.'
)
} , )
UpperCamelCase_ = field(
default=snake_case__ , metadata={
'help': (
'For debugging purposes or quicker training, truncate the number of prediction examples to this '
'value if set.'
)
} , )
@dataclass
class __snake_case :
"""simple docstring"""
UpperCamelCase_ = field(
default=snake_case__ , metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'} )
UpperCamelCase_ = field(
default=snake_case__ , metadata={'help': 'Evaluation language. Also train language if `train_language` is set to None.'} )
UpperCamelCase_ = field(
default=snake_case__ , metadata={'help': 'Train language if it is different from the evaluation language.'} )
UpperCamelCase_ = field(
default=snake_case__ , metadata={'help': 'Pretrained config name or path if not the same as model_name'} )
UpperCamelCase_ = field(
default=snake_case__ , metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'} )
UpperCamelCase_ = field(
default=snake_case__ , metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'} , )
UpperCamelCase_ = field(
default=snake_case__ , metadata={'help': 'arg to indicate if tokenizer should do lower case in AutoTokenizer.from_pretrained()'} , )
UpperCamelCase_ = field(
default=snake_case__ , metadata={'help': 'Whether to use one of the fast tokenizer (backed by the tokenizers library) or not.'} , )
UpperCamelCase_ = field(
default='main' , metadata={'help': 'The specific model version to use (can be a branch name, tag name or commit id).'} , )
UpperCamelCase_ = field(
default=snake_case__ , metadata={
'help': (
'Will use the token generated when running `huggingface-cli login` (necessary to use this script '
'with private models).'
)
} , )
UpperCamelCase_ = field(
default=snake_case__ , metadata={'help': 'Will enable to load a pretrained model whose head dimensions are different.'} , )
def UpperCamelCase ( ):
# See all possible arguments in src/transformers/training_args.py
# or by passing the --help flag to this script.
# We now keep distinct sets of args, for a cleaner separation of concerns.
lowerCAmelCase_ : Optional[Any] = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ : Optional[int] = parser.parse_args_into_dataclasses()
# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
# information sent is the one passed as arguments along with your Python/PyTorch versions.
send_example_telemetry("run_xnli" , snake_case__)
# Setup logging
logging.basicConfig(
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , handlers=[logging.StreamHandler(sys.stdout)] , )
if training_args.should_log:
# The default of training_args.log_level is passive, so we set log level at info here to have that default.
transformers.utils.logging.set_verbosity_info()
lowerCAmelCase_ : List[str] = training_args.get_process_log_level()
logger.setLevel(snake_case__)
datasets.utils.logging.set_verbosity(snake_case__)
transformers.utils.logging.set_verbosity(snake_case__)
transformers.utils.logging.enable_default_handler()
transformers.utils.logging.enable_explicit_format()
# Log on each process the small summary:
logger.warning(
F'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}'''
+ F'''distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fpaa}''')
logger.info(F'''Training/evaluation parameters {training_args}''')
# Detecting last checkpoint.
lowerCAmelCase_ : List[str] = None
if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
lowerCAmelCase_ : Optional[Any] = get_last_checkpoint(training_args.output_dir)
if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
raise ValueError(
F'''Output directory ({training_args.output_dir}) already exists and is not empty. '''
"Use --overwrite_output_dir to overcome.")
elif last_checkpoint is not None:
logger.info(
F'''Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change '''
"the `--output_dir` or add `--overwrite_output_dir` to train from scratch.")
# Set seed before initializing model.
set_seed(training_args.seed)
# In distributed training, the load_dataset function guarantees that only one local process can concurrently
# download the dataset.
# Downloading and loading xnli dataset from the hub.
if training_args.do_train:
if model_args.train_language is None:
lowerCAmelCase_ : List[str] = load_dataset(
"xnli" , model_args.language , split="train" , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , )
else:
lowerCAmelCase_ : str = load_dataset(
"xnli" , model_args.train_language , split="train" , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , )
lowerCAmelCase_ : Any = train_dataset.features["label"].names
if training_args.do_eval:
lowerCAmelCase_ : int = load_dataset(
"xnli" , model_args.language , split="validation" , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , )
lowerCAmelCase_ : str = eval_dataset.features["label"].names
if training_args.do_predict:
lowerCAmelCase_ : Union[str, Any] = load_dataset(
"xnli" , model_args.language , split="test" , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , )
lowerCAmelCase_ : Union[str, Any] = predict_dataset.features["label"].names
# Labels
lowerCAmelCase_ : List[Any] = len(snake_case__)
# Load pretrained model and tokenizer
# In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently
# download model & vocab.
lowerCAmelCase_ : str = AutoConfig.from_pretrained(
model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=snake_case__ , idalabel={str(snake_case__): label for i, label in enumerate(snake_case__)} , labelaid={label: i for i, label in enumerate(snake_case__)} , finetuning_task="xnli" , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , )
lowerCAmelCase_ : int = AutoTokenizer.from_pretrained(
model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , do_lower_case=model_args.do_lower_case , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast_tokenizer , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , )
lowerCAmelCase_ : List[str] = AutoModelForSequenceClassification.from_pretrained(
model_args.model_name_or_path , from_tf=bool(".ckpt" in model_args.model_name_or_path) , config=snake_case__ , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ignore_mismatched_sizes=model_args.ignore_mismatched_sizes , )
# Preprocessing the datasets
# Padding strategy
if data_args.pad_to_max_length:
lowerCAmelCase_ : Tuple = "max_length"
else:
# We will pad later, dynamically at batch creation, to the max sequence length in each batch
lowerCAmelCase_ : List[Any] = False
def preprocess_function(snake_case__):
# Tokenize the texts
return tokenizer(
examples["premise"] , examples["hypothesis"] , padding=snake_case__ , max_length=data_args.max_seq_length , truncation=snake_case__ , )
if training_args.do_train:
if data_args.max_train_samples is not None:
lowerCAmelCase_ : str = min(len(snake_case__) , data_args.max_train_samples)
lowerCAmelCase_ : List[str] = train_dataset.select(range(snake_case__))
with training_args.main_process_first(desc="train dataset map pre-processing"):
lowerCAmelCase_ : List[str] = train_dataset.map(
snake_case__ , batched=snake_case__ , load_from_cache_file=not data_args.overwrite_cache , desc="Running tokenizer on train dataset" , )
# Log a few random samples from the training set:
for index in random.sample(range(len(snake_case__)) , 3):
logger.info(F'''Sample {index} of the training set: {train_dataset[index]}.''')
if training_args.do_eval:
if data_args.max_eval_samples is not None:
lowerCAmelCase_ : Union[str, Any] = min(len(snake_case__) , data_args.max_eval_samples)
lowerCAmelCase_ : List[Any] = eval_dataset.select(range(snake_case__))
with training_args.main_process_first(desc="validation dataset map pre-processing"):
lowerCAmelCase_ : Optional[int] = eval_dataset.map(
snake_case__ , batched=snake_case__ , load_from_cache_file=not data_args.overwrite_cache , desc="Running tokenizer on validation dataset" , )
if training_args.do_predict:
if data_args.max_predict_samples is not None:
lowerCAmelCase_ : Optional[int] = min(len(snake_case__) , data_args.max_predict_samples)
lowerCAmelCase_ : str = predict_dataset.select(range(snake_case__))
with training_args.main_process_first(desc="prediction dataset map pre-processing"):
lowerCAmelCase_ : Union[str, Any] = predict_dataset.map(
snake_case__ , batched=snake_case__ , load_from_cache_file=not data_args.overwrite_cache , desc="Running tokenizer on prediction dataset" , )
# Get the metric function
lowerCAmelCase_ : Any = evaluate.load("xnli")
# You can define your custom compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a
# predictions and label_ids field) and has to return a dictionary string to float.
def compute_metrics(snake_case__):
lowerCAmelCase_ : Tuple = p.predictions[0] if isinstance(p.predictions , snake_case__) else p.predictions
lowerCAmelCase_ : Dict = np.argmax(snake_case__ , axis=1)
return metric.compute(predictions=snake_case__ , references=p.label_ids)
# Data collator will default to DataCollatorWithPadding, so we change it if we already did the padding.
if data_args.pad_to_max_length:
lowerCAmelCase_ : Dict = default_data_collator
elif training_args.fpaa:
lowerCAmelCase_ : Tuple = DataCollatorWithPadding(snake_case__ , pad_to_multiple_of=8)
else:
lowerCAmelCase_ : Optional[int] = None
# Initialize our Trainer
lowerCAmelCase_ : Optional[Any] = Trainer(
model=snake_case__ , args=snake_case__ , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , compute_metrics=snake_case__ , tokenizer=snake_case__ , data_collator=snake_case__ , )
# Training
if training_args.do_train:
lowerCAmelCase_ : Optional[Any] = None
if training_args.resume_from_checkpoint is not None:
lowerCAmelCase_ : Dict = training_args.resume_from_checkpoint
elif last_checkpoint is not None:
lowerCAmelCase_ : Optional[Any] = last_checkpoint
lowerCAmelCase_ : List[Any] = trainer.train(resume_from_checkpoint=snake_case__)
lowerCAmelCase_ : Tuple = train_result.metrics
lowerCAmelCase_ : Any = (
data_args.max_train_samples if data_args.max_train_samples is not None else len(snake_case__)
)
lowerCAmelCase_ : List[Any] = min(snake_case__ , len(snake_case__))
trainer.save_model() # Saves the tokenizer too for easy upload
trainer.log_metrics("train" , snake_case__)
trainer.save_metrics("train" , snake_case__)
trainer.save_state()
# Evaluation
if training_args.do_eval:
logger.info("*** Evaluate ***")
lowerCAmelCase_ : Optional[Any] = trainer.evaluate(eval_dataset=snake_case__)
lowerCAmelCase_ : str = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(snake_case__)
lowerCAmelCase_ : Union[str, Any] = min(snake_case__ , len(snake_case__))
trainer.log_metrics("eval" , snake_case__)
trainer.save_metrics("eval" , snake_case__)
# Prediction
if training_args.do_predict:
logger.info("*** Predict ***")
lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ : Any = trainer.predict(snake_case__ , metric_key_prefix="predict")
lowerCAmelCase_ : Tuple = (
data_args.max_predict_samples if data_args.max_predict_samples is not None else len(snake_case__)
)
lowerCAmelCase_ : List[str] = min(snake_case__ , len(snake_case__))
trainer.log_metrics("predict" , snake_case__)
trainer.save_metrics("predict" , snake_case__)
lowerCAmelCase_ : Union[str, Any] = np.argmax(snake_case__ , axis=1)
lowerCAmelCase_ : Optional[int] = os.path.join(training_args.output_dir , "predictions.txt")
if trainer.is_world_process_zero():
with open(snake_case__ , "w") as writer:
writer.write("index\tprediction\n")
for index, item in enumerate(snake_case__):
lowerCAmelCase_ : str = label_list[item]
writer.write(F'''{index}\t{item}\n''')
if __name__ == "__main__":
main()
| 659 |
import os
_lowercase = {'''I''': 1, '''V''': 5, '''X''': 10, '''L''': 50, '''C''': 100, '''D''': 500, '''M''': 1000}
def UpperCamelCase ( snake_case__):
lowerCAmelCase_ : List[str] = 0
lowerCAmelCase_ : Any = 0
while index < len(snake_case__) - 1:
lowerCAmelCase_ : Optional[Any] = SYMBOLS[numerals[index]]
lowerCAmelCase_ : int = SYMBOLS[numerals[index + 1]]
if current_value < next_value:
total_value -= current_value
else:
total_value += current_value
index += 1
total_value += SYMBOLS[numerals[index]]
return total_value
def UpperCamelCase ( snake_case__):
lowerCAmelCase_ : Optional[int] = ""
lowerCAmelCase_ : Tuple = num // 10_00
numerals += m_count * "M"
num %= 10_00
lowerCAmelCase_ : int = num // 1_00
if c_count == 9:
numerals += "CM"
c_count -= 9
elif c_count == 4:
numerals += "CD"
c_count -= 4
if c_count >= 5:
numerals += "D"
c_count -= 5
numerals += c_count * "C"
num %= 1_00
lowerCAmelCase_ : int = num // 10
if x_count == 9:
numerals += "XC"
x_count -= 9
elif x_count == 4:
numerals += "XL"
x_count -= 4
if x_count >= 5:
numerals += "L"
x_count -= 5
numerals += x_count * "X"
num %= 10
if num == 9:
numerals += "IX"
num -= 9
elif num == 4:
numerals += "IV"
num -= 4
if num >= 5:
numerals += "V"
num -= 5
numerals += num * "I"
return numerals
def UpperCamelCase ( snake_case__ = "/p089_roman.txt"):
lowerCAmelCase_ : int = 0
with open(os.path.dirname(snake_case__) + roman_numerals_filename) as filea:
lowerCAmelCase_ : List[Any] = filea.readlines()
for line in lines:
lowerCAmelCase_ : Any = line.strip()
lowerCAmelCase_ : Tuple = parse_roman_numerals(snake_case__)
lowerCAmelCase_ : List[Any] = generate_roman_numerals(snake_case__)
savings += len(snake_case__) - len(snake_case__)
return savings
if __name__ == "__main__":
print(f"{solution() = }")
| 659 | 1 |
def UpperCamelCase ( snake_case__):
lowerCAmelCase_ : list[list[float]] = []
for data in source_data:
for i, el in enumerate(snake_case__):
if len(snake_case__) < i + 1:
data_lists.append([])
data_lists[i].append(float(snake_case__))
return data_lists
def UpperCamelCase ( snake_case__ , snake_case__):
lowerCAmelCase_ : list[list[float]] = []
for dlist, weight in zip(snake_case__ , snake_case__):
lowerCAmelCase_ : Optional[Any] = min(snake_case__)
lowerCAmelCase_ : Optional[int] = max(snake_case__)
lowerCAmelCase_ : list[float] = []
# for weight 0 score is 1 - actual score
if weight == 0:
for item in dlist:
try:
score.append(1 - ((item - mind) / (maxd - mind)))
except ZeroDivisionError:
score.append(1)
elif weight == 1:
for item in dlist:
try:
score.append((item - mind) / (maxd - mind))
except ZeroDivisionError:
score.append(0)
# weight not 0 or 1
else:
lowerCAmelCase_ : str = F'''Invalid weight of {weight:f} provided'''
raise ValueError(snake_case__)
score_lists.append(snake_case__)
return score_lists
def UpperCamelCase ( snake_case__):
lowerCAmelCase_ : list[float] = [0 for i in range(len(score_lists[0]))]
for slist in score_lists:
for j, ele in enumerate(snake_case__):
lowerCAmelCase_ : Any = final_scores[j] + ele
return final_scores
def UpperCamelCase ( snake_case__ , snake_case__):
lowerCAmelCase_ : Tuple = get_data(snake_case__)
lowerCAmelCase_ : List[Any] = calculate_each_score(snake_case__ , snake_case__)
lowerCAmelCase_ : Dict = generate_final_scores(snake_case__)
# append scores to source data
for i, ele in enumerate(snake_case__):
source_data[i].append(snake_case__)
return source_data
| 659 |
from transformers import HfArgumentParser, TensorFlowBenchmark, TensorFlowBenchmarkArguments
def UpperCamelCase ( ):
lowerCAmelCase_ : Dict = HfArgumentParser(snake_case__)
lowerCAmelCase_ : Dict = parser.parse_args_into_dataclasses()[0]
lowerCAmelCase_ : List[Any] = TensorFlowBenchmark(args=snake_case__)
try:
lowerCAmelCase_ : str = parser.parse_args_into_dataclasses()[0]
except ValueError as e:
lowerCAmelCase_ : Optional[Any] = "Arg --no_{0} is no longer used, please use --no-{0} instead."
lowerCAmelCase_ : Tuple = " ".join(str(snake_case__).split(" ")[:-1])
lowerCAmelCase_ : List[Any] = ""
lowerCAmelCase_ : Optional[Any] = eval(str(snake_case__).split(" ")[-1])
lowerCAmelCase_ : List[Any] = []
for arg in depreciated_args:
# arg[2:] removes '--'
if arg[2:] in TensorFlowBenchmark.deprecated_args:
# arg[5:] removes '--no_'
full_error_msg += arg_error_msg.format(arg[5:])
else:
wrong_args.append(snake_case__)
if len(snake_case__) > 0:
lowerCAmelCase_ : int = full_error_msg + begin_error_msg + str(snake_case__)
raise ValueError(snake_case__)
benchmark.run()
if __name__ == "__main__":
main()
| 659 | 1 |
from __future__ import annotations
import csv
import requests
from bsa import BeautifulSoup
def UpperCamelCase ( snake_case__ = ""):
lowerCAmelCase_ : Dict = url or "https://www.imdb.com/chart/top/?ref_=nv_mv_250"
lowerCAmelCase_ : Any = BeautifulSoup(requests.get(snake_case__).text , "html.parser")
lowerCAmelCase_ : List[Any] = soup.find_all("td" , attrs="titleColumn")
lowerCAmelCase_ : Tuple = soup.find_all("td" , class_="ratingColumn imdbRating")
return {
title.a.text: float(rating.strong.text)
for title, rating in zip(snake_case__ , snake_case__)
}
def UpperCamelCase ( snake_case__ = "IMDb_Top_250_Movies.csv"):
lowerCAmelCase_ : List[str] = get_imdb_top_aaa_movies()
with open(snake_case__ , "w" , newline="") as out_file:
lowerCAmelCase_ : int = csv.writer(snake_case__)
writer.writerow(["Movie title", "IMDb rating"])
for title, rating in movies.items():
writer.writerow([title, rating])
if __name__ == "__main__":
write_movies()
| 659 |
from collections import defaultdict
from pathlib import Path
import pandas as pd
from rouge_cli import calculate_rouge_path
from utils import calculate_rouge
_lowercase = [
'''Prosecutor: "No videos were used in the crash investigation" German papers say they saw a cell phone video of the'''
''' final seconds on board Flight 9525. The Germanwings co-pilot says he had a "previous episode of severe'''
''' depression\" German airline confirms it knew of Andreas Lubitz\'s depression years before he took control.''',
'''The Palestinian Authority officially becomes the 123rd member of the International Criminal Court. The formal'''
''' accession was marked with a ceremony at The Hague, in the Netherlands. The Palestinians signed the ICC\'s'''
''' founding Rome Statute in January. Israel and the United States opposed the Palestinians\' efforts to join the'''
''' body.''',
'''Amnesty International releases its annual report on the death penalty. The report catalogs the use of'''
''' state-sanctioned killing as a punitive measure across the globe. At least 607 people were executed around the'''
''' world in 2014, compared to 778 in 2013. The U.S. remains one of the worst offenders for imposing capital'''
''' punishment.''',
]
_lowercase = [
'''Marseille prosecutor says "so far no videos were used in the crash investigation" despite media reports .'''
''' Journalists at Bild and Paris Match are "very confident" the video clip is real, an editor says . Andreas Lubitz'''
''' had informed his Lufthansa training school of an episode of severe depression, airline says .''',
'''Membership gives the ICC jurisdiction over alleged crimes committed in Palestinian territories since last June .'''
''' Israel and the United States opposed the move, which could open the door to war crimes investigations against'''
''' Israelis .''',
'''Amnesty\'s annual death penalty report catalogs encouraging signs, but setbacks in numbers of those sentenced to'''
''' death . Organization claims that governments around the world are using the threat of terrorism to advance'''
''' executions . The number of executions worldwide has gone down by almost 22% compared with 2013, but death'''
''' sentences up by 28% .''',
]
def UpperCamelCase ( ):
lowerCAmelCase_ : Any = calculate_rouge(snake_case__ , snake_case__ , bootstrap_aggregation=snake_case__ , rouge_keys=["rouge2", "rougeL"])
assert isinstance(snake_case__ , snake_case__)
lowerCAmelCase_ : str = calculate_rouge(snake_case__ , snake_case__ , bootstrap_aggregation=snake_case__ , rouge_keys=["rouge2"])
assert (
pd.DataFrame(no_aggregation["rouge2"]).fmeasure.mean()
== pd.DataFrame(no_aggregation_just_ra["rouge2"]).fmeasure.mean()
)
def UpperCamelCase ( ):
lowerCAmelCase_ : str = "rougeLsum"
lowerCAmelCase_ : Any = calculate_rouge(snake_case__ , snake_case__ , newline_sep=snake_case__ , rouge_keys=[k])[k]
lowerCAmelCase_ : List[Any] = calculate_rouge(snake_case__ , snake_case__ , newline_sep=snake_case__ , rouge_keys=[k])[k]
assert score > score_no_sep
def UpperCamelCase ( ):
lowerCAmelCase_ : int = ["rouge1", "rouge2", "rougeL"]
lowerCAmelCase_ : List[Any] = calculate_rouge(snake_case__ , snake_case__ , newline_sep=snake_case__ , rouge_keys=snake_case__)
lowerCAmelCase_ : List[Any] = calculate_rouge(snake_case__ , snake_case__ , newline_sep=snake_case__ , rouge_keys=snake_case__)
assert score_sep == score_no_sep
def UpperCamelCase ( ):
lowerCAmelCase_ : List[str] = [
"Her older sister, Margot Frank, died in 1945, a month earlier than previously thought.",
"Marseille prosecutor says \"so far no videos were used in the crash investigation\" despite media reports .",
]
lowerCAmelCase_ : Dict = [
"Margot Frank, died in 1945, a month earlier than previously thought.",
"Prosecutor: \"No videos were used in the crash investigation\" German papers say they saw a cell phone video of"
" the final seconds on board Flight 9525.",
]
assert calculate_rouge(snake_case__ , snake_case__ , newline_sep=snake_case__) == calculate_rouge(snake_case__ , snake_case__ , newline_sep=snake_case__)
def UpperCamelCase ( ):
lowerCAmelCase_ : Optional[int] = [
"\" \"a person who has such a video needs to immediately give it to the investigators,\" prosecutor says .<n> \"it is a very disturbing scene,\" editor-in-chief of bild online tells \"erin burnett: outfront\" "
]
lowerCAmelCase_ : Any = [
" Marseille prosecutor says \"so far no videos were used in the crash investigation\" despite media reports . Journalists at Bild and Paris Match are \"very confident\" the video clip is real, an editor says . Andreas Lubitz had informed his Lufthansa training school of an episode of severe depression, airline says ."
]
lowerCAmelCase_ : Any = calculate_rouge(snake_case__ , snake_case__ , rouge_keys=["rougeLsum"] , newline_sep=snake_case__)["rougeLsum"]
lowerCAmelCase_ : Any = calculate_rouge(snake_case__ , snake_case__ , rouge_keys=["rougeLsum"])["rougeLsum"]
assert new_score > prev_score
def UpperCamelCase ( ):
lowerCAmelCase_ : int = Path("examples/seq2seq/test_data/wmt_en_ro")
lowerCAmelCase_ : Dict = calculate_rouge_path(data_dir.joinpath("test.source") , data_dir.joinpath("test.target"))
assert isinstance(snake_case__ , snake_case__)
lowerCAmelCase_ : Any = calculate_rouge_path(
data_dir.joinpath("test.source") , data_dir.joinpath("test.target") , bootstrap_aggregation=snake_case__)
assert isinstance(snake_case__ , snake_case__)
| 659 | 1 |
import os
import re
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple
import sentencepiece as spm
from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging
_lowercase = logging.get_logger(__name__)
_lowercase = {'''vocab_file''': '''spiece.model'''}
_lowercase = {
'''vocab_file''': {
'''google/bigbird-roberta-base''': '''https://huggingface.co/google/bigbird-roberta-base/resolve/main/spiece.model''',
'''google/bigbird-roberta-large''': (
'''https://huggingface.co/google/bigbird-roberta-large/resolve/main/spiece.model'''
),
'''google/bigbird-base-trivia-itc''': (
'''https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/spiece.model'''
),
}
}
_lowercase = {
'''google/bigbird-roberta-base''': 4096,
'''google/bigbird-roberta-large''': 4096,
'''google/bigbird-base-trivia-itc''': 4096,
}
class __snake_case ( snake_case__ ):
"""simple docstring"""
UpperCamelCase_ = VOCAB_FILES_NAMES
UpperCamelCase_ = PRETRAINED_VOCAB_FILES_MAP
UpperCamelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
UpperCamelCase_ = ['input_ids', 'attention_mask']
UpperCamelCase_ = []
def __init__( self : Dict ,lowerCAmelCase__ : Dict ,lowerCAmelCase__ : Any="<unk>" ,lowerCAmelCase__ : Any="<s>" ,lowerCAmelCase__ : List[Any]="</s>" ,lowerCAmelCase__ : Optional[int]="<pad>" ,lowerCAmelCase__ : int="[SEP]" ,lowerCAmelCase__ : Union[str, Any]="[MASK]" ,lowerCAmelCase__ : Union[str, Any]="[CLS]" ,lowerCAmelCase__ : Optional[Dict[str, Any]] = None ,**lowerCAmelCase__ : List[Any] ,) -> None:
'''simple docstring'''
lowerCAmelCase_ : List[str] = AddedToken(lowerCAmelCase__ ,lstrip=lowerCAmelCase__ ,rstrip=lowerCAmelCase__ ) if isinstance(lowerCAmelCase__ ,lowerCAmelCase__ ) else bos_token
lowerCAmelCase_ : List[Any] = AddedToken(lowerCAmelCase__ ,lstrip=lowerCAmelCase__ ,rstrip=lowerCAmelCase__ ) if isinstance(lowerCAmelCase__ ,lowerCAmelCase__ ) else eos_token
lowerCAmelCase_ : List[Any] = AddedToken(lowerCAmelCase__ ,lstrip=lowerCAmelCase__ ,rstrip=lowerCAmelCase__ ) if isinstance(lowerCAmelCase__ ,lowerCAmelCase__ ) else unk_token
lowerCAmelCase_ : List[Any] = AddedToken(lowerCAmelCase__ ,lstrip=lowerCAmelCase__ ,rstrip=lowerCAmelCase__ ) if isinstance(lowerCAmelCase__ ,lowerCAmelCase__ ) else pad_token
lowerCAmelCase_ : Union[str, Any] = AddedToken(lowerCAmelCase__ ,lstrip=lowerCAmelCase__ ,rstrip=lowerCAmelCase__ ) if isinstance(lowerCAmelCase__ ,lowerCAmelCase__ ) else cls_token
lowerCAmelCase_ : Tuple = AddedToken(lowerCAmelCase__ ,lstrip=lowerCAmelCase__ ,rstrip=lowerCAmelCase__ ) if isinstance(lowerCAmelCase__ ,lowerCAmelCase__ ) else sep_token
# Mask token behave like a normal word, i.e. include the space before it
lowerCAmelCase_ : Any = AddedToken(lowerCAmelCase__ ,lstrip=lowerCAmelCase__ ,rstrip=lowerCAmelCase__ ) if isinstance(lowerCAmelCase__ ,lowerCAmelCase__ ) else mask_token
lowerCAmelCase_ : Tuple = {} if sp_model_kwargs is None else sp_model_kwargs
super().__init__(
bos_token=lowerCAmelCase__ ,eos_token=lowerCAmelCase__ ,unk_token=lowerCAmelCase__ ,pad_token=lowerCAmelCase__ ,sep_token=lowerCAmelCase__ ,mask_token=lowerCAmelCase__ ,cls_token=lowerCAmelCase__ ,sp_model_kwargs=self.sp_model_kwargs ,**lowerCAmelCase__ ,)
lowerCAmelCase_ : Dict = vocab_file
lowerCAmelCase_ : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(lowerCAmelCase__ )
@property
def UpperCAmelCase_ ( self : Optional[Any] ) -> Any:
'''simple docstring'''
return self.sp_model.get_piece_size()
def UpperCAmelCase_ ( self : Any ) -> Optional[int]:
'''simple docstring'''
lowerCAmelCase_ : Optional[int] = {self.convert_ids_to_tokens(lowerCAmelCase__ ): i for i in range(self.vocab_size )}
vocab.update(self.added_tokens_encoder )
return vocab
def __getstate__( self : Tuple ) -> Any:
'''simple docstring'''
lowerCAmelCase_ : str = self.__dict__.copy()
lowerCAmelCase_ : Any = None
return state
def __setstate__( self : Tuple ,lowerCAmelCase__ : List[str] ) -> Union[str, Any]:
'''simple docstring'''
lowerCAmelCase_ : Optional[int] = d
# for backward compatibility
if not hasattr(self ,"sp_model_kwargs" ):
lowerCAmelCase_ : Tuple = {}
lowerCAmelCase_ : Dict = spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(self.vocab_file )
def UpperCAmelCase_ ( self : Optional[Any] ,lowerCAmelCase__ : str ) -> List[str]:
'''simple docstring'''
return self.sp_model.encode(lowerCAmelCase__ ,out_type=lowerCAmelCase__ )
def UpperCAmelCase_ ( self : Tuple ,lowerCAmelCase__ : Tuple ) -> List[str]:
'''simple docstring'''
return self.sp_model.piece_to_id(lowerCAmelCase__ )
def UpperCAmelCase_ ( self : Union[str, Any] ,lowerCAmelCase__ : List[str] ) -> Optional[Any]:
'''simple docstring'''
lowerCAmelCase_ : Optional[int] = self.sp_model.IdToPiece(lowerCAmelCase__ )
return token
def UpperCAmelCase_ ( self : Dict ,lowerCAmelCase__ : List[Any] ) -> Tuple:
'''simple docstring'''
lowerCAmelCase_ : Optional[Any] = []
lowerCAmelCase_ : Any = ""
lowerCAmelCase_ : Union[str, Any] = False
for token in tokens:
# make sure that special tokens are not decoded using sentencepiece model
if token in self.all_special_tokens:
if not prev_is_special:
out_string += " "
out_string += self.sp_model.decode(lowerCAmelCase__ ) + token
lowerCAmelCase_ : Union[str, Any] = True
lowerCAmelCase_ : List[str] = []
else:
current_sub_tokens.append(lowerCAmelCase__ )
lowerCAmelCase_ : Dict = False
out_string += self.sp_model.decode(lowerCAmelCase__ )
return out_string.strip()
def UpperCAmelCase_ ( self : Union[str, Any] ,lowerCAmelCase__ : List[int] ,lowerCAmelCase__ : bool = False ,lowerCAmelCase__ : bool = None ,lowerCAmelCase__ : bool = True ,**lowerCAmelCase__ : Any ,) -> str:
'''simple docstring'''
lowerCAmelCase_ : str = kwargs.pop("use_source_tokenizer" ,lowerCAmelCase__ )
lowerCAmelCase_ : int = self.convert_ids_to_tokens(lowerCAmelCase__ ,skip_special_tokens=lowerCAmelCase__ )
# To avoid mixing byte-level and unicode for byte-level BPT
# we need to build string separately for added tokens and byte-level tokens
# cf. https://github.com/huggingface/transformers/issues/1133
lowerCAmelCase_ : Optional[int] = []
lowerCAmelCase_ : Optional[int] = []
for token in filtered_tokens:
if skip_special_tokens and token in self.all_special_ids:
continue
if token in self.added_tokens_encoder:
if current_sub_text:
sub_texts.append(self.convert_tokens_to_string(lowerCAmelCase__ ) )
lowerCAmelCase_ : Any = []
sub_texts.append(lowerCAmelCase__ )
else:
current_sub_text.append(lowerCAmelCase__ )
if current_sub_text:
sub_texts.append(self.convert_tokens_to_string(lowerCAmelCase__ ) )
# Mimic the behavior of the Rust tokenizer:
# No space before [MASK] and [SEP]
if spaces_between_special_tokens:
lowerCAmelCase_ : Optional[int] = re.sub(R" (\[(MASK|SEP)\])" ,R"\1" ," ".join(lowerCAmelCase__ ) )
else:
lowerCAmelCase_ : List[str] = "".join(lowerCAmelCase__ )
lowerCAmelCase_ : List[str] = (
clean_up_tokenization_spaces
if clean_up_tokenization_spaces is not None
else self.clean_up_tokenization_spaces
)
if clean_up_tokenization_spaces:
lowerCAmelCase_ : Tuple = self.clean_up_tokenization(lowerCAmelCase__ )
return clean_text
else:
return text
def UpperCAmelCase_ ( self : Any ,lowerCAmelCase__ : str ,lowerCAmelCase__ : Optional[str] = None ) -> Tuple[str]:
'''simple docstring'''
if not os.path.isdir(lowerCAmelCase__ ):
logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' )
return
lowerCAmelCase_ : str = os.path.join(
lowerCAmelCase__ ,(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] )
if os.path.abspath(self.vocab_file ) != os.path.abspath(lowerCAmelCase__ ) and os.path.isfile(self.vocab_file ):
copyfile(self.vocab_file ,lowerCAmelCase__ )
elif not os.path.isfile(self.vocab_file ):
with open(lowerCAmelCase__ ,"wb" ) as fi:
lowerCAmelCase_ : Tuple = self.sp_model.serialized_model_proto()
fi.write(lowerCAmelCase__ )
return (out_vocab_file,)
def UpperCAmelCase_ ( self : Optional[int] ,lowerCAmelCase__ : List[int] ,lowerCAmelCase__ : Optional[List[int]] = None ) -> List[int]:
'''simple docstring'''
if token_ids_a is None:
return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
lowerCAmelCase_ : List[str] = [self.cls_token_id]
lowerCAmelCase_ : Dict = [self.sep_token_id]
return cls + token_ids_a + sep + token_ids_a + sep
def UpperCAmelCase_ ( self : Any ,lowerCAmelCase__ : List[int] ,lowerCAmelCase__ : Optional[List[int]] = None ,lowerCAmelCase__ : bool = False ) -> List[int]:
'''simple docstring'''
if already_has_special_tokens:
return super().get_special_tokens_mask(
token_ids_a=lowerCAmelCase__ ,token_ids_a=lowerCAmelCase__ ,already_has_special_tokens=lowerCAmelCase__ )
if token_ids_a is None:
return [1] + ([0] * len(lowerCAmelCase__ )) + [1]
return [1] + ([0] * len(lowerCAmelCase__ )) + [1] + ([0] * len(lowerCAmelCase__ )) + [1]
def UpperCAmelCase_ ( self : Optional[int] ,lowerCAmelCase__ : List[int] ,lowerCAmelCase__ : Optional[List[int]] = None ) -> List[int]:
'''simple docstring'''
lowerCAmelCase_ : Optional[Any] = [self.sep_token_id]
lowerCAmelCase_ : str = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1]
| 659 |
import json
import os
import unittest
from transformers import BatchEncoding, LEDTokenizer, LEDTokenizerFast
from transformers.models.led.tokenization_led import VOCAB_FILES_NAMES
from transformers.testing_utils import require_tokenizers, require_torch
from transformers.utils import cached_property
from ...test_tokenization_common import TokenizerTesterMixin
@require_tokenizers
class __snake_case ( snake_case__ , unittest.TestCase ):
"""simple docstring"""
UpperCamelCase_ = LEDTokenizer
UpperCamelCase_ = LEDTokenizerFast
UpperCamelCase_ = True
def UpperCAmelCase_ ( self : List[Any] ) -> Optional[int]:
'''simple docstring'''
super().setUp()
lowerCAmelCase_ : Union[str, Any] = [
"l",
"o",
"w",
"e",
"r",
"s",
"t",
"i",
"d",
"n",
"\u0120",
"\u0120l",
"\u0120n",
"\u0120lo",
"\u0120low",
"er",
"\u0120lowest",
"\u0120newer",
"\u0120wider",
"<unk>",
]
lowerCAmelCase_ : Tuple = dict(zip(lowerCAmelCase__ ,range(len(lowerCAmelCase__ ) ) ) )
lowerCAmelCase_ : int = ["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""]
lowerCAmelCase_ : Union[str, Any] = {"unk_token": "<unk>"}
lowerCAmelCase_ : List[Any] = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES["vocab_file"] )
lowerCAmelCase_ : Any = 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(lowerCAmelCase__ ) + "\n" )
with open(self.merges_file ,"w" ,encoding="utf-8" ) as fp:
fp.write("\n".join(lowerCAmelCase__ ) )
def UpperCAmelCase_ ( self : List[Any] ,**lowerCAmelCase__ : int ) -> Tuple:
'''simple docstring'''
kwargs.update(self.special_tokens_map )
return self.tokenizer_class.from_pretrained(self.tmpdirname ,**lowerCAmelCase__ )
def UpperCAmelCase_ ( self : Union[str, Any] ,**lowerCAmelCase__ : Optional[int] ) -> List[Any]:
'''simple docstring'''
kwargs.update(self.special_tokens_map )
return self.rust_tokenizer_class.from_pretrained(self.tmpdirname ,**lowerCAmelCase__ )
def UpperCAmelCase_ ( self : str ,lowerCAmelCase__ : int ) -> List[str]:
'''simple docstring'''
return "lower newer", "lower newer"
@cached_property
def UpperCAmelCase_ ( self : int ) -> Union[str, Any]:
'''simple docstring'''
return LEDTokenizer.from_pretrained("allenai/led-base-16384" )
@cached_property
def UpperCAmelCase_ ( self : List[str] ) -> Dict:
'''simple docstring'''
return LEDTokenizerFast.from_pretrained("allenai/led-base-16384" )
@require_torch
def UpperCAmelCase_ ( self : int ) -> Optional[int]:
'''simple docstring'''
lowerCAmelCase_ : Union[str, Any] = ["A long paragraph for summarization.", "Another paragraph for summarization."]
lowerCAmelCase_ : int = [0, 2_50, 2_51, 1_78_18, 13, 3_91_86, 19_38, 4, 2]
for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
lowerCAmelCase_ : Any = tokenizer(lowerCAmelCase__ ,max_length=len(lowerCAmelCase__ ) ,padding=lowerCAmelCase__ ,return_tensors="pt" )
self.assertIsInstance(lowerCAmelCase__ ,lowerCAmelCase__ )
self.assertEqual((2, 9) ,batch.input_ids.shape )
self.assertEqual((2, 9) ,batch.attention_mask.shape )
lowerCAmelCase_ : int = batch.input_ids.tolist()[0]
self.assertListEqual(lowerCAmelCase__ ,lowerCAmelCase__ )
@require_torch
def UpperCAmelCase_ ( self : Dict ) -> Any:
'''simple docstring'''
lowerCAmelCase_ : int = ["A long paragraph for summarization.", "Another paragraph for summarization."]
for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
lowerCAmelCase_ : Optional[Any] = tokenizer(lowerCAmelCase__ ,padding=lowerCAmelCase__ ,return_tensors="pt" )
self.assertIn("input_ids" ,lowerCAmelCase__ )
self.assertIn("attention_mask" ,lowerCAmelCase__ )
self.assertNotIn("labels" ,lowerCAmelCase__ )
self.assertNotIn("decoder_attention_mask" ,lowerCAmelCase__ )
@require_torch
def UpperCAmelCase_ ( self : Union[str, Any] ) -> Optional[int]:
'''simple docstring'''
lowerCAmelCase_ : int = [
"Summary of the text.",
"Another summary.",
]
for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
lowerCAmelCase_ : Optional[int] = tokenizer(text_target=lowerCAmelCase__ ,max_length=32 ,padding="max_length" ,return_tensors="pt" )
self.assertEqual(32 ,targets["input_ids"].shape[1] )
@require_torch
def UpperCAmelCase_ ( self : Tuple ) -> List[str]:
'''simple docstring'''
for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
lowerCAmelCase_ : Tuple = tokenizer(
["I am a small frog" * 10_24, "I am a small frog"] ,padding=lowerCAmelCase__ ,truncation=lowerCAmelCase__ ,return_tensors="pt" )
self.assertIsInstance(lowerCAmelCase__ ,lowerCAmelCase__ )
self.assertEqual(batch.input_ids.shape ,(2, 51_22) )
@require_torch
def UpperCAmelCase_ ( self : List[str] ) -> Union[str, Any]:
'''simple docstring'''
lowerCAmelCase_ : Tuple = ["A long paragraph for summarization."]
lowerCAmelCase_ : Dict = [
"Summary of the text.",
]
for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
lowerCAmelCase_ : Optional[Any] = tokenizer(lowerCAmelCase__ ,return_tensors="pt" )
lowerCAmelCase_ : Optional[Any] = tokenizer(text_target=lowerCAmelCase__ ,return_tensors="pt" )
lowerCAmelCase_ : List[str] = inputs["input_ids"]
lowerCAmelCase_ : Any = targets["input_ids"]
self.assertTrue((input_ids[:, 0] == tokenizer.bos_token_id).all().item() )
self.assertTrue((labels[:, 0] == tokenizer.bos_token_id).all().item() )
self.assertTrue((input_ids[:, -1] == tokenizer.eos_token_id).all().item() )
self.assertTrue((labels[:, -1] == tokenizer.eos_token_id).all().item() )
@require_torch
def UpperCAmelCase_ ( self : str ) -> Tuple:
'''simple docstring'''
for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
lowerCAmelCase_ : str = ["Summary of the text.", "Another summary."]
lowerCAmelCase_ : str = [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, -1, -1]]
lowerCAmelCase_ : List[Any] = tokenizer(lowerCAmelCase__ ,padding=lowerCAmelCase__ )
lowerCAmelCase_ : Optional[int] = [[0] * len(lowerCAmelCase__ ) for x in encoded_output["input_ids"]]
lowerCAmelCase_ : Optional[int] = tokenizer.pad(lowerCAmelCase__ )
self.assertSequenceEqual(outputs["global_attention_mask"] ,lowerCAmelCase__ )
def UpperCAmelCase_ ( self : Union[str, Any] ) -> Dict:
'''simple docstring'''
pass
def UpperCAmelCase_ ( self : str ) -> Union[str, Any]:
'''simple docstring'''
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ):
lowerCAmelCase_ : Dict = self.rust_tokenizer_class.from_pretrained(lowerCAmelCase__ ,**lowerCAmelCase__ )
lowerCAmelCase_ : Tuple = self.tokenizer_class.from_pretrained(lowerCAmelCase__ ,**lowerCAmelCase__ )
lowerCAmelCase_ : Dict = "A, <mask> AllenNLP sentence."
lowerCAmelCase_ : Tuple = tokenizer_r.encode_plus(lowerCAmelCase__ ,add_special_tokens=lowerCAmelCase__ ,return_token_type_ids=lowerCAmelCase__ )
lowerCAmelCase_ : int = tokenizer_p.encode_plus(lowerCAmelCase__ ,add_special_tokens=lowerCAmelCase__ ,return_token_type_ids=lowerCAmelCase__ )
self.assertEqual(sum(tokens_r["token_type_ids"] ) ,sum(tokens_p["token_type_ids"] ) )
self.assertEqual(
sum(tokens_r["attention_mask"] ) / len(tokens_r["attention_mask"] ) ,sum(tokens_p["attention_mask"] ) / len(tokens_p["attention_mask"] ) ,)
lowerCAmelCase_ : Any = tokenizer_r.convert_ids_to_tokens(tokens_r["input_ids"] )
lowerCAmelCase_ : Union[str, Any] = tokenizer_p.convert_ids_to_tokens(tokens_p["input_ids"] )
self.assertSequenceEqual(tokens_p["input_ids"] ,[0, 2_50, 6, 5_02_64, 38_23, 4_87, 2_19_92, 36_45, 4, 2] )
self.assertSequenceEqual(tokens_r["input_ids"] ,[0, 2_50, 6, 5_02_64, 38_23, 4_87, 2_19_92, 36_45, 4, 2] )
self.assertSequenceEqual(
lowerCAmelCase__ ,["<s>", "A", ",", "<mask>", "ĠAllen", "N", "LP", "Ġsentence", ".", "</s>"] )
self.assertSequenceEqual(
lowerCAmelCase__ ,["<s>", "A", ",", "<mask>", "ĠAllen", "N", "LP", "Ġsentence", ".", "</s>"] )
| 659 | 1 |
from __future__ import annotations
import unittest
from transformers import RoFormerConfig, is_tf_available
from transformers.testing_utils import require_tf, slow
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers import (
TFRoFormerForCausalLM,
TFRoFormerForMaskedLM,
TFRoFormerForMultipleChoice,
TFRoFormerForQuestionAnswering,
TFRoFormerForSequenceClassification,
TFRoFormerForTokenClassification,
TFRoFormerModel,
)
from transformers.models.roformer.modeling_tf_roformer import (
TFRoFormerSelfAttention,
TFRoFormerSinusoidalPositionalEmbedding,
)
class __snake_case :
"""simple docstring"""
def __init__( self : Tuple ,lowerCAmelCase__ : Tuple ,lowerCAmelCase__ : Dict=13 ,lowerCAmelCase__ : List[str]=7 ,lowerCAmelCase__ : Any=True ,lowerCAmelCase__ : str=True ,lowerCAmelCase__ : List[Any]=True ,lowerCAmelCase__ : Dict=True ,lowerCAmelCase__ : int=99 ,lowerCAmelCase__ : int=32 ,lowerCAmelCase__ : List[Any]=2 ,lowerCAmelCase__ : int=4 ,lowerCAmelCase__ : Optional[Any]=37 ,lowerCAmelCase__ : int="gelu" ,lowerCAmelCase__ : Optional[Any]=0.1 ,lowerCAmelCase__ : Optional[Any]=0.1 ,lowerCAmelCase__ : Optional[int]=5_12 ,lowerCAmelCase__ : Tuple=16 ,lowerCAmelCase__ : List[str]=2 ,lowerCAmelCase__ : int=0.02 ,lowerCAmelCase__ : Optional[int]=3 ,lowerCAmelCase__ : Union[str, Any]=4 ,lowerCAmelCase__ : Dict=None ,) -> Tuple:
'''simple docstring'''
lowerCAmelCase_ : Optional[int] = parent
lowerCAmelCase_ : int = 13
lowerCAmelCase_ : Optional[int] = 7
lowerCAmelCase_ : Optional[Any] = True
lowerCAmelCase_ : str = True
lowerCAmelCase_ : Union[str, Any] = True
lowerCAmelCase_ : Optional[int] = True
lowerCAmelCase_ : Dict = 99
lowerCAmelCase_ : Any = 32
lowerCAmelCase_ : List[str] = 2
lowerCAmelCase_ : Optional[Any] = 4
lowerCAmelCase_ : List[str] = 37
lowerCAmelCase_ : int = "gelu"
lowerCAmelCase_ : Dict = 0.1
lowerCAmelCase_ : Union[str, Any] = 0.1
lowerCAmelCase_ : Optional[Any] = 5_12
lowerCAmelCase_ : Any = 16
lowerCAmelCase_ : Any = 2
lowerCAmelCase_ : Dict = 0.02
lowerCAmelCase_ : List[Any] = 3
lowerCAmelCase_ : Optional[int] = 4
lowerCAmelCase_ : str = None
def UpperCAmelCase_ ( self : Any ) -> Union[str, Any]:
'''simple docstring'''
lowerCAmelCase_ : List[Any] = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size )
lowerCAmelCase_ : Optional[Any] = None
if self.use_input_mask:
lowerCAmelCase_ : Tuple = random_attention_mask([self.batch_size, self.seq_length] )
lowerCAmelCase_ : List[Any] = None
if self.use_token_type_ids:
lowerCAmelCase_ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] ,self.type_vocab_size )
lowerCAmelCase_ : Union[str, Any] = None
lowerCAmelCase_ : str = None
lowerCAmelCase_ : Any = None
if self.use_labels:
lowerCAmelCase_ : Any = ids_tensor([self.batch_size] ,self.type_sequence_label_size )
lowerCAmelCase_ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] ,self.num_labels )
lowerCAmelCase_ : Any = ids_tensor([self.batch_size] ,self.num_choices )
lowerCAmelCase_ : List[str] = RoFormerConfig(
vocab_size=self.vocab_size ,hidden_size=self.hidden_size ,num_hidden_layers=self.num_hidden_layers ,num_attention_heads=self.num_attention_heads ,intermediate_size=self.intermediate_size ,hidden_act=self.hidden_act ,hidden_dropout_prob=self.hidden_dropout_prob ,attention_probs_dropout_prob=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,type_vocab_size=self.type_vocab_size ,initializer_range=self.initializer_range ,return_dict=lowerCAmelCase__ ,)
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
def UpperCAmelCase_ ( self : Tuple ,lowerCAmelCase__ : Optional[Any] ,lowerCAmelCase__ : Optional[Any] ,lowerCAmelCase__ : Any ,lowerCAmelCase__ : Tuple ,lowerCAmelCase__ : int ,lowerCAmelCase__ : Dict ,lowerCAmelCase__ : Optional[int] ) -> Optional[Any]:
'''simple docstring'''
lowerCAmelCase_ : int = TFRoFormerModel(config=lowerCAmelCase__ )
lowerCAmelCase_ : Union[str, Any] = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
lowerCAmelCase_ : Optional[int] = [input_ids, input_mask]
lowerCAmelCase_ : Dict = model(lowerCAmelCase__ )
lowerCAmelCase_ : Optional[int] = model(lowerCAmelCase__ )
self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) )
def UpperCAmelCase_ ( self : Optional[int] ,lowerCAmelCase__ : Dict ,lowerCAmelCase__ : List[Any] ,lowerCAmelCase__ : Union[str, Any] ,lowerCAmelCase__ : Optional[Any] ,lowerCAmelCase__ : Optional[Any] ,lowerCAmelCase__ : int ,lowerCAmelCase__ : str ) -> Union[str, Any]:
'''simple docstring'''
lowerCAmelCase_ : str = True
lowerCAmelCase_ : List[Any] = TFRoFormerForCausalLM(config=lowerCAmelCase__ )
lowerCAmelCase_ : List[str] = {
"input_ids": input_ids,
"attention_mask": input_mask,
"token_type_ids": token_type_ids,
}
lowerCAmelCase_ : Union[str, Any] = model(lowerCAmelCase__ )["logits"]
self.parent.assertListEqual(
list(prediction_scores.numpy().shape ) ,[self.batch_size, self.seq_length, self.vocab_size] )
def UpperCAmelCase_ ( self : List[Any] ,lowerCAmelCase__ : Any ,lowerCAmelCase__ : Union[str, Any] ,lowerCAmelCase__ : Tuple ,lowerCAmelCase__ : List[Any] ,lowerCAmelCase__ : Union[str, Any] ,lowerCAmelCase__ : List[str] ,lowerCAmelCase__ : Optional[Any] ) -> List[Any]:
'''simple docstring'''
lowerCAmelCase_ : Optional[Any] = TFRoFormerForMaskedLM(config=lowerCAmelCase__ )
lowerCAmelCase_ : Union[str, Any] = {
"input_ids": input_ids,
"attention_mask": input_mask,
"token_type_ids": token_type_ids,
}
lowerCAmelCase_ : Union[str, Any] = model(lowerCAmelCase__ )
self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) )
def UpperCAmelCase_ ( self : Union[str, Any] ,lowerCAmelCase__ : List[Any] ,lowerCAmelCase__ : Tuple ,lowerCAmelCase__ : int ,lowerCAmelCase__ : Any ,lowerCAmelCase__ : Optional[int] ,lowerCAmelCase__ : Any ,lowerCAmelCase__ : Any ) -> int:
'''simple docstring'''
lowerCAmelCase_ : int = self.num_labels
lowerCAmelCase_ : int = TFRoFormerForSequenceClassification(config=lowerCAmelCase__ )
lowerCAmelCase_ : Union[str, Any] = {
"input_ids": input_ids,
"attention_mask": input_mask,
"token_type_ids": token_type_ids,
}
lowerCAmelCase_ : Optional[Any] = model(lowerCAmelCase__ )
self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) )
def UpperCAmelCase_ ( self : List[str] ,lowerCAmelCase__ : Tuple ,lowerCAmelCase__ : Tuple ,lowerCAmelCase__ : Union[str, Any] ,lowerCAmelCase__ : Optional[Any] ,lowerCAmelCase__ : Any ,lowerCAmelCase__ : Optional[int] ,lowerCAmelCase__ : int ) -> List[str]:
'''simple docstring'''
lowerCAmelCase_ : Dict = self.num_choices
lowerCAmelCase_ : List[str] = TFRoFormerForMultipleChoice(config=lowerCAmelCase__ )
lowerCAmelCase_ : Optional[Any] = tf.tile(tf.expand_dims(lowerCAmelCase__ ,1 ) ,(1, self.num_choices, 1) )
lowerCAmelCase_ : Optional[Any] = tf.tile(tf.expand_dims(lowerCAmelCase__ ,1 ) ,(1, self.num_choices, 1) )
lowerCAmelCase_ : str = tf.tile(tf.expand_dims(lowerCAmelCase__ ,1 ) ,(1, self.num_choices, 1) )
lowerCAmelCase_ : List[Any] = {
"input_ids": multiple_choice_inputs_ids,
"attention_mask": multiple_choice_input_mask,
"token_type_ids": multiple_choice_token_type_ids,
}
lowerCAmelCase_ : Tuple = model(lowerCAmelCase__ )
self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_choices) )
def UpperCAmelCase_ ( self : Optional[Any] ,lowerCAmelCase__ : Optional[Any] ,lowerCAmelCase__ : List[Any] ,lowerCAmelCase__ : Dict ,lowerCAmelCase__ : Optional[int] ,lowerCAmelCase__ : List[Any] ,lowerCAmelCase__ : int ,lowerCAmelCase__ : List[str] ) -> Optional[Any]:
'''simple docstring'''
lowerCAmelCase_ : Dict = self.num_labels
lowerCAmelCase_ : Dict = TFRoFormerForTokenClassification(config=lowerCAmelCase__ )
lowerCAmelCase_ : int = {
"input_ids": input_ids,
"attention_mask": input_mask,
"token_type_ids": token_type_ids,
}
lowerCAmelCase_ : Any = model(lowerCAmelCase__ )
self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.num_labels) )
def UpperCAmelCase_ ( self : Tuple ,lowerCAmelCase__ : Optional[int] ,lowerCAmelCase__ : str ,lowerCAmelCase__ : Dict ,lowerCAmelCase__ : Union[str, Any] ,lowerCAmelCase__ : Any ,lowerCAmelCase__ : List[Any] ,lowerCAmelCase__ : Optional[Any] ) -> Dict:
'''simple docstring'''
lowerCAmelCase_ : List[str] = TFRoFormerForQuestionAnswering(config=lowerCAmelCase__ )
lowerCAmelCase_ : Union[str, Any] = {
"input_ids": input_ids,
"attention_mask": input_mask,
"token_type_ids": token_type_ids,
}
lowerCAmelCase_ : Union[str, Any] = model(lowerCAmelCase__ )
self.parent.assertEqual(result.start_logits.shape ,(self.batch_size, self.seq_length) )
self.parent.assertEqual(result.end_logits.shape ,(self.batch_size, self.seq_length) )
def UpperCAmelCase_ ( self : Union[str, Any] ) -> Tuple:
'''simple docstring'''
lowerCAmelCase_ : Any = self.prepare_config_and_inputs()
(
(
lowerCAmelCase_
) , (
lowerCAmelCase_
) , (
lowerCAmelCase_
) , (
lowerCAmelCase_
) , (
lowerCAmelCase_
) , (
lowerCAmelCase_
) , (
lowerCAmelCase_
) ,
) : List[str] = config_and_inputs
lowerCAmelCase_ : Optional[Any] = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
return config, inputs_dict
@require_tf
class __snake_case ( snake_case__ , snake_case__ , unittest.TestCase ):
"""simple docstring"""
UpperCamelCase_ = (
(
TFRoFormerModel,
TFRoFormerForCausalLM,
TFRoFormerForMaskedLM,
TFRoFormerForQuestionAnswering,
TFRoFormerForSequenceClassification,
TFRoFormerForTokenClassification,
TFRoFormerForMultipleChoice,
)
if is_tf_available()
else ()
)
UpperCamelCase_ = (
{
'feature-extraction': TFRoFormerModel,
'fill-mask': TFRoFormerForMaskedLM,
'question-answering': TFRoFormerForQuestionAnswering,
'text-classification': TFRoFormerForSequenceClassification,
'text-generation': TFRoFormerForCausalLM,
'token-classification': TFRoFormerForTokenClassification,
'zero-shot': TFRoFormerForSequenceClassification,
}
if is_tf_available()
else {}
)
UpperCamelCase_ = False
UpperCamelCase_ = False
def UpperCAmelCase_ ( self : List[str] ,lowerCAmelCase__ : List[Any] ,lowerCAmelCase__ : Tuple ,lowerCAmelCase__ : Dict ,lowerCAmelCase__ : Dict ,lowerCAmelCase__ : Optional[Any] ) -> Any:
'''simple docstring'''
if pipeline_test_casse_name == "TextGenerationPipelineTests":
return True
return False
def UpperCAmelCase_ ( self : str ) -> int:
'''simple docstring'''
lowerCAmelCase_ : Tuple = TFRoFormerModelTester(self )
lowerCAmelCase_ : int = ConfigTester(self ,config_class=lowerCAmelCase__ ,hidden_size=37 )
def UpperCAmelCase_ ( self : Dict ) -> List[Any]:
'''simple docstring'''
self.config_tester.run_common_tests()
def UpperCAmelCase_ ( self : List[str] ) -> Optional[Any]:
'''simple docstring'''
lowerCAmelCase_ : Dict = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*lowerCAmelCase__ )
def UpperCAmelCase_ ( self : int ) -> str:
'''simple docstring'''
lowerCAmelCase_ : str = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_lm(*lowerCAmelCase__ )
def UpperCAmelCase_ ( self : Tuple ) -> Dict:
'''simple docstring'''
lowerCAmelCase_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_lm_head(*lowerCAmelCase__ )
def UpperCAmelCase_ ( self : Union[str, Any] ) -> List[Any]:
'''simple docstring'''
lowerCAmelCase_ : Optional[int] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_multiple_choice(*lowerCAmelCase__ )
def UpperCAmelCase_ ( self : Tuple ) -> Union[str, Any]:
'''simple docstring'''
lowerCAmelCase_ : List[str] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_question_answering(*lowerCAmelCase__ )
def UpperCAmelCase_ ( self : Any ) -> Optional[Any]:
'''simple docstring'''
lowerCAmelCase_ : List[Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_sequence_classification(*lowerCAmelCase__ )
def UpperCAmelCase_ ( self : Optional[int] ) -> Optional[Any]:
'''simple docstring'''
lowerCAmelCase_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_token_classification(*lowerCAmelCase__ )
@slow
def UpperCAmelCase_ ( self : Dict ) -> str:
'''simple docstring'''
lowerCAmelCase_ : Optional[Any] = TFRoFormerModel.from_pretrained("junnyu/roformer_chinese_base" )
self.assertIsNotNone(lowerCAmelCase__ )
@require_tf
class __snake_case ( unittest.TestCase ):
"""simple docstring"""
@slow
def UpperCAmelCase_ ( self : Dict ) -> str:
'''simple docstring'''
lowerCAmelCase_ : Union[str, Any] = TFRoFormerForMaskedLM.from_pretrained("junnyu/roformer_chinese_base" )
lowerCAmelCase_ : int = tf.constant([[0, 1, 2, 3, 4, 5]] )
lowerCAmelCase_ : List[Any] = model(lowerCAmelCase__ )[0]
# TODO Replace vocab size
lowerCAmelCase_ : int = 5_00_00
lowerCAmelCase_ : List[str] = [1, 6, vocab_size]
self.assertEqual(output.shape ,lowerCAmelCase__ )
print(output[:, :3, :3] )
# TODO Replace values below with what was printed above.
lowerCAmelCase_ : Optional[Any] = tf.constant(
[
[
[-0.12_053_341, -1.0_264_901, 0.29_221_946],
[-1.5_133_783, 0.197_433, 0.15_190_607],
[-5.0_135_403, -3.900_256, -0.84_038_764],
]
] )
tf.debugging.assert_near(output[:, :3, :3] ,lowerCAmelCase__ ,atol=1e-4 )
@require_tf
class __snake_case ( unittest.TestCase ):
"""simple docstring"""
UpperCamelCase_ = 1e-4
def UpperCAmelCase_ ( self : List[Any] ) -> Union[str, Any]:
'''simple docstring'''
lowerCAmelCase_ : Tuple = tf.constant([[4, 10]] )
lowerCAmelCase_ : Union[str, Any] = TFRoFormerSinusoidalPositionalEmbedding(num_positions=6 ,embedding_dim=6 )
lowerCAmelCase_ : List[str] = emba(input_ids.shape )
lowerCAmelCase_ : Any = tf.constant(
[[0.0_000, 0.0_000, 0.0_000, 1.0_000, 1.0_000, 1.0_000], [0.8_415, 0.0_464, 0.0_022, 0.5_403, 0.9_989, 1.0_000]] )
tf.debugging.assert_near(lowerCAmelCase__ ,lowerCAmelCase__ ,atol=self.tolerance )
def UpperCAmelCase_ ( self : Any ) -> Optional[int]:
'''simple docstring'''
lowerCAmelCase_ : str = tf.constant(
[
[0.0_000, 0.0_000, 0.0_000, 0.0_000, 0.0_000],
[0.8_415, 0.8_219, 0.8_020, 0.7_819, 0.7_617],
[0.9_093, 0.9_364, 0.9_581, 0.9_749, 0.9_870],
] )
lowerCAmelCase_ : Any = TFRoFormerSinusoidalPositionalEmbedding(num_positions=5_12 ,embedding_dim=5_12 )
emba([2, 16, 5_12] )
lowerCAmelCase_ : Any = emba.weight[:3, :5]
tf.debugging.assert_near(lowerCAmelCase__ ,lowerCAmelCase__ ,atol=self.tolerance )
@require_tf
class __snake_case ( unittest.TestCase ):
"""simple docstring"""
UpperCamelCase_ = 1e-4
def UpperCAmelCase_ ( self : List[Any] ) -> List[str]:
'''simple docstring'''
lowerCAmelCase_ : int = tf.reshape(tf.range(2 * 12 * 16 * 64 ,dtype=tf.floataa ) ,shape=(2, 12, 16, 64) ) / 1_00
lowerCAmelCase_ : Optional[int] = -tf.reshape(tf.range(2 * 12 * 16 * 64 ,dtype=tf.floataa ) ,shape=(2, 12, 16, 64) ) / 1_00
lowerCAmelCase_ : Union[str, Any] = TFRoFormerSinusoidalPositionalEmbedding(num_positions=32 ,embedding_dim=64 )
lowerCAmelCase_ : Tuple = embed_positions([2, 16, 7_68] )[None, None, :, :]
lowerCAmelCase_ , lowerCAmelCase_ : int = TFRoFormerSelfAttention.apply_rotary_position_embeddings(
lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ )
lowerCAmelCase_ : Tuple = tf.constant(
[
[0.0_000, 0.0_100, 0.0_200, 0.0_300, 0.0_400, 0.0_500, 0.0_600, 0.0_700],
[-0.2_012, 0.8_897, 0.0_263, 0.9_401, 0.2_074, 0.9_463, 0.3_481, 0.9_343],
[-1.7_057, 0.6_271, -1.2_145, 1.3_897, -0.6_303, 1.7_647, -0.1_173, 1.8_985],
[-2.1_731, -1.6_397, -2.7_358, 0.2_854, -2.1_840, 1.7_183, -1.3_018, 2.4_871],
[0.2_717, -3.6_173, -2.9_206, -2.1_988, -3.6_638, 0.3_858, -2.9_155, 2.2_980],
[3.9_859, -2.1_580, -0.7_984, -4.4_904, -4.1_181, -2.0_252, -4.4_782, 1.1_253],
] )
lowerCAmelCase_ : Optional[Any] = tf.constant(
[
[0.0_000, -0.0_100, -0.0_200, -0.0_300, -0.0_400, -0.0_500, -0.0_600, -0.0_700],
[0.2_012, -0.8_897, -0.0_263, -0.9_401, -0.2_074, -0.9_463, -0.3_481, -0.9_343],
[1.7_057, -0.6_271, 1.2_145, -1.3_897, 0.6_303, -1.7_647, 0.1_173, -1.8_985],
[2.1_731, 1.6_397, 2.7_358, -0.2_854, 2.1_840, -1.7_183, 1.3_018, -2.4_871],
[-0.2_717, 3.6_173, 2.9_206, 2.1_988, 3.6_638, -0.3_858, 2.9_155, -2.2_980],
[-3.9_859, 2.1_580, 0.7_984, 4.4_904, 4.1_181, 2.0_252, 4.4_782, -1.1_253],
] )
tf.debugging.assert_near(query_layer[0, 0, :6, :8] ,lowerCAmelCase__ ,atol=self.tolerance )
tf.debugging.assert_near(key_layer[0, 0, :6, :8] ,lowerCAmelCase__ ,atol=self.tolerance )
| 659 |
from ....configuration_utils import PretrainedConfig
from ....utils import logging
_lowercase = logging.get_logger(__name__)
_lowercase = {
'''Visual-Attention-Network/van-base''': (
'''https://huggingface.co/Visual-Attention-Network/van-base/blob/main/config.json'''
),
}
class __snake_case ( snake_case__ ):
"""simple docstring"""
UpperCamelCase_ = 'van'
def __init__( self : List[str] ,lowerCAmelCase__ : int=2_24 ,lowerCAmelCase__ : Optional[int]=3 ,lowerCAmelCase__ : Dict=[7, 3, 3, 3] ,lowerCAmelCase__ : List[str]=[4, 2, 2, 2] ,lowerCAmelCase__ : Union[str, Any]=[64, 1_28, 3_20, 5_12] ,lowerCAmelCase__ : Union[str, Any]=[3, 3, 12, 3] ,lowerCAmelCase__ : Any=[8, 8, 4, 4] ,lowerCAmelCase__ : Optional[int]="gelu" ,lowerCAmelCase__ : List[str]=0.02 ,lowerCAmelCase__ : Optional[Any]=1e-6 ,lowerCAmelCase__ : Dict=1e-2 ,lowerCAmelCase__ : Union[str, Any]=0.0 ,lowerCAmelCase__ : Optional[Any]=0.0 ,**lowerCAmelCase__ : List[str] ,) -> Tuple:
'''simple docstring'''
super().__init__(**lowerCAmelCase__ )
lowerCAmelCase_ : Optional[int] = image_size
lowerCAmelCase_ : List[str] = num_channels
lowerCAmelCase_ : str = patch_sizes
lowerCAmelCase_ : Optional[Any] = strides
lowerCAmelCase_ : List[Any] = hidden_sizes
lowerCAmelCase_ : int = depths
lowerCAmelCase_ : int = mlp_ratios
lowerCAmelCase_ : str = hidden_act
lowerCAmelCase_ : List[str] = initializer_range
lowerCAmelCase_ : Dict = layer_norm_eps
lowerCAmelCase_ : str = layer_scale_init_value
lowerCAmelCase_ : Tuple = drop_path_rate
lowerCAmelCase_ : Dict = dropout_rate
| 659 | 1 |
from manim import *
class __snake_case ( snake_case__ ):
"""simple docstring"""
def UpperCAmelCase_ ( self : List[str] ) -> Any:
'''simple docstring'''
lowerCAmelCase_ : int = Rectangle(height=0.5 ,width=0.5 )
lowerCAmelCase_ : str = Rectangle(height=0.46 ,width=0.46 ).set_stroke(width=0 )
lowerCAmelCase_ : List[Any] = Rectangle(height=0.25 ,width=0.25 )
lowerCAmelCase_ : Optional[Any] = [mem.copy() for i in range(6 )]
lowerCAmelCase_ : List[Any] = [mem.copy() for i in range(6 )]
lowerCAmelCase_ : str = VGroup(*lowerCAmelCase__ ).arrange(lowerCAmelCase__ ,buff=0 )
lowerCAmelCase_ : List[str] = VGroup(*lowerCAmelCase__ ).arrange(lowerCAmelCase__ ,buff=0 )
lowerCAmelCase_ : Any = VGroup(lowerCAmelCase__ ,lowerCAmelCase__ ).arrange(lowerCAmelCase__ ,buff=0 )
lowerCAmelCase_ : List[Any] = Text("CPU" ,font_size=24 )
lowerCAmelCase_ : Tuple = Group(lowerCAmelCase__ ,lowerCAmelCase__ ).arrange(lowerCAmelCase__ ,buff=0.5 ,aligned_edge=lowerCAmelCase__ )
cpu.move_to([-2.5, -0.5, 0] )
self.add(lowerCAmelCase__ )
lowerCAmelCase_ : Tuple = [mem.copy() for i in range(4 )]
lowerCAmelCase_ : Dict = VGroup(*lowerCAmelCase__ ).arrange(lowerCAmelCase__ ,buff=0 )
lowerCAmelCase_ : str = Text("GPU" ,font_size=24 )
lowerCAmelCase_ : Optional[int] = Group(lowerCAmelCase__ ,lowerCAmelCase__ ).arrange(lowerCAmelCase__ ,buff=0.5 ,aligned_edge=lowerCAmelCase__ )
gpu.move_to([-1, -1, 0] )
self.add(lowerCAmelCase__ )
lowerCAmelCase_ : List[Any] = [mem.copy() for i in range(6 )]
lowerCAmelCase_ : int = VGroup(*lowerCAmelCase__ ).arrange(lowerCAmelCase__ ,buff=0 )
lowerCAmelCase_ : Union[str, Any] = Text("Model" ,font_size=24 )
lowerCAmelCase_ : Tuple = Group(lowerCAmelCase__ ,lowerCAmelCase__ ).arrange(lowerCAmelCase__ ,buff=0.5 ,aligned_edge=lowerCAmelCase__ )
model.move_to([3, -1.0, 0] )
self.add(lowerCAmelCase__ )
lowerCAmelCase_ : List[Any] = []
lowerCAmelCase_ : Tuple = []
for i, rect in enumerate(lowerCAmelCase__ ):
lowerCAmelCase_ : Tuple = fill.copy().set_fill(lowerCAmelCase__ ,opacity=0.8 )
target.move_to(lowerCAmelCase__ )
model_arr.append(lowerCAmelCase__ )
lowerCAmelCase_ : int = Rectangle(height=0.46 ,width=0.46 ).set_stroke(width=0.0 ).set_fill(lowerCAmelCase__ ,opacity=0.8 )
cpu_target.move_to(cpu_left_col_base[i] )
model_cpu_arr.append(lowerCAmelCase__ )
self.add(*lowerCAmelCase__ ,*lowerCAmelCase__ )
lowerCAmelCase_ : List[str] = [meta_mem.copy() for i in range(6 )]
lowerCAmelCase_ : Union[str, Any] = [meta_mem.copy() for i in range(6 )]
lowerCAmelCase_ : List[Any] = VGroup(*lowerCAmelCase__ ).arrange(lowerCAmelCase__ ,buff=0 )
lowerCAmelCase_ : List[str] = VGroup(*lowerCAmelCase__ ).arrange(lowerCAmelCase__ ,buff=0 )
lowerCAmelCase_ : Dict = VGroup(lowerCAmelCase__ ,lowerCAmelCase__ ).arrange(lowerCAmelCase__ ,buff=0 )
lowerCAmelCase_ : Dict = Text("Disk" ,font_size=24 )
lowerCAmelCase_ : Optional[Any] = Group(lowerCAmelCase__ ,lowerCAmelCase__ ).arrange(lowerCAmelCase__ ,buff=0.5 ,aligned_edge=lowerCAmelCase__ )
disk.move_to([-4, -1.25, 0] )
self.add(lowerCAmelCase__ ,lowerCAmelCase__ )
lowerCAmelCase_ : List[str] = Square(side_length=2.2 )
key.move_to([-5, 2, 0] )
lowerCAmelCase_ : List[str] = MarkupText(
f'''<b>Key:</b>\n\n<span fgcolor=\'{YELLOW}\'>●</span> Empty Model''' ,font_size=18 ,)
key_text.move_to([-5, 2.4, 0] )
self.add(lowerCAmelCase__ ,lowerCAmelCase__ )
lowerCAmelCase_ : Dict = MarkupText(
f'''<span fgcolor=\'{BLUE}\'>●</span> Checkpoint''' ,font_size=18 ,)
blue_text.next_to(lowerCAmelCase__ ,DOWN * 2.4 ,aligned_edge=key_text.get_left() )
self.add(lowerCAmelCase__ )
lowerCAmelCase_ : Union[str, Any] = MarkupText(
f'''Now watch as an input is passed through the model\nand how the memory is utilized and handled.''' ,font_size=24 ,)
step_a.move_to([2, 2, 0] )
self.play(Write(lowerCAmelCase__ ) )
lowerCAmelCase_ : int = Square(0.3 )
input.set_fill(lowerCAmelCase__ ,opacity=1.0 )
input.set_stroke(width=0.0 )
input.next_to(model_base[0] ,lowerCAmelCase__ ,buff=0.5 )
self.play(Write(lowerCAmelCase__ ) )
input.generate_target()
input.target.next_to(model_arr[0] ,direction=lowerCAmelCase__ ,buff=0.02 )
self.play(MoveToTarget(lowerCAmelCase__ ) )
self.play(FadeOut(lowerCAmelCase__ ) )
lowerCAmelCase_ : int = Arrow(start=lowerCAmelCase__ ,end=lowerCAmelCase__ ,color=lowerCAmelCase__ ,buff=0.5 )
a.next_to(model_arr[0].get_left() ,lowerCAmelCase__ ,buff=0.2 )
model_cpu_arr[0].generate_target()
model_cpu_arr[0].target.move_to(gpu_rect[0] )
lowerCAmelCase_ : Tuple = MarkupText(
f'''As the input reaches a layer, the hook triggers\nand weights are moved from the CPU\nto the GPU and back.''' ,font_size=24 ,)
step_a.move_to([2, 2, 0] )
self.play(Write(lowerCAmelCase__ ,run_time=3 ) )
lowerCAmelCase_ : Tuple = {"run_time": 1, "fade_in": True, "fade_out": True, "buff": 0.02}
self.play(
Write(lowerCAmelCase__ ) ,Circumscribe(model_arr[0] ,color=lowerCAmelCase__ ,**lowerCAmelCase__ ) ,Circumscribe(model_cpu_arr[0] ,color=lowerCAmelCase__ ,**lowerCAmelCase__ ) ,Circumscribe(gpu_rect[0] ,color=lowerCAmelCase__ ,**lowerCAmelCase__ ) ,)
self.play(MoveToTarget(model_cpu_arr[0] ) )
lowerCAmelCase_ : int = a.copy()
for i in range(6 ):
a_c.next_to(model_arr[i].get_right() + 0.02 ,lowerCAmelCase__ ,buff=0.2 )
input.generate_target()
input.target.move_to(model_arr[i].get_right() + 0.02 )
lowerCAmelCase_ : Tuple = AnimationGroup(
FadeOut(lowerCAmelCase__ ,run_time=0.5 ) ,MoveToTarget(lowerCAmelCase__ ,run_time=0.5 ) ,FadeIn(lowerCAmelCase__ ,run_time=0.5 ) ,lag_ratio=0.2 )
self.play(lowerCAmelCase__ )
model_cpu_arr[i].generate_target()
model_cpu_arr[i].target.move_to(cpu_left_col_base[i] )
if i < 5:
model_cpu_arr[i + 1].generate_target()
model_cpu_arr[i + 1].target.move_to(gpu_rect[0] )
if i >= 1:
lowerCAmelCase_ : List[str] = 0.7
self.play(
Circumscribe(model_arr[i] ,**lowerCAmelCase__ ) ,Circumscribe(cpu_left_col_base[i] ,**lowerCAmelCase__ ) ,Circumscribe(cpu_left_col_base[i + 1] ,color=lowerCAmelCase__ ,**lowerCAmelCase__ ) ,Circumscribe(gpu_rect[0] ,color=lowerCAmelCase__ ,**lowerCAmelCase__ ) ,Circumscribe(model_arr[i + 1] ,color=lowerCAmelCase__ ,**lowerCAmelCase__ ) ,)
if i < 1:
self.play(
MoveToTarget(model_cpu_arr[i] ) ,MoveToTarget(model_cpu_arr[i + 1] ) ,)
else:
self.play(
MoveToTarget(model_cpu_arr[i] ,run_time=0.7 ) ,MoveToTarget(model_cpu_arr[i + 1] ,run_time=0.7 ) ,)
else:
model_cpu_arr[i].generate_target()
model_cpu_arr[i].target.move_to(cpu_left_col_base[-1] )
input.generate_target()
input.target.next_to(model_arr[-1].get_right() ,RIGHT + 0.02 ,buff=0.2 )
self.play(
Circumscribe(model_arr[-1] ,color=lowerCAmelCase__ ,**lowerCAmelCase__ ) ,Circumscribe(cpu_left_col_base[-1] ,color=lowerCAmelCase__ ,**lowerCAmelCase__ ) ,Circumscribe(gpu_rect[0] ,color=lowerCAmelCase__ ,**lowerCAmelCase__ ) ,)
self.play(MoveToTarget(model_cpu_arr[i] ) )
lowerCAmelCase_ : int = a_c
lowerCAmelCase_ : int = a_c.copy()
input.generate_target()
input.target.next_to(model_base[-1] ,RIGHT + 0.02 ,buff=0.5 )
self.play(
FadeOut(lowerCAmelCase__ ) ,FadeOut(lowerCAmelCase__ ,run_time=0.5 ) ,)
lowerCAmelCase_ : str = MarkupText(f'''Inference on a model too large for GPU memory\nis successfully completed.''' ,font_size=24 )
step_a.move_to([2, 2, 0] )
self.play(Write(lowerCAmelCase__ ,run_time=3 ) ,MoveToTarget(lowerCAmelCase__ ) )
self.wait()
| 659 |
from math import factorial
def UpperCamelCase ( snake_case__ , snake_case__):
# If either of the conditions are true, the function is being asked
# to calculate a factorial of a negative number, which is not possible
if n < k or k < 0:
raise ValueError("Please enter positive integers for n and k where n >= k")
return factorial(snake_case__) // (factorial(snake_case__) * factorial(n - k))
if __name__ == "__main__":
print(
'''The number of five-card hands possible from a standard''',
f"fifty-two card deck is: {combinations(52, 5)}\n",
)
print(
'''If a class of 40 students must be arranged into groups of''',
f"4 for group projects, there are {combinations(40, 4)} ways",
'''to arrange them.\n''',
)
print(
'''If 10 teams are competing in a Formula One race, there''',
f"are {combinations(10, 3)} ways that first, second and",
'''third place can be awarded.''',
)
| 659 | 1 |
from collections.abc import Sequence
def UpperCamelCase ( snake_case__ = None):
if nums is None or not nums:
raise ValueError("Input sequence should not be empty")
lowerCAmelCase_ : Dict = nums[0]
for i in range(1 , len(snake_case__)):
lowerCAmelCase_ : Optional[int] = nums[i]
lowerCAmelCase_ : Optional[int] = max(snake_case__ , ans + num , snake_case__)
return ans
if __name__ == "__main__":
import doctest
doctest.testmod()
# Try on a sample input from the user
_lowercase = int(input('''Enter number of elements : ''').strip())
_lowercase = list(map(int, input('''\nEnter the numbers : ''').strip().split()))[:n]
print(max_subsequence_sum(array))
| 659 |
import argparse
import json
from tqdm import tqdm
def UpperCamelCase ( ):
lowerCAmelCase_ : Any = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--src_path" , type=snake_case__ , default="biencoder-nq-dev.json" , help="Path to raw DPR training data" , )
parser.add_argument(
"--evaluation_set" , type=snake_case__ , help="where to store parsed evaluation_set file" , )
parser.add_argument(
"--gold_data_path" , type=snake_case__ , help="where to store parsed gold_data_path file" , )
lowerCAmelCase_ : Dict = parser.parse_args()
with open(args.src_path , "r") as src_file, open(args.evaluation_set , "w") as eval_file, open(
args.gold_data_path , "w") as gold_file:
lowerCAmelCase_ : Optional[int] = json.load(snake_case__)
for dpr_record in tqdm(snake_case__):
lowerCAmelCase_ : str = dpr_record["question"]
lowerCAmelCase_ : Dict = [context["title"] for context in dpr_record["positive_ctxs"]]
eval_file.write(question + "\n")
gold_file.write("\t".join(snake_case__) + "\n")
if __name__ == "__main__":
main()
| 659 | 1 |
from __future__ import annotations
import time
from math import sqrt
# 1 for manhattan, 0 for euclidean
_lowercase = 0
_lowercase = [
[0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0],
[1, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0],
]
_lowercase = [[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right
_lowercase = tuple[int, int]
class __snake_case :
"""simple docstring"""
def __init__( self : Union[str, Any] ,lowerCAmelCase__ : int ,lowerCAmelCase__ : int ,lowerCAmelCase__ : int ,lowerCAmelCase__ : int ,lowerCAmelCase__ : int ,lowerCAmelCase__ : Node | None ,) -> None:
'''simple docstring'''
lowerCAmelCase_ : Optional[Any] = pos_x
lowerCAmelCase_ : Tuple = pos_y
lowerCAmelCase_ : int = (pos_y, pos_x)
lowerCAmelCase_ : Any = goal_x
lowerCAmelCase_ : int = goal_y
lowerCAmelCase_ : Dict = g_cost
lowerCAmelCase_ : List[str] = parent
lowerCAmelCase_ : List[Any] = self.calculate_heuristic()
lowerCAmelCase_ : Optional[int] = self.g_cost + self.h_cost
def UpperCAmelCase_ ( self : str ) -> float:
'''simple docstring'''
lowerCAmelCase_ : str = self.pos_x - self.goal_x
lowerCAmelCase_ : List[str] = self.pos_y - self.goal_y
if HEURISTIC == 1:
return abs(lowerCAmelCase__ ) + abs(lowerCAmelCase__ )
else:
return sqrt(dy**2 + dx**2 )
def __lt__( self : Any ,lowerCAmelCase__ : Node ) -> bool:
'''simple docstring'''
return self.f_cost < other.f_cost
class __snake_case :
"""simple docstring"""
def __init__( self : Dict ,lowerCAmelCase__ : TPosition ,lowerCAmelCase__ : TPosition ) -> Union[str, Any]:
'''simple docstring'''
lowerCAmelCase_ : List[str] = Node(start[1] ,start[0] ,goal[1] ,goal[0] ,0 ,lowerCAmelCase__ )
lowerCAmelCase_ : Optional[int] = Node(goal[1] ,goal[0] ,goal[1] ,goal[0] ,9_99_99 ,lowerCAmelCase__ )
lowerCAmelCase_ : int = [self.start]
lowerCAmelCase_ : list[Node] = []
lowerCAmelCase_ : int = False
def UpperCAmelCase_ ( self : str ) -> list[TPosition]:
'''simple docstring'''
while self.open_nodes:
# Open Nodes are sorted using __lt__
self.open_nodes.sort()
lowerCAmelCase_ : Dict = self.open_nodes.pop(0 )
if current_node.pos == self.target.pos:
return self.retrace_path(lowerCAmelCase__ )
self.closed_nodes.append(lowerCAmelCase__ )
lowerCAmelCase_ : int = self.get_successors(lowerCAmelCase__ )
for child_node in successors:
if child_node in self.closed_nodes:
continue
if child_node not in self.open_nodes:
self.open_nodes.append(lowerCAmelCase__ )
else:
# retrieve the best current path
lowerCAmelCase_ : List[Any] = self.open_nodes.pop(self.open_nodes.index(lowerCAmelCase__ ) )
if child_node.g_cost < better_node.g_cost:
self.open_nodes.append(lowerCAmelCase__ )
else:
self.open_nodes.append(lowerCAmelCase__ )
return [self.start.pos]
def UpperCAmelCase_ ( self : Tuple ,lowerCAmelCase__ : Node ) -> list[Node]:
'''simple docstring'''
lowerCAmelCase_ : Optional[int] = []
for action in delta:
lowerCAmelCase_ : Any = parent.pos_x + action[1]
lowerCAmelCase_ : Optional[Any] = parent.pos_y + action[0]
if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(lowerCAmelCase__ ) - 1):
continue
if grid[pos_y][pos_x] != 0:
continue
successors.append(
Node(
lowerCAmelCase__ ,lowerCAmelCase__ ,self.target.pos_y ,self.target.pos_x ,parent.g_cost + 1 ,lowerCAmelCase__ ,) )
return successors
def UpperCAmelCase_ ( self : List[str] ,lowerCAmelCase__ : Node | None ) -> list[TPosition]:
'''simple docstring'''
lowerCAmelCase_ : Optional[Any] = node
lowerCAmelCase_ : str = []
while current_node is not None:
path.append((current_node.pos_y, current_node.pos_x) )
lowerCAmelCase_ : Optional[int] = current_node.parent
path.reverse()
return path
class __snake_case :
"""simple docstring"""
def __init__( self : str ,lowerCAmelCase__ : TPosition ,lowerCAmelCase__ : TPosition ) -> None:
'''simple docstring'''
lowerCAmelCase_ : Optional[int] = AStar(lowerCAmelCase__ ,lowerCAmelCase__ )
lowerCAmelCase_ : Union[str, Any] = AStar(lowerCAmelCase__ ,lowerCAmelCase__ )
lowerCAmelCase_ : Any = False
def UpperCAmelCase_ ( self : Union[str, Any] ) -> list[TPosition]:
'''simple docstring'''
while self.fwd_astar.open_nodes or self.bwd_astar.open_nodes:
self.fwd_astar.open_nodes.sort()
self.bwd_astar.open_nodes.sort()
lowerCAmelCase_ : Any = self.fwd_astar.open_nodes.pop(0 )
lowerCAmelCase_ : Union[str, Any] = self.bwd_astar.open_nodes.pop(0 )
if current_bwd_node.pos == current_fwd_node.pos:
return self.retrace_bidirectional_path(
lowerCAmelCase__ ,lowerCAmelCase__ )
self.fwd_astar.closed_nodes.append(lowerCAmelCase__ )
self.bwd_astar.closed_nodes.append(lowerCAmelCase__ )
lowerCAmelCase_ : Dict = current_bwd_node
lowerCAmelCase_ : Optional[Any] = current_fwd_node
lowerCAmelCase_ : str = {
self.fwd_astar: self.fwd_astar.get_successors(lowerCAmelCase__ ),
self.bwd_astar: self.bwd_astar.get_successors(lowerCAmelCase__ ),
}
for astar in [self.fwd_astar, self.bwd_astar]:
for child_node in successors[astar]:
if child_node in astar.closed_nodes:
continue
if child_node not in astar.open_nodes:
astar.open_nodes.append(lowerCAmelCase__ )
else:
# retrieve the best current path
lowerCAmelCase_ : int = astar.open_nodes.pop(
astar.open_nodes.index(lowerCAmelCase__ ) )
if child_node.g_cost < better_node.g_cost:
astar.open_nodes.append(lowerCAmelCase__ )
else:
astar.open_nodes.append(lowerCAmelCase__ )
return [self.fwd_astar.start.pos]
def UpperCAmelCase_ ( self : Optional[Any] ,lowerCAmelCase__ : Node ,lowerCAmelCase__ : Node ) -> list[TPosition]:
'''simple docstring'''
lowerCAmelCase_ : int = self.fwd_astar.retrace_path(lowerCAmelCase__ )
lowerCAmelCase_ : Dict = self.bwd_astar.retrace_path(lowerCAmelCase__ )
bwd_path.pop()
bwd_path.reverse()
lowerCAmelCase_ : List[Any] = fwd_path + bwd_path
return path
if __name__ == "__main__":
# all coordinates are given in format [y,x]
_lowercase = (0, 0)
_lowercase = (len(grid) - 1, len(grid[0]) - 1)
for elem in grid:
print(elem)
_lowercase = time.time()
_lowercase = AStar(init, goal)
_lowercase = a_star.search()
_lowercase = time.time() - start_time
print(f"AStar execution time = {end_time:f} seconds")
_lowercase = time.time()
_lowercase = BidirectionalAStar(init, goal)
_lowercase = time.time() - bd_start_time
print(f"BidirectionalAStar execution time = {bd_end_time:f} seconds")
| 659 |
from collections.abc import Sequence
def UpperCamelCase ( snake_case__ = None):
if nums is None or not nums:
raise ValueError("Input sequence should not be empty")
lowerCAmelCase_ : Dict = nums[0]
for i in range(1 , len(snake_case__)):
lowerCAmelCase_ : Optional[int] = nums[i]
lowerCAmelCase_ : Optional[int] = max(snake_case__ , ans + num , snake_case__)
return ans
if __name__ == "__main__":
import doctest
doctest.testmod()
# Try on a sample input from the user
_lowercase = int(input('''Enter number of elements : ''').strip())
_lowercase = list(map(int, input('''\nEnter the numbers : ''').strip().split()))[:n]
print(max_subsequence_sum(array))
| 659 | 1 |
# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING
# rely on isort to merge the imports
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available
_lowercase = {
'''configuration_efficientnet''': [
'''EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP''',
'''EfficientNetConfig''',
'''EfficientNetOnnxConfig''',
]
}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowercase = ['''EfficientNetImageProcessor''']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowercase = [
'''EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''EfficientNetForImageClassification''',
'''EfficientNetModel''',
'''EfficientNetPreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_efficientnet import (
EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP,
EfficientNetConfig,
EfficientNetOnnxConfig,
)
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .image_processing_efficientnet import EfficientNetImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_efficientnet import (
EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST,
EfficientNetForImageClassification,
EfficientNetModel,
EfficientNetPreTrainedModel,
)
else:
import sys
_lowercase = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
| 659 |
from typing import TYPE_CHECKING
from ....utils import _LazyModule
_lowercase = {'''tokenization_tapex''': ['''TapexTokenizer''']}
if TYPE_CHECKING:
from .tokenization_tapex import TapexTokenizer
else:
import sys
_lowercase = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
| 659 | 1 |
import unittest
import numpy as np
from transformers import AlbertConfig, is_flax_available
from transformers.testing_utils import require_flax, slow
from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask
if is_flax_available():
import jax.numpy as jnp
from transformers.models.albert.modeling_flax_albert import (
FlaxAlbertForMaskedLM,
FlaxAlbertForMultipleChoice,
FlaxAlbertForPreTraining,
FlaxAlbertForQuestionAnswering,
FlaxAlbertForSequenceClassification,
FlaxAlbertForTokenClassification,
FlaxAlbertModel,
)
class __snake_case ( unittest.TestCase ):
"""simple docstring"""
def __init__( self : int ,lowerCAmelCase__ : List[str] ,lowerCAmelCase__ : str=13 ,lowerCAmelCase__ : int=7 ,lowerCAmelCase__ : Union[str, Any]=True ,lowerCAmelCase__ : str=True ,lowerCAmelCase__ : Dict=True ,lowerCAmelCase__ : str=True ,lowerCAmelCase__ : Optional[int]=99 ,lowerCAmelCase__ : str=32 ,lowerCAmelCase__ : Any=5 ,lowerCAmelCase__ : List[str]=4 ,lowerCAmelCase__ : List[Any]=37 ,lowerCAmelCase__ : Optional[Any]="gelu" ,lowerCAmelCase__ : Union[str, Any]=0.1 ,lowerCAmelCase__ : Dict=0.1 ,lowerCAmelCase__ : Union[str, Any]=5_12 ,lowerCAmelCase__ : List[str]=16 ,lowerCAmelCase__ : Optional[int]=2 ,lowerCAmelCase__ : List[str]=0.02 ,lowerCAmelCase__ : int=4 ,) -> Optional[Any]:
'''simple docstring'''
lowerCAmelCase_ : int = parent
lowerCAmelCase_ : int = batch_size
lowerCAmelCase_ : Optional[Any] = seq_length
lowerCAmelCase_ : Optional[Any] = is_training
lowerCAmelCase_ : List[str] = use_attention_mask
lowerCAmelCase_ : Tuple = use_token_type_ids
lowerCAmelCase_ : Optional[Any] = use_labels
lowerCAmelCase_ : Optional[int] = vocab_size
lowerCAmelCase_ : Optional[int] = hidden_size
lowerCAmelCase_ : Any = num_hidden_layers
lowerCAmelCase_ : List[Any] = num_attention_heads
lowerCAmelCase_ : Optional[int] = intermediate_size
lowerCAmelCase_ : Optional[int] = hidden_act
lowerCAmelCase_ : Optional[Any] = hidden_dropout_prob
lowerCAmelCase_ : Optional[int] = attention_probs_dropout_prob
lowerCAmelCase_ : List[Any] = max_position_embeddings
lowerCAmelCase_ : Dict = type_vocab_size
lowerCAmelCase_ : Union[str, Any] = type_sequence_label_size
lowerCAmelCase_ : Union[str, Any] = initializer_range
lowerCAmelCase_ : List[Any] = num_choices
def UpperCAmelCase_ ( self : List[str] ) -> List[Any]:
'''simple docstring'''
lowerCAmelCase_ : int = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size )
lowerCAmelCase_ : Optional[Any] = None
if self.use_attention_mask:
lowerCAmelCase_ : Union[str, Any] = random_attention_mask([self.batch_size, self.seq_length] )
lowerCAmelCase_ : Dict = None
if self.use_token_type_ids:
lowerCAmelCase_ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] ,self.type_vocab_size )
lowerCAmelCase_ : Optional[int] = AlbertConfig(
vocab_size=self.vocab_size ,hidden_size=self.hidden_size ,num_hidden_layers=self.num_hidden_layers ,num_attention_heads=self.num_attention_heads ,intermediate_size=self.intermediate_size ,hidden_act=self.hidden_act ,hidden_dropout_prob=self.hidden_dropout_prob ,attention_probs_dropout_prob=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,type_vocab_size=self.type_vocab_size ,is_decoder=lowerCAmelCase__ ,initializer_range=self.initializer_range ,)
return config, input_ids, token_type_ids, attention_mask
def UpperCAmelCase_ ( self : Union[str, Any] ) -> Union[str, Any]:
'''simple docstring'''
lowerCAmelCase_ : Optional[int] = self.prepare_config_and_inputs()
lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ : Any = config_and_inputs
lowerCAmelCase_ : Optional[Any] = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": attention_mask}
return config, inputs_dict
@require_flax
class __snake_case ( snake_case__ , unittest.TestCase ):
"""simple docstring"""
UpperCamelCase_ = (
(
FlaxAlbertModel,
FlaxAlbertForPreTraining,
FlaxAlbertForMaskedLM,
FlaxAlbertForMultipleChoice,
FlaxAlbertForQuestionAnswering,
FlaxAlbertForSequenceClassification,
FlaxAlbertForTokenClassification,
FlaxAlbertForQuestionAnswering,
)
if is_flax_available()
else ()
)
def UpperCAmelCase_ ( self : int ) -> Union[str, Any]:
'''simple docstring'''
lowerCAmelCase_ : Dict = FlaxAlbertModelTester(self )
@slow
def UpperCAmelCase_ ( self : Union[str, Any] ) -> List[Any]:
'''simple docstring'''
for model_class_name in self.all_model_classes:
lowerCAmelCase_ : Any = model_class_name.from_pretrained("albert-base-v2" )
lowerCAmelCase_ : Any = model(np.ones((1, 1) ) )
self.assertIsNotNone(lowerCAmelCase__ )
@require_flax
class __snake_case ( unittest.TestCase ):
"""simple docstring"""
@slow
def UpperCAmelCase_ ( self : Any ) -> str:
'''simple docstring'''
lowerCAmelCase_ : Optional[Any] = FlaxAlbertModel.from_pretrained("albert-base-v2" )
lowerCAmelCase_ : str = np.array([[0, 3_45, 2_32, 3_28, 7_40, 1_40, 16_95, 69, 60_78, 15_88, 2]] )
lowerCAmelCase_ : Any = np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] )
lowerCAmelCase_ : Union[str, Any] = model(lowerCAmelCase__ ,attention_mask=lowerCAmelCase__ )[0]
lowerCAmelCase_ : List[Any] = (1, 11, 7_68)
self.assertEqual(output.shape ,lowerCAmelCase__ )
lowerCAmelCase_ : Dict = np.array(
[[[-0.6_513, 1.5_035, -0.2_766], [-0.6_515, 1.5_046, -0.2_780], [-0.6_512, 1.5_049, -0.2_784]]] )
self.assertTrue(jnp.allclose(output[:, 1:4, 1:4] ,lowerCAmelCase__ ,atol=1e-4 ) )
| 659 |
import argparse
import glob
import importlib.util
import os
import re
import black
from doc_builder.style_doc import style_docstrings_in_code
# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_copies.py
_lowercase = '''src/diffusers'''
_lowercase = '''.'''
# This is to make sure the diffusers module imported is the one in the repo.
_lowercase = importlib.util.spec_from_file_location(
'''diffusers''',
os.path.join(DIFFUSERS_PATH, '''__init__.py'''),
submodule_search_locations=[DIFFUSERS_PATH],
)
_lowercase = spec.loader.load_module()
def UpperCamelCase ( snake_case__ , snake_case__):
return line.startswith(snake_case__) or len(snake_case__) <= 1 or re.search(R"^\s*\)(\s*->.*:|:)\s*$" , snake_case__) is not None
def UpperCamelCase ( snake_case__):
lowerCAmelCase_ : Tuple = object_name.split(".")
lowerCAmelCase_ : Union[str, Any] = 0
# First let's find the module where our object lives.
lowerCAmelCase_ : Union[str, Any] = parts[i]
while i < len(snake_case__) and not os.path.isfile(os.path.join(snake_case__ , F'''{module}.py''')):
i += 1
if i < len(snake_case__):
lowerCAmelCase_ : Dict = os.path.join(snake_case__ , parts[i])
if i >= len(snake_case__):
raise ValueError(F'''`object_name` should begin with the name of a module of diffusers but got {object_name}.''')
with open(os.path.join(snake_case__ , F'''{module}.py''') , "r" , encoding="utf-8" , newline="\n") as f:
lowerCAmelCase_ : Optional[Any] = f.readlines()
# Now let's find the class / func in the code!
lowerCAmelCase_ : Union[str, Any] = ""
lowerCAmelCase_ : int = 0
for name in parts[i + 1 :]:
while (
line_index < len(snake_case__) and re.search(RF'''^{indent}(class|def)\s+{name}(\(|\:)''' , lines[line_index]) is None
):
line_index += 1
indent += " "
line_index += 1
if line_index >= len(snake_case__):
raise ValueError(F''' {object_name} does not match any function or class in {module}.''')
# We found the beginning of the class / func, now let's find the end (when the indent diminishes).
lowerCAmelCase_ : Union[str, Any] = line_index
while line_index < len(snake_case__) and _should_continue(lines[line_index] , snake_case__):
line_index += 1
# Clean up empty lines at the end (if any).
while len(lines[line_index - 1]) <= 1:
line_index -= 1
lowerCAmelCase_ : List[str] = lines[start_index:line_index]
return "".join(snake_case__)
_lowercase = re.compile(r'''^(\s*)#\s*Copied from\s+diffusers\.(\S+\.\S+)\s*($|\S.*$)''')
_lowercase = re.compile(r'''^\s*(\S+)->(\S+)(\s+.*|$)''')
_lowercase = re.compile(r'''<FILL\s+[^>]*>''')
def UpperCamelCase ( snake_case__):
lowerCAmelCase_ : Any = code.split("\n")
lowerCAmelCase_ : Any = 0
while idx < len(snake_case__) and len(lines[idx]) == 0:
idx += 1
if idx < len(snake_case__):
return re.search(R"^(\s*)\S" , lines[idx]).groups()[0]
return ""
def UpperCamelCase ( snake_case__):
lowerCAmelCase_ : Dict = len(get_indent(snake_case__)) > 0
if has_indent:
lowerCAmelCase_ : Dict = F'''class Bla:\n{code}'''
lowerCAmelCase_ : Optional[int] = black.Mode(target_versions={black.TargetVersion.PYaa} , line_length=1_19 , preview=snake_case__)
lowerCAmelCase_ : Optional[Any] = black.format_str(snake_case__ , mode=snake_case__)
lowerCAmelCase_ , lowerCAmelCase_ : List[Any] = style_docstrings_in_code(snake_case__)
return result[len("class Bla:\n") :] if has_indent else result
def UpperCamelCase ( snake_case__ , snake_case__=False):
with open(snake_case__ , "r" , encoding="utf-8" , newline="\n") as f:
lowerCAmelCase_ : Tuple = f.readlines()
lowerCAmelCase_ : Tuple = []
lowerCAmelCase_ : Union[str, Any] = 0
# Not a for loop cause `lines` is going to change (if `overwrite=True`).
while line_index < len(snake_case__):
lowerCAmelCase_ : Optional[int] = _re_copy_warning.search(lines[line_index])
if search is None:
line_index += 1
continue
# There is some copied code here, let's retrieve the original.
lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ : str = search.groups()
lowerCAmelCase_ : int = find_code_in_diffusers(snake_case__)
lowerCAmelCase_ : Dict = get_indent(snake_case__)
lowerCAmelCase_ : Union[str, Any] = line_index + 1 if indent == theoretical_indent else line_index + 2
lowerCAmelCase_ : str = theoretical_indent
lowerCAmelCase_ : Union[str, Any] = start_index
# Loop to check the observed code, stop when indentation diminishes or if we see a End copy comment.
lowerCAmelCase_ : Optional[int] = True
while line_index < len(snake_case__) and should_continue:
line_index += 1
if line_index >= len(snake_case__):
break
lowerCAmelCase_ : Dict = lines[line_index]
lowerCAmelCase_ : List[str] = _should_continue(snake_case__ , snake_case__) and re.search(F'''^{indent}# End copy''' , snake_case__) is None
# Clean up empty lines at the end (if any).
while len(lines[line_index - 1]) <= 1:
line_index -= 1
lowerCAmelCase_ : Dict = lines[start_index:line_index]
lowerCAmelCase_ : Optional[int] = "".join(snake_case__)
# Remove any nested `Copied from` comments to avoid circular copies
lowerCAmelCase_ : List[Any] = [line for line in theoretical_code.split("\n") if _re_copy_warning.search(snake_case__) is None]
lowerCAmelCase_ : Optional[Any] = "\n".join(snake_case__)
# Before comparing, use the `replace_pattern` on the original code.
if len(snake_case__) > 0:
lowerCAmelCase_ : List[str] = replace_pattern.replace("with" , "").split(",")
lowerCAmelCase_ : Tuple = [_re_replace_pattern.search(snake_case__) for p in patterns]
for pattern in patterns:
if pattern is None:
continue
lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ : List[str] = pattern.groups()
lowerCAmelCase_ : int = re.sub(snake_case__ , snake_case__ , snake_case__)
if option.strip() == "all-casing":
lowerCAmelCase_ : List[str] = re.sub(obja.lower() , obja.lower() , snake_case__)
lowerCAmelCase_ : int = re.sub(obja.upper() , obja.upper() , snake_case__)
# Blackify after replacement. To be able to do that, we need the header (class or function definition)
# from the previous line
lowerCAmelCase_ : List[Any] = blackify(lines[start_index - 1] + theoretical_code)
lowerCAmelCase_ : Union[str, Any] = theoretical_code[len(lines[start_index - 1]) :]
# Test for a diff and act accordingly.
if observed_code != theoretical_code:
diffs.append([object_name, start_index])
if overwrite:
lowerCAmelCase_ : List[Any] = lines[:start_index] + [theoretical_code] + lines[line_index:]
lowerCAmelCase_ : Union[str, Any] = start_index + 1
if overwrite and len(snake_case__) > 0:
# Warn the user a file has been modified.
print(F'''Detected changes, rewriting {filename}.''')
with open(snake_case__ , "w" , encoding="utf-8" , newline="\n") as f:
f.writelines(snake_case__)
return diffs
def UpperCamelCase ( snake_case__ = False):
lowerCAmelCase_ : Tuple = glob.glob(os.path.join(snake_case__ , "**/*.py") , recursive=snake_case__)
lowerCAmelCase_ : int = []
for filename in all_files:
lowerCAmelCase_ : Union[str, Any] = is_copy_consistent(snake_case__ , snake_case__)
diffs += [F'''- {filename}: copy does not match {d[0]} at line {d[1]}''' for d in new_diffs]
if not overwrite and len(snake_case__) > 0:
lowerCAmelCase_ : Optional[Any] = "\n".join(snake_case__)
raise Exception(
"Found the following copy inconsistencies:\n"
+ diff
+ "\nRun `make fix-copies` or `python utils/check_copies.py --fix_and_overwrite` to fix them.")
if __name__ == "__main__":
_lowercase = argparse.ArgumentParser()
parser.add_argument('''--fix_and_overwrite''', action='''store_true''', help='''Whether to fix inconsistencies.''')
_lowercase = parser.parse_args()
check_copies(args.fix_and_overwrite)
| 659 | 1 |
import torch
import torch.nn as nn
from transformers import CLIPConfig, CLIPVisionModel, PreTrainedModel
from ...utils import logging
_lowercase = logging.get_logger(__name__)
def UpperCamelCase ( snake_case__ , snake_case__):
lowerCAmelCase_ : Optional[int] = nn.functional.normalize(snake_case__)
lowerCAmelCase_ : int = nn.functional.normalize(snake_case__)
return torch.mm(snake_case__ , normalized_text_embeds.t())
class __snake_case ( snake_case__ ):
"""simple docstring"""
UpperCamelCase_ = CLIPConfig
UpperCamelCase_ = ['CLIPEncoderLayer']
def __init__( self : Dict ,lowerCAmelCase__ : CLIPConfig ) -> Optional[int]:
'''simple docstring'''
super().__init__(lowerCAmelCase__ )
lowerCAmelCase_ : Dict = CLIPVisionModel(config.vision_config )
lowerCAmelCase_ : List[Any] = nn.Linear(config.vision_config.hidden_size ,config.projection_dim ,bias=lowerCAmelCase__ )
lowerCAmelCase_ : Optional[Any] = nn.Parameter(torch.ones(17 ,config.projection_dim ) ,requires_grad=lowerCAmelCase__ )
lowerCAmelCase_ : Optional[int] = nn.Parameter(torch.ones(3 ,config.projection_dim ) ,requires_grad=lowerCAmelCase__ )
lowerCAmelCase_ : str = nn.Parameter(torch.ones(17 ) ,requires_grad=lowerCAmelCase__ )
lowerCAmelCase_ : Optional[int] = nn.Parameter(torch.ones(3 ) ,requires_grad=lowerCAmelCase__ )
@torch.no_grad()
def UpperCAmelCase_ ( self : List[Any] ,lowerCAmelCase__ : Dict ,lowerCAmelCase__ : Any ) -> Tuple:
'''simple docstring'''
lowerCAmelCase_ : Optional[Any] = self.vision_model(lowerCAmelCase__ )[1] # pooled_output
lowerCAmelCase_ : Any = self.visual_projection(lowerCAmelCase__ )
# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
lowerCAmelCase_ : List[Any] = cosine_distance(lowerCAmelCase__ ,self.special_care_embeds ).cpu().float().numpy()
lowerCAmelCase_ : List[str] = cosine_distance(lowerCAmelCase__ ,self.concept_embeds ).cpu().float().numpy()
lowerCAmelCase_ : List[Any] = []
lowerCAmelCase_ : List[str] = image_embeds.shape[0]
for i in range(lowerCAmelCase__ ):
lowerCAmelCase_ : Any = {"special_scores": {}, "special_care": [], "concept_scores": {}, "bad_concepts": []}
# increase this value to create a stronger `nfsw` filter
# at the cost of increasing the possibility of filtering benign images
lowerCAmelCase_ : Union[str, Any] = 0.0
for concept_idx in range(len(special_cos_dist[0] ) ):
lowerCAmelCase_ : Union[str, Any] = special_cos_dist[i][concept_idx]
lowerCAmelCase_ : Union[str, Any] = self.special_care_embeds_weights[concept_idx].item()
lowerCAmelCase_ : int = round(concept_cos - concept_threshold + adjustment ,3 )
if result_img["special_scores"][concept_idx] > 0:
result_img["special_care"].append({concept_idx, result_img["special_scores"][concept_idx]} )
lowerCAmelCase_ : Tuple = 0.01
for concept_idx in range(len(cos_dist[0] ) ):
lowerCAmelCase_ : List[str] = cos_dist[i][concept_idx]
lowerCAmelCase_ : Optional[Any] = self.concept_embeds_weights[concept_idx].item()
lowerCAmelCase_ : int = round(concept_cos - concept_threshold + adjustment ,3 )
if result_img["concept_scores"][concept_idx] > 0:
result_img["bad_concepts"].append(lowerCAmelCase__ )
result.append(lowerCAmelCase__ )
lowerCAmelCase_ : Union[str, Any] = [len(res["bad_concepts"] ) > 0 for res in result]
return images, has_nsfw_concepts
@torch.no_grad()
def UpperCAmelCase_ ( self : List[Any] ,lowerCAmelCase__ : torch.FloatTensor ,lowerCAmelCase__ : torch.FloatTensor ) -> str:
'''simple docstring'''
lowerCAmelCase_ : Optional[int] = self.vision_model(lowerCAmelCase__ )[1] # pooled_output
lowerCAmelCase_ : List[Any] = self.visual_projection(lowerCAmelCase__ )
lowerCAmelCase_ : Tuple = cosine_distance(lowerCAmelCase__ ,self.special_care_embeds )
lowerCAmelCase_ : List[str] = cosine_distance(lowerCAmelCase__ ,self.concept_embeds )
# increase this value to create a stronger `nsfw` filter
# at the cost of increasing the possibility of filtering benign images
lowerCAmelCase_ : Tuple = 0.0
lowerCAmelCase_ : Dict = special_cos_dist - self.special_care_embeds_weights + adjustment
# special_scores = special_scores.round(decimals=3)
lowerCAmelCase_ : List[str] = torch.any(special_scores > 0 ,dim=1 )
lowerCAmelCase_ : Any = special_care * 0.01
lowerCAmelCase_ : int = special_adjustment.unsqueeze(1 ).expand(-1 ,cos_dist.shape[1] )
lowerCAmelCase_ : Optional[int] = (cos_dist - self.concept_embeds_weights) + special_adjustment
# concept_scores = concept_scores.round(decimals=3)
lowerCAmelCase_ : List[str] = torch.any(concept_scores > 0 ,dim=1 )
return images, has_nsfw_concepts
| 659 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
_lowercase = logging.get_logger(__name__)
_lowercase = {
'''microsoft/swinv2-tiny-patch4-window8-256''': (
'''https://huggingface.co/microsoft/swinv2-tiny-patch4-window8-256/resolve/main/config.json'''
),
}
class __snake_case ( snake_case__ ):
"""simple docstring"""
UpperCamelCase_ = 'swinv2'
UpperCamelCase_ = {
'num_attention_heads': 'num_heads',
'num_hidden_layers': 'num_layers',
}
def __init__( self : List[Any] ,lowerCAmelCase__ : Optional[int]=2_24 ,lowerCAmelCase__ : Dict=4 ,lowerCAmelCase__ : Dict=3 ,lowerCAmelCase__ : List[Any]=96 ,lowerCAmelCase__ : Optional[Any]=[2, 2, 6, 2] ,lowerCAmelCase__ : Optional[Any]=[3, 6, 12, 24] ,lowerCAmelCase__ : Optional[int]=7 ,lowerCAmelCase__ : Dict=4.0 ,lowerCAmelCase__ : Dict=True ,lowerCAmelCase__ : str=0.0 ,lowerCAmelCase__ : Tuple=0.0 ,lowerCAmelCase__ : str=0.1 ,lowerCAmelCase__ : List[str]="gelu" ,lowerCAmelCase__ : Union[str, Any]=False ,lowerCAmelCase__ : Dict=0.02 ,lowerCAmelCase__ : int=1e-5 ,lowerCAmelCase__ : List[str]=32 ,**lowerCAmelCase__ : Tuple ,) -> List[str]:
'''simple docstring'''
super().__init__(**lowerCAmelCase__ )
lowerCAmelCase_ : Optional[int] = image_size
lowerCAmelCase_ : List[Any] = patch_size
lowerCAmelCase_ : Dict = num_channels
lowerCAmelCase_ : Optional[int] = embed_dim
lowerCAmelCase_ : Optional[Any] = depths
lowerCAmelCase_ : Any = len(lowerCAmelCase__ )
lowerCAmelCase_ : str = num_heads
lowerCAmelCase_ : List[str] = window_size
lowerCAmelCase_ : List[str] = mlp_ratio
lowerCAmelCase_ : Dict = qkv_bias
lowerCAmelCase_ : str = hidden_dropout_prob
lowerCAmelCase_ : str = attention_probs_dropout_prob
lowerCAmelCase_ : Union[str, Any] = drop_path_rate
lowerCAmelCase_ : List[Any] = hidden_act
lowerCAmelCase_ : Any = use_absolute_embeddings
lowerCAmelCase_ : List[str] = layer_norm_eps
lowerCAmelCase_ : int = initializer_range
lowerCAmelCase_ : Union[str, Any] = encoder_stride
# we set the hidden_size attribute in order to make Swinv2 work with VisionEncoderDecoderModel
# this indicates the channel dimension after the last stage of the model
lowerCAmelCase_ : Tuple = int(embed_dim * 2 ** (len(lowerCAmelCase__ ) - 1) )
lowerCAmelCase_ : str = (0, 0, 0, 0)
| 659 | 1 |
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_flax_available,
is_sentencepiece_available,
is_tf_available,
is_tokenizers_available,
is_torch_available,
)
_lowercase = {
'''configuration_xlm_roberta''': [
'''XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP''',
'''XLMRobertaConfig''',
'''XLMRobertaOnnxConfig''',
],
}
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowercase = ['''XLMRobertaTokenizer''']
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowercase = ['''XLMRobertaTokenizerFast''']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowercase = [
'''XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''XLMRobertaForCausalLM''',
'''XLMRobertaForMaskedLM''',
'''XLMRobertaForMultipleChoice''',
'''XLMRobertaForQuestionAnswering''',
'''XLMRobertaForSequenceClassification''',
'''XLMRobertaForTokenClassification''',
'''XLMRobertaModel''',
'''XLMRobertaPreTrainedModel''',
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowercase = [
'''TF_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''TFXLMRobertaForCausalLM''',
'''TFXLMRobertaForMaskedLM''',
'''TFXLMRobertaForMultipleChoice''',
'''TFXLMRobertaForQuestionAnswering''',
'''TFXLMRobertaForSequenceClassification''',
'''TFXLMRobertaForTokenClassification''',
'''TFXLMRobertaModel''',
'''TFXLMRobertaPreTrainedModel''',
]
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowercase = [
'''FLAX_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''FlaxXLMRobertaForMaskedLM''',
'''FlaxXLMRobertaForCausalLM''',
'''FlaxXLMRobertaForMultipleChoice''',
'''FlaxXLMRobertaForQuestionAnswering''',
'''FlaxXLMRobertaForSequenceClassification''',
'''FlaxXLMRobertaForTokenClassification''',
'''FlaxXLMRobertaModel''',
'''FlaxXLMRobertaPreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_xlm_roberta import (
XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP,
XLMRobertaConfig,
XLMRobertaOnnxConfig,
)
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_xlm_roberta import XLMRobertaTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_xlm_roberta_fast import XLMRobertaTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_xlm_roberta import (
XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST,
XLMRobertaForCausalLM,
XLMRobertaForMaskedLM,
XLMRobertaForMultipleChoice,
XLMRobertaForQuestionAnswering,
XLMRobertaForSequenceClassification,
XLMRobertaForTokenClassification,
XLMRobertaModel,
XLMRobertaPreTrainedModel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_xlm_roberta import (
TF_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST,
TFXLMRobertaForCausalLM,
TFXLMRobertaForMaskedLM,
TFXLMRobertaForMultipleChoice,
TFXLMRobertaForQuestionAnswering,
TFXLMRobertaForSequenceClassification,
TFXLMRobertaForTokenClassification,
TFXLMRobertaModel,
TFXLMRobertaPreTrainedModel,
)
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_flax_xlm_roberta import (
FLAX_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST,
FlaxXLMRobertaForCausalLM,
FlaxXLMRobertaForMaskedLM,
FlaxXLMRobertaForMultipleChoice,
FlaxXLMRobertaForQuestionAnswering,
FlaxXLMRobertaForSequenceClassification,
FlaxXLMRobertaForTokenClassification,
FlaxXLMRobertaModel,
FlaxXLMRobertaPreTrainedModel,
)
else:
import sys
_lowercase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 659 |
from typing import List, Optional, Union
import numpy as np
from ....audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function
from ....feature_extraction_sequence_utils import SequenceFeatureExtractor
from ....feature_extraction_utils import BatchFeature
from ....file_utils import PaddingStrategy, TensorType
from ....utils import logging
_lowercase = logging.get_logger(__name__)
class __snake_case ( snake_case__ ):
"""simple docstring"""
UpperCamelCase_ = ['input_features', 'attention_mask']
def __init__( self : Optional[Any] ,lowerCAmelCase__ : Any=80 ,lowerCAmelCase__ : Optional[Any]=1_60_00 ,lowerCAmelCase__ : List[str]=0.0 ,lowerCAmelCase__ : Tuple=10 ,lowerCAmelCase__ : Optional[Any]=25 ,lowerCAmelCase__ : Any="hamming_window" ,lowerCAmelCase__ : List[str]=32_768.0 ,lowerCAmelCase__ : Union[str, Any]=0.97 ,lowerCAmelCase__ : Any=1.0 ,lowerCAmelCase__ : str=True ,lowerCAmelCase__ : int=True ,lowerCAmelCase__ : Tuple=False ,**lowerCAmelCase__ : Optional[int] ,) -> Optional[Any]:
'''simple docstring'''
super().__init__(feature_size=lowerCAmelCase__ ,sampling_rate=lowerCAmelCase__ ,padding_value=lowerCAmelCase__ ,**lowerCAmelCase__ )
lowerCAmelCase_ : Optional[int] = feature_size
lowerCAmelCase_ : List[Any] = sampling_rate
lowerCAmelCase_ : Union[str, Any] = padding_value
lowerCAmelCase_ : str = hop_length
lowerCAmelCase_ : str = win_length
lowerCAmelCase_ : str = frame_signal_scale
lowerCAmelCase_ : Any = preemphasis_coeff
lowerCAmelCase_ : Optional[Any] = mel_floor
lowerCAmelCase_ : List[str] = normalize_means
lowerCAmelCase_ : Optional[Any] = normalize_vars
lowerCAmelCase_ : Dict = win_function
lowerCAmelCase_ : List[Any] = return_attention_mask
lowerCAmelCase_ : Tuple = win_length * sampling_rate // 10_00
lowerCAmelCase_ : str = hop_length * sampling_rate // 10_00
lowerCAmelCase_ : Dict = optimal_fft_length(self.sample_size )
lowerCAmelCase_ : Optional[int] = (self.n_fft // 2) + 1
def UpperCAmelCase_ ( self : List[Any] ,lowerCAmelCase__ : np.array ) -> np.ndarray:
'''simple docstring'''
if self.win_function == "hamming_window":
lowerCAmelCase_ : int = window_function(window_length=self.sample_size ,name=self.win_function ,periodic=lowerCAmelCase__ )
else:
lowerCAmelCase_ : Tuple = window_function(window_length=self.sample_size ,name=self.win_function )
lowerCAmelCase_ : List[str] = mel_filter_bank(
num_frequency_bins=self.n_freqs ,num_mel_filters=self.feature_size ,min_frequency=0.0 ,max_frequency=self.sampling_rate / 2.0 ,sampling_rate=self.sampling_rate ,)
lowerCAmelCase_ : Any = spectrogram(
one_waveform * self.frame_signal_scale ,window=lowerCAmelCase__ ,frame_length=self.sample_size ,hop_length=self.sample_stride ,fft_length=self.n_fft ,center=lowerCAmelCase__ ,preemphasis=self.preemphasis_coeff ,mel_filters=lowerCAmelCase__ ,mel_floor=self.mel_floor ,log_mel="log" ,)
return msfc_features.T
def UpperCAmelCase_ ( self : int ,lowerCAmelCase__ : List[Any] ,lowerCAmelCase__ : Optional[Any] ,lowerCAmelCase__ : Tuple ) -> Optional[Any]:
'''simple docstring'''
if self.normalize_means:
lowerCAmelCase_ : Optional[int] = x[:input_length].mean(axis=0 )
lowerCAmelCase_ : List[str] = np.subtract(lowerCAmelCase__ ,lowerCAmelCase__ )
if self.normalize_vars:
lowerCAmelCase_ : Optional[Any] = x[:input_length].std(axis=0 )
lowerCAmelCase_ : Tuple = np.divide(lowerCAmelCase__ ,lowerCAmelCase__ )
if input_length < x.shape[0]:
lowerCAmelCase_ : int = padding_value
# make sure array is in float32
lowerCAmelCase_ : Any = x.astype(np.floataa )
return x
def UpperCAmelCase_ ( self : List[Any] ,lowerCAmelCase__ : List[np.ndarray] ,lowerCAmelCase__ : Optional[np.ndarray] = None ) -> List[np.ndarray]:
'''simple docstring'''
lowerCAmelCase_ : List[Any] = attention_mask.sum(-1 ) if attention_mask is not None else [x.shape[0] for x in input_features]
return [self._normalize_one(lowerCAmelCase__ ,lowerCAmelCase__ ,self.padding_value ) for x, n in zip(lowerCAmelCase__ ,lowerCAmelCase__ )]
def __call__( self : int ,lowerCAmelCase__ : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] ,lowerCAmelCase__ : Union[bool, str, PaddingStrategy] = False ,lowerCAmelCase__ : Optional[int] = None ,lowerCAmelCase__ : bool = False ,lowerCAmelCase__ : Optional[int] = None ,lowerCAmelCase__ : Optional[bool] = None ,lowerCAmelCase__ : Optional[Union[str, TensorType]] = None ,lowerCAmelCase__ : Optional[int] = None ,**lowerCAmelCase__ : Union[str, Any] ,) -> BatchFeature:
'''simple docstring'''
if sampling_rate is not None:
if sampling_rate != self.sampling_rate:
raise ValueError(
f'''The model corresponding to this feature extractor: {self} was trained using a sampling rate of'''
f''' {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with'''
f''' {self.sampling_rate} and not {sampling_rate}.''' )
else:
logger.warning(
"It is strongly recommended to pass the ``sampling_rate`` argument to this function. "
"Failing to do so can result in silent errors that might be hard to debug." )
lowerCAmelCase_ : List[Any] = isinstance(lowerCAmelCase__ ,np.ndarray ) and len(raw_speech.shape ) > 1
if is_batched_numpy and len(raw_speech.shape ) > 2:
raise ValueError(f'''Only mono-channel audio is supported for input to {self}''' )
lowerCAmelCase_ : str = is_batched_numpy or (
isinstance(lowerCAmelCase__ ,(list, tuple) ) and (isinstance(raw_speech[0] ,(np.ndarray, tuple, list) ))
)
if is_batched:
lowerCAmelCase_ : Tuple = [np.asarray(lowerCAmelCase__ ,dtype=np.floataa ) for speech in raw_speech]
elif not is_batched and not isinstance(lowerCAmelCase__ ,np.ndarray ):
lowerCAmelCase_ : int = np.asarray(lowerCAmelCase__ ,dtype=np.floataa )
elif isinstance(lowerCAmelCase__ ,np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ):
lowerCAmelCase_ : Union[str, Any] = raw_speech.astype(np.floataa )
# always return batch
if not is_batched:
lowerCAmelCase_ : Optional[int] = [raw_speech]
# extract fbank features
lowerCAmelCase_ : Dict = [self._extract_mfsc_features(lowerCAmelCase__ ) for one_waveform in raw_speech]
# convert into correct format for padding
lowerCAmelCase_ : int = BatchFeature({"input_features": features} )
lowerCAmelCase_ : Union[str, Any] = self.pad(
lowerCAmelCase__ ,padding=lowerCAmelCase__ ,max_length=lowerCAmelCase__ ,truncation=lowerCAmelCase__ ,pad_to_multiple_of=lowerCAmelCase__ ,return_attention_mask=lowerCAmelCase__ ,**lowerCAmelCase__ ,)
# make sure list is in array format
lowerCAmelCase_ : Optional[Any] = padded_inputs.get("input_features" )
if isinstance(input_features[0] ,lowerCAmelCase__ ):
lowerCAmelCase_ : Optional[int] = [np.asarray(lowerCAmelCase__ ,dtype=np.floataa ) for feature in input_features]
lowerCAmelCase_ : List[Any] = padded_inputs.get("attention_mask" )
if attention_mask is not None:
lowerCAmelCase_ : Dict = [np.asarray(lowerCAmelCase__ ,dtype=np.intaa ) for array in attention_mask]
if self.normalize_means or self.normalize_vars:
lowerCAmelCase_ : Dict = (
np.array(lowerCAmelCase__ ,dtype=np.intaa )
if self._get_padding_strategies(lowerCAmelCase__ ,max_length=lowerCAmelCase__ ) is not PaddingStrategy.DO_NOT_PAD
and padding
else None
)
lowerCAmelCase_ : List[str] = self.normalize(
padded_inputs["input_features"] ,attention_mask=lowerCAmelCase__ )
if return_tensors is not None:
lowerCAmelCase_ : Dict = padded_inputs.convert_to_tensors(lowerCAmelCase__ )
return padded_inputs
| 659 | 1 |
from typing import Optional, Tuple, Union
import tensorflow as tf
from ...activations_tf import ACTaFN
from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward
from ...modeling_tf_outputs import (
TFBaseModelOutputWithNoAttention,
TFBaseModelOutputWithPoolingAndNoAttention,
TFSequenceClassifierOutput,
)
from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs
from ...tf_utils import shape_list
from ...utils import logging
from .configuration_regnet import RegNetConfig
_lowercase = logging.get_logger(__name__)
# General docstring
_lowercase = '''RegNetConfig'''
# Base docstring
_lowercase = '''facebook/regnet-y-040'''
_lowercase = [1, 1088, 7, 7]
# Image classification docstring
_lowercase = '''facebook/regnet-y-040'''
_lowercase = '''tabby, tabby cat'''
_lowercase = [
'''facebook/regnet-y-040''',
# See all regnet models at https://huggingface.co/models?filter=regnet
]
class __snake_case ( tf.keras.layers.Layer ):
"""simple docstring"""
def __init__( self : str ,lowerCAmelCase__ : int ,lowerCAmelCase__ : int = 3 ,lowerCAmelCase__ : int = 1 ,lowerCAmelCase__ : int = 1 ,lowerCAmelCase__ : Optional[str] = "relu" ,**lowerCAmelCase__ : List[Any] ,) -> List[Any]:
'''simple docstring'''
super().__init__(**lowerCAmelCase__ )
# The padding and conv has been verified in
# https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb
lowerCAmelCase_ : int = tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2 )
lowerCAmelCase_ : List[Any] = tf.keras.layers.ConvaD(
filters=lowerCAmelCase__ ,kernel_size=lowerCAmelCase__ ,strides=lowerCAmelCase__ ,padding="VALID" ,groups=lowerCAmelCase__ ,use_bias=lowerCAmelCase__ ,name="convolution" ,)
lowerCAmelCase_ : Union[str, Any] = tf.keras.layers.BatchNormalization(epsilon=1e-5 ,momentum=0.9 ,name="normalization" )
lowerCAmelCase_ : Tuple = ACTaFN[activation] if activation is not None else tf.identity
def UpperCAmelCase_ ( self : Optional[Any] ,lowerCAmelCase__ : List[str] ) -> Dict:
'''simple docstring'''
lowerCAmelCase_ : List[str] = self.convolution(self.padding(lowerCAmelCase__ ) )
lowerCAmelCase_ : Optional[int] = self.normalization(lowerCAmelCase__ )
lowerCAmelCase_ : Dict = self.activation(lowerCAmelCase__ )
return hidden_state
class __snake_case ( tf.keras.layers.Layer ):
"""simple docstring"""
def __init__( self : Any ,lowerCAmelCase__ : RegNetConfig ,**lowerCAmelCase__ : Any ) -> str:
'''simple docstring'''
super().__init__(**lowerCAmelCase__ )
lowerCAmelCase_ : Dict = config.num_channels
lowerCAmelCase_ : int = TFRegNetConvLayer(
out_channels=config.embedding_size ,kernel_size=3 ,stride=2 ,activation=config.hidden_act ,name="embedder" ,)
def UpperCAmelCase_ ( self : Optional[Any] ,lowerCAmelCase__ : Any ) -> Union[str, Any]:
'''simple docstring'''
lowerCAmelCase_ : str = shape_list(lowerCAmelCase__ )[1]
if tf.executing_eagerly() and num_channels != self.num_channels:
raise ValueError(
"Make sure that the channel dimension of the pixel values match with the one set in the configuration." )
# When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format.
# So change the input format from `NCHW` to `NHWC`.
# shape = (batch_size, in_height, in_width, in_channels=num_channels)
lowerCAmelCase_ : Any = tf.transpose(lowerCAmelCase__ ,perm=(0, 2, 3, 1) )
lowerCAmelCase_ : Optional[Any] = self.embedder(lowerCAmelCase__ )
return hidden_state
class __snake_case ( tf.keras.layers.Layer ):
"""simple docstring"""
def __init__( self : str ,lowerCAmelCase__ : int ,lowerCAmelCase__ : int = 2 ,**lowerCAmelCase__ : Dict ) -> Tuple:
'''simple docstring'''
super().__init__(**lowerCAmelCase__ )
lowerCAmelCase_ : Union[str, Any] = tf.keras.layers.ConvaD(
filters=lowerCAmelCase__ ,kernel_size=1 ,strides=lowerCAmelCase__ ,use_bias=lowerCAmelCase__ ,name="convolution" )
lowerCAmelCase_ : Optional[Any] = tf.keras.layers.BatchNormalization(epsilon=1e-5 ,momentum=0.9 ,name="normalization" )
def UpperCAmelCase_ ( self : Optional[Any] ,lowerCAmelCase__ : tf.Tensor ,lowerCAmelCase__ : bool = False ) -> tf.Tensor:
'''simple docstring'''
return self.normalization(self.convolution(lowerCAmelCase__ ) ,training=lowerCAmelCase__ )
class __snake_case ( tf.keras.layers.Layer ):
"""simple docstring"""
def __init__( self : List[str] ,lowerCAmelCase__ : int ,lowerCAmelCase__ : int ,**lowerCAmelCase__ : Tuple ) -> Union[str, Any]:
'''simple docstring'''
super().__init__(**lowerCAmelCase__ )
lowerCAmelCase_ : int = tf.keras.layers.GlobalAveragePoolingaD(keepdims=lowerCAmelCase__ ,name="pooler" )
lowerCAmelCase_ : Optional[int] = [
tf.keras.layers.ConvaD(filters=lowerCAmelCase__ ,kernel_size=1 ,activation="relu" ,name="attention.0" ),
tf.keras.layers.ConvaD(filters=lowerCAmelCase__ ,kernel_size=1 ,activation="sigmoid" ,name="attention.2" ),
]
def UpperCAmelCase_ ( self : Optional[int] ,lowerCAmelCase__ : Optional[int] ) -> str:
'''simple docstring'''
lowerCAmelCase_ : Tuple = self.pooler(lowerCAmelCase__ )
for layer_module in self.attention:
lowerCAmelCase_ : Optional[Any] = layer_module(lowerCAmelCase__ )
lowerCAmelCase_ : Union[str, Any] = hidden_state * pooled
return hidden_state
class __snake_case ( tf.keras.layers.Layer ):
"""simple docstring"""
def __init__( self : Any ,lowerCAmelCase__ : RegNetConfig ,lowerCAmelCase__ : int ,lowerCAmelCase__ : int ,lowerCAmelCase__ : int = 1 ,**lowerCAmelCase__ : Any ) -> Tuple:
'''simple docstring'''
super().__init__(**lowerCAmelCase__ )
lowerCAmelCase_ : Any = in_channels != out_channels or stride != 1
lowerCAmelCase_ : List[str] = max(1 ,out_channels // config.groups_width )
lowerCAmelCase_ : List[str] = (
TFRegNetShortCut(lowerCAmelCase__ ,stride=lowerCAmelCase__ ,name="shortcut" )
if should_apply_shortcut
else tf.keras.layers.Activation("linear" ,name="shortcut" )
)
# `self.layers` instead of `self.layer` because that is a reserved argument.
lowerCAmelCase_ : List[str] = [
TFRegNetConvLayer(lowerCAmelCase__ ,kernel_size=1 ,activation=config.hidden_act ,name="layer.0" ),
TFRegNetConvLayer(
lowerCAmelCase__ ,stride=lowerCAmelCase__ ,groups=lowerCAmelCase__ ,activation=config.hidden_act ,name="layer.1" ),
TFRegNetConvLayer(lowerCAmelCase__ ,kernel_size=1 ,activation=lowerCAmelCase__ ,name="layer.2" ),
]
lowerCAmelCase_ : Any = ACTaFN[config.hidden_act]
def UpperCAmelCase_ ( self : List[Any] ,lowerCAmelCase__ : Optional[int] ) -> Dict:
'''simple docstring'''
lowerCAmelCase_ : Dict = hidden_state
for layer_module in self.layers:
lowerCAmelCase_ : List[str] = layer_module(lowerCAmelCase__ )
lowerCAmelCase_ : List[Any] = self.shortcut(lowerCAmelCase__ )
hidden_state += residual
lowerCAmelCase_ : Dict = self.activation(lowerCAmelCase__ )
return hidden_state
class __snake_case ( tf.keras.layers.Layer ):
"""simple docstring"""
def __init__( self : Optional[int] ,lowerCAmelCase__ : RegNetConfig ,lowerCAmelCase__ : int ,lowerCAmelCase__ : int ,lowerCAmelCase__ : int = 1 ,**lowerCAmelCase__ : Any ) -> str:
'''simple docstring'''
super().__init__(**lowerCAmelCase__ )
lowerCAmelCase_ : Any = in_channels != out_channels or stride != 1
lowerCAmelCase_ : Optional[int] = max(1 ,out_channels // config.groups_width )
lowerCAmelCase_ : Dict = (
TFRegNetShortCut(lowerCAmelCase__ ,stride=lowerCAmelCase__ ,name="shortcut" )
if should_apply_shortcut
else tf.keras.layers.Activation("linear" ,name="shortcut" )
)
lowerCAmelCase_ : str = [
TFRegNetConvLayer(lowerCAmelCase__ ,kernel_size=1 ,activation=config.hidden_act ,name="layer.0" ),
TFRegNetConvLayer(
lowerCAmelCase__ ,stride=lowerCAmelCase__ ,groups=lowerCAmelCase__ ,activation=config.hidden_act ,name="layer.1" ),
TFRegNetSELayer(lowerCAmelCase__ ,reduced_channels=int(round(in_channels / 4 ) ) ,name="layer.2" ),
TFRegNetConvLayer(lowerCAmelCase__ ,kernel_size=1 ,activation=lowerCAmelCase__ ,name="layer.3" ),
]
lowerCAmelCase_ : int = ACTaFN[config.hidden_act]
def UpperCAmelCase_ ( self : Tuple ,lowerCAmelCase__ : Optional[Any] ) -> Tuple:
'''simple docstring'''
lowerCAmelCase_ : List[str] = hidden_state
for layer_module in self.layers:
lowerCAmelCase_ : Tuple = layer_module(lowerCAmelCase__ )
lowerCAmelCase_ : str = self.shortcut(lowerCAmelCase__ )
hidden_state += residual
lowerCAmelCase_ : int = self.activation(lowerCAmelCase__ )
return hidden_state
class __snake_case ( tf.keras.layers.Layer ):
"""simple docstring"""
def __init__( self : Optional[Any] ,lowerCAmelCase__ : RegNetConfig ,lowerCAmelCase__ : int ,lowerCAmelCase__ : int ,lowerCAmelCase__ : int = 2 ,lowerCAmelCase__ : int = 2 ,**lowerCAmelCase__ : Dict ) -> int:
'''simple docstring'''
super().__init__(**lowerCAmelCase__ )
lowerCAmelCase_ : Union[str, Any] = TFRegNetXLayer if config.layer_type == "x" else TFRegNetYLayer
lowerCAmelCase_ : Dict = [
# downsampling is done in the first layer with stride of 2
layer(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,stride=lowerCAmelCase__ ,name="layers.0" ),
*[layer(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,name=f'''layers.{i+1}''' ) for i in range(depth - 1 )],
]
def UpperCAmelCase_ ( self : Optional[int] ,lowerCAmelCase__ : List[str] ) -> Dict:
'''simple docstring'''
for layer_module in self.layers:
lowerCAmelCase_ : List[Any] = layer_module(lowerCAmelCase__ )
return hidden_state
class __snake_case ( tf.keras.layers.Layer ):
"""simple docstring"""
def __init__( self : List[Any] ,lowerCAmelCase__ : RegNetConfig ,**lowerCAmelCase__ : Optional[Any] ) -> Optional[Any]:
'''simple docstring'''
super().__init__(**lowerCAmelCase__ )
lowerCAmelCase_ : List[str] = []
# based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input
self.stages.append(
TFRegNetStage(
lowerCAmelCase__ ,config.embedding_size ,config.hidden_sizes[0] ,stride=2 if config.downsample_in_first_stage else 1 ,depth=config.depths[0] ,name="stages.0" ,) )
lowerCAmelCase_ : Union[str, Any] = zip(config.hidden_sizes ,config.hidden_sizes[1:] )
for i, ((in_channels, out_channels), depth) in enumerate(zip(lowerCAmelCase__ ,config.depths[1:] ) ):
self.stages.append(TFRegNetStage(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,depth=lowerCAmelCase__ ,name=f'''stages.{i+1}''' ) )
def UpperCAmelCase_ ( self : List[Any] ,lowerCAmelCase__ : tf.Tensor ,lowerCAmelCase__ : bool = False ,lowerCAmelCase__ : bool = True ) -> TFBaseModelOutputWithNoAttention:
'''simple docstring'''
lowerCAmelCase_ : Dict = () if output_hidden_states else None
for stage_module in self.stages:
if output_hidden_states:
lowerCAmelCase_ : Any = hidden_states + (hidden_state,)
lowerCAmelCase_ : List[str] = stage_module(lowerCAmelCase__ )
if output_hidden_states:
lowerCAmelCase_ : List[str] = hidden_states + (hidden_state,)
if not return_dict:
return tuple(v for v in [hidden_state, hidden_states] if v is not None )
return TFBaseModelOutputWithNoAttention(last_hidden_state=lowerCAmelCase__ ,hidden_states=lowerCAmelCase__ )
@keras_serializable
class __snake_case ( tf.keras.layers.Layer ):
"""simple docstring"""
UpperCamelCase_ = RegNetConfig
def __init__( self : Any ,lowerCAmelCase__ : Union[str, Any] ,**lowerCAmelCase__ : str ) -> Optional[int]:
'''simple docstring'''
super().__init__(**lowerCAmelCase__ )
lowerCAmelCase_ : Optional[int] = config
lowerCAmelCase_ : int = TFRegNetEmbeddings(lowerCAmelCase__ ,name="embedder" )
lowerCAmelCase_ : Any = TFRegNetEncoder(lowerCAmelCase__ ,name="encoder" )
lowerCAmelCase_ : str = tf.keras.layers.GlobalAveragePoolingaD(keepdims=lowerCAmelCase__ ,name="pooler" )
@unpack_inputs
def UpperCAmelCase_ ( self : int ,lowerCAmelCase__ : tf.Tensor ,lowerCAmelCase__ : Optional[bool] = None ,lowerCAmelCase__ : Optional[bool] = None ,lowerCAmelCase__ : bool = False ,) -> TFBaseModelOutputWithPoolingAndNoAttention:
'''simple docstring'''
lowerCAmelCase_ : Union[str, Any] = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
lowerCAmelCase_ : Optional[int] = return_dict if return_dict is not None else self.config.use_return_dict
lowerCAmelCase_ : int = self.embedder(lowerCAmelCase__ ,training=lowerCAmelCase__ )
lowerCAmelCase_ : Tuple = self.encoder(
lowerCAmelCase__ ,output_hidden_states=lowerCAmelCase__ ,return_dict=lowerCAmelCase__ ,training=lowerCAmelCase__ )
lowerCAmelCase_ : Any = encoder_outputs[0]
lowerCAmelCase_ : Any = self.pooler(lowerCAmelCase__ )
# Change to NCHW output format have uniformity in the modules
lowerCAmelCase_ : Union[str, Any] = tf.transpose(lowerCAmelCase__ ,perm=(0, 3, 1, 2) )
lowerCAmelCase_ : Dict = tf.transpose(lowerCAmelCase__ ,perm=(0, 3, 1, 2) )
# Change the other hidden state outputs to NCHW as well
if output_hidden_states:
lowerCAmelCase_ : Optional[int] = tuple([tf.transpose(lowerCAmelCase__ ,perm=(0, 3, 1, 2) ) for h in encoder_outputs[1]] )
if not return_dict:
return (last_hidden_state, pooled_output) + encoder_outputs[1:]
return TFBaseModelOutputWithPoolingAndNoAttention(
last_hidden_state=lowerCAmelCase__ ,pooler_output=lowerCAmelCase__ ,hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states ,)
class __snake_case ( snake_case__ ):
"""simple docstring"""
UpperCamelCase_ = RegNetConfig
UpperCamelCase_ = 'regnet'
UpperCamelCase_ = 'pixel_values'
@property
def UpperCAmelCase_ ( self : Optional[Any] ) -> List[Any]:
'''simple docstring'''
return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 2_24, 2_24) ,dtype=tf.floataa )}
_lowercase = r'''
Parameters:
This model is a Tensorflow
[tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a
regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and
behavior.
config ([`RegNetConfig`]): Model configuration class with all the parameters of the model.
Initializing with a config file does not load the weights associated with the model, only the
configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.
'''
_lowercase = r'''
Args:
pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`):
Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
[`ConveNextImageProcessor.__call__`] for details.
output_hidden_states (`bool`, *optional*):
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
more detail.
return_dict (`bool`, *optional*):
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
'''
@add_start_docstrings(
'The bare RegNet model outputting raw features without any specific head on top.' , snake_case__ , )
class __snake_case ( snake_case__ ):
"""simple docstring"""
def __init__( self : Optional[int] ,lowerCAmelCase__ : RegNetConfig ,*lowerCAmelCase__ : Union[str, Any] ,**lowerCAmelCase__ : Dict ) -> Optional[Any]:
'''simple docstring'''
super().__init__(lowerCAmelCase__ ,*lowerCAmelCase__ ,**lowerCAmelCase__ )
lowerCAmelCase_ : int = TFRegNetMainLayer(lowerCAmelCase__ ,name="regnet" )
@unpack_inputs
@add_start_docstrings_to_model_forward(lowerCAmelCase__ )
@add_code_sample_docstrings(
checkpoint=_CHECKPOINT_FOR_DOC ,output_type=lowerCAmelCase__ ,config_class=_CONFIG_FOR_DOC ,modality="vision" ,expected_output=_EXPECTED_OUTPUT_SHAPE ,)
def UpperCAmelCase_ ( self : Union[str, Any] ,lowerCAmelCase__ : tf.Tensor ,lowerCAmelCase__ : Optional[bool] = None ,lowerCAmelCase__ : Optional[bool] = None ,lowerCAmelCase__ : Tuple=False ,) -> Union[TFBaseModelOutputWithPoolingAndNoAttention, Tuple[tf.Tensor]]:
'''simple docstring'''
lowerCAmelCase_ : List[str] = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
lowerCAmelCase_ : List[str] = return_dict if return_dict is not None else self.config.use_return_dict
lowerCAmelCase_ : Optional[int] = self.regnet(
pixel_values=lowerCAmelCase__ ,output_hidden_states=lowerCAmelCase__ ,return_dict=lowerCAmelCase__ ,training=lowerCAmelCase__ ,)
if not return_dict:
return (outputs[0],) + outputs[1:]
return TFBaseModelOutputWithPoolingAndNoAttention(
last_hidden_state=outputs.last_hidden_state ,pooler_output=outputs.pooler_output ,hidden_states=outputs.hidden_states ,)
@add_start_docstrings(
'\n RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n ' , snake_case__ , )
class __snake_case ( snake_case__ , snake_case__ ):
"""simple docstring"""
def __init__( self : Union[str, Any] ,lowerCAmelCase__ : RegNetConfig ,*lowerCAmelCase__ : List[Any] ,**lowerCAmelCase__ : Optional[Any] ) -> List[Any]:
'''simple docstring'''
super().__init__(lowerCAmelCase__ ,*lowerCAmelCase__ ,**lowerCAmelCase__ )
lowerCAmelCase_ : Union[str, Any] = config.num_labels
lowerCAmelCase_ : Optional[int] = TFRegNetMainLayer(lowerCAmelCase__ ,name="regnet" )
# classification head
lowerCAmelCase_ : List[str] = [
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(config.num_labels ,name="classifier.1" ) if config.num_labels > 0 else tf.identity,
]
@unpack_inputs
@add_start_docstrings_to_model_forward(lowerCAmelCase__ )
@add_code_sample_docstrings(
checkpoint=_IMAGE_CLASS_CHECKPOINT ,output_type=lowerCAmelCase__ ,config_class=_CONFIG_FOR_DOC ,expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT ,)
def UpperCAmelCase_ ( self : int ,lowerCAmelCase__ : tf.Tensor = None ,lowerCAmelCase__ : tf.Tensor = None ,lowerCAmelCase__ : bool = None ,lowerCAmelCase__ : bool = None ,lowerCAmelCase__ : Any=False ,) -> Union[TFSequenceClassifierOutput, Tuple[tf.Tensor]]:
'''simple docstring'''
lowerCAmelCase_ : Dict = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
lowerCAmelCase_ : Tuple = return_dict if return_dict is not None else self.config.use_return_dict
lowerCAmelCase_ : Tuple = self.regnet(
lowerCAmelCase__ ,output_hidden_states=lowerCAmelCase__ ,return_dict=lowerCAmelCase__ ,training=lowerCAmelCase__ )
lowerCAmelCase_ : List[str] = outputs.pooler_output if return_dict else outputs[1]
lowerCAmelCase_ : List[Any] = self.classifier[0](lowerCAmelCase__ )
lowerCAmelCase_ : int = self.classifier[1](lowerCAmelCase__ )
lowerCAmelCase_ : Optional[int] = None if labels is None else self.hf_compute_loss(labels=lowerCAmelCase__ ,logits=lowerCAmelCase__ )
if not return_dict:
lowerCAmelCase_ : Optional[int] = (logits,) + outputs[2:]
return ((loss,) + output) if loss is not None else output
return TFSequenceClassifierOutput(loss=lowerCAmelCase__ ,logits=lowerCAmelCase__ ,hidden_states=outputs.hidden_states )
| 659 |
from __future__ import annotations
# This is the precision for this function which can be altered.
# It is recommended for users to keep this number greater than or equal to 10.
_lowercase = 10
def UpperCamelCase ( snake_case__ , snake_case__ , snake_case__ , snake_case__):
for i in range(snake_case__ , snake_case__):
if array[i] == target:
return i
return -1
def UpperCamelCase ( snake_case__ , snake_case__):
lowerCAmelCase_ : List[str] = 0
lowerCAmelCase_ : Tuple = len(snake_case__)
while left <= right:
if right - left < precision:
return lin_search(snake_case__ , snake_case__ , snake_case__ , snake_case__)
lowerCAmelCase_ : List[str] = (left + right) // 3 + 1
lowerCAmelCase_ : Tuple = 2 * (left + right) // 3 + 1
if array[one_third] == target:
return one_third
elif array[two_third] == target:
return two_third
elif target < array[one_third]:
lowerCAmelCase_ : str = one_third - 1
elif array[two_third] < target:
lowerCAmelCase_ : Any = two_third + 1
else:
lowerCAmelCase_ : List[str] = one_third + 1
lowerCAmelCase_ : Tuple = two_third - 1
else:
return -1
def UpperCamelCase ( snake_case__ , snake_case__ , snake_case__ , snake_case__):
if left < right:
if right - left < precision:
return lin_search(snake_case__ , snake_case__ , snake_case__ , snake_case__)
lowerCAmelCase_ : Dict = (left + right) // 3 + 1
lowerCAmelCase_ : List[Any] = 2 * (left + right) // 3 + 1
if array[one_third] == target:
return one_third
elif array[two_third] == target:
return two_third
elif target < array[one_third]:
return rec_ternary_search(snake_case__ , one_third - 1 , snake_case__ , snake_case__)
elif array[two_third] < target:
return rec_ternary_search(two_third + 1 , snake_case__ , snake_case__ , snake_case__)
else:
return rec_ternary_search(one_third + 1 , two_third - 1 , snake_case__ , snake_case__)
else:
return -1
if __name__ == "__main__":
import doctest
doctest.testmod()
_lowercase = input('''Enter numbers separated by comma:\n''').strip()
_lowercase = [int(item.strip()) for item in user_input.split(''',''')]
assert collection == sorted(collection), f"List must be ordered.\n{collection}."
_lowercase = int(input('''Enter the number to be found in the list:\n''').strip())
_lowercase = ite_ternary_search(collection, target)
_lowercase = rec_ternary_search(0, len(collection) - 1, collection, target)
if resulta != -1:
print(f"Iterative search: {target} found at positions: {resulta}")
print(f"Recursive search: {target} found at positions: {resulta}")
else:
print('''Not found''')
| 659 | 1 |
import unittest
from transformers import is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
if is_torch_available():
import torch
from transformers import AutoModelForImageClassification
if is_vision_available():
from transformers import AutoImageProcessor
@require_torch
@require_vision
class __snake_case ( unittest.TestCase ):
"""simple docstring"""
@slow
def UpperCAmelCase_ ( self : Any ) -> int:
'''simple docstring'''
lowerCAmelCase_ : Any = AutoImageProcessor.from_pretrained("microsoft/dit-base-finetuned-rvlcdip" )
lowerCAmelCase_ : str = AutoModelForImageClassification.from_pretrained("microsoft/dit-base-finetuned-rvlcdip" )
model.to(lowerCAmelCase__ )
from datasets import load_dataset
lowerCAmelCase_ : Any = load_dataset("nielsr/rvlcdip-demo" )
lowerCAmelCase_ : List[Any] = dataset["train"][0]["image"].convert("RGB" )
lowerCAmelCase_ : Optional[int] = image_processor(lowerCAmelCase__ ,return_tensors="pt" ).to(lowerCAmelCase__ )
# forward pass
with torch.no_grad():
lowerCAmelCase_ : Union[str, Any] = model(**lowerCAmelCase__ )
lowerCAmelCase_ : Dict = outputs.logits
lowerCAmelCase_ : int = torch.Size((1, 16) )
self.assertEqual(logits.shape ,lowerCAmelCase__ )
lowerCAmelCase_ : List[Any] = torch.tensor(
[-0.4_158, -0.4_092, -0.4_347] ,device=lowerCAmelCase__ ,dtype=torch.float ,)
self.assertTrue(torch.allclose(logits[0, :3] ,lowerCAmelCase__ ,atol=1e-4 ) )
| 659 |
from typing import List, Optional
from tokenizers import ByteLevelBPETokenizer
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_blenderbot_small import BlenderbotSmallTokenizer
_lowercase = logging.get_logger(__name__)
_lowercase = {
'''vocab_file''': '''vocab.json''',
'''merges_file''': '''merges.txt''',
'''tokenizer_config_file''': '''tokenizer_config.json''',
}
_lowercase = {
'''vocab_file''': {
'''facebook/blenderbot_small-90M''': '''https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/vocab.json'''
},
'''merges_file''': {
'''facebook/blenderbot_small-90M''': '''https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/merges.txt'''
},
'''tokenizer_config_file''': {
'''facebook/blenderbot_small-90M''': (
'''https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/tokenizer_config.json'''
)
},
}
_lowercase = {
'''facebook/blenderbot_small-90M''': 512,
}
class __snake_case ( snake_case__ ):
"""simple docstring"""
UpperCamelCase_ = VOCAB_FILES_NAMES
UpperCamelCase_ = PRETRAINED_VOCAB_FILES_MAP
UpperCamelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
UpperCamelCase_ = BlenderbotSmallTokenizer
def __init__( self : Optional[int] ,lowerCAmelCase__ : Optional[int]=None ,lowerCAmelCase__ : Union[str, Any]=None ,lowerCAmelCase__ : Any="<|endoftext|>" ,lowerCAmelCase__ : int="<|endoftext|>" ,lowerCAmelCase__ : Optional[Any]="<|endoftext|>" ,lowerCAmelCase__ : Union[str, Any]=False ,lowerCAmelCase__ : Optional[Any]=True ,**lowerCAmelCase__ : Union[str, Any] ,) -> str:
'''simple docstring'''
super().__init__(
ByteLevelBPETokenizer(
vocab=lowerCAmelCase__ ,merges=lowerCAmelCase__ ,add_prefix_space=lowerCAmelCase__ ,trim_offsets=lowerCAmelCase__ ,) ,bos_token=lowerCAmelCase__ ,eos_token=lowerCAmelCase__ ,unk_token=lowerCAmelCase__ ,**lowerCAmelCase__ ,)
lowerCAmelCase_ : Dict = add_prefix_space
def UpperCAmelCase_ ( self : int ,lowerCAmelCase__ : List[str] ,lowerCAmelCase__ : Tuple=None ) -> Optional[int]:
'''simple docstring'''
lowerCAmelCase_ : str = [self.bos_token_id] + token_ids_a + [self.eos_token_id]
if token_ids_a is None:
return output
return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id]
def UpperCAmelCase_ ( self : int ,lowerCAmelCase__ : List[int] ,lowerCAmelCase__ : Optional[List[int]] = None ) -> List[int]:
'''simple docstring'''
lowerCAmelCase_ : Dict = [self.sep_token_id]
lowerCAmelCase_ : Optional[Any] = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
| 659 | 1 |
# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING
# rely on isort to merge the imports
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available
_lowercase = {'''configuration_mra''': ['''MRA_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MraConfig''']}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowercase = [
'''MRA_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''MraForMaskedLM''',
'''MraForMultipleChoice''',
'''MraForQuestionAnswering''',
'''MraForSequenceClassification''',
'''MraForTokenClassification''',
'''MraLayer''',
'''MraModel''',
'''MraPreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_mra import MRA_PRETRAINED_CONFIG_ARCHIVE_MAP, MraConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_mra import (
MRA_PRETRAINED_MODEL_ARCHIVE_LIST,
MraForMaskedLM,
MraForMultipleChoice,
MraForQuestionAnswering,
MraForSequenceClassification,
MraForTokenClassification,
MraLayer,
MraModel,
MraPreTrainedModel,
)
else:
import sys
_lowercase = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
| 659 |
from collections.abc import Generator
from math import sin
def UpperCamelCase ( snake_case__):
if len(snake_case__) != 32:
raise ValueError("Input must be of length 32")
lowerCAmelCase_ : Tuple = b""
for i in [3, 2, 1, 0]:
little_endian += string_aa[8 * i : 8 * i + 8]
return little_endian
def UpperCamelCase ( snake_case__):
if i < 0:
raise ValueError("Input must be non-negative")
lowerCAmelCase_ : List[str] = format(snake_case__ , "08x")[-8:]
lowerCAmelCase_ : Any = b""
for i in [3, 2, 1, 0]:
little_endian_hex += hex_rep[2 * i : 2 * i + 2].encode("utf-8")
return little_endian_hex
def UpperCamelCase ( snake_case__):
lowerCAmelCase_ : Union[str, Any] = b""
for char in message:
bit_string += format(snake_case__ , "08b").encode("utf-8")
lowerCAmelCase_ : Optional[int] = format(len(snake_case__) , "064b").encode("utf-8")
# Pad bit_string to a multiple of 512 chars
bit_string += b"1"
while len(snake_case__) % 5_12 != 4_48:
bit_string += b"0"
bit_string += to_little_endian(start_len[32:]) + to_little_endian(start_len[:32])
return bit_string
def UpperCamelCase ( snake_case__):
if len(snake_case__) % 5_12 != 0:
raise ValueError("Input must have length that's a multiple of 512")
for pos in range(0 , len(snake_case__) , 5_12):
lowerCAmelCase_ : List[str] = bit_string[pos : pos + 5_12]
lowerCAmelCase_ : Union[str, Any] = []
for i in range(0 , 5_12 , 32):
block_words.append(int(to_little_endian(block[i : i + 32]) , 2))
yield block_words
def UpperCamelCase ( snake_case__):
if i < 0:
raise ValueError("Input must be non-negative")
lowerCAmelCase_ : Dict = format(snake_case__ , "032b")
lowerCAmelCase_ : str = ""
for c in i_str:
new_str += "1" if c == "0" else "0"
return int(snake_case__ , 2)
def UpperCamelCase ( snake_case__ , snake_case__):
return (a + b) % 2**32
def UpperCamelCase ( snake_case__ , snake_case__):
if i < 0:
raise ValueError("Input must be non-negative")
if shift < 0:
raise ValueError("Shift must be non-negative")
return ((i << shift) ^ (i >> (32 - shift))) % 2**32
def UpperCamelCase ( snake_case__):
lowerCAmelCase_ : Optional[Any] = preprocess(snake_case__)
lowerCAmelCase_ : Optional[Any] = [int(2**32 * abs(sin(i + 1))) for i in range(64)]
# Starting states
lowerCAmelCase_ : List[str] = 0x67_45_23_01
lowerCAmelCase_ : Union[str, Any] = 0xef_cd_ab_89
lowerCAmelCase_ : List[Any] = 0x98_ba_dc_fe
lowerCAmelCase_ : Tuple = 0x10_32_54_76
lowerCAmelCase_ : Any = [
7,
12,
17,
22,
7,
12,
17,
22,
7,
12,
17,
22,
7,
12,
17,
22,
5,
9,
14,
20,
5,
9,
14,
20,
5,
9,
14,
20,
5,
9,
14,
20,
4,
11,
16,
23,
4,
11,
16,
23,
4,
11,
16,
23,
4,
11,
16,
23,
6,
10,
15,
21,
6,
10,
15,
21,
6,
10,
15,
21,
6,
10,
15,
21,
]
# Process bit string in chunks, each with 16 32-char words
for block_words in get_block_words(snake_case__):
lowerCAmelCase_ : Optional[int] = aa
lowerCAmelCase_ : List[str] = ba
lowerCAmelCase_ : Any = ca
lowerCAmelCase_ : Union[str, Any] = da
# Hash current chunk
for i in range(64):
if i <= 15:
# f = (b & c) | (not_32(b) & d) # Alternate definition for f
lowerCAmelCase_ : Any = d ^ (b & (c ^ d))
lowerCAmelCase_ : Dict = i
elif i <= 31:
# f = (d & b) | (not_32(d) & c) # Alternate definition for f
lowerCAmelCase_ : Any = c ^ (d & (b ^ c))
lowerCAmelCase_ : List[str] = (5 * i + 1) % 16
elif i <= 47:
lowerCAmelCase_ : int = b ^ c ^ d
lowerCAmelCase_ : Optional[Any] = (3 * i + 5) % 16
else:
lowerCAmelCase_ : List[Any] = c ^ (b | not_aa(snake_case__))
lowerCAmelCase_ : List[Any] = (7 * i) % 16
lowerCAmelCase_ : Optional[Any] = (f + a + added_consts[i] + block_words[g]) % 2**32
lowerCAmelCase_ : Optional[Any] = d
lowerCAmelCase_ : Dict = c
lowerCAmelCase_ : List[str] = b
lowerCAmelCase_ : Any = sum_aa(snake_case__ , left_rotate_aa(snake_case__ , shift_amounts[i]))
# Add hashed chunk to running total
lowerCAmelCase_ : Dict = sum_aa(snake_case__ , snake_case__)
lowerCAmelCase_ : str = sum_aa(snake_case__ , snake_case__)
lowerCAmelCase_ : Optional[int] = sum_aa(snake_case__ , snake_case__)
lowerCAmelCase_ : int = sum_aa(snake_case__ , snake_case__)
lowerCAmelCase_ : Union[str, Any] = reformat_hex(snake_case__) + reformat_hex(snake_case__) + reformat_hex(snake_case__) + reformat_hex(snake_case__)
return digest
if __name__ == "__main__":
import doctest
doctest.testmod()
| 659 | 1 |
from __future__ import annotations
import copy
import inspect
import unittest
import numpy as np
from transformers import is_tf_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_tf, slow
from transformers.utils import cached_property
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers import (
TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST,
TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING,
TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING,
TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
LayoutLMvaConfig,
TFLayoutLMvaForQuestionAnswering,
TFLayoutLMvaForSequenceClassification,
TFLayoutLMvaForTokenClassification,
TFLayoutLMvaModel,
)
if is_vision_available():
from PIL import Image
from transformers import LayoutLMvaImageProcessor
class __snake_case :
"""simple docstring"""
def __init__( self : Optional[Any] ,lowerCAmelCase__ : Dict ,lowerCAmelCase__ : Dict=2 ,lowerCAmelCase__ : str=3 ,lowerCAmelCase__ : str=4 ,lowerCAmelCase__ : Optional[Any]=2 ,lowerCAmelCase__ : Union[str, Any]=7 ,lowerCAmelCase__ : List[Any]=True ,lowerCAmelCase__ : Any=True ,lowerCAmelCase__ : Dict=True ,lowerCAmelCase__ : Union[str, Any]=True ,lowerCAmelCase__ : Optional[Any]=99 ,lowerCAmelCase__ : Union[str, Any]=36 ,lowerCAmelCase__ : Any=2 ,lowerCAmelCase__ : Dict=4 ,lowerCAmelCase__ : Dict=37 ,lowerCAmelCase__ : Optional[Any]="gelu" ,lowerCAmelCase__ : Union[str, Any]=0.1 ,lowerCAmelCase__ : Optional[int]=0.1 ,lowerCAmelCase__ : Union[str, Any]=5_12 ,lowerCAmelCase__ : Dict=16 ,lowerCAmelCase__ : Optional[Any]=2 ,lowerCAmelCase__ : List[Any]=0.02 ,lowerCAmelCase__ : Dict=6 ,lowerCAmelCase__ : int=6 ,lowerCAmelCase__ : Optional[Any]=3 ,lowerCAmelCase__ : Dict=4 ,lowerCAmelCase__ : str=None ,lowerCAmelCase__ : Dict=10_00 ,) -> Dict:
'''simple docstring'''
lowerCAmelCase_ : Optional[Any] = parent
lowerCAmelCase_ : List[str] = batch_size
lowerCAmelCase_ : Dict = num_channels
lowerCAmelCase_ : List[str] = image_size
lowerCAmelCase_ : str = patch_size
lowerCAmelCase_ : List[str] = is_training
lowerCAmelCase_ : Union[str, Any] = use_input_mask
lowerCAmelCase_ : Dict = use_token_type_ids
lowerCAmelCase_ : Optional[Any] = use_labels
lowerCAmelCase_ : Union[str, Any] = vocab_size
lowerCAmelCase_ : Dict = hidden_size
lowerCAmelCase_ : List[str] = num_hidden_layers
lowerCAmelCase_ : Any = num_attention_heads
lowerCAmelCase_ : List[str] = intermediate_size
lowerCAmelCase_ : Optional[int] = hidden_act
lowerCAmelCase_ : List[str] = hidden_dropout_prob
lowerCAmelCase_ : int = attention_probs_dropout_prob
lowerCAmelCase_ : List[Any] = max_position_embeddings
lowerCAmelCase_ : List[Any] = type_vocab_size
lowerCAmelCase_ : Optional[int] = type_sequence_label_size
lowerCAmelCase_ : List[str] = initializer_range
lowerCAmelCase_ : List[str] = coordinate_size
lowerCAmelCase_ : List[str] = shape_size
lowerCAmelCase_ : Optional[Any] = num_labels
lowerCAmelCase_ : List[Any] = num_choices
lowerCAmelCase_ : Dict = scope
lowerCAmelCase_ : List[str] = range_bbox
# LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token)
lowerCAmelCase_ : Tuple = text_seq_length
lowerCAmelCase_ : Any = (image_size // patch_size) ** 2 + 1
lowerCAmelCase_ : List[Any] = self.text_seq_length + self.image_seq_length
def UpperCAmelCase_ ( self : Optional[Any] ) -> Union[str, Any]:
'''simple docstring'''
lowerCAmelCase_ : Tuple = ids_tensor([self.batch_size, self.text_seq_length] ,self.vocab_size )
lowerCAmelCase_ : Dict = ids_tensor([self.batch_size, self.text_seq_length, 4] ,self.range_bbox )
lowerCAmelCase_ : Union[str, Any] = bbox.numpy()
# Ensure that bbox is legal
for i in range(bbox.shape[0] ):
for j in range(bbox.shape[1] ):
if bbox[i, j, 3] < bbox[i, j, 1]:
lowerCAmelCase_ : Any = bbox[i, j, 3]
lowerCAmelCase_ : Tuple = bbox[i, j, 1]
lowerCAmelCase_ : Tuple = tmp_coordinate
if bbox[i, j, 2] < bbox[i, j, 0]:
lowerCAmelCase_ : List[str] = bbox[i, j, 2]
lowerCAmelCase_ : Union[str, Any] = bbox[i, j, 0]
lowerCAmelCase_ : Any = tmp_coordinate
lowerCAmelCase_ : Optional[Any] = tf.constant(lowerCAmelCase__ )
lowerCAmelCase_ : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
lowerCAmelCase_ : Optional[Any] = None
if self.use_input_mask:
lowerCAmelCase_ : List[Any] = random_attention_mask([self.batch_size, self.text_seq_length] )
lowerCAmelCase_ : str = None
if self.use_token_type_ids:
lowerCAmelCase_ : List[Any] = ids_tensor([self.batch_size, self.text_seq_length] ,self.type_vocab_size )
lowerCAmelCase_ : str = None
lowerCAmelCase_ : Union[str, Any] = None
if self.use_labels:
lowerCAmelCase_ : Optional[int] = ids_tensor([self.batch_size] ,self.type_sequence_label_size )
lowerCAmelCase_ : str = ids_tensor([self.batch_size, self.text_seq_length] ,self.num_labels )
lowerCAmelCase_ : Optional[int] = LayoutLMvaConfig(
vocab_size=self.vocab_size ,hidden_size=self.hidden_size ,num_hidden_layers=self.num_hidden_layers ,num_attention_heads=self.num_attention_heads ,intermediate_size=self.intermediate_size ,hidden_act=self.hidden_act ,hidden_dropout_prob=self.hidden_dropout_prob ,attention_probs_dropout_prob=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,type_vocab_size=self.type_vocab_size ,initializer_range=self.initializer_range ,coordinate_size=self.coordinate_size ,shape_size=self.shape_size ,input_size=self.image_size ,patch_size=self.patch_size ,)
return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels
def UpperCAmelCase_ ( self : str ,lowerCAmelCase__ : List[str] ,lowerCAmelCase__ : str ,lowerCAmelCase__ : str ,lowerCAmelCase__ : List[str] ,lowerCAmelCase__ : Any ,lowerCAmelCase__ : Optional[Any] ) -> List[str]:
'''simple docstring'''
lowerCAmelCase_ : Any = TFLayoutLMvaModel(config=lowerCAmelCase__ )
# text + image
lowerCAmelCase_ : Union[str, Any] = model(lowerCAmelCase__ ,pixel_values=lowerCAmelCase__ ,training=lowerCAmelCase__ )
lowerCAmelCase_ : List[str] = model(
lowerCAmelCase__ ,bbox=lowerCAmelCase__ ,pixel_values=lowerCAmelCase__ ,attention_mask=lowerCAmelCase__ ,token_type_ids=lowerCAmelCase__ ,training=lowerCAmelCase__ ,)
lowerCAmelCase_ : Tuple = model(lowerCAmelCase__ ,bbox=lowerCAmelCase__ ,pixel_values=lowerCAmelCase__ ,training=lowerCAmelCase__ )
self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) )
# text only
lowerCAmelCase_ : Union[str, Any] = model(lowerCAmelCase__ ,training=lowerCAmelCase__ )
self.parent.assertEqual(
result.last_hidden_state.shape ,(self.batch_size, self.text_seq_length, self.hidden_size) )
# image only
lowerCAmelCase_ : str = model({"pixel_values": pixel_values} ,training=lowerCAmelCase__ )
self.parent.assertEqual(
result.last_hidden_state.shape ,(self.batch_size, self.image_seq_length, self.hidden_size) )
def UpperCAmelCase_ ( self : Optional[Any] ,lowerCAmelCase__ : List[Any] ,lowerCAmelCase__ : Dict ,lowerCAmelCase__ : Dict ,lowerCAmelCase__ : Union[str, Any] ,lowerCAmelCase__ : str ,lowerCAmelCase__ : Dict ,lowerCAmelCase__ : Union[str, Any] ) -> Optional[Any]:
'''simple docstring'''
lowerCAmelCase_ : Tuple = self.num_labels
lowerCAmelCase_ : int = TFLayoutLMvaForSequenceClassification(config=lowerCAmelCase__ )
lowerCAmelCase_ : Tuple = model(
lowerCAmelCase__ ,bbox=lowerCAmelCase__ ,pixel_values=lowerCAmelCase__ ,attention_mask=lowerCAmelCase__ ,token_type_ids=lowerCAmelCase__ ,labels=lowerCAmelCase__ ,training=lowerCAmelCase__ ,)
self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) )
def UpperCAmelCase_ ( self : Any ,lowerCAmelCase__ : int ,lowerCAmelCase__ : Optional[int] ,lowerCAmelCase__ : List[str] ,lowerCAmelCase__ : Tuple ,lowerCAmelCase__ : List[str] ,lowerCAmelCase__ : Optional[int] ,lowerCAmelCase__ : List[Any] ) -> str:
'''simple docstring'''
lowerCAmelCase_ : List[Any] = self.num_labels
lowerCAmelCase_ : List[str] = TFLayoutLMvaForTokenClassification(config=lowerCAmelCase__ )
lowerCAmelCase_ : str = model(
lowerCAmelCase__ ,bbox=lowerCAmelCase__ ,pixel_values=lowerCAmelCase__ ,attention_mask=lowerCAmelCase__ ,token_type_ids=lowerCAmelCase__ ,labels=lowerCAmelCase__ ,training=lowerCAmelCase__ ,)
self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.text_seq_length, self.num_labels) )
def UpperCAmelCase_ ( self : Optional[Any] ,lowerCAmelCase__ : Dict ,lowerCAmelCase__ : int ,lowerCAmelCase__ : int ,lowerCAmelCase__ : str ,lowerCAmelCase__ : Optional[int] ,lowerCAmelCase__ : int ,lowerCAmelCase__ : Union[str, Any] ) -> Dict:
'''simple docstring'''
lowerCAmelCase_ : List[str] = 2
lowerCAmelCase_ : Any = TFLayoutLMvaForQuestionAnswering(config=lowerCAmelCase__ )
lowerCAmelCase_ : Any = model(
lowerCAmelCase__ ,bbox=lowerCAmelCase__ ,pixel_values=lowerCAmelCase__ ,attention_mask=lowerCAmelCase__ ,token_type_ids=lowerCAmelCase__ ,start_positions=lowerCAmelCase__ ,end_positions=lowerCAmelCase__ ,training=lowerCAmelCase__ ,)
self.parent.assertEqual(result.start_logits.shape ,(self.batch_size, self.seq_length) )
self.parent.assertEqual(result.end_logits.shape ,(self.batch_size, self.seq_length) )
def UpperCAmelCase_ ( self : Union[str, Any] ) -> Union[str, Any]:
'''simple docstring'''
lowerCAmelCase_ : str = self.prepare_config_and_inputs()
((lowerCAmelCase_) , (lowerCAmelCase_) , (lowerCAmelCase_) , (lowerCAmelCase_) , (lowerCAmelCase_) , (lowerCAmelCase_) , (lowerCAmelCase_) , (lowerCAmelCase_)) : Tuple = config_and_inputs
lowerCAmelCase_ : Dict = {
"input_ids": input_ids,
"bbox": bbox,
"pixel_values": pixel_values,
"token_type_ids": token_type_ids,
"attention_mask": input_mask,
}
return config, inputs_dict
@require_tf
class __snake_case ( snake_case__ , snake_case__ , unittest.TestCase ):
"""simple docstring"""
UpperCamelCase_ = (
(
TFLayoutLMvaModel,
TFLayoutLMvaForQuestionAnswering,
TFLayoutLMvaForSequenceClassification,
TFLayoutLMvaForTokenClassification,
)
if is_tf_available()
else ()
)
UpperCamelCase_ = (
{'document-question-answering': TFLayoutLMvaForQuestionAnswering, 'feature-extraction': TFLayoutLMvaModel}
if is_tf_available()
else {}
)
UpperCamelCase_ = False
UpperCamelCase_ = False
UpperCamelCase_ = False
def UpperCAmelCase_ ( self : Dict ,lowerCAmelCase__ : List[Any] ,lowerCAmelCase__ : str ,lowerCAmelCase__ : Dict ,lowerCAmelCase__ : Any ,lowerCAmelCase__ : Any ) -> Optional[Any]:
'''simple docstring'''
return True
def UpperCAmelCase_ ( self : List[str] ,lowerCAmelCase__ : Any ,lowerCAmelCase__ : List[str] ,lowerCAmelCase__ : List[Any]=False ) -> dict:
'''simple docstring'''
lowerCAmelCase_ : Dict = copy.deepcopy(lowerCAmelCase__ )
if model_class in get_values(lowerCAmelCase__ ):
lowerCAmelCase_ : List[str] = {
k: tf.tile(tf.expand_dims(lowerCAmelCase__ ,1 ) ,(1, self.model_tester.num_choices) + (1,) * (v.ndim - 1) )
if isinstance(lowerCAmelCase__ ,tf.Tensor ) and v.ndim > 0
else v
for k, v in inputs_dict.items()
}
if return_labels:
if model_class in get_values(lowerCAmelCase__ ):
lowerCAmelCase_ : str = tf.ones(self.model_tester.batch_size ,dtype=tf.intaa )
elif model_class in get_values(lowerCAmelCase__ ):
lowerCAmelCase_ : Optional[int] = tf.zeros(self.model_tester.batch_size ,dtype=tf.intaa )
lowerCAmelCase_ : str = tf.zeros(self.model_tester.batch_size ,dtype=tf.intaa )
elif model_class in get_values(lowerCAmelCase__ ):
lowerCAmelCase_ : List[Any] = tf.zeros(self.model_tester.batch_size ,dtype=tf.intaa )
elif model_class in get_values(lowerCAmelCase__ ):
lowerCAmelCase_ : Optional[int] = tf.zeros(
(self.model_tester.batch_size, self.model_tester.text_seq_length) ,dtype=tf.intaa )
return inputs_dict
def UpperCAmelCase_ ( self : Optional[Any] ) -> Any:
'''simple docstring'''
lowerCAmelCase_ : List[Any] = TFLayoutLMvaModelTester(self )
lowerCAmelCase_ : Optional[int] = ConfigTester(self ,config_class=lowerCAmelCase__ ,hidden_size=37 )
def UpperCAmelCase_ ( self : Dict ) -> int:
'''simple docstring'''
self.config_tester.run_common_tests()
def UpperCAmelCase_ ( self : Any ) -> Dict:
'''simple docstring'''
lowerCAmelCase_ , lowerCAmelCase_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
lowerCAmelCase_ : Any = model_class(lowerCAmelCase__ )
if getattr(lowerCAmelCase__ ,"hf_compute_loss" ,lowerCAmelCase__ ):
# The number of elements in the loss should be the same as the number of elements in the label
lowerCAmelCase_ : Optional[int] = self._prepare_for_class(inputs_dict.copy() ,lowerCAmelCase__ ,return_labels=lowerCAmelCase__ )
lowerCAmelCase_ : List[Any] = prepared_for_class[
sorted(prepared_for_class.keys() - inputs_dict.keys() ,reverse=lowerCAmelCase__ )[0]
]
lowerCAmelCase_ : int = added_label.shape.as_list()[:1]
# Test that model correctly compute the loss with kwargs
lowerCAmelCase_ : Union[str, Any] = self._prepare_for_class(inputs_dict.copy() ,lowerCAmelCase__ ,return_labels=lowerCAmelCase__ )
lowerCAmelCase_ : str = prepared_for_class.pop("input_ids" )
lowerCAmelCase_ : Any = model(lowerCAmelCase__ ,**lowerCAmelCase__ )[0]
self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] )
# Test that model correctly compute the loss when we mask some positions
lowerCAmelCase_ : List[str] = self._prepare_for_class(inputs_dict.copy() ,lowerCAmelCase__ ,return_labels=lowerCAmelCase__ )
lowerCAmelCase_ : List[Any] = prepared_for_class.pop("input_ids" )
if "labels" in prepared_for_class:
lowerCAmelCase_ : Dict = prepared_for_class["labels"].numpy()
if len(labels.shape ) > 1 and labels.shape[1] != 1:
lowerCAmelCase_ : Tuple = -1_00
lowerCAmelCase_ : List[Any] = tf.convert_to_tensor(lowerCAmelCase__ )
lowerCAmelCase_ : Any = model(lowerCAmelCase__ ,**lowerCAmelCase__ )[0]
self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] )
self.assertTrue(not np.any(np.isnan(loss.numpy() ) ) )
# Test that model correctly compute the loss with a dict
lowerCAmelCase_ : Union[str, Any] = self._prepare_for_class(inputs_dict.copy() ,lowerCAmelCase__ ,return_labels=lowerCAmelCase__ )
lowerCAmelCase_ : Optional[int] = model(lowerCAmelCase__ )[0]
self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] )
# Test that model correctly compute the loss with a tuple
lowerCAmelCase_ : Union[str, Any] = self._prepare_for_class(inputs_dict.copy() ,lowerCAmelCase__ ,return_labels=lowerCAmelCase__ )
# Get keys that were added with the _prepare_for_class function
lowerCAmelCase_ : Dict = prepared_for_class.keys() - inputs_dict.keys()
lowerCAmelCase_ : Any = inspect.signature(model.call ).parameters
lowerCAmelCase_ : Optional[Any] = list(signature.keys() )
# Create a dictionary holding the location of the tensors in the tuple
lowerCAmelCase_ : Tuple = {0: "input_ids"}
for label_key in label_keys:
lowerCAmelCase_ : Tuple = signature_names.index(lowerCAmelCase__ )
lowerCAmelCase_ : Optional[Any] = label_key
lowerCAmelCase_ : Any = sorted(tuple_index_mapping.items() )
# Initialize a list with their default values, update the values and convert to a tuple
lowerCAmelCase_ : str = []
for name in signature_names:
if name != "kwargs":
list_input.append(signature[name].default )
for index, value in sorted_tuple_index_mapping:
lowerCAmelCase_ : Any = prepared_for_class[value]
lowerCAmelCase_ : Dict = tuple(lowerCAmelCase__ )
# Send to model
lowerCAmelCase_ : Optional[Any] = model(tuple_input[:-1] )[0]
self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] )
def UpperCAmelCase_ ( self : Optional[Any] ) -> List[Any]:
'''simple docstring'''
(
(
lowerCAmelCase_
) , (
lowerCAmelCase_
) , (
lowerCAmelCase_
) , (
lowerCAmelCase_
) , (
lowerCAmelCase_
) , (
lowerCAmelCase_
) , (
lowerCAmelCase_
) , (
lowerCAmelCase_
) ,
) : int = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ )
def UpperCAmelCase_ ( self : Any ) -> Dict:
'''simple docstring'''
(
(
lowerCAmelCase_
) , (
lowerCAmelCase_
) , (
lowerCAmelCase_
) , (
lowerCAmelCase_
) , (
lowerCAmelCase_
) , (
lowerCAmelCase_
) , (
lowerCAmelCase_
) , (
lowerCAmelCase_
) ,
) : int = self.model_tester.prepare_config_and_inputs()
for type in ["absolute", "relative_key", "relative_key_query"]:
lowerCAmelCase_ : List[str] = type
self.model_tester.create_and_check_model(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ )
def UpperCAmelCase_ ( self : Dict ) -> int:
'''simple docstring'''
(
(
lowerCAmelCase_
) , (
lowerCAmelCase_
) , (
lowerCAmelCase_
) , (
lowerCAmelCase_
) , (
lowerCAmelCase_
) , (
lowerCAmelCase_
) , (
lowerCAmelCase_
) , (
lowerCAmelCase_
) ,
) : Dict = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_sequence_classification(
lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ )
def UpperCAmelCase_ ( self : str ) -> int:
'''simple docstring'''
(
(
lowerCAmelCase_
) , (
lowerCAmelCase_
) , (
lowerCAmelCase_
) , (
lowerCAmelCase_
) , (
lowerCAmelCase_
) , (
lowerCAmelCase_
) , (
lowerCAmelCase_
) , (
lowerCAmelCase_
) ,
) : Dict = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_token_classification(
lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ )
def UpperCAmelCase_ ( self : Tuple ) -> Union[str, Any]:
'''simple docstring'''
(
(
lowerCAmelCase_
) , (
lowerCAmelCase_
) , (
lowerCAmelCase_
) , (
lowerCAmelCase_
) , (
lowerCAmelCase_
) , (
lowerCAmelCase_
) , (
lowerCAmelCase_
) , (
lowerCAmelCase_
) ,
) : Dict = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_question_answering(
lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ )
@slow
def UpperCAmelCase_ ( self : Any ) -> Union[str, Any]:
'''simple docstring'''
for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
lowerCAmelCase_ : Dict = TFLayoutLMvaModel.from_pretrained(lowerCAmelCase__ )
self.assertIsNotNone(lowerCAmelCase__ )
def UpperCamelCase ( ):
lowerCAmelCase_ : Optional[Any] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
return image
@require_tf
class __snake_case ( unittest.TestCase ):
"""simple docstring"""
@cached_property
def UpperCAmelCase_ ( self : Union[str, Any] ) -> Optional[Any]:
'''simple docstring'''
return LayoutLMvaImageProcessor(apply_ocr=lowerCAmelCase__ ) if is_vision_available() else None
@slow
def UpperCAmelCase_ ( self : List[str] ) -> Optional[Any]:
'''simple docstring'''
lowerCAmelCase_ : Optional[int] = TFLayoutLMvaModel.from_pretrained("microsoft/layoutlmv3-base" )
lowerCAmelCase_ : Optional[Any] = self.default_image_processor
lowerCAmelCase_ : List[Any] = prepare_img()
lowerCAmelCase_ : List[str] = image_processor(images=lowerCAmelCase__ ,return_tensors="tf" ).pixel_values
lowerCAmelCase_ : int = tf.constant([[1, 2]] )
lowerCAmelCase_ : str = tf.expand_dims(tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]] ) ,axis=0 )
# forward pass
lowerCAmelCase_ : Dict = model(input_ids=lowerCAmelCase__ ,bbox=lowerCAmelCase__ ,pixel_values=lowerCAmelCase__ ,training=lowerCAmelCase__ )
# verify the logits
lowerCAmelCase_ : List[str] = (1, 1_99, 7_68)
self.assertEqual(outputs.last_hidden_state.shape ,lowerCAmelCase__ )
lowerCAmelCase_ : Optional[Any] = tf.constant(
[[-0.0_529, 0.3_618, 0.1_632], [-0.1_587, -0.1_667, -0.0_400], [-0.1_557, -0.1_671, -0.0_505]] )
self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3] ,lowerCAmelCase__ ,atol=1e-4 ) )
| 659 |
import logging
import sys
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Union
import librosa
import torch
from datasets import DatasetDict, load_dataset
from packaging import version
from torch import nn
from transformers import (
HfArgumentParser,
Trainer,
TrainingArguments,
WavaVecaConfig,
WavaVecaFeatureExtractor,
WavaVecaForPreTraining,
is_apex_available,
trainer_utils,
)
from transformers.models.wavaveca.modeling_wavaveca import _compute_mask_indices
if is_apex_available():
from apex import amp
if version.parse(version.parse(torch.__version__).base_version) >= version.parse('''1.6'''):
_lowercase = True
from torch.cuda.amp import autocast
_lowercase = logging.getLogger(__name__)
@dataclass
class __snake_case :
"""simple docstring"""
UpperCamelCase_ = field(
metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'} )
UpperCamelCase_ = field(
default=snake_case__ , metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'} , )
UpperCamelCase_ = field(
default=snake_case__ , metadata={'help': 'Whether to freeze the feature extractor layers of the model.'} )
UpperCamelCase_ = field(
default=snake_case__ , metadata={'help': 'Whether to log verbose messages or not.'} , )
UpperCamelCase_ = field(
default=2.0 , metadata={'help': 'Maximum temperature for gumbel softmax.'} )
UpperCamelCase_ = field(
default=0.5 , metadata={'help': 'Minimum temperature for gumbel softmax.'} )
UpperCamelCase_ = field(
default=0.99_99_95 , metadata={'help': 'Decay of gumbel temperature during training.'} )
def UpperCamelCase ( snake_case__ , snake_case__):
logging.basicConfig(
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , handlers=[logging.StreamHandler(sys.stdout)] , )
lowerCAmelCase_ : str = logging.WARNING
if model_args.verbose_logging:
lowerCAmelCase_ : int = logging.DEBUG
elif trainer_utils.is_main_process(training_args.local_rank):
lowerCAmelCase_ : Any = logging.INFO
logger.setLevel(snake_case__)
@dataclass
class __snake_case :
"""simple docstring"""
UpperCamelCase_ = field(
default=snake_case__ , metadata={'help': 'The name of the dataset to use (via the datasets library).'} )
UpperCamelCase_ = field(
default=snake_case__ , metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'} )
UpperCamelCase_ = field(
default='train' , metadata={
'help': 'The name of the training data set split to use (via the datasets library). Defaults to \'train\''
} , )
UpperCamelCase_ = field(
default='validation' , metadata={
'help': (
'The name of the validation data set split to use (via the datasets library). Defaults to \'validation\''
)
} , )
UpperCamelCase_ = field(
default='file' , metadata={'help': 'Column in the dataset that contains speech file path. Defaults to \'file\''} , )
UpperCamelCase_ = field(
default=snake_case__ , metadata={'help': 'Overwrite the cached preprocessed datasets or not.'} )
UpperCamelCase_ = field(
default=1 , metadata={
'help': 'The percentage of the train set used as validation set in case there\'s no validation split'
} , )
UpperCamelCase_ = field(
default=snake_case__ , metadata={'help': 'The number of processes to use for the preprocessing.'} , )
UpperCamelCase_ = field(
default=20.0 , metadata={'help': 'Filter audio files that are longer than `max_duration_in_seconds` seconds'} )
@dataclass
class __snake_case :
"""simple docstring"""
UpperCamelCase_ = 42
UpperCamelCase_ = 42
UpperCamelCase_ = "longest"
UpperCamelCase_ = None
UpperCamelCase_ = None
def __call__( self : str ,lowerCAmelCase__ : List[Dict[str, Union[List[int], torch.Tensor]]] ) -> Dict[str, torch.Tensor]:
'''simple docstring'''
lowerCAmelCase_ : Tuple = self.feature_extractor.pad(
lowerCAmelCase__ ,max_length=self.max_length ,padding=self.padding ,pad_to_multiple_of=self.pad_to_multiple_of ,return_tensors="pt" ,)
lowerCAmelCase_ : Union[str, Any] = self.model._get_feat_extract_output_lengths(batch["input_values"].shape[-1] )
lowerCAmelCase_ : List[str] = batch["input_values"].shape[0]
# make sure that no loss is computed on padded inputs
if batch["attention_mask"] is not None:
# compute real output lengths according to convolution formula
lowerCAmelCase_ : Tuple = self.model._get_feat_extract_output_lengths(batch["attention_mask"].sum(-1 ) ).to(
torch.long )
lowerCAmelCase_ : Optional[Any] = torch.zeros(
(batch_size, mask_indices_seq_length) ,dtype=torch.long ,device=batch["input_values"].device )
# these two operations makes sure that all values
# before the output lengths indices are attended to
lowerCAmelCase_ : Tuple = 1
lowerCAmelCase_ : int = attention_mask.flip([-1] ).cumsum(-1 ).flip([-1] ).bool()
# sample randomly masked indices
lowerCAmelCase_ : str = _compute_mask_indices(
(batch_size, mask_indices_seq_length) ,self.model.config.mask_time_prob ,self.model.config.mask_time_length ,attention_mask=lowerCAmelCase__ ,min_masks=2 ,)
return batch
class __snake_case ( snake_case__ ):
"""simple docstring"""
def __init__( self : List[str] ,*lowerCAmelCase__ : Optional[int] ,lowerCAmelCase__ : Tuple=1 ,lowerCAmelCase__ : Optional[int]=0 ,lowerCAmelCase__ : Optional[Any]=1.0 ,**lowerCAmelCase__ : Any ) -> str:
'''simple docstring'''
super().__init__(*lowerCAmelCase__ ,**lowerCAmelCase__ )
lowerCAmelCase_ : Tuple = 0
lowerCAmelCase_ : int = max_gumbel_temp
lowerCAmelCase_ : Union[str, Any] = min_gumbel_temp
lowerCAmelCase_ : str = gumbel_temp_decay
def UpperCAmelCase_ ( self : Tuple ,lowerCAmelCase__ : nn.Module ,lowerCAmelCase__ : Dict[str, Union[torch.Tensor, Any]] ) -> torch.Tensor:
'''simple docstring'''
model.train()
lowerCAmelCase_ : str = self._prepare_inputs(lowerCAmelCase__ )
if self.use_amp:
with autocast():
lowerCAmelCase_ : List[Any] = self.compute_loss(lowerCAmelCase__ ,lowerCAmelCase__ )
else:
lowerCAmelCase_ : List[Any] = self.compute_loss(lowerCAmelCase__ ,lowerCAmelCase__ )
if self.args.n_gpu > 1 or self.deepspeed:
if model.module.config.ctc_loss_reduction == "mean":
lowerCAmelCase_ : List[Any] = loss.mean()
elif model.module.config.ctc_loss_reduction == "sum":
lowerCAmelCase_ : Optional[Any] = loss.sum() / (inputs["mask_time_indices"]).sum()
else:
raise ValueError(f'''{model.config.ctc_loss_reduction} is not valid. Choose one of [\'mean\', \'sum\']''' )
if self.args.gradient_accumulation_steps > 1:
lowerCAmelCase_ : int = loss / self.args.gradient_accumulation_steps
if self.use_amp:
self.scaler.scale(lowerCAmelCase__ ).backward()
elif self.use_apex:
with amp.scale_loss(lowerCAmelCase__ ,self.optimizer ) as scaled_loss:
scaled_loss.backward()
elif self.deepspeed:
self.deepspeed.backward(lowerCAmelCase__ )
else:
loss.backward()
self.num_update_step += 1
# make sure gumbel softmax temperature is decayed
if self.args.n_gpu > 1 or self.deepspeed:
model.module.set_gumbel_temperature(
max(self.max_gumbel_temp * self.gumbel_temp_decay**self.num_update_step ,self.min_gumbel_temp ) )
else:
model.set_gumbel_temperature(
max(self.max_gumbel_temp * self.gumbel_temp_decay**self.num_update_step ,self.min_gumbel_temp ) )
return loss.detach()
def UpperCamelCase ( ):
# See all possible arguments in src/transformers/training_args.py
# or by passing the --help flag to this script.
# We now keep distinct sets of args, for a cleaner separation of concerns.
lowerCAmelCase_ : Tuple = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ : Dict = parser.parse_args_into_dataclasses()
configure_logger(snake_case__ , snake_case__)
# Downloading and loading a dataset from the hub.
lowerCAmelCase_ : List[str] = load_dataset(data_args.dataset_name , data_args.dataset_config_name , cache_dir=model_args.cache_dir)
if "validation" not in datasets.keys():
# make sure only "validation" and "train" keys remain"
lowerCAmelCase_ : Any = DatasetDict()
lowerCAmelCase_ : Union[str, Any] = load_dataset(
data_args.dataset_name , data_args.dataset_config_name , split=F'''{data_args.train_split_name}[:{data_args.validation_split_percentage}%]''' , cache_dir=model_args.cache_dir , )
lowerCAmelCase_ : List[str] = load_dataset(
data_args.dataset_name , data_args.dataset_config_name , split=F'''{data_args.train_split_name}[{data_args.validation_split_percentage}%:]''' , cache_dir=model_args.cache_dir , )
else:
# make sure only "validation" and "train" keys remain"
lowerCAmelCase_ : Union[str, Any] = DatasetDict()
lowerCAmelCase_ : int = load_dataset(
data_args.dataset_name , data_args.dataset_config_name , split="validation" , cache_dir=model_args.cache_dir , )
lowerCAmelCase_ : Any = load_dataset(
data_args.dataset_name , data_args.dataset_config_name , split=F'''{data_args.train_split_name}''' , cache_dir=model_args.cache_dir , )
# only normalized-inputs-training is supported
lowerCAmelCase_ : Dict = WavaVecaFeatureExtractor.from_pretrained(
model_args.model_name_or_path , cache_dir=model_args.cache_dir , do_normalize=snake_case__)
def prepare_dataset(snake_case__):
# check that all files have the correct sampling rate
lowerCAmelCase_ , lowerCAmelCase_ : str = librosa.load(batch[data_args.speech_file_column] , sr=feature_extractor.sampling_rate)
return batch
# load audio files into numpy arrays
lowerCAmelCase_ : int = datasets.map(
snake_case__ , num_proc=data_args.preprocessing_num_workers , remove_columns=datasets["train"].column_names)
# filter audio files that are too long
lowerCAmelCase_ : int = vectorized_datasets.filter(
lambda snake_case__: len(data["speech"]) < int(data_args.max_duration_in_seconds * feature_extractor.sampling_rate))
def normalize(snake_case__):
return feature_extractor(batch["speech"] , sampling_rate=feature_extractor.sampling_rate)
# normalize and transform to `BatchFeatures`
lowerCAmelCase_ : str = vectorized_datasets.map(
snake_case__ , batched=snake_case__ , num_proc=data_args.preprocessing_num_workers , load_from_cache_file=not data_args.overwrite_cache , remove_columns=vectorized_datasets["train"].column_names , )
# pretraining is only supported for "newer" stable layer norm architecture
# apply_spec_augment has to be True, mask_feature_prob has to be 0.0
lowerCAmelCase_ : Optional[Any] = WavaVecaConfig.from_pretrained(
model_args.model_name_or_path , cache_dir=model_args.cache_dir , gradient_checkpointing=training_args.gradient_checkpointing , )
if not config.do_stable_layer_norm or config.feat_extract_norm != "layer":
raise ValueError(
"PreTraining is only supported for ``config.do_stable_layer_norm=True`` and"
" ``config.feat_extract_norm='layer'")
lowerCAmelCase_ : Dict = WavaVecaForPreTraining(snake_case__)
lowerCAmelCase_ : int = DataCollatorForWavaVecaPretraining(model=snake_case__ , feature_extractor=snake_case__)
lowerCAmelCase_ : List[Any] = WavaVecaPreTrainer(
model=snake_case__ , data_collator=snake_case__ , args=snake_case__ , train_dataset=vectorized_datasets["train"] , eval_dataset=vectorized_datasets["validation"] , tokenizer=snake_case__ , max_gumbel_temp=model_args.max_gumbel_temperature , min_gumbel_temp=model_args.min_gumbel_temperature , gumbel_temp_decay=model_args.gumbel_temperature_decay , )
trainer.train()
if __name__ == "__main__":
main()
| 659 | 1 |
_lowercase = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5]
_lowercase = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5]
_lowercase = {
0: '''Sunday''',
1: '''Monday''',
2: '''Tuesday''',
3: '''Wednesday''',
4: '''Thursday''',
5: '''Friday''',
6: '''Saturday''',
}
def UpperCamelCase ( snake_case__ , snake_case__ , snake_case__):
assert len(str(snake_case__)) > 2, "year should be in YYYY format"
assert 1 <= month <= 12, "month should be between 1 to 12"
assert 1 <= day <= 31, "day should be between 1 to 31"
# Doomsday algorithm:
lowerCAmelCase_ : str = year // 1_00
lowerCAmelCase_ : Dict = (5 * (century % 4) + 2) % 7
lowerCAmelCase_ : Optional[Any] = year % 1_00
lowerCAmelCase_ : Any = centurian % 12
lowerCAmelCase_ : Optional[Any] = (
(centurian // 12) + centurian_m + (centurian_m // 4) + century_anchor
) % 7
lowerCAmelCase_ : List[Any] = (
DOOMSDAY_NOT_LEAP[month - 1]
if (year % 4 != 0) or (centurian == 0 and (year % 4_00) == 0)
else DOOMSDAY_LEAP[month - 1]
)
lowerCAmelCase_ : int = (dooms_day + day - day_anchor) % 7
return WEEK_DAY_NAMES[week_day]
if __name__ == "__main__":
import doctest
doctest.testmod()
| 659 |
from __future__ import annotations
from collections.abc import Callable
def UpperCamelCase ( snake_case__ , snake_case__ , snake_case__ , snake_case__ = 1_00 , ):
lowerCAmelCase_ : Any = x_start
lowerCAmelCase_ : Optional[Any] = fnc(snake_case__)
lowerCAmelCase_ : Union[str, Any] = 0.0
for _ in range(snake_case__):
# Approximates small segments of curve as linear and solve
# for trapezoidal area
lowerCAmelCase_ : Any = (x_end - x_start) / steps + xa
lowerCAmelCase_ : Dict = fnc(snake_case__)
area += abs(fxa + fxa) * (xa - xa) / 2
# Increment step
lowerCAmelCase_ : int = xa
lowerCAmelCase_ : str = fxa
return area
if __name__ == "__main__":
def UpperCamelCase ( snake_case__):
return x**3 + x**2
print('''f(x) = x^3 + x^2''')
print('''The area between the curve, x = -5, x = 5 and the x axis is:''')
_lowercase = 10
while i <= 100000:
print(f"with {i} steps: {trapezoidal_area(f, -5, 5, i)}")
i *= 10
| 659 | 1 |
def UpperCamelCase ( snake_case__):
if upper_limit < 0:
raise ValueError("Limit for the Catalan sequence must be ≥ 0")
lowerCAmelCase_ : List[Any] = [0] * (upper_limit + 1)
# Base case: C(0) = C(1) = 1
lowerCAmelCase_ : Optional[Any] = 1
if upper_limit > 0:
lowerCAmelCase_ : List[str] = 1
# Recurrence relation: C(i) = sum(C(j).C(i-j-1)), from j = 0 to i
for i in range(2 , upper_limit + 1):
for j in range(snake_case__):
catalan_list[i] += catalan_list[j] * catalan_list[i - j - 1]
return catalan_list
if __name__ == "__main__":
print('''\n********* Catalan Numbers Using Dynamic Programming ************\n''')
print('''\n*** Enter -1 at any time to quit ***''')
print('''\nEnter the upper limit (≥ 0) for the Catalan number sequence: ''', end='''''')
try:
while True:
_lowercase = int(input().strip())
if N < 0:
print('''\n********* Goodbye!! ************''')
break
else:
print(f"The Catalan numbers from 0 through {N} are:")
print(catalan_numbers(N))
print('''Try another upper limit for the sequence: ''', end='''''')
except (NameError, ValueError):
print('''\n********* Invalid input, goodbye! ************\n''')
import doctest
doctest.testmod()
| 659 |
import gc
import unittest
import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer
from diffusers import (
AutoencoderKL,
DDIMScheduler,
PNDMScheduler,
StableDiffusionLDMaDPipeline,
UNetaDConditionModel,
)
from diffusers.utils import nightly, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu
from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
enable_full_determinism()
class __snake_case ( unittest.TestCase ):
"""simple docstring"""
UpperCamelCase_ = StableDiffusionLDMaDPipeline
UpperCamelCase_ = TEXT_TO_IMAGE_PARAMS
UpperCamelCase_ = TEXT_TO_IMAGE_BATCH_PARAMS
UpperCamelCase_ = TEXT_TO_IMAGE_IMAGE_PARAMS
def UpperCAmelCase_ ( self : Tuple ) -> str:
'''simple docstring'''
torch.manual_seed(0 )
lowerCAmelCase_ : Optional[Any] = UNetaDConditionModel(
block_out_channels=(32, 64) ,layers_per_block=2 ,sample_size=32 ,in_channels=4 ,out_channels=4 ,down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") ,up_block_types=("CrossAttnUpBlock2D", "UpBlock2D") ,cross_attention_dim=32 ,)
lowerCAmelCase_ : Any = DDIMScheduler(
beta_start=0.00_085 ,beta_end=0.012 ,beta_schedule="scaled_linear" ,clip_sample=lowerCAmelCase__ ,set_alpha_to_one=lowerCAmelCase__ ,)
torch.manual_seed(0 )
lowerCAmelCase_ : str = AutoencoderKL(
block_out_channels=[32, 64] ,in_channels=6 ,out_channels=6 ,down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] ,up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] ,latent_channels=4 ,)
torch.manual_seed(0 )
lowerCAmelCase_ : Optional[Any] = CLIPTextConfig(
bos_token_id=0 ,eos_token_id=2 ,hidden_size=32 ,intermediate_size=37 ,layer_norm_eps=1e-0_5 ,num_attention_heads=4 ,num_hidden_layers=5 ,pad_token_id=1 ,vocab_size=10_00 ,)
lowerCAmelCase_ : Optional[int] = CLIPTextModel(lowerCAmelCase__ )
lowerCAmelCase_ : Dict = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" )
lowerCAmelCase_ : List[Any] = {
"unet": unet,
"scheduler": scheduler,
"vae": vae,
"text_encoder": text_encoder,
"tokenizer": tokenizer,
"safety_checker": None,
"feature_extractor": None,
}
return components
def UpperCAmelCase_ ( self : Tuple ,lowerCAmelCase__ : List[Any] ,lowerCAmelCase__ : List[str]=0 ) -> Dict:
'''simple docstring'''
if str(lowerCAmelCase__ ).startswith("mps" ):
lowerCAmelCase_ : Optional[int] = torch.manual_seed(lowerCAmelCase__ )
else:
lowerCAmelCase_ : Dict = torch.Generator(device=lowerCAmelCase__ ).manual_seed(lowerCAmelCase__ )
lowerCAmelCase_ : str = {
"prompt": "A painting of a squirrel eating a burger",
"generator": generator,
"num_inference_steps": 2,
"guidance_scale": 6.0,
"output_type": "numpy",
}
return inputs
def UpperCAmelCase_ ( self : Any ) -> Optional[int]:
'''simple docstring'''
lowerCAmelCase_ : Dict = "cpu" # ensure determinism for the device-dependent torch.Generator
lowerCAmelCase_ : List[str] = self.get_dummy_components()
lowerCAmelCase_ : Union[str, Any] = StableDiffusionLDMaDPipeline(**lowerCAmelCase__ )
lowerCAmelCase_ : List[Any] = ldmad_pipe.to(lowerCAmelCase__ )
ldmad_pipe.set_progress_bar_config(disable=lowerCAmelCase__ )
lowerCAmelCase_ : Any = self.get_dummy_inputs(lowerCAmelCase__ )
lowerCAmelCase_ : Union[str, Any] = ldmad_pipe(**lowerCAmelCase__ )
lowerCAmelCase_ , lowerCAmelCase_ : Any = output.rgb, output.depth
lowerCAmelCase_ : Dict = rgb[0, -3:, -3:, -1]
lowerCAmelCase_ : Tuple = depth[0, -3:, -1]
assert rgb.shape == (1, 64, 64, 3)
assert depth.shape == (1, 64, 64)
lowerCAmelCase_ : Optional[Any] = np.array(
[0.37_338_176, 0.70_247, 0.74_203_193, 0.51_643_604, 0.58_256_793, 0.60_932_136, 0.4_181_095, 0.48_355_877, 0.46_535_262] )
lowerCAmelCase_ : Tuple = np.array([103.46_727, 85.812_004, 87.849_236] )
assert np.abs(image_slice_rgb.flatten() - expected_slice_rgb ).max() < 1e-2
assert np.abs(image_slice_depth.flatten() - expected_slice_depth ).max() < 1e-2
def UpperCAmelCase_ ( self : int ) -> Optional[int]:
'''simple docstring'''
lowerCAmelCase_ : Dict = self.get_dummy_components()
lowerCAmelCase_ : List[str] = StableDiffusionLDMaDPipeline(**lowerCAmelCase__ )
lowerCAmelCase_ : List[Any] = ldmad_pipe.to(lowerCAmelCase__ )
ldmad_pipe.set_progress_bar_config(disable=lowerCAmelCase__ )
lowerCAmelCase_ : Union[str, Any] = self.get_dummy_inputs(lowerCAmelCase__ )
lowerCAmelCase_ : str = 3 * [inputs["prompt"]]
# forward
lowerCAmelCase_ : Union[str, Any] = ldmad_pipe(**lowerCAmelCase__ )
lowerCAmelCase_ , lowerCAmelCase_ : Optional[Any] = output.rgb, output.depth
lowerCAmelCase_ : str = rgb_slice_a[0, -3:, -3:, -1]
lowerCAmelCase_ : List[str] = depth_slice_a[0, -3:, -1]
lowerCAmelCase_ : Union[str, Any] = self.get_dummy_inputs(lowerCAmelCase__ )
lowerCAmelCase_ : Tuple = 3 * [inputs.pop("prompt" )]
lowerCAmelCase_ : str = ldmad_pipe.tokenizer(
lowerCAmelCase__ ,padding="max_length" ,max_length=ldmad_pipe.tokenizer.model_max_length ,truncation=lowerCAmelCase__ ,return_tensors="pt" ,)
lowerCAmelCase_ : Union[str, Any] = text_inputs["input_ids"].to(lowerCAmelCase__ )
lowerCAmelCase_ : Optional[int] = ldmad_pipe.text_encoder(lowerCAmelCase__ )[0]
lowerCAmelCase_ : Optional[int] = prompt_embeds
# forward
lowerCAmelCase_ : str = ldmad_pipe(**lowerCAmelCase__ )
lowerCAmelCase_ , lowerCAmelCase_ : str = output.rgb, output.depth
lowerCAmelCase_ : Optional[Any] = rgb_slice_a[0, -3:, -3:, -1]
lowerCAmelCase_ : Tuple = depth_slice_a[0, -3:, -1]
assert np.abs(rgb_slice_a.flatten() - rgb_slice_a.flatten() ).max() < 1e-4
assert np.abs(depth_slice_a.flatten() - depth_slice_a.flatten() ).max() < 1e-4
def UpperCAmelCase_ ( self : Union[str, Any] ) -> Tuple:
'''simple docstring'''
lowerCAmelCase_ : Any = "cpu" # ensure determinism for the device-dependent torch.Generator
lowerCAmelCase_ : Optional[int] = self.get_dummy_components()
lowerCAmelCase_ : Dict = PNDMScheduler(skip_prk_steps=lowerCAmelCase__ )
lowerCAmelCase_ : Union[str, Any] = StableDiffusionLDMaDPipeline(**lowerCAmelCase__ )
lowerCAmelCase_ : Any = ldmad_pipe.to(lowerCAmelCase__ )
ldmad_pipe.set_progress_bar_config(disable=lowerCAmelCase__ )
lowerCAmelCase_ : List[str] = self.get_dummy_inputs(lowerCAmelCase__ )
lowerCAmelCase_ : List[Any] = "french fries"
lowerCAmelCase_ : Optional[int] = ldmad_pipe(**lowerCAmelCase__ ,negative_prompt=lowerCAmelCase__ )
lowerCAmelCase_ , lowerCAmelCase_ : Union[str, Any] = output.rgb, output.depth
lowerCAmelCase_ : Any = rgb[0, -3:, -3:, -1]
lowerCAmelCase_ : Tuple = depth[0, -3:, -1]
assert rgb.shape == (1, 64, 64, 3)
assert depth.shape == (1, 64, 64)
lowerCAmelCase_ : int = np.array(
[0.37_044, 0.71_811_503, 0.7_223_251, 0.48_603_675, 0.5_638_391, 0.6_364_948, 0.42_833_704, 0.4_901_315, 0.47_926_217] )
lowerCAmelCase_ : Union[str, Any] = np.array([107.84_738, 84.62_802, 89.962_135] )
assert np.abs(rgb_slice.flatten() - expected_slice_rgb ).max() < 1e-2
assert np.abs(depth_slice.flatten() - expected_slice_depth ).max() < 1e-2
@slow
@require_torch_gpu
class __snake_case ( unittest.TestCase ):
"""simple docstring"""
def UpperCAmelCase_ ( self : Tuple ) -> Union[str, Any]:
'''simple docstring'''
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def UpperCAmelCase_ ( self : Any ,lowerCAmelCase__ : Tuple ,lowerCAmelCase__ : Dict="cpu" ,lowerCAmelCase__ : Union[str, Any]=torch.floataa ,lowerCAmelCase__ : List[str]=0 ) -> int:
'''simple docstring'''
lowerCAmelCase_ : Any = torch.Generator(device=lowerCAmelCase__ ).manual_seed(lowerCAmelCase__ )
lowerCAmelCase_ : List[str] = np.random.RandomState(lowerCAmelCase__ ).standard_normal((1, 4, 64, 64) )
lowerCAmelCase_ : Optional[Any] = torch.from_numpy(lowerCAmelCase__ ).to(device=lowerCAmelCase__ ,dtype=lowerCAmelCase__ )
lowerCAmelCase_ : Union[str, Any] = {
"prompt": "a photograph of an astronaut riding a horse",
"latents": latents,
"generator": generator,
"num_inference_steps": 3,
"guidance_scale": 7.5,
"output_type": "numpy",
}
return inputs
def UpperCAmelCase_ ( self : List[Any] ) -> List[str]:
'''simple docstring'''
lowerCAmelCase_ : Optional[Any] = StableDiffusionLDMaDPipeline.from_pretrained("Intel/ldm3d" )
lowerCAmelCase_ : List[str] = ldmad_pipe.to(lowerCAmelCase__ )
ldmad_pipe.set_progress_bar_config(disable=lowerCAmelCase__ )
lowerCAmelCase_ : Dict = self.get_inputs(lowerCAmelCase__ )
lowerCAmelCase_ : List[str] = ldmad_pipe(**lowerCAmelCase__ )
lowerCAmelCase_ , lowerCAmelCase_ : Dict = output.rgb, output.depth
lowerCAmelCase_ : List[str] = rgb[0, -3:, -3:, -1].flatten()
lowerCAmelCase_ : Optional[int] = rgb[0, -3:, -1].flatten()
assert rgb.shape == (1, 5_12, 5_12, 3)
assert depth.shape == (1, 5_12, 5_12)
lowerCAmelCase_ : int = np.array(
[0.53_805_465, 0.56_707_305, 0.5_486_515, 0.57_012_236, 0.5_814_511, 0.56_253_487, 0.54_843_014, 0.55_092_263, 0.6_459_706] )
lowerCAmelCase_ : Optional[Any] = np.array(
[0.9_263_781, 0.6_678_672, 0.5_486_515, 0.92_202_145, 0.67_831_135, 0.56_253_487, 0.9_241_694, 0.7_551_478, 0.6_459_706] )
assert np.abs(rgb_slice - expected_slice_rgb ).max() < 3e-3
assert np.abs(depth_slice - expected_slice_depth ).max() < 3e-3
@nightly
@require_torch_gpu
class __snake_case ( unittest.TestCase ):
"""simple docstring"""
def UpperCAmelCase_ ( self : Tuple ) -> Union[str, Any]:
'''simple docstring'''
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def UpperCAmelCase_ ( self : Tuple ,lowerCAmelCase__ : Tuple ,lowerCAmelCase__ : Dict="cpu" ,lowerCAmelCase__ : List[str]=torch.floataa ,lowerCAmelCase__ : Optional[int]=0 ) -> int:
'''simple docstring'''
lowerCAmelCase_ : Dict = torch.Generator(device=lowerCAmelCase__ ).manual_seed(lowerCAmelCase__ )
lowerCAmelCase_ : Tuple = np.random.RandomState(lowerCAmelCase__ ).standard_normal((1, 4, 64, 64) )
lowerCAmelCase_ : Any = torch.from_numpy(lowerCAmelCase__ ).to(device=lowerCAmelCase__ ,dtype=lowerCAmelCase__ )
lowerCAmelCase_ : int = {
"prompt": "a photograph of an astronaut riding a horse",
"latents": latents,
"generator": generator,
"num_inference_steps": 50,
"guidance_scale": 7.5,
"output_type": "numpy",
}
return inputs
def UpperCAmelCase_ ( self : Dict ) -> int:
'''simple docstring'''
lowerCAmelCase_ : List[Any] = StableDiffusionLDMaDPipeline.from_pretrained("Intel/ldm3d" ).to(lowerCAmelCase__ )
ldmad_pipe.set_progress_bar_config(disable=lowerCAmelCase__ )
lowerCAmelCase_ : Union[str, Any] = self.get_inputs(lowerCAmelCase__ )
lowerCAmelCase_ : Union[str, Any] = ldmad_pipe(**lowerCAmelCase__ )
lowerCAmelCase_ , lowerCAmelCase_ : Any = output.rgb, output.depth
lowerCAmelCase_ : Dict = 0.495_586
lowerCAmelCase_ : Optional[Any] = 0.33_795_515
lowerCAmelCase_ : Any = 112.48_518
lowerCAmelCase_ : List[Any] = 98.489_746
assert np.abs(expected_rgb_mean - rgb.mean() ) < 1e-3
assert np.abs(expected_rgb_std - rgb.std() ) < 1e-3
assert np.abs(expected_depth_mean - depth.mean() ) < 1e-3
assert np.abs(expected_depth_std - depth.std() ) < 1e-3
def UpperCAmelCase_ ( self : Tuple ) -> List[str]:
'''simple docstring'''
lowerCAmelCase_ : int = StableDiffusionLDMaDPipeline.from_pretrained("Intel/ldm3d-4c" ).to(lowerCAmelCase__ )
ldmad_pipe.set_progress_bar_config(disable=lowerCAmelCase__ )
lowerCAmelCase_ : str = self.get_inputs(lowerCAmelCase__ )
lowerCAmelCase_ : Tuple = ldmad_pipe(**lowerCAmelCase__ )
lowerCAmelCase_ , lowerCAmelCase_ : Tuple = output.rgb, output.depth
lowerCAmelCase_ : List[str] = 0.4_194_127
lowerCAmelCase_ : List[str] = 0.35_375_586
lowerCAmelCase_ : str = 0.5_638_502
lowerCAmelCase_ : Optional[Any] = 0.34_686_103
assert rgb.shape == (1, 5_12, 5_12, 3)
assert depth.shape == (1, 5_12, 5_12, 1)
assert np.abs(expected_rgb_mean - rgb.mean() ) < 1e-3
assert np.abs(expected_rgb_std - rgb.std() ) < 1e-3
assert np.abs(expected_depth_mean - depth.mean() ) < 1e-3
assert np.abs(expected_depth_std - depth.std() ) < 1e-3
| 659 | 1 |
import unittest
from datasets import load_dataset
from transformers import BloomTokenizerFast
from transformers.testing_utils import require_tokenizers
from ...test_tokenization_common import TokenizerTesterMixin
@require_tokenizers
class __snake_case ( snake_case__ , unittest.TestCase ):
"""simple docstring"""
UpperCamelCase_ = None
UpperCamelCase_ = BloomTokenizerFast
UpperCamelCase_ = BloomTokenizerFast
UpperCamelCase_ = True
UpperCamelCase_ = False
UpperCamelCase_ = 'tokenizer_file'
UpperCamelCase_ = {'bos_token': '<s>', 'eos_token': '</s>', 'unk_token': '<unk>', 'pad_token': '<pad>'}
def UpperCAmelCase_ ( self : Optional[Any] ) -> Union[str, Any]:
'''simple docstring'''
super().setUp()
lowerCAmelCase_ : Optional[int] = BloomTokenizerFast.from_pretrained("bigscience/tokenizer" )
tokenizer.save_pretrained(self.tmpdirname )
def UpperCAmelCase_ ( self : Optional[Any] ,**lowerCAmelCase__ : List[str] ) -> int:
'''simple docstring'''
kwargs.update(self.special_tokens_map )
return BloomTokenizerFast.from_pretrained(self.tmpdirname ,**lowerCAmelCase__ )
def UpperCAmelCase_ ( self : List[Any] ) -> Tuple:
'''simple docstring'''
lowerCAmelCase_ : int = self.get_rust_tokenizer()
lowerCAmelCase_ : List[str] = ["The quick brown fox</s>", "jumps over the lazy dog</s>"]
lowerCAmelCase_ : List[str] = [[21_75, 2_37_14, 7_31_73, 14_42_52, 2], [77, 13_26_19, 34_78, 3_68, 10_95_86, 3_54_33, 2]]
lowerCAmelCase_ : List[str] = tokenizer.batch_encode_plus(lowerCAmelCase__ )["input_ids"]
self.assertListEqual(lowerCAmelCase__ ,lowerCAmelCase__ )
lowerCAmelCase_ : Optional[int] = tokenizer.batch_decode(lowerCAmelCase__ )
self.assertListEqual(lowerCAmelCase__ ,lowerCAmelCase__ )
def UpperCAmelCase_ ( self : int ,lowerCAmelCase__ : List[str]=6 ) -> str:
'''simple docstring'''
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ):
lowerCAmelCase_ : List[str] = self.rust_tokenizer_class.from_pretrained(lowerCAmelCase__ ,**lowerCAmelCase__ )
# tokenizer_r.pad_token = None # Hotfixing padding = None
# Simple input
lowerCAmelCase_ : Optional[Any] = "This is a simple input"
lowerCAmelCase_ : Any = ["This is a simple input 1", "This is a simple input 2"]
lowerCAmelCase_ : Dict = ("This is a simple input", "This is a pair")
lowerCAmelCase_ : Tuple = [
("This is a simple input 1", "This is a simple input 2"),
("This is a simple pair 1", "This is a simple pair 2"),
]
# Simple input tests
try:
tokenizer_r.encode(lowerCAmelCase__ ,max_length=lowerCAmelCase__ )
tokenizer_r.encode_plus(lowerCAmelCase__ ,max_length=lowerCAmelCase__ )
tokenizer_r.batch_encode_plus(lowerCAmelCase__ ,max_length=lowerCAmelCase__ )
tokenizer_r.encode(lowerCAmelCase__ ,max_length=lowerCAmelCase__ )
tokenizer_r.batch_encode_plus(lowerCAmelCase__ ,max_length=lowerCAmelCase__ )
except ValueError:
self.fail("Bloom Tokenizer should be able to deal with padding" )
lowerCAmelCase_ : List[str] = None # Hotfixing padding = None
self.assertRaises(lowerCAmelCase__ ,tokenizer_r.encode ,lowerCAmelCase__ ,max_length=lowerCAmelCase__ ,padding="max_length" )
# Simple input
self.assertRaises(lowerCAmelCase__ ,tokenizer_r.encode_plus ,lowerCAmelCase__ ,max_length=lowerCAmelCase__ ,padding="max_length" )
# Simple input
self.assertRaises(
lowerCAmelCase__ ,tokenizer_r.batch_encode_plus ,lowerCAmelCase__ ,max_length=lowerCAmelCase__ ,padding="max_length" ,)
# Pair input
self.assertRaises(lowerCAmelCase__ ,tokenizer_r.encode ,lowerCAmelCase__ ,max_length=lowerCAmelCase__ ,padding="max_length" )
# Pair input
self.assertRaises(lowerCAmelCase__ ,tokenizer_r.encode_plus ,lowerCAmelCase__ ,max_length=lowerCAmelCase__ ,padding="max_length" )
# Pair input
self.assertRaises(
lowerCAmelCase__ ,tokenizer_r.batch_encode_plus ,lowerCAmelCase__ ,max_length=lowerCAmelCase__ ,padding="max_length" ,)
def UpperCAmelCase_ ( self : int ) -> Optional[Any]:
'''simple docstring'''
lowerCAmelCase_ : Any = self.get_rust_tokenizer()
lowerCAmelCase_ : Dict = load_dataset("xnli" ,"all_languages" ,split="test" ,streaming=lowerCAmelCase__ )
lowerCAmelCase_ : Optional[Any] = next(iter(lowerCAmelCase__ ) )["premise"] # pick up one data
lowerCAmelCase_ : List[str] = list(sample_data.values() )
lowerCAmelCase_ : str = list(map(tokenizer.encode ,lowerCAmelCase__ ) )
lowerCAmelCase_ : Optional[int] = [tokenizer.decode(lowerCAmelCase__ ,clean_up_tokenization_spaces=lowerCAmelCase__ ) for x in output_tokens]
self.assertListEqual(lowerCAmelCase__ ,lowerCAmelCase__ )
def UpperCAmelCase_ ( self : List[str] ) -> List[str]:
'''simple docstring'''
self.assertGreaterEqual(len(self.tokenizer_class.pretrained_vocab_files_map ) ,1 )
self.assertGreaterEqual(len(list(self.tokenizer_class.pretrained_vocab_files_map.values() )[0] ) ,1 )
| 659 |
import argparse
import re
import numpy as np
import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from transformers import (
SamConfig,
SamImageProcessor,
SamModel,
SamProcessor,
SamVisionConfig,
)
_lowercase = {
'''iou_prediction_head.layers.0''': '''iou_prediction_head.proj_in''',
'''iou_prediction_head.layers.1''': '''iou_prediction_head.layers.0''',
'''iou_prediction_head.layers.2''': '''iou_prediction_head.proj_out''',
'''mask_decoder.output_upscaling.0''': '''mask_decoder.upscale_conv1''',
'''mask_decoder.output_upscaling.1''': '''mask_decoder.upscale_layer_norm''',
'''mask_decoder.output_upscaling.3''': '''mask_decoder.upscale_conv2''',
'''mask_downscaling.0''': '''mask_embed.conv1''',
'''mask_downscaling.1''': '''mask_embed.layer_norm1''',
'''mask_downscaling.3''': '''mask_embed.conv2''',
'''mask_downscaling.4''': '''mask_embed.layer_norm2''',
'''mask_downscaling.6''': '''mask_embed.conv3''',
'''point_embeddings''': '''point_embed''',
'''pe_layer.positional_encoding_gaussian_matrix''': '''shared_embedding.positional_embedding''',
'''image_encoder''': '''vision_encoder''',
'''neck.0''': '''neck.conv1''',
'''neck.1''': '''neck.layer_norm1''',
'''neck.2''': '''neck.conv2''',
'''neck.3''': '''neck.layer_norm2''',
'''patch_embed.proj''': '''patch_embed.projection''',
'''.norm''': '''.layer_norm''',
'''blocks''': '''layers''',
}
def UpperCamelCase ( snake_case__):
lowerCAmelCase_ : int = {}
state_dict.pop("pixel_mean" , snake_case__)
state_dict.pop("pixel_std" , snake_case__)
lowerCAmelCase_ : List[Any] = R".*.output_hypernetworks_mlps.(\d+).layers.(\d+).*"
for key, value in state_dict.items():
for key_to_modify, new_key in KEYS_TO_MODIFY_MAPPING.items():
if key_to_modify in key:
lowerCAmelCase_ : Dict = key.replace(snake_case__ , snake_case__)
if re.match(snake_case__ , snake_case__):
lowerCAmelCase_ : Any = int(re.match(snake_case__ , snake_case__).group(2))
if layer_nb == 0:
lowerCAmelCase_ : List[Any] = key.replace("layers.0" , "proj_in")
elif layer_nb == 1:
lowerCAmelCase_ : List[Any] = key.replace("layers.1" , "layers.0")
elif layer_nb == 2:
lowerCAmelCase_ : int = key.replace("layers.2" , "proj_out")
lowerCAmelCase_ : int = value
lowerCAmelCase_ : Optional[int] = model_state_dict[
"prompt_encoder.shared_embedding.positional_embedding"
]
return model_state_dict
def UpperCamelCase ( snake_case__ , snake_case__ , snake_case__ , snake_case__="ybelkada/segment-anything"):
lowerCAmelCase_ : Optional[int] = hf_hub_download(snake_case__ , F'''checkpoints/{model_name}.pth''')
if "sam_vit_b" in model_name:
lowerCAmelCase_ : Optional[Any] = SamConfig()
elif "sam_vit_l" in model_name:
lowerCAmelCase_ : Optional[int] = SamVisionConfig(
hidden_size=10_24 , num_hidden_layers=24 , num_attention_heads=16 , global_attn_indexes=[5, 11, 17, 23] , )
lowerCAmelCase_ : Union[str, Any] = SamConfig(
vision_config=snake_case__ , )
elif "sam_vit_h" in model_name:
lowerCAmelCase_ : Optional[Any] = SamVisionConfig(
hidden_size=12_80 , num_hidden_layers=32 , num_attention_heads=16 , global_attn_indexes=[7, 15, 23, 31] , )
lowerCAmelCase_ : Tuple = SamConfig(
vision_config=snake_case__ , )
lowerCAmelCase_ : Optional[Any] = torch.load(snake_case__ , map_location="cpu")
lowerCAmelCase_ : Union[str, Any] = replace_keys(snake_case__)
lowerCAmelCase_ : List[Any] = SamImageProcessor()
lowerCAmelCase_ : Any = SamProcessor(image_processor=snake_case__)
lowerCAmelCase_ : Any = SamModel(snake_case__)
hf_model.load_state_dict(snake_case__)
lowerCAmelCase_ : Dict = hf_model.to("cuda")
lowerCAmelCase_ : List[str] = "https://huggingface.co/ybelkada/segment-anything/resolve/main/assets/car.png"
lowerCAmelCase_ : List[Any] = Image.open(requests.get(snake_case__ , stream=snake_case__).raw).convert("RGB")
lowerCAmelCase_ : Optional[int] = [[[4_00, 6_50]]]
lowerCAmelCase_ : int = [[1]]
lowerCAmelCase_ : Optional[Any] = processor(images=np.array(snake_case__) , return_tensors="pt").to("cuda")
with torch.no_grad():
lowerCAmelCase_ : Optional[Any] = hf_model(**snake_case__)
lowerCAmelCase_ : Optional[int] = output.iou_scores.squeeze()
if model_name == "sam_vit_h_4b8939":
assert scores[-1].item() == 0.579_890_251_159_668
lowerCAmelCase_ : Any = processor(
images=np.array(snake_case__) , input_points=snake_case__ , input_labels=snake_case__ , return_tensors="pt").to("cuda")
with torch.no_grad():
lowerCAmelCase_ : Optional[Any] = hf_model(**snake_case__)
lowerCAmelCase_ : Union[str, Any] = output.iou_scores.squeeze()
assert scores[-1].item() == 0.9_712_603_092_193_604
lowerCAmelCase_ : Tuple = ((75, 2_75, 17_25, 8_50),)
lowerCAmelCase_ : Optional[Any] = processor(images=np.array(snake_case__) , input_boxes=snake_case__ , return_tensors="pt").to("cuda")
with torch.no_grad():
lowerCAmelCase_ : List[Any] = hf_model(**snake_case__)
lowerCAmelCase_ : str = output.iou_scores.squeeze()
assert scores[-1].item() == 0.8_686_015_605_926_514
# Test with 2 points and 1 image.
lowerCAmelCase_ : int = [[[4_00, 6_50], [8_00, 6_50]]]
lowerCAmelCase_ : Optional[Any] = [[1, 1]]
lowerCAmelCase_ : List[Any] = processor(
images=np.array(snake_case__) , input_points=snake_case__ , input_labels=snake_case__ , return_tensors="pt").to("cuda")
with torch.no_grad():
lowerCAmelCase_ : Tuple = hf_model(**snake_case__)
lowerCAmelCase_ : str = output.iou_scores.squeeze()
assert scores[-1].item() == 0.9_936_047_792_434_692
if __name__ == "__main__":
_lowercase = argparse.ArgumentParser()
_lowercase = ['''sam_vit_b_01ec64''', '''sam_vit_h_4b8939''', '''sam_vit_l_0b3195''']
parser.add_argument(
'''--model_name''',
default='''sam_vit_h_4b8939''',
choices=choices,
type=str,
help='''Path to hf config.json of model to convert''',
)
parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''')
parser.add_argument(
'''--push_to_hub''',
action='''store_true''',
help='''Whether to push the model and processor to the hub after converting''',
)
parser.add_argument(
'''--model_hub_id''',
default='''ybelkada/segment-anything''',
choices=choices,
type=str,
help='''Path to hf config.json of model to convert''',
)
_lowercase = parser.parse_args()
convert_sam_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub, args.model_hub_id)
| 659 | 1 |
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union
import pyarrow as pa
if TYPE_CHECKING:
from .features import FeatureType
@dataclass
class __snake_case :
"""simple docstring"""
UpperCamelCase_ = 42
UpperCamelCase_ = None
# Automatically constructed
UpperCamelCase_ = "dict"
UpperCamelCase_ = None
UpperCamelCase_ = field(default='Translation' , init=snake_case__ , repr=snake_case__ )
def __call__( self : Dict ) -> str:
'''simple docstring'''
return pa.struct({lang: pa.string() for lang in sorted(self.languages )} )
def UpperCAmelCase_ ( self : Optional[int] ) -> Union["FeatureType", Dict[str, "FeatureType"]]:
'''simple docstring'''
from .features import Value
return {k: Value("string" ) for k in sorted(self.languages )}
@dataclass
class __snake_case :
"""simple docstring"""
UpperCamelCase_ = None
UpperCamelCase_ = None
UpperCamelCase_ = None
# Automatically constructed
UpperCamelCase_ = "dict"
UpperCamelCase_ = None
UpperCamelCase_ = field(default='TranslationVariableLanguages' , init=snake_case__ , repr=snake_case__ )
def UpperCAmelCase_ ( self : Optional[int] ) -> Union[str, Any]:
'''simple docstring'''
lowerCAmelCase_ : Optional[Any] = sorted(set(self.languages ) ) if self.languages else None
lowerCAmelCase_ : List[Any] = len(self.languages ) if self.languages else None
def __call__( self : List[Any] ) -> List[str]:
'''simple docstring'''
return pa.struct({"language": pa.list_(pa.string() ), "translation": pa.list_(pa.string() )} )
def UpperCAmelCase_ ( self : Dict ,lowerCAmelCase__ : Optional[Any] ) -> Union[str, Any]:
'''simple docstring'''
lowerCAmelCase_ : str = set(self.languages )
if self.languages and set(lowerCAmelCase__ ) - lang_set:
raise ValueError(
f'''Some languages in example ({", ".join(sorted(set(lowerCAmelCase__ ) - lang_set ) )}) are not in valid set ({", ".join(lowerCAmelCase__ )}).''' )
# Convert dictionary into tuples, splitting out cases where there are
# multiple translations for a single language.
lowerCAmelCase_ : Tuple = []
for lang, text in translation_dict.items():
if isinstance(lowerCAmelCase__ ,lowerCAmelCase__ ):
translation_tuples.append((lang, text) )
else:
translation_tuples.extend([(lang, el) for el in text] )
# Ensure translations are in ascending order by language code.
lowerCAmelCase_ , lowerCAmelCase_ : int = zip(*sorted(lowerCAmelCase__ ) )
return {"language": languages, "translation": translations}
def UpperCAmelCase_ ( self : List[str] ) -> Union["FeatureType", Dict[str, "FeatureType"]]:
'''simple docstring'''
from .features import Sequence, Value
return {
"language": Sequence(Value("string" ) ),
"translation": Sequence(Value("string" ) ),
}
| 659 |
class __snake_case :
"""simple docstring"""
def __init__( self : Union[str, Any] ,lowerCAmelCase__ : str = "" ,lowerCAmelCase__ : bool = False ) -> None:
'''simple docstring'''
lowerCAmelCase_ : dict[str, RadixNode] = {}
# A node will be a leaf if the tree contains its word
lowerCAmelCase_ : Optional[int] = is_leaf
lowerCAmelCase_ : List[str] = prefix
def UpperCAmelCase_ ( self : List[str] ,lowerCAmelCase__ : str ) -> tuple[str, str, str]:
'''simple docstring'''
lowerCAmelCase_ : List[str] = 0
for q, w in zip(self.prefix ,lowerCAmelCase__ ):
if q != w:
break
x += 1
return self.prefix[:x], self.prefix[x:], word[x:]
def UpperCAmelCase_ ( self : Optional[Any] ,lowerCAmelCase__ : list[str] ) -> None:
'''simple docstring'''
for word in words:
self.insert(lowerCAmelCase__ )
def UpperCAmelCase_ ( self : List[Any] ,lowerCAmelCase__ : str ) -> None:
'''simple docstring'''
if self.prefix == word:
lowerCAmelCase_ : Optional[Any] = True
# Case 2: The node has no edges that have a prefix to the word
# Solution: We create an edge from the current node to a new one
# containing the word
elif word[0] not in self.nodes:
lowerCAmelCase_ : Optional[int] = RadixNode(prefix=lowerCAmelCase__ ,is_leaf=lowerCAmelCase__ )
else:
lowerCAmelCase_ : Optional[Any] = self.nodes[word[0]]
lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ : Any = incoming_node.match(
lowerCAmelCase__ )
# Case 3: The node prefix is equal to the matching
# Solution: We insert remaining word on the next node
if remaining_prefix == "":
self.nodes[matching_string[0]].insert(lowerCAmelCase__ )
# Case 4: The word is greater equal to the matching
# Solution: Create a node in between both nodes, change
# prefixes and add the new node for the remaining word
else:
lowerCAmelCase_ : Dict = remaining_prefix
lowerCAmelCase_ : str = self.nodes[matching_string[0]]
lowerCAmelCase_ : Dict = RadixNode(lowerCAmelCase__ ,lowerCAmelCase__ )
lowerCAmelCase_ : Any = aux_node
if remaining_word == "":
lowerCAmelCase_ : Optional[Any] = True
else:
self.nodes[matching_string[0]].insert(lowerCAmelCase__ )
def UpperCAmelCase_ ( self : Optional[Any] ,lowerCAmelCase__ : str ) -> bool:
'''simple docstring'''
lowerCAmelCase_ : List[str] = self.nodes.get(word[0] ,lowerCAmelCase__ )
if not incoming_node:
return False
else:
lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ : Optional[int] = incoming_node.match(
lowerCAmelCase__ )
# If there is remaining prefix, the word can't be on the tree
if remaining_prefix != "":
return False
# This applies when the word and the prefix are equal
elif remaining_word == "":
return incoming_node.is_leaf
# We have word remaining so we check the next node
else:
return incoming_node.find(lowerCAmelCase__ )
def UpperCAmelCase_ ( self : Tuple ,lowerCAmelCase__ : str ) -> bool:
'''simple docstring'''
lowerCAmelCase_ : int = self.nodes.get(word[0] ,lowerCAmelCase__ )
if not incoming_node:
return False
else:
lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ : List[Any] = incoming_node.match(
lowerCAmelCase__ )
# If there is remaining prefix, the word can't be on the tree
if remaining_prefix != "":
return False
# We have word remaining so we check the next node
elif remaining_word != "":
return incoming_node.delete(lowerCAmelCase__ )
else:
# If it is not a leaf, we don't have to delete
if not incoming_node.is_leaf:
return False
else:
# We delete the nodes if no edges go from it
if len(incoming_node.nodes ) == 0:
del self.nodes[word[0]]
# We merge the current node with its only child
if len(self.nodes ) == 1 and not self.is_leaf:
lowerCAmelCase_ : int = list(self.nodes.values() )[0]
lowerCAmelCase_ : List[Any] = merging_node.is_leaf
self.prefix += merging_node.prefix
lowerCAmelCase_ : int = merging_node.nodes
# If there is more than 1 edge, we just mark it as non-leaf
elif len(incoming_node.nodes ) > 1:
lowerCAmelCase_ : List[str] = False
# If there is 1 edge, we merge it with its child
else:
lowerCAmelCase_ : Union[str, Any] = list(incoming_node.nodes.values() )[0]
lowerCAmelCase_ : Optional[int] = merging_node.is_leaf
incoming_node.prefix += merging_node.prefix
lowerCAmelCase_ : List[str] = merging_node.nodes
return True
def UpperCAmelCase_ ( self : int ,lowerCAmelCase__ : int = 0 ) -> None:
'''simple docstring'''
if self.prefix != "":
print("-" * height ,self.prefix ," (leaf)" if self.is_leaf else "" )
for value in self.nodes.values():
value.print_tree(height + 1 )
def UpperCamelCase ( ):
lowerCAmelCase_ : List[Any] = "banana bananas bandana band apple all beast".split()
lowerCAmelCase_ : Optional[Any] = RadixNode()
root.insert_many(snake_case__)
assert all(root.find(snake_case__) for word in words)
assert not root.find("bandanas")
assert not root.find("apps")
root.delete("all")
assert not root.find("all")
root.delete("banana")
assert not root.find("banana")
assert root.find("bananas")
return True
def UpperCamelCase ( ):
assert test_trie()
def UpperCamelCase ( ):
lowerCAmelCase_ : str = RadixNode()
lowerCAmelCase_ : str = "banana bananas bandanas bandana band apple all beast".split()
root.insert_many(snake_case__)
print("Words:" , snake_case__)
print("Tree:")
root.print_tree()
if __name__ == "__main__":
main()
| 659 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.