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
'''simple docstring''' from __future__ import annotations import math import random from typing import Any class UpperCamelCase_ : """simple docstring""" def __init__( self : List[Any] ) -> None: __magic_name__ = [] __magic_name__ = 0 __magic_name__ = 0 def __A ( self : Dict ) -> bool: return self.head == self.tail def __A ( self : List[Any] , _lowerCamelCase : Any ) -> None: self.data.append(_lowerCamelCase ) __magic_name__ = self.tail + 1 def __A ( self : int ) -> Any: __magic_name__ = self.data[self.head] __magic_name__ = self.head + 1 return ret def __A ( self : Optional[Any] ) -> int: return self.tail - self.head def __A ( self : List[Any] ) -> None: print(self.data ) print("**************" ) print(self.data[self.head : self.tail] ) class UpperCamelCase_ : """simple docstring""" def __init__( self : List[Any] , _lowerCamelCase : Any ) -> None: __magic_name__ = data __magic_name__ = None __magic_name__ = None __magic_name__ = 1 def __A ( self : List[Any] ) -> Any: return self.data def __A ( self : Union[str, Any] ) -> MyNode | None: return self.left def __A ( self : List[Any] ) -> MyNode | None: return self.right def __A ( self : List[str] ) -> int: return self.height def __A ( self : str , _lowerCamelCase : Any ) -> None: __magic_name__ = data def __A ( self : List[str] , _lowerCamelCase : MyNode | None ) -> None: __magic_name__ = node def __A ( self : Dict , _lowerCamelCase : MyNode | None ) -> None: __magic_name__ = node def __A ( self : List[Any] , _lowerCamelCase : int ) -> None: __magic_name__ = height def __snake_case ( lowerCamelCase_ : MyNode | None ): '''simple docstring''' if node is None: return 0 return node.get_height() def __snake_case ( lowerCamelCase_ : int , lowerCamelCase_ : int ): '''simple docstring''' if a > b: return a return b def __snake_case ( lowerCamelCase_ : MyNode ): '''simple docstring''' print("left rotation node:" , node.get_data() ) __magic_name__ = node.get_left() assert ret is not None node.set_left(ret.get_right() ) ret.set_right(lowerCamelCase_ ) __magic_name__ = my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1 node.set_height(lowerCamelCase_ ) __magic_name__ = my_max(get_height(ret.get_right() ) , get_height(ret.get_left() ) ) + 1 ret.set_height(lowerCamelCase_ ) return ret def __snake_case ( lowerCamelCase_ : MyNode ): '''simple docstring''' print("right rotation node:" , node.get_data() ) __magic_name__ = node.get_right() assert ret is not None node.set_right(ret.get_left() ) ret.set_left(lowerCamelCase_ ) __magic_name__ = my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1 node.set_height(lowerCamelCase_ ) __magic_name__ = my_max(get_height(ret.get_right() ) , get_height(ret.get_left() ) ) + 1 ret.set_height(lowerCamelCase_ ) return ret def __snake_case ( lowerCamelCase_ : MyNode ): '''simple docstring''' __magic_name__ = node.get_left() assert left_child is not None node.set_left(left_rotation(lowerCamelCase_ ) ) return right_rotation(lowerCamelCase_ ) def __snake_case ( lowerCamelCase_ : MyNode ): '''simple docstring''' __magic_name__ = node.get_right() assert right_child is not None node.set_right(right_rotation(lowerCamelCase_ ) ) return left_rotation(lowerCamelCase_ ) def __snake_case ( lowerCamelCase_ : MyNode | None , lowerCamelCase_ : Any ): '''simple docstring''' if node is None: return MyNode(lowerCamelCase_ ) if data < node.get_data(): node.set_left(insert_node(node.get_left() , lowerCamelCase_ ) ) if ( get_height(node.get_left() ) - get_height(node.get_right() ) == 2 ): # an unbalance detected __magic_name__ = node.get_left() assert left_child is not None if ( data < left_child.get_data() ): # new node is the left child of the left child __magic_name__ = right_rotation(lowerCamelCase_ ) else: __magic_name__ = lr_rotation(lowerCamelCase_ ) else: node.set_right(insert_node(node.get_right() , lowerCamelCase_ ) ) if get_height(node.get_right() ) - get_height(node.get_left() ) == 2: __magic_name__ = node.get_right() assert right_child is not None if data < right_child.get_data(): __magic_name__ = rl_rotation(lowerCamelCase_ ) else: __magic_name__ = left_rotation(lowerCamelCase_ ) __magic_name__ = my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1 node.set_height(lowerCamelCase_ ) return node def __snake_case ( lowerCamelCase_ : MyNode ): '''simple docstring''' while True: __magic_name__ = root.get_right() if right_child is None: break __magic_name__ = right_child return root.get_data() def __snake_case ( lowerCamelCase_ : MyNode ): '''simple docstring''' while True: __magic_name__ = root.get_left() if left_child is None: break __magic_name__ = left_child return root.get_data() def __snake_case ( lowerCamelCase_ : MyNode , lowerCamelCase_ : Any ): '''simple docstring''' __magic_name__ = root.get_left() __magic_name__ = root.get_right() if root.get_data() == data: if left_child is not None and right_child is not None: __magic_name__ = get_left_most(lowerCamelCase_ ) root.set_data(lowerCamelCase_ ) root.set_right(del_node(lowerCamelCase_ , lowerCamelCase_ ) ) elif left_child is not None: __magic_name__ = left_child elif right_child is not None: __magic_name__ = right_child else: return None elif root.get_data() > data: if left_child is None: print("No such data" ) return root else: root.set_left(del_node(lowerCamelCase_ , lowerCamelCase_ ) ) else: # root.get_data() < data if right_child is None: return root else: root.set_right(del_node(lowerCamelCase_ , lowerCamelCase_ ) ) if get_height(lowerCamelCase_ ) - get_height(lowerCamelCase_ ) == 2: assert right_child is not None if get_height(right_child.get_right() ) > get_height(right_child.get_left() ): __magic_name__ = left_rotation(lowerCamelCase_ ) else: __magic_name__ = rl_rotation(lowerCamelCase_ ) elif get_height(lowerCamelCase_ ) - get_height(lowerCamelCase_ ) == -2: assert left_child is not None if get_height(left_child.get_left() ) > get_height(left_child.get_right() ): __magic_name__ = right_rotation(lowerCamelCase_ ) else: __magic_name__ = lr_rotation(lowerCamelCase_ ) __magic_name__ = my_max(get_height(root.get_right() ) , get_height(root.get_left() ) ) + 1 root.set_height(lowerCamelCase_ ) return root class UpperCamelCase_ : """simple docstring""" def __init__( self : str ) -> None: __magic_name__ = None def __A ( self : List[str] ) -> int: return get_height(self.root ) def __A ( self : Optional[Any] , _lowerCamelCase : Any ) -> None: print("insert:" + str(_lowerCamelCase ) ) __magic_name__ = insert_node(self.root , _lowerCamelCase ) def __A ( self : Union[str, Any] , _lowerCamelCase : Any ) -> None: print("delete:" + str(_lowerCamelCase ) ) if self.root is None: print("Tree is empty!" ) return __magic_name__ = del_node(self.root , _lowerCamelCase ) def __str__( self : List[Any] , ) -> str: # a level traversale, gives a more intuitive look on the tree __magic_name__ = "" __magic_name__ = MyQueue() q.push(self.root ) __magic_name__ = self.get_height() if layer == 0: return output __magic_name__ = 0 while not q.is_empty(): __magic_name__ = q.pop() __magic_name__ = " " * int(math.pow(2 , layer - 1 ) ) output += space if node is None: output += "*" q.push(_lowerCamelCase ) q.push(_lowerCamelCase ) else: output += str(node.get_data() ) q.push(node.get_left() ) q.push(node.get_right() ) output += space __magic_name__ = cnt + 1 for i in range(1_00 ): if cnt == math.pow(2 , _lowerCamelCase ) - 1: __magic_name__ = layer - 1 if layer == 0: output += "\n*************************************" return output output += "\n" break output += "\n*************************************" return output def __snake_case ( ): '''simple docstring''' import doctest doctest.testmod() if __name__ == "__main__": _test() __magic_name__ : Optional[Any] =AVLtree() __magic_name__ : Optional[int] =list(range(10)) random.shuffle(lst) for i in lst: t.insert(i) print(str(t)) random.shuffle(lst) for i in lst: t.del_node(i) print(str(t))
664
'''simple docstring''' def __snake_case ( lowerCamelCase_ : int , lowerCamelCase_ : int ): '''simple docstring''' if a < 0 or b < 0: raise ValueError("the value of both inputs must be positive" ) __magic_name__ = str(bin(lowerCamelCase_ ) )[2:] # remove the leading "0b" __magic_name__ = str(bin(lowerCamelCase_ ) )[2:] # remove the leading "0b" __magic_name__ = max(len(lowerCamelCase_ ) , len(lowerCamelCase_ ) ) return "0b" + "".join( str(int(char_a == "1" and char_b == "1" ) ) for char_a, char_b in zip(a_binary.zfill(lowerCamelCase_ ) , b_binary.zfill(lowerCamelCase_ ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
664
1
'''simple docstring''' import json import os from datetime import date from pathlib import Path from tabulate import DataRow, TableFormat, tabulate __magic_name__ : str =TableFormat( lineabove=None, linebelowheader=None, linebetweenrows=None, linebelow=None, headerrow=DataRow('', '|', '|'), datarow=DataRow('', '|', '|'), padding=1, with_header_hide=None, ) __magic_name__ : Optional[Any] =[] __magic_name__ : str =[] __magic_name__ : int ={'type': 'section', 'text': {'type': 'plain_text', 'text': 'No failed tests! 🤗', 'emoji': True}} __magic_name__ : str =[ { 'type': 'header', 'text': { 'type': 'plain_text', 'text': F'''🤗 Accelerate nightly {os.environ.get('TEST_TYPE', '')} test results''', 'emoji': True, }, } ] __magic_name__ : Any =0 for log in Path().glob('*.log'): __magic_name__ : List[Any] =0 with open(log, 'r') as f: for line in f: __magic_name__ : List[Any] =json.loads(line) if line.get('nodeid', '') != "": __magic_name__ : List[Any] =line['nodeid'] if line.get('duration', None) is not None: __magic_name__ : Any =F'''{line['duration']:.4f}''' if line.get('outcome', '') == "failed": section_num_failed += 1 failed.append([test, duration, log.name.split('_')[0]]) total_num_failed += 1 group_info.append([str(log), section_num_failed, failed]) __magic_name__ : int =[] log.unlink() __magic_name__ : Dict ='' __magic_name__ : Dict =[] if total_num_failed > 0: for name, num_failed, failed_tests in group_info: if num_failed > 0: if num_failed == 1: message += F"*{name[1:]}: {num_failed} failed test*\n" else: message += F"*{name[1:]}: {num_failed} failed tests*\n" __magic_name__ : Any =[] __magic_name__ : List[str] ={} for test in failed_tests: __magic_name__ : Optional[Any] =test[0].split('::') __magic_name__ : Tuple =data[0].split('/')[-1] if data[0] not in filesafailed: __magic_name__ : Union[str, Any] =[data[1:]] else: filesafailed[data[0]] += [data[1:]] failed_table.append(data) __magic_name__ : Optional[int] =[test[0] for test in failed_table] __magic_name__ : Dict =list(set(files)) # Count number of instances in failed_tests __magic_name__ : Dict =[] for file in individual_files: table.append([file, len(filesafailed[file])]) __magic_name__ : int =tabulate( table, headers=['Test Location', 'Num Failed'], tablefmt=hf_table_format, stralign='right', ) message += F"\n```\n{failed_table}\n```" all_filesafailed.append(filesafailed) if len(message) > 30_00: __magic_name__ : Union[str, Any] ='Too many failed tests, please see the full report in the Action results.' __magic_name__ : Union[str, Any] =len(err) + 10 __magic_name__ : str =message[: 30_00 - offset] + F'''\n...\n```\n{err}''' print(F'''### {message}''') else: __magic_name__ : Dict ='No failed tests! 🤗' print(F'''## {message}''') payload.append(no_error_payload) if os.environ.get('TEST_TYPE', '') != "": from slack_sdk import WebClient __magic_name__ : Optional[int] =WebClient(token=os.environ['SLACK_API_TOKEN']) if message != "No failed tests! 🤗": __magic_name__ : str ={ 'type': 'section', 'text': { 'type': 'mrkdwn', 'text': message, }, } payload.append(md_report) __magic_name__ : Tuple ={ 'type': 'section', 'text': { 'type': 'mrkdwn', 'text': '*For more details:*', }, 'accessory': { 'type': 'button', 'text': { 'type': 'plain_text', 'text': 'Check Action results', 'emoji': True, }, 'url': F'''https://github.com/{os.environ['GITHUB_REPOSITORY']}/actions/runs/{os.environ['GITHUB_RUN_ID']}''', }, } payload.append(action_button) __magic_name__ : int ={ 'type': 'context', 'elements': [ { 'type': 'plain_text', 'text': F'''Nightly {os.environ.get('TEST_TYPE')} test results for {date.today()}''', } ], } payload.append(date_report) __magic_name__ : int =client.chat_postMessage(channel='#accelerate-ci-daily', text=message, blocks=payload) __magic_name__ : List[str] =response.data['ts'] for failed_file in all_filesafailed: for test_location, test_failures in failed_file.items(): # Keep only the first instance of the test name __magic_name__ : Dict ='' for i, row in enumerate(test_failures): if row[0] != test_class: __magic_name__ : Union[str, Any] =row[0] else: __magic_name__ : List[Any] ='' __magic_name__ : Tuple ={ 'type': 'section', 'text': { 'type': 'mrkdwn', 'text': F'''Test location: {test_location}\n```\n{tabulate(test_failures, headers=['Class', 'Test'], tablefmt=hf_table_format, stralign='right')}\n```''', }, } client.chat_postMessage( channel='#accelerate-ci-daily', thread_ts=ts, blocks=[payload], )
664
'''simple docstring''' import functools import logging import os import sys import threading from logging import ( CRITICAL, # NOQA DEBUG, # NOQA ERROR, # NOQA FATAL, # NOQA INFO, # NOQA NOTSET, # NOQA WARN, # NOQA WARNING, # NOQA ) from typing import Optional import huggingface_hub.utils as hf_hub_utils from tqdm import auto as tqdm_lib __magic_name__ : Tuple =threading.Lock() __magic_name__ : Optional[logging.Handler] =None __magic_name__ : List[str] ={ 'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'critical': logging.CRITICAL, } __magic_name__ : str =logging.WARNING __magic_name__ : Any =True def __snake_case ( ): '''simple docstring''' __magic_name__ = os.getenv("TRANSFORMERS_VERBOSITY" , lowerCamelCase_ ) if env_level_str: if env_level_str in log_levels: return log_levels[env_level_str] else: logging.getLogger().warning( F'Unknown option TRANSFORMERS_VERBOSITY={env_level_str}, ' F'has to be one of: { ", ".join(log_levels.keys() ) }' ) return _default_log_level def __snake_case ( ): '''simple docstring''' return __name__.split("." )[0] def __snake_case ( ): '''simple docstring''' return logging.getLogger(_get_library_name() ) def __snake_case ( ): '''simple docstring''' global _default_handler with _lock: if _default_handler: # This library has already configured the library root logger. return __magic_name__ = logging.StreamHandler() # Set sys.stderr as stream. __magic_name__ = sys.stderr.flush # Apply our default configuration to the library root logger. __magic_name__ = _get_library_root_logger() library_root_logger.addHandler(_default_handler ) library_root_logger.setLevel(_get_default_logging_level() ) __magic_name__ = False def __snake_case ( ): '''simple docstring''' global _default_handler with _lock: if not _default_handler: return __magic_name__ = _get_library_root_logger() library_root_logger.removeHandler(_default_handler ) library_root_logger.setLevel(logging.NOTSET ) __magic_name__ = None def __snake_case ( ): '''simple docstring''' return log_levels def __snake_case ( lowerCamelCase_ : Optional[str] = None ): '''simple docstring''' if name is None: __magic_name__ = _get_library_name() _configure_library_root_logger() return logging.getLogger(lowerCamelCase_ ) def __snake_case ( ): '''simple docstring''' _configure_library_root_logger() return _get_library_root_logger().getEffectiveLevel() def __snake_case ( lowerCamelCase_ : int ): '''simple docstring''' _configure_library_root_logger() _get_library_root_logger().setLevel(lowerCamelCase_ ) def __snake_case ( ): '''simple docstring''' return set_verbosity(lowerCamelCase_ ) def __snake_case ( ): '''simple docstring''' return set_verbosity(lowerCamelCase_ ) def __snake_case ( ): '''simple docstring''' return set_verbosity(lowerCamelCase_ ) def __snake_case ( ): '''simple docstring''' return set_verbosity(lowerCamelCase_ ) def __snake_case ( ): '''simple docstring''' _configure_library_root_logger() assert _default_handler is not None _get_library_root_logger().removeHandler(_default_handler ) def __snake_case ( ): '''simple docstring''' _configure_library_root_logger() assert _default_handler is not None _get_library_root_logger().addHandler(_default_handler ) def __snake_case ( lowerCamelCase_ : logging.Handler ): '''simple docstring''' _configure_library_root_logger() assert handler is not None _get_library_root_logger().addHandler(lowerCamelCase_ ) def __snake_case ( lowerCamelCase_ : logging.Handler ): '''simple docstring''' _configure_library_root_logger() assert handler is not None and handler not in _get_library_root_logger().handlers _get_library_root_logger().removeHandler(lowerCamelCase_ ) def __snake_case ( ): '''simple docstring''' _configure_library_root_logger() __magic_name__ = False def __snake_case ( ): '''simple docstring''' _configure_library_root_logger() __magic_name__ = True def __snake_case ( ): '''simple docstring''' __magic_name__ = _get_library_root_logger().handlers for handler in handlers: __magic_name__ = logging.Formatter("[%(levelname)s|%(filename)s:%(lineno)s] %(asctime)s >> %(message)s" ) handler.setFormatter(lowerCamelCase_ ) def __snake_case ( ): '''simple docstring''' __magic_name__ = _get_library_root_logger().handlers for handler in handlers: handler.setFormatter(lowerCamelCase_ ) def __snake_case ( self : Union[str, Any] , *lowerCamelCase_ : str , **lowerCamelCase_ : Any ): '''simple docstring''' __magic_name__ = os.getenv("TRANSFORMERS_NO_ADVISORY_WARNINGS" , lowerCamelCase_ ) if no_advisory_warnings: return self.warning(*lowerCamelCase_ , **lowerCamelCase_ ) __magic_name__ : int =warning_advice @functools.lru_cache(lowerCamelCase_ ) def __snake_case ( self : Dict , *lowerCamelCase_ : int , **lowerCamelCase_ : int ): '''simple docstring''' self.warning(*lowerCamelCase_ , **lowerCamelCase_ ) __magic_name__ : Optional[int] =warning_once class UpperCamelCase_ : """simple docstring""" def __init__( self : int , *_lowerCamelCase : Tuple , **_lowerCamelCase : Optional[Any] ) -> Any: # pylint: disable=unused-argument __magic_name__ = args[0] if args else None def __iter__( self : int ) -> Tuple: return iter(self._iterator ) def __getattr__( self : List[Any] , _lowerCamelCase : int ) -> List[Any]: def empty_fn(*_lowerCamelCase : List[str] , **_lowerCamelCase : List[str] ): # pylint: disable=unused-argument return return empty_fn def __enter__( self : Optional[Any] ) -> Any: return self def __exit__( self : int , _lowerCamelCase : List[Any] , _lowerCamelCase : List[Any] , _lowerCamelCase : List[str] ) -> Dict: return class UpperCamelCase_ : """simple docstring""" def __call__( self : Any , *_lowerCamelCase : Optional[Any] , **_lowerCamelCase : Any ) -> List[Any]: if _tqdm_active: return tqdm_lib.tqdm(*_lowerCamelCase , **_lowerCamelCase ) else: return EmptyTqdm(*_lowerCamelCase , **_lowerCamelCase ) def __A ( self : Optional[Any] , *_lowerCamelCase : Optional[Any] , **_lowerCamelCase : Dict ) -> Union[str, Any]: __magic_name__ = None if _tqdm_active: return tqdm_lib.tqdm.set_lock(*_lowerCamelCase , **_lowerCamelCase ) def __A ( self : str ) -> Any: if _tqdm_active: return tqdm_lib.tqdm.get_lock() __magic_name__ : List[Any] =_tqdm_cls() def __snake_case ( ): '''simple docstring''' global _tqdm_active return bool(_tqdm_active ) def __snake_case ( ): '''simple docstring''' global _tqdm_active __magic_name__ = True hf_hub_utils.enable_progress_bars() def __snake_case ( ): '''simple docstring''' global _tqdm_active __magic_name__ = False hf_hub_utils.disable_progress_bars()
664
1
'''simple docstring''' import tempfile import unittest from pathlib import Path from shutil import copyfile from transformers import BatchEncoding, MarianTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow from transformers.utils import is_sentencepiece_available, is_tf_available, is_torch_available if is_sentencepiece_available(): from transformers.models.marian.tokenization_marian import VOCAB_FILES_NAMES, save_json from ...test_tokenization_common import TokenizerTesterMixin __magic_name__ : Union[str, Any] =get_tests_dir('fixtures/test_sentencepiece.model') __magic_name__ : Optional[int] ={'target_lang': 'fi', 'source_lang': 'en'} __magic_name__ : Tuple ='>>zh<<' __magic_name__ : Dict ='Helsinki-NLP/' if is_torch_available(): __magic_name__ : List[Any] ='pt' elif is_tf_available(): __magic_name__ : Tuple ='tf' else: __magic_name__ : int ='jax' @require_sentencepiece class UpperCamelCase_ ( A , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Optional[Any] = MarianTokenizer UpperCAmelCase__ : Any = False UpperCAmelCase__ : List[str] = True def __A ( self : str ) -> Union[str, Any]: super().setUp() __magic_name__ = ["</s>", "<unk>", "▁This", "▁is", "▁a", "▁t", "est", "\u0120", "<pad>"] __magic_name__ = dict(zip(_lowerCamelCase , range(len(_lowerCamelCase ) ) ) ) __magic_name__ = Path(self.tmpdirname ) save_json(_lowerCamelCase , save_dir / VOCAB_FILES_NAMES["vocab"] ) save_json(_lowerCamelCase , save_dir / VOCAB_FILES_NAMES["tokenizer_config_file"] ) if not (save_dir / VOCAB_FILES_NAMES["source_spm"]).exists(): copyfile(_lowerCamelCase , save_dir / VOCAB_FILES_NAMES["source_spm"] ) copyfile(_lowerCamelCase , save_dir / VOCAB_FILES_NAMES["target_spm"] ) __magic_name__ = MarianTokenizer.from_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname ) def __A ( self : Tuple , **_lowerCamelCase : Union[str, Any] ) -> MarianTokenizer: return MarianTokenizer.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def __A ( self : Tuple , _lowerCamelCase : Tuple ) -> Optional[Any]: return ( "This is a test", "This is a test", ) def __A ( self : str ) -> List[Any]: __magic_name__ = "</s>" __magic_name__ = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_lowerCamelCase ) , _lowerCamelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_lowerCamelCase ) , _lowerCamelCase ) def __A ( self : Optional[int] ) -> str: __magic_name__ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "</s>" ) self.assertEqual(vocab_keys[1] , "<unk>" ) self.assertEqual(vocab_keys[-1] , "<pad>" ) self.assertEqual(len(_lowerCamelCase ) , 9 ) def __A ( self : int ) -> Optional[Any]: self.assertEqual(self.get_tokenizer().vocab_size , 9 ) def __A ( self : Tuple ) -> Any: __magic_name__ = MarianTokenizer.from_pretrained(f'{ORG_NAME}opus-mt-en-de' ) __magic_name__ = en_de_tokenizer(["I am a small frog"] , return_tensors=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __magic_name__ = [38, 1_21, 14, 6_97, 3_88_48, 0] self.assertListEqual(_lowerCamelCase , batch.input_ids[0] ) __magic_name__ = tempfile.mkdtemp() en_de_tokenizer.save_pretrained(_lowerCamelCase ) __magic_name__ = [x.name for x in Path(_lowerCamelCase ).glob("*" )] self.assertIn("source.spm" , _lowerCamelCase ) MarianTokenizer.from_pretrained(_lowerCamelCase ) def __A ( self : Tuple ) -> Union[str, Any]: __magic_name__ = self.get_tokenizer() __magic_name__ = tok( ["I am a small frog" * 10_00, "I am a small frog"] , padding=_lowerCamelCase , truncation=_lowerCamelCase , return_tensors=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(batch.input_ids.shape , (2, 5_12) ) def __A ( self : Tuple ) -> Union[str, Any]: __magic_name__ = self.get_tokenizer() __magic_name__ = tok(["I am a tiny frog", "I am a small frog"] , padding=_lowerCamelCase , return_tensors=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(batch_smaller.input_ids.shape , (2, 10) ) @slow def __A ( self : Dict ) -> List[Any]: # fmt: off __magic_name__ = {"input_ids": [[4_34_95, 4_62, 20, 4_21_64, 13_69, 52, 4_64, 1_32, 17_03, 4_92, 13, 74_91, 3_89_99, 6, 8, 4_64, 1_32, 17_03, 4_92, 13, 46_69, 3_78_67, 13, 75_25, 27, 15_93, 9_88, 13, 3_39_72, 70_29, 6, 20, 82_51, 3_83, 2, 2_70, 58_66, 37_88, 2, 23_53, 82_51, 1_23_38, 2, 1_39_58, 3_87, 2, 36_29, 69_53, 1_88, 29_00, 2, 1_39_58, 80_11, 1_15_01, 23, 84_60, 40_73, 3_40_09, 20, 4_35, 1_14_39, 27, 8, 84_60, 40_73, 60_04, 20, 99_88, 3_75, 27, 33, 2_66, 19_45, 10_76, 13_50, 3_78_67, 32_88, 5, 5_77, 10_76, 43_74, 8, 50_82, 5, 2_64_53, 2_57, 5_56, 4_03, 2, 2_42, 1_32, 3_83, 3_16, 4_92, 8, 1_07_67, 6, 3_16, 3_04, 42_39, 3, 0], [1_48, 1_57_22, 19, 18_39, 12, 13_50, 13, 2_23_27, 50_82, 54_18, 4_75_67, 3_59_38, 59, 3_18, 1_95_52, 1_08, 21_83, 54, 1_49_76, 48_35, 32, 5_47, 11_14, 8, 3_15, 24_17, 5, 92, 1_90_88, 3, 0, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00], [36, 63_95, 1_25_70, 3_91_47, 1_15_97, 6, 2_66, 4, 4_54_05, 72_96, 3, 0, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00]], "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, 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], [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, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=_lowerCamelCase , model_name="Helsinki-NLP/opus-mt-en-de" , revision="1a8c2263da11e68e50938f97e10cd57820bd504c" , decode_kwargs={"use_source_tokenizer": True} , ) def __A ( self : Tuple ) -> Any: __magic_name__ = MarianTokenizer.from_pretrained("hf-internal-testing/test-marian-two-vocabs" ) __magic_name__ = "Tämä on testi" __magic_name__ = "This is a test" __magic_name__ = [76, 7, 20_47, 2] __magic_name__ = [69, 12, 11, 9_40, 2] __magic_name__ = tokenizer(_lowerCamelCase ).input_ids self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) __magic_name__ = tokenizer(text_target=_lowerCamelCase ).input_ids self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) __magic_name__ = tokenizer.decode(_lowerCamelCase , skip_special_tokens=_lowerCamelCase ) self.assertEqual(_lowerCamelCase , _lowerCamelCase )
664
'''simple docstring''' from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __magic_name__ : Union[str, Any] ={'configuration_focalnet': ['FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP', 'FocalNetConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ : str =[ 'FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST', 'FocalNetForImageClassification', 'FocalNetForMaskedImageModeling', 'FocalNetBackbone', 'FocalNetModel', 'FocalNetPreTrainedModel', ] if TYPE_CHECKING: from .configuration_focalnet import FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FocalNetConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_focalnet import ( FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST, FocalNetBackbone, FocalNetForImageClassification, FocalNetForMaskedImageModeling, FocalNetModel, FocalNetPreTrainedModel, ) else: import sys __magic_name__ : List[Any] =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
664
1
'''simple docstring''' # Copyright 2022 The HuggingFace Team and The OpenBMB 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 __magic_name__ : Dict ={ 'configuration_cpmant': ['CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'CpmAntConfig'], 'tokenization_cpmant': ['CpmAntTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ : List[Any] =[ 'CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST', 'CpmAntForCausalLM', 'CpmAntModel', 'CpmAntPreTrainedModel', ] if TYPE_CHECKING: from .configuration_cpmant import CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP, CpmAntConfig from .tokenization_cpmant import CpmAntTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_cpmant import ( CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST, CpmAntForCausalLM, CpmAntModel, CpmAntPreTrainedModel, ) else: import sys __magic_name__ : Any =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
664
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) __magic_name__ : Optional[Any] ={ 'configuration_longformer': [ 'LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LongformerConfig', 'LongformerOnnxConfig', ], 'tokenization_longformer': ['LongformerTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ : int =['LongformerTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ : Dict =[ 'LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'LongformerForMaskedLM', 'LongformerForMultipleChoice', 'LongformerForQuestionAnswering', 'LongformerForSequenceClassification', 'LongformerForTokenClassification', 'LongformerModel', 'LongformerPreTrainedModel', 'LongformerSelfAttention', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ : Tuple =[ 'TF_LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFLongformerForMaskedLM', 'TFLongformerForMultipleChoice', 'TFLongformerForQuestionAnswering', 'TFLongformerForSequenceClassification', 'TFLongformerForTokenClassification', 'TFLongformerModel', 'TFLongformerPreTrainedModel', 'TFLongformerSelfAttention', ] if TYPE_CHECKING: from .configuration_longformer import ( LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, LongformerConfig, LongformerOnnxConfig, ) from .tokenization_longformer import LongformerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_longformer_fast import LongformerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_longformer import ( LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, LongformerForMaskedLM, LongformerForMultipleChoice, LongformerForQuestionAnswering, LongformerForSequenceClassification, LongformerForTokenClassification, LongformerModel, LongformerPreTrainedModel, LongformerSelfAttention, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_longformer import ( TF_LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFLongformerForMaskedLM, TFLongformerForMultipleChoice, TFLongformerForQuestionAnswering, TFLongformerForSequenceClassification, TFLongformerForTokenClassification, TFLongformerModel, TFLongformerPreTrainedModel, TFLongformerSelfAttention, ) else: import sys __magic_name__ : int =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
664
1
'''simple docstring''' def __snake_case ( lowerCamelCase_ : list[int] , lowerCamelCase_ : str ): '''simple docstring''' __magic_name__ = int(lowerCamelCase_ ) # Initialize Result __magic_name__ = [] # Traverse through all denomination for denomination in reversed(lowerCamelCase_ ): # Find denominations while int(lowerCamelCase_ ) >= int(lowerCamelCase_ ): total_value -= int(lowerCamelCase_ ) answer.append(lowerCamelCase_ ) # Append the "answers" array return answer # Driver Code if __name__ == "__main__": __magic_name__ : Any =[] __magic_name__ : List[str] ='0' if ( input('Do you want to enter your denominations ? (yY/n): ').strip().lower() == "y" ): __magic_name__ : Dict =int(input('Enter the number of denominations you want to add: ').strip()) for i in range(0, n): denominations.append(int(input(F'''Denomination {i}: ''').strip())) __magic_name__ : Dict =input('Enter the change you want to make in Indian Currency: ').strip() else: # All denominations of Indian Currency if user does not enter __magic_name__ : List[Any] =[1, 2, 5, 10, 20, 50, 1_00, 5_00, 20_00] __magic_name__ : List[Any] =input('Enter the change you want to make: ').strip() if int(value) == 0 or int(value) < 0: print('The total value cannot be zero or negative.') else: print(F'''Following is minimal change for {value}: ''') __magic_name__ : Optional[int] =find_minimum_change(denominations, value) # Print result for i in range(len(answer)): print(answer[i], end=' ')
664
'''simple docstring''' import PIL.Image import PIL.ImageOps from packaging import version from PIL import Image if version.parse(version.parse(PIL.__version__).base_version) >= version.parse('9.1.0'): __magic_name__ : str ={ 'linear': PIL.Image.Resampling.BILINEAR, 'bilinear': PIL.Image.Resampling.BILINEAR, 'bicubic': PIL.Image.Resampling.BICUBIC, 'lanczos': PIL.Image.Resampling.LANCZOS, 'nearest': PIL.Image.Resampling.NEAREST, } else: __magic_name__ : Tuple ={ 'linear': PIL.Image.LINEAR, 'bilinear': PIL.Image.BILINEAR, 'bicubic': PIL.Image.BICUBIC, 'lanczos': PIL.Image.LANCZOS, 'nearest': PIL.Image.NEAREST, } def __snake_case ( lowerCamelCase_ : Optional[Any] ): '''simple docstring''' __magic_name__ = (images / 2 + 0.5).clamp(0 , 1 ) __magic_name__ = images.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() __magic_name__ = numpy_to_pil(lowerCamelCase_ ) return images def __snake_case ( lowerCamelCase_ : Optional[Any] ): '''simple docstring''' if images.ndim == 3: __magic_name__ = images[None, ...] __magic_name__ = (images * 255).round().astype("uint8" ) if images.shape[-1] == 1: # special case for grayscale (single channel) images __magic_name__ = [Image.fromarray(image.squeeze() , mode="L" ) for image in images] else: __magic_name__ = [Image.fromarray(lowerCamelCase_ ) for image in images] return pil_images
664
1
'''simple docstring''' def __snake_case ( lowerCamelCase_ : Tuple , lowerCamelCase_ : Optional[Any] ): '''simple docstring''' __magic_name__ = 0 __magic_name__ = len(lowerCamelCase_ ) - 1 while left <= right: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None __magic_name__ = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(lowerCamelCase_ ): return None __magic_name__ = sorted_collection[point] if current_item == item: return point else: if point < left: __magic_name__ = left __magic_name__ = point elif point > right: __magic_name__ = right __magic_name__ = point else: if item < current_item: __magic_name__ = point - 1 else: __magic_name__ = point + 1 return None def __snake_case ( lowerCamelCase_ : Dict , lowerCamelCase_ : int , lowerCamelCase_ : Any , lowerCamelCase_ : List[Any] ): '''simple docstring''' if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None __magic_name__ = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(lowerCamelCase_ ): return None if sorted_collection[point] == item: return point elif point < left: return interpolation_search_by_recursion(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) elif point > right: return interpolation_search_by_recursion(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) else: if sorted_collection[point] > item: return interpolation_search_by_recursion( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , point - 1 ) else: return interpolation_search_by_recursion( lowerCamelCase_ , lowerCamelCase_ , point + 1 , lowerCamelCase_ ) def __snake_case ( lowerCamelCase_ : List[str] ): '''simple docstring''' if collection != sorted(lowerCamelCase_ ): raise ValueError("Collection must be ascending sorted" ) return True if __name__ == "__main__": import sys __magic_name__ : str =0 if debug == 1: __magic_name__ : Union[str, Any] =[10, 30, 40, 45, 50, 66, 77, 93] try: __assert_sorted(collection) except ValueError: sys.exit('Sequence must be ascending sorted to apply interpolation search') __magic_name__ : str =67 __magic_name__ : Optional[int] =interpolation_search(collection, target) if result is not None: print(F'''{target} found at positions: {result}''') else: print('Not found')
664
'''simple docstring''' from typing import Dict import numpy as np from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException if is_tf_available(): import tensorflow as tf from ..tf_utils import stable_softmax if is_torch_available(): import torch __magic_name__ : Optional[Any] =logging.get_logger(__name__) @add_end_docstrings( A , r''' top_k (`int`, defaults to 5): The number of predictions to return. targets (`str` or `List[str]`, *optional*): When passed, the model will limit the scores to the passed targets instead of looking up in the whole vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting token will be used (with a warning, and that might be slower). ''' , ) class UpperCamelCase_ ( A ): """simple docstring""" def __A ( self : Any , _lowerCamelCase : GenericTensor ) -> np.ndarray: if self.framework == "tf": __magic_name__ = tf.where(input_ids == self.tokenizer.mask_token_id ).numpy() elif self.framework == "pt": __magic_name__ = torch.nonzero(input_ids == self.tokenizer.mask_token_id , as_tuple=_lowerCamelCase ) else: raise ValueError("Unsupported framework" ) return masked_index def __A ( self : str , _lowerCamelCase : GenericTensor ) -> np.ndarray: __magic_name__ = self.get_masked_index(_lowerCamelCase ) __magic_name__ = np.prod(masked_index.shape ) if numel < 1: raise PipelineException( "fill-mask" , self.model.base_model_prefix , f'No mask_token ({self.tokenizer.mask_token}) found on the input' , ) def __A ( self : int , _lowerCamelCase : GenericTensor ) -> Any: if isinstance(_lowerCamelCase , _lowerCamelCase ): for model_input in model_inputs: self._ensure_exactly_one_mask_token(model_input["input_ids"][0] ) else: for input_ids in model_inputs["input_ids"]: self._ensure_exactly_one_mask_token(_lowerCamelCase ) def __A ( self : List[Any] , _lowerCamelCase : str , _lowerCamelCase : Any=None , **_lowerCamelCase : List[str] ) -> Dict[str, GenericTensor]: if return_tensors is None: __magic_name__ = self.framework __magic_name__ = self.tokenizer(_lowerCamelCase , return_tensors=_lowerCamelCase ) self.ensure_exactly_one_mask_token(_lowerCamelCase ) return model_inputs def __A ( self : List[str] , _lowerCamelCase : int ) -> List[Any]: __magic_name__ = self.model(**_lowerCamelCase ) __magic_name__ = model_inputs["input_ids"] return model_outputs def __A ( self : Tuple , _lowerCamelCase : List[str] , _lowerCamelCase : List[Any]=5 , _lowerCamelCase : Dict=None ) -> Dict: # Cap top_k if there are targets if target_ids is not None and target_ids.shape[0] < top_k: __magic_name__ = target_ids.shape[0] __magic_name__ = model_outputs["input_ids"][0] __magic_name__ = model_outputs["logits"] if self.framework == "tf": __magic_name__ = tf.where(input_ids == self.tokenizer.mask_token_id ).numpy()[:, 0] __magic_name__ = outputs.numpy() __magic_name__ = outputs[0, masked_index, :] __magic_name__ = stable_softmax(_lowerCamelCase , axis=-1 ) if target_ids is not None: __magic_name__ = tf.gather_nd(tf.squeeze(_lowerCamelCase , 0 ) , target_ids.reshape(-1 , 1 ) ) __magic_name__ = tf.expand_dims(_lowerCamelCase , 0 ) __magic_name__ = tf.math.top_k(_lowerCamelCase , k=_lowerCamelCase ) __magic_name__ , __magic_name__ = topk.values.numpy(), topk.indices.numpy() else: __magic_name__ = torch.nonzero(input_ids == self.tokenizer.mask_token_id , as_tuple=_lowerCamelCase ).squeeze(-1 ) # Fill mask pipeline supports only one ${mask_token} per sample __magic_name__ = outputs[0, masked_index, :] __magic_name__ = logits.softmax(dim=-1 ) if target_ids is not None: __magic_name__ = probs[..., target_ids] __magic_name__ , __magic_name__ = probs.topk(_lowerCamelCase ) __magic_name__ = [] __magic_name__ = values.shape[0] == 1 for i, (_values, _predictions) in enumerate(zip(values.tolist() , predictions.tolist() ) ): __magic_name__ = [] for v, p in zip(_values , _predictions ): # Copy is important since we're going to modify this array in place __magic_name__ = input_ids.numpy().copy() if target_ids is not None: __magic_name__ = target_ids[p].tolist() __magic_name__ = p # Filter padding out: __magic_name__ = tokens[np.where(tokens != self.tokenizer.pad_token_id )] # Originally we skip special tokens to give readable output. # For multi masks though, the other [MASK] would be removed otherwise # making the output look odd, so we add them back __magic_name__ = self.tokenizer.decode(_lowerCamelCase , skip_special_tokens=_lowerCamelCase ) __magic_name__ = {"score": v, "token": p, "token_str": self.tokenizer.decode([p] ), "sequence": sequence} row.append(_lowerCamelCase ) result.append(_lowerCamelCase ) if single_mask: return result[0] return result def __A ( self : List[Any] , _lowerCamelCase : Any , _lowerCamelCase : List[Any]=None ) -> List[str]: if isinstance(_lowerCamelCase , _lowerCamelCase ): __magic_name__ = [targets] try: __magic_name__ = self.tokenizer.get_vocab() except Exception: __magic_name__ = {} __magic_name__ = [] for target in targets: __magic_name__ = vocab.get(_lowerCamelCase , _lowerCamelCase ) if id_ is None: __magic_name__ = self.tokenizer( _lowerCamelCase , add_special_tokens=_lowerCamelCase , return_attention_mask=_lowerCamelCase , return_token_type_ids=_lowerCamelCase , max_length=1 , truncation=_lowerCamelCase , )["input_ids"] if len(_lowerCamelCase ) == 0: logger.warning( f'The specified target token `{target}` does not exist in the model vocabulary. ' "We cannot replace it with anything meaningful, ignoring it" ) continue __magic_name__ = input_ids[0] # XXX: If users encounter this pass # it becomes pretty slow, so let's make sure # The warning enables them to fix the input to # get faster performance. logger.warning( f'The specified target token `{target}` does not exist in the model vocabulary. ' f'Replacing with `{self.tokenizer.convert_ids_to_tokens(id_ )}`.' ) target_ids.append(id_ ) __magic_name__ = list(set(_lowerCamelCase ) ) if len(_lowerCamelCase ) == 0: raise ValueError("At least one target must be provided when passed." ) __magic_name__ = np.array(_lowerCamelCase ) return target_ids def __A ( self : Optional[Any] , _lowerCamelCase : Any=None , _lowerCamelCase : int=None ) -> Tuple: __magic_name__ = {} if targets is not None: __magic_name__ = self.get_target_ids(_lowerCamelCase , _lowerCamelCase ) __magic_name__ = target_ids if top_k is not None: __magic_name__ = top_k if self.tokenizer.mask_token_id is None: raise PipelineException( "fill-mask" , self.model.base_model_prefix , "The tokenizer does not define a `mask_token`." ) return {}, {}, postprocess_params def __call__( self : int , _lowerCamelCase : Any , *_lowerCamelCase : str , **_lowerCamelCase : int ) -> Optional[int]: __magic_name__ = super().__call__(_lowerCamelCase , **_lowerCamelCase ) if isinstance(_lowerCamelCase , _lowerCamelCase ) and len(_lowerCamelCase ) == 1: return outputs[0] return outputs
664
1
'''simple docstring''' class UpperCamelCase_ : """simple docstring""" def __init__( self : Tuple ) -> None: __magic_name__ = {} # Mapping from char to TrieNode __magic_name__ = False def __A ( self : Tuple , _lowerCamelCase : list[str] ) -> None: for word in words: self.insert(_lowerCamelCase ) def __A ( self : Dict , _lowerCamelCase : str ) -> None: __magic_name__ = self for char in word: if char not in curr.nodes: __magic_name__ = TrieNode() __magic_name__ = curr.nodes[char] __magic_name__ = True def __A ( self : Dict , _lowerCamelCase : str ) -> bool: __magic_name__ = self for char in word: if char not in curr.nodes: return False __magic_name__ = curr.nodes[char] return curr.is_leaf def __A ( self : Dict , _lowerCamelCase : str ) -> None: def _delete(_lowerCamelCase : TrieNode , _lowerCamelCase : str , _lowerCamelCase : int ) -> bool: if index == len(_lowerCamelCase ): # If word does not exist if not curr.is_leaf: return False __magic_name__ = False return len(curr.nodes ) == 0 __magic_name__ = word[index] __magic_name__ = curr.nodes.get(_lowerCamelCase ) # If char not in current trie node if not char_node: return False # Flag to check if node can be deleted __magic_name__ = _delete(_lowerCamelCase , _lowerCamelCase , index + 1 ) if delete_curr: del curr.nodes[char] return len(curr.nodes ) == 0 return delete_curr _delete(self , _lowerCamelCase , 0 ) def __snake_case ( lowerCamelCase_ : TrieNode , lowerCamelCase_ : str ): '''simple docstring''' if node.is_leaf: print(lowerCamelCase_ , end=" " ) for key, value in node.nodes.items(): print_words(lowerCamelCase_ , word + key ) def __snake_case ( ): '''simple docstring''' __magic_name__ = "banana bananas bandana band apple all beast".split() __magic_name__ = TrieNode() root.insert_many(lowerCamelCase_ ) # print_words(root, "") assert all(root.find(lowerCamelCase_ ) for word in words ) assert root.find("banana" ) assert not root.find("bandanas" ) assert not root.find("apps" ) assert root.find("apple" ) assert root.find("all" ) root.delete("all" ) assert not root.find("all" ) root.delete("banana" ) assert not root.find("banana" ) assert root.find("bananas" ) return True def __snake_case ( lowerCamelCase_ : str , lowerCamelCase_ : bool ): '''simple docstring''' print(str(lowerCamelCase_ ) , "works!" if passes else "doesn't work :(" ) def __snake_case ( ): '''simple docstring''' assert test_trie() def __snake_case ( ): '''simple docstring''' print_results("Testing trie functionality" , test_trie() ) if __name__ == "__main__": main()
664
'''simple docstring''' from __future__ import annotations def __snake_case ( lowerCamelCase_ : list[int] , lowerCamelCase_ : int ): '''simple docstring''' if len(lowerCamelCase_ ) < k or k < 0: raise ValueError("Invalid Input" ) __magic_name__ = __magic_name__ = sum(array[:k] ) for i in range(len(lowerCamelCase_ ) - k ): __magic_name__ = current_sum - array[i] + array[i + k] __magic_name__ = max(lowerCamelCase_ , lowerCamelCase_ ) return max_sum if __name__ == "__main__": from doctest import testmod from random import randint testmod() __magic_name__ : List[str] =[randint(-10_00, 10_00) for i in range(1_00)] __magic_name__ : List[str] =randint(0, 1_10) print(F'''The maximum sum of {k} consecutive elements is {max_sum_in_array(array,k)}''')
664
1
'''simple docstring''' from functools import reduce __magic_name__ : int =( '73167176531330624919225119674426574742355349194934' '96983520312774506326239578318016984801869478851843' '85861560789112949495459501737958331952853208805511' '12540698747158523863050715693290963295227443043557' '66896648950445244523161731856403098711121722383113' '62229893423380308135336276614282806444486645238749' '30358907296290491560440772390713810515859307960866' '70172427121883998797908792274921901699720888093776' '65727333001053367881220235421809751254540594752243' '52584907711670556013604839586446706324415722155397' '53697817977846174064955149290862569321978468622482' '83972241375657056057490261407972968652414535100474' '82166370484403199890008895243450658541227588666881' '16427171479924442928230863465674813919123162824586' '17866458359124566529476545682848912883142607690042' '24219022671055626321111109370544217506941658960408' '07198403850962455444362981230987879927244284909188' '84580156166097919133875499200524063689912560717606' '05886116467109405077541002256983155200055935729725' '71636269561882670428252483600823257530420752963450' ) def __snake_case ( lowerCamelCase_ : str = N ): '''simple docstring''' return max( # mypy cannot properly interpret reduce int(reduce(lambda lowerCamelCase_ , lowerCamelCase_ : str(int(lowerCamelCase_ ) * int(lowerCamelCase_ ) ) , n[i : i + 13] ) ) for i in range(len(lowerCamelCase_ ) - 12 ) ) if __name__ == "__main__": print(F'''{solution() = }''')
664
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __magic_name__ : int =logging.get_logger(__name__) __magic_name__ : List[Any] ={} class UpperCamelCase_ ( A ): """simple docstring""" UpperCAmelCase__ : int = '''llama''' UpperCAmelCase__ : Any = ['''past_key_values'''] def __init__( self : List[Any] , _lowerCamelCase : List[Any]=3_20_00 , _lowerCamelCase : Optional[Any]=40_96 , _lowerCamelCase : Tuple=1_10_08 , _lowerCamelCase : List[Any]=32 , _lowerCamelCase : Tuple=32 , _lowerCamelCase : List[str]=None , _lowerCamelCase : str="silu" , _lowerCamelCase : Optional[Any]=20_48 , _lowerCamelCase : Optional[Any]=0.02 , _lowerCamelCase : Union[str, Any]=1e-6 , _lowerCamelCase : Optional[int]=True , _lowerCamelCase : Dict=0 , _lowerCamelCase : int=1 , _lowerCamelCase : str=2 , _lowerCamelCase : List[Any]=1 , _lowerCamelCase : Optional[int]=False , _lowerCamelCase : List[str]=None , **_lowerCamelCase : List[Any] , ) -> Any: __magic_name__ = vocab_size __magic_name__ = max_position_embeddings __magic_name__ = hidden_size __magic_name__ = intermediate_size __magic_name__ = num_hidden_layers __magic_name__ = num_attention_heads # for backward compatibility if num_key_value_heads is None: __magic_name__ = num_attention_heads __magic_name__ = num_key_value_heads __magic_name__ = hidden_act __magic_name__ = initializer_range __magic_name__ = rms_norm_eps __magic_name__ = pretraining_tp __magic_name__ = use_cache __magic_name__ = rope_scaling self._rope_scaling_validation() super().__init__( pad_token_id=_lowerCamelCase , bos_token_id=_lowerCamelCase , eos_token_id=_lowerCamelCase , tie_word_embeddings=_lowerCamelCase , **_lowerCamelCase , ) def __A ( self : Union[str, Any] ) -> List[Any]: if self.rope_scaling is None: return if not isinstance(self.rope_scaling , _lowerCamelCase ) or len(self.rope_scaling ) != 2: raise ValueError( "`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, " f'got {self.rope_scaling}' ) __magic_name__ = self.rope_scaling.get("type" , _lowerCamelCase ) __magic_name__ = self.rope_scaling.get("factor" , _lowerCamelCase ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( f'`rope_scaling`\'s name field must be one of [\'linear\', \'dynamic\'], got {rope_scaling_type}' ) if rope_scaling_factor is None or not isinstance(_lowerCamelCase , _lowerCamelCase ) or rope_scaling_factor <= 1.0: raise ValueError(f'`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}' )
664
1
'''simple docstring''' import logging import os from typing import List, TextIO, Union from conllu import parse_incr from utils_ner import InputExample, Split, TokenClassificationTask __magic_name__ : List[Any] =logging.getLogger(__name__) class UpperCamelCase_ ( A ): """simple docstring""" def __init__( self : Optional[Any] , _lowerCamelCase : str=-1 ) -> List[str]: # in NER datasets, the last column is usually reserved for NER label __magic_name__ = label_idx def __A ( self : Any , _lowerCamelCase : str , _lowerCamelCase : Union[Split, str] ) -> List[InputExample]: if isinstance(_lowerCamelCase , _lowerCamelCase ): __magic_name__ = mode.value __magic_name__ = os.path.join(_lowerCamelCase , f'{mode}.txt' ) __magic_name__ = 1 __magic_name__ = [] with open(_lowerCamelCase , encoding="utf-8" ) as f: __magic_name__ = [] __magic_name__ = [] for line in f: if line.startswith("-DOCSTART-" ) or line == "" or line == "\n": if words: examples.append(InputExample(guid=f'{mode}-{guid_index}' , words=_lowerCamelCase , labels=_lowerCamelCase ) ) guid_index += 1 __magic_name__ = [] __magic_name__ = [] else: __magic_name__ = line.split(" " ) words.append(splits[0] ) if len(_lowerCamelCase ) > 1: labels.append(splits[self.label_idx].replace("\n" , "" ) ) else: # Examples could have no label for mode = "test" labels.append("O" ) if words: examples.append(InputExample(guid=f'{mode}-{guid_index}' , words=_lowerCamelCase , labels=_lowerCamelCase ) ) return examples def __A ( self : Optional[Any] , _lowerCamelCase : TextIO , _lowerCamelCase : TextIO , _lowerCamelCase : List ) -> Union[str, Any]: __magic_name__ = 0 for line in test_input_reader: if line.startswith("-DOCSTART-" ) or line == "" or line == "\n": writer.write(_lowerCamelCase ) if not preds_list[example_id]: example_id += 1 elif preds_list[example_id]: __magic_name__ = line.split()[0] + " " + preds_list[example_id].pop(0 ) + "\n" writer.write(_lowerCamelCase ) else: logger.warning("Maximum sequence length exceeded: No prediction for '%s'." , line.split()[0] ) def __A ( self : Tuple , _lowerCamelCase : str ) -> List[str]: if path: with open(_lowerCamelCase , "r" ) as f: __magic_name__ = f.read().splitlines() if "O" not in labels: __magic_name__ = ["O"] + labels return labels else: return ["O", "B-MISC", "I-MISC", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC"] class UpperCamelCase_ ( A ): """simple docstring""" def __init__( self : int ) -> str: # in CONLL2003 dataset chunk column is second-to-last super().__init__(label_idx=-2 ) def __A ( self : int , _lowerCamelCase : str ) -> List[str]: if path: with open(_lowerCamelCase , "r" ) as f: __magic_name__ = f.read().splitlines() if "O" not in labels: __magic_name__ = ["O"] + labels return labels else: return [ "O", "B-ADVP", "B-INTJ", "B-LST", "B-PRT", "B-NP", "B-SBAR", "B-VP", "B-ADJP", "B-CONJP", "B-PP", "I-ADVP", "I-INTJ", "I-LST", "I-PRT", "I-NP", "I-SBAR", "I-VP", "I-ADJP", "I-CONJP", "I-PP", ] class UpperCamelCase_ ( A ): """simple docstring""" def __A ( self : List[Any] , _lowerCamelCase : Union[str, Any] , _lowerCamelCase : Union[Split, str] ) -> List[InputExample]: if isinstance(_lowerCamelCase , _lowerCamelCase ): __magic_name__ = mode.value __magic_name__ = os.path.join(_lowerCamelCase , f'{mode}.txt' ) __magic_name__ = 1 __magic_name__ = [] with open(_lowerCamelCase , encoding="utf-8" ) as f: for sentence in parse_incr(_lowerCamelCase ): __magic_name__ = [] __magic_name__ = [] for token in sentence: words.append(token["form"] ) labels.append(token["upos"] ) assert len(_lowerCamelCase ) == len(_lowerCamelCase ) if words: examples.append(InputExample(guid=f'{mode}-{guid_index}' , words=_lowerCamelCase , labels=_lowerCamelCase ) ) guid_index += 1 return examples def __A ( self : Optional[int] , _lowerCamelCase : TextIO , _lowerCamelCase : TextIO , _lowerCamelCase : List ) -> Any: __magic_name__ = 0 for sentence in parse_incr(_lowerCamelCase ): __magic_name__ = preds_list[example_id] __magic_name__ = "" for token in sentence: out += f'{token["form"]} ({token["upos"]}|{s_p.pop(0 )}) ' out += "\n" writer.write(_lowerCamelCase ) example_id += 1 def __A ( self : Dict , _lowerCamelCase : str ) -> List[str]: if path: with open(_lowerCamelCase , "r" ) as f: return f.read().splitlines() else: return [ "ADJ", "ADP", "ADV", "AUX", "CCONJ", "DET", "INTJ", "NOUN", "NUM", "PART", "PRON", "PROPN", "PUNCT", "SCONJ", "SYM", "VERB", "X", ]
664
'''simple docstring''' __magic_name__ : Dict =8.3_1_4_4_6_2 # Unit - J mol-1 K-1 def __snake_case ( lowerCamelCase_ : float , lowerCamelCase_ : float , lowerCamelCase_ : float ): '''simple docstring''' if moles < 0 or kelvin < 0 or volume < 0: raise ValueError("Invalid inputs. Enter positive value." ) return moles * kelvin * UNIVERSAL_GAS_CONSTANT / volume def __snake_case ( lowerCamelCase_ : float , lowerCamelCase_ : float , lowerCamelCase_ : float ): '''simple docstring''' if moles < 0 or kelvin < 0 or pressure < 0: raise ValueError("Invalid inputs. Enter positive value." ) return moles * kelvin * UNIVERSAL_GAS_CONSTANT / pressure if __name__ == "__main__": from doctest import testmod testmod()
664
1
'''simple docstring''' import gc import unittest import numpy as np import torch from diffusers import AutoencoderKL, DDIMScheduler, DiTPipeline, DPMSolverMultistepScheduler, TransformeraDModel from diffusers.utils import is_xformers_available, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS, CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class UpperCamelCase_ ( A , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Optional[int] = DiTPipeline UpperCAmelCase__ : Union[str, Any] = CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS UpperCAmelCase__ : str = PipelineTesterMixin.required_optional_params - { '''latents''', '''num_images_per_prompt''', '''callback''', '''callback_steps''', } UpperCAmelCase__ : List[Any] = CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS UpperCAmelCase__ : Tuple = False def __A ( self : Union[str, Any] ) -> Any: torch.manual_seed(0 ) __magic_name__ = TransformeraDModel( sample_size=16 , num_layers=2 , patch_size=4 , attention_head_dim=8 , num_attention_heads=2 , in_channels=4 , out_channels=8 , attention_bias=_lowerCamelCase , activation_fn="gelu-approximate" , num_embeds_ada_norm=10_00 , norm_type="ada_norm_zero" , norm_elementwise_affine=_lowerCamelCase , ) __magic_name__ = AutoencoderKL() __magic_name__ = DDIMScheduler() __magic_name__ = {"transformer": transformer.eval(), "vae": vae.eval(), "scheduler": scheduler} return components def __A ( self : Optional[int] , _lowerCamelCase : List[Any] , _lowerCamelCase : Dict=0 ) -> Dict: if str(_lowerCamelCase ).startswith("mps" ): __magic_name__ = torch.manual_seed(_lowerCamelCase ) else: __magic_name__ = torch.Generator(device=_lowerCamelCase ).manual_seed(_lowerCamelCase ) __magic_name__ = { "class_labels": [1], "generator": generator, "num_inference_steps": 2, "output_type": "numpy", } return inputs def __A ( self : int ) -> Dict: __magic_name__ = "cpu" __magic_name__ = self.get_dummy_components() __magic_name__ = self.pipeline_class(**_lowerCamelCase ) pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) __magic_name__ = self.get_dummy_inputs(_lowerCamelCase ) __magic_name__ = pipe(**_lowerCamelCase ).images __magic_name__ = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 16, 16, 3) ) __magic_name__ = np.array([0.2_946, 0.6_601, 0.4_329, 0.3_296, 0.4_144, 0.5_319, 0.7_273, 0.5_013, 0.4_457] ) __magic_name__ = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(_lowerCamelCase , 1e-3 ) def __A ( self : str ) -> List[Any]: self._test_inference_batch_single_identical(relax_max_difference=_lowerCamelCase , expected_max_diff=1e-3 ) @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def __A ( self : Optional[Any] ) -> List[Any]: self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3 ) @require_torch_gpu @slow class UpperCamelCase_ ( unittest.TestCase ): """simple docstring""" def __A ( self : Tuple ) -> List[Any]: super().tearDown() gc.collect() torch.cuda.empty_cache() def __A ( self : List[str] ) -> Optional[int]: __magic_name__ = torch.manual_seed(0 ) __magic_name__ = DiTPipeline.from_pretrained("facebook/DiT-XL-2-256" ) pipe.to("cuda" ) __magic_name__ = ["vase", "umbrella", "white shark", "white wolf"] __magic_name__ = pipe.get_label_ids(_lowerCamelCase ) __magic_name__ = pipe(_lowerCamelCase , generator=_lowerCamelCase , num_inference_steps=40 , output_type="np" ).images for word, image in zip(_lowerCamelCase , _lowerCamelCase ): __magic_name__ = load_numpy( f'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/dit/{word}.npy' ) assert np.abs((expected_image - image).max() ) < 1e-2 def __A ( self : Tuple ) -> Any: __magic_name__ = DiTPipeline.from_pretrained("facebook/DiT-XL-2-512" ) __magic_name__ = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.to("cuda" ) __magic_name__ = ["vase", "umbrella"] __magic_name__ = pipe.get_label_ids(_lowerCamelCase ) __magic_name__ = torch.manual_seed(0 ) __magic_name__ = pipe(_lowerCamelCase , generator=_lowerCamelCase , num_inference_steps=25 , output_type="np" ).images for word, image in zip(_lowerCamelCase , _lowerCamelCase ): __magic_name__ = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" f'/dit/{word}_512.npy' ) assert np.abs((expected_image - image).max() ) < 1e-1
664
'''simple docstring''' import logging import os from typing import List, TextIO, Union from conllu import parse_incr from utils_ner import InputExample, Split, TokenClassificationTask __magic_name__ : List[Any] =logging.getLogger(__name__) class UpperCamelCase_ ( A ): """simple docstring""" def __init__( self : Optional[Any] , _lowerCamelCase : str=-1 ) -> List[str]: # in NER datasets, the last column is usually reserved for NER label __magic_name__ = label_idx def __A ( self : Any , _lowerCamelCase : str , _lowerCamelCase : Union[Split, str] ) -> List[InputExample]: if isinstance(_lowerCamelCase , _lowerCamelCase ): __magic_name__ = mode.value __magic_name__ = os.path.join(_lowerCamelCase , f'{mode}.txt' ) __magic_name__ = 1 __magic_name__ = [] with open(_lowerCamelCase , encoding="utf-8" ) as f: __magic_name__ = [] __magic_name__ = [] for line in f: if line.startswith("-DOCSTART-" ) or line == "" or line == "\n": if words: examples.append(InputExample(guid=f'{mode}-{guid_index}' , words=_lowerCamelCase , labels=_lowerCamelCase ) ) guid_index += 1 __magic_name__ = [] __magic_name__ = [] else: __magic_name__ = line.split(" " ) words.append(splits[0] ) if len(_lowerCamelCase ) > 1: labels.append(splits[self.label_idx].replace("\n" , "" ) ) else: # Examples could have no label for mode = "test" labels.append("O" ) if words: examples.append(InputExample(guid=f'{mode}-{guid_index}' , words=_lowerCamelCase , labels=_lowerCamelCase ) ) return examples def __A ( self : Optional[Any] , _lowerCamelCase : TextIO , _lowerCamelCase : TextIO , _lowerCamelCase : List ) -> Union[str, Any]: __magic_name__ = 0 for line in test_input_reader: if line.startswith("-DOCSTART-" ) or line == "" or line == "\n": writer.write(_lowerCamelCase ) if not preds_list[example_id]: example_id += 1 elif preds_list[example_id]: __magic_name__ = line.split()[0] + " " + preds_list[example_id].pop(0 ) + "\n" writer.write(_lowerCamelCase ) else: logger.warning("Maximum sequence length exceeded: No prediction for '%s'." , line.split()[0] ) def __A ( self : Tuple , _lowerCamelCase : str ) -> List[str]: if path: with open(_lowerCamelCase , "r" ) as f: __magic_name__ = f.read().splitlines() if "O" not in labels: __magic_name__ = ["O"] + labels return labels else: return ["O", "B-MISC", "I-MISC", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC"] class UpperCamelCase_ ( A ): """simple docstring""" def __init__( self : int ) -> str: # in CONLL2003 dataset chunk column is second-to-last super().__init__(label_idx=-2 ) def __A ( self : int , _lowerCamelCase : str ) -> List[str]: if path: with open(_lowerCamelCase , "r" ) as f: __magic_name__ = f.read().splitlines() if "O" not in labels: __magic_name__ = ["O"] + labels return labels else: return [ "O", "B-ADVP", "B-INTJ", "B-LST", "B-PRT", "B-NP", "B-SBAR", "B-VP", "B-ADJP", "B-CONJP", "B-PP", "I-ADVP", "I-INTJ", "I-LST", "I-PRT", "I-NP", "I-SBAR", "I-VP", "I-ADJP", "I-CONJP", "I-PP", ] class UpperCamelCase_ ( A ): """simple docstring""" def __A ( self : List[Any] , _lowerCamelCase : Union[str, Any] , _lowerCamelCase : Union[Split, str] ) -> List[InputExample]: if isinstance(_lowerCamelCase , _lowerCamelCase ): __magic_name__ = mode.value __magic_name__ = os.path.join(_lowerCamelCase , f'{mode}.txt' ) __magic_name__ = 1 __magic_name__ = [] with open(_lowerCamelCase , encoding="utf-8" ) as f: for sentence in parse_incr(_lowerCamelCase ): __magic_name__ = [] __magic_name__ = [] for token in sentence: words.append(token["form"] ) labels.append(token["upos"] ) assert len(_lowerCamelCase ) == len(_lowerCamelCase ) if words: examples.append(InputExample(guid=f'{mode}-{guid_index}' , words=_lowerCamelCase , labels=_lowerCamelCase ) ) guid_index += 1 return examples def __A ( self : Optional[int] , _lowerCamelCase : TextIO , _lowerCamelCase : TextIO , _lowerCamelCase : List ) -> Any: __magic_name__ = 0 for sentence in parse_incr(_lowerCamelCase ): __magic_name__ = preds_list[example_id] __magic_name__ = "" for token in sentence: out += f'{token["form"]} ({token["upos"]}|{s_p.pop(0 )}) ' out += "\n" writer.write(_lowerCamelCase ) example_id += 1 def __A ( self : Dict , _lowerCamelCase : str ) -> List[str]: if path: with open(_lowerCamelCase , "r" ) as f: return f.read().splitlines() else: return [ "ADJ", "ADP", "ADV", "AUX", "CCONJ", "DET", "INTJ", "NOUN", "NUM", "PART", "PRON", "PROPN", "PUNCT", "SCONJ", "SYM", "VERB", "X", ]
664
1
'''simple docstring''' __magic_name__ : Optional[Any] ={ 'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.', 'G': '--.', 'H': '....', 'I': '..', 'J': '.---', 'K': '-.-', 'L': '.-..', 'M': '--', 'N': '-.', 'O': '---', 'P': '.--.', 'Q': '--.-', 'R': '.-.', 'S': '...', 'T': '-', 'U': '..-', 'V': '...-', 'W': '.--', 'X': '-..-', 'Y': '-.--', 'Z': '--..', '1': '.----', '2': '..---', '3': '...--', '4': '....-', '5': '.....', '6': '-....', '7': '--...', '8': '---..', '9': '----.', '0': '-----', '&': '.-...', '@': '.--.-.', ':': '---...', ',': '--..--', '.': '.-.-.-', '\'': '.----.', '"': '.-..-.', '?': '..--..', '/': '-..-.', '=': '-...-', '+': '.-.-.', '-': '-....-', '(': '-.--.', ')': '-.--.-', '!': '-.-.--', ' ': '/' } # Exclamation mark is not in ITU-R recommendation # fmt: on __magic_name__ : str ={value: key for key, value in MORSE_CODE_DICT.items()} def __snake_case ( lowerCamelCase_ : str ): '''simple docstring''' return " ".join(MORSE_CODE_DICT[char] for char in message.upper() ) def __snake_case ( lowerCamelCase_ : str ): '''simple docstring''' return "".join(REVERSE_DICT[char] for char in message.split() ) def __snake_case ( ): '''simple docstring''' __magic_name__ = "Morse code here!" print(lowerCamelCase_ ) __magic_name__ = encrypt(lowerCamelCase_ ) print(lowerCamelCase_ ) __magic_name__ = decrypt(lowerCamelCase_ ) print(lowerCamelCase_ ) if __name__ == "__main__": main()
664
'''simple docstring''' from __future__ import annotations from typing import Any class UpperCamelCase_ : """simple docstring""" def __init__( self : int , _lowerCamelCase : int , _lowerCamelCase : int , _lowerCamelCase : float = 0 ) -> None: __magic_name__ , __magic_name__ = row, column __magic_name__ = [[default_value for c in range(_lowerCamelCase )] for r in range(_lowerCamelCase )] def __str__( self : Optional[Any] ) -> str: __magic_name__ = f'Matrix consist of {self.row} rows and {self.column} columns\n' # Make string identifier __magic_name__ = 0 for row_vector in self.array: for obj in row_vector: __magic_name__ = max(_lowerCamelCase , len(str(_lowerCamelCase ) ) ) __magic_name__ = f'%{max_element_length}s' # Make string and return def single_line(_lowerCamelCase : list[float] ) -> str: nonlocal string_format_identifier __magic_name__ = "[" line += ", ".join(string_format_identifier % (obj,) for obj in row_vector ) line += "]" return line s += "\n".join(single_line(_lowerCamelCase ) for row_vector in self.array ) return s def __repr__( self : Optional[int] ) -> str: return str(self ) def __A ( self : Optional[Any] , _lowerCamelCase : tuple[int, int] ) -> bool: if not (isinstance(_lowerCamelCase , (list, tuple) ) and len(_lowerCamelCase ) == 2): return False elif not (0 <= loc[0] < self.row and 0 <= loc[1] < self.column): return False else: return True def __getitem__( self : Optional[int] , _lowerCamelCase : tuple[int, int] ) -> Any: assert self.validate_indicies(_lowerCamelCase ) return self.array[loc[0]][loc[1]] def __setitem__( self : Tuple , _lowerCamelCase : tuple[int, int] , _lowerCamelCase : float ) -> None: assert self.validate_indicies(_lowerCamelCase ) __magic_name__ = value def __add__( self : Union[str, Any] , _lowerCamelCase : Matrix ) -> Matrix: assert isinstance(_lowerCamelCase , _lowerCamelCase ) assert self.row == another.row and self.column == another.column # Add __magic_name__ = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): __magic_name__ = self[r, c] + another[r, c] return result def __neg__( self : int ) -> Matrix: __magic_name__ = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): __magic_name__ = -self[r, c] return result def __sub__( self : Optional[int] , _lowerCamelCase : Matrix ) -> Matrix: return self + (-another) def __mul__( self : Optional[int] , _lowerCamelCase : int | float | Matrix ) -> Matrix: if isinstance(_lowerCamelCase , (int, float) ): # Scalar multiplication __magic_name__ = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): __magic_name__ = self[r, c] * another return result elif isinstance(_lowerCamelCase , _lowerCamelCase ): # Matrix multiplication assert self.column == another.row __magic_name__ = Matrix(self.row , another.column ) for r in range(self.row ): for c in range(another.column ): for i in range(self.column ): result[r, c] += self[r, i] * another[i, c] return result else: __magic_name__ = f'Unsupported type given for another ({type(_lowerCamelCase )})' raise TypeError(_lowerCamelCase ) def __A ( self : Optional[int] ) -> Matrix: __magic_name__ = Matrix(self.column , self.row ) for r in range(self.row ): for c in range(self.column ): __magic_name__ = self[r, c] return result def __A ( self : int , _lowerCamelCase : Matrix , _lowerCamelCase : Matrix ) -> Any: assert isinstance(_lowerCamelCase , _lowerCamelCase ) and isinstance(_lowerCamelCase , _lowerCamelCase ) assert self.row == self.column == u.row == v.row # u, v should be column vector assert u.column == v.column == 1 # u, v should be column vector # Calculate __magic_name__ = v.transpose() __magic_name__ = (v_t * self * u)[0, 0] + 1 if numerator_factor == 0: return None # It's not invertable return self - ((self * u) * (v_t * self) * (1.0 / numerator_factor)) # Testing if __name__ == "__main__": def __snake_case ( ): '''simple docstring''' __magic_name__ = Matrix(3 , 3 , 0 ) for i in range(3 ): __magic_name__ = 1 print(F'a^(-1) is {ainv}' ) # u, v __magic_name__ = Matrix(3 , 1 , 0 ) __magic_name__ , __magic_name__ , __magic_name__ = 1, 2, -3 __magic_name__ = Matrix(3 , 1 , 0 ) __magic_name__ , __magic_name__ , __magic_name__ = 4, -2, 5 print(F'u is {u}' ) print(F'v is {v}' ) print(F'uv^T is {u * v.transpose()}' ) # Sherman Morrison print(F'(a + uv^T)^(-1) is {ainv.sherman_morrison(lowerCamelCase_ , lowerCamelCase_ )}' ) def __snake_case ( ): '''simple docstring''' import doctest doctest.testmod() testa()
664
1
'''simple docstring''' import gc import unittest import numpy as np import torch from diffusers import ( AudioDiffusionPipeline, AutoencoderKL, DDIMScheduler, DDPMScheduler, DiffusionPipeline, Mel, UNetaDConditionModel, UNetaDModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() class UpperCamelCase_ ( unittest.TestCase ): """simple docstring""" def __A ( self : str ) -> int: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() @property def __A ( self : str ) -> List[str]: torch.manual_seed(0 ) __magic_name__ = UNetaDModel( sample_size=(32, 64) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(1_28, 1_28) , down_block_types=("AttnDownBlock2D", "DownBlock2D") , up_block_types=("UpBlock2D", "AttnUpBlock2D") , ) return model @property def __A ( self : List[Any] ) -> Any: torch.manual_seed(0 ) __magic_name__ = UNetaDConditionModel( sample_size=(64, 32) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(1_28, 1_28) , down_block_types=("CrossAttnDownBlock2D", "DownBlock2D") , up_block_types=("UpBlock2D", "CrossAttnUpBlock2D") , cross_attention_dim=10 , ) return model @property def __A ( self : Optional[int] ) -> Union[str, Any]: torch.manual_seed(0 ) __magic_name__ = AutoencoderKL( sample_size=(1_28, 64) , in_channels=1 , out_channels=1 , latent_channels=1 , layers_per_block=2 , block_out_channels=(1_28, 1_28) , down_block_types=("DownEncoderBlock2D", "DownEncoderBlock2D") , up_block_types=("UpDecoderBlock2D", "UpDecoderBlock2D") , ) __magic_name__ = UNetaDModel( sample_size=(64, 32) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(1_28, 1_28) , down_block_types=("AttnDownBlock2D", "DownBlock2D") , up_block_types=("UpBlock2D", "AttnUpBlock2D") , ) return vqvae, unet @slow def __A ( self : str ) -> Union[str, Any]: __magic_name__ = "cpu" # ensure determinism for the device-dependent torch.Generator __magic_name__ = Mel( x_res=self.dummy_unet.config.sample_size[1] , y_res=self.dummy_unet.config.sample_size[0] , ) __magic_name__ = DDPMScheduler() __magic_name__ = AudioDiffusionPipeline(vqvae=_lowerCamelCase , unet=self.dummy_unet , mel=_lowerCamelCase , scheduler=_lowerCamelCase ) __magic_name__ = pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) __magic_name__ = torch.Generator(device=_lowerCamelCase ).manual_seed(42 ) __magic_name__ = pipe(generator=_lowerCamelCase , steps=4 ) __magic_name__ = output.audios[0] __magic_name__ = output.images[0] __magic_name__ = torch.Generator(device=_lowerCamelCase ).manual_seed(42 ) __magic_name__ = pipe(generator=_lowerCamelCase , steps=4 , return_dict=_lowerCamelCase ) __magic_name__ = output[0][0] assert audio.shape == (1, (self.dummy_unet.config.sample_size[1] - 1) * mel.hop_length) assert ( image.height == self.dummy_unet.config.sample_size[0] and image.width == self.dummy_unet.config.sample_size[1] ) __magic_name__ = np.frombuffer(image.tobytes() , dtype="uint8" )[:10] __magic_name__ = np.frombuffer(image_from_tuple.tobytes() , dtype="uint8" )[:10] __magic_name__ = np.array([69, 2_55, 2_55, 2_55, 0, 0, 77, 1_81, 12, 1_27] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() == 0 __magic_name__ = Mel( x_res=self.dummy_vqvae_and_unet[0].config.sample_size[1] , y_res=self.dummy_vqvae_and_unet[0].config.sample_size[0] , ) __magic_name__ = DDIMScheduler() __magic_name__ = self.dummy_vqvae_and_unet __magic_name__ = AudioDiffusionPipeline( vqvae=self.dummy_vqvae_and_unet[0] , unet=dummy_vqvae_and_unet[1] , mel=_lowerCamelCase , scheduler=_lowerCamelCase ) __magic_name__ = pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) np.random.seed(0 ) __magic_name__ = np.random.uniform(-1 , 1 , ((dummy_vqvae_and_unet[0].config.sample_size[1] - 1) * mel.hop_length,) ) __magic_name__ = torch.Generator(device=_lowerCamelCase ).manual_seed(42 ) __magic_name__ = pipe(raw_audio=_lowerCamelCase , generator=_lowerCamelCase , start_step=5 , steps=10 ) __magic_name__ = output.images[0] assert ( image.height == self.dummy_vqvae_and_unet[0].config.sample_size[0] and image.width == self.dummy_vqvae_and_unet[0].config.sample_size[1] ) __magic_name__ = np.frombuffer(image.tobytes() , dtype="uint8" )[:10] __magic_name__ = np.array([1_20, 1_17, 1_10, 1_09, 1_38, 1_67, 1_38, 1_48, 1_32, 1_21] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 __magic_name__ = self.dummy_unet_condition __magic_name__ = AudioDiffusionPipeline( vqvae=self.dummy_vqvae_and_unet[0] , unet=_lowerCamelCase , mel=_lowerCamelCase , scheduler=_lowerCamelCase ) __magic_name__ = pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) np.random.seed(0 ) __magic_name__ = torch.rand((1, 1, 10) ) __magic_name__ = pipe(generator=_lowerCamelCase , encoding=_lowerCamelCase ) __magic_name__ = output.images[0] __magic_name__ = np.frombuffer(image.tobytes() , dtype="uint8" )[:10] __magic_name__ = np.array([1_07, 1_03, 1_20, 1_27, 1_42, 1_22, 1_13, 1_22, 97, 1_11] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 @slow @require_torch_gpu class UpperCamelCase_ ( unittest.TestCase ): """simple docstring""" def __A ( self : Dict ) -> Optional[Any]: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __A ( self : Dict ) -> int: __magic_name__ = torch_device __magic_name__ = DiffusionPipeline.from_pretrained("teticio/audio-diffusion-ddim-256" ) __magic_name__ = pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) __magic_name__ = torch.Generator(device=_lowerCamelCase ).manual_seed(42 ) __magic_name__ = pipe(generator=_lowerCamelCase ) __magic_name__ = output.audios[0] __magic_name__ = output.images[0] assert audio.shape == (1, (pipe.unet.config.sample_size[1] - 1) * pipe.mel.hop_length) assert image.height == pipe.unet.config.sample_size[0] and image.width == pipe.unet.config.sample_size[1] __magic_name__ = np.frombuffer(image.tobytes() , dtype="uint8" )[:10] __magic_name__ = np.array([1_51, 1_67, 1_54, 1_44, 1_22, 1_34, 1_21, 1_05, 70, 26] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0
664
'''simple docstring''' import argparse import logging from collections import namedtuple import torch from model_bertabs import BertAbsSummarizer from models.model_builder import AbsSummarizer # The authors' implementation from transformers import BertTokenizer logging.basicConfig(level=logging.INFO) __magic_name__ : List[Any] =logging.getLogger(__name__) __magic_name__ : int ='Hello world! cécé herlolip' __magic_name__ : List[Any] =namedtuple( 'BertAbsConfig', [ 'temp_dir', 'large', 'use_bert_emb', 'finetune_bert', 'encoder', 'share_emb', 'max_pos', 'enc_layers', 'enc_hidden_size', 'enc_heads', 'enc_ff_size', 'enc_dropout', 'dec_layers', 'dec_hidden_size', 'dec_heads', 'dec_ff_size', 'dec_dropout', ], ) def __snake_case ( lowerCamelCase_ : Optional[int] , lowerCamelCase_ : Dict ): '''simple docstring''' __magic_name__ = BertAbsConfig( temp_dir="." , finetune_bert=lowerCamelCase_ , large=lowerCamelCase_ , share_emb=lowerCamelCase_ , use_bert_emb=lowerCamelCase_ , encoder="bert" , max_pos=512 , enc_layers=6 , enc_hidden_size=512 , enc_heads=8 , enc_ff_size=512 , enc_dropout=0.2 , dec_layers=6 , dec_hidden_size=768 , dec_heads=8 , dec_ff_size=2048 , dec_dropout=0.2 , ) __magic_name__ = torch.load(lowerCamelCase_ , lambda lowerCamelCase_ , lowerCamelCase_ : storage ) __magic_name__ = AbsSummarizer(lowerCamelCase_ , torch.device("cpu" ) , lowerCamelCase_ ) original.eval() __magic_name__ = BertAbsSummarizer(lowerCamelCase_ , torch.device("cpu" ) ) new_model.eval() # ------------------- # Convert the weights # ------------------- logging.info("convert the model" ) new_model.bert.load_state_dict(original.bert.state_dict() ) new_model.decoder.load_state_dict(original.decoder.state_dict() ) new_model.generator.load_state_dict(original.generator.state_dict() ) # ---------------------------------- # Make sure the outpus are identical # ---------------------------------- logging.info("Make sure that the models' outputs are identical" ) __magic_name__ = BertTokenizer.from_pretrained("bert-base-uncased" ) # prepare the model inputs __magic_name__ = tokenizer.encode("This is sample éàalj'-." ) encoder_input_ids.extend([tokenizer.pad_token_id] * (512 - len(lowerCamelCase_ )) ) __magic_name__ = torch.tensor(lowerCamelCase_ ).unsqueeze(0 ) __magic_name__ = tokenizer.encode("This is sample 3 éàalj'-." ) decoder_input_ids.extend([tokenizer.pad_token_id] * (512 - len(lowerCamelCase_ )) ) __magic_name__ = torch.tensor(lowerCamelCase_ ).unsqueeze(0 ) # failsafe to make sure the weights reset does not affect the # loaded weights. assert torch.max(torch.abs(original.generator[0].weight - new_model.generator[0].weight ) ) == 0 # forward pass __magic_name__ = encoder_input_ids __magic_name__ = decoder_input_ids __magic_name__ = __magic_name__ = None __magic_name__ = None __magic_name__ = __magic_name__ = None __magic_name__ = __magic_name__ = None __magic_name__ = None # The original model does not apply the geneator layer immediatly but rather in # the beam search (where it combines softmax + linear layer). Since we already # apply the softmax in our generation process we only apply the linear layer here. # We make sure that the outputs of the full stack are identical __magic_name__ = original(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )[0] __magic_name__ = original.generator(lowerCamelCase_ ) __magic_name__ = new_model( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )[0] __magic_name__ = new_model.generator(lowerCamelCase_ ) __magic_name__ = torch.max(torch.abs(output_converted_model - output_original_model ) ).item() print("Maximum absolute difference beween weights: {:.2f}".format(lowerCamelCase_ ) ) __magic_name__ = torch.max(torch.abs(output_converted_generator - output_original_generator ) ).item() print("Maximum absolute difference beween weights: {:.2f}".format(lowerCamelCase_ ) ) __magic_name__ = torch.allclose(lowerCamelCase_ , lowerCamelCase_ , atol=1e-3 ) if are_identical: logging.info("all weights are equal up to 1e-3" ) else: raise ValueError("the weights are different. The new model is likely different from the original one." ) # The model has been saved with torch.save(model) and this is bound to the exact # directory structure. We save the state_dict instead. logging.info("saving the model's state dictionary" ) torch.save( new_model.state_dict() , "./bertabs-finetuned-cnndm-extractive-abstractive-summarization/pytorch_model.bin" ) if __name__ == "__main__": __magic_name__ : Dict =argparse.ArgumentParser() parser.add_argument( '--bertabs_checkpoint_path', default=None, type=str, required=True, help='Path the official PyTorch dump.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.', ) __magic_name__ : Any =parser.parse_args() convert_bertabs_checkpoints( args.bertabs_checkpoint_path, args.pytorch_dump_folder_path, )
664
1
'''simple docstring''' import argparse import torch from ...utils import logging from . import AlbertConfig, AlbertForPreTraining, load_tf_weights_in_albert logging.set_verbosity_info() def __snake_case ( lowerCamelCase_ : int , lowerCamelCase_ : Union[str, Any] , lowerCamelCase_ : List[Any] ): '''simple docstring''' __magic_name__ = AlbertConfig.from_json_file(lowerCamelCase_ ) print(F'Building PyTorch model from configuration: {config}' ) __magic_name__ = AlbertForPreTraining(lowerCamelCase_ ) # Load weights from tf checkpoint load_tf_weights_in_albert(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) # Save pytorch-model print(F'Save PyTorch model to {pytorch_dump_path}' ) torch.save(model.state_dict() , lowerCamelCase_ ) if __name__ == "__main__": __magic_name__ : List[str] =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( '--albert_config_file', default=None, type=str, required=True, help=( 'The config json file corresponding to the pre-trained ALBERT 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.' ) __magic_name__ : Union[str, Any] =parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.albert_config_file, args.pytorch_dump_path)
664
'''simple docstring''' import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.generation import DisjunctiveConstraint @require_torch class UpperCamelCase_ ( unittest.TestCase ): """simple docstring""" def __A ( self : List[str] ) -> str: # For consistency across different places the DisjunctiveConstraint is called, # dc.token_ids is a list of integers. It is also initialized only by integers. __magic_name__ = [[1, 2, 4], [1, 2, 3, 4]] __magic_name__ = DisjunctiveConstraint(_lowerCamelCase ) self.assertTrue(isinstance(dc.token_ids , _lowerCamelCase ) ) with self.assertRaises(_lowerCamelCase ): DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]] ) ) with self.assertRaises(_lowerCamelCase ): DisjunctiveConstraint([torch.LongTensor([1, 2, 4] ), torch.LongTensor([1, 2, 3, 4, 5] )] ) def __A ( self : List[Any] ) -> str: # We can't have constraints that are complete subsets of another. This leads to a preverse # interpretation of "constraint fulfillment": does generating [1,2,3] fulfill the constraint? # It would mean that it generated [1,2] which fulfills it, but it's in the middle of potentially # fulfilling [1,2,3,4]. If we believe that [1,2,3] does fulfill the constraint, then the algorithm # will necessarily never reach [1,2,3,4], giving users a false sense of control (better to just not allow it). __magic_name__ = [[1, 2], [1, 2, 3, 4]] with self.assertRaises(_lowerCamelCase ): DisjunctiveConstraint(_lowerCamelCase ) # fails here def __A ( self : List[Any] ) -> int: __magic_name__ = [[1, 2, 3], [1, 2, 4]] __magic_name__ = DisjunctiveConstraint(_lowerCamelCase ) __magic_name__ , __magic_name__ , __magic_name__ = dc.update(1 ) __magic_name__ = stepped is True and completed is False and reset is False self.assertTrue(_lowerCamelCase ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) __magic_name__ , __magic_name__ , __magic_name__ = dc.update(2 ) __magic_name__ = stepped is True and completed is False and reset is False self.assertTrue(_lowerCamelCase ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) __magic_name__ , __magic_name__ , __magic_name__ = dc.update(3 ) __magic_name__ = stepped is True and completed is True and reset is False self.assertTrue(_lowerCamelCase ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 3] ) def __A ( self : Any ) -> Union[str, Any]: __magic_name__ = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]] __magic_name__ = DisjunctiveConstraint(_lowerCamelCase ) __magic_name__ , __magic_name__ , __magic_name__ = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) __magic_name__ , __magic_name__ , __magic_name__ = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) __magic_name__ , __magic_name__ , __magic_name__ = dc.update(4 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2, 4] ) __magic_name__ , __magic_name__ , __magic_name__ = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 4, 5] ) dc.reset() __magic_name__ , __magic_name__ , __magic_name__ = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 3 ) self.assertTrue(dc.current_seq == [1] ) __magic_name__ , __magic_name__ , __magic_name__ = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 2 ) self.assertTrue(dc.current_seq == [1, 2] ) __magic_name__ , __magic_name__ , __magic_name__ = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.remaining() == 0 ) self.assertTrue(dc.current_seq == [1, 2, 5] )
664
1
'''simple docstring''' 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 __magic_name__ : Tuple ='' if version.parse(importlib_metadata.version('jiwer')) < version.parse('2.3.0'): class UpperCamelCase_ ( tr.AbstractTransform ): """simple docstring""" def __init__( self : List[Any] , _lowerCamelCase : str = " " ) -> List[str]: __magic_name__ = sentence_delimiter def __A ( self : Optional[Any] , _lowerCamelCase : str ) -> Union[str, Any]: return list(_lowerCamelCase ) def __A ( self : str , _lowerCamelCase : List[str] ) -> Optional[Any]: __magic_name__ = [] for sent_idx, sentence in enumerate(_lowerCamelCase ): chars.extend(self.process_string(_lowerCamelCase ) ) if self.sentence_delimiter is not None and self.sentence_delimiter != "" and sent_idx < len(_lowerCamelCase ) - 1: chars.append(self.sentence_delimiter ) return chars __magic_name__ : Optional[Any] =tr.Compose( [tr.RemoveMultipleSpaces(), tr.Strip(), SentencesToListOfCharacters(SENTENCE_DELIMITER)] ) else: __magic_name__ : Tuple =tr.Compose( [ tr.RemoveMultipleSpaces(), tr.Strip(), tr.ReduceToSingleSentence(SENTENCE_DELIMITER), tr.ReduceToListOfListOfChars(), ] ) __magic_name__ : List[Any] ='\\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' __magic_name__ : Tuple ='\\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' __magic_name__ : int ='\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 UpperCamelCase_ ( datasets.Metric ): """simple docstring""" def __A ( self : List[str] ) -> Optional[Any]: 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 : Dict , _lowerCamelCase : List[Any] , _lowerCamelCase : Union[str, Any] , _lowerCamelCase : Dict=False ) -> Dict: if concatenate_texts: return jiwer.compute_measures( _lowerCamelCase , _lowerCamelCase , truth_transform=_lowerCamelCase , hypothesis_transform=_lowerCamelCase , )["wer"] __magic_name__ = 0 __magic_name__ = 0 for prediction, reference in zip(_lowerCamelCase , _lowerCamelCase ): __magic_name__ = jiwer.compute_measures( _lowerCamelCase , _lowerCamelCase , truth_transform=_lowerCamelCase , hypothesis_transform=_lowerCamelCase , ) incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"] total += measures["substitutions"] + measures["deletions"] + measures["hits"] return incorrect / total
664
'''simple docstring''' import json import os import shutil import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import AutoConfig, BertConfig, GPTaConfig from transformers.configuration_utils import PretrainedConfig from transformers.testing_utils import TOKEN, USER, is_staging_test sys.path.append(str(Path(__file__).parent.parent / 'utils')) from test_module.custom_configuration import CustomConfig # noqa E402 __magic_name__ : Dict ={ 'return_dict': False, 'output_hidden_states': True, 'output_attentions': True, 'torchscript': True, 'torch_dtype': 'float16', 'use_bfloat16': True, 'tf_legacy_loss': True, 'pruned_heads': {'a': 1}, 'tie_word_embeddings': False, 'is_decoder': True, 'cross_attention_hidden_size': 1_28, 'add_cross_attention': True, 'tie_encoder_decoder': True, 'max_length': 50, 'min_length': 3, 'do_sample': True, 'early_stopping': True, 'num_beams': 3, 'num_beam_groups': 3, 'diversity_penalty': 0.5, 'temperature': 2.0, 'top_k': 10, 'top_p': 0.7, 'typical_p': 0.2, 'repetition_penalty': 0.8, 'length_penalty': 0.8, 'no_repeat_ngram_size': 5, 'encoder_no_repeat_ngram_size': 5, 'bad_words_ids': [1, 2, 3], 'num_return_sequences': 3, 'chunk_size_feed_forward': 5, 'output_scores': True, 'return_dict_in_generate': True, 'forced_bos_token_id': 2, 'forced_eos_token_id': 3, 'remove_invalid_values': True, 'architectures': ['BertModel'], 'finetuning_task': 'translation', 'id2label': {0: 'label'}, 'label2id': {'label': '0'}, 'tokenizer_class': 'BertTokenizerFast', 'prefix': 'prefix', 'bos_token_id': 6, 'pad_token_id': 7, 'eos_token_id': 8, 'sep_token_id': 9, 'decoder_start_token_id': 10, 'exponential_decay_length_penalty': (5, 1.0_1), 'suppress_tokens': [0, 1], 'begin_suppress_tokens': 2, 'task_specific_params': {'translation': 'some_params'}, 'problem_type': 'regression', } @is_staging_test class UpperCamelCase_ ( unittest.TestCase ): """simple docstring""" @classmethod def __A ( cls : Any ) -> Union[str, Any]: __magic_name__ = TOKEN HfFolder.save_token(_lowerCamelCase ) @classmethod def __A ( cls : Any ) -> Tuple: try: delete_repo(token=cls._token , repo_id="test-config" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="valid_org/test-config-org" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="test-dynamic-config" ) except HTTPError: pass def __A ( self : Optional[Any] ) -> Dict: __magic_name__ = BertConfig( vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 ) config.push_to_hub("test-config" , use_auth_token=self._token ) __magic_name__ = BertConfig.from_pretrained(f'{USER}/test-config' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(_lowerCamelCase , getattr(_lowerCamelCase , _lowerCamelCase ) ) # Reset repo delete_repo(token=self._token , repo_id="test-config" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(_lowerCamelCase , repo_id="test-config" , push_to_hub=_lowerCamelCase , use_auth_token=self._token ) __magic_name__ = BertConfig.from_pretrained(f'{USER}/test-config' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(_lowerCamelCase , getattr(_lowerCamelCase , _lowerCamelCase ) ) def __A ( self : str ) -> Optional[int]: __magic_name__ = BertConfig( vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 ) config.push_to_hub("valid_org/test-config-org" , use_auth_token=self._token ) __magic_name__ = BertConfig.from_pretrained("valid_org/test-config-org" ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(_lowerCamelCase , getattr(_lowerCamelCase , _lowerCamelCase ) ) # Reset repo delete_repo(token=self._token , repo_id="valid_org/test-config-org" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( _lowerCamelCase , repo_id="valid_org/test-config-org" , push_to_hub=_lowerCamelCase , use_auth_token=self._token ) __magic_name__ = BertConfig.from_pretrained("valid_org/test-config-org" ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(_lowerCamelCase , getattr(_lowerCamelCase , _lowerCamelCase ) ) def __A ( self : Optional[int] ) -> Union[str, Any]: CustomConfig.register_for_auto_class() __magic_name__ = CustomConfig(attribute=42 ) config.push_to_hub("test-dynamic-config" , use_auth_token=self._token ) # This has added the proper auto_map field to the config self.assertDictEqual(config.auto_map , {"AutoConfig": "custom_configuration.CustomConfig"} ) __magic_name__ = AutoConfig.from_pretrained(f'{USER}/test-dynamic-config' , trust_remote_code=_lowerCamelCase ) # Can't make an isinstance check because the new_config is from the FakeConfig class of a dynamic module self.assertEqual(new_config.__class__.__name__ , "CustomConfig" ) self.assertEqual(new_config.attribute , 42 ) class UpperCamelCase_ ( unittest.TestCase ): """simple docstring""" def __A ( self : Optional[int] ) -> Optional[Any]: __magic_name__ = GPTaConfig() # attempt to modify each of int/float/bool/str config records and verify they were updated __magic_name__ = c.n_embd + 1 # int __magic_name__ = c.resid_pdrop + 1.0 # float __magic_name__ = not c.scale_attn_weights # bool __magic_name__ = c.summary_type + "foo" # str c.update_from_string( f'n_embd={n_embd},resid_pdrop={resid_pdrop},scale_attn_weights={scale_attn_weights},summary_type={summary_type}' ) self.assertEqual(_lowerCamelCase , c.n_embd , "mismatch for key: n_embd" ) self.assertEqual(_lowerCamelCase , c.resid_pdrop , "mismatch for key: resid_pdrop" ) self.assertEqual(_lowerCamelCase , c.scale_attn_weights , "mismatch for key: scale_attn_weights" ) self.assertEqual(_lowerCamelCase , c.summary_type , "mismatch for key: summary_type" ) def __A ( self : List[Any] ) -> Union[str, Any]: __magic_name__ = PretrainedConfig() __magic_name__ = [key for key in base_config.__dict__ if key not in config_common_kwargs] # If this part of the test fails, you have arguments to addin config_common_kwargs above. self.assertListEqual( _lowerCamelCase , ["is_encoder_decoder", "_name_or_path", "_commit_hash", "transformers_version"] ) __magic_name__ = [key for key, value in config_common_kwargs.items() if value == getattr(_lowerCamelCase , _lowerCamelCase )] if len(_lowerCamelCase ) > 0: raise ValueError( "The following keys are set with the default values in" " `test_configuration_common.config_common_kwargs` pick another value for them:" f' {", ".join(_lowerCamelCase )}.' ) def __A ( self : List[Any] ) -> List[Any]: with self.assertRaises(_lowerCamelCase ): # config is in subfolder, the following should not work without specifying the subfolder __magic_name__ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert-subfolder" ) __magic_name__ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert-subfolder" , subfolder="bert" ) self.assertIsNotNone(_lowerCamelCase ) def __A ( self : Tuple ) -> int: # A mock response for an HTTP head request to emulate server down __magic_name__ = mock.Mock() __magic_name__ = 5_00 __magic_name__ = {} __magic_name__ = HTTPError __magic_name__ = {} # Download this model to make sure it's in the cache. __magic_name__ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert" ) # Under the mock environment we get a 500 error when trying to reach the model. with mock.patch("requests.Session.request" , return_value=_lowerCamelCase ) as mock_head: __magic_name__ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert" ) # This check we did call the fake head request mock_head.assert_called() def __A ( self : Union[str, Any] ) -> Dict: # This test is for deprecated behavior and can be removed in v5 __magic_name__ = BertConfig.from_pretrained( "https://huggingface.co/hf-internal-testing/tiny-random-bert/resolve/main/config.json" ) def __A ( self : Dict ) -> Optional[int]: __magic_name__ = AutoConfig.from_pretrained("bert-base-cased" ) __magic_name__ = ["config.4.0.0.json"] with tempfile.TemporaryDirectory() as tmp_dir: configuration.save_pretrained(_lowerCamelCase ) __magic_name__ = 2 json.dump(configuration.to_dict() , open(os.path.join(_lowerCamelCase , "config.4.0.0.json" ) , "w" ) ) # This should pick the new configuration file as the version of Transformers is > 4.0.0 __magic_name__ = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertEqual(new_configuration.hidden_size , 2 ) # Will need to be adjusted if we reach v42 and this test is still here. # Should pick the old configuration file as the version of Transformers is < 4.42.0 __magic_name__ = ["config.42.0.0.json"] __magic_name__ = 7_68 configuration.save_pretrained(_lowerCamelCase ) shutil.move(os.path.join(_lowerCamelCase , "config.4.0.0.json" ) , os.path.join(_lowerCamelCase , "config.42.0.0.json" ) ) __magic_name__ = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertEqual(new_configuration.hidden_size , 7_68 ) def __A ( self : Optional[int] ) -> str: # This repo has two configuration files, one for v4.0.0 and above with a different hidden size. __magic_name__ = "hf-internal-testing/test-two-configs" import transformers as new_transformers __magic_name__ = "v4.0.0" __magic_name__ , __magic_name__ = new_transformers.models.auto.AutoConfig.from_pretrained( _lowerCamelCase , return_unused_kwargs=_lowerCamelCase ) self.assertEqual(new_configuration.hidden_size , 2 ) # This checks `_configuration_file` ia not kept in the kwargs by mistake. self.assertDictEqual(_lowerCamelCase , {} ) # Testing an older version by monkey-patching the version in the module it's used. import transformers as old_transformers __magic_name__ = "v3.0.0" __magic_name__ = old_transformers.models.auto.AutoConfig.from_pretrained(_lowerCamelCase ) self.assertEqual(old_configuration.hidden_size , 7_68 )
664
1
'''simple docstring''' import datasets from .nmt_bleu import compute_bleu # From: https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py __magic_name__ : int ='\\n@INPROCEEDINGS{Papineni02bleu:a,\n author = {Kishore Papineni and Salim Roukos and Todd Ward and Wei-jing Zhu},\n title = {BLEU: a Method for Automatic Evaluation of Machine Translation},\n booktitle = {},\n year = {2002},\n pages = {311--318}\n}\n@inproceedings{lin-och-2004-orange,\n title = "{ORANGE}: a Method for Evaluating Automatic Evaluation Metrics for Machine Translation",\n author = "Lin, Chin-Yew and\n Och, Franz Josef",\n booktitle = "{COLING} 2004: Proceedings of the 20th International Conference on Computational Linguistics",\n month = "aug 23{--}aug 27",\n year = "2004",\n address = "Geneva, Switzerland",\n publisher = "COLING",\n url = "https://www.aclweb.org/anthology/C04-1072",\n pages = "501--507",\n}\n' __magic_name__ : Union[str, Any] ='\\nBLEU (bilingual evaluation understudy) is an algorithm for evaluating the quality of text which has been machine-translated from one natural language to another.\nQuality is considered to be the correspondence between a machine\'s output and that of a human: "the closer a machine translation is to a professional human translation,\nthe better it is" – this is the central idea behind BLEU. BLEU was one of the first metrics to claim a high correlation with human judgements of quality, and\nremains one of the most popular automated and inexpensive metrics.\n\nScores are calculated for individual translated segments—generally sentences—by comparing them with a set of good quality reference translations.\nThose scores are then averaged over the whole corpus to reach an estimate of the translation\'s overall quality. Intelligibility or grammatical correctness\nare not taken into account[citation needed].\n\nBLEU\'s output is always a number between 0 and 1. This value indicates how similar the candidate text is to the reference texts, with values closer to 1\nrepresenting more similar texts. Few human translations will attain a score of 1, since this would indicate that the candidate is identical to one of the\nreference translations. For this reason, it is not necessary to attain a score of 1. Because there are more opportunities to match, adding additional\nreference translations will increase the BLEU score.\n' __magic_name__ : Optional[Any] ='\nComputes BLEU score of translated segments against one or more references.\nArgs:\n predictions: list of translations to score.\n Each translation should be tokenized into a list of tokens.\n references: list of lists of references for each translation.\n Each reference should be tokenized into a list of tokens.\n max_order: Maximum n-gram order to use when computing BLEU score.\n smooth: Whether or not to apply Lin et al. 2004 smoothing.\nReturns:\n \'bleu\': bleu score,\n \'precisions\': geometric mean of n-gram precisions,\n \'brevity_penalty\': brevity penalty,\n \'length_ratio\': ratio of lengths,\n \'translation_length\': translation_length,\n \'reference_length\': reference_length\nExamples:\n\n >>> predictions = [\n ... ["hello", "there", "general", "kenobi"], # tokenized prediction of the first sample\n ... ["foo", "bar", "foobar"] # tokenized prediction of the second sample\n ... ]\n >>> references = [\n ... [["hello", "there", "general", "kenobi"], ["hello", "there", "!"]], # tokenized references for the first sample (2 references)\n ... [["foo", "bar", "foobar"]] # tokenized references for the second sample (1 reference)\n ... ]\n >>> bleu = datasets.load_metric("bleu")\n >>> results = bleu.compute(predictions=predictions, references=references)\n >>> print(results["bleu"])\n 1.0\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCamelCase_ ( datasets.Metric ): """simple docstring""" def __A ( self : Optional[int] ) -> Optional[Any]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Sequence(datasets.Value("string" , id="token" ) , id="sequence" ), "references": datasets.Sequence( datasets.Sequence(datasets.Value("string" , id="token" ) , id="sequence" ) , id="references" ), } ) , codebase_urls=["https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py"] , reference_urls=[ "https://en.wikipedia.org/wiki/BLEU", "https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213", ] , ) def __A ( self : List[str] , _lowerCamelCase : List[Any] , _lowerCamelCase : Dict , _lowerCamelCase : List[Any]=4 , _lowerCamelCase : Tuple=False ) -> Dict: __magic_name__ = compute_bleu( reference_corpus=_lowerCamelCase , translation_corpus=_lowerCamelCase , max_order=_lowerCamelCase , smooth=_lowerCamelCase ) ((__magic_name__) , (__magic_name__) , (__magic_name__) , (__magic_name__) , (__magic_name__) , (__magic_name__)) = score return { "bleu": bleu, "precisions": precisions, "brevity_penalty": bp, "length_ratio": ratio, "translation_length": translation_length, "reference_length": reference_length, }
664
'''simple docstring''' import unittest import numpy as np from transformers.file_utils import is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_vision from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import DPTImageProcessor class UpperCamelCase_ ( unittest.TestCase ): """simple docstring""" def __init__( self : str , _lowerCamelCase : str , _lowerCamelCase : Optional[Any]=7 , _lowerCamelCase : Optional[int]=3 , _lowerCamelCase : List[Any]=18 , _lowerCamelCase : Union[str, Any]=30 , _lowerCamelCase : Tuple=4_00 , _lowerCamelCase : Union[str, Any]=True , _lowerCamelCase : Optional[Any]=None , _lowerCamelCase : int=True , _lowerCamelCase : Dict=[0.5, 0.5, 0.5] , _lowerCamelCase : Dict=[0.5, 0.5, 0.5] , ) -> Dict: __magic_name__ = size if size is not None else {"height": 18, "width": 18} __magic_name__ = parent __magic_name__ = batch_size __magic_name__ = num_channels __magic_name__ = image_size __magic_name__ = min_resolution __magic_name__ = max_resolution __magic_name__ = do_resize __magic_name__ = size __magic_name__ = do_normalize __magic_name__ = image_mean __magic_name__ = image_std def __A ( self : int ) -> List[str]: return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, } @require_torch @require_vision class UpperCamelCase_ ( A , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Union[str, Any] = DPTImageProcessor if is_vision_available() else None def __A ( self : Dict ) -> Any: __magic_name__ = DPTImageProcessingTester(self ) @property def __A ( self : str ) -> str: return self.image_processor_tester.prepare_image_processor_dict() def __A ( self : Tuple ) -> List[str]: __magic_name__ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCamelCase , "image_mean" ) ) self.assertTrue(hasattr(_lowerCamelCase , "image_std" ) ) self.assertTrue(hasattr(_lowerCamelCase , "do_normalize" ) ) self.assertTrue(hasattr(_lowerCamelCase , "do_resize" ) ) self.assertTrue(hasattr(_lowerCamelCase , "size" ) ) def __A ( self : List[str] ) -> List[Any]: __magic_name__ = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"height": 18, "width": 18} ) __magic_name__ = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {"height": 42, "width": 42} ) def __A ( self : Union[str, Any] ) -> List[str]: # Initialize image_processing __magic_name__ = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __magic_name__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , Image.Image ) # Test not batched input __magic_name__ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) # Test batched __magic_name__ = image_processing(_lowerCamelCase , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) def __A ( self : Dict ) -> Optional[Any]: # Initialize image_processing __magic_name__ = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __magic_name__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , numpify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , np.ndarray ) # Test not batched input __magic_name__ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) # Test batched __magic_name__ = image_processing(_lowerCamelCase , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) def __A ( self : Optional[int] ) -> Dict: # Initialize image_processing __magic_name__ = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __magic_name__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , torch.Tensor ) # Test not batched input __magic_name__ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) # Test batched __magic_name__ = image_processing(_lowerCamelCase , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , )
664
1
'''simple docstring''' import logging import os import sys import warnings from dataclasses import dataclass, field from random import randint from typing import Optional import datasets import evaluate import numpy as np from datasets import DatasetDict, load_dataset import transformers from transformers import ( AutoConfig, AutoFeatureExtractor, AutoModelForAudioClassification, HfArgumentParser, Trainer, TrainingArguments, 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 __magic_name__ : List[Any] =logging.getLogger(__name__) # 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.14.0', 'To fix: pip install -r examples/pytorch/audio-classification/requirements.txt') def __snake_case ( lowerCamelCase_ : np.ndarray , lowerCamelCase_ : float , lowerCamelCase_ : int = 1_6000 ): '''simple docstring''' __magic_name__ = int(round(sample_rate * max_length ) ) if len(lowerCamelCase_ ) <= sample_length: return wav __magic_name__ = randint(0 , len(lowerCamelCase_ ) - sample_length - 1 ) return wav[random_offset : random_offset + sample_length] @dataclass class UpperCamelCase_ : """simple docstring""" UpperCAmelCase__ : Optional[str] = field(default=A , metadata={'''help''': '''Name of a dataset from the datasets package'''} ) UpperCAmelCase__ : Optional[str] = field( default=A , metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''} ) UpperCAmelCase__ : Optional[str] = field( default=A , metadata={'''help''': '''A file containing the training audio paths and labels.'''} ) UpperCAmelCase__ : Optional[str] = field( default=A , metadata={'''help''': '''A file containing the validation audio paths and labels.'''} ) UpperCAmelCase__ : str = field( default='''train''' , metadata={ '''help''': '''The name of the training data set split to use (via the datasets library). Defaults to \'train\'''' } , ) UpperCAmelCase__ : str = field( default='''validation''' , metadata={ '''help''': ( '''The name of the training data set split to use (via the datasets library). Defaults to \'validation\'''' ) } , ) UpperCAmelCase__ : str = field( default='''audio''' , metadata={'''help''': '''The name of the dataset column containing the audio data. Defaults to \'audio\''''} , ) UpperCAmelCase__ : str = field( default='''label''' , metadata={'''help''': '''The name of the dataset column containing the labels. Defaults to \'label\''''} ) UpperCAmelCase__ : Optional[int] = field( default=A , metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of training examples to this ''' '''value if set.''' ) } , ) UpperCAmelCase__ : Optional[int] = field( default=A , metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of evaluation examples to this ''' '''value if set.''' ) } , ) UpperCAmelCase__ : float = field( default=20 , metadata={'''help''': '''Audio clips will be randomly cut to this length during training if the value is set.'''} , ) @dataclass class UpperCamelCase_ : """simple docstring""" UpperCAmelCase__ : str = field( default='''facebook/wav2vec2-base''' , metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''} , ) UpperCAmelCase__ : Optional[str] = field( default=A , metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''} ) UpperCAmelCase__ : Optional[str] = field( default=A , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from the Hub'''} ) UpperCAmelCase__ : str = field( default='''main''' , metadata={'''help''': '''The specific model version to use (can be a branch name, tag name or commit id).'''} , ) UpperCAmelCase__ : Optional[str] = field( default=A , metadata={'''help''': '''Name or path of preprocessor config.'''} ) UpperCAmelCase__ : bool = field( default=A , metadata={'''help''': '''Whether to freeze the feature encoder layers of the model.'''} ) UpperCAmelCase__ : bool = field( default=A , metadata={'''help''': '''Whether to generate an attention mask in the feature extractor.'''} ) UpperCAmelCase__ : bool = field( default=A , metadata={ '''help''': ( '''Will use the token generated when running `huggingface-cli login` (necessary to use this script ''' '''with private models).''' ) } , ) UpperCAmelCase__ : Optional[bool] = field( default=A , metadata={'''help''': '''Whether to freeze the feature extractor layers of the model.'''} ) UpperCAmelCase__ : bool = field( default=A , metadata={'''help''': '''Will enable to load a pretrained model whose head dimensions are different.'''} , ) def __A ( self : Optional[int] ) -> Optional[int]: if not self.freeze_feature_extractor and self.freeze_feature_encoder: warnings.warn( "The argument `--freeze_feature_extractor` is deprecated and " "will be removed in a future version. Use `--freeze_feature_encoder`" "instead. Setting `freeze_feature_encoder==True`." , _lowerCamelCase , ) if self.freeze_feature_extractor and not self.freeze_feature_encoder: raise ValueError( "The argument `--freeze_feature_extractor` is deprecated and " "should not be used in combination with `--freeze_feature_encoder`." "Only make use of `--freeze_feature_encoder`." ) def __snake_case ( ): '''simple docstring''' __magic_name__ = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(".json" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. __magic_name__ , __magic_name__ , __magic_name__ = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: __magic_name__ , __magic_name__ , __magic_name__ = 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_audio_classification" , lowerCamelCase_ , lowerCamelCase_ ) # 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() __magic_name__ = training_args.get_process_log_level() logger.setLevel(lowerCamelCase_ ) transformers.utils.logging.set_verbosity(lowerCamelCase_ ) 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}' ) # Set seed before initializing model. set_seed(training_args.seed ) # Detecting last checkpoint. __magic_name__ = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: __magic_name__ = 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 train from scratch." ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is 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." ) # Initialize our dataset and prepare it for the audio classification task. __magic_name__ = DatasetDict() __magic_name__ = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=data_args.train_split_name , use_auth_token=True if model_args.use_auth_token else None , ) __magic_name__ = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=data_args.eval_split_name , use_auth_token=True if model_args.use_auth_token else None , ) if data_args.audio_column_name not in raw_datasets["train"].column_names: raise ValueError( F'--audio_column_name {data_args.audio_column_name} not found in dataset \'{data_args.dataset_name}\'. ' "Make sure to set `--audio_column_name` to the correct audio column - one of " F'{", ".join(raw_datasets["train"].column_names )}.' ) if data_args.label_column_name not in raw_datasets["train"].column_names: raise ValueError( F'--label_column_name {data_args.label_column_name} not found in dataset \'{data_args.dataset_name}\'. ' "Make sure to set `--label_column_name` to the correct text column - one of " F'{", ".join(raw_datasets["train"].column_names )}.' ) # Setting `return_attention_mask=True` is the way to get a correctly masked mean-pooling over # transformer outputs in the classifier, but it doesn't always lead to better accuracy __magic_name__ = AutoFeatureExtractor.from_pretrained( model_args.feature_extractor_name or model_args.model_name_or_path , return_attention_mask=model_args.attention_mask , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) # `datasets` takes care of automatically loading and resampling the audio, # so we just need to set the correct target sampling rate. __magic_name__ = raw_datasets.cast_column( data_args.audio_column_name , datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate ) ) __magic_name__ = feature_extractor.model_input_names[0] def train_transforms(lowerCamelCase_ : List[Any] ): __magic_name__ = [] for audio in batch[data_args.audio_column_name]: __magic_name__ = random_subsample( audio["array"] , max_length=data_args.max_length_seconds , sample_rate=feature_extractor.sampling_rate ) subsampled_wavs.append(lowerCamelCase_ ) __magic_name__ = feature_extractor(lowerCamelCase_ , sampling_rate=feature_extractor.sampling_rate ) __magic_name__ = {model_input_name: inputs.get(lowerCamelCase_ )} __magic_name__ = list(batch[data_args.label_column_name] ) return output_batch def val_transforms(lowerCamelCase_ : Dict ): __magic_name__ = [audio["array"] for audio in batch[data_args.audio_column_name]] __magic_name__ = feature_extractor(lowerCamelCase_ , sampling_rate=feature_extractor.sampling_rate ) __magic_name__ = {model_input_name: inputs.get(lowerCamelCase_ )} __magic_name__ = list(batch[data_args.label_column_name] ) return output_batch # Prepare label mappings. # We'll include these in the model's config to get human readable labels in the Inference API. __magic_name__ = raw_datasets["train"].features[data_args.label_column_name].names __magic_name__ , __magic_name__ = {}, {} for i, label in enumerate(lowerCamelCase_ ): __magic_name__ = str(lowerCamelCase_ ) __magic_name__ = label # Load the accuracy metric from the datasets package __magic_name__ = evaluate.load("accuracy" ) # Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with # `predictions` and `label_ids` fields) and has to return a dictionary string to float. def compute_metrics(lowerCamelCase_ : Dict ): __magic_name__ = np.argmax(eval_pred.predictions , axis=1 ) return metric.compute(predictions=lowerCamelCase_ , references=eval_pred.label_ids ) __magic_name__ = AutoConfig.from_pretrained( model_args.config_name or model_args.model_name_or_path , num_labels=len(lowerCamelCase_ ) , labelaid=lowerCamelCase_ , idalabel=lowerCamelCase_ , finetuning_task="audio-classification" , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) __magic_name__ = AutoModelForAudioClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool(".ckpt" in model_args.model_name_or_path ) , config=lowerCamelCase_ , 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 , ) # freeze the convolutional waveform encoder if model_args.freeze_feature_encoder: model.freeze_feature_encoder() if training_args.do_train: if data_args.max_train_samples is not None: __magic_name__ = ( raw_datasets["train"].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) ) # Set the training transforms raw_datasets["train"].set_transform(lowerCamelCase_ , output_all_columns=lowerCamelCase_ ) if training_args.do_eval: if data_args.max_eval_samples is not None: __magic_name__ = ( raw_datasets["eval"].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms raw_datasets["eval"].set_transform(lowerCamelCase_ , output_all_columns=lowerCamelCase_ ) # Initialize our trainer __magic_name__ = Trainer( model=lowerCamelCase_ , args=lowerCamelCase_ , train_dataset=raw_datasets["train"] if training_args.do_train else None , eval_dataset=raw_datasets["eval"] if training_args.do_eval else None , compute_metrics=lowerCamelCase_ , tokenizer=lowerCamelCase_ , ) # Training if training_args.do_train: __magic_name__ = None if training_args.resume_from_checkpoint is not None: __magic_name__ = training_args.resume_from_checkpoint elif last_checkpoint is not None: __magic_name__ = last_checkpoint __magic_name__ = trainer.train(resume_from_checkpoint=lowerCamelCase_ ) trainer.save_model() trainer.log_metrics("train" , train_result.metrics ) trainer.save_metrics("train" , train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: __magic_name__ = trainer.evaluate() trainer.log_metrics("eval" , lowerCamelCase_ ) trainer.save_metrics("eval" , lowerCamelCase_ ) # Write model card and (optionally) push to hub __magic_name__ = { "finetuned_from": model_args.model_name_or_path, "tasks": "audio-classification", "dataset": data_args.dataset_name, "tags": ["audio-classification"], } if training_args.push_to_hub: trainer.push_to_hub(**lowerCamelCase_ ) else: trainer.create_model_card(**lowerCamelCase_ ) if __name__ == "__main__": main()
664
'''simple docstring''' import numpy class UpperCamelCase_ : """simple docstring""" def __init__( self : Union[str, Any] , _lowerCamelCase : numpy.ndarray , _lowerCamelCase : numpy.ndarray ) -> None: __magic_name__ = input_array # Random initial weights are assigned where first argument is the # number of nodes in previous layer and second argument is the # number of nodes in the next layer. # Random initial weights are assigned. # self.input_array.shape[1] is used to represent number of nodes in input layer. # First hidden layer consists of 4 nodes. __magic_name__ = numpy.random.rand( self.input_array.shape[1] , 4 ) # Random initial values for the first hidden layer. # First hidden layer has 4 nodes. # Second hidden layer has 3 nodes. __magic_name__ = numpy.random.rand( 4 , 3 ) # Random initial values for the second hidden layer. # Second hidden layer has 3 nodes. # Output layer has 1 node. __magic_name__ = numpy.random.rand(3 , 1 ) # Real output values provided. __magic_name__ = output_array # Predicted output values by the neural network. # Predicted_output array initially consists of zeroes. __magic_name__ = numpy.zeros(output_array.shape ) def __A ( self : int ) -> numpy.ndarray: __magic_name__ = sigmoid( numpy.dot(self.input_array , self.input_layer_and_first_hidden_layer_weights ) ) # layer_between_first_hidden_layer_and_second_hidden_layer is the layer # connecting the first hidden set of nodes with the second hidden set of nodes. __magic_name__ = sigmoid( numpy.dot( self.layer_between_input_and_first_hidden_layer , self.first_hidden_layer_and_second_hidden_layer_weights , ) ) # layer_between_second_hidden_layer_and_output is the layer connecting # second hidden layer with the output node. __magic_name__ = sigmoid( numpy.dot( self.layer_between_first_hidden_layer_and_second_hidden_layer , self.second_hidden_layer_and_output_layer_weights , ) ) return self.layer_between_second_hidden_layer_and_output def __A ( self : Dict ) -> None: __magic_name__ = numpy.dot( self.layer_between_first_hidden_layer_and_second_hidden_layer.T , 2 * (self.output_array - self.predicted_output) * sigmoid_derivative(self.predicted_output ) , ) __magic_name__ = numpy.dot( self.layer_between_input_and_first_hidden_layer.T , numpy.dot( 2 * (self.output_array - self.predicted_output) * sigmoid_derivative(self.predicted_output ) , self.second_hidden_layer_and_output_layer_weights.T , ) * sigmoid_derivative( self.layer_between_first_hidden_layer_and_second_hidden_layer ) , ) __magic_name__ = numpy.dot( self.input_array.T , numpy.dot( numpy.dot( 2 * (self.output_array - self.predicted_output) * sigmoid_derivative(self.predicted_output ) , self.second_hidden_layer_and_output_layer_weights.T , ) * sigmoid_derivative( self.layer_between_first_hidden_layer_and_second_hidden_layer ) , self.first_hidden_layer_and_second_hidden_layer_weights.T , ) * sigmoid_derivative(self.layer_between_input_and_first_hidden_layer ) , ) self.input_layer_and_first_hidden_layer_weights += ( updated_input_layer_and_first_hidden_layer_weights ) self.first_hidden_layer_and_second_hidden_layer_weights += ( updated_first_hidden_layer_and_second_hidden_layer_weights ) self.second_hidden_layer_and_output_layer_weights += ( updated_second_hidden_layer_and_output_layer_weights ) def __A ( self : Optional[int] , _lowerCamelCase : numpy.ndarray , _lowerCamelCase : int , _lowerCamelCase : bool ) -> None: for iteration in range(1 , iterations + 1 ): __magic_name__ = self.feedforward() self.back_propagation() if give_loss: __magic_name__ = numpy.mean(numpy.square(output - self.feedforward() ) ) print(f'Iteration {iteration} Loss: {loss}' ) def __A ( self : Tuple , _lowerCamelCase : numpy.ndarray ) -> int: __magic_name__ = input_arr __magic_name__ = sigmoid( numpy.dot(self.array , self.input_layer_and_first_hidden_layer_weights ) ) __magic_name__ = sigmoid( numpy.dot( self.layer_between_input_and_first_hidden_layer , self.first_hidden_layer_and_second_hidden_layer_weights , ) ) __magic_name__ = sigmoid( numpy.dot( self.layer_between_first_hidden_layer_and_second_hidden_layer , self.second_hidden_layer_and_output_layer_weights , ) ) return int(self.layer_between_second_hidden_layer_and_output > 0.6 ) def __snake_case ( lowerCamelCase_ : numpy.ndarray ): '''simple docstring''' return 1 / (1 + numpy.exp(-value )) def __snake_case ( lowerCamelCase_ : numpy.ndarray ): '''simple docstring''' return (value) * (1 - (value)) def __snake_case ( ): '''simple docstring''' __magic_name__ = numpy.array( ( [0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1], ) , dtype=numpy.floataa , ) # True output values for the given input values. __magic_name__ = numpy.array(([0], [1], [1], [0], [1], [0], [0], [1]) , dtype=numpy.floataa ) # Calling neural network class. __magic_name__ = TwoHiddenLayerNeuralNetwork( input_array=lowerCamelCase_ , output_array=lowerCamelCase_ ) # Calling training function. # Set give_loss to True if you want to see loss in every iteration. neural_network.train(output=lowerCamelCase_ , iterations=10 , give_loss=lowerCamelCase_ ) return neural_network.predict(numpy.array(([1, 1, 1]) , dtype=numpy.floataa ) ) if __name__ == "__main__": example()
664
1
'''simple docstring''' import unittest from huggingface_hub import hf_hub_download from transformers import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, VideoMAEFeatureExtractor from transformers.pipelines import VideoClassificationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_decord, require_tf, require_torch, require_torch_or_tf, require_vision, ) from .test_pipelines_common import ANY @is_pipeline_test @require_torch_or_tf @require_vision @require_decord class UpperCamelCase_ ( unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : List[Any] = MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING def __A ( self : Dict , _lowerCamelCase : Tuple , _lowerCamelCase : Dict , _lowerCamelCase : Tuple ) -> Tuple: __magic_name__ = hf_hub_download( repo_id="nateraw/video-demo" , filename="archery.mp4" , repo_type="dataset" ) __magic_name__ = VideoClassificationPipeline(model=_lowerCamelCase , image_processor=_lowerCamelCase , top_k=2 ) __magic_name__ = [ example_video_filepath, "https://huggingface.co/datasets/nateraw/video-demo/resolve/main/archery.mp4", ] return video_classifier, examples def __A ( self : Optional[Any] , _lowerCamelCase : Optional[Any] , _lowerCamelCase : int ) -> Optional[int]: for example in examples: __magic_name__ = video_classifier(_lowerCamelCase ) self.assertEqual( _lowerCamelCase , [ {"score": ANY(_lowerCamelCase ), "label": ANY(_lowerCamelCase )}, {"score": ANY(_lowerCamelCase ), "label": ANY(_lowerCamelCase )}, ] , ) @require_torch def __A ( self : Dict ) -> Any: __magic_name__ = "hf-internal-testing/tiny-random-VideoMAEForVideoClassification" __magic_name__ = VideoMAEFeatureExtractor( size={"shortest_edge": 10} , crop_size={"height": 10, "width": 10} ) __magic_name__ = pipeline( "video-classification" , model=_lowerCamelCase , feature_extractor=_lowerCamelCase , frame_sampling_rate=4 ) __magic_name__ = hf_hub_download(repo_id="nateraw/video-demo" , filename="archery.mp4" , repo_type="dataset" ) __magic_name__ = video_classifier(_lowerCamelCase , top_k=2 ) self.assertEqual( nested_simplify(_lowerCamelCase , decimals=4 ) , [{"score": 0.5_199, "label": "LABEL_0"}, {"score": 0.4_801, "label": "LABEL_1"}] , ) __magic_name__ = video_classifier( [ video_file_path, video_file_path, ] , top_k=2 , ) self.assertEqual( nested_simplify(_lowerCamelCase , decimals=4 ) , [ [{"score": 0.5_199, "label": "LABEL_0"}, {"score": 0.4_801, "label": "LABEL_1"}], [{"score": 0.5_199, "label": "LABEL_0"}, {"score": 0.4_801, "label": "LABEL_1"}], ] , ) @require_tf def __A ( self : Optional[int] ) -> List[Any]: pass
664
'''simple docstring''' import torch from transformers import AutoModel class UpperCamelCase_ ( torch.nn.Module ): """simple docstring""" def __init__( self : Any , _lowerCamelCase : Optional[int]="sayef/fsner-bert-base-uncased" ) -> List[Any]: super(_lowerCamelCase , self ).__init__() __magic_name__ = AutoModel.from_pretrained(_lowerCamelCase , return_dict=_lowerCamelCase ) __magic_name__ = torch.nn.CosineSimilarity(3 , 1e-08 ) __magic_name__ = torch.nn.Softmax(dim=1 ) def __A ( self : Tuple , **_lowerCamelCase : Union[str, Any] ) -> Optional[int]: return self.bert(**_lowerCamelCase ).last_hidden_state def __A ( self : Dict , _lowerCamelCase : Dict ) -> Dict: return token_embeddings.sum(2 , keepdim=_lowerCamelCase ) def __A ( self : Optional[int] , _lowerCamelCase : Dict , _lowerCamelCase : str , _lowerCamelCase : Tuple=1 ) -> Optional[Any]: return self.softmax(T * self.cos(_lowerCamelCase , _lowerCamelCase ) ) def __A ( self : List[Any] , _lowerCamelCase : Optional[Any] , _lowerCamelCase : Optional[int] ) -> List[str]: __magic_name__ = W_supports["sizes"].tolist() __magic_name__ = W_supports["start_token_id"].item() __magic_name__ = W_supports["end_token_id"].item() del W_supports["sizes"] del W_supports["start_token_id"] del W_supports["end_token_id"] __magic_name__ = self.BERT(**_lowerCamelCase ) __magic_name__ = self.BERT(**_lowerCamelCase ) __magic_name__ = None __magic_name__ = None __magic_name__ = W_supports["input_ids"] == start_token_id __magic_name__ = W_supports["input_ids"] == end_token_id for i, size in enumerate(_lowerCamelCase ): if i == 0: __magic_name__ = 0 else: __magic_name__ = support_sizes[i - 1] __magic_name__ = S[s : s + size][start_token_masks[s : s + size]] __magic_name__ = S[s : s + size][end_token_masks[s : s + size]] __magic_name__ = torch.matmul(q[i] , s_start.T ).sum(1 ).softmax(0 ) __magic_name__ = torch.matmul(q[i] , s_end.T ).sum(1 ).softmax(0 ) if p_starts is not None: __magic_name__ = torch.vstack((p_starts, p_start) ) __magic_name__ = torch.vstack((p_ends, p_end) ) else: __magic_name__ = p_start __magic_name__ = p_end return p_starts, p_ends
664
1
'''simple docstring''' __magic_name__ : Dict =8.3_1_4_4_6_2 # Unit - J mol-1 K-1 def __snake_case ( lowerCamelCase_ : float , lowerCamelCase_ : float , lowerCamelCase_ : float ): '''simple docstring''' if moles < 0 or kelvin < 0 or volume < 0: raise ValueError("Invalid inputs. Enter positive value." ) return moles * kelvin * UNIVERSAL_GAS_CONSTANT / volume def __snake_case ( lowerCamelCase_ : float , lowerCamelCase_ : float , lowerCamelCase_ : float ): '''simple docstring''' if moles < 0 or kelvin < 0 or pressure < 0: raise ValueError("Invalid inputs. Enter positive value." ) return moles * kelvin * UNIVERSAL_GAS_CONSTANT / pressure if __name__ == "__main__": from doctest import testmod testmod()
664
'''simple docstring''' # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from ...utils import deprecate from ..controlnet.pipeline_flax_controlnet import FlaxStableDiffusionControlNetPipeline # noqa: F401 deprecate( 'stable diffusion controlnet', '0.22.0', 'Importing `FlaxStableDiffusionControlNetPipeline` from diffusers.pipelines.stable_diffusion.flax_pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import FlaxStableDiffusionControlNetPipeline` instead.', standard_warn=False, stacklevel=3, )
664
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __magic_name__ : int ={ 'configuration_clipseg': [ 'CLIPSEG_PRETRAINED_CONFIG_ARCHIVE_MAP', 'CLIPSegConfig', 'CLIPSegTextConfig', 'CLIPSegVisionConfig', ], 'processing_clipseg': ['CLIPSegProcessor'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ : List[Any] =[ 'CLIPSEG_PRETRAINED_MODEL_ARCHIVE_LIST', 'CLIPSegModel', 'CLIPSegPreTrainedModel', 'CLIPSegTextModel', 'CLIPSegVisionModel', 'CLIPSegForImageSegmentation', ] if TYPE_CHECKING: from .configuration_clipseg import ( CLIPSEG_PRETRAINED_CONFIG_ARCHIVE_MAP, CLIPSegConfig, CLIPSegTextConfig, CLIPSegVisionConfig, ) from .processing_clipseg import CLIPSegProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_clipseg import ( CLIPSEG_PRETRAINED_MODEL_ARCHIVE_LIST, CLIPSegForImageSegmentation, CLIPSegModel, CLIPSegPreTrainedModel, CLIPSegTextModel, CLIPSegVisionModel, ) else: import sys __magic_name__ : List[str] =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
664
'''simple docstring''' import argparse from tax import checkpoints from transformers import AutoConfig, FlaxAutoModelForSeqaSeqLM def __snake_case ( lowerCamelCase_ : Any , lowerCamelCase_ : int , lowerCamelCase_ : Optional[Any] ): '''simple docstring''' __magic_name__ = AutoConfig.from_pretrained(lowerCamelCase_ ) __magic_name__ = FlaxAutoModelForSeqaSeqLM.from_config(config=lowerCamelCase_ ) __magic_name__ = checkpoints.load_tax_checkpoint(lowerCamelCase_ ) __magic_name__ = "wi_0" in tax_model["target"]["encoder"]["layers_0"]["mlp"] if config.model_type == "t5": __magic_name__ = "SelfAttention" if config.model_type == "longt5" and config.encoder_attention_type == "local": __magic_name__ = "LocalSelfAttention" elif config.model_type == "longt5" and config.encoder_attention_type == "transient-global": __magic_name__ = "TransientGlobalSelfAttention" else: raise ValueError( "Given config is expected to have `model_type='t5'`, or `model_type='longt5` with `encoder_attention_type`" " attribute with a value from ['local', 'transient-global]." ) # Encoder for layer_index in range(config.num_layers ): __magic_name__ = F'layers_{str(lowerCamelCase_ )}' # Self-Attention __magic_name__ = tax_model["target"]["encoder"][layer_name]["attention"]["key"]["kernel"] __magic_name__ = tax_model["target"]["encoder"][layer_name]["attention"]["out"]["kernel"] __magic_name__ = tax_model["target"]["encoder"][layer_name]["attention"]["query"]["kernel"] __magic_name__ = tax_model["target"]["encoder"][layer_name]["attention"]["value"]["kernel"] # Global input layer norm if config.model_type == "longt5" and config.encoder_attention_type == "transient-global": __magic_name__ = tax_model["target"]["encoder"][layer_name]["attention"]["T5LayerNorm_0"]["scale"] # Layer Normalization __magic_name__ = tax_model["target"]["encoder"][layer_name]["pre_attention_layer_norm"]["scale"] if split_mlp_wi: __magic_name__ = tax_model["target"]["encoder"][layer_name]["mlp"]["wi_0"]["kernel"] __magic_name__ = tax_model["target"]["encoder"][layer_name]["mlp"]["wi_1"]["kernel"] else: __magic_name__ = tax_model["target"]["encoder"][layer_name]["mlp"]["wi"]["kernel"] __magic_name__ = tax_model["target"]["encoder"][layer_name]["mlp"]["wo"]["kernel"] # Layer Normalization __magic_name__ = tax_model["target"]["encoder"][layer_name]["pre_mlp_layer_norm"]["scale"] # Assigning __magic_name__ = flax_model.params["encoder"]["block"][str(lowerCamelCase_ )]["layer"] __magic_name__ = tax_attention_key __magic_name__ = tax_attention_out __magic_name__ = tax_attention_query __magic_name__ = tax_attention_value __magic_name__ = tax_attention_layer_norm # Global input layer norm if config.model_type == "longt5" and config.encoder_attention_type == "transient-global": __magic_name__ = tax_global_layer_norm if split_mlp_wi: __magic_name__ = tax_mlp_wi_a __magic_name__ = tax_mlp_wi_a else: __magic_name__ = tax_mlp_wi __magic_name__ = tax_mlp_wo __magic_name__ = tax_mlp_layer_norm __magic_name__ = flax_model_encoder_layer_block # Only for layer 0: __magic_name__ = tax_model["target"]["encoder"]["relpos_bias"]["rel_embedding"].T __magic_name__ = tax_encoder_rel_embedding # Side/global relative position_bias + layer norm if config.model_type == "longt5" and config.encoder_attention_type == "transient-global": __magic_name__ = tax_model["target"]["encoder"]["side_relpos_bias"]["rel_embedding"].T __magic_name__ = tax_encoder_global_rel_embedding # Assigning __magic_name__ = tax_model["target"]["encoder"]["encoder_norm"]["scale"] __magic_name__ = tax_encoder_norm # Decoder for layer_index in range(config.num_layers ): __magic_name__ = F'layers_{str(lowerCamelCase_ )}' # Self-Attention __magic_name__ = tax_model["target"]["decoder"][layer_name]["self_attention"]["key"]["kernel"] __magic_name__ = tax_model["target"]["decoder"][layer_name]["self_attention"]["out"]["kernel"] __magic_name__ = tax_model["target"]["decoder"][layer_name]["self_attention"]["query"]["kernel"] __magic_name__ = tax_model["target"]["decoder"][layer_name]["self_attention"]["value"]["kernel"] # Layer Normalization __magic_name__ = tax_model["target"]["decoder"][layer_name]["pre_self_attention_layer_norm"][ "scale" ] # Encoder-Decoder-Attention __magic_name__ = tax_model["target"]["decoder"][layer_name]["encoder_decoder_attention"] __magic_name__ = tax_enc_dec_attention_module["key"]["kernel"] __magic_name__ = tax_enc_dec_attention_module["out"]["kernel"] __magic_name__ = tax_enc_dec_attention_module["query"]["kernel"] __magic_name__ = tax_enc_dec_attention_module["value"]["kernel"] # Layer Normalization __magic_name__ = tax_model["target"]["decoder"][layer_name]["pre_cross_attention_layer_norm"]["scale"] # MLP if split_mlp_wi: __magic_name__ = tax_model["target"]["decoder"][layer_name]["mlp"]["wi_0"]["kernel"] __magic_name__ = tax_model["target"]["decoder"][layer_name]["mlp"]["wi_1"]["kernel"] else: __magic_name__ = tax_model["target"]["decoder"][layer_name]["mlp"]["wi"]["kernel"] __magic_name__ = tax_model["target"]["decoder"][layer_name]["mlp"]["wo"]["kernel"] # Layer Normalization __magic_name__ = tax_model["target"]["decoder"][layer_name]["pre_mlp_layer_norm"]["scale"] # Assigning __magic_name__ = flax_model.params["decoder"]["block"][str(lowerCamelCase_ )]["layer"] __magic_name__ = tax_attention_key __magic_name__ = tax_attention_out __magic_name__ = tax_attention_query __magic_name__ = tax_attention_value __magic_name__ = tax_pre_attention_layer_norm __magic_name__ = tax_enc_dec_attention_key __magic_name__ = tax_enc_dec_attention_out __magic_name__ = tax_enc_dec_attention_query __magic_name__ = tax_enc_dec_attention_value __magic_name__ = tax_cross_layer_norm if split_mlp_wi: __magic_name__ = tax_mlp_wi_a __magic_name__ = tax_mlp_wi_a else: __magic_name__ = tax_mlp_wi __magic_name__ = tax_mlp_wo __magic_name__ = txa_mlp_layer_norm __magic_name__ = flax_model_decoder_layer_block # Decoder Normalization __magic_name__ = tax_model["target"]["decoder"]["decoder_norm"]["scale"] __magic_name__ = txa_decoder_norm # Only for layer 0: __magic_name__ = tax_model["target"]["decoder"]["relpos_bias"]["rel_embedding"].T __magic_name__ = tax_decoder_rel_embedding # Token Embeddings __magic_name__ = tax_model["target"]["token_embedder"]["embedding"] __magic_name__ = txa_token_embeddings # LM Head (only in v1.1 and LongT5 checkpoints) if "logits_dense" in tax_model["target"]["decoder"]: __magic_name__ = tax_model["target"]["decoder"]["logits_dense"]["kernel"] flax_model.save_pretrained(lowerCamelCase_ ) print("T5X Model was sucessfully converted!" ) if __name__ == "__main__": __magic_name__ : Optional[Any] =argparse.ArgumentParser() # Required parameters parser.add_argument( '--t5x_checkpoint_path', default=None, type=str, required=True, help='Path the T5X checkpoint.' ) parser.add_argument('--config_name', default=None, type=str, required=True, help='Config name of LongT5/T5 model.') parser.add_argument( '--flax_dump_folder_path', default=None, type=str, required=True, help='Path to the output FLAX model.' ) __magic_name__ : Optional[int] =parser.parse_args() convert_tax_checkpoint_to_flax(args.tax_checkpoint_path, args.config_name, args.flax_dump_folder_path)
664
1
'''simple docstring''' import heapq import sys import numpy as np __magic_name__ : str =tuple[int, int] class UpperCamelCase_ : """simple docstring""" def __init__( self : Any ) -> List[str]: __magic_name__ = [] __magic_name__ = set() def __A ( self : List[Any] ) -> List[Any]: if not self.empty(): return self.elements[0][0] else: return float("inf" ) def __A ( self : Dict ) -> str: return len(self.elements ) == 0 def __A ( self : Dict , _lowerCamelCase : int , _lowerCamelCase : int ) -> int: if item not in self.set: heapq.heappush(self.elements , (priority, item) ) self.set.add(_lowerCamelCase ) else: # update # print("update", item) __magic_name__ = [] ((__magic_name__) , (__magic_name__)) = heapq.heappop(self.elements ) while x != item: temp.append((pri, x) ) ((__magic_name__) , (__magic_name__)) = heapq.heappop(self.elements ) temp.append((priority, item) ) for pro, xxx in temp: heapq.heappush(self.elements , (pro, xxx) ) def __A ( self : str , _lowerCamelCase : int ) -> List[str]: if item in self.set: self.set.remove(_lowerCamelCase ) __magic_name__ = [] ((__magic_name__) , (__magic_name__)) = heapq.heappop(self.elements ) while x != item: temp.append((pro, x) ) ((__magic_name__) , (__magic_name__)) = heapq.heappop(self.elements ) for prito, yyy in temp: heapq.heappush(self.elements , (prito, yyy) ) def __A ( self : List[str] ) -> int: return self.elements[0][1] def __A ( self : Optional[int] ) -> Union[str, Any]: ((__magic_name__) , (__magic_name__)) = heapq.heappop(self.elements ) self.set.remove(_lowerCamelCase ) return (priority, item) def __snake_case ( lowerCamelCase_ : TPos , lowerCamelCase_ : TPos ): '''simple docstring''' __magic_name__ = np.array(lowerCamelCase_ ) __magic_name__ = np.array(lowerCamelCase_ ) return np.linalg.norm(a - b ) def __snake_case ( lowerCamelCase_ : TPos , lowerCamelCase_ : TPos ): '''simple docstring''' return consistent_heuristic(lowerCamelCase_ , lowerCamelCase_ ) // t def __snake_case ( lowerCamelCase_ : TPos , lowerCamelCase_ : TPos ): '''simple docstring''' return abs(p[0] - goal[0] ) + abs(p[1] - goal[1] ) def __snake_case ( lowerCamelCase_ : TPos , lowerCamelCase_ : int , lowerCamelCase_ : TPos , lowerCamelCase_ : dict[TPos, float] ): '''simple docstring''' __magic_name__ = g_function[start] + Wa * heuristics[i](lowerCamelCase_ , lowerCamelCase_ ) return ans def __snake_case ( lowerCamelCase_ : List[Any] , lowerCamelCase_ : List[Any] , lowerCamelCase_ : Dict ): '''simple docstring''' __magic_name__ = np.chararray((n, n) ) for i in range(lowerCamelCase_ ): for j in range(lowerCamelCase_ ): __magic_name__ = "*" for i in range(lowerCamelCase_ ): for j in range(lowerCamelCase_ ): if (j, (n - 1) - i) in blocks: __magic_name__ = "#" __magic_name__ = "-" __magic_name__ = back_pointer[goal] while x != start: ((__magic_name__) , (__magic_name__)) = x # print(x) __magic_name__ = "-" __magic_name__ = back_pointer[x] __magic_name__ = "-" for i in range(lowerCamelCase_ ): for j in range(lowerCamelCase_ ): if (i, j) == (0, n - 1): print(grid[i][j] , end=" " ) print("<-- End position" , end=" " ) else: print(grid[i][j] , end=" " ) print() print("^" ) print("Start position" ) print() print("# is an obstacle" ) print("- is the path taken by algorithm" ) print("PATH TAKEN BY THE ALGORITHM IS:-" ) __magic_name__ = back_pointer[goal] while x != start: print(lowerCamelCase_ , end=" " ) __magic_name__ = back_pointer[x] print(lowerCamelCase_ ) sys.exit() def __snake_case ( lowerCamelCase_ : TPos ): '''simple docstring''' if p[0] < 0 or p[0] > n - 1: return False if p[1] < 0 or p[1] > n - 1: return False return True def __snake_case ( lowerCamelCase_ : int , lowerCamelCase_ : Tuple , lowerCamelCase_ : Optional[int] , lowerCamelCase_ : Union[str, Any] , lowerCamelCase_ : int , lowerCamelCase_ : Optional[int] , lowerCamelCase_ : str , lowerCamelCase_ : Optional[Any] , ): '''simple docstring''' for itera in range(lowerCamelCase_ ): open_list[itera].remove_element(lowerCamelCase_ ) # print("s", s) # print("j", j) ((__magic_name__) , (__magic_name__)) = s __magic_name__ = (x - 1, y) __magic_name__ = (x + 1, y) __magic_name__ = (x, y + 1) __magic_name__ = (x, y - 1) for neighbours in [left, right, up, down]: if neighbours not in blocks: if valid(lowerCamelCase_ ) and neighbours not in visited: # print("neighbour", neighbours) visited.add(lowerCamelCase_ ) __magic_name__ = -1 __magic_name__ = float("inf" ) if valid(lowerCamelCase_ ) and g_function[neighbours] > g_function[s] + 1: __magic_name__ = g_function[s] + 1 __magic_name__ = s if neighbours not in close_list_anchor: open_list[0].put(lowerCamelCase_ , key(lowerCamelCase_ , 0 , lowerCamelCase_ , lowerCamelCase_ ) ) if neighbours not in close_list_inad: for var in range(1 , lowerCamelCase_ ): if key(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) <= Wa * key( lowerCamelCase_ , 0 , lowerCamelCase_ , lowerCamelCase_ ): open_list[j].put( lowerCamelCase_ , key(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) ) def __snake_case ( ): '''simple docstring''' __magic_name__ = [] for x in range(1 , 5 ): for y in range(1 , 6 ): some_list.append((x, y) ) for x in range(15 , 20 ): some_list.append((x, 17) ) for x in range(10 , 19 ): for y in range(1 , 15 ): some_list.append((x, y) ) # L block for x in range(1 , 4 ): for y in range(12 , 19 ): some_list.append((x, y) ) for x in range(3 , 13 ): for y in range(16 , 19 ): some_list.append((x, y) ) return some_list __magic_name__ : Union[str, Any] ={0: consistent_heuristic, 1: heuristic_a, 2: heuristic_a} __magic_name__ : Union[str, Any] =[ (0, 1), (1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 1), (8, 1), (9, 1), (10, 1), (11, 1), (12, 1), (13, 1), (14, 1), (15, 1), (16, 1), (17, 1), (18, 1), (19, 1), ] __magic_name__ : Any =make_common_ground() __magic_name__ : Union[str, Any] =blocks_blk # hyper parameters __magic_name__ : Any =1 __magic_name__ : Dict =1 __magic_name__ : List[str] =20 __magic_name__ : Optional[int] =3 # one consistent and two other inconsistent # start and end destination __magic_name__ : int =(0, 0) __magic_name__ : int =(n - 1, n - 1) __magic_name__ : Dict =1 def __snake_case ( lowerCamelCase_ : TPos , lowerCamelCase_ : TPos , lowerCamelCase_ : int ): '''simple docstring''' __magic_name__ = {start: 0, goal: float("inf" )} __magic_name__ = {start: -1, goal: -1} __magic_name__ = [] __magic_name__ = set() for i in range(lowerCamelCase_ ): open_list.append(PriorityQueue() ) open_list[i].put(lowerCamelCase_ , key(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) ) __magic_name__ = [] __magic_name__ = [] while open_list[0].minkey() < float("inf" ): for i in range(1 , lowerCamelCase_ ): # print(open_list[0].minkey(), open_list[i].minkey()) if open_list[i].minkey() <= Wa * open_list[0].minkey(): global t t += 1 if g_function[goal] <= open_list[i].minkey(): if g_function[goal] < float("inf" ): do_something(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) else: __magic_name__ , __magic_name__ = open_list[i].top_show() visited.add(lowerCamelCase_ ) expand_state( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , ) close_list_inad.append(lowerCamelCase_ ) else: if g_function[goal] <= open_list[0].minkey(): if g_function[goal] < float("inf" ): do_something(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) else: __magic_name__ = open_list[0].top_show() visited.add(lowerCamelCase_ ) expand_state( lowerCamelCase_ , 0 , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , ) close_list_anchor.append(lowerCamelCase_ ) print("No path found to goal" ) print() for i in range(n - 1 , -1 , -1 ): for j in range(lowerCamelCase_ ): if (j, i) in blocks: print("#" , end=" " ) elif (j, i) in back_pointer: if (j, i) == (n - 1, n - 1): print("*" , end=" " ) else: print("-" , end=" " ) else: print("*" , end=" " ) if (j, i) == (n - 1, n - 1): print("<-- End position" , end=" " ) print() print("^" ) print("Start position" ) print() print("# is an obstacle" ) print("- is the path taken by algorithm" ) if __name__ == "__main__": multi_a_star(start, goal, n_heuristic)
664
'''simple docstring''' import unittest from transformers import load_tool from transformers.utils import is_torch_available if is_torch_available(): import torch from transformers.testing_utils import require_torch from .test_tools_common import ToolTesterMixin @require_torch class UpperCamelCase_ ( unittest.TestCase , A ): """simple docstring""" def __A ( self : Optional[int] ) -> Any: __magic_name__ = load_tool("text-to-speech" ) self.tool.setup() def __A ( self : Union[str, Any] ) -> int: # SpeechT5 isn't deterministic torch.manual_seed(0 ) __magic_name__ = self.tool("hey" ) __magic_name__ = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] , torch.tensor([-0.0_005_966_668_832_115_829, -0.0_003_657_640_190_795_064, -0.00_013_439_502_799_883_485] ) , ) ) def __A ( self : List[str] ) -> int: # SpeechT5 isn't deterministic torch.manual_seed(0 ) __magic_name__ = self.tool("hey" ) __magic_name__ = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] , torch.tensor([-0.0_005_966_668_832_115_829, -0.0_003_657_640_190_795_064, -0.00_013_439_502_799_883_485] ) , ) )
664
1
'''simple docstring''' import functools import gc import inspect import torch from .imports import is_npu_available, is_xpu_available def __snake_case ( *lowerCamelCase_ : List[str] ): '''simple docstring''' if not isinstance(lowerCamelCase_ , lowerCamelCase_ ): __magic_name__ = list(lowerCamelCase_ ) for i in range(len(lowerCamelCase_ ) ): __magic_name__ = None gc.collect() if is_xpu_available(): torch.xpu.empty_cache() elif is_npu_available(): torch.npu.empty_cache() else: torch.cuda.empty_cache() return objects def __snake_case ( lowerCamelCase_ : Exception ): '''simple docstring''' __magic_name__ = [ "CUDA out of memory.", # CUDA OOM "cuDNN error: CUDNN_STATUS_NOT_SUPPORTED.", # CUDNN SNAFU "DefaultCPUAllocator: can't allocate memory", # CPU OOM ] if isinstance(lowerCamelCase_ , lowerCamelCase_ ) and len(exception.args ) == 1: return any(err in exception.args[0] for err in _statements ) return False def __snake_case ( lowerCamelCase_ : callable = None , lowerCamelCase_ : int = 128 ): '''simple docstring''' if function is None: return functools.partial(lowerCamelCase_ , starting_batch_size=lowerCamelCase_ ) __magic_name__ = starting_batch_size def decorator(*lowerCamelCase_ : Dict , **lowerCamelCase_ : Optional[Any] ): nonlocal batch_size gc.collect() if is_xpu_available(): torch.xpu.empty_cache() elif is_npu_available(): torch.npu.empty_cache() else: torch.cuda.empty_cache() __magic_name__ = list(inspect.signature(lowerCamelCase_ ).parameters.keys() ) # Guard against user error if len(lowerCamelCase_ ) < (len(lowerCamelCase_ ) + 1): __magic_name__ = ", ".join([F'{arg}={value}' for arg, value in zip(params[1:] , args[1:] )] ) raise TypeError( F'Batch size was passed into `{function.__name__}` as the first argument when called.' F'Remove this as the decorator already does so: `{function.__name__}({arg_str})`' ) while True: if batch_size == 0: raise RuntimeError("No executable batch size found, reached zero." ) try: return function(lowerCamelCase_ , *lowerCamelCase_ , **lowerCamelCase_ ) except Exception as e: if should_reduce_batch_size(lowerCamelCase_ ): gc.collect() if is_xpu_available(): torch.xpu.empty_cache() elif is_npu_available(): torch.npu.empty_cache() else: torch.cuda.empty_cache() batch_size //= 2 else: raise return decorator
664
'''simple docstring''' import json import multiprocessing as mp import re from collections import defaultdict from functools import partial from typing import Dict, List, Optional, Set, Tuple, Type from datasets import Dataset from datasketch import MinHash, MinHashLSH from dpu_utils.utils.iterators import ThreadedIterator from tqdm import tqdm __magic_name__ : Dict =re.compile('[^A-Za-z_0-9]') # parameters used in DuplicationIndex __magic_name__ : int =10 __magic_name__ : Union[str, Any] =2_56 def __snake_case ( lowerCamelCase_ : List[str] ): '''simple docstring''' if len(lowerCamelCase_ ) < MIN_NUM_TOKENS: return None __magic_name__ = MinHash(num_perm=lowerCamelCase_ ) for token in set(lowerCamelCase_ ): min_hash.update(token.encode() ) return min_hash def __snake_case ( lowerCamelCase_ : str ): '''simple docstring''' return {t for t in NON_ALPHA.split(lowerCamelCase_ ) if len(t.strip() ) > 0} class UpperCamelCase_ : """simple docstring""" def __init__( self : int , *, _lowerCamelCase : float = 0.85 , ) -> Optional[Any]: __magic_name__ = duplication_jaccard_threshold __magic_name__ = NUM_PERM __magic_name__ = MinHashLSH(threshold=self._duplication_jaccard_threshold , num_perm=self._num_perm ) __magic_name__ = defaultdict(_lowerCamelCase ) def __A ( self : List[Any] , _lowerCamelCase : Tuple , _lowerCamelCase : MinHash ) -> None: __magic_name__ = self._index.query(_lowerCamelCase ) if code_key in self._index.keys: print(f'Duplicate key {code_key}' ) return self._index.insert(_lowerCamelCase , _lowerCamelCase ) if len(_lowerCamelCase ) > 0: for base_duplicate in close_duplicates: if base_duplicate in self._duplicate_clusters: self._duplicate_clusters[base_duplicate].add(_lowerCamelCase ) break else: self._duplicate_clusters[close_duplicates[0]].add(_lowerCamelCase ) def __A ( self : Union[str, Any] ) -> List[List[Dict]]: __magic_name__ = [] for base, duplicates in self._duplicate_clusters.items(): __magic_name__ = [base] + list(_lowerCamelCase ) # reformat the cluster to be a list of dict __magic_name__ = [{"base_index": el[0], "repo_name": el[1], "path": el[2]} for el in cluster] duplicate_clusters.append(_lowerCamelCase ) return duplicate_clusters def __A ( self : Tuple , _lowerCamelCase : Tuple ) -> None: __magic_name__ = self.get_duplicate_clusters() with open(_lowerCamelCase , "w" ) as f: json.dump(_lowerCamelCase , _lowerCamelCase ) def __snake_case ( lowerCamelCase_ : List[Any] ): '''simple docstring''' __magic_name__ , __magic_name__ = element __magic_name__ = get_min_hash([t for t in NON_ALPHA.split(data["content"] ) if len(t.strip() ) > 0] ) if min_hash is not None: return (index, data["repo_name"], data["path"]), min_hash def __snake_case ( lowerCamelCase_ : Type[Dataset] ): '''simple docstring''' with mp.Pool() as pool: for data in pool.imap_unordered( _compute_min_hash , ThreadedIterator(lowerCamelCase_ , max_queue_size=1_0000 ) , chunksize=100 , ): if data is not None: yield data def __snake_case ( lowerCamelCase_ : Type[Dataset] , lowerCamelCase_ : float ): '''simple docstring''' __magic_name__ = DuplicationIndex(duplication_jaccard_threshold=lowerCamelCase_ ) for filename, min_hash in tqdm(ThreadedIterator(minhash_iter(enumerate(lowerCamelCase_ ) ) , max_queue_size=100 ) ): di.add(lowerCamelCase_ , lowerCamelCase_ ) # Returns a List[Cluster] where Cluster is List[str] with the filenames. return di.get_duplicate_clusters() def __snake_case ( lowerCamelCase_ : str , lowerCamelCase_ : str ): '''simple docstring''' __magic_name__ = get_tokens(lowerCamelCase_ ) __magic_name__ = get_tokens(lowerCamelCase_ ) return len(tokensa & tokensa ) / len(tokensa | tokensa ) __magic_name__ : List[str] =None def __snake_case ( lowerCamelCase_ : Dict , lowerCamelCase_ : List[Any] ): '''simple docstring''' __magic_name__ = [] for elementa in cluster: __magic_name__ = _shared_dataset[elementa["base_index"]]["content"] for elementa in extremes: __magic_name__ = _shared_dataset[elementa["base_index"]]["content"] if jaccard_similarity(lowerCamelCase_ , lowerCamelCase_ ) >= jaccard_threshold: elementa["copies"] += 1 break else: __magic_name__ = 1 extremes.append(lowerCamelCase_ ) return extremes def __snake_case ( lowerCamelCase_ : Dict , lowerCamelCase_ : Any , lowerCamelCase_ : Union[str, Any] ): '''simple docstring''' global _shared_dataset __magic_name__ = dataset __magic_name__ = [] __magic_name__ = partial(_find_cluster_extremes_shared , jaccard_threshold=lowerCamelCase_ ) with mp.Pool() as pool: for extremes in tqdm( pool.imap_unordered( lowerCamelCase_ , lowerCamelCase_ , ) , total=len(lowerCamelCase_ ) , ): extremes_list.append(lowerCamelCase_ ) return extremes_list def __snake_case ( lowerCamelCase_ : Type[Dataset] , lowerCamelCase_ : float = 0.85 ): '''simple docstring''' __magic_name__ = make_duplicate_clusters(lowerCamelCase_ , lowerCamelCase_ ) __magic_name__ = {x["base_index"] for cluster in duplicate_clusters for x in cluster} __magic_name__ = {} __magic_name__ = find_extremes(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) for extremes in extremes_clusters: for element in extremes: __magic_name__ = element __magic_name__ = duplicate_indices - set(extreme_dict.keys() ) __magic_name__ = dataset.filter(lambda lowerCamelCase_ , lowerCamelCase_ : idx not in remove_indices , with_indices=lowerCamelCase_ ) # update duplicate_clusters for cluster in duplicate_clusters: for element in cluster: __magic_name__ = element["base_index"] in extreme_dict if element["is_extreme"]: __magic_name__ = extreme_dict[element["base_index"]]["copies"] print(F'Original dataset size: {len(lowerCamelCase_ )}' ) print(F'Number of duplicate clusters: {len(lowerCamelCase_ )}' ) print(F'Files in duplicate cluster: {len(lowerCamelCase_ )}' ) print(F'Unique files in duplicate cluster: {len(lowerCamelCase_ )}' ) print(F'Filtered dataset size: {len(lowerCamelCase_ )}' ) return ds_filter, duplicate_clusters
664
1
'''simple docstring''' from __future__ import annotations def __snake_case ( lowerCamelCase_ : float , lowerCamelCase_ : float , lowerCamelCase_ : float , ): '''simple docstring''' if (stress, tangential_force, area).count(0 ) != 1: raise ValueError("You cannot supply more or less than 2 values" ) elif stress < 0: raise ValueError("Stress cannot be negative" ) elif tangential_force < 0: raise ValueError("Tangential Force cannot be negative" ) elif area < 0: raise ValueError("Area cannot be negative" ) elif stress == 0: return ( "stress", tangential_force / area, ) elif tangential_force == 0: return ( "tangential_force", stress * area, ) else: return ( "area", tangential_force / stress, ) if __name__ == "__main__": import doctest doctest.testmod()
664
'''simple docstring''' import argparse import os import gluonnlp as nlp import mxnet as mx import numpy as np import torch from gluonnlp.base import get_home_dir from gluonnlp.model.bert import BERTEncoder from gluonnlp.model.utils import _load_vocab from gluonnlp.vocab import Vocab from packaging import version from torch import nn from transformers import BertConfig, BertForMaskedLM, BertModel, RobertaTokenizer from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertSelfAttention, BertSelfOutput, ) from transformers.utils import logging if version.parse(nlp.__version__) != version.parse('0.8.3'): raise Exception('requires gluonnlp == 0.8.3') if version.parse(mx.__version__) != version.parse('1.5.0'): raise Exception('requires mxnet == 1.5.0') logging.set_verbosity_info() __magic_name__ : Optional[int] =logging.get_logger(__name__) __magic_name__ : Tuple ='The Nymphenburg Palace is a beautiful palace in Munich!' def __snake_case ( lowerCamelCase_ : str , lowerCamelCase_ : str ): '''simple docstring''' __magic_name__ = { "attention_cell": "multi_head", "num_layers": 4, "units": 1024, "hidden_size": 768, "max_length": 512, "num_heads": 8, "scaled": True, "dropout": 0.1, "use_residual": True, "embed_size": 1024, "embed_dropout": 0.1, "word_embed": None, "layer_norm_eps": 1e-5, "token_type_vocab_size": 2, } __magic_name__ = bort_4_8_768_1024_hparams # Let's construct the original Bort model here # Taken from official BERT implementation, see: # https://github.com/alexa/bort/blob/master/bort/bort.py __magic_name__ = BERTEncoder( attention_cell=predefined_args["attention_cell"] , num_layers=predefined_args["num_layers"] , units=predefined_args["units"] , hidden_size=predefined_args["hidden_size"] , max_length=predefined_args["max_length"] , num_heads=predefined_args["num_heads"] , scaled=predefined_args["scaled"] , dropout=predefined_args["dropout"] , output_attention=lowerCamelCase_ , output_all_encodings=lowerCamelCase_ , use_residual=predefined_args["use_residual"] , activation=predefined_args.get("activation" , "gelu" ) , layer_norm_eps=predefined_args.get("layer_norm_eps" , lowerCamelCase_ ) , ) # Vocab information needs to be fetched first # It's the same as RoBERTa, so RobertaTokenizer can be used later __magic_name__ = "openwebtext_ccnews_stories_books_cased" # Specify download folder to Gluonnlp's vocab __magic_name__ = os.path.join(get_home_dir() , "models" ) __magic_name__ = _load_vocab(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , cls=lowerCamelCase_ ) __magic_name__ = nlp.model.BERTModel( lowerCamelCase_ , len(lowerCamelCase_ ) , units=predefined_args["units"] , embed_size=predefined_args["embed_size"] , embed_dropout=predefined_args["embed_dropout"] , word_embed=predefined_args["word_embed"] , use_pooler=lowerCamelCase_ , use_token_type_embed=lowerCamelCase_ , token_type_vocab_size=predefined_args["token_type_vocab_size"] , use_classifier=lowerCamelCase_ , use_decoder=lowerCamelCase_ , ) original_bort.load_parameters(lowerCamelCase_ , cast_dtype=lowerCamelCase_ , ignore_extra=lowerCamelCase_ ) __magic_name__ = original_bort._collect_params_with_prefix() # Build our config 🤗 __magic_name__ = { "architectures": ["BertForMaskedLM"], "attention_probs_dropout_prob": predefined_args["dropout"], "hidden_act": "gelu", "hidden_dropout_prob": predefined_args["dropout"], "hidden_size": predefined_args["embed_size"], "initializer_range": 0.02, "intermediate_size": predefined_args["hidden_size"], "layer_norm_eps": predefined_args["layer_norm_eps"], "max_position_embeddings": predefined_args["max_length"], "model_type": "bort", "num_attention_heads": predefined_args["num_heads"], "num_hidden_layers": predefined_args["num_layers"], "pad_token_id": 1, # 2 = BERT, 1 = RoBERTa "type_vocab_size": 1, # 2 = BERT, 1 = RoBERTa "vocab_size": len(lowerCamelCase_ ), } __magic_name__ = BertConfig.from_dict(lowerCamelCase_ ) __magic_name__ = BertForMaskedLM(lowerCamelCase_ ) hf_bort_model.eval() # Parameter mapping table (Gluonnlp to Transformers) # * denotes layer index # # | Gluon Parameter | Transformers Parameter # | -------------------------------------------------------------- | ---------------------- # | `encoder.layer_norm.beta` | `bert.embeddings.LayerNorm.bias` # | `encoder.layer_norm.gamma` | `bert.embeddings.LayerNorm.weight` # | `encoder.position_weight` | `bert.embeddings.position_embeddings.weight` # | `word_embed.0.weight` | `bert.embeddings.word_embeddings.weight` # | `encoder.transformer_cells.*.attention_cell.proj_key.bias` | `bert.encoder.layer.*.attention.self.key.bias` # | `encoder.transformer_cells.*.attention_cell.proj_key.weight` | `bert.encoder.layer.*.attention.self.key.weight` # | `encoder.transformer_cells.*.attention_cell.proj_query.bias` | `bert.encoder.layer.*.attention.self.query.bias` # | `encoder.transformer_cells.*.attention_cell.proj_query.weight` | `bert.encoder.layer.*.attention.self.query.weight` # | `encoder.transformer_cells.*.attention_cell.proj_value.bias` | `bert.encoder.layer.*.attention.self.value.bias` # | `encoder.transformer_cells.*.attention_cell.proj_value.weight` | `bert.encoder.layer.*.attention.self.value.weight` # | `encoder.transformer_cells.*.ffn.ffn_2.bias` | `bert.encoder.layer.*.attention.output.dense.bias` # | `encoder.transformer_cells.*.ffn.ffn_2.weight` | `bert.encoder.layer.*.attention.output.dense.weight` # | `encoder.transformer_cells.*.layer_norm.beta` | `bert.encoder.layer.*.attention.output.LayerNorm.bias` # | `encoder.transformer_cells.*.layer_norm.gamma` | `bert.encoder.layer.*.attention.output.LayerNorm.weight` # | `encoder.transformer_cells.*.ffn.ffn_1.bias` | `bert.encoder.layer.*.intermediate.dense.bias` # | `encoder.transformer_cells.*.ffn.ffn_1.weight` | `bert.encoder.layer.*.intermediate.dense.weight` # | `encoder.transformer_cells.*.ffn.layer_norm.beta` | `bert.encoder.layer.*.output.LayerNorm.bias` # | `encoder.transformer_cells.*.ffn.layer_norm.gamma` | `bert.encoder.layer.*.output.LayerNorm.weight` # | `encoder.transformer_cells.*.proj.bias` | `bert.encoder.layer.*.output.dense.bias` # | `encoder.transformer_cells.*.proj.weight` | `bert.encoder.layer.*.output.dense.weight` # Helper function to convert MXNET Arrays to PyTorch def to_torch(lowerCamelCase_ : Any ) -> nn.Parameter: return nn.Parameter(torch.FloatTensor(mx_array.data().asnumpy() ) ) # Check param shapes and map new HF param back def check_and_map_params(lowerCamelCase_ : Optional[int] , lowerCamelCase_ : int ): __magic_name__ = hf_param.shape __magic_name__ = to_torch(params[gluon_param] ) __magic_name__ = gluon_param.shape assert ( shape_hf == shape_gluon ), F'The gluon parameter {gluon_param} has shape {shape_gluon}, but expects shape {shape_hf} for Transformers' return gluon_param __magic_name__ = check_and_map_params( hf_bort_model.bert.embeddings.word_embeddings.weight , "word_embed.0.weight" ) __magic_name__ = check_and_map_params( hf_bort_model.bert.embeddings.position_embeddings.weight , "encoder.position_weight" ) __magic_name__ = check_and_map_params( hf_bort_model.bert.embeddings.LayerNorm.bias , "encoder.layer_norm.beta" ) __magic_name__ = check_and_map_params( hf_bort_model.bert.embeddings.LayerNorm.weight , "encoder.layer_norm.gamma" ) # Inspired by RoBERTa conversion script, we just zero them out (Bort does not use them) __magic_name__ = torch.zeros_like( hf_bort_model.bert.embeddings.token_type_embeddings.weight.data ) for i in range(hf_bort_config.num_hidden_layers ): __magic_name__ = hf_bort_model.bert.encoder.layer[i] # self attention __magic_name__ = layer.attention.self __magic_name__ = check_and_map_params( self_attn.key.bias.data , F'encoder.transformer_cells.{i}.attention_cell.proj_key.bias' ) __magic_name__ = check_and_map_params( self_attn.key.weight.data , F'encoder.transformer_cells.{i}.attention_cell.proj_key.weight' ) __magic_name__ = check_and_map_params( self_attn.query.bias.data , F'encoder.transformer_cells.{i}.attention_cell.proj_query.bias' ) __magic_name__ = check_and_map_params( self_attn.query.weight.data , F'encoder.transformer_cells.{i}.attention_cell.proj_query.weight' ) __magic_name__ = check_and_map_params( self_attn.value.bias.data , F'encoder.transformer_cells.{i}.attention_cell.proj_value.bias' ) __magic_name__ = check_and_map_params( self_attn.value.weight.data , F'encoder.transformer_cells.{i}.attention_cell.proj_value.weight' ) # self attention output __magic_name__ = layer.attention.output __magic_name__ = check_and_map_params( self_output.dense.bias , F'encoder.transformer_cells.{i}.proj.bias' ) __magic_name__ = check_and_map_params( self_output.dense.weight , F'encoder.transformer_cells.{i}.proj.weight' ) __magic_name__ = check_and_map_params( self_output.LayerNorm.bias , F'encoder.transformer_cells.{i}.layer_norm.beta' ) __magic_name__ = check_and_map_params( self_output.LayerNorm.weight , F'encoder.transformer_cells.{i}.layer_norm.gamma' ) # intermediate __magic_name__ = layer.intermediate __magic_name__ = check_and_map_params( intermediate.dense.bias , F'encoder.transformer_cells.{i}.ffn.ffn_1.bias' ) __magic_name__ = check_and_map_params( intermediate.dense.weight , F'encoder.transformer_cells.{i}.ffn.ffn_1.weight' ) # output __magic_name__ = layer.output __magic_name__ = check_and_map_params( bert_output.dense.bias , F'encoder.transformer_cells.{i}.ffn.ffn_2.bias' ) __magic_name__ = check_and_map_params( bert_output.dense.weight , F'encoder.transformer_cells.{i}.ffn.ffn_2.weight' ) __magic_name__ = check_and_map_params( bert_output.LayerNorm.bias , F'encoder.transformer_cells.{i}.ffn.layer_norm.beta' ) __magic_name__ = check_and_map_params( bert_output.LayerNorm.weight , F'encoder.transformer_cells.{i}.ffn.layer_norm.gamma' ) # Save space and energy 🎄 hf_bort_model.half() # Compare output of both models __magic_name__ = RobertaTokenizer.from_pretrained("roberta-base" ) __magic_name__ = tokenizer.encode_plus(lowerCamelCase_ )["input_ids"] # Get gluon output __magic_name__ = mx.nd.array([input_ids] ) __magic_name__ = original_bort(inputs=lowerCamelCase_ , token_types=[] ) # Get Transformer output (save and reload model again) hf_bort_model.save_pretrained(lowerCamelCase_ ) __magic_name__ = BertModel.from_pretrained(lowerCamelCase_ ) hf_bort_model.eval() __magic_name__ = tokenizer.encode_plus(lowerCamelCase_ , return_tensors="pt" ) __magic_name__ = hf_bort_model(**lowerCamelCase_ )[0] __magic_name__ = output_gluon[0].asnumpy() __magic_name__ = output_hf[0].detach().numpy() __magic_name__ = np.max(np.abs(hf_layer - gluon_layer ) ).item() __magic_name__ = np.allclose(lowerCamelCase_ , lowerCamelCase_ , atol=1e-3 ) if success: print("✔️ Both model do output the same tensors" ) else: print("❌ Both model do **NOT** output the same tensors" ) print("Absolute difference is:" , lowerCamelCase_ ) if __name__ == "__main__": __magic_name__ : int =argparse.ArgumentParser() # Required parameters parser.add_argument( '--bort_checkpoint_path', default=None, type=str, required=True, help='Path the official Bort params file.' ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) __magic_name__ : Optional[Any] =parser.parse_args() convert_bort_checkpoint_to_pytorch(args.bort_checkpoint_path, args.pytorch_dump_folder_path)
664
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __magic_name__ : Optional[Any] ={ 'configuration_time_series_transformer': [ 'TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'TimeSeriesTransformerConfig', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ : Dict =[ 'TIME_SERIES_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'TimeSeriesTransformerForPrediction', 'TimeSeriesTransformerModel', 'TimeSeriesTransformerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_time_series_transformer import ( TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TimeSeriesTransformerConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_time_series_transformer import ( TIME_SERIES_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TimeSeriesTransformerForPrediction, TimeSeriesTransformerModel, TimeSeriesTransformerPreTrainedModel, ) else: import sys __magic_name__ : Dict =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
664
'''simple docstring''' def __snake_case ( lowerCamelCase_ : int , lowerCamelCase_ : int ): '''simple docstring''' if a < 0 or b < 0: raise ValueError("the value of both inputs must be positive" ) __magic_name__ = str(bin(lowerCamelCase_ ) )[2:] # remove the leading "0b" __magic_name__ = str(bin(lowerCamelCase_ ) )[2:] # remove the leading "0b" __magic_name__ = max(len(lowerCamelCase_ ) , len(lowerCamelCase_ ) ) return "0b" + "".join( str(int(char_a == "1" and char_b == "1" ) ) for char_a, char_b in zip(a_binary.zfill(lowerCamelCase_ ) , b_binary.zfill(lowerCamelCase_ ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
664
1
'''simple docstring''' from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __magic_name__ : Optional[int] ={ 'configuration_trajectory_transformer': [ 'TRAJECTORY_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'TrajectoryTransformerConfig', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ : Optional[int] =[ '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 __magic_name__ : Any =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
664
'''simple docstring''' import functools import logging import os import sys import threading from logging import ( CRITICAL, # NOQA DEBUG, # NOQA ERROR, # NOQA FATAL, # NOQA INFO, # NOQA NOTSET, # NOQA WARN, # NOQA WARNING, # NOQA ) from typing import Optional import huggingface_hub.utils as hf_hub_utils from tqdm import auto as tqdm_lib __magic_name__ : Tuple =threading.Lock() __magic_name__ : Optional[logging.Handler] =None __magic_name__ : List[str] ={ 'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'critical': logging.CRITICAL, } __magic_name__ : str =logging.WARNING __magic_name__ : Any =True def __snake_case ( ): '''simple docstring''' __magic_name__ = os.getenv("TRANSFORMERS_VERBOSITY" , lowerCamelCase_ ) if env_level_str: if env_level_str in log_levels: return log_levels[env_level_str] else: logging.getLogger().warning( F'Unknown option TRANSFORMERS_VERBOSITY={env_level_str}, ' F'has to be one of: { ", ".join(log_levels.keys() ) }' ) return _default_log_level def __snake_case ( ): '''simple docstring''' return __name__.split("." )[0] def __snake_case ( ): '''simple docstring''' return logging.getLogger(_get_library_name() ) def __snake_case ( ): '''simple docstring''' global _default_handler with _lock: if _default_handler: # This library has already configured the library root logger. return __magic_name__ = logging.StreamHandler() # Set sys.stderr as stream. __magic_name__ = sys.stderr.flush # Apply our default configuration to the library root logger. __magic_name__ = _get_library_root_logger() library_root_logger.addHandler(_default_handler ) library_root_logger.setLevel(_get_default_logging_level() ) __magic_name__ = False def __snake_case ( ): '''simple docstring''' global _default_handler with _lock: if not _default_handler: return __magic_name__ = _get_library_root_logger() library_root_logger.removeHandler(_default_handler ) library_root_logger.setLevel(logging.NOTSET ) __magic_name__ = None def __snake_case ( ): '''simple docstring''' return log_levels def __snake_case ( lowerCamelCase_ : Optional[str] = None ): '''simple docstring''' if name is None: __magic_name__ = _get_library_name() _configure_library_root_logger() return logging.getLogger(lowerCamelCase_ ) def __snake_case ( ): '''simple docstring''' _configure_library_root_logger() return _get_library_root_logger().getEffectiveLevel() def __snake_case ( lowerCamelCase_ : int ): '''simple docstring''' _configure_library_root_logger() _get_library_root_logger().setLevel(lowerCamelCase_ ) def __snake_case ( ): '''simple docstring''' return set_verbosity(lowerCamelCase_ ) def __snake_case ( ): '''simple docstring''' return set_verbosity(lowerCamelCase_ ) def __snake_case ( ): '''simple docstring''' return set_verbosity(lowerCamelCase_ ) def __snake_case ( ): '''simple docstring''' return set_verbosity(lowerCamelCase_ ) def __snake_case ( ): '''simple docstring''' _configure_library_root_logger() assert _default_handler is not None _get_library_root_logger().removeHandler(_default_handler ) def __snake_case ( ): '''simple docstring''' _configure_library_root_logger() assert _default_handler is not None _get_library_root_logger().addHandler(_default_handler ) def __snake_case ( lowerCamelCase_ : logging.Handler ): '''simple docstring''' _configure_library_root_logger() assert handler is not None _get_library_root_logger().addHandler(lowerCamelCase_ ) def __snake_case ( lowerCamelCase_ : logging.Handler ): '''simple docstring''' _configure_library_root_logger() assert handler is not None and handler not in _get_library_root_logger().handlers _get_library_root_logger().removeHandler(lowerCamelCase_ ) def __snake_case ( ): '''simple docstring''' _configure_library_root_logger() __magic_name__ = False def __snake_case ( ): '''simple docstring''' _configure_library_root_logger() __magic_name__ = True def __snake_case ( ): '''simple docstring''' __magic_name__ = _get_library_root_logger().handlers for handler in handlers: __magic_name__ = logging.Formatter("[%(levelname)s|%(filename)s:%(lineno)s] %(asctime)s >> %(message)s" ) handler.setFormatter(lowerCamelCase_ ) def __snake_case ( ): '''simple docstring''' __magic_name__ = _get_library_root_logger().handlers for handler in handlers: handler.setFormatter(lowerCamelCase_ ) def __snake_case ( self : Union[str, Any] , *lowerCamelCase_ : str , **lowerCamelCase_ : Any ): '''simple docstring''' __magic_name__ = os.getenv("TRANSFORMERS_NO_ADVISORY_WARNINGS" , lowerCamelCase_ ) if no_advisory_warnings: return self.warning(*lowerCamelCase_ , **lowerCamelCase_ ) __magic_name__ : int =warning_advice @functools.lru_cache(lowerCamelCase_ ) def __snake_case ( self : Dict , *lowerCamelCase_ : int , **lowerCamelCase_ : int ): '''simple docstring''' self.warning(*lowerCamelCase_ , **lowerCamelCase_ ) __magic_name__ : Optional[int] =warning_once class UpperCamelCase_ : """simple docstring""" def __init__( self : int , *_lowerCamelCase : Tuple , **_lowerCamelCase : Optional[Any] ) -> Any: # pylint: disable=unused-argument __magic_name__ = args[0] if args else None def __iter__( self : int ) -> Tuple: return iter(self._iterator ) def __getattr__( self : List[Any] , _lowerCamelCase : int ) -> List[Any]: def empty_fn(*_lowerCamelCase : List[str] , **_lowerCamelCase : List[str] ): # pylint: disable=unused-argument return return empty_fn def __enter__( self : Optional[Any] ) -> Any: return self def __exit__( self : int , _lowerCamelCase : List[Any] , _lowerCamelCase : List[Any] , _lowerCamelCase : List[str] ) -> Dict: return class UpperCamelCase_ : """simple docstring""" def __call__( self : Any , *_lowerCamelCase : Optional[Any] , **_lowerCamelCase : Any ) -> List[Any]: if _tqdm_active: return tqdm_lib.tqdm(*_lowerCamelCase , **_lowerCamelCase ) else: return EmptyTqdm(*_lowerCamelCase , **_lowerCamelCase ) def __A ( self : Optional[Any] , *_lowerCamelCase : Optional[Any] , **_lowerCamelCase : Dict ) -> Union[str, Any]: __magic_name__ = None if _tqdm_active: return tqdm_lib.tqdm.set_lock(*_lowerCamelCase , **_lowerCamelCase ) def __A ( self : str ) -> Any: if _tqdm_active: return tqdm_lib.tqdm.get_lock() __magic_name__ : List[Any] =_tqdm_cls() def __snake_case ( ): '''simple docstring''' global _tqdm_active return bool(_tqdm_active ) def __snake_case ( ): '''simple docstring''' global _tqdm_active __magic_name__ = True hf_hub_utils.enable_progress_bars() def __snake_case ( ): '''simple docstring''' global _tqdm_active __magic_name__ = False hf_hub_utils.disable_progress_bars()
664
1
'''simple docstring''' from __future__ import annotations from collections.abc import Iterator class UpperCamelCase_ : """simple docstring""" def __init__( self : List[Any] , _lowerCamelCase : int ) -> None: __magic_name__ = value __magic_name__ = None __magic_name__ = None class UpperCamelCase_ : """simple docstring""" def __init__( self : Optional[int] , _lowerCamelCase : Node ) -> None: __magic_name__ = tree def __A ( self : List[str] , _lowerCamelCase : Node | None ) -> int: if node is None: return 0 return node.value + ( self.depth_first_search(node.left ) + self.depth_first_search(node.right ) ) def __iter__( self : int ) -> Iterator[int]: yield self.depth_first_search(self.tree ) if __name__ == "__main__": import doctest doctest.testmod()
664
'''simple docstring''' from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __magic_name__ : Union[str, Any] ={'configuration_focalnet': ['FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP', 'FocalNetConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ : str =[ 'FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST', 'FocalNetForImageClassification', 'FocalNetForMaskedImageModeling', 'FocalNetBackbone', 'FocalNetModel', 'FocalNetPreTrainedModel', ] if TYPE_CHECKING: from .configuration_focalnet import FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FocalNetConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_focalnet import ( FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST, FocalNetBackbone, FocalNetForImageClassification, FocalNetForMaskedImageModeling, FocalNetModel, FocalNetPreTrainedModel, ) else: import sys __magic_name__ : List[Any] =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
664
1
'''simple docstring''' import inspect import re from hashlib import shaaaa from typing import Dict, List from .arrow import arrow from .audiofolder import audiofolder from .csv import csv from .imagefolder import imagefolder from .json import json from .pandas import pandas from .parquet import parquet from .sql import sql # noqa F401 from .text import text def __snake_case ( lowerCamelCase_ : List[str] ): '''simple docstring''' __magic_name__ = [] for line in lines: __magic_name__ = re.sub(R"#.*" , "" , lowerCamelCase_ ) # remove comments if line: filtered_lines.append(lowerCamelCase_ ) __magic_name__ = "\n".join(lowerCamelCase_ ) # Make a hash from all this code __magic_name__ = full_str.encode("utf-8" ) return shaaaa(lowerCamelCase_ ).hexdigest() # get importable module names and hash for caching __magic_name__ : Optional[int] ={ 'csv': (csv.__name__, _hash_python_lines(inspect.getsource(csv).splitlines())), 'json': (json.__name__, _hash_python_lines(inspect.getsource(json).splitlines())), 'pandas': (pandas.__name__, _hash_python_lines(inspect.getsource(pandas).splitlines())), 'parquet': (parquet.__name__, _hash_python_lines(inspect.getsource(parquet).splitlines())), 'arrow': (arrow.__name__, _hash_python_lines(inspect.getsource(arrow).splitlines())), 'text': (text.__name__, _hash_python_lines(inspect.getsource(text).splitlines())), 'imagefolder': (imagefolder.__name__, _hash_python_lines(inspect.getsource(imagefolder).splitlines())), 'audiofolder': (audiofolder.__name__, _hash_python_lines(inspect.getsource(audiofolder).splitlines())), } # Used to infer the module to use based on the data files extensions __magic_name__ : Dict ={ '.csv': ('csv', {}), '.tsv': ('csv', {'sep': '\t'}), '.json': ('json', {}), '.jsonl': ('json', {}), '.parquet': ('parquet', {}), '.arrow': ('arrow', {}), '.txt': ('text', {}), } _EXTENSION_TO_MODULE.update({ext: ('imagefolder', {}) for ext in imagefolder.ImageFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext.upper(): ('imagefolder', {}) for ext in imagefolder.ImageFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext: ('audiofolder', {}) for ext in audiofolder.AudioFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext.upper(): ('audiofolder', {}) for ext in audiofolder.AudioFolder.EXTENSIONS}) __magic_name__ : List[str] ={'imagefolder', 'audiofolder'} # Used to filter data files based on extensions given a module name __magic_name__ : Dict[str, List[str]] ={} for _ext, (_module, _) in _EXTENSION_TO_MODULE.items(): _MODULE_TO_EXTENSIONS.setdefault(_module, []).append(_ext) _MODULE_TO_EXTENSIONS["imagefolder"].append('.zip') _MODULE_TO_EXTENSIONS["audiofolder"].append('.zip')
664
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) __magic_name__ : Optional[Any] ={ 'configuration_longformer': [ 'LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LongformerConfig', 'LongformerOnnxConfig', ], 'tokenization_longformer': ['LongformerTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ : int =['LongformerTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ : Dict =[ 'LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'LongformerForMaskedLM', 'LongformerForMultipleChoice', 'LongformerForQuestionAnswering', 'LongformerForSequenceClassification', 'LongformerForTokenClassification', 'LongformerModel', 'LongformerPreTrainedModel', 'LongformerSelfAttention', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ : Tuple =[ 'TF_LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFLongformerForMaskedLM', 'TFLongformerForMultipleChoice', 'TFLongformerForQuestionAnswering', 'TFLongformerForSequenceClassification', 'TFLongformerForTokenClassification', 'TFLongformerModel', 'TFLongformerPreTrainedModel', 'TFLongformerSelfAttention', ] if TYPE_CHECKING: from .configuration_longformer import ( LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, LongformerConfig, LongformerOnnxConfig, ) from .tokenization_longformer import LongformerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_longformer_fast import LongformerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_longformer import ( LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, LongformerForMaskedLM, LongformerForMultipleChoice, LongformerForQuestionAnswering, LongformerForSequenceClassification, LongformerForTokenClassification, LongformerModel, LongformerPreTrainedModel, LongformerSelfAttention, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_longformer import ( TF_LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFLongformerForMaskedLM, TFLongformerForMultipleChoice, TFLongformerForQuestionAnswering, TFLongformerForSequenceClassification, TFLongformerForTokenClassification, TFLongformerModel, TFLongformerPreTrainedModel, TFLongformerSelfAttention, ) else: import sys __magic_name__ : int =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
664
1
'''simple docstring''' import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_video_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import VivitImageProcessor class UpperCamelCase_ ( unittest.TestCase ): """simple docstring""" def __init__( self : Union[str, Any] , _lowerCamelCase : List[str] , _lowerCamelCase : int=7 , _lowerCamelCase : Union[str, Any]=3 , _lowerCamelCase : Union[str, Any]=10 , _lowerCamelCase : Any=18 , _lowerCamelCase : Union[str, Any]=30 , _lowerCamelCase : Any=4_00 , _lowerCamelCase : Optional[Any]=True , _lowerCamelCase : List[str]=None , _lowerCamelCase : str=True , _lowerCamelCase : List[Any]=[0.5, 0.5, 0.5] , _lowerCamelCase : List[str]=[0.5, 0.5, 0.5] , _lowerCamelCase : List[Any]=None , ) -> Any: __magic_name__ = size if size is not None else {"shortest_edge": 18} __magic_name__ = crop_size if crop_size is not None else {"height": 18, "width": 18} __magic_name__ = parent __magic_name__ = batch_size __magic_name__ = num_channels __magic_name__ = num_frames __magic_name__ = image_size __magic_name__ = min_resolution __magic_name__ = max_resolution __magic_name__ = do_resize __magic_name__ = size __magic_name__ = do_normalize __magic_name__ = image_mean __magic_name__ = image_std __magic_name__ = crop_size def __A ( self : int ) -> Optional[int]: return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, "crop_size": self.crop_size, } @require_torch @require_vision class UpperCamelCase_ ( A , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Tuple = VivitImageProcessor if is_vision_available() else None def __A ( self : Optional[Any] ) -> int: __magic_name__ = VivitImageProcessingTester(self ) @property def __A ( self : Union[str, Any] ) -> Tuple: return self.image_processor_tester.prepare_image_processor_dict() def __A ( self : Any ) -> List[str]: __magic_name__ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCamelCase , "image_mean" ) ) self.assertTrue(hasattr(_lowerCamelCase , "image_std" ) ) self.assertTrue(hasattr(_lowerCamelCase , "do_normalize" ) ) self.assertTrue(hasattr(_lowerCamelCase , "do_resize" ) ) self.assertTrue(hasattr(_lowerCamelCase , "do_center_crop" ) ) self.assertTrue(hasattr(_lowerCamelCase , "size" ) ) def __A ( self : List[Any] ) -> Optional[Any]: __magic_name__ = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"shortest_edge": 18} ) self.assertEqual(image_processor.crop_size , {"height": 18, "width": 18} ) __magic_name__ = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 ) self.assertEqual(image_processor.size , {"shortest_edge": 42} ) self.assertEqual(image_processor.crop_size , {"height": 84, "width": 84} ) def __A ( self : List[Any] ) -> List[str]: # Initialize image_processing __magic_name__ = self.image_processing_class(**self.image_processor_dict ) # create random PIL videos __magic_name__ = prepare_video_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase ) for video in video_inputs: self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertIsInstance(video[0] , Image.Image ) # Test not batched input __magic_name__ = image_processing(video_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_videos.shape , ( 1, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched __magic_name__ = image_processing(_lowerCamelCase , return_tensors="pt" ).pixel_values self.assertEqual( encoded_videos.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) def __A ( self : Union[str, Any] ) -> Tuple: # Initialize image_processing __magic_name__ = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __magic_name__ = prepare_video_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , numpify=_lowerCamelCase ) for video in video_inputs: self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertIsInstance(video[0] , np.ndarray ) # Test not batched input __magic_name__ = image_processing(video_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_videos.shape , ( 1, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched __magic_name__ = image_processing(_lowerCamelCase , return_tensors="pt" ).pixel_values self.assertEqual( encoded_videos.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) def __A ( self : Optional[Any] ) -> Dict: # Initialize image_processing __magic_name__ = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __magic_name__ = prepare_video_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase ) for video in video_inputs: self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertIsInstance(video[0] , torch.Tensor ) # Test not batched input __magic_name__ = image_processing(video_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_videos.shape , ( 1, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched __magic_name__ = image_processing(_lowerCamelCase , return_tensors="pt" ).pixel_values self.assertEqual( encoded_videos.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , )
664
'''simple docstring''' import PIL.Image import PIL.ImageOps from packaging import version from PIL import Image if version.parse(version.parse(PIL.__version__).base_version) >= version.parse('9.1.0'): __magic_name__ : str ={ 'linear': PIL.Image.Resampling.BILINEAR, 'bilinear': PIL.Image.Resampling.BILINEAR, 'bicubic': PIL.Image.Resampling.BICUBIC, 'lanczos': PIL.Image.Resampling.LANCZOS, 'nearest': PIL.Image.Resampling.NEAREST, } else: __magic_name__ : Tuple ={ 'linear': PIL.Image.LINEAR, 'bilinear': PIL.Image.BILINEAR, 'bicubic': PIL.Image.BICUBIC, 'lanczos': PIL.Image.LANCZOS, 'nearest': PIL.Image.NEAREST, } def __snake_case ( lowerCamelCase_ : Optional[Any] ): '''simple docstring''' __magic_name__ = (images / 2 + 0.5).clamp(0 , 1 ) __magic_name__ = images.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() __magic_name__ = numpy_to_pil(lowerCamelCase_ ) return images def __snake_case ( lowerCamelCase_ : Optional[Any] ): '''simple docstring''' if images.ndim == 3: __magic_name__ = images[None, ...] __magic_name__ = (images * 255).round().astype("uint8" ) if images.shape[-1] == 1: # special case for grayscale (single channel) images __magic_name__ = [Image.fromarray(image.squeeze() , mode="L" ) for image in images] else: __magic_name__ = [Image.fromarray(lowerCamelCase_ ) for image in images] return pil_images
664
1
'''simple docstring''' import inspect import os import unittest from pathlib import Path import torch import accelerate from accelerate.test_utils import execute_subprocess_async from accelerate.test_utils.testing import run_command class UpperCamelCase_ ( unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : List[Any] = inspect.getfile(accelerate.test_utils ) UpperCAmelCase__ : Optional[int] = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_cli.py'''] ) UpperCAmelCase__ : Optional[int] = ['''accelerate''', '''launch'''] UpperCAmelCase__ : Any = Path.home() / '''.cache/huggingface/accelerate''' UpperCAmelCase__ : List[str] = '''default_config.yaml''' UpperCAmelCase__ : Optional[Any] = config_folder / config_file UpperCAmelCase__ : Any = config_folder / '''_default_config.yaml''' UpperCAmelCase__ : List[str] = Path('''tests/test_configs''' ) @classmethod def __A ( cls : Tuple ) -> Optional[int]: if cls.config_path.is_file(): cls.config_path.rename(cls.changed_path ) @classmethod def __A ( cls : Dict ) -> str: if cls.changed_path.is_file(): cls.changed_path.rename(cls.config_path ) def __A ( self : str ) -> Any: __magic_name__ = self.base_cmd if torch.cuda.is_available() and (torch.cuda.device_count() > 1): cmd += ["--multi_gpu"] execute_subprocess_async(cmd + [self.test_file_path] , env=os.environ.copy() ) def __A ( self : Tuple ) -> List[Any]: for config in sorted(self.test_config_path.glob("**/*.yaml" ) ): with self.subTest(config_file=_lowerCamelCase ): execute_subprocess_async( self.base_cmd + ["--config_file", str(_lowerCamelCase ), self.test_file_path] , env=os.environ.copy() ) def __A ( self : Dict ) -> Tuple: execute_subprocess_async(["accelerate", "test"] , env=os.environ.copy() ) class UpperCamelCase_ ( unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : List[Any] = '''test-tpu''' UpperCAmelCase__ : int = '''us-central1-a''' UpperCAmelCase__ : Tuple = '''ls''' UpperCAmelCase__ : Union[str, Any] = ['''accelerate''', '''tpu-config'''] UpperCAmelCase__ : Union[str, Any] = '''cd /usr/share''' UpperCAmelCase__ : Optional[int] = '''tests/test_samples/test_command_file.sh''' UpperCAmelCase__ : Optional[Any] = '''Running gcloud compute tpus tpu-vm ssh''' def __A ( self : Dict ) -> Any: __magic_name__ = run_command( self.cmd + ["--command", self.command, "--tpu_zone", self.tpu_zone, "--tpu_name", self.tpu_name, "--debug"] , return_stdout=_lowerCamelCase , ) self.assertIn( f'{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all' , _lowerCamelCase , ) def __A ( self : Tuple ) -> Optional[int]: __magic_name__ = run_command( self.cmd + [ "--config_file", "tests/test_configs/0_12_0.yaml", "--command", self.command, "--tpu_zone", self.tpu_zone, "--tpu_name", self.tpu_name, "--debug", ] , return_stdout=_lowerCamelCase , ) self.assertIn( f'{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all' , _lowerCamelCase , ) def __A ( self : Optional[Any] ) -> List[str]: __magic_name__ = run_command( self.cmd + ["--config_file", "tests/test_configs/latest.yaml", "--debug"] , return_stdout=_lowerCamelCase ) self.assertIn( f'{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo "hello world"; echo "this is a second command" --worker all' , _lowerCamelCase , ) def __A ( self : Union[str, Any] ) -> List[Any]: __magic_name__ = run_command( self.cmd + ["--config_file", "tests/test_configs/latest.yaml", "--command", self.command, "--debug"] , return_stdout=_lowerCamelCase , ) self.assertIn( f'{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all' , _lowerCamelCase , ) def __A ( self : Optional[Any] ) -> List[Any]: __magic_name__ = run_command( self.cmd + [ "--config_file", "tests/test_configs/latest.yaml", "--command", self.command, "--command", "echo \"Hello World\"", "--debug", ] , return_stdout=_lowerCamelCase , ) self.assertIn( f'{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls; echo "Hello World" --worker all' , _lowerCamelCase , ) def __A ( self : Optional[Any] ) -> Tuple: __magic_name__ = run_command( self.cmd + ["--config_file", "tests/test_configs/latest.yaml", "--command_file", self.command_file, "--debug"] , return_stdout=_lowerCamelCase , ) self.assertIn( f'{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo "hello world"; echo "this is a second command" --worker all' , _lowerCamelCase , ) def __A ( self : Tuple ) -> Dict: __magic_name__ = run_command( self.cmd + [ "--config_file", "tests/test_configs/0_12_0.yaml", "--command_file", self.command_file, "--tpu_zone", self.tpu_zone, "--tpu_name", self.tpu_name, "--debug", ] , return_stdout=_lowerCamelCase , ) self.assertIn( f'{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo "hello world"; echo "this is a second command" --worker all' , _lowerCamelCase , ) def __A ( self : Tuple ) -> Tuple: __magic_name__ = run_command( self.cmd + ["--config_file", "tests/test_configs/latest.yaml", "--install_accelerate", "--debug"] , return_stdout=_lowerCamelCase , ) self.assertIn( f'{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate -U; echo "hello world"; echo "this is a second command" --worker all' , _lowerCamelCase , ) def __A ( self : Optional[Any] ) -> Optional[Any]: __magic_name__ = run_command( self.cmd + [ "--config_file", "tests/test_configs/latest.yaml", "--install_accelerate", "--accelerate_version", "12.0.0", "--debug", ] , return_stdout=_lowerCamelCase , ) self.assertIn( f'{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate==12.0.0; echo "hello world"; echo "this is a second command" --worker all' , _lowerCamelCase , )
664
'''simple docstring''' from typing import Dict import numpy as np from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException if is_tf_available(): import tensorflow as tf from ..tf_utils import stable_softmax if is_torch_available(): import torch __magic_name__ : Optional[Any] =logging.get_logger(__name__) @add_end_docstrings( A , r''' top_k (`int`, defaults to 5): The number of predictions to return. targets (`str` or `List[str]`, *optional*): When passed, the model will limit the scores to the passed targets instead of looking up in the whole vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting token will be used (with a warning, and that might be slower). ''' , ) class UpperCamelCase_ ( A ): """simple docstring""" def __A ( self : Any , _lowerCamelCase : GenericTensor ) -> np.ndarray: if self.framework == "tf": __magic_name__ = tf.where(input_ids == self.tokenizer.mask_token_id ).numpy() elif self.framework == "pt": __magic_name__ = torch.nonzero(input_ids == self.tokenizer.mask_token_id , as_tuple=_lowerCamelCase ) else: raise ValueError("Unsupported framework" ) return masked_index def __A ( self : str , _lowerCamelCase : GenericTensor ) -> np.ndarray: __magic_name__ = self.get_masked_index(_lowerCamelCase ) __magic_name__ = np.prod(masked_index.shape ) if numel < 1: raise PipelineException( "fill-mask" , self.model.base_model_prefix , f'No mask_token ({self.tokenizer.mask_token}) found on the input' , ) def __A ( self : int , _lowerCamelCase : GenericTensor ) -> Any: if isinstance(_lowerCamelCase , _lowerCamelCase ): for model_input in model_inputs: self._ensure_exactly_one_mask_token(model_input["input_ids"][0] ) else: for input_ids in model_inputs["input_ids"]: self._ensure_exactly_one_mask_token(_lowerCamelCase ) def __A ( self : List[Any] , _lowerCamelCase : str , _lowerCamelCase : Any=None , **_lowerCamelCase : List[str] ) -> Dict[str, GenericTensor]: if return_tensors is None: __magic_name__ = self.framework __magic_name__ = self.tokenizer(_lowerCamelCase , return_tensors=_lowerCamelCase ) self.ensure_exactly_one_mask_token(_lowerCamelCase ) return model_inputs def __A ( self : List[str] , _lowerCamelCase : int ) -> List[Any]: __magic_name__ = self.model(**_lowerCamelCase ) __magic_name__ = model_inputs["input_ids"] return model_outputs def __A ( self : Tuple , _lowerCamelCase : List[str] , _lowerCamelCase : List[Any]=5 , _lowerCamelCase : Dict=None ) -> Dict: # Cap top_k if there are targets if target_ids is not None and target_ids.shape[0] < top_k: __magic_name__ = target_ids.shape[0] __magic_name__ = model_outputs["input_ids"][0] __magic_name__ = model_outputs["logits"] if self.framework == "tf": __magic_name__ = tf.where(input_ids == self.tokenizer.mask_token_id ).numpy()[:, 0] __magic_name__ = outputs.numpy() __magic_name__ = outputs[0, masked_index, :] __magic_name__ = stable_softmax(_lowerCamelCase , axis=-1 ) if target_ids is not None: __magic_name__ = tf.gather_nd(tf.squeeze(_lowerCamelCase , 0 ) , target_ids.reshape(-1 , 1 ) ) __magic_name__ = tf.expand_dims(_lowerCamelCase , 0 ) __magic_name__ = tf.math.top_k(_lowerCamelCase , k=_lowerCamelCase ) __magic_name__ , __magic_name__ = topk.values.numpy(), topk.indices.numpy() else: __magic_name__ = torch.nonzero(input_ids == self.tokenizer.mask_token_id , as_tuple=_lowerCamelCase ).squeeze(-1 ) # Fill mask pipeline supports only one ${mask_token} per sample __magic_name__ = outputs[0, masked_index, :] __magic_name__ = logits.softmax(dim=-1 ) if target_ids is not None: __magic_name__ = probs[..., target_ids] __magic_name__ , __magic_name__ = probs.topk(_lowerCamelCase ) __magic_name__ = [] __magic_name__ = values.shape[0] == 1 for i, (_values, _predictions) in enumerate(zip(values.tolist() , predictions.tolist() ) ): __magic_name__ = [] for v, p in zip(_values , _predictions ): # Copy is important since we're going to modify this array in place __magic_name__ = input_ids.numpy().copy() if target_ids is not None: __magic_name__ = target_ids[p].tolist() __magic_name__ = p # Filter padding out: __magic_name__ = tokens[np.where(tokens != self.tokenizer.pad_token_id )] # Originally we skip special tokens to give readable output. # For multi masks though, the other [MASK] would be removed otherwise # making the output look odd, so we add them back __magic_name__ = self.tokenizer.decode(_lowerCamelCase , skip_special_tokens=_lowerCamelCase ) __magic_name__ = {"score": v, "token": p, "token_str": self.tokenizer.decode([p] ), "sequence": sequence} row.append(_lowerCamelCase ) result.append(_lowerCamelCase ) if single_mask: return result[0] return result def __A ( self : List[Any] , _lowerCamelCase : Any , _lowerCamelCase : List[Any]=None ) -> List[str]: if isinstance(_lowerCamelCase , _lowerCamelCase ): __magic_name__ = [targets] try: __magic_name__ = self.tokenizer.get_vocab() except Exception: __magic_name__ = {} __magic_name__ = [] for target in targets: __magic_name__ = vocab.get(_lowerCamelCase , _lowerCamelCase ) if id_ is None: __magic_name__ = self.tokenizer( _lowerCamelCase , add_special_tokens=_lowerCamelCase , return_attention_mask=_lowerCamelCase , return_token_type_ids=_lowerCamelCase , max_length=1 , truncation=_lowerCamelCase , )["input_ids"] if len(_lowerCamelCase ) == 0: logger.warning( f'The specified target token `{target}` does not exist in the model vocabulary. ' "We cannot replace it with anything meaningful, ignoring it" ) continue __magic_name__ = input_ids[0] # XXX: If users encounter this pass # it becomes pretty slow, so let's make sure # The warning enables them to fix the input to # get faster performance. logger.warning( f'The specified target token `{target}` does not exist in the model vocabulary. ' f'Replacing with `{self.tokenizer.convert_ids_to_tokens(id_ )}`.' ) target_ids.append(id_ ) __magic_name__ = list(set(_lowerCamelCase ) ) if len(_lowerCamelCase ) == 0: raise ValueError("At least one target must be provided when passed." ) __magic_name__ = np.array(_lowerCamelCase ) return target_ids def __A ( self : Optional[Any] , _lowerCamelCase : Any=None , _lowerCamelCase : int=None ) -> Tuple: __magic_name__ = {} if targets is not None: __magic_name__ = self.get_target_ids(_lowerCamelCase , _lowerCamelCase ) __magic_name__ = target_ids if top_k is not None: __magic_name__ = top_k if self.tokenizer.mask_token_id is None: raise PipelineException( "fill-mask" , self.model.base_model_prefix , "The tokenizer does not define a `mask_token`." ) return {}, {}, postprocess_params def __call__( self : int , _lowerCamelCase : Any , *_lowerCamelCase : str , **_lowerCamelCase : int ) -> Optional[int]: __magic_name__ = super().__call__(_lowerCamelCase , **_lowerCamelCase ) if isinstance(_lowerCamelCase , _lowerCamelCase ) and len(_lowerCamelCase ) == 1: return outputs[0] return outputs
664
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __magic_name__ : Union[str, Any] ={ 'configuration_transfo_xl': ['TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP', 'TransfoXLConfig'], 'tokenization_transfo_xl': ['TransfoXLCorpus', 'TransfoXLTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ : Optional[int] =[ 'TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST', 'AdaptiveEmbedding', 'TransfoXLForSequenceClassification', 'TransfoXLLMHeadModel', 'TransfoXLModel', 'TransfoXLPreTrainedModel', 'load_tf_weights_in_transfo_xl', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ : List[Any] =[ 'TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFAdaptiveEmbedding', 'TFTransfoXLForSequenceClassification', 'TFTransfoXLLMHeadModel', 'TFTransfoXLMainLayer', 'TFTransfoXLModel', 'TFTransfoXLPreTrainedModel', ] if TYPE_CHECKING: from .configuration_transfo_xl import TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, TransfoXLConfig from .tokenization_transfo_xl import TransfoXLCorpus, TransfoXLTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_transfo_xl import ( TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST, AdaptiveEmbedding, TransfoXLForSequenceClassification, TransfoXLLMHeadModel, TransfoXLModel, TransfoXLPreTrainedModel, load_tf_weights_in_transfo_xl, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_transfo_xl import ( TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST, TFAdaptiveEmbedding, TFTransfoXLForSequenceClassification, TFTransfoXLLMHeadModel, TFTransfoXLMainLayer, TFTransfoXLModel, TFTransfoXLPreTrainedModel, ) else: import sys __magic_name__ : Tuple =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
664
'''simple docstring''' from __future__ import annotations def __snake_case ( lowerCamelCase_ : list[int] , lowerCamelCase_ : int ): '''simple docstring''' if len(lowerCamelCase_ ) < k or k < 0: raise ValueError("Invalid Input" ) __magic_name__ = __magic_name__ = sum(array[:k] ) for i in range(len(lowerCamelCase_ ) - k ): __magic_name__ = current_sum - array[i] + array[i + k] __magic_name__ = max(lowerCamelCase_ , lowerCamelCase_ ) return max_sum if __name__ == "__main__": from doctest import testmod from random import randint testmod() __magic_name__ : List[str] =[randint(-10_00, 10_00) for i in range(1_00)] __magic_name__ : List[str] =randint(0, 1_10) print(F'''The maximum sum of {k} consecutive elements is {max_sum_in_array(array,k)}''')
664
1
'''simple docstring''' import json import multiprocessing as mp import re from collections import defaultdict from functools import partial from typing import Dict, List, Optional, Set, Tuple, Type from datasets import Dataset from datasketch import MinHash, MinHashLSH from dpu_utils.utils.iterators import ThreadedIterator from tqdm import tqdm __magic_name__ : Dict =re.compile('[^A-Za-z_0-9]') # parameters used in DuplicationIndex __magic_name__ : int =10 __magic_name__ : Union[str, Any] =2_56 def __snake_case ( lowerCamelCase_ : List[str] ): '''simple docstring''' if len(lowerCamelCase_ ) < MIN_NUM_TOKENS: return None __magic_name__ = MinHash(num_perm=lowerCamelCase_ ) for token in set(lowerCamelCase_ ): min_hash.update(token.encode() ) return min_hash def __snake_case ( lowerCamelCase_ : str ): '''simple docstring''' return {t for t in NON_ALPHA.split(lowerCamelCase_ ) if len(t.strip() ) > 0} class UpperCamelCase_ : """simple docstring""" def __init__( self : int , *, _lowerCamelCase : float = 0.85 , ) -> Optional[Any]: __magic_name__ = duplication_jaccard_threshold __magic_name__ = NUM_PERM __magic_name__ = MinHashLSH(threshold=self._duplication_jaccard_threshold , num_perm=self._num_perm ) __magic_name__ = defaultdict(_lowerCamelCase ) def __A ( self : List[Any] , _lowerCamelCase : Tuple , _lowerCamelCase : MinHash ) -> None: __magic_name__ = self._index.query(_lowerCamelCase ) if code_key in self._index.keys: print(f'Duplicate key {code_key}' ) return self._index.insert(_lowerCamelCase , _lowerCamelCase ) if len(_lowerCamelCase ) > 0: for base_duplicate in close_duplicates: if base_duplicate in self._duplicate_clusters: self._duplicate_clusters[base_duplicate].add(_lowerCamelCase ) break else: self._duplicate_clusters[close_duplicates[0]].add(_lowerCamelCase ) def __A ( self : Union[str, Any] ) -> List[List[Dict]]: __magic_name__ = [] for base, duplicates in self._duplicate_clusters.items(): __magic_name__ = [base] + list(_lowerCamelCase ) # reformat the cluster to be a list of dict __magic_name__ = [{"base_index": el[0], "repo_name": el[1], "path": el[2]} for el in cluster] duplicate_clusters.append(_lowerCamelCase ) return duplicate_clusters def __A ( self : Tuple , _lowerCamelCase : Tuple ) -> None: __magic_name__ = self.get_duplicate_clusters() with open(_lowerCamelCase , "w" ) as f: json.dump(_lowerCamelCase , _lowerCamelCase ) def __snake_case ( lowerCamelCase_ : List[Any] ): '''simple docstring''' __magic_name__ , __magic_name__ = element __magic_name__ = get_min_hash([t for t in NON_ALPHA.split(data["content"] ) if len(t.strip() ) > 0] ) if min_hash is not None: return (index, data["repo_name"], data["path"]), min_hash def __snake_case ( lowerCamelCase_ : Type[Dataset] ): '''simple docstring''' with mp.Pool() as pool: for data in pool.imap_unordered( _compute_min_hash , ThreadedIterator(lowerCamelCase_ , max_queue_size=1_0000 ) , chunksize=100 , ): if data is not None: yield data def __snake_case ( lowerCamelCase_ : Type[Dataset] , lowerCamelCase_ : float ): '''simple docstring''' __magic_name__ = DuplicationIndex(duplication_jaccard_threshold=lowerCamelCase_ ) for filename, min_hash in tqdm(ThreadedIterator(minhash_iter(enumerate(lowerCamelCase_ ) ) , max_queue_size=100 ) ): di.add(lowerCamelCase_ , lowerCamelCase_ ) # Returns a List[Cluster] where Cluster is List[str] with the filenames. return di.get_duplicate_clusters() def __snake_case ( lowerCamelCase_ : str , lowerCamelCase_ : str ): '''simple docstring''' __magic_name__ = get_tokens(lowerCamelCase_ ) __magic_name__ = get_tokens(lowerCamelCase_ ) return len(tokensa & tokensa ) / len(tokensa | tokensa ) __magic_name__ : List[str] =None def __snake_case ( lowerCamelCase_ : Dict , lowerCamelCase_ : List[Any] ): '''simple docstring''' __magic_name__ = [] for elementa in cluster: __magic_name__ = _shared_dataset[elementa["base_index"]]["content"] for elementa in extremes: __magic_name__ = _shared_dataset[elementa["base_index"]]["content"] if jaccard_similarity(lowerCamelCase_ , lowerCamelCase_ ) >= jaccard_threshold: elementa["copies"] += 1 break else: __magic_name__ = 1 extremes.append(lowerCamelCase_ ) return extremes def __snake_case ( lowerCamelCase_ : Dict , lowerCamelCase_ : Any , lowerCamelCase_ : Union[str, Any] ): '''simple docstring''' global _shared_dataset __magic_name__ = dataset __magic_name__ = [] __magic_name__ = partial(_find_cluster_extremes_shared , jaccard_threshold=lowerCamelCase_ ) with mp.Pool() as pool: for extremes in tqdm( pool.imap_unordered( lowerCamelCase_ , lowerCamelCase_ , ) , total=len(lowerCamelCase_ ) , ): extremes_list.append(lowerCamelCase_ ) return extremes_list def __snake_case ( lowerCamelCase_ : Type[Dataset] , lowerCamelCase_ : float = 0.85 ): '''simple docstring''' __magic_name__ = make_duplicate_clusters(lowerCamelCase_ , lowerCamelCase_ ) __magic_name__ = {x["base_index"] for cluster in duplicate_clusters for x in cluster} __magic_name__ = {} __magic_name__ = find_extremes(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) for extremes in extremes_clusters: for element in extremes: __magic_name__ = element __magic_name__ = duplicate_indices - set(extreme_dict.keys() ) __magic_name__ = dataset.filter(lambda lowerCamelCase_ , lowerCamelCase_ : idx not in remove_indices , with_indices=lowerCamelCase_ ) # update duplicate_clusters for cluster in duplicate_clusters: for element in cluster: __magic_name__ = element["base_index"] in extreme_dict if element["is_extreme"]: __magic_name__ = extreme_dict[element["base_index"]]["copies"] print(F'Original dataset size: {len(lowerCamelCase_ )}' ) print(F'Number of duplicate clusters: {len(lowerCamelCase_ )}' ) print(F'Files in duplicate cluster: {len(lowerCamelCase_ )}' ) print(F'Unique files in duplicate cluster: {len(lowerCamelCase_ )}' ) print(F'Filtered dataset size: {len(lowerCamelCase_ )}' ) return ds_filter, duplicate_clusters
664
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __magic_name__ : int =logging.get_logger(__name__) __magic_name__ : List[Any] ={} class UpperCamelCase_ ( A ): """simple docstring""" UpperCAmelCase__ : int = '''llama''' UpperCAmelCase__ : Any = ['''past_key_values'''] def __init__( self : List[Any] , _lowerCamelCase : List[Any]=3_20_00 , _lowerCamelCase : Optional[Any]=40_96 , _lowerCamelCase : Tuple=1_10_08 , _lowerCamelCase : List[Any]=32 , _lowerCamelCase : Tuple=32 , _lowerCamelCase : List[str]=None , _lowerCamelCase : str="silu" , _lowerCamelCase : Optional[Any]=20_48 , _lowerCamelCase : Optional[Any]=0.02 , _lowerCamelCase : Union[str, Any]=1e-6 , _lowerCamelCase : Optional[int]=True , _lowerCamelCase : Dict=0 , _lowerCamelCase : int=1 , _lowerCamelCase : str=2 , _lowerCamelCase : List[Any]=1 , _lowerCamelCase : Optional[int]=False , _lowerCamelCase : List[str]=None , **_lowerCamelCase : List[Any] , ) -> Any: __magic_name__ = vocab_size __magic_name__ = max_position_embeddings __magic_name__ = hidden_size __magic_name__ = intermediate_size __magic_name__ = num_hidden_layers __magic_name__ = num_attention_heads # for backward compatibility if num_key_value_heads is None: __magic_name__ = num_attention_heads __magic_name__ = num_key_value_heads __magic_name__ = hidden_act __magic_name__ = initializer_range __magic_name__ = rms_norm_eps __magic_name__ = pretraining_tp __magic_name__ = use_cache __magic_name__ = rope_scaling self._rope_scaling_validation() super().__init__( pad_token_id=_lowerCamelCase , bos_token_id=_lowerCamelCase , eos_token_id=_lowerCamelCase , tie_word_embeddings=_lowerCamelCase , **_lowerCamelCase , ) def __A ( self : Union[str, Any] ) -> List[Any]: if self.rope_scaling is None: return if not isinstance(self.rope_scaling , _lowerCamelCase ) or len(self.rope_scaling ) != 2: raise ValueError( "`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, " f'got {self.rope_scaling}' ) __magic_name__ = self.rope_scaling.get("type" , _lowerCamelCase ) __magic_name__ = self.rope_scaling.get("factor" , _lowerCamelCase ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( f'`rope_scaling`\'s name field must be one of [\'linear\', \'dynamic\'], got {rope_scaling_type}' ) if rope_scaling_factor is None or not isinstance(_lowerCamelCase , _lowerCamelCase ) or rope_scaling_factor <= 1.0: raise ValueError(f'`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}' )
664
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices __magic_name__ : List[str] =logging.get_logger(__name__) __magic_name__ : List[str] ={ 'microsoft/focalnet-tiny': 'https://huggingface.co/microsoft/focalnet-tiny/resolve/main/config.json', } class UpperCamelCase_ ( A , A ): """simple docstring""" UpperCAmelCase__ : Dict = '''focalnet''' def __init__( self : List[str] , _lowerCamelCase : Optional[Any]=2_24 , _lowerCamelCase : Tuple=4 , _lowerCamelCase : Tuple=3 , _lowerCamelCase : List[str]=96 , _lowerCamelCase : Optional[int]=False , _lowerCamelCase : List[str]=[1_92, 3_84, 7_68, 7_68] , _lowerCamelCase : Union[str, Any]=[2, 2, 6, 2] , _lowerCamelCase : List[str]=[2, 2, 2, 2] , _lowerCamelCase : Optional[int]=[3, 3, 3, 3] , _lowerCamelCase : List[str]="gelu" , _lowerCamelCase : Union[str, Any]=4.0 , _lowerCamelCase : Any=0.0 , _lowerCamelCase : Any=0.1 , _lowerCamelCase : Dict=False , _lowerCamelCase : Tuple=1e-4 , _lowerCamelCase : Tuple=False , _lowerCamelCase : Union[str, Any]=False , _lowerCamelCase : Optional[Any]=False , _lowerCamelCase : int=0.02 , _lowerCamelCase : int=1e-5 , _lowerCamelCase : Tuple=32 , _lowerCamelCase : Optional[int]=None , _lowerCamelCase : Union[str, Any]=None , **_lowerCamelCase : List[Any] , ) -> Union[str, Any]: super().__init__(**_lowerCamelCase ) __magic_name__ = image_size __magic_name__ = patch_size __magic_name__ = num_channels __magic_name__ = embed_dim __magic_name__ = use_conv_embed __magic_name__ = hidden_sizes __magic_name__ = depths __magic_name__ = focal_levels __magic_name__ = focal_windows __magic_name__ = hidden_act __magic_name__ = mlp_ratio __magic_name__ = hidden_dropout_prob __magic_name__ = drop_path_rate __magic_name__ = use_layerscale __magic_name__ = layerscale_value __magic_name__ = use_post_layernorm __magic_name__ = use_post_layernorm_in_modulation __magic_name__ = normalize_modulator __magic_name__ = initializer_range __magic_name__ = layer_norm_eps __magic_name__ = encoder_stride __magic_name__ = ["stem"] + [f'stage{idx}' for idx in range(1 , len(self.depths ) + 1 )] __magic_name__ , __magic_name__ = get_aligned_output_features_output_indices( out_features=_lowerCamelCase , out_indices=_lowerCamelCase , stage_names=self.stage_names )
664
'''simple docstring''' __magic_name__ : Dict =8.3_1_4_4_6_2 # Unit - J mol-1 K-1 def __snake_case ( lowerCamelCase_ : float , lowerCamelCase_ : float , lowerCamelCase_ : float ): '''simple docstring''' if moles < 0 or kelvin < 0 or volume < 0: raise ValueError("Invalid inputs. Enter positive value." ) return moles * kelvin * UNIVERSAL_GAS_CONSTANT / volume def __snake_case ( lowerCamelCase_ : float , lowerCamelCase_ : float , lowerCamelCase_ : float ): '''simple docstring''' if moles < 0 or kelvin < 0 or pressure < 0: raise ValueError("Invalid inputs. Enter positive value." ) return moles * kelvin * UNIVERSAL_GAS_CONSTANT / pressure if __name__ == "__main__": from doctest import testmod testmod()
664
1
'''simple docstring''' import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_tf_available from transformers.testing_utils import require_tf if is_tf_available(): import tensorflow as tf from transformers import TensorFlowBenchmark, TensorFlowBenchmarkArguments @require_tf class UpperCamelCase_ ( unittest.TestCase ): """simple docstring""" def __A ( self : List[str] , _lowerCamelCase : List[Any] ) -> Any: for model_result in results.values(): for batch_size, sequence_length in zip(model_result["bs"] , model_result["ss"] ): __magic_name__ = model_result["result"][batch_size][sequence_length] self.assertIsNotNone(_lowerCamelCase ) def __A ( self : Tuple ) -> List[str]: __magic_name__ = "sshleifer/tiny-gpt2" __magic_name__ = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=_lowerCamelCase , inference=_lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , eager_mode=_lowerCamelCase , multi_process=_lowerCamelCase , ) __magic_name__ = TensorFlowBenchmark(_lowerCamelCase ) __magic_name__ = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __A ( self : Tuple ) -> List[Any]: __magic_name__ = "sgugger/tiny-distilbert-classification" __magic_name__ = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=_lowerCamelCase , inference=_lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_lowerCamelCase , only_pretrain_model=_lowerCamelCase , ) __magic_name__ = TensorFlowBenchmark(_lowerCamelCase ) __magic_name__ = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __A ( self : List[Any] ) -> str: __magic_name__ = "sshleifer/tiny-gpt2" __magic_name__ = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=_lowerCamelCase , inference=_lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_lowerCamelCase , ) __magic_name__ = TensorFlowBenchmark(_lowerCamelCase ) __magic_name__ = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __A ( self : Union[str, Any] ) -> Tuple: __magic_name__ = "sshleifer/tiny-gpt2" __magic_name__ = AutoConfig.from_pretrained(_lowerCamelCase ) __magic_name__ = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=_lowerCamelCase , inference=_lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , eager_mode=_lowerCamelCase , multi_process=_lowerCamelCase , ) __magic_name__ = TensorFlowBenchmark(_lowerCamelCase , [config] ) __magic_name__ = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __A ( self : Any ) -> str: __magic_name__ = "sshleifer/tiny-gpt2" __magic_name__ = AutoConfig.from_pretrained(_lowerCamelCase ) __magic_name__ = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=_lowerCamelCase , inference=_lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_lowerCamelCase , ) __magic_name__ = TensorFlowBenchmark(_lowerCamelCase , [config] ) __magic_name__ = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __A ( self : Dict ) -> str: __magic_name__ = "sshleifer/tiny-gpt2" __magic_name__ = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=_lowerCamelCase , inference=_lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_lowerCamelCase , ) __magic_name__ = TensorFlowBenchmark(_lowerCamelCase ) __magic_name__ = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def __A ( self : Any ) -> Tuple: __magic_name__ = "sshleifer/tiny-gpt2" __magic_name__ = AutoConfig.from_pretrained(_lowerCamelCase ) __magic_name__ = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=_lowerCamelCase , inference=_lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_lowerCamelCase , ) __magic_name__ = TensorFlowBenchmark(_lowerCamelCase , [config] ) __magic_name__ = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def __A ( self : Optional[int] ) -> Any: __magic_name__ = "patrickvonplaten/t5-tiny-random" __magic_name__ = AutoConfig.from_pretrained(_lowerCamelCase ) __magic_name__ = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=_lowerCamelCase , inference=_lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_lowerCamelCase , ) __magic_name__ = TensorFlowBenchmark(_lowerCamelCase , configs=[config] ) __magic_name__ = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) @unittest.skipIf(is_tf_available() and len(tf.config.list_physical_devices("GPU" ) ) == 0 , "Cannot do xla on CPU." ) def __A ( self : str ) -> str: __magic_name__ = "sshleifer/tiny-gpt2" __magic_name__ = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=_lowerCamelCase , inference=_lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , use_xla=_lowerCamelCase , multi_process=_lowerCamelCase , ) __magic_name__ = TensorFlowBenchmark(_lowerCamelCase ) __magic_name__ = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __A ( self : Any ) -> str: __magic_name__ = "sshleifer/tiny-gpt2" with tempfile.TemporaryDirectory() as tmp_dir: __magic_name__ = TensorFlowBenchmarkArguments( models=[MODEL_ID] , inference=_lowerCamelCase , save_to_csv=_lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , inference_time_csv_file=os.path.join(_lowerCamelCase , "inf_time.csv" ) , inference_memory_csv_file=os.path.join(_lowerCamelCase , "inf_mem.csv" ) , env_info_csv_file=os.path.join(_lowerCamelCase , "env.csv" ) , multi_process=_lowerCamelCase , ) __magic_name__ = TensorFlowBenchmark(_lowerCamelCase ) benchmark.run() self.assertTrue(Path(os.path.join(_lowerCamelCase , "inf_time.csv" ) ).exists() ) self.assertTrue(Path(os.path.join(_lowerCamelCase , "inf_mem.csv" ) ).exists() ) self.assertTrue(Path(os.path.join(_lowerCamelCase , "env.csv" ) ).exists() ) def __A ( self : int ) -> List[Any]: __magic_name__ = "sshleifer/tiny-gpt2" def _check_summary_is_not_empty(_lowerCamelCase : List[str] ): self.assertTrue(hasattr(_lowerCamelCase , "sequential" ) ) self.assertTrue(hasattr(_lowerCamelCase , "cumulative" ) ) self.assertTrue(hasattr(_lowerCamelCase , "current" ) ) self.assertTrue(hasattr(_lowerCamelCase , "total" ) ) with tempfile.TemporaryDirectory() as tmp_dir: __magic_name__ = TensorFlowBenchmarkArguments( models=[MODEL_ID] , inference=_lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , log_filename=os.path.join(_lowerCamelCase , "log.txt" ) , log_print=_lowerCamelCase , trace_memory_line_by_line=_lowerCamelCase , eager_mode=_lowerCamelCase , multi_process=_lowerCamelCase , ) __magic_name__ = TensorFlowBenchmark(_lowerCamelCase ) __magic_name__ = benchmark.run() _check_summary_is_not_empty(result.inference_summary ) self.assertTrue(Path(os.path.join(_lowerCamelCase , "log.txt" ) ).exists() )
664
'''simple docstring''' import logging import os from typing import List, TextIO, Union from conllu import parse_incr from utils_ner import InputExample, Split, TokenClassificationTask __magic_name__ : List[Any] =logging.getLogger(__name__) class UpperCamelCase_ ( A ): """simple docstring""" def __init__( self : Optional[Any] , _lowerCamelCase : str=-1 ) -> List[str]: # in NER datasets, the last column is usually reserved for NER label __magic_name__ = label_idx def __A ( self : Any , _lowerCamelCase : str , _lowerCamelCase : Union[Split, str] ) -> List[InputExample]: if isinstance(_lowerCamelCase , _lowerCamelCase ): __magic_name__ = mode.value __magic_name__ = os.path.join(_lowerCamelCase , f'{mode}.txt' ) __magic_name__ = 1 __magic_name__ = [] with open(_lowerCamelCase , encoding="utf-8" ) as f: __magic_name__ = [] __magic_name__ = [] for line in f: if line.startswith("-DOCSTART-" ) or line == "" or line == "\n": if words: examples.append(InputExample(guid=f'{mode}-{guid_index}' , words=_lowerCamelCase , labels=_lowerCamelCase ) ) guid_index += 1 __magic_name__ = [] __magic_name__ = [] else: __magic_name__ = line.split(" " ) words.append(splits[0] ) if len(_lowerCamelCase ) > 1: labels.append(splits[self.label_idx].replace("\n" , "" ) ) else: # Examples could have no label for mode = "test" labels.append("O" ) if words: examples.append(InputExample(guid=f'{mode}-{guid_index}' , words=_lowerCamelCase , labels=_lowerCamelCase ) ) return examples def __A ( self : Optional[Any] , _lowerCamelCase : TextIO , _lowerCamelCase : TextIO , _lowerCamelCase : List ) -> Union[str, Any]: __magic_name__ = 0 for line in test_input_reader: if line.startswith("-DOCSTART-" ) or line == "" or line == "\n": writer.write(_lowerCamelCase ) if not preds_list[example_id]: example_id += 1 elif preds_list[example_id]: __magic_name__ = line.split()[0] + " " + preds_list[example_id].pop(0 ) + "\n" writer.write(_lowerCamelCase ) else: logger.warning("Maximum sequence length exceeded: No prediction for '%s'." , line.split()[0] ) def __A ( self : Tuple , _lowerCamelCase : str ) -> List[str]: if path: with open(_lowerCamelCase , "r" ) as f: __magic_name__ = f.read().splitlines() if "O" not in labels: __magic_name__ = ["O"] + labels return labels else: return ["O", "B-MISC", "I-MISC", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC"] class UpperCamelCase_ ( A ): """simple docstring""" def __init__( self : int ) -> str: # in CONLL2003 dataset chunk column is second-to-last super().__init__(label_idx=-2 ) def __A ( self : int , _lowerCamelCase : str ) -> List[str]: if path: with open(_lowerCamelCase , "r" ) as f: __magic_name__ = f.read().splitlines() if "O" not in labels: __magic_name__ = ["O"] + labels return labels else: return [ "O", "B-ADVP", "B-INTJ", "B-LST", "B-PRT", "B-NP", "B-SBAR", "B-VP", "B-ADJP", "B-CONJP", "B-PP", "I-ADVP", "I-INTJ", "I-LST", "I-PRT", "I-NP", "I-SBAR", "I-VP", "I-ADJP", "I-CONJP", "I-PP", ] class UpperCamelCase_ ( A ): """simple docstring""" def __A ( self : List[Any] , _lowerCamelCase : Union[str, Any] , _lowerCamelCase : Union[Split, str] ) -> List[InputExample]: if isinstance(_lowerCamelCase , _lowerCamelCase ): __magic_name__ = mode.value __magic_name__ = os.path.join(_lowerCamelCase , f'{mode}.txt' ) __magic_name__ = 1 __magic_name__ = [] with open(_lowerCamelCase , encoding="utf-8" ) as f: for sentence in parse_incr(_lowerCamelCase ): __magic_name__ = [] __magic_name__ = [] for token in sentence: words.append(token["form"] ) labels.append(token["upos"] ) assert len(_lowerCamelCase ) == len(_lowerCamelCase ) if words: examples.append(InputExample(guid=f'{mode}-{guid_index}' , words=_lowerCamelCase , labels=_lowerCamelCase ) ) guid_index += 1 return examples def __A ( self : Optional[int] , _lowerCamelCase : TextIO , _lowerCamelCase : TextIO , _lowerCamelCase : List ) -> Any: __magic_name__ = 0 for sentence in parse_incr(_lowerCamelCase ): __magic_name__ = preds_list[example_id] __magic_name__ = "" for token in sentence: out += f'{token["form"]} ({token["upos"]}|{s_p.pop(0 )}) ' out += "\n" writer.write(_lowerCamelCase ) example_id += 1 def __A ( self : Dict , _lowerCamelCase : str ) -> List[str]: if path: with open(_lowerCamelCase , "r" ) as f: return f.read().splitlines() else: return [ "ADJ", "ADP", "ADV", "AUX", "CCONJ", "DET", "INTJ", "NOUN", "NUM", "PART", "PRON", "PROPN", "PUNCT", "SCONJ", "SYM", "VERB", "X", ]
664
1
'''simple docstring''' from typing import List from .keymap import KEYMAP, get_character def __snake_case ( lowerCamelCase_ : str ): '''simple docstring''' def decorator(lowerCamelCase_ : Dict ): __magic_name__ = getattr(lowerCamelCase_ , "handle_key" , [] ) handle += [key] setattr(lowerCamelCase_ , "handle_key" , lowerCamelCase_ ) return func return decorator def __snake_case ( *lowerCamelCase_ : List[str] ): '''simple docstring''' def decorator(lowerCamelCase_ : Optional[Any] ): __magic_name__ = getattr(lowerCamelCase_ , "handle_key" , [] ) handle += keys setattr(lowerCamelCase_ , "handle_key" , lowerCamelCase_ ) return func return decorator class UpperCamelCase_ ( A ): """simple docstring""" def __new__( cls : Any , _lowerCamelCase : Any , _lowerCamelCase : Optional[Any] , _lowerCamelCase : Optional[Any] ) -> Tuple: __magic_name__ = super().__new__(cls , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) if not hasattr(_lowerCamelCase , "key_handler" ): setattr(_lowerCamelCase , "key_handler" , {} ) setattr(_lowerCamelCase , "handle_input" , KeyHandler.handle_input ) for value in attrs.values(): __magic_name__ = getattr(_lowerCamelCase , "handle_key" , [] ) for key in handled_keys: __magic_name__ = value return new_cls @staticmethod def __A ( cls : Optional[int] ) -> Dict: __magic_name__ = get_character() if char != KEYMAP["undefined"]: __magic_name__ = ord(_lowerCamelCase ) __magic_name__ = cls.key_handler.get(_lowerCamelCase ) if handler: __magic_name__ = char return handler(cls ) else: return None def __snake_case ( cls : Tuple ): '''simple docstring''' return KeyHandler(cls.__name__ , cls.__bases__ , cls.__dict__.copy() )
664
'''simple docstring''' from __future__ import annotations from typing import Any class UpperCamelCase_ : """simple docstring""" def __init__( self : int , _lowerCamelCase : int , _lowerCamelCase : int , _lowerCamelCase : float = 0 ) -> None: __magic_name__ , __magic_name__ = row, column __magic_name__ = [[default_value for c in range(_lowerCamelCase )] for r in range(_lowerCamelCase )] def __str__( self : Optional[Any] ) -> str: __magic_name__ = f'Matrix consist of {self.row} rows and {self.column} columns\n' # Make string identifier __magic_name__ = 0 for row_vector in self.array: for obj in row_vector: __magic_name__ = max(_lowerCamelCase , len(str(_lowerCamelCase ) ) ) __magic_name__ = f'%{max_element_length}s' # Make string and return def single_line(_lowerCamelCase : list[float] ) -> str: nonlocal string_format_identifier __magic_name__ = "[" line += ", ".join(string_format_identifier % (obj,) for obj in row_vector ) line += "]" return line s += "\n".join(single_line(_lowerCamelCase ) for row_vector in self.array ) return s def __repr__( self : Optional[int] ) -> str: return str(self ) def __A ( self : Optional[Any] , _lowerCamelCase : tuple[int, int] ) -> bool: if not (isinstance(_lowerCamelCase , (list, tuple) ) and len(_lowerCamelCase ) == 2): return False elif not (0 <= loc[0] < self.row and 0 <= loc[1] < self.column): return False else: return True def __getitem__( self : Optional[int] , _lowerCamelCase : tuple[int, int] ) -> Any: assert self.validate_indicies(_lowerCamelCase ) return self.array[loc[0]][loc[1]] def __setitem__( self : Tuple , _lowerCamelCase : tuple[int, int] , _lowerCamelCase : float ) -> None: assert self.validate_indicies(_lowerCamelCase ) __magic_name__ = value def __add__( self : Union[str, Any] , _lowerCamelCase : Matrix ) -> Matrix: assert isinstance(_lowerCamelCase , _lowerCamelCase ) assert self.row == another.row and self.column == another.column # Add __magic_name__ = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): __magic_name__ = self[r, c] + another[r, c] return result def __neg__( self : int ) -> Matrix: __magic_name__ = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): __magic_name__ = -self[r, c] return result def __sub__( self : Optional[int] , _lowerCamelCase : Matrix ) -> Matrix: return self + (-another) def __mul__( self : Optional[int] , _lowerCamelCase : int | float | Matrix ) -> Matrix: if isinstance(_lowerCamelCase , (int, float) ): # Scalar multiplication __magic_name__ = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): __magic_name__ = self[r, c] * another return result elif isinstance(_lowerCamelCase , _lowerCamelCase ): # Matrix multiplication assert self.column == another.row __magic_name__ = Matrix(self.row , another.column ) for r in range(self.row ): for c in range(another.column ): for i in range(self.column ): result[r, c] += self[r, i] * another[i, c] return result else: __magic_name__ = f'Unsupported type given for another ({type(_lowerCamelCase )})' raise TypeError(_lowerCamelCase ) def __A ( self : Optional[int] ) -> Matrix: __magic_name__ = Matrix(self.column , self.row ) for r in range(self.row ): for c in range(self.column ): __magic_name__ = self[r, c] return result def __A ( self : int , _lowerCamelCase : Matrix , _lowerCamelCase : Matrix ) -> Any: assert isinstance(_lowerCamelCase , _lowerCamelCase ) and isinstance(_lowerCamelCase , _lowerCamelCase ) assert self.row == self.column == u.row == v.row # u, v should be column vector assert u.column == v.column == 1 # u, v should be column vector # Calculate __magic_name__ = v.transpose() __magic_name__ = (v_t * self * u)[0, 0] + 1 if numerator_factor == 0: return None # It's not invertable return self - ((self * u) * (v_t * self) * (1.0 / numerator_factor)) # Testing if __name__ == "__main__": def __snake_case ( ): '''simple docstring''' __magic_name__ = Matrix(3 , 3 , 0 ) for i in range(3 ): __magic_name__ = 1 print(F'a^(-1) is {ainv}' ) # u, v __magic_name__ = Matrix(3 , 1 , 0 ) __magic_name__ , __magic_name__ , __magic_name__ = 1, 2, -3 __magic_name__ = Matrix(3 , 1 , 0 ) __magic_name__ , __magic_name__ , __magic_name__ = 4, -2, 5 print(F'u is {u}' ) print(F'v is {v}' ) print(F'uv^T is {u * v.transpose()}' ) # Sherman Morrison print(F'(a + uv^T)^(-1) is {ainv.sherman_morrison(lowerCamelCase_ , lowerCamelCase_ )}' ) def __snake_case ( ): '''simple docstring''' import doctest doctest.testmod() testa()
664
1
'''simple docstring''' from __future__ import annotations import sys from collections import deque from typing import Generic, TypeVar __magic_name__ : List[str] =TypeVar('T') class UpperCamelCase_ ( Generic[T] ): """simple docstring""" UpperCAmelCase__ : deque[T] # Cache store of keys UpperCAmelCase__ : set[T] # References of the keys in cache UpperCAmelCase__ : int = 10 # Maximum capacity of cache def __init__( self : Dict , _lowerCamelCase : int ) -> None: __magic_name__ = deque() __magic_name__ = set() if not n: __magic_name__ = sys.maxsize elif n < 0: raise ValueError("n should be an integer greater than 0." ) else: __magic_name__ = n def __A ( self : Dict , _lowerCamelCase : T ) -> None: if x not in self.key_reference: if len(self.dq_store ) == LRUCache._MAX_CAPACITY: __magic_name__ = self.dq_store.pop() self.key_reference.remove(_lowerCamelCase ) else: self.dq_store.remove(_lowerCamelCase ) self.dq_store.appendleft(_lowerCamelCase ) self.key_reference.add(_lowerCamelCase ) def __A ( self : List[str] ) -> None: for k in self.dq_store: print(_lowerCamelCase ) def __repr__( self : List[str] ) -> str: return f'LRUCache({self._MAX_CAPACITY}) => {list(self.dq_store )}' if __name__ == "__main__": import doctest doctest.testmod() __magic_name__ : LRUCache[str | int] =LRUCache(4) lru_cache.refer('A') lru_cache.refer(2) lru_cache.refer(3) lru_cache.refer('A') lru_cache.refer(4) lru_cache.refer(5) lru_cache.display() print(lru_cache) assert str(lru_cache) == "LRUCache(4) => [5, 4, 'A', 3]"
664
'''simple docstring''' import argparse import logging from collections import namedtuple import torch from model_bertabs import BertAbsSummarizer from models.model_builder import AbsSummarizer # The authors' implementation from transformers import BertTokenizer logging.basicConfig(level=logging.INFO) __magic_name__ : List[Any] =logging.getLogger(__name__) __magic_name__ : int ='Hello world! cécé herlolip' __magic_name__ : List[Any] =namedtuple( 'BertAbsConfig', [ 'temp_dir', 'large', 'use_bert_emb', 'finetune_bert', 'encoder', 'share_emb', 'max_pos', 'enc_layers', 'enc_hidden_size', 'enc_heads', 'enc_ff_size', 'enc_dropout', 'dec_layers', 'dec_hidden_size', 'dec_heads', 'dec_ff_size', 'dec_dropout', ], ) def __snake_case ( lowerCamelCase_ : Optional[int] , lowerCamelCase_ : Dict ): '''simple docstring''' __magic_name__ = BertAbsConfig( temp_dir="." , finetune_bert=lowerCamelCase_ , large=lowerCamelCase_ , share_emb=lowerCamelCase_ , use_bert_emb=lowerCamelCase_ , encoder="bert" , max_pos=512 , enc_layers=6 , enc_hidden_size=512 , enc_heads=8 , enc_ff_size=512 , enc_dropout=0.2 , dec_layers=6 , dec_hidden_size=768 , dec_heads=8 , dec_ff_size=2048 , dec_dropout=0.2 , ) __magic_name__ = torch.load(lowerCamelCase_ , lambda lowerCamelCase_ , lowerCamelCase_ : storage ) __magic_name__ = AbsSummarizer(lowerCamelCase_ , torch.device("cpu" ) , lowerCamelCase_ ) original.eval() __magic_name__ = BertAbsSummarizer(lowerCamelCase_ , torch.device("cpu" ) ) new_model.eval() # ------------------- # Convert the weights # ------------------- logging.info("convert the model" ) new_model.bert.load_state_dict(original.bert.state_dict() ) new_model.decoder.load_state_dict(original.decoder.state_dict() ) new_model.generator.load_state_dict(original.generator.state_dict() ) # ---------------------------------- # Make sure the outpus are identical # ---------------------------------- logging.info("Make sure that the models' outputs are identical" ) __magic_name__ = BertTokenizer.from_pretrained("bert-base-uncased" ) # prepare the model inputs __magic_name__ = tokenizer.encode("This is sample éàalj'-." ) encoder_input_ids.extend([tokenizer.pad_token_id] * (512 - len(lowerCamelCase_ )) ) __magic_name__ = torch.tensor(lowerCamelCase_ ).unsqueeze(0 ) __magic_name__ = tokenizer.encode("This is sample 3 éàalj'-." ) decoder_input_ids.extend([tokenizer.pad_token_id] * (512 - len(lowerCamelCase_ )) ) __magic_name__ = torch.tensor(lowerCamelCase_ ).unsqueeze(0 ) # failsafe to make sure the weights reset does not affect the # loaded weights. assert torch.max(torch.abs(original.generator[0].weight - new_model.generator[0].weight ) ) == 0 # forward pass __magic_name__ = encoder_input_ids __magic_name__ = decoder_input_ids __magic_name__ = __magic_name__ = None __magic_name__ = None __magic_name__ = __magic_name__ = None __magic_name__ = __magic_name__ = None __magic_name__ = None # The original model does not apply the geneator layer immediatly but rather in # the beam search (where it combines softmax + linear layer). Since we already # apply the softmax in our generation process we only apply the linear layer here. # We make sure that the outputs of the full stack are identical __magic_name__ = original(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )[0] __magic_name__ = original.generator(lowerCamelCase_ ) __magic_name__ = new_model( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )[0] __magic_name__ = new_model.generator(lowerCamelCase_ ) __magic_name__ = torch.max(torch.abs(output_converted_model - output_original_model ) ).item() print("Maximum absolute difference beween weights: {:.2f}".format(lowerCamelCase_ ) ) __magic_name__ = torch.max(torch.abs(output_converted_generator - output_original_generator ) ).item() print("Maximum absolute difference beween weights: {:.2f}".format(lowerCamelCase_ ) ) __magic_name__ = torch.allclose(lowerCamelCase_ , lowerCamelCase_ , atol=1e-3 ) if are_identical: logging.info("all weights are equal up to 1e-3" ) else: raise ValueError("the weights are different. The new model is likely different from the original one." ) # The model has been saved with torch.save(model) and this is bound to the exact # directory structure. We save the state_dict instead. logging.info("saving the model's state dictionary" ) torch.save( new_model.state_dict() , "./bertabs-finetuned-cnndm-extractive-abstractive-summarization/pytorch_model.bin" ) if __name__ == "__main__": __magic_name__ : Dict =argparse.ArgumentParser() parser.add_argument( '--bertabs_checkpoint_path', default=None, type=str, required=True, help='Path the official PyTorch dump.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.', ) __magic_name__ : Any =parser.parse_args() convert_bertabs_checkpoints( args.bertabs_checkpoint_path, args.pytorch_dump_folder_path, )
664
1
'''simple docstring''' def __snake_case ( lowerCamelCase_ : list[list[int | float]] ): '''simple docstring''' __magic_name__ = len(lowerCamelCase_ ) __magic_name__ = len(matrix[0] ) __magic_name__ = min(lowerCamelCase_ , lowerCamelCase_ ) for row in range(lowerCamelCase_ ): # Check if diagonal element is not zero if matrix[row][row] != 0: # Eliminate all the elements below the diagonal for col in range(row + 1 , lowerCamelCase_ ): __magic_name__ = matrix[col][row] / matrix[row][row] for i in range(lowerCamelCase_ , lowerCamelCase_ ): matrix[col][i] -= multiplier * matrix[row][i] else: # Find a non-zero diagonal element to swap rows __magic_name__ = True for i in range(row + 1 , lowerCamelCase_ ): if matrix[i][row] != 0: __magic_name__ , __magic_name__ = matrix[i], matrix[row] __magic_name__ = False break if reduce: rank -= 1 for i in range(lowerCamelCase_ ): __magic_name__ = matrix[i][rank] # Reduce the row pointer by one to stay on the same row row -= 1 return rank if __name__ == "__main__": import doctest doctest.testmod()
664
'''simple docstring''' import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.generation import DisjunctiveConstraint @require_torch class UpperCamelCase_ ( unittest.TestCase ): """simple docstring""" def __A ( self : List[str] ) -> str: # For consistency across different places the DisjunctiveConstraint is called, # dc.token_ids is a list of integers. It is also initialized only by integers. __magic_name__ = [[1, 2, 4], [1, 2, 3, 4]] __magic_name__ = DisjunctiveConstraint(_lowerCamelCase ) self.assertTrue(isinstance(dc.token_ids , _lowerCamelCase ) ) with self.assertRaises(_lowerCamelCase ): DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]] ) ) with self.assertRaises(_lowerCamelCase ): DisjunctiveConstraint([torch.LongTensor([1, 2, 4] ), torch.LongTensor([1, 2, 3, 4, 5] )] ) def __A ( self : List[Any] ) -> str: # We can't have constraints that are complete subsets of another. This leads to a preverse # interpretation of "constraint fulfillment": does generating [1,2,3] fulfill the constraint? # It would mean that it generated [1,2] which fulfills it, but it's in the middle of potentially # fulfilling [1,2,3,4]. If we believe that [1,2,3] does fulfill the constraint, then the algorithm # will necessarily never reach [1,2,3,4], giving users a false sense of control (better to just not allow it). __magic_name__ = [[1, 2], [1, 2, 3, 4]] with self.assertRaises(_lowerCamelCase ): DisjunctiveConstraint(_lowerCamelCase ) # fails here def __A ( self : List[Any] ) -> int: __magic_name__ = [[1, 2, 3], [1, 2, 4]] __magic_name__ = DisjunctiveConstraint(_lowerCamelCase ) __magic_name__ , __magic_name__ , __magic_name__ = dc.update(1 ) __magic_name__ = stepped is True and completed is False and reset is False self.assertTrue(_lowerCamelCase ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) __magic_name__ , __magic_name__ , __magic_name__ = dc.update(2 ) __magic_name__ = stepped is True and completed is False and reset is False self.assertTrue(_lowerCamelCase ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) __magic_name__ , __magic_name__ , __magic_name__ = dc.update(3 ) __magic_name__ = stepped is True and completed is True and reset is False self.assertTrue(_lowerCamelCase ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 3] ) def __A ( self : Any ) -> Union[str, Any]: __magic_name__ = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]] __magic_name__ = DisjunctiveConstraint(_lowerCamelCase ) __magic_name__ , __magic_name__ , __magic_name__ = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) __magic_name__ , __magic_name__ , __magic_name__ = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) __magic_name__ , __magic_name__ , __magic_name__ = dc.update(4 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2, 4] ) __magic_name__ , __magic_name__ , __magic_name__ = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 4, 5] ) dc.reset() __magic_name__ , __magic_name__ , __magic_name__ = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 3 ) self.assertTrue(dc.current_seq == [1] ) __magic_name__ , __magic_name__ , __magic_name__ = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 2 ) self.assertTrue(dc.current_seq == [1, 2] ) __magic_name__ , __magic_name__ , __magic_name__ = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.remaining() == 0 ) self.assertTrue(dc.current_seq == [1, 2, 5] )
664
1
'''simple docstring''' # DISCLAIMER: This code is strongly influenced by https://github.com/pesser/pytorch_diffusion # and https://github.com/hojonathanho/diffusion import math from dataclasses import dataclass from typing import List, Optional, Tuple, Union import numpy as np import torch from diffusers.configuration_utils import ConfigMixin, register_to_config from diffusers.schedulers.scheduling_utils import SchedulerMixin from diffusers.utils import BaseOutput, deprecate @dataclass # Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->DDIM class UpperCamelCase_ ( A ): """simple docstring""" UpperCAmelCase__ : torch.FloatTensor UpperCAmelCase__ : Optional[torch.FloatTensor] = None def __snake_case ( lowerCamelCase_ : str , lowerCamelCase_ : str=0.999 , lowerCamelCase_ : Any="cosine" , ): '''simple docstring''' if alpha_transform_type == "cosine": def alpha_bar_fn(lowerCamelCase_ : List[Any] ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(lowerCamelCase_ : List[str] ): return math.exp(t * -12.0 ) else: raise ValueError(F'Unsupported alpha_tranform_type: {alpha_transform_type}' ) __magic_name__ = [] for i in range(lowerCamelCase_ ): __magic_name__ = i / num_diffusion_timesteps __magic_name__ = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(lowerCamelCase_ ) / alpha_bar_fn(lowerCamelCase_ ) , lowerCamelCase_ ) ) return torch.tensor(lowerCamelCase_ , dtype=torch.floataa ) class UpperCamelCase_ ( A , A ): """simple docstring""" UpperCAmelCase__ : Dict = 1 @register_to_config def __init__( self : int , _lowerCamelCase : int = 10_00 , _lowerCamelCase : float = 0.0_001 , _lowerCamelCase : float = 0.02 , _lowerCamelCase : str = "linear" , _lowerCamelCase : Optional[Union[np.ndarray, List[float]]] = None , _lowerCamelCase : bool = True , _lowerCamelCase : bool = True , _lowerCamelCase : int = 0 , _lowerCamelCase : str = "epsilon" , _lowerCamelCase : float = 1.0 , **_lowerCamelCase : List[Any] , ) -> str: if kwargs.get("set_alpha_to_one" , _lowerCamelCase ) is not None: __magic_name__ = ( "The `set_alpha_to_one` argument is deprecated. Please use `set_alpha_to_zero` instead." ) deprecate("set_alpha_to_one" , "1.0.0" , _lowerCamelCase , standard_warn=_lowerCamelCase ) __magic_name__ = kwargs["set_alpha_to_one"] if trained_betas is not None: __magic_name__ = torch.tensor(_lowerCamelCase , dtype=torch.floataa ) elif beta_schedule == "linear": __magic_name__ = torch.linspace(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. __magic_name__ = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , _lowerCamelCase , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule __magic_name__ = betas_for_alpha_bar(_lowerCamelCase ) else: raise NotImplementedError(f'{beta_schedule} does is not implemented for {self.__class__}' ) __magic_name__ = 1.0 - self.betas __magic_name__ = torch.cumprod(self.alphas , dim=0 ) # At every step in inverted ddim, we are looking into the next alphas_cumprod # For the final step, there is no next alphas_cumprod, and the index is out of bounds # `set_alpha_to_zero` decides whether we set this parameter simply to zero # in this case, self.step() just output the predicted noise # or whether we use the final alpha of the "non-previous" one. __magic_name__ = torch.tensor(0.0 ) if set_alpha_to_zero else self.alphas_cumprod[-1] # standard deviation of the initial noise distribution __magic_name__ = 1.0 # setable values __magic_name__ = None __magic_name__ = torch.from_numpy(np.arange(0 , _lowerCamelCase ).copy().astype(np.intaa ) ) def __A ( self : Dict , _lowerCamelCase : torch.FloatTensor , _lowerCamelCase : Optional[int] = None ) -> torch.FloatTensor: return sample def __A ( self : Any , _lowerCamelCase : int , _lowerCamelCase : Union[str, torch.device] = None ) -> Optional[int]: if num_inference_steps > self.config.num_train_timesteps: raise ValueError( f'`num_inference_steps`: {num_inference_steps} cannot be larger than `self.config.train_timesteps`:' f' {self.config.num_train_timesteps} as the unet model trained with this scheduler can only handle' f' maximal {self.config.num_train_timesteps} timesteps.' ) __magic_name__ = num_inference_steps __magic_name__ = self.config.num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 __magic_name__ = (np.arange(0 , _lowerCamelCase ) * step_ratio).round().copy().astype(np.intaa ) __magic_name__ = torch.from_numpy(_lowerCamelCase ).to(_lowerCamelCase ) self.timesteps += self.config.steps_offset def __A ( self : Dict , _lowerCamelCase : torch.FloatTensor , _lowerCamelCase : int , _lowerCamelCase : torch.FloatTensor , _lowerCamelCase : float = 0.0 , _lowerCamelCase : bool = False , _lowerCamelCase : Optional[torch.FloatTensor] = None , _lowerCamelCase : bool = True , ) -> Union[DDIMSchedulerOutput, Tuple]: # 1. get previous step value (=t+1) __magic_name__ = timestep + self.config.num_train_timesteps // self.num_inference_steps # 2. compute alphas, betas # change original implementation to exactly match noise levels for analogous forward process __magic_name__ = self.alphas_cumprod[timestep] __magic_name__ = ( self.alphas_cumprod[prev_timestep] if prev_timestep < self.config.num_train_timesteps else self.final_alpha_cumprod ) __magic_name__ = 1 - alpha_prod_t # 3. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf if self.config.prediction_type == "epsilon": __magic_name__ = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 __magic_name__ = model_output elif self.config.prediction_type == "sample": __magic_name__ = model_output __magic_name__ = (sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5 elif self.config.prediction_type == "v_prediction": __magic_name__ = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output __magic_name__ = (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample else: raise ValueError( f'prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or' " `v_prediction`" ) # 4. Clip or threshold "predicted x_0" if self.config.clip_sample: __magic_name__ = pred_original_sample.clamp( -self.config.clip_sample_range , self.config.clip_sample_range ) # 5. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf __magic_name__ = (1 - alpha_prod_t_prev) ** 0.5 * pred_epsilon # 6. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf __magic_name__ = alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction if not return_dict: return (prev_sample, pred_original_sample) return DDIMSchedulerOutput(prev_sample=_lowerCamelCase , pred_original_sample=_lowerCamelCase ) def __len__( self : str ) -> Any: return self.config.num_train_timesteps
664
'''simple docstring''' import json import os import shutil import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import AutoConfig, BertConfig, GPTaConfig from transformers.configuration_utils import PretrainedConfig from transformers.testing_utils import TOKEN, USER, is_staging_test sys.path.append(str(Path(__file__).parent.parent / 'utils')) from test_module.custom_configuration import CustomConfig # noqa E402 __magic_name__ : Dict ={ 'return_dict': False, 'output_hidden_states': True, 'output_attentions': True, 'torchscript': True, 'torch_dtype': 'float16', 'use_bfloat16': True, 'tf_legacy_loss': True, 'pruned_heads': {'a': 1}, 'tie_word_embeddings': False, 'is_decoder': True, 'cross_attention_hidden_size': 1_28, 'add_cross_attention': True, 'tie_encoder_decoder': True, 'max_length': 50, 'min_length': 3, 'do_sample': True, 'early_stopping': True, 'num_beams': 3, 'num_beam_groups': 3, 'diversity_penalty': 0.5, 'temperature': 2.0, 'top_k': 10, 'top_p': 0.7, 'typical_p': 0.2, 'repetition_penalty': 0.8, 'length_penalty': 0.8, 'no_repeat_ngram_size': 5, 'encoder_no_repeat_ngram_size': 5, 'bad_words_ids': [1, 2, 3], 'num_return_sequences': 3, 'chunk_size_feed_forward': 5, 'output_scores': True, 'return_dict_in_generate': True, 'forced_bos_token_id': 2, 'forced_eos_token_id': 3, 'remove_invalid_values': True, 'architectures': ['BertModel'], 'finetuning_task': 'translation', 'id2label': {0: 'label'}, 'label2id': {'label': '0'}, 'tokenizer_class': 'BertTokenizerFast', 'prefix': 'prefix', 'bos_token_id': 6, 'pad_token_id': 7, 'eos_token_id': 8, 'sep_token_id': 9, 'decoder_start_token_id': 10, 'exponential_decay_length_penalty': (5, 1.0_1), 'suppress_tokens': [0, 1], 'begin_suppress_tokens': 2, 'task_specific_params': {'translation': 'some_params'}, 'problem_type': 'regression', } @is_staging_test class UpperCamelCase_ ( unittest.TestCase ): """simple docstring""" @classmethod def __A ( cls : Any ) -> Union[str, Any]: __magic_name__ = TOKEN HfFolder.save_token(_lowerCamelCase ) @classmethod def __A ( cls : Any ) -> Tuple: try: delete_repo(token=cls._token , repo_id="test-config" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="valid_org/test-config-org" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="test-dynamic-config" ) except HTTPError: pass def __A ( self : Optional[Any] ) -> Dict: __magic_name__ = BertConfig( vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 ) config.push_to_hub("test-config" , use_auth_token=self._token ) __magic_name__ = BertConfig.from_pretrained(f'{USER}/test-config' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(_lowerCamelCase , getattr(_lowerCamelCase , _lowerCamelCase ) ) # Reset repo delete_repo(token=self._token , repo_id="test-config" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(_lowerCamelCase , repo_id="test-config" , push_to_hub=_lowerCamelCase , use_auth_token=self._token ) __magic_name__ = BertConfig.from_pretrained(f'{USER}/test-config' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(_lowerCamelCase , getattr(_lowerCamelCase , _lowerCamelCase ) ) def __A ( self : str ) -> Optional[int]: __magic_name__ = BertConfig( vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 ) config.push_to_hub("valid_org/test-config-org" , use_auth_token=self._token ) __magic_name__ = BertConfig.from_pretrained("valid_org/test-config-org" ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(_lowerCamelCase , getattr(_lowerCamelCase , _lowerCamelCase ) ) # Reset repo delete_repo(token=self._token , repo_id="valid_org/test-config-org" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( _lowerCamelCase , repo_id="valid_org/test-config-org" , push_to_hub=_lowerCamelCase , use_auth_token=self._token ) __magic_name__ = BertConfig.from_pretrained("valid_org/test-config-org" ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(_lowerCamelCase , getattr(_lowerCamelCase , _lowerCamelCase ) ) def __A ( self : Optional[int] ) -> Union[str, Any]: CustomConfig.register_for_auto_class() __magic_name__ = CustomConfig(attribute=42 ) config.push_to_hub("test-dynamic-config" , use_auth_token=self._token ) # This has added the proper auto_map field to the config self.assertDictEqual(config.auto_map , {"AutoConfig": "custom_configuration.CustomConfig"} ) __magic_name__ = AutoConfig.from_pretrained(f'{USER}/test-dynamic-config' , trust_remote_code=_lowerCamelCase ) # Can't make an isinstance check because the new_config is from the FakeConfig class of a dynamic module self.assertEqual(new_config.__class__.__name__ , "CustomConfig" ) self.assertEqual(new_config.attribute , 42 ) class UpperCamelCase_ ( unittest.TestCase ): """simple docstring""" def __A ( self : Optional[int] ) -> Optional[Any]: __magic_name__ = GPTaConfig() # attempt to modify each of int/float/bool/str config records and verify they were updated __magic_name__ = c.n_embd + 1 # int __magic_name__ = c.resid_pdrop + 1.0 # float __magic_name__ = not c.scale_attn_weights # bool __magic_name__ = c.summary_type + "foo" # str c.update_from_string( f'n_embd={n_embd},resid_pdrop={resid_pdrop},scale_attn_weights={scale_attn_weights},summary_type={summary_type}' ) self.assertEqual(_lowerCamelCase , c.n_embd , "mismatch for key: n_embd" ) self.assertEqual(_lowerCamelCase , c.resid_pdrop , "mismatch for key: resid_pdrop" ) self.assertEqual(_lowerCamelCase , c.scale_attn_weights , "mismatch for key: scale_attn_weights" ) self.assertEqual(_lowerCamelCase , c.summary_type , "mismatch for key: summary_type" ) def __A ( self : List[Any] ) -> Union[str, Any]: __magic_name__ = PretrainedConfig() __magic_name__ = [key for key in base_config.__dict__ if key not in config_common_kwargs] # If this part of the test fails, you have arguments to addin config_common_kwargs above. self.assertListEqual( _lowerCamelCase , ["is_encoder_decoder", "_name_or_path", "_commit_hash", "transformers_version"] ) __magic_name__ = [key for key, value in config_common_kwargs.items() if value == getattr(_lowerCamelCase , _lowerCamelCase )] if len(_lowerCamelCase ) > 0: raise ValueError( "The following keys are set with the default values in" " `test_configuration_common.config_common_kwargs` pick another value for them:" f' {", ".join(_lowerCamelCase )}.' ) def __A ( self : List[Any] ) -> List[Any]: with self.assertRaises(_lowerCamelCase ): # config is in subfolder, the following should not work without specifying the subfolder __magic_name__ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert-subfolder" ) __magic_name__ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert-subfolder" , subfolder="bert" ) self.assertIsNotNone(_lowerCamelCase ) def __A ( self : Tuple ) -> int: # A mock response for an HTTP head request to emulate server down __magic_name__ = mock.Mock() __magic_name__ = 5_00 __magic_name__ = {} __magic_name__ = HTTPError __magic_name__ = {} # Download this model to make sure it's in the cache. __magic_name__ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert" ) # Under the mock environment we get a 500 error when trying to reach the model. with mock.patch("requests.Session.request" , return_value=_lowerCamelCase ) as mock_head: __magic_name__ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert" ) # This check we did call the fake head request mock_head.assert_called() def __A ( self : Union[str, Any] ) -> Dict: # This test is for deprecated behavior and can be removed in v5 __magic_name__ = BertConfig.from_pretrained( "https://huggingface.co/hf-internal-testing/tiny-random-bert/resolve/main/config.json" ) def __A ( self : Dict ) -> Optional[int]: __magic_name__ = AutoConfig.from_pretrained("bert-base-cased" ) __magic_name__ = ["config.4.0.0.json"] with tempfile.TemporaryDirectory() as tmp_dir: configuration.save_pretrained(_lowerCamelCase ) __magic_name__ = 2 json.dump(configuration.to_dict() , open(os.path.join(_lowerCamelCase , "config.4.0.0.json" ) , "w" ) ) # This should pick the new configuration file as the version of Transformers is > 4.0.0 __magic_name__ = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertEqual(new_configuration.hidden_size , 2 ) # Will need to be adjusted if we reach v42 and this test is still here. # Should pick the old configuration file as the version of Transformers is < 4.42.0 __magic_name__ = ["config.42.0.0.json"] __magic_name__ = 7_68 configuration.save_pretrained(_lowerCamelCase ) shutil.move(os.path.join(_lowerCamelCase , "config.4.0.0.json" ) , os.path.join(_lowerCamelCase , "config.42.0.0.json" ) ) __magic_name__ = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertEqual(new_configuration.hidden_size , 7_68 ) def __A ( self : Optional[int] ) -> str: # This repo has two configuration files, one for v4.0.0 and above with a different hidden size. __magic_name__ = "hf-internal-testing/test-two-configs" import transformers as new_transformers __magic_name__ = "v4.0.0" __magic_name__ , __magic_name__ = new_transformers.models.auto.AutoConfig.from_pretrained( _lowerCamelCase , return_unused_kwargs=_lowerCamelCase ) self.assertEqual(new_configuration.hidden_size , 2 ) # This checks `_configuration_file` ia not kept in the kwargs by mistake. self.assertDictEqual(_lowerCamelCase , {} ) # Testing an older version by monkey-patching the version in the module it's used. import transformers as old_transformers __magic_name__ = "v3.0.0" __magic_name__ = old_transformers.models.auto.AutoConfig.from_pretrained(_lowerCamelCase ) self.assertEqual(old_configuration.hidden_size , 7_68 )
664
1
'''simple docstring''' from __future__ import annotations def __snake_case ( lowerCamelCase_ : list ): '''simple docstring''' if len(lowerCamelCase_ ) == 0: return [] __magic_name__ , __magic_name__ = min(lowerCamelCase_ ), max(lowerCamelCase_ ) __magic_name__ = int(max_value - min_value ) + 1 __magic_name__ = [[] for _ in range(lowerCamelCase_ )] for i in my_list: buckets[int(i - min_value )].append(lowerCamelCase_ ) return [v for bucket in buckets for v in sorted(lowerCamelCase_ )] if __name__ == "__main__": from doctest import testmod testmod() assert bucket_sort([4, 5, 3, 2, 1]) == [1, 2, 3, 4, 5] assert bucket_sort([0, 1, -10, 15, 2, -2]) == [-10, -2, 0, 1, 2, 15]
664
'''simple docstring''' import unittest import numpy as np from transformers.file_utils import is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_vision from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import DPTImageProcessor class UpperCamelCase_ ( unittest.TestCase ): """simple docstring""" def __init__( self : str , _lowerCamelCase : str , _lowerCamelCase : Optional[Any]=7 , _lowerCamelCase : Optional[int]=3 , _lowerCamelCase : List[Any]=18 , _lowerCamelCase : Union[str, Any]=30 , _lowerCamelCase : Tuple=4_00 , _lowerCamelCase : Union[str, Any]=True , _lowerCamelCase : Optional[Any]=None , _lowerCamelCase : int=True , _lowerCamelCase : Dict=[0.5, 0.5, 0.5] , _lowerCamelCase : Dict=[0.5, 0.5, 0.5] , ) -> Dict: __magic_name__ = size if size is not None else {"height": 18, "width": 18} __magic_name__ = parent __magic_name__ = batch_size __magic_name__ = num_channels __magic_name__ = image_size __magic_name__ = min_resolution __magic_name__ = max_resolution __magic_name__ = do_resize __magic_name__ = size __magic_name__ = do_normalize __magic_name__ = image_mean __magic_name__ = image_std def __A ( self : int ) -> List[str]: return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, } @require_torch @require_vision class UpperCamelCase_ ( A , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Union[str, Any] = DPTImageProcessor if is_vision_available() else None def __A ( self : Dict ) -> Any: __magic_name__ = DPTImageProcessingTester(self ) @property def __A ( self : str ) -> str: return self.image_processor_tester.prepare_image_processor_dict() def __A ( self : Tuple ) -> List[str]: __magic_name__ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCamelCase , "image_mean" ) ) self.assertTrue(hasattr(_lowerCamelCase , "image_std" ) ) self.assertTrue(hasattr(_lowerCamelCase , "do_normalize" ) ) self.assertTrue(hasattr(_lowerCamelCase , "do_resize" ) ) self.assertTrue(hasattr(_lowerCamelCase , "size" ) ) def __A ( self : List[str] ) -> List[Any]: __magic_name__ = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"height": 18, "width": 18} ) __magic_name__ = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {"height": 42, "width": 42} ) def __A ( self : Union[str, Any] ) -> List[str]: # Initialize image_processing __magic_name__ = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __magic_name__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , Image.Image ) # Test not batched input __magic_name__ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) # Test batched __magic_name__ = image_processing(_lowerCamelCase , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) def __A ( self : Dict ) -> Optional[Any]: # Initialize image_processing __magic_name__ = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __magic_name__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , numpify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , np.ndarray ) # Test not batched input __magic_name__ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) # Test batched __magic_name__ = image_processing(_lowerCamelCase , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) def __A ( self : Optional[int] ) -> Dict: # Initialize image_processing __magic_name__ = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __magic_name__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , torch.Tensor ) # Test not batched input __magic_name__ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) # Test batched __magic_name__ = image_processing(_lowerCamelCase , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , )
664
1
'''simple docstring''' import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import MobileViTImageProcessor class UpperCamelCase_ ( unittest.TestCase ): """simple docstring""" def __init__( self : Dict , _lowerCamelCase : Optional[Any] , _lowerCamelCase : Union[str, Any]=7 , _lowerCamelCase : str=3 , _lowerCamelCase : List[str]=18 , _lowerCamelCase : Optional[Any]=30 , _lowerCamelCase : Dict=4_00 , _lowerCamelCase : Optional[Any]=True , _lowerCamelCase : str=None , _lowerCamelCase : Optional[Any]=True , _lowerCamelCase : Optional[int]=None , _lowerCamelCase : int=True , ) -> Tuple: __magic_name__ = size if size is not None else {"shortest_edge": 20} __magic_name__ = crop_size if crop_size is not None else {"height": 18, "width": 18} __magic_name__ = parent __magic_name__ = batch_size __magic_name__ = num_channels __magic_name__ = image_size __magic_name__ = min_resolution __magic_name__ = max_resolution __magic_name__ = do_resize __magic_name__ = size __magic_name__ = do_center_crop __magic_name__ = crop_size __magic_name__ = do_flip_channel_order def __A ( self : Optional[int] ) -> Dict: return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_flip_channel_order": self.do_flip_channel_order, } @require_torch @require_vision class UpperCamelCase_ ( A , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Optional[Any] = MobileViTImageProcessor if is_vision_available() else None def __A ( self : Optional[Any] ) -> Optional[Any]: __magic_name__ = MobileViTImageProcessingTester(self ) @property def __A ( self : str ) -> List[Any]: return self.image_processor_tester.prepare_image_processor_dict() def __A ( self : List[str] ) -> List[str]: __magic_name__ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCamelCase , "do_resize" ) ) self.assertTrue(hasattr(_lowerCamelCase , "size" ) ) self.assertTrue(hasattr(_lowerCamelCase , "do_center_crop" ) ) self.assertTrue(hasattr(_lowerCamelCase , "center_crop" ) ) self.assertTrue(hasattr(_lowerCamelCase , "do_flip_channel_order" ) ) def __A ( self : Optional[int] ) -> List[str]: __magic_name__ = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"shortest_edge": 20} ) self.assertEqual(image_processor.crop_size , {"height": 18, "width": 18} ) __magic_name__ = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 ) self.assertEqual(image_processor.size , {"shortest_edge": 42} ) self.assertEqual(image_processor.crop_size , {"height": 84, "width": 84} ) def __A ( self : Union[str, Any] ) -> int: pass def __A ( self : Dict ) -> List[Any]: # Initialize image_processing __magic_name__ = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __magic_name__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , Image.Image ) # Test not batched input __magic_name__ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched __magic_name__ = image_processing(_lowerCamelCase , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) def __A ( self : Tuple ) -> Dict: # Initialize image_processing __magic_name__ = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __magic_name__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , numpify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , np.ndarray ) # Test not batched input __magic_name__ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched __magic_name__ = image_processing(_lowerCamelCase , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) def __A ( self : Optional[int] ) -> int: # Initialize image_processing __magic_name__ = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __magic_name__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , torch.Tensor ) # Test not batched input __magic_name__ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched __magic_name__ = image_processing(_lowerCamelCase , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , )
664
'''simple docstring''' import numpy class UpperCamelCase_ : """simple docstring""" def __init__( self : Union[str, Any] , _lowerCamelCase : numpy.ndarray , _lowerCamelCase : numpy.ndarray ) -> None: __magic_name__ = input_array # Random initial weights are assigned where first argument is the # number of nodes in previous layer and second argument is the # number of nodes in the next layer. # Random initial weights are assigned. # self.input_array.shape[1] is used to represent number of nodes in input layer. # First hidden layer consists of 4 nodes. __magic_name__ = numpy.random.rand( self.input_array.shape[1] , 4 ) # Random initial values for the first hidden layer. # First hidden layer has 4 nodes. # Second hidden layer has 3 nodes. __magic_name__ = numpy.random.rand( 4 , 3 ) # Random initial values for the second hidden layer. # Second hidden layer has 3 nodes. # Output layer has 1 node. __magic_name__ = numpy.random.rand(3 , 1 ) # Real output values provided. __magic_name__ = output_array # Predicted output values by the neural network. # Predicted_output array initially consists of zeroes. __magic_name__ = numpy.zeros(output_array.shape ) def __A ( self : int ) -> numpy.ndarray: __magic_name__ = sigmoid( numpy.dot(self.input_array , self.input_layer_and_first_hidden_layer_weights ) ) # layer_between_first_hidden_layer_and_second_hidden_layer is the layer # connecting the first hidden set of nodes with the second hidden set of nodes. __magic_name__ = sigmoid( numpy.dot( self.layer_between_input_and_first_hidden_layer , self.first_hidden_layer_and_second_hidden_layer_weights , ) ) # layer_between_second_hidden_layer_and_output is the layer connecting # second hidden layer with the output node. __magic_name__ = sigmoid( numpy.dot( self.layer_between_first_hidden_layer_and_second_hidden_layer , self.second_hidden_layer_and_output_layer_weights , ) ) return self.layer_between_second_hidden_layer_and_output def __A ( self : Dict ) -> None: __magic_name__ = numpy.dot( self.layer_between_first_hidden_layer_and_second_hidden_layer.T , 2 * (self.output_array - self.predicted_output) * sigmoid_derivative(self.predicted_output ) , ) __magic_name__ = numpy.dot( self.layer_between_input_and_first_hidden_layer.T , numpy.dot( 2 * (self.output_array - self.predicted_output) * sigmoid_derivative(self.predicted_output ) , self.second_hidden_layer_and_output_layer_weights.T , ) * sigmoid_derivative( self.layer_between_first_hidden_layer_and_second_hidden_layer ) , ) __magic_name__ = numpy.dot( self.input_array.T , numpy.dot( numpy.dot( 2 * (self.output_array - self.predicted_output) * sigmoid_derivative(self.predicted_output ) , self.second_hidden_layer_and_output_layer_weights.T , ) * sigmoid_derivative( self.layer_between_first_hidden_layer_and_second_hidden_layer ) , self.first_hidden_layer_and_second_hidden_layer_weights.T , ) * sigmoid_derivative(self.layer_between_input_and_first_hidden_layer ) , ) self.input_layer_and_first_hidden_layer_weights += ( updated_input_layer_and_first_hidden_layer_weights ) self.first_hidden_layer_and_second_hidden_layer_weights += ( updated_first_hidden_layer_and_second_hidden_layer_weights ) self.second_hidden_layer_and_output_layer_weights += ( updated_second_hidden_layer_and_output_layer_weights ) def __A ( self : Optional[int] , _lowerCamelCase : numpy.ndarray , _lowerCamelCase : int , _lowerCamelCase : bool ) -> None: for iteration in range(1 , iterations + 1 ): __magic_name__ = self.feedforward() self.back_propagation() if give_loss: __magic_name__ = numpy.mean(numpy.square(output - self.feedforward() ) ) print(f'Iteration {iteration} Loss: {loss}' ) def __A ( self : Tuple , _lowerCamelCase : numpy.ndarray ) -> int: __magic_name__ = input_arr __magic_name__ = sigmoid( numpy.dot(self.array , self.input_layer_and_first_hidden_layer_weights ) ) __magic_name__ = sigmoid( numpy.dot( self.layer_between_input_and_first_hidden_layer , self.first_hidden_layer_and_second_hidden_layer_weights , ) ) __magic_name__ = sigmoid( numpy.dot( self.layer_between_first_hidden_layer_and_second_hidden_layer , self.second_hidden_layer_and_output_layer_weights , ) ) return int(self.layer_between_second_hidden_layer_and_output > 0.6 ) def __snake_case ( lowerCamelCase_ : numpy.ndarray ): '''simple docstring''' return 1 / (1 + numpy.exp(-value )) def __snake_case ( lowerCamelCase_ : numpy.ndarray ): '''simple docstring''' return (value) * (1 - (value)) def __snake_case ( ): '''simple docstring''' __magic_name__ = numpy.array( ( [0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1], ) , dtype=numpy.floataa , ) # True output values for the given input values. __magic_name__ = numpy.array(([0], [1], [1], [0], [1], [0], [0], [1]) , dtype=numpy.floataa ) # Calling neural network class. __magic_name__ = TwoHiddenLayerNeuralNetwork( input_array=lowerCamelCase_ , output_array=lowerCamelCase_ ) # Calling training function. # Set give_loss to True if you want to see loss in every iteration. neural_network.train(output=lowerCamelCase_ , iterations=10 , give_loss=lowerCamelCase_ ) return neural_network.predict(numpy.array(([1, 1, 1]) , dtype=numpy.floataa ) ) if __name__ == "__main__": example()
664
1
'''simple docstring''' from string import ascii_uppercase __magic_name__ : Dict ={char: i for i, char in enumerate(ascii_uppercase)} __magic_name__ : Union[str, Any] =dict(enumerate(ascii_uppercase)) def __snake_case ( lowerCamelCase_ : str , lowerCamelCase_ : str ): '''simple docstring''' __magic_name__ = len(lowerCamelCase_ ) __magic_name__ = 0 while True: if x == i: __magic_name__ = 0 if len(lowerCamelCase_ ) == len(lowerCamelCase_ ): break key += key[i] i += 1 return key def __snake_case ( lowerCamelCase_ : str , lowerCamelCase_ : str ): '''simple docstring''' __magic_name__ = "" __magic_name__ = 0 for letter in message: if letter == " ": cipher_text += " " else: __magic_name__ = (dicta[letter] - dicta[key_new[i]]) % 26 i += 1 cipher_text += dicta[x] return cipher_text def __snake_case ( lowerCamelCase_ : str , lowerCamelCase_ : str ): '''simple docstring''' __magic_name__ = "" __magic_name__ = 0 for letter in cipher_text: if letter == " ": or_txt += " " else: __magic_name__ = (dicta[letter] + dicta[key_new[i]] + 26) % 26 i += 1 or_txt += dicta[x] return or_txt def __snake_case ( ): '''simple docstring''' __magic_name__ = "THE GERMAN ATTACK" __magic_name__ = "SECRET" __magic_name__ = generate_key(lowerCamelCase_ , lowerCamelCase_ ) __magic_name__ = cipher_text(lowerCamelCase_ , lowerCamelCase_ ) print(F'Encrypted Text = {s}' ) print(F'Original Text = {original_text(lowerCamelCase_ , lowerCamelCase_ )}' ) if __name__ == "__main__": import doctest doctest.testmod() main()
664
'''simple docstring''' import torch from transformers import AutoModel class UpperCamelCase_ ( torch.nn.Module ): """simple docstring""" def __init__( self : Any , _lowerCamelCase : Optional[int]="sayef/fsner-bert-base-uncased" ) -> List[Any]: super(_lowerCamelCase , self ).__init__() __magic_name__ = AutoModel.from_pretrained(_lowerCamelCase , return_dict=_lowerCamelCase ) __magic_name__ = torch.nn.CosineSimilarity(3 , 1e-08 ) __magic_name__ = torch.nn.Softmax(dim=1 ) def __A ( self : Tuple , **_lowerCamelCase : Union[str, Any] ) -> Optional[int]: return self.bert(**_lowerCamelCase ).last_hidden_state def __A ( self : Dict , _lowerCamelCase : Dict ) -> Dict: return token_embeddings.sum(2 , keepdim=_lowerCamelCase ) def __A ( self : Optional[int] , _lowerCamelCase : Dict , _lowerCamelCase : str , _lowerCamelCase : Tuple=1 ) -> Optional[Any]: return self.softmax(T * self.cos(_lowerCamelCase , _lowerCamelCase ) ) def __A ( self : List[Any] , _lowerCamelCase : Optional[Any] , _lowerCamelCase : Optional[int] ) -> List[str]: __magic_name__ = W_supports["sizes"].tolist() __magic_name__ = W_supports["start_token_id"].item() __magic_name__ = W_supports["end_token_id"].item() del W_supports["sizes"] del W_supports["start_token_id"] del W_supports["end_token_id"] __magic_name__ = self.BERT(**_lowerCamelCase ) __magic_name__ = self.BERT(**_lowerCamelCase ) __magic_name__ = None __magic_name__ = None __magic_name__ = W_supports["input_ids"] == start_token_id __magic_name__ = W_supports["input_ids"] == end_token_id for i, size in enumerate(_lowerCamelCase ): if i == 0: __magic_name__ = 0 else: __magic_name__ = support_sizes[i - 1] __magic_name__ = S[s : s + size][start_token_masks[s : s + size]] __magic_name__ = S[s : s + size][end_token_masks[s : s + size]] __magic_name__ = torch.matmul(q[i] , s_start.T ).sum(1 ).softmax(0 ) __magic_name__ = torch.matmul(q[i] , s_end.T ).sum(1 ).softmax(0 ) if p_starts is not None: __magic_name__ = torch.vstack((p_starts, p_start) ) __magic_name__ = torch.vstack((p_ends, p_end) ) else: __magic_name__ = p_start __magic_name__ = p_end return p_starts, p_ends
664
1
'''simple docstring''' from typing import List, Optional, Union from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class UpperCamelCase_ ( A ): """simple docstring""" UpperCAmelCase__ : Tuple = ['''image_processor''', '''tokenizer'''] UpperCAmelCase__ : str = '''BlipImageProcessor''' UpperCAmelCase__ : Optional[int] = '''AutoTokenizer''' def __init__( self : List[str] , _lowerCamelCase : List[str] , _lowerCamelCase : int ) -> Optional[Any]: __magic_name__ = False super().__init__(_lowerCamelCase , _lowerCamelCase ) __magic_name__ = self.image_processor def __call__( self : Optional[int] , _lowerCamelCase : ImageInput = None , _lowerCamelCase : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , _lowerCamelCase : bool = True , _lowerCamelCase : Union[bool, str, PaddingStrategy] = False , _lowerCamelCase : Union[bool, str, TruncationStrategy] = None , _lowerCamelCase : Optional[int] = None , _lowerCamelCase : int = 0 , _lowerCamelCase : Optional[int] = None , _lowerCamelCase : Optional[bool] = None , _lowerCamelCase : bool = False , _lowerCamelCase : bool = False , _lowerCamelCase : bool = False , _lowerCamelCase : bool = False , _lowerCamelCase : bool = False , _lowerCamelCase : bool = True , _lowerCamelCase : Optional[Union[str, TensorType]] = None , **_lowerCamelCase : List[Any] , ) -> BatchEncoding: if images is None and text is None: raise ValueError("You have to specify either images or text." ) # Get only text if images is None: __magic_name__ = self.tokenizer __magic_name__ = self.tokenizer( text=_lowerCamelCase , add_special_tokens=_lowerCamelCase , padding=_lowerCamelCase , truncation=_lowerCamelCase , max_length=_lowerCamelCase , stride=_lowerCamelCase , pad_to_multiple_of=_lowerCamelCase , return_attention_mask=_lowerCamelCase , return_overflowing_tokens=_lowerCamelCase , return_special_tokens_mask=_lowerCamelCase , return_offsets_mapping=_lowerCamelCase , return_token_type_ids=_lowerCamelCase , return_length=_lowerCamelCase , verbose=_lowerCamelCase , return_tensors=_lowerCamelCase , **_lowerCamelCase , ) return text_encoding # add pixel_values __magic_name__ = self.image_processor(_lowerCamelCase , return_tensors=_lowerCamelCase ) if text is not None: __magic_name__ = self.tokenizer( text=_lowerCamelCase , add_special_tokens=_lowerCamelCase , padding=_lowerCamelCase , truncation=_lowerCamelCase , max_length=_lowerCamelCase , stride=_lowerCamelCase , pad_to_multiple_of=_lowerCamelCase , return_attention_mask=_lowerCamelCase , return_overflowing_tokens=_lowerCamelCase , return_special_tokens_mask=_lowerCamelCase , return_offsets_mapping=_lowerCamelCase , return_token_type_ids=_lowerCamelCase , return_length=_lowerCamelCase , verbose=_lowerCamelCase , return_tensors=_lowerCamelCase , **_lowerCamelCase , ) else: __magic_name__ = None if text_encoding is not None: encoding_image_processor.update(_lowerCamelCase ) return encoding_image_processor def __A ( self : str , *_lowerCamelCase : Union[str, Any] , **_lowerCamelCase : int ) -> List[str]: return self.tokenizer.batch_decode(*_lowerCamelCase , **_lowerCamelCase ) def __A ( self : Optional[Any] , *_lowerCamelCase : Any , **_lowerCamelCase : Optional[Any] ) -> Dict: return self.tokenizer.decode(*_lowerCamelCase , **_lowerCamelCase ) @property # Copied from transformers.models.blip.processing_blip.BlipProcessor.model_input_names def __A ( self : Union[str, Any] ) -> List[str]: __magic_name__ = self.tokenizer.model_input_names __magic_name__ = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
664
'''simple docstring''' # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from ...utils import deprecate from ..controlnet.pipeline_flax_controlnet import FlaxStableDiffusionControlNetPipeline # noqa: F401 deprecate( 'stable diffusion controlnet', '0.22.0', 'Importing `FlaxStableDiffusionControlNetPipeline` from diffusers.pipelines.stable_diffusion.flax_pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import FlaxStableDiffusionControlNetPipeline` instead.', standard_warn=False, stacklevel=3, )
664
1
'''simple docstring''' import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer import diffusers from diffusers import ( AutoencoderKL, EulerDiscreteScheduler, StableDiffusionLatentUpscalePipeline, StableDiffusionPipeline, UNetaDConditionModel, ) from diffusers.schedulers import KarrasDiffusionSchedulers from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() def __snake_case ( lowerCamelCase_ : Union[str, Any] ): '''simple docstring''' __magic_name__ = [tensor.shape for tensor in tensor_list] return all(shape == shapes[0] for shape in shapes[1:] ) class UpperCamelCase_ ( A , A , A , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Any = StableDiffusionLatentUpscalePipeline UpperCAmelCase__ : int = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - { '''height''', '''width''', '''cross_attention_kwargs''', '''negative_prompt_embeds''', '''prompt_embeds''', } UpperCAmelCase__ : Optional[int] = PipelineTesterMixin.required_optional_params - {'''num_images_per_prompt'''} UpperCAmelCase__ : List[str] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS UpperCAmelCase__ : Tuple = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess UpperCAmelCase__ : Tuple = frozenset([] ) UpperCAmelCase__ : Union[str, Any] = True @property def __A ( self : Optional[Any] ) -> int: __magic_name__ = 1 __magic_name__ = 4 __magic_name__ = (16, 16) __magic_name__ = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(_lowerCamelCase ) return image def __A ( self : Union[str, Any] ) -> Tuple: torch.manual_seed(0 ) __magic_name__ = UNetaDConditionModel( act_fn="gelu" , attention_head_dim=8 , norm_num_groups=_lowerCamelCase , block_out_channels=[32, 32, 64, 64] , time_cond_proj_dim=1_60 , conv_in_kernel=1 , conv_out_kernel=1 , cross_attention_dim=32 , down_block_types=( "KDownBlock2D", "KCrossAttnDownBlock2D", "KCrossAttnDownBlock2D", "KCrossAttnDownBlock2D", ) , in_channels=8 , mid_block_type=_lowerCamelCase , only_cross_attention=_lowerCamelCase , out_channels=5 , resnet_time_scale_shift="scale_shift" , time_embedding_type="fourier" , timestep_post_act="gelu" , up_block_types=("KCrossAttnUpBlock2D", "KCrossAttnUpBlock2D", "KCrossAttnUpBlock2D", "KUpBlock2D") , ) __magic_name__ = AutoencoderKL( block_out_channels=[32, 32, 64, 64] , in_channels=3 , out_channels=3 , down_block_types=[ "DownEncoderBlock2D", "DownEncoderBlock2D", "DownEncoderBlock2D", "DownEncoderBlock2D", ] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , ) __magic_name__ = EulerDiscreteScheduler(prediction_type="sample" ) __magic_name__ = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=10_00 , hidden_act="quick_gelu" , projection_dim=5_12 , ) __magic_name__ = CLIPTextModel(_lowerCamelCase ) __magic_name__ = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) __magic_name__ = { "unet": model.eval(), "vae": vae.eval(), "scheduler": scheduler, "text_encoder": text_encoder, "tokenizer": tokenizer, } return components def __A ( self : str , _lowerCamelCase : Optional[int] , _lowerCamelCase : List[Any]=0 ) -> Any: if str(_lowerCamelCase ).startswith("mps" ): __magic_name__ = torch.manual_seed(_lowerCamelCase ) else: __magic_name__ = torch.Generator(device=_lowerCamelCase ).manual_seed(_lowerCamelCase ) __magic_name__ = { "prompt": "A painting of a squirrel eating a burger", "image": self.dummy_image.cpu(), "generator": generator, "num_inference_steps": 2, "output_type": "numpy", } return inputs def __A ( self : Dict ) -> int: __magic_name__ = "cpu" __magic_name__ = self.get_dummy_components() __magic_name__ = self.pipeline_class(**_lowerCamelCase ) pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) __magic_name__ = self.get_dummy_inputs(_lowerCamelCase ) __magic_name__ = pipe(**_lowerCamelCase ).images __magic_name__ = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 2_56, 2_56, 3) ) __magic_name__ = np.array( [0.47_222_412, 0.41_921_633, 0.44_717_434, 0.46_874_192, 0.42_588_258, 0.46_150_726, 0.4_677_534, 0.45_583_832, 0.48_579_055] ) __magic_name__ = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(_lowerCamelCase , 1e-3 ) def __A ( self : List[str] ) -> List[Any]: super().test_attention_slicing_forward_pass(expected_max_diff=7e-3 ) def __A ( self : str ) -> Dict: super().test_cpu_offload_forward_pass(expected_max_diff=3e-3 ) def __A ( self : Any ) -> int: super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3 ) def __A ( self : str ) -> Optional[int]: super().test_inference_batch_single_identical(expected_max_diff=7e-3 ) def __A ( self : str ) -> int: super().test_pt_np_pil_outputs_equivalent(expected_max_diff=3e-3 ) def __A ( self : List[Any] ) -> Optional[int]: super().test_save_load_local(expected_max_difference=3e-3 ) def __A ( self : Union[str, Any] ) -> Tuple: super().test_save_load_optional_components(expected_max_difference=3e-3 ) def __A ( self : Union[str, Any] ) -> Any: __magic_name__ = [ "DDIMScheduler", "DDPMScheduler", "PNDMScheduler", "HeunDiscreteScheduler", "EulerAncestralDiscreteScheduler", "KDPM2DiscreteScheduler", "KDPM2AncestralDiscreteScheduler", "DPMSolverSDEScheduler", ] __magic_name__ = self.get_dummy_components() __magic_name__ = self.pipeline_class(**_lowerCamelCase ) # make sure that PNDM does not need warm-up pipe.scheduler.register_to_config(skip_prk_steps=_lowerCamelCase ) pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) __magic_name__ = self.get_dummy_inputs(_lowerCamelCase ) __magic_name__ = 2 __magic_name__ = [] for scheduler_enum in KarrasDiffusionSchedulers: if scheduler_enum.name in skip_schedulers: # no sigma schedulers are not supported # no schedulers continue __magic_name__ = getattr(_lowerCamelCase , scheduler_enum.name ) __magic_name__ = scheduler_cls.from_config(pipe.scheduler.config ) __magic_name__ = pipe(**_lowerCamelCase )[0] outputs.append(_lowerCamelCase ) assert check_same_shape(_lowerCamelCase ) @require_torch_gpu @slow class UpperCamelCase_ ( unittest.TestCase ): """simple docstring""" def __A ( self : Dict ) -> Any: super().tearDown() gc.collect() torch.cuda.empty_cache() def __A ( self : Union[str, Any] ) -> Optional[int]: __magic_name__ = torch.manual_seed(33 ) __magic_name__ = StableDiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4" , torch_dtype=torch.floataa ) pipe.to("cuda" ) __magic_name__ = StableDiffusionLatentUpscalePipeline.from_pretrained( "stabilityai/sd-x2-latent-upscaler" , torch_dtype=torch.floataa ) upscaler.to("cuda" ) __magic_name__ = "a photo of an astronaut high resolution, unreal engine, ultra realistic" __magic_name__ = pipe(_lowerCamelCase , generator=_lowerCamelCase , output_type="latent" ).images __magic_name__ = upscaler( prompt=_lowerCamelCase , image=_lowerCamelCase , num_inference_steps=20 , guidance_scale=0 , generator=_lowerCamelCase , output_type="np" , ).images[0] __magic_name__ = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/latent-upscaler/astronaut_1024.npy" ) assert np.abs((expected_image - image).mean() ) < 5e-2 def __A ( self : Union[str, Any] ) -> str: __magic_name__ = torch.manual_seed(33 ) __magic_name__ = StableDiffusionLatentUpscalePipeline.from_pretrained( "stabilityai/sd-x2-latent-upscaler" , torch_dtype=torch.floataa ) upscaler.to("cuda" ) __magic_name__ = "the temple of fire by Ross Tran and Gerardo Dottori, oil on canvas" __magic_name__ = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/latent-upscaler/fire_temple_512.png" ) __magic_name__ = upscaler( prompt=_lowerCamelCase , image=_lowerCamelCase , num_inference_steps=20 , guidance_scale=0 , generator=_lowerCamelCase , output_type="np" , ).images[0] __magic_name__ = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/latent-upscaler/fire_temple_1024.npy" ) assert np.abs((expected_image - image).max() ) < 5e-2
664
'''simple docstring''' import argparse from tax import checkpoints from transformers import AutoConfig, FlaxAutoModelForSeqaSeqLM def __snake_case ( lowerCamelCase_ : Any , lowerCamelCase_ : int , lowerCamelCase_ : Optional[Any] ): '''simple docstring''' __magic_name__ = AutoConfig.from_pretrained(lowerCamelCase_ ) __magic_name__ = FlaxAutoModelForSeqaSeqLM.from_config(config=lowerCamelCase_ ) __magic_name__ = checkpoints.load_tax_checkpoint(lowerCamelCase_ ) __magic_name__ = "wi_0" in tax_model["target"]["encoder"]["layers_0"]["mlp"] if config.model_type == "t5": __magic_name__ = "SelfAttention" if config.model_type == "longt5" and config.encoder_attention_type == "local": __magic_name__ = "LocalSelfAttention" elif config.model_type == "longt5" and config.encoder_attention_type == "transient-global": __magic_name__ = "TransientGlobalSelfAttention" else: raise ValueError( "Given config is expected to have `model_type='t5'`, or `model_type='longt5` with `encoder_attention_type`" " attribute with a value from ['local', 'transient-global]." ) # Encoder for layer_index in range(config.num_layers ): __magic_name__ = F'layers_{str(lowerCamelCase_ )}' # Self-Attention __magic_name__ = tax_model["target"]["encoder"][layer_name]["attention"]["key"]["kernel"] __magic_name__ = tax_model["target"]["encoder"][layer_name]["attention"]["out"]["kernel"] __magic_name__ = tax_model["target"]["encoder"][layer_name]["attention"]["query"]["kernel"] __magic_name__ = tax_model["target"]["encoder"][layer_name]["attention"]["value"]["kernel"] # Global input layer norm if config.model_type == "longt5" and config.encoder_attention_type == "transient-global": __magic_name__ = tax_model["target"]["encoder"][layer_name]["attention"]["T5LayerNorm_0"]["scale"] # Layer Normalization __magic_name__ = tax_model["target"]["encoder"][layer_name]["pre_attention_layer_norm"]["scale"] if split_mlp_wi: __magic_name__ = tax_model["target"]["encoder"][layer_name]["mlp"]["wi_0"]["kernel"] __magic_name__ = tax_model["target"]["encoder"][layer_name]["mlp"]["wi_1"]["kernel"] else: __magic_name__ = tax_model["target"]["encoder"][layer_name]["mlp"]["wi"]["kernel"] __magic_name__ = tax_model["target"]["encoder"][layer_name]["mlp"]["wo"]["kernel"] # Layer Normalization __magic_name__ = tax_model["target"]["encoder"][layer_name]["pre_mlp_layer_norm"]["scale"] # Assigning __magic_name__ = flax_model.params["encoder"]["block"][str(lowerCamelCase_ )]["layer"] __magic_name__ = tax_attention_key __magic_name__ = tax_attention_out __magic_name__ = tax_attention_query __magic_name__ = tax_attention_value __magic_name__ = tax_attention_layer_norm # Global input layer norm if config.model_type == "longt5" and config.encoder_attention_type == "transient-global": __magic_name__ = tax_global_layer_norm if split_mlp_wi: __magic_name__ = tax_mlp_wi_a __magic_name__ = tax_mlp_wi_a else: __magic_name__ = tax_mlp_wi __magic_name__ = tax_mlp_wo __magic_name__ = tax_mlp_layer_norm __magic_name__ = flax_model_encoder_layer_block # Only for layer 0: __magic_name__ = tax_model["target"]["encoder"]["relpos_bias"]["rel_embedding"].T __magic_name__ = tax_encoder_rel_embedding # Side/global relative position_bias + layer norm if config.model_type == "longt5" and config.encoder_attention_type == "transient-global": __magic_name__ = tax_model["target"]["encoder"]["side_relpos_bias"]["rel_embedding"].T __magic_name__ = tax_encoder_global_rel_embedding # Assigning __magic_name__ = tax_model["target"]["encoder"]["encoder_norm"]["scale"] __magic_name__ = tax_encoder_norm # Decoder for layer_index in range(config.num_layers ): __magic_name__ = F'layers_{str(lowerCamelCase_ )}' # Self-Attention __magic_name__ = tax_model["target"]["decoder"][layer_name]["self_attention"]["key"]["kernel"] __magic_name__ = tax_model["target"]["decoder"][layer_name]["self_attention"]["out"]["kernel"] __magic_name__ = tax_model["target"]["decoder"][layer_name]["self_attention"]["query"]["kernel"] __magic_name__ = tax_model["target"]["decoder"][layer_name]["self_attention"]["value"]["kernel"] # Layer Normalization __magic_name__ = tax_model["target"]["decoder"][layer_name]["pre_self_attention_layer_norm"][ "scale" ] # Encoder-Decoder-Attention __magic_name__ = tax_model["target"]["decoder"][layer_name]["encoder_decoder_attention"] __magic_name__ = tax_enc_dec_attention_module["key"]["kernel"] __magic_name__ = tax_enc_dec_attention_module["out"]["kernel"] __magic_name__ = tax_enc_dec_attention_module["query"]["kernel"] __magic_name__ = tax_enc_dec_attention_module["value"]["kernel"] # Layer Normalization __magic_name__ = tax_model["target"]["decoder"][layer_name]["pre_cross_attention_layer_norm"]["scale"] # MLP if split_mlp_wi: __magic_name__ = tax_model["target"]["decoder"][layer_name]["mlp"]["wi_0"]["kernel"] __magic_name__ = tax_model["target"]["decoder"][layer_name]["mlp"]["wi_1"]["kernel"] else: __magic_name__ = tax_model["target"]["decoder"][layer_name]["mlp"]["wi"]["kernel"] __magic_name__ = tax_model["target"]["decoder"][layer_name]["mlp"]["wo"]["kernel"] # Layer Normalization __magic_name__ = tax_model["target"]["decoder"][layer_name]["pre_mlp_layer_norm"]["scale"] # Assigning __magic_name__ = flax_model.params["decoder"]["block"][str(lowerCamelCase_ )]["layer"] __magic_name__ = tax_attention_key __magic_name__ = tax_attention_out __magic_name__ = tax_attention_query __magic_name__ = tax_attention_value __magic_name__ = tax_pre_attention_layer_norm __magic_name__ = tax_enc_dec_attention_key __magic_name__ = tax_enc_dec_attention_out __magic_name__ = tax_enc_dec_attention_query __magic_name__ = tax_enc_dec_attention_value __magic_name__ = tax_cross_layer_norm if split_mlp_wi: __magic_name__ = tax_mlp_wi_a __magic_name__ = tax_mlp_wi_a else: __magic_name__ = tax_mlp_wi __magic_name__ = tax_mlp_wo __magic_name__ = txa_mlp_layer_norm __magic_name__ = flax_model_decoder_layer_block # Decoder Normalization __magic_name__ = tax_model["target"]["decoder"]["decoder_norm"]["scale"] __magic_name__ = txa_decoder_norm # Only for layer 0: __magic_name__ = tax_model["target"]["decoder"]["relpos_bias"]["rel_embedding"].T __magic_name__ = tax_decoder_rel_embedding # Token Embeddings __magic_name__ = tax_model["target"]["token_embedder"]["embedding"] __magic_name__ = txa_token_embeddings # LM Head (only in v1.1 and LongT5 checkpoints) if "logits_dense" in tax_model["target"]["decoder"]: __magic_name__ = tax_model["target"]["decoder"]["logits_dense"]["kernel"] flax_model.save_pretrained(lowerCamelCase_ ) print("T5X Model was sucessfully converted!" ) if __name__ == "__main__": __magic_name__ : Optional[Any] =argparse.ArgumentParser() # Required parameters parser.add_argument( '--t5x_checkpoint_path', default=None, type=str, required=True, help='Path the T5X checkpoint.' ) parser.add_argument('--config_name', default=None, type=str, required=True, help='Config name of LongT5/T5 model.') parser.add_argument( '--flax_dump_folder_path', default=None, type=str, required=True, help='Path to the output FLAX model.' ) __magic_name__ : Optional[int] =parser.parse_args() convert_tax_checkpoint_to_flax(args.tax_checkpoint_path, args.config_name, args.flax_dump_folder_path)
664
1
'''simple docstring''' import inspect from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch import torch.utils.checkpoint from ...models import UNetaDModel, VQModel from ...schedulers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, ) from ...utils import PIL_INTERPOLATION, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput def __snake_case ( lowerCamelCase_ : Optional[Any] ): '''simple docstring''' __magic_name__ , __magic_name__ = image.size __magic_name__ , __magic_name__ = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 __magic_name__ = image.resize((w, h) , resample=PIL_INTERPOLATION["lanczos"] ) __magic_name__ = np.array(lowerCamelCase_ ).astype(np.floataa ) / 255.0 __magic_name__ = image[None].transpose(0 , 3 , 1 , 2 ) __magic_name__ = torch.from_numpy(lowerCamelCase_ ) return 2.0 * image - 1.0 class UpperCamelCase_ ( A ): """simple docstring""" def __init__( self : Tuple , _lowerCamelCase : VQModel , _lowerCamelCase : UNetaDModel , _lowerCamelCase : Union[ DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler, EulerDiscreteScheduler, EulerAncestralDiscreteScheduler, DPMSolverMultistepScheduler, ] , ) -> int: super().__init__() self.register_modules(vqvae=_lowerCamelCase , unet=_lowerCamelCase , scheduler=_lowerCamelCase ) @torch.no_grad() def __call__( self : Optional[int] , _lowerCamelCase : Union[torch.Tensor, PIL.Image.Image] = None , _lowerCamelCase : Optional[int] = 1 , _lowerCamelCase : Optional[int] = 1_00 , _lowerCamelCase : Optional[float] = 0.0 , _lowerCamelCase : Optional[Union[torch.Generator, List[torch.Generator]]] = None , _lowerCamelCase : Optional[str] = "pil" , _lowerCamelCase : bool = True , ) -> Union[Tuple, ImagePipelineOutput]: if isinstance(_lowerCamelCase , PIL.Image.Image ): __magic_name__ = 1 elif isinstance(_lowerCamelCase , torch.Tensor ): __magic_name__ = image.shape[0] else: raise ValueError(f'`image` has to be of type `PIL.Image.Image` or `torch.Tensor` but is {type(_lowerCamelCase )}' ) if isinstance(_lowerCamelCase , PIL.Image.Image ): __magic_name__ = preprocess(_lowerCamelCase ) __magic_name__ , __magic_name__ = image.shape[-2:] # in_channels should be 6: 3 for latents, 3 for low resolution image __magic_name__ = (batch_size, self.unet.config.in_channels // 2, height, width) __magic_name__ = next(self.unet.parameters() ).dtype __magic_name__ = randn_tensor(_lowerCamelCase , generator=_lowerCamelCase , device=self.device , dtype=_lowerCamelCase ) __magic_name__ = image.to(device=self.device , dtype=_lowerCamelCase ) # set timesteps and move to the correct device self.scheduler.set_timesteps(_lowerCamelCase , device=self.device ) __magic_name__ = self.scheduler.timesteps # scale the initial noise by the standard deviation required by the scheduler __magic_name__ = 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] __magic_name__ = "eta" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) __magic_name__ = {} if accepts_eta: __magic_name__ = eta for t in self.progress_bar(_lowerCamelCase ): # concat latents and low resolution image in the channel dimension. __magic_name__ = torch.cat([latents, image] , dim=1 ) __magic_name__ = self.scheduler.scale_model_input(_lowerCamelCase , _lowerCamelCase ) # predict the noise residual __magic_name__ = self.unet(_lowerCamelCase , _lowerCamelCase ).sample # compute the previous noisy sample x_t -> x_t-1 __magic_name__ = self.scheduler.step(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , **_lowerCamelCase ).prev_sample # decode the image latents with the VQVAE __magic_name__ = self.vqvae.decode(_lowerCamelCase ).sample __magic_name__ = torch.clamp(_lowerCamelCase , -1.0 , 1.0 ) __magic_name__ = image / 2 + 0.5 __magic_name__ = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": __magic_name__ = self.numpy_to_pil(_lowerCamelCase ) if not return_dict: return (image,) return ImagePipelineOutput(images=_lowerCamelCase )
664
'''simple docstring''' import unittest from transformers import load_tool from transformers.utils import is_torch_available if is_torch_available(): import torch from transformers.testing_utils import require_torch from .test_tools_common import ToolTesterMixin @require_torch class UpperCamelCase_ ( unittest.TestCase , A ): """simple docstring""" def __A ( self : Optional[int] ) -> Any: __magic_name__ = load_tool("text-to-speech" ) self.tool.setup() def __A ( self : Union[str, Any] ) -> int: # SpeechT5 isn't deterministic torch.manual_seed(0 ) __magic_name__ = self.tool("hey" ) __magic_name__ = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] , torch.tensor([-0.0_005_966_668_832_115_829, -0.0_003_657_640_190_795_064, -0.00_013_439_502_799_883_485] ) , ) ) def __A ( self : List[str] ) -> int: # SpeechT5 isn't deterministic torch.manual_seed(0 ) __magic_name__ = self.tool("hey" ) __magic_name__ = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] , torch.tensor([-0.0_005_966_668_832_115_829, -0.0_003_657_640_190_795_064, -0.00_013_439_502_799_883_485] ) , ) )
664
1
'''simple docstring''' import importlib import torch import yaml from omegaconf import OmegaConf from taming.models.vqgan import VQModel def __snake_case ( lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : Any=False ): '''simple docstring''' __magic_name__ = OmegaConf.load(lowerCamelCase_ ) if display: print(yaml.dump(OmegaConf.to_container(lowerCamelCase_ ) ) ) return config def __snake_case ( lowerCamelCase_ : Any , lowerCamelCase_ : Optional[Any]=None , lowerCamelCase_ : Optional[Any]=None ): '''simple docstring''' if conf_path is None: __magic_name__ = "./model_checkpoints/vqgan_only.yaml" __magic_name__ = load_config(lowerCamelCase_ , display=lowerCamelCase_ ) __magic_name__ = VQModel(**config.model.params ) if ckpt_path is None: __magic_name__ = "./model_checkpoints/vqgan_only.pt" __magic_name__ = torch.load(lowerCamelCase_ , map_location=lowerCamelCase_ ) if ".ckpt" in ckpt_path: __magic_name__ = sd["state_dict"] model.load_state_dict(lowerCamelCase_ , strict=lowerCamelCase_ ) model.to(lowerCamelCase_ ) del sd return model def __snake_case ( lowerCamelCase_ : Optional[int] , lowerCamelCase_ : Tuple ): '''simple docstring''' __magic_name__ , __magic_name__ , __magic_name__ = model.encode(lowerCamelCase_ ) print(F'VQGAN --- {model.__class__.__name__}: latent shape: {z.shape[2:]}' ) __magic_name__ = model.decode(lowerCamelCase_ ) return xrec def __snake_case ( lowerCamelCase_ : str , lowerCamelCase_ : Optional[Any]=False ): '''simple docstring''' __magic_name__ , __magic_name__ = string.rsplit("." , 1 ) if reload: __magic_name__ = importlib.import_module(lowerCamelCase_ ) importlib.reload(lowerCamelCase_ ) return getattr(importlib.import_module(lowerCamelCase_ , package=lowerCamelCase_ ) , cls ) def __snake_case ( lowerCamelCase_ : List[str] ): '''simple docstring''' if "target" not in config: raise KeyError("Expected key `target` to instantiate." ) return get_obj_from_str(config["target"] )(**config.get("params" , {} ) ) def __snake_case ( lowerCamelCase_ : str , lowerCamelCase_ : Optional[int] , lowerCamelCase_ : Tuple=True , lowerCamelCase_ : Dict=True ): '''simple docstring''' __magic_name__ = instantiate_from_config(lowerCamelCase_ ) if sd is not None: model.load_state_dict(lowerCamelCase_ ) if gpu: model.cuda() if eval_mode: model.eval() return {"model": model} def __snake_case ( lowerCamelCase_ : List[str] , lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : Dict , lowerCamelCase_ : Union[str, Any] ): '''simple docstring''' if ckpt: __magic_name__ = torch.load(lowerCamelCase_ , map_location="cpu" ) __magic_name__ = pl_sd["global_step"] print(F'loaded model from global step {global_step}.' ) else: __magic_name__ = {"state_dict": None} __magic_name__ = None __magic_name__ = load_model_from_config(config.model , pl_sd["state_dict"] , gpu=lowerCamelCase_ , eval_mode=lowerCamelCase_ )["model"] return model, global_step
664
'''simple docstring''' import json import multiprocessing as mp import re from collections import defaultdict from functools import partial from typing import Dict, List, Optional, Set, Tuple, Type from datasets import Dataset from datasketch import MinHash, MinHashLSH from dpu_utils.utils.iterators import ThreadedIterator from tqdm import tqdm __magic_name__ : Dict =re.compile('[^A-Za-z_0-9]') # parameters used in DuplicationIndex __magic_name__ : int =10 __magic_name__ : Union[str, Any] =2_56 def __snake_case ( lowerCamelCase_ : List[str] ): '''simple docstring''' if len(lowerCamelCase_ ) < MIN_NUM_TOKENS: return None __magic_name__ = MinHash(num_perm=lowerCamelCase_ ) for token in set(lowerCamelCase_ ): min_hash.update(token.encode() ) return min_hash def __snake_case ( lowerCamelCase_ : str ): '''simple docstring''' return {t for t in NON_ALPHA.split(lowerCamelCase_ ) if len(t.strip() ) > 0} class UpperCamelCase_ : """simple docstring""" def __init__( self : int , *, _lowerCamelCase : float = 0.85 , ) -> Optional[Any]: __magic_name__ = duplication_jaccard_threshold __magic_name__ = NUM_PERM __magic_name__ = MinHashLSH(threshold=self._duplication_jaccard_threshold , num_perm=self._num_perm ) __magic_name__ = defaultdict(_lowerCamelCase ) def __A ( self : List[Any] , _lowerCamelCase : Tuple , _lowerCamelCase : MinHash ) -> None: __magic_name__ = self._index.query(_lowerCamelCase ) if code_key in self._index.keys: print(f'Duplicate key {code_key}' ) return self._index.insert(_lowerCamelCase , _lowerCamelCase ) if len(_lowerCamelCase ) > 0: for base_duplicate in close_duplicates: if base_duplicate in self._duplicate_clusters: self._duplicate_clusters[base_duplicate].add(_lowerCamelCase ) break else: self._duplicate_clusters[close_duplicates[0]].add(_lowerCamelCase ) def __A ( self : Union[str, Any] ) -> List[List[Dict]]: __magic_name__ = [] for base, duplicates in self._duplicate_clusters.items(): __magic_name__ = [base] + list(_lowerCamelCase ) # reformat the cluster to be a list of dict __magic_name__ = [{"base_index": el[0], "repo_name": el[1], "path": el[2]} for el in cluster] duplicate_clusters.append(_lowerCamelCase ) return duplicate_clusters def __A ( self : Tuple , _lowerCamelCase : Tuple ) -> None: __magic_name__ = self.get_duplicate_clusters() with open(_lowerCamelCase , "w" ) as f: json.dump(_lowerCamelCase , _lowerCamelCase ) def __snake_case ( lowerCamelCase_ : List[Any] ): '''simple docstring''' __magic_name__ , __magic_name__ = element __magic_name__ = get_min_hash([t for t in NON_ALPHA.split(data["content"] ) if len(t.strip() ) > 0] ) if min_hash is not None: return (index, data["repo_name"], data["path"]), min_hash def __snake_case ( lowerCamelCase_ : Type[Dataset] ): '''simple docstring''' with mp.Pool() as pool: for data in pool.imap_unordered( _compute_min_hash , ThreadedIterator(lowerCamelCase_ , max_queue_size=1_0000 ) , chunksize=100 , ): if data is not None: yield data def __snake_case ( lowerCamelCase_ : Type[Dataset] , lowerCamelCase_ : float ): '''simple docstring''' __magic_name__ = DuplicationIndex(duplication_jaccard_threshold=lowerCamelCase_ ) for filename, min_hash in tqdm(ThreadedIterator(minhash_iter(enumerate(lowerCamelCase_ ) ) , max_queue_size=100 ) ): di.add(lowerCamelCase_ , lowerCamelCase_ ) # Returns a List[Cluster] where Cluster is List[str] with the filenames. return di.get_duplicate_clusters() def __snake_case ( lowerCamelCase_ : str , lowerCamelCase_ : str ): '''simple docstring''' __magic_name__ = get_tokens(lowerCamelCase_ ) __magic_name__ = get_tokens(lowerCamelCase_ ) return len(tokensa & tokensa ) / len(tokensa | tokensa ) __magic_name__ : List[str] =None def __snake_case ( lowerCamelCase_ : Dict , lowerCamelCase_ : List[Any] ): '''simple docstring''' __magic_name__ = [] for elementa in cluster: __magic_name__ = _shared_dataset[elementa["base_index"]]["content"] for elementa in extremes: __magic_name__ = _shared_dataset[elementa["base_index"]]["content"] if jaccard_similarity(lowerCamelCase_ , lowerCamelCase_ ) >= jaccard_threshold: elementa["copies"] += 1 break else: __magic_name__ = 1 extremes.append(lowerCamelCase_ ) return extremes def __snake_case ( lowerCamelCase_ : Dict , lowerCamelCase_ : Any , lowerCamelCase_ : Union[str, Any] ): '''simple docstring''' global _shared_dataset __magic_name__ = dataset __magic_name__ = [] __magic_name__ = partial(_find_cluster_extremes_shared , jaccard_threshold=lowerCamelCase_ ) with mp.Pool() as pool: for extremes in tqdm( pool.imap_unordered( lowerCamelCase_ , lowerCamelCase_ , ) , total=len(lowerCamelCase_ ) , ): extremes_list.append(lowerCamelCase_ ) return extremes_list def __snake_case ( lowerCamelCase_ : Type[Dataset] , lowerCamelCase_ : float = 0.85 ): '''simple docstring''' __magic_name__ = make_duplicate_clusters(lowerCamelCase_ , lowerCamelCase_ ) __magic_name__ = {x["base_index"] for cluster in duplicate_clusters for x in cluster} __magic_name__ = {} __magic_name__ = find_extremes(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) for extremes in extremes_clusters: for element in extremes: __magic_name__ = element __magic_name__ = duplicate_indices - set(extreme_dict.keys() ) __magic_name__ = dataset.filter(lambda lowerCamelCase_ , lowerCamelCase_ : idx not in remove_indices , with_indices=lowerCamelCase_ ) # update duplicate_clusters for cluster in duplicate_clusters: for element in cluster: __magic_name__ = element["base_index"] in extreme_dict if element["is_extreme"]: __magic_name__ = extreme_dict[element["base_index"]]["copies"] print(F'Original dataset size: {len(lowerCamelCase_ )}' ) print(F'Number of duplicate clusters: {len(lowerCamelCase_ )}' ) print(F'Files in duplicate cluster: {len(lowerCamelCase_ )}' ) print(F'Unique files in duplicate cluster: {len(lowerCamelCase_ )}' ) print(F'Filtered dataset size: {len(lowerCamelCase_ )}' ) return ds_filter, duplicate_clusters
664
1
'''simple docstring''' __magic_name__ : Union[str, Any] ={ 'A': ['B', 'C', 'E'], 'B': ['A', 'D', 'E'], 'C': ['A', 'F', 'G'], 'D': ['B'], 'E': ['A', 'B', 'D'], 'F': ['C'], 'G': ['C'], } def __snake_case ( lowerCamelCase_ : dict , lowerCamelCase_ : Tuple , lowerCamelCase_ : Tuple ): '''simple docstring''' __magic_name__ = set() # keep track of all the paths to be checked __magic_name__ = [[start]] # return path if start is goal if start == goal: return [start] # keeps looping until all possible paths have been checked while queue: # pop the first path from the queue __magic_name__ = queue.pop(0 ) # get the last node from the path __magic_name__ = path[-1] if node not in explored: __magic_name__ = graph[node] # go through all neighbour nodes, construct a new path and # push it into the queue for neighbour in neighbours: __magic_name__ = list(lowerCamelCase_ ) new_path.append(lowerCamelCase_ ) queue.append(lowerCamelCase_ ) # return path if neighbour is goal if neighbour == goal: return new_path # mark node as explored explored.add(lowerCamelCase_ ) # in case there's no path between the 2 nodes return [] def __snake_case ( lowerCamelCase_ : dict , lowerCamelCase_ : int , lowerCamelCase_ : Optional[Any] ): '''simple docstring''' if not graph or start not in graph or target not in graph: return -1 if start == target: return 0 __magic_name__ = [start] __magic_name__ = set(lowerCamelCase_ ) # Keep tab on distances from `start` node. __magic_name__ = {start: 0, target: -1} while queue: __magic_name__ = queue.pop(0 ) if node == target: __magic_name__ = ( dist[node] if dist[target] == -1 else min(dist[target] , dist[node] ) ) for adjacent in graph[node]: if adjacent not in visited: visited.add(lowerCamelCase_ ) queue.append(lowerCamelCase_ ) __magic_name__ = dist[node] + 1 return dist[target] if __name__ == "__main__": print(bfs_shortest_path(demo_graph, 'G', 'D')) # returns ['G', 'C', 'A', 'B', 'D'] print(bfs_shortest_path_distance(demo_graph, 'G', 'D')) # returns 4
664
'''simple docstring''' import argparse import os import gluonnlp as nlp import mxnet as mx import numpy as np import torch from gluonnlp.base import get_home_dir from gluonnlp.model.bert import BERTEncoder from gluonnlp.model.utils import _load_vocab from gluonnlp.vocab import Vocab from packaging import version from torch import nn from transformers import BertConfig, BertForMaskedLM, BertModel, RobertaTokenizer from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertSelfAttention, BertSelfOutput, ) from transformers.utils import logging if version.parse(nlp.__version__) != version.parse('0.8.3'): raise Exception('requires gluonnlp == 0.8.3') if version.parse(mx.__version__) != version.parse('1.5.0'): raise Exception('requires mxnet == 1.5.0') logging.set_verbosity_info() __magic_name__ : Optional[int] =logging.get_logger(__name__) __magic_name__ : Tuple ='The Nymphenburg Palace is a beautiful palace in Munich!' def __snake_case ( lowerCamelCase_ : str , lowerCamelCase_ : str ): '''simple docstring''' __magic_name__ = { "attention_cell": "multi_head", "num_layers": 4, "units": 1024, "hidden_size": 768, "max_length": 512, "num_heads": 8, "scaled": True, "dropout": 0.1, "use_residual": True, "embed_size": 1024, "embed_dropout": 0.1, "word_embed": None, "layer_norm_eps": 1e-5, "token_type_vocab_size": 2, } __magic_name__ = bort_4_8_768_1024_hparams # Let's construct the original Bort model here # Taken from official BERT implementation, see: # https://github.com/alexa/bort/blob/master/bort/bort.py __magic_name__ = BERTEncoder( attention_cell=predefined_args["attention_cell"] , num_layers=predefined_args["num_layers"] , units=predefined_args["units"] , hidden_size=predefined_args["hidden_size"] , max_length=predefined_args["max_length"] , num_heads=predefined_args["num_heads"] , scaled=predefined_args["scaled"] , dropout=predefined_args["dropout"] , output_attention=lowerCamelCase_ , output_all_encodings=lowerCamelCase_ , use_residual=predefined_args["use_residual"] , activation=predefined_args.get("activation" , "gelu" ) , layer_norm_eps=predefined_args.get("layer_norm_eps" , lowerCamelCase_ ) , ) # Vocab information needs to be fetched first # It's the same as RoBERTa, so RobertaTokenizer can be used later __magic_name__ = "openwebtext_ccnews_stories_books_cased" # Specify download folder to Gluonnlp's vocab __magic_name__ = os.path.join(get_home_dir() , "models" ) __magic_name__ = _load_vocab(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , cls=lowerCamelCase_ ) __magic_name__ = nlp.model.BERTModel( lowerCamelCase_ , len(lowerCamelCase_ ) , units=predefined_args["units"] , embed_size=predefined_args["embed_size"] , embed_dropout=predefined_args["embed_dropout"] , word_embed=predefined_args["word_embed"] , use_pooler=lowerCamelCase_ , use_token_type_embed=lowerCamelCase_ , token_type_vocab_size=predefined_args["token_type_vocab_size"] , use_classifier=lowerCamelCase_ , use_decoder=lowerCamelCase_ , ) original_bort.load_parameters(lowerCamelCase_ , cast_dtype=lowerCamelCase_ , ignore_extra=lowerCamelCase_ ) __magic_name__ = original_bort._collect_params_with_prefix() # Build our config 🤗 __magic_name__ = { "architectures": ["BertForMaskedLM"], "attention_probs_dropout_prob": predefined_args["dropout"], "hidden_act": "gelu", "hidden_dropout_prob": predefined_args["dropout"], "hidden_size": predefined_args["embed_size"], "initializer_range": 0.02, "intermediate_size": predefined_args["hidden_size"], "layer_norm_eps": predefined_args["layer_norm_eps"], "max_position_embeddings": predefined_args["max_length"], "model_type": "bort", "num_attention_heads": predefined_args["num_heads"], "num_hidden_layers": predefined_args["num_layers"], "pad_token_id": 1, # 2 = BERT, 1 = RoBERTa "type_vocab_size": 1, # 2 = BERT, 1 = RoBERTa "vocab_size": len(lowerCamelCase_ ), } __magic_name__ = BertConfig.from_dict(lowerCamelCase_ ) __magic_name__ = BertForMaskedLM(lowerCamelCase_ ) hf_bort_model.eval() # Parameter mapping table (Gluonnlp to Transformers) # * denotes layer index # # | Gluon Parameter | Transformers Parameter # | -------------------------------------------------------------- | ---------------------- # | `encoder.layer_norm.beta` | `bert.embeddings.LayerNorm.bias` # | `encoder.layer_norm.gamma` | `bert.embeddings.LayerNorm.weight` # | `encoder.position_weight` | `bert.embeddings.position_embeddings.weight` # | `word_embed.0.weight` | `bert.embeddings.word_embeddings.weight` # | `encoder.transformer_cells.*.attention_cell.proj_key.bias` | `bert.encoder.layer.*.attention.self.key.bias` # | `encoder.transformer_cells.*.attention_cell.proj_key.weight` | `bert.encoder.layer.*.attention.self.key.weight` # | `encoder.transformer_cells.*.attention_cell.proj_query.bias` | `bert.encoder.layer.*.attention.self.query.bias` # | `encoder.transformer_cells.*.attention_cell.proj_query.weight` | `bert.encoder.layer.*.attention.self.query.weight` # | `encoder.transformer_cells.*.attention_cell.proj_value.bias` | `bert.encoder.layer.*.attention.self.value.bias` # | `encoder.transformer_cells.*.attention_cell.proj_value.weight` | `bert.encoder.layer.*.attention.self.value.weight` # | `encoder.transformer_cells.*.ffn.ffn_2.bias` | `bert.encoder.layer.*.attention.output.dense.bias` # | `encoder.transformer_cells.*.ffn.ffn_2.weight` | `bert.encoder.layer.*.attention.output.dense.weight` # | `encoder.transformer_cells.*.layer_norm.beta` | `bert.encoder.layer.*.attention.output.LayerNorm.bias` # | `encoder.transformer_cells.*.layer_norm.gamma` | `bert.encoder.layer.*.attention.output.LayerNorm.weight` # | `encoder.transformer_cells.*.ffn.ffn_1.bias` | `bert.encoder.layer.*.intermediate.dense.bias` # | `encoder.transformer_cells.*.ffn.ffn_1.weight` | `bert.encoder.layer.*.intermediate.dense.weight` # | `encoder.transformer_cells.*.ffn.layer_norm.beta` | `bert.encoder.layer.*.output.LayerNorm.bias` # | `encoder.transformer_cells.*.ffn.layer_norm.gamma` | `bert.encoder.layer.*.output.LayerNorm.weight` # | `encoder.transformer_cells.*.proj.bias` | `bert.encoder.layer.*.output.dense.bias` # | `encoder.transformer_cells.*.proj.weight` | `bert.encoder.layer.*.output.dense.weight` # Helper function to convert MXNET Arrays to PyTorch def to_torch(lowerCamelCase_ : Any ) -> nn.Parameter: return nn.Parameter(torch.FloatTensor(mx_array.data().asnumpy() ) ) # Check param shapes and map new HF param back def check_and_map_params(lowerCamelCase_ : Optional[int] , lowerCamelCase_ : int ): __magic_name__ = hf_param.shape __magic_name__ = to_torch(params[gluon_param] ) __magic_name__ = gluon_param.shape assert ( shape_hf == shape_gluon ), F'The gluon parameter {gluon_param} has shape {shape_gluon}, but expects shape {shape_hf} for Transformers' return gluon_param __magic_name__ = check_and_map_params( hf_bort_model.bert.embeddings.word_embeddings.weight , "word_embed.0.weight" ) __magic_name__ = check_and_map_params( hf_bort_model.bert.embeddings.position_embeddings.weight , "encoder.position_weight" ) __magic_name__ = check_and_map_params( hf_bort_model.bert.embeddings.LayerNorm.bias , "encoder.layer_norm.beta" ) __magic_name__ = check_and_map_params( hf_bort_model.bert.embeddings.LayerNorm.weight , "encoder.layer_norm.gamma" ) # Inspired by RoBERTa conversion script, we just zero them out (Bort does not use them) __magic_name__ = torch.zeros_like( hf_bort_model.bert.embeddings.token_type_embeddings.weight.data ) for i in range(hf_bort_config.num_hidden_layers ): __magic_name__ = hf_bort_model.bert.encoder.layer[i] # self attention __magic_name__ = layer.attention.self __magic_name__ = check_and_map_params( self_attn.key.bias.data , F'encoder.transformer_cells.{i}.attention_cell.proj_key.bias' ) __magic_name__ = check_and_map_params( self_attn.key.weight.data , F'encoder.transformer_cells.{i}.attention_cell.proj_key.weight' ) __magic_name__ = check_and_map_params( self_attn.query.bias.data , F'encoder.transformer_cells.{i}.attention_cell.proj_query.bias' ) __magic_name__ = check_and_map_params( self_attn.query.weight.data , F'encoder.transformer_cells.{i}.attention_cell.proj_query.weight' ) __magic_name__ = check_and_map_params( self_attn.value.bias.data , F'encoder.transformer_cells.{i}.attention_cell.proj_value.bias' ) __magic_name__ = check_and_map_params( self_attn.value.weight.data , F'encoder.transformer_cells.{i}.attention_cell.proj_value.weight' ) # self attention output __magic_name__ = layer.attention.output __magic_name__ = check_and_map_params( self_output.dense.bias , F'encoder.transformer_cells.{i}.proj.bias' ) __magic_name__ = check_and_map_params( self_output.dense.weight , F'encoder.transformer_cells.{i}.proj.weight' ) __magic_name__ = check_and_map_params( self_output.LayerNorm.bias , F'encoder.transformer_cells.{i}.layer_norm.beta' ) __magic_name__ = check_and_map_params( self_output.LayerNorm.weight , F'encoder.transformer_cells.{i}.layer_norm.gamma' ) # intermediate __magic_name__ = layer.intermediate __magic_name__ = check_and_map_params( intermediate.dense.bias , F'encoder.transformer_cells.{i}.ffn.ffn_1.bias' ) __magic_name__ = check_and_map_params( intermediate.dense.weight , F'encoder.transformer_cells.{i}.ffn.ffn_1.weight' ) # output __magic_name__ = layer.output __magic_name__ = check_and_map_params( bert_output.dense.bias , F'encoder.transformer_cells.{i}.ffn.ffn_2.bias' ) __magic_name__ = check_and_map_params( bert_output.dense.weight , F'encoder.transformer_cells.{i}.ffn.ffn_2.weight' ) __magic_name__ = check_and_map_params( bert_output.LayerNorm.bias , F'encoder.transformer_cells.{i}.ffn.layer_norm.beta' ) __magic_name__ = check_and_map_params( bert_output.LayerNorm.weight , F'encoder.transformer_cells.{i}.ffn.layer_norm.gamma' ) # Save space and energy 🎄 hf_bort_model.half() # Compare output of both models __magic_name__ = RobertaTokenizer.from_pretrained("roberta-base" ) __magic_name__ = tokenizer.encode_plus(lowerCamelCase_ )["input_ids"] # Get gluon output __magic_name__ = mx.nd.array([input_ids] ) __magic_name__ = original_bort(inputs=lowerCamelCase_ , token_types=[] ) # Get Transformer output (save and reload model again) hf_bort_model.save_pretrained(lowerCamelCase_ ) __magic_name__ = BertModel.from_pretrained(lowerCamelCase_ ) hf_bort_model.eval() __magic_name__ = tokenizer.encode_plus(lowerCamelCase_ , return_tensors="pt" ) __magic_name__ = hf_bort_model(**lowerCamelCase_ )[0] __magic_name__ = output_gluon[0].asnumpy() __magic_name__ = output_hf[0].detach().numpy() __magic_name__ = np.max(np.abs(hf_layer - gluon_layer ) ).item() __magic_name__ = np.allclose(lowerCamelCase_ , lowerCamelCase_ , atol=1e-3 ) if success: print("✔️ Both model do output the same tensors" ) else: print("❌ Both model do **NOT** output the same tensors" ) print("Absolute difference is:" , lowerCamelCase_ ) if __name__ == "__main__": __magic_name__ : int =argparse.ArgumentParser() # Required parameters parser.add_argument( '--bort_checkpoint_path', default=None, type=str, required=True, help='Path the official Bort params file.' ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) __magic_name__ : Optional[Any] =parser.parse_args() convert_bort_checkpoint_to_pytorch(args.bort_checkpoint_path, args.pytorch_dump_folder_path)
664
1
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, DDIMScheduler, DDPMScheduler, StableDiffusionUpscalePipeline, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() class UpperCamelCase_ ( unittest.TestCase ): """simple docstring""" def __A ( self : Optional[Any] ) -> Optional[int]: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() @property def __A ( self : Optional[Any] ) -> Union[str, Any]: __magic_name__ = 1 __magic_name__ = 3 __magic_name__ = (32, 32) __magic_name__ = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(_lowerCamelCase ) return image @property def __A ( self : int ) -> int: torch.manual_seed(0 ) __magic_name__ = UNetaDConditionModel( block_out_channels=(32, 32, 64) , layers_per_block=2 , sample_size=32 , in_channels=7 , out_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D") , up_block_types=("CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "UpBlock2D") , cross_attention_dim=32 , attention_head_dim=8 , use_linear_projection=_lowerCamelCase , only_cross_attention=(True, True, False) , num_class_embeds=1_00 , ) return model @property def __A ( self : Tuple ) -> Optional[int]: torch.manual_seed(0 ) __magic_name__ = AutoencoderKL( block_out_channels=[32, 32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , ) return model @property def __A ( self : int ) -> int: torch.manual_seed(0 ) __magic_name__ = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=10_00 , hidden_act="gelu" , projection_dim=5_12 , ) return CLIPTextModel(_lowerCamelCase ) def __A ( self : Optional[int] ) -> int: __magic_name__ = "cpu" # ensure determinism for the device-dependent torch.Generator __magic_name__ = self.dummy_cond_unet_upscale __magic_name__ = DDPMScheduler() __magic_name__ = DDIMScheduler(prediction_type="v_prediction" ) __magic_name__ = self.dummy_vae __magic_name__ = self.dummy_text_encoder __magic_name__ = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) __magic_name__ = self.dummy_image.cpu().permute(0 , 2 , 3 , 1 )[0] __magic_name__ = Image.fromarray(np.uinta(_lowerCamelCase ) ).convert("RGB" ).resize((64, 64) ) # make sure here that pndm scheduler skips prk __magic_name__ = StableDiffusionUpscalePipeline( unet=_lowerCamelCase , low_res_scheduler=_lowerCamelCase , scheduler=_lowerCamelCase , vae=_lowerCamelCase , text_encoder=_lowerCamelCase , tokenizer=_lowerCamelCase , max_noise_level=3_50 , ) __magic_name__ = sd_pipe.to(_lowerCamelCase ) sd_pipe.set_progress_bar_config(disable=_lowerCamelCase ) __magic_name__ = "A painting of a squirrel eating a burger" __magic_name__ = torch.Generator(device=_lowerCamelCase ).manual_seed(0 ) __magic_name__ = sd_pipe( [prompt] , image=_lowerCamelCase , generator=_lowerCamelCase , guidance_scale=6.0 , noise_level=20 , num_inference_steps=2 , output_type="np" , ) __magic_name__ = output.images __magic_name__ = torch.Generator(device=_lowerCamelCase ).manual_seed(0 ) __magic_name__ = sd_pipe( [prompt] , image=_lowerCamelCase , generator=_lowerCamelCase , guidance_scale=6.0 , noise_level=20 , num_inference_steps=2 , output_type="np" , return_dict=_lowerCamelCase , )[0] __magic_name__ = image[0, -3:, -3:, -1] __magic_name__ = image_from_tuple[0, -3:, -3:, -1] __magic_name__ = low_res_image.size[0] * 4 assert image.shape == (1, expected_height_width, expected_height_width, 3) __magic_name__ = np.array([0.3_113, 0.3_910, 0.4_272, 0.4_859, 0.5_061, 0.4_652, 0.5_362, 0.5_715, 0.5_661] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 def __A ( self : int ) -> List[str]: __magic_name__ = "cpu" # ensure determinism for the device-dependent torch.Generator __magic_name__ = self.dummy_cond_unet_upscale __magic_name__ = DDPMScheduler() __magic_name__ = DDIMScheduler(prediction_type="v_prediction" ) __magic_name__ = self.dummy_vae __magic_name__ = self.dummy_text_encoder __magic_name__ = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) __magic_name__ = self.dummy_image.cpu().permute(0 , 2 , 3 , 1 )[0] __magic_name__ = Image.fromarray(np.uinta(_lowerCamelCase ) ).convert("RGB" ).resize((64, 64) ) # make sure here that pndm scheduler skips prk __magic_name__ = StableDiffusionUpscalePipeline( unet=_lowerCamelCase , low_res_scheduler=_lowerCamelCase , scheduler=_lowerCamelCase , vae=_lowerCamelCase , text_encoder=_lowerCamelCase , tokenizer=_lowerCamelCase , max_noise_level=3_50 , ) __magic_name__ = sd_pipe.to(_lowerCamelCase ) sd_pipe.set_progress_bar_config(disable=_lowerCamelCase ) __magic_name__ = "A painting of a squirrel eating a burger" __magic_name__ = sd_pipe( 2 * [prompt] , image=2 * [low_res_image] , guidance_scale=6.0 , noise_level=20 , num_inference_steps=2 , output_type="np" , ) __magic_name__ = output.images assert image.shape[0] == 2 __magic_name__ = torch.Generator(device=_lowerCamelCase ).manual_seed(0 ) __magic_name__ = sd_pipe( [prompt] , image=_lowerCamelCase , generator=_lowerCamelCase , num_images_per_prompt=2 , guidance_scale=6.0 , noise_level=20 , num_inference_steps=2 , output_type="np" , ) __magic_name__ = output.images assert image.shape[0] == 2 @unittest.skipIf(torch_device != "cuda" , "This test requires a GPU" ) def __A ( self : str ) -> Tuple: __magic_name__ = self.dummy_cond_unet_upscale __magic_name__ = DDPMScheduler() __magic_name__ = DDIMScheduler(prediction_type="v_prediction" ) __magic_name__ = self.dummy_vae __magic_name__ = self.dummy_text_encoder __magic_name__ = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) __magic_name__ = self.dummy_image.cpu().permute(0 , 2 , 3 , 1 )[0] __magic_name__ = Image.fromarray(np.uinta(_lowerCamelCase ) ).convert("RGB" ).resize((64, 64) ) # put models in fp16, except vae as it overflows in fp16 __magic_name__ = unet.half() __magic_name__ = text_encoder.half() # make sure here that pndm scheduler skips prk __magic_name__ = StableDiffusionUpscalePipeline( unet=_lowerCamelCase , low_res_scheduler=_lowerCamelCase , scheduler=_lowerCamelCase , vae=_lowerCamelCase , text_encoder=_lowerCamelCase , tokenizer=_lowerCamelCase , max_noise_level=3_50 , ) __magic_name__ = sd_pipe.to(_lowerCamelCase ) sd_pipe.set_progress_bar_config(disable=_lowerCamelCase ) __magic_name__ = "A painting of a squirrel eating a burger" __magic_name__ = torch.manual_seed(0 ) __magic_name__ = sd_pipe( [prompt] , image=_lowerCamelCase , generator=_lowerCamelCase , num_inference_steps=2 , output_type="np" , ).images __magic_name__ = low_res_image.size[0] * 4 assert image.shape == (1, expected_height_width, expected_height_width, 3) @slow @require_torch_gpu class UpperCamelCase_ ( unittest.TestCase ): """simple docstring""" def __A ( self : Optional[int] ) -> List[str]: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __A ( self : Union[str, Any] ) -> List[str]: __magic_name__ = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/sd2-upscale/low_res_cat.png" ) __magic_name__ = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale" "/upsampled_cat.npy" ) __magic_name__ = "stabilityai/stable-diffusion-x4-upscaler" __magic_name__ = StableDiffusionUpscalePipeline.from_pretrained(_lowerCamelCase ) pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) pipe.enable_attention_slicing() __magic_name__ = "a cat sitting on a park bench" __magic_name__ = torch.manual_seed(0 ) __magic_name__ = pipe( prompt=_lowerCamelCase , image=_lowerCamelCase , generator=_lowerCamelCase , output_type="np" , ) __magic_name__ = output.images[0] assert image.shape == (5_12, 5_12, 3) assert np.abs(expected_image - image ).max() < 1e-3 def __A ( self : Any ) -> str: __magic_name__ = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/sd2-upscale/low_res_cat.png" ) __magic_name__ = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale" "/upsampled_cat_fp16.npy" ) __magic_name__ = "stabilityai/stable-diffusion-x4-upscaler" __magic_name__ = StableDiffusionUpscalePipeline.from_pretrained( _lowerCamelCase , torch_dtype=torch.floataa , ) pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) pipe.enable_attention_slicing() __magic_name__ = "a cat sitting on a park bench" __magic_name__ = torch.manual_seed(0 ) __magic_name__ = pipe( prompt=_lowerCamelCase , image=_lowerCamelCase , generator=_lowerCamelCase , output_type="np" , ) __magic_name__ = output.images[0] assert image.shape == (5_12, 5_12, 3) assert np.abs(expected_image - image ).max() < 5e-1 def __A ( self : int ) -> Any: torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() __magic_name__ = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/sd2-upscale/low_res_cat.png" ) __magic_name__ = "stabilityai/stable-diffusion-x4-upscaler" __magic_name__ = StableDiffusionUpscalePipeline.from_pretrained( _lowerCamelCase , torch_dtype=torch.floataa , ) pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() __magic_name__ = "a cat sitting on a park bench" __magic_name__ = torch.manual_seed(0 ) __magic_name__ = pipe( prompt=_lowerCamelCase , image=_lowerCamelCase , generator=_lowerCamelCase , num_inference_steps=5 , output_type="np" , ) __magic_name__ = torch.cuda.max_memory_allocated() # make sure that less than 2.9 GB is allocated assert mem_bytes < 2.9 * 10**9
664
'''simple docstring''' def __snake_case ( lowerCamelCase_ : int , lowerCamelCase_ : int ): '''simple docstring''' if a < 0 or b < 0: raise ValueError("the value of both inputs must be positive" ) __magic_name__ = str(bin(lowerCamelCase_ ) )[2:] # remove the leading "0b" __magic_name__ = str(bin(lowerCamelCase_ ) )[2:] # remove the leading "0b" __magic_name__ = max(len(lowerCamelCase_ ) , len(lowerCamelCase_ ) ) return "0b" + "".join( str(int(char_a == "1" and char_b == "1" ) ) for char_a, char_b in zip(a_binary.zfill(lowerCamelCase_ ) , b_binary.zfill(lowerCamelCase_ ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
664
1
'''simple docstring''' from typing import Optional from .. import Features, NamedSplit from ..packaged_modules.text.text import Text from ..utils.typing import NestedDataStructureLike, PathLike from .abc import AbstractDatasetReader class UpperCamelCase_ ( A ): """simple docstring""" def __init__( self : str , _lowerCamelCase : NestedDataStructureLike[PathLike] , _lowerCamelCase : Optional[NamedSplit] = None , _lowerCamelCase : Optional[Features] = None , _lowerCamelCase : str = None , _lowerCamelCase : bool = False , _lowerCamelCase : bool = False , _lowerCamelCase : Optional[int] = None , **_lowerCamelCase : int , ) -> Optional[Any]: super().__init__( _lowerCamelCase , split=_lowerCamelCase , features=_lowerCamelCase , cache_dir=_lowerCamelCase , keep_in_memory=_lowerCamelCase , streaming=_lowerCamelCase , num_proc=_lowerCamelCase , **_lowerCamelCase , ) __magic_name__ = path_or_paths if isinstance(_lowerCamelCase , _lowerCamelCase ) else {self.split: path_or_paths} __magic_name__ = Text( cache_dir=_lowerCamelCase , data_files=_lowerCamelCase , features=_lowerCamelCase , **_lowerCamelCase , ) def __A ( self : List[Any] ) -> str: # Build iterable dataset if self.streaming: __magic_name__ = self.builder.as_streaming_dataset(split=self.split ) # Build regular (map-style) dataset else: __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = None self.builder.download_and_prepare( download_config=_lowerCamelCase , download_mode=_lowerCamelCase , verification_mode=_lowerCamelCase , base_path=_lowerCamelCase , num_proc=self.num_proc , ) __magic_name__ = self.builder.as_dataset( split=self.split , verification_mode=_lowerCamelCase , in_memory=self.keep_in_memory ) return dataset
664
'''simple docstring''' import functools import logging import os import sys import threading from logging import ( CRITICAL, # NOQA DEBUG, # NOQA ERROR, # NOQA FATAL, # NOQA INFO, # NOQA NOTSET, # NOQA WARN, # NOQA WARNING, # NOQA ) from typing import Optional import huggingface_hub.utils as hf_hub_utils from tqdm import auto as tqdm_lib __magic_name__ : Tuple =threading.Lock() __magic_name__ : Optional[logging.Handler] =None __magic_name__ : List[str] ={ 'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'critical': logging.CRITICAL, } __magic_name__ : str =logging.WARNING __magic_name__ : Any =True def __snake_case ( ): '''simple docstring''' __magic_name__ = os.getenv("TRANSFORMERS_VERBOSITY" , lowerCamelCase_ ) if env_level_str: if env_level_str in log_levels: return log_levels[env_level_str] else: logging.getLogger().warning( F'Unknown option TRANSFORMERS_VERBOSITY={env_level_str}, ' F'has to be one of: { ", ".join(log_levels.keys() ) }' ) return _default_log_level def __snake_case ( ): '''simple docstring''' return __name__.split("." )[0] def __snake_case ( ): '''simple docstring''' return logging.getLogger(_get_library_name() ) def __snake_case ( ): '''simple docstring''' global _default_handler with _lock: if _default_handler: # This library has already configured the library root logger. return __magic_name__ = logging.StreamHandler() # Set sys.stderr as stream. __magic_name__ = sys.stderr.flush # Apply our default configuration to the library root logger. __magic_name__ = _get_library_root_logger() library_root_logger.addHandler(_default_handler ) library_root_logger.setLevel(_get_default_logging_level() ) __magic_name__ = False def __snake_case ( ): '''simple docstring''' global _default_handler with _lock: if not _default_handler: return __magic_name__ = _get_library_root_logger() library_root_logger.removeHandler(_default_handler ) library_root_logger.setLevel(logging.NOTSET ) __magic_name__ = None def __snake_case ( ): '''simple docstring''' return log_levels def __snake_case ( lowerCamelCase_ : Optional[str] = None ): '''simple docstring''' if name is None: __magic_name__ = _get_library_name() _configure_library_root_logger() return logging.getLogger(lowerCamelCase_ ) def __snake_case ( ): '''simple docstring''' _configure_library_root_logger() return _get_library_root_logger().getEffectiveLevel() def __snake_case ( lowerCamelCase_ : int ): '''simple docstring''' _configure_library_root_logger() _get_library_root_logger().setLevel(lowerCamelCase_ ) def __snake_case ( ): '''simple docstring''' return set_verbosity(lowerCamelCase_ ) def __snake_case ( ): '''simple docstring''' return set_verbosity(lowerCamelCase_ ) def __snake_case ( ): '''simple docstring''' return set_verbosity(lowerCamelCase_ ) def __snake_case ( ): '''simple docstring''' return set_verbosity(lowerCamelCase_ ) def __snake_case ( ): '''simple docstring''' _configure_library_root_logger() assert _default_handler is not None _get_library_root_logger().removeHandler(_default_handler ) def __snake_case ( ): '''simple docstring''' _configure_library_root_logger() assert _default_handler is not None _get_library_root_logger().addHandler(_default_handler ) def __snake_case ( lowerCamelCase_ : logging.Handler ): '''simple docstring''' _configure_library_root_logger() assert handler is not None _get_library_root_logger().addHandler(lowerCamelCase_ ) def __snake_case ( lowerCamelCase_ : logging.Handler ): '''simple docstring''' _configure_library_root_logger() assert handler is not None and handler not in _get_library_root_logger().handlers _get_library_root_logger().removeHandler(lowerCamelCase_ ) def __snake_case ( ): '''simple docstring''' _configure_library_root_logger() __magic_name__ = False def __snake_case ( ): '''simple docstring''' _configure_library_root_logger() __magic_name__ = True def __snake_case ( ): '''simple docstring''' __magic_name__ = _get_library_root_logger().handlers for handler in handlers: __magic_name__ = logging.Formatter("[%(levelname)s|%(filename)s:%(lineno)s] %(asctime)s >> %(message)s" ) handler.setFormatter(lowerCamelCase_ ) def __snake_case ( ): '''simple docstring''' __magic_name__ = _get_library_root_logger().handlers for handler in handlers: handler.setFormatter(lowerCamelCase_ ) def __snake_case ( self : Union[str, Any] , *lowerCamelCase_ : str , **lowerCamelCase_ : Any ): '''simple docstring''' __magic_name__ = os.getenv("TRANSFORMERS_NO_ADVISORY_WARNINGS" , lowerCamelCase_ ) if no_advisory_warnings: return self.warning(*lowerCamelCase_ , **lowerCamelCase_ ) __magic_name__ : int =warning_advice @functools.lru_cache(lowerCamelCase_ ) def __snake_case ( self : Dict , *lowerCamelCase_ : int , **lowerCamelCase_ : int ): '''simple docstring''' self.warning(*lowerCamelCase_ , **lowerCamelCase_ ) __magic_name__ : Optional[int] =warning_once class UpperCamelCase_ : """simple docstring""" def __init__( self : int , *_lowerCamelCase : Tuple , **_lowerCamelCase : Optional[Any] ) -> Any: # pylint: disable=unused-argument __magic_name__ = args[0] if args else None def __iter__( self : int ) -> Tuple: return iter(self._iterator ) def __getattr__( self : List[Any] , _lowerCamelCase : int ) -> List[Any]: def empty_fn(*_lowerCamelCase : List[str] , **_lowerCamelCase : List[str] ): # pylint: disable=unused-argument return return empty_fn def __enter__( self : Optional[Any] ) -> Any: return self def __exit__( self : int , _lowerCamelCase : List[Any] , _lowerCamelCase : List[Any] , _lowerCamelCase : List[str] ) -> Dict: return class UpperCamelCase_ : """simple docstring""" def __call__( self : Any , *_lowerCamelCase : Optional[Any] , **_lowerCamelCase : Any ) -> List[Any]: if _tqdm_active: return tqdm_lib.tqdm(*_lowerCamelCase , **_lowerCamelCase ) else: return EmptyTqdm(*_lowerCamelCase , **_lowerCamelCase ) def __A ( self : Optional[Any] , *_lowerCamelCase : Optional[Any] , **_lowerCamelCase : Dict ) -> Union[str, Any]: __magic_name__ = None if _tqdm_active: return tqdm_lib.tqdm.set_lock(*_lowerCamelCase , **_lowerCamelCase ) def __A ( self : str ) -> Any: if _tqdm_active: return tqdm_lib.tqdm.get_lock() __magic_name__ : List[Any] =_tqdm_cls() def __snake_case ( ): '''simple docstring''' global _tqdm_active return bool(_tqdm_active ) def __snake_case ( ): '''simple docstring''' global _tqdm_active __magic_name__ = True hf_hub_utils.enable_progress_bars() def __snake_case ( ): '''simple docstring''' global _tqdm_active __magic_name__ = False hf_hub_utils.disable_progress_bars()
664
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __magic_name__ : Union[str, Any] ={ 'configuration_roberta': ['ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP', 'RobertaConfig', 'RobertaOnnxConfig'], 'tokenization_roberta': ['RobertaTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ : Dict =['RobertaTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ : str =[ 'ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST', 'RobertaForCausalLM', 'RobertaForMaskedLM', 'RobertaForMultipleChoice', 'RobertaForQuestionAnswering', 'RobertaForSequenceClassification', 'RobertaForTokenClassification', 'RobertaModel', 'RobertaPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ : Union[str, Any] =[ 'TF_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFRobertaForCausalLM', 'TFRobertaForMaskedLM', 'TFRobertaForMultipleChoice', 'TFRobertaForQuestionAnswering', 'TFRobertaForSequenceClassification', 'TFRobertaForTokenClassification', 'TFRobertaMainLayer', 'TFRobertaModel', 'TFRobertaPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ : Dict =[ 'FlaxRobertaForCausalLM', 'FlaxRobertaForMaskedLM', 'FlaxRobertaForMultipleChoice', 'FlaxRobertaForQuestionAnswering', 'FlaxRobertaForSequenceClassification', 'FlaxRobertaForTokenClassification', 'FlaxRobertaModel', 'FlaxRobertaPreTrainedModel', ] if TYPE_CHECKING: from .configuration_roberta import ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, RobertaConfig, RobertaOnnxConfig from .tokenization_roberta import RobertaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roberta_fast import RobertaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roberta import ( ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, RobertaForCausalLM, RobertaForMaskedLM, RobertaForMultipleChoice, RobertaForQuestionAnswering, RobertaForSequenceClassification, RobertaForTokenClassification, RobertaModel, RobertaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roberta import ( TF_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, TFRobertaForCausalLM, TFRobertaForMaskedLM, TFRobertaForMultipleChoice, TFRobertaForQuestionAnswering, TFRobertaForSequenceClassification, TFRobertaForTokenClassification, TFRobertaMainLayer, TFRobertaModel, TFRobertaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roberta import ( FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaModel, FlaxRobertaPreTrainedModel, ) else: import sys __magic_name__ : List[str] =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
664
'''simple docstring''' from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __magic_name__ : Union[str, Any] ={'configuration_focalnet': ['FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP', 'FocalNetConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ : str =[ 'FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST', 'FocalNetForImageClassification', 'FocalNetForMaskedImageModeling', 'FocalNetBackbone', 'FocalNetModel', 'FocalNetPreTrainedModel', ] if TYPE_CHECKING: from .configuration_focalnet import FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FocalNetConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_focalnet import ( FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST, FocalNetBackbone, FocalNetForImageClassification, FocalNetForMaskedImageModeling, FocalNetModel, FocalNetPreTrainedModel, ) else: import sys __magic_name__ : List[Any] =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
664
1
'''simple docstring''' import tempfile import unittest from transformers import SPIECE_UNDERLINE, BatchEncoding, PLBartTokenizer, 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 __magic_name__ : Tuple =get_tests_dir('fixtures/test_sentencepiece.model') if is_torch_available(): from transformers.models.plbart.modeling_plbart import shift_tokens_right __magic_name__ : Any =5_00_03 __magic_name__ : Optional[int] =5_00_02 @require_sentencepiece @require_tokenizers class UpperCamelCase_ ( A , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Dict = PLBartTokenizer UpperCAmelCase__ : Tuple = None UpperCAmelCase__ : str = False def __A ( self : Tuple ) -> Optional[Any]: super().setUp() # We have a SentencePiece fixture for testing __magic_name__ = PLBartTokenizer(_lowerCamelCase , language_codes="base" , keep_accents=_lowerCamelCase ) tokenizer.save_pretrained(self.tmpdirname ) def __A ( self : int ) -> List[Any]: __magic_name__ = PLBartTokenizer(_lowerCamelCase , language_codes="base" , keep_accents=_lowerCamelCase ) __magic_name__ = tokenizer.tokenize("This is a test" ) self.assertListEqual(_lowerCamelCase , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(_lowerCamelCase ) , [value + tokenizer.fairseq_offset for value in [2_85, 46, 10, 1_70, 3_82]] , ) __magic_name__ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( _lowerCamelCase , [ 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", "é", ".", ] , ) __magic_name__ = tokenizer.convert_tokens_to_ids(_lowerCamelCase ) self.assertListEqual( _lowerCamelCase , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 6_02, 3_47, 3_47, 3_47, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) __magic_name__ = tokenizer.convert_ids_to_tokens(_lowerCamelCase ) self.assertListEqual( _lowerCamelCase , [ 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>", ".", ] , ) __magic_name__ = tokenizer.vocab_size __magic_name__ = [tokenizer.convert_ids_to_tokens(_lowerCamelCase ) for x in range(end - 4 , _lowerCamelCase )] self.assertListEqual(_lowerCamelCase , ["__java__", "__python__", "__en_XX__", "<mask>"] ) __magic_name__ = "java.lang.Exception, python.lang.Exception, javascript, php, ruby, go" __magic_name__ = tokenizer(_lowerCamelCase ).input_ids self.assertEqual( tokenizer.decode(_lowerCamelCase , skip_special_tokens=_lowerCamelCase , clean_up_tokenization_spaces=_lowerCamelCase ) , _lowerCamelCase , ) def __A ( self : List[str] ) -> str: __magic_name__ = PLBartTokenizer(_lowerCamelCase , language_codes="multi" , keep_accents=_lowerCamelCase ) __magic_name__ = tokenizer.tokenize("This is a test" ) self.assertListEqual(_lowerCamelCase , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(_lowerCamelCase ) , [value + tokenizer.fairseq_offset for value in [2_85, 46, 10, 1_70, 3_82]] , ) __magic_name__ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( _lowerCamelCase , [ 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", "é", ".", ] , ) __magic_name__ = tokenizer.convert_tokens_to_ids(_lowerCamelCase ) self.assertListEqual( _lowerCamelCase , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 6_02, 3_47, 3_47, 3_47, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) __magic_name__ = tokenizer.convert_ids_to_tokens(_lowerCamelCase ) self.assertListEqual( _lowerCamelCase , [ 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>", ".", ] , ) __magic_name__ = tokenizer.vocab_size __magic_name__ = [tokenizer.convert_ids_to_tokens(_lowerCamelCase ) for x in range(end - 7 , _lowerCamelCase )] self.assertListEqual( _lowerCamelCase , ["__java__", "__python__", "__en_XX__", "__javascript__", "__php__", "__ruby__", "__go__"] ) __magic_name__ = "java.lang.Exception, python.lang.Exception, javascript, php, ruby, go" __magic_name__ = tokenizer(_lowerCamelCase ).input_ids self.assertEqual( tokenizer.decode(_lowerCamelCase , skip_special_tokens=_lowerCamelCase , clean_up_tokenization_spaces=_lowerCamelCase ) , _lowerCamelCase , ) @require_torch @require_sentencepiece @require_tokenizers class UpperCamelCase_ ( unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : int = '''uclanlp/plbart-python-en_XX''' UpperCAmelCase__ : Any = [ '''def maximum(a,b,c):NEW_LINE_INDENTreturn max([a,b,c])''', '''def sum(a,b,c):NEW_LINE_INDENTreturn sum([a,b,c])''', ] UpperCAmelCase__ : Union[str, Any] = [ '''Returns the maximum value of a b c.''', '''Sums the values of a b c.''', ] UpperCAmelCase__ : int = [ 134, 5452, 3_3460, 3_3441, 3_3463, 3_3465, 3_3463, 3_3449, 988, 20, 3_3456, 19, 3_3456, 771, 39, 4258, 889, 3318, 3_3441, 3_3463, 3_3465, 3_3463, 3_3449, 2471, 2, PYTHON_CODE, ] @classmethod def __A ( cls : Any ) -> int: __magic_name__ = PLBartTokenizer.from_pretrained( cls.checkpoint_name , language_codes="base" , src_lang="python" , tgt_lang="en_XX" ) __magic_name__ = 1 return cls def __A ( self : Any ) -> str: self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["__java__"] , 5_00_01 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["__python__"] , 5_00_02 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["__en_XX__"] , 5_00_03 ) def __A ( self : Dict ) -> List[str]: __magic_name__ = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , _lowerCamelCase ) def __A ( self : Dict ) -> Any: self.assertIn(_lowerCamelCase , self.tokenizer.all_special_ids ) __magic_name__ = [EN_CODE, 90_37, 3_34_42, 57, 7_52, 1_53, 14, 56, 18, 9, 2] __magic_name__ = self.tokenizer.decode(_lowerCamelCase , skip_special_tokens=_lowerCamelCase ) __magic_name__ = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=_lowerCamelCase ) self.assertEqual(_lowerCamelCase , _lowerCamelCase ) self.assertNotIn(self.tokenizer.eos_token , _lowerCamelCase ) def __A ( self : Optional[int] ) -> str: __magic_name__ = ["def sum(a,b,c):NEW_LINE_INDENTreturn sum([a,b,c])" * 20] self.assertIsInstance(src_text[0] , _lowerCamelCase ) __magic_name__ = 10 __magic_name__ = self.tokenizer(_lowerCamelCase , max_length=_lowerCamelCase , truncation=_lowerCamelCase ).input_ids[0] self.assertEqual(ids[-2] , 2 ) self.assertEqual(ids[-1] , _lowerCamelCase ) self.assertEqual(len(_lowerCamelCase ) , _lowerCamelCase ) def __A ( self : Dict ) -> str: self.assertListEqual(self.tokenizer.convert_tokens_to_ids(["<mask>", "__java__"] ) , [5_00_04, 5_00_01] ) def __A ( self : Dict ) -> List[str]: __magic_name__ = tempfile.mkdtemp() __magic_name__ = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(_lowerCamelCase ) __magic_name__ = PLBartTokenizer.from_pretrained(_lowerCamelCase ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , _lowerCamelCase ) @require_torch def __A ( self : List[Any] ) -> Any: __magic_name__ = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=_lowerCamelCase , return_tensors="pt" ) __magic_name__ = shift_tokens_right(batch["labels"] , self.tokenizer.pad_token_id ) # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 self.assertEqual(batch.input_ids[1][-2:].tolist() , [2, PYTHON_CODE] ) self.assertEqual(batch.decoder_input_ids[1][0] , _lowerCamelCase ) self.assertEqual(batch.decoder_input_ids[1][-1] , 2 ) self.assertEqual(batch.labels[1][-2:].tolist() , [2, EN_CODE] ) @require_torch def __A ( self : Dict ) -> Optional[Any]: __magic_name__ = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=_lowerCamelCase , truncation=_lowerCamelCase , max_length=len(self.expected_src_tokens ) , return_tensors="pt" , ) __magic_name__ = shift_tokens_right(batch["labels"] , self.tokenizer.pad_token_id ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual((2, 26) , batch.input_ids.shape ) self.assertEqual((2, 26) , batch.attention_mask.shape ) __magic_name__ = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , _lowerCamelCase ) self.assertEqual(2 , batch.decoder_input_ids[0, -1] ) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id, PYTHON_CODE] ) def __A ( self : Optional[Any] ) -> Optional[int]: __magic_name__ = self.tokenizer(self.src_text , padding=_lowerCamelCase , truncation=_lowerCamelCase , max_length=3 , return_tensors="pt" ) __magic_name__ = self.tokenizer( text_target=self.tgt_text , padding=_lowerCamelCase , truncation=_lowerCamelCase , max_length=10 , return_tensors="pt" ) __magic_name__ = targets["input_ids"] __magic_name__ = shift_tokens_right(_lowerCamelCase , self.tokenizer.pad_token_id ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 10 ) @require_torch def __A ( self : List[str] ) -> List[str]: __magic_name__ = self.tokenizer._build_translation_inputs( "A test" , return_tensors="pt" , src_lang="en_XX" , tgt_lang="java" ) self.assertEqual( nested_simplify(_lowerCamelCase ) , { # A, test, EOS, en_XX "input_ids": [[1_50, 2_42, 2, 5_00_03]], "attention_mask": [[1, 1, 1, 1]], # java "forced_bos_token_id": 5_00_01, } , )
664
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) __magic_name__ : Optional[Any] ={ 'configuration_longformer': [ 'LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LongformerConfig', 'LongformerOnnxConfig', ], 'tokenization_longformer': ['LongformerTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ : int =['LongformerTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ : Dict =[ 'LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'LongformerForMaskedLM', 'LongformerForMultipleChoice', 'LongformerForQuestionAnswering', 'LongformerForSequenceClassification', 'LongformerForTokenClassification', 'LongformerModel', 'LongformerPreTrainedModel', 'LongformerSelfAttention', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ : Tuple =[ 'TF_LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFLongformerForMaskedLM', 'TFLongformerForMultipleChoice', 'TFLongformerForQuestionAnswering', 'TFLongformerForSequenceClassification', 'TFLongformerForTokenClassification', 'TFLongformerModel', 'TFLongformerPreTrainedModel', 'TFLongformerSelfAttention', ] if TYPE_CHECKING: from .configuration_longformer import ( LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, LongformerConfig, LongformerOnnxConfig, ) from .tokenization_longformer import LongformerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_longformer_fast import LongformerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_longformer import ( LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, LongformerForMaskedLM, LongformerForMultipleChoice, LongformerForQuestionAnswering, LongformerForSequenceClassification, LongformerForTokenClassification, LongformerModel, LongformerPreTrainedModel, LongformerSelfAttention, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_longformer import ( TF_LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFLongformerForMaskedLM, TFLongformerForMultipleChoice, TFLongformerForQuestionAnswering, TFLongformerForSequenceClassification, TFLongformerForTokenClassification, TFLongformerModel, TFLongformerPreTrainedModel, TFLongformerSelfAttention, ) else: import sys __magic_name__ : int =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
664
1
'''simple docstring''' # 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 typing import TYPE_CHECKING from ..models.auto import AutoModelForVisionaSeq from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class UpperCamelCase_ ( A ): """simple docstring""" UpperCAmelCase__ : Optional[int] = '''Salesforce/blip-image-captioning-base''' UpperCAmelCase__ : Optional[int] = ( '''This is a tool that generates a description of an image. It takes an input named `image` which should be the ''' '''image to caption, and returns a text that contains the description in English.''' ) UpperCAmelCase__ : Optional[Any] = '''image_captioner''' UpperCAmelCase__ : str = AutoModelForVisionaSeq UpperCAmelCase__ : Dict = ['''image'''] UpperCAmelCase__ : Any = ['''text'''] def __init__( self : str , *_lowerCamelCase : str , **_lowerCamelCase : int ) -> Union[str, Any]: requires_backends(self , ["vision"] ) super().__init__(*_lowerCamelCase , **_lowerCamelCase ) def __A ( self : List[str] , _lowerCamelCase : "Image" ) -> List[Any]: return self.pre_processor(images=_lowerCamelCase , return_tensors="pt" ) def __A ( self : Union[str, Any] , _lowerCamelCase : Union[str, Any] ) -> Tuple: return self.model.generate(**_lowerCamelCase ) def __A ( self : Optional[int] , _lowerCamelCase : Dict ) -> List[Any]: return self.pre_processor.batch_decode(_lowerCamelCase , skip_special_tokens=_lowerCamelCase )[0].strip()
664
'''simple docstring''' import PIL.Image import PIL.ImageOps from packaging import version from PIL import Image if version.parse(version.parse(PIL.__version__).base_version) >= version.parse('9.1.0'): __magic_name__ : str ={ 'linear': PIL.Image.Resampling.BILINEAR, 'bilinear': PIL.Image.Resampling.BILINEAR, 'bicubic': PIL.Image.Resampling.BICUBIC, 'lanczos': PIL.Image.Resampling.LANCZOS, 'nearest': PIL.Image.Resampling.NEAREST, } else: __magic_name__ : Tuple ={ 'linear': PIL.Image.LINEAR, 'bilinear': PIL.Image.BILINEAR, 'bicubic': PIL.Image.BICUBIC, 'lanczos': PIL.Image.LANCZOS, 'nearest': PIL.Image.NEAREST, } def __snake_case ( lowerCamelCase_ : Optional[Any] ): '''simple docstring''' __magic_name__ = (images / 2 + 0.5).clamp(0 , 1 ) __magic_name__ = images.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() __magic_name__ = numpy_to_pil(lowerCamelCase_ ) return images def __snake_case ( lowerCamelCase_ : Optional[Any] ): '''simple docstring''' if images.ndim == 3: __magic_name__ = images[None, ...] __magic_name__ = (images * 255).round().astype("uint8" ) if images.shape[-1] == 1: # special case for grayscale (single channel) images __magic_name__ = [Image.fromarray(image.squeeze() , mode="L" ) for image in images] else: __magic_name__ = [Image.fromarray(lowerCamelCase_ ) for image in images] return pil_images
664
1
'''simple docstring''' import shutil import tempfile import unittest from transformers import ClapFeatureExtractor, ClapProcessor, RobertaTokenizer, RobertaTokenizerFast from transformers.testing_utils import require_sentencepiece, require_torchaudio from .test_feature_extraction_clap import floats_list @require_torchaudio @require_sentencepiece class UpperCamelCase_ ( unittest.TestCase ): """simple docstring""" def __A ( self : List[str] ) -> Dict: __magic_name__ = "laion/clap-htsat-unfused" __magic_name__ = tempfile.mkdtemp() def __A ( self : Union[str, Any] , **_lowerCamelCase : Tuple ) -> Optional[Any]: return RobertaTokenizer.from_pretrained(self.checkpoint , **_lowerCamelCase ) def __A ( self : Tuple , **_lowerCamelCase : Dict ) -> List[str]: return ClapFeatureExtractor.from_pretrained(self.checkpoint , **_lowerCamelCase ) def __A ( self : Union[str, Any] ) -> int: shutil.rmtree(self.tmpdirname ) def __A ( self : Optional[int] ) -> Optional[int]: __magic_name__ = self.get_tokenizer() __magic_name__ = self.get_feature_extractor() __magic_name__ = ClapProcessor(tokenizer=_lowerCamelCase , feature_extractor=_lowerCamelCase ) processor.save_pretrained(self.tmpdirname ) __magic_name__ = ClapProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , _lowerCamelCase ) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor.to_json_string() ) self.assertIsInstance(processor.feature_extractor , _lowerCamelCase ) def __A ( self : int ) -> Optional[int]: __magic_name__ = ClapProcessor(tokenizer=self.get_tokenizer() , feature_extractor=self.get_feature_extractor() ) processor.save_pretrained(self.tmpdirname ) __magic_name__ = self.get_tokenizer(bos_token="(BOS)" , eos_token="(EOS)" ) __magic_name__ = self.get_feature_extractor(do_normalize=_lowerCamelCase , padding_value=1.0 ) __magic_name__ = ClapProcessor.from_pretrained( self.tmpdirname , bos_token="(BOS)" , eos_token="(EOS)" , do_normalize=_lowerCamelCase , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , _lowerCamelCase ) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.feature_extractor , _lowerCamelCase ) def __A ( self : Union[str, Any] ) -> List[Any]: __magic_name__ = self.get_feature_extractor() __magic_name__ = self.get_tokenizer() __magic_name__ = ClapProcessor(tokenizer=_lowerCamelCase , feature_extractor=_lowerCamelCase ) __magic_name__ = floats_list((3, 10_00) ) __magic_name__ = feature_extractor(_lowerCamelCase , return_tensors="np" ) __magic_name__ = processor(audios=_lowerCamelCase , return_tensors="np" ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def __A ( self : Dict ) -> Union[str, Any]: __magic_name__ = self.get_feature_extractor() __magic_name__ = self.get_tokenizer() __magic_name__ = ClapProcessor(tokenizer=_lowerCamelCase , feature_extractor=_lowerCamelCase ) __magic_name__ = "This is a test string" __magic_name__ = processor(text=_lowerCamelCase ) __magic_name__ = tokenizer(_lowerCamelCase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def __A ( self : List[Any] ) -> Dict: __magic_name__ = self.get_feature_extractor() __magic_name__ = self.get_tokenizer() __magic_name__ = ClapProcessor(tokenizer=_lowerCamelCase , feature_extractor=_lowerCamelCase ) __magic_name__ = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __magic_name__ = processor.batch_decode(_lowerCamelCase ) __magic_name__ = tokenizer.batch_decode(_lowerCamelCase ) self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) def __A ( self : Tuple ) -> str: __magic_name__ = self.get_feature_extractor() __magic_name__ = self.get_tokenizer() __magic_name__ = ClapProcessor(tokenizer=_lowerCamelCase , feature_extractor=_lowerCamelCase ) self.assertListEqual( processor.model_input_names[2:] , feature_extractor.model_input_names , msg="`processor` and `feature_extractor` model input names do not match" , )
664
'''simple docstring''' from typing import Dict import numpy as np from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException if is_tf_available(): import tensorflow as tf from ..tf_utils import stable_softmax if is_torch_available(): import torch __magic_name__ : Optional[Any] =logging.get_logger(__name__) @add_end_docstrings( A , r''' top_k (`int`, defaults to 5): The number of predictions to return. targets (`str` or `List[str]`, *optional*): When passed, the model will limit the scores to the passed targets instead of looking up in the whole vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting token will be used (with a warning, and that might be slower). ''' , ) class UpperCamelCase_ ( A ): """simple docstring""" def __A ( self : Any , _lowerCamelCase : GenericTensor ) -> np.ndarray: if self.framework == "tf": __magic_name__ = tf.where(input_ids == self.tokenizer.mask_token_id ).numpy() elif self.framework == "pt": __magic_name__ = torch.nonzero(input_ids == self.tokenizer.mask_token_id , as_tuple=_lowerCamelCase ) else: raise ValueError("Unsupported framework" ) return masked_index def __A ( self : str , _lowerCamelCase : GenericTensor ) -> np.ndarray: __magic_name__ = self.get_masked_index(_lowerCamelCase ) __magic_name__ = np.prod(masked_index.shape ) if numel < 1: raise PipelineException( "fill-mask" , self.model.base_model_prefix , f'No mask_token ({self.tokenizer.mask_token}) found on the input' , ) def __A ( self : int , _lowerCamelCase : GenericTensor ) -> Any: if isinstance(_lowerCamelCase , _lowerCamelCase ): for model_input in model_inputs: self._ensure_exactly_one_mask_token(model_input["input_ids"][0] ) else: for input_ids in model_inputs["input_ids"]: self._ensure_exactly_one_mask_token(_lowerCamelCase ) def __A ( self : List[Any] , _lowerCamelCase : str , _lowerCamelCase : Any=None , **_lowerCamelCase : List[str] ) -> Dict[str, GenericTensor]: if return_tensors is None: __magic_name__ = self.framework __magic_name__ = self.tokenizer(_lowerCamelCase , return_tensors=_lowerCamelCase ) self.ensure_exactly_one_mask_token(_lowerCamelCase ) return model_inputs def __A ( self : List[str] , _lowerCamelCase : int ) -> List[Any]: __magic_name__ = self.model(**_lowerCamelCase ) __magic_name__ = model_inputs["input_ids"] return model_outputs def __A ( self : Tuple , _lowerCamelCase : List[str] , _lowerCamelCase : List[Any]=5 , _lowerCamelCase : Dict=None ) -> Dict: # Cap top_k if there are targets if target_ids is not None and target_ids.shape[0] < top_k: __magic_name__ = target_ids.shape[0] __magic_name__ = model_outputs["input_ids"][0] __magic_name__ = model_outputs["logits"] if self.framework == "tf": __magic_name__ = tf.where(input_ids == self.tokenizer.mask_token_id ).numpy()[:, 0] __magic_name__ = outputs.numpy() __magic_name__ = outputs[0, masked_index, :] __magic_name__ = stable_softmax(_lowerCamelCase , axis=-1 ) if target_ids is not None: __magic_name__ = tf.gather_nd(tf.squeeze(_lowerCamelCase , 0 ) , target_ids.reshape(-1 , 1 ) ) __magic_name__ = tf.expand_dims(_lowerCamelCase , 0 ) __magic_name__ = tf.math.top_k(_lowerCamelCase , k=_lowerCamelCase ) __magic_name__ , __magic_name__ = topk.values.numpy(), topk.indices.numpy() else: __magic_name__ = torch.nonzero(input_ids == self.tokenizer.mask_token_id , as_tuple=_lowerCamelCase ).squeeze(-1 ) # Fill mask pipeline supports only one ${mask_token} per sample __magic_name__ = outputs[0, masked_index, :] __magic_name__ = logits.softmax(dim=-1 ) if target_ids is not None: __magic_name__ = probs[..., target_ids] __magic_name__ , __magic_name__ = probs.topk(_lowerCamelCase ) __magic_name__ = [] __magic_name__ = values.shape[0] == 1 for i, (_values, _predictions) in enumerate(zip(values.tolist() , predictions.tolist() ) ): __magic_name__ = [] for v, p in zip(_values , _predictions ): # Copy is important since we're going to modify this array in place __magic_name__ = input_ids.numpy().copy() if target_ids is not None: __magic_name__ = target_ids[p].tolist() __magic_name__ = p # Filter padding out: __magic_name__ = tokens[np.where(tokens != self.tokenizer.pad_token_id )] # Originally we skip special tokens to give readable output. # For multi masks though, the other [MASK] would be removed otherwise # making the output look odd, so we add them back __magic_name__ = self.tokenizer.decode(_lowerCamelCase , skip_special_tokens=_lowerCamelCase ) __magic_name__ = {"score": v, "token": p, "token_str": self.tokenizer.decode([p] ), "sequence": sequence} row.append(_lowerCamelCase ) result.append(_lowerCamelCase ) if single_mask: return result[0] return result def __A ( self : List[Any] , _lowerCamelCase : Any , _lowerCamelCase : List[Any]=None ) -> List[str]: if isinstance(_lowerCamelCase , _lowerCamelCase ): __magic_name__ = [targets] try: __magic_name__ = self.tokenizer.get_vocab() except Exception: __magic_name__ = {} __magic_name__ = [] for target in targets: __magic_name__ = vocab.get(_lowerCamelCase , _lowerCamelCase ) if id_ is None: __magic_name__ = self.tokenizer( _lowerCamelCase , add_special_tokens=_lowerCamelCase , return_attention_mask=_lowerCamelCase , return_token_type_ids=_lowerCamelCase , max_length=1 , truncation=_lowerCamelCase , )["input_ids"] if len(_lowerCamelCase ) == 0: logger.warning( f'The specified target token `{target}` does not exist in the model vocabulary. ' "We cannot replace it with anything meaningful, ignoring it" ) continue __magic_name__ = input_ids[0] # XXX: If users encounter this pass # it becomes pretty slow, so let's make sure # The warning enables them to fix the input to # get faster performance. logger.warning( f'The specified target token `{target}` does not exist in the model vocabulary. ' f'Replacing with `{self.tokenizer.convert_ids_to_tokens(id_ )}`.' ) target_ids.append(id_ ) __magic_name__ = list(set(_lowerCamelCase ) ) if len(_lowerCamelCase ) == 0: raise ValueError("At least one target must be provided when passed." ) __magic_name__ = np.array(_lowerCamelCase ) return target_ids def __A ( self : Optional[Any] , _lowerCamelCase : Any=None , _lowerCamelCase : int=None ) -> Tuple: __magic_name__ = {} if targets is not None: __magic_name__ = self.get_target_ids(_lowerCamelCase , _lowerCamelCase ) __magic_name__ = target_ids if top_k is not None: __magic_name__ = top_k if self.tokenizer.mask_token_id is None: raise PipelineException( "fill-mask" , self.model.base_model_prefix , "The tokenizer does not define a `mask_token`." ) return {}, {}, postprocess_params def __call__( self : int , _lowerCamelCase : Any , *_lowerCamelCase : str , **_lowerCamelCase : int ) -> Optional[int]: __magic_name__ = super().__call__(_lowerCamelCase , **_lowerCamelCase ) if isinstance(_lowerCamelCase , _lowerCamelCase ) and len(_lowerCamelCase ) == 1: return outputs[0] return outputs
664
1
'''simple docstring''' import unittest from transformers import load_tool from transformers.utils import is_torch_available if is_torch_available(): import torch from transformers.testing_utils import require_torch from .test_tools_common import ToolTesterMixin @require_torch class UpperCamelCase_ ( unittest.TestCase , A ): """simple docstring""" def __A ( self : Optional[int] ) -> Any: __magic_name__ = load_tool("text-to-speech" ) self.tool.setup() def __A ( self : Union[str, Any] ) -> int: # SpeechT5 isn't deterministic torch.manual_seed(0 ) __magic_name__ = self.tool("hey" ) __magic_name__ = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] , torch.tensor([-0.0_005_966_668_832_115_829, -0.0_003_657_640_190_795_064, -0.00_013_439_502_799_883_485] ) , ) ) def __A ( self : List[str] ) -> int: # SpeechT5 isn't deterministic torch.manual_seed(0 ) __magic_name__ = self.tool("hey" ) __magic_name__ = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] , torch.tensor([-0.0_005_966_668_832_115_829, -0.0_003_657_640_190_795_064, -0.00_013_439_502_799_883_485] ) , ) )
664
'''simple docstring''' from __future__ import annotations def __snake_case ( lowerCamelCase_ : list[int] , lowerCamelCase_ : int ): '''simple docstring''' if len(lowerCamelCase_ ) < k or k < 0: raise ValueError("Invalid Input" ) __magic_name__ = __magic_name__ = sum(array[:k] ) for i in range(len(lowerCamelCase_ ) - k ): __magic_name__ = current_sum - array[i] + array[i + k] __magic_name__ = max(lowerCamelCase_ , lowerCamelCase_ ) return max_sum if __name__ == "__main__": from doctest import testmod from random import randint testmod() __magic_name__ : List[str] =[randint(-10_00, 10_00) for i in range(1_00)] __magic_name__ : List[str] =randint(0, 1_10) print(F'''The maximum sum of {k} consecutive elements is {max_sum_in_array(array,k)}''')
664
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __magic_name__ : int =logging.get_logger(__name__) __magic_name__ : List[Any] ={} class UpperCamelCase_ ( A ): """simple docstring""" UpperCAmelCase__ : int = '''llama''' UpperCAmelCase__ : Any = ['''past_key_values'''] def __init__( self : List[Any] , _lowerCamelCase : List[Any]=3_20_00 , _lowerCamelCase : Optional[Any]=40_96 , _lowerCamelCase : Tuple=1_10_08 , _lowerCamelCase : List[Any]=32 , _lowerCamelCase : Tuple=32 , _lowerCamelCase : List[str]=None , _lowerCamelCase : str="silu" , _lowerCamelCase : Optional[Any]=20_48 , _lowerCamelCase : Optional[Any]=0.02 , _lowerCamelCase : Union[str, Any]=1e-6 , _lowerCamelCase : Optional[int]=True , _lowerCamelCase : Dict=0 , _lowerCamelCase : int=1 , _lowerCamelCase : str=2 , _lowerCamelCase : List[Any]=1 , _lowerCamelCase : Optional[int]=False , _lowerCamelCase : List[str]=None , **_lowerCamelCase : List[Any] , ) -> Any: __magic_name__ = vocab_size __magic_name__ = max_position_embeddings __magic_name__ = hidden_size __magic_name__ = intermediate_size __magic_name__ = num_hidden_layers __magic_name__ = num_attention_heads # for backward compatibility if num_key_value_heads is None: __magic_name__ = num_attention_heads __magic_name__ = num_key_value_heads __magic_name__ = hidden_act __magic_name__ = initializer_range __magic_name__ = rms_norm_eps __magic_name__ = pretraining_tp __magic_name__ = use_cache __magic_name__ = rope_scaling self._rope_scaling_validation() super().__init__( pad_token_id=_lowerCamelCase , bos_token_id=_lowerCamelCase , eos_token_id=_lowerCamelCase , tie_word_embeddings=_lowerCamelCase , **_lowerCamelCase , ) def __A ( self : Union[str, Any] ) -> List[Any]: if self.rope_scaling is None: return if not isinstance(self.rope_scaling , _lowerCamelCase ) or len(self.rope_scaling ) != 2: raise ValueError( "`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, " f'got {self.rope_scaling}' ) __magic_name__ = self.rope_scaling.get("type" , _lowerCamelCase ) __magic_name__ = self.rope_scaling.get("factor" , _lowerCamelCase ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( f'`rope_scaling`\'s name field must be one of [\'linear\', \'dynamic\'], got {rope_scaling_type}' ) if rope_scaling_factor is None or not isinstance(_lowerCamelCase , _lowerCamelCase ) or rope_scaling_factor <= 1.0: raise ValueError(f'`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}' )
664
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __magic_name__ : int =logging.get_logger(__name__) __magic_name__ : List[Any] ={} class UpperCamelCase_ ( A ): """simple docstring""" UpperCAmelCase__ : int = '''llama''' UpperCAmelCase__ : Any = ['''past_key_values'''] def __init__( self : List[Any] , _lowerCamelCase : List[Any]=3_20_00 , _lowerCamelCase : Optional[Any]=40_96 , _lowerCamelCase : Tuple=1_10_08 , _lowerCamelCase : List[Any]=32 , _lowerCamelCase : Tuple=32 , _lowerCamelCase : List[str]=None , _lowerCamelCase : str="silu" , _lowerCamelCase : Optional[Any]=20_48 , _lowerCamelCase : Optional[Any]=0.02 , _lowerCamelCase : Union[str, Any]=1e-6 , _lowerCamelCase : Optional[int]=True , _lowerCamelCase : Dict=0 , _lowerCamelCase : int=1 , _lowerCamelCase : str=2 , _lowerCamelCase : List[Any]=1 , _lowerCamelCase : Optional[int]=False , _lowerCamelCase : List[str]=None , **_lowerCamelCase : List[Any] , ) -> Any: __magic_name__ = vocab_size __magic_name__ = max_position_embeddings __magic_name__ = hidden_size __magic_name__ = intermediate_size __magic_name__ = num_hidden_layers __magic_name__ = num_attention_heads # for backward compatibility if num_key_value_heads is None: __magic_name__ = num_attention_heads __magic_name__ = num_key_value_heads __magic_name__ = hidden_act __magic_name__ = initializer_range __magic_name__ = rms_norm_eps __magic_name__ = pretraining_tp __magic_name__ = use_cache __magic_name__ = rope_scaling self._rope_scaling_validation() super().__init__( pad_token_id=_lowerCamelCase , bos_token_id=_lowerCamelCase , eos_token_id=_lowerCamelCase , tie_word_embeddings=_lowerCamelCase , **_lowerCamelCase , ) def __A ( self : Union[str, Any] ) -> List[Any]: if self.rope_scaling is None: return if not isinstance(self.rope_scaling , _lowerCamelCase ) or len(self.rope_scaling ) != 2: raise ValueError( "`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, " f'got {self.rope_scaling}' ) __magic_name__ = self.rope_scaling.get("type" , _lowerCamelCase ) __magic_name__ = self.rope_scaling.get("factor" , _lowerCamelCase ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( f'`rope_scaling`\'s name field must be one of [\'linear\', \'dynamic\'], got {rope_scaling_type}' ) if rope_scaling_factor is None or not isinstance(_lowerCamelCase , _lowerCamelCase ) or rope_scaling_factor <= 1.0: raise ValueError(f'`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}' )
664
1
'''simple docstring''' import gc import unittest import numpy as np import torch from diffusers import StableDiffusionKDiffusionPipeline from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() @slow @require_torch_gpu class UpperCamelCase_ ( unittest.TestCase ): """simple docstring""" def __A ( self : Union[str, Any] ) -> Dict: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __A ( self : Union[str, Any] ) -> Optional[Any]: __magic_name__ = StableDiffusionKDiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4" ) __magic_name__ = sd_pipe.to(_lowerCamelCase ) sd_pipe.set_progress_bar_config(disable=_lowerCamelCase ) sd_pipe.set_scheduler("sample_euler" ) __magic_name__ = "A painting of a squirrel eating a burger" __magic_name__ = torch.manual_seed(0 ) __magic_name__ = sd_pipe([prompt] , generator=_lowerCamelCase , guidance_scale=9.0 , num_inference_steps=20 , output_type="np" ) __magic_name__ = output.images __magic_name__ = image[0, -3:, -3:, -1] assert image.shape == (1, 5_12, 5_12, 3) __magic_name__ = np.array([0.0_447, 0.0_492, 0.0_468, 0.0_408, 0.0_383, 0.0_408, 0.0_354, 0.0_380, 0.0_339] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __A ( self : Tuple ) -> Any: __magic_name__ = StableDiffusionKDiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1-base" ) __magic_name__ = sd_pipe.to(_lowerCamelCase ) sd_pipe.set_progress_bar_config(disable=_lowerCamelCase ) sd_pipe.set_scheduler("sample_euler" ) __magic_name__ = "A painting of a squirrel eating a burger" __magic_name__ = torch.manual_seed(0 ) __magic_name__ = sd_pipe([prompt] , generator=_lowerCamelCase , guidance_scale=9.0 , num_inference_steps=20 , output_type="np" ) __magic_name__ = output.images __magic_name__ = image[0, -3:, -3:, -1] assert image.shape == (1, 5_12, 5_12, 3) __magic_name__ = np.array([0.1_237, 0.1_320, 0.1_438, 0.1_359, 0.1_390, 0.1_132, 0.1_277, 0.1_175, 0.1_112] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-1 def __A ( self : Any ) -> Union[str, Any]: __magic_name__ = StableDiffusionKDiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1-base" ) __magic_name__ = sd_pipe.to(_lowerCamelCase ) sd_pipe.set_progress_bar_config(disable=_lowerCamelCase ) sd_pipe.set_scheduler("sample_dpmpp_2m" ) __magic_name__ = "A painting of a squirrel eating a burger" __magic_name__ = torch.manual_seed(0 ) __magic_name__ = sd_pipe( [prompt] , generator=_lowerCamelCase , guidance_scale=7.5 , num_inference_steps=15 , output_type="np" , use_karras_sigmas=_lowerCamelCase , ) __magic_name__ = output.images __magic_name__ = image[0, -3:, -3:, -1] assert image.shape == (1, 5_12, 5_12, 3) __magic_name__ = np.array( [0.11_381_689, 0.12_112_921, 0.1_389_457, 0.12_549_606, 0.1_244_964, 0.10_831_517, 0.11_562_866, 0.10_867_816, 0.10_499_048] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
664
'''simple docstring''' __magic_name__ : Dict =8.3_1_4_4_6_2 # Unit - J mol-1 K-1 def __snake_case ( lowerCamelCase_ : float , lowerCamelCase_ : float , lowerCamelCase_ : float ): '''simple docstring''' if moles < 0 or kelvin < 0 or volume < 0: raise ValueError("Invalid inputs. Enter positive value." ) return moles * kelvin * UNIVERSAL_GAS_CONSTANT / volume def __snake_case ( lowerCamelCase_ : float , lowerCamelCase_ : float , lowerCamelCase_ : float ): '''simple docstring''' if moles < 0 or kelvin < 0 or pressure < 0: raise ValueError("Invalid inputs. Enter positive value." ) return moles * kelvin * UNIVERSAL_GAS_CONSTANT / pressure if __name__ == "__main__": from doctest import testmod testmod()
664
1
'''simple docstring''' # this script reports modified .py files under the desired list of top-level sub-dirs passed as a list of arguments, e.g.: # python ./utils/get_modified_files.py utils src tests examples # # it uses git to find the forking point and which files were modified - i.e. files not under git won't be considered # since the output of this script is fed into Makefile commands it doesn't print a newline after the results import re import subprocess import sys __magic_name__ : List[str] =subprocess.check_output('git merge-base main HEAD'.split()).decode('utf-8') __magic_name__ : Any =( subprocess.check_output(F'''git diff --diff-filter=d --name-only {fork_point_sha}'''.split()).decode('utf-8').split() ) __magic_name__ : Union[str, Any] ='|'.join(sys.argv[1:]) __magic_name__ : List[Any] =re.compile(RF'''^({joined_dirs}).*?\.py$''') __magic_name__ : Optional[int] =[x for x in modified_files if regex.match(x)] print(' '.join(relevant_modified_files), end='')
664
'''simple docstring''' import logging import os from typing import List, TextIO, Union from conllu import parse_incr from utils_ner import InputExample, Split, TokenClassificationTask __magic_name__ : List[Any] =logging.getLogger(__name__) class UpperCamelCase_ ( A ): """simple docstring""" def __init__( self : Optional[Any] , _lowerCamelCase : str=-1 ) -> List[str]: # in NER datasets, the last column is usually reserved for NER label __magic_name__ = label_idx def __A ( self : Any , _lowerCamelCase : str , _lowerCamelCase : Union[Split, str] ) -> List[InputExample]: if isinstance(_lowerCamelCase , _lowerCamelCase ): __magic_name__ = mode.value __magic_name__ = os.path.join(_lowerCamelCase , f'{mode}.txt' ) __magic_name__ = 1 __magic_name__ = [] with open(_lowerCamelCase , encoding="utf-8" ) as f: __magic_name__ = [] __magic_name__ = [] for line in f: if line.startswith("-DOCSTART-" ) or line == "" or line == "\n": if words: examples.append(InputExample(guid=f'{mode}-{guid_index}' , words=_lowerCamelCase , labels=_lowerCamelCase ) ) guid_index += 1 __magic_name__ = [] __magic_name__ = [] else: __magic_name__ = line.split(" " ) words.append(splits[0] ) if len(_lowerCamelCase ) > 1: labels.append(splits[self.label_idx].replace("\n" , "" ) ) else: # Examples could have no label for mode = "test" labels.append("O" ) if words: examples.append(InputExample(guid=f'{mode}-{guid_index}' , words=_lowerCamelCase , labels=_lowerCamelCase ) ) return examples def __A ( self : Optional[Any] , _lowerCamelCase : TextIO , _lowerCamelCase : TextIO , _lowerCamelCase : List ) -> Union[str, Any]: __magic_name__ = 0 for line in test_input_reader: if line.startswith("-DOCSTART-" ) or line == "" or line == "\n": writer.write(_lowerCamelCase ) if not preds_list[example_id]: example_id += 1 elif preds_list[example_id]: __magic_name__ = line.split()[0] + " " + preds_list[example_id].pop(0 ) + "\n" writer.write(_lowerCamelCase ) else: logger.warning("Maximum sequence length exceeded: No prediction for '%s'." , line.split()[0] ) def __A ( self : Tuple , _lowerCamelCase : str ) -> List[str]: if path: with open(_lowerCamelCase , "r" ) as f: __magic_name__ = f.read().splitlines() if "O" not in labels: __magic_name__ = ["O"] + labels return labels else: return ["O", "B-MISC", "I-MISC", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC"] class UpperCamelCase_ ( A ): """simple docstring""" def __init__( self : int ) -> str: # in CONLL2003 dataset chunk column is second-to-last super().__init__(label_idx=-2 ) def __A ( self : int , _lowerCamelCase : str ) -> List[str]: if path: with open(_lowerCamelCase , "r" ) as f: __magic_name__ = f.read().splitlines() if "O" not in labels: __magic_name__ = ["O"] + labels return labels else: return [ "O", "B-ADVP", "B-INTJ", "B-LST", "B-PRT", "B-NP", "B-SBAR", "B-VP", "B-ADJP", "B-CONJP", "B-PP", "I-ADVP", "I-INTJ", "I-LST", "I-PRT", "I-NP", "I-SBAR", "I-VP", "I-ADJP", "I-CONJP", "I-PP", ] class UpperCamelCase_ ( A ): """simple docstring""" def __A ( self : List[Any] , _lowerCamelCase : Union[str, Any] , _lowerCamelCase : Union[Split, str] ) -> List[InputExample]: if isinstance(_lowerCamelCase , _lowerCamelCase ): __magic_name__ = mode.value __magic_name__ = os.path.join(_lowerCamelCase , f'{mode}.txt' ) __magic_name__ = 1 __magic_name__ = [] with open(_lowerCamelCase , encoding="utf-8" ) as f: for sentence in parse_incr(_lowerCamelCase ): __magic_name__ = [] __magic_name__ = [] for token in sentence: words.append(token["form"] ) labels.append(token["upos"] ) assert len(_lowerCamelCase ) == len(_lowerCamelCase ) if words: examples.append(InputExample(guid=f'{mode}-{guid_index}' , words=_lowerCamelCase , labels=_lowerCamelCase ) ) guid_index += 1 return examples def __A ( self : Optional[int] , _lowerCamelCase : TextIO , _lowerCamelCase : TextIO , _lowerCamelCase : List ) -> Any: __magic_name__ = 0 for sentence in parse_incr(_lowerCamelCase ): __magic_name__ = preds_list[example_id] __magic_name__ = "" for token in sentence: out += f'{token["form"]} ({token["upos"]}|{s_p.pop(0 )}) ' out += "\n" writer.write(_lowerCamelCase ) example_id += 1 def __A ( self : Dict , _lowerCamelCase : str ) -> List[str]: if path: with open(_lowerCamelCase , "r" ) as f: return f.read().splitlines() else: return [ "ADJ", "ADP", "ADV", "AUX", "CCONJ", "DET", "INTJ", "NOUN", "NUM", "PART", "PRON", "PROPN", "PUNCT", "SCONJ", "SYM", "VERB", "X", ]
664
1
'''simple docstring''' 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_ ( A ): """simple docstring""" def __A ( self : str ) -> Dict: __magic_name__ = tempfile.mkdtemp() __magic_name__ = 5 # Realm tok __magic_name__ = [ "[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", ] __magic_name__ = os.path.join(self.tmpdirname , "realm_tokenizer" ) os.makedirs(_lowerCamelCase , exist_ok=_lowerCamelCase ) __magic_name__ = os.path.join(_lowerCamelCase , 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] ) ) __magic_name__ = os.path.join(self.tmpdirname , "realm_block_records" ) os.makedirs(_lowerCamelCase , exist_ok=_lowerCamelCase ) def __A ( self : List[str] ) -> RealmTokenizer: return RealmTokenizer.from_pretrained(os.path.join(self.tmpdirname , "realm_tokenizer" ) ) def __A ( self : List[str] ) -> Dict: shutil.rmtree(self.tmpdirname ) def __A ( self : Any ) -> str: __magic_name__ = RealmConfig(num_block_records=self.num_block_records ) return config def __A ( self : Any ) -> Tuple: __magic_name__ = Dataset.from_dict( { "id": ["0", "1"], "question": ["foo", "bar"], "answers": [["Foo", "Bar"], ["Bar"]], } ) return dataset def __A ( self : str ) -> str: __magic_name__ = 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=_lowerCamelCase , ) return block_records def __A ( self : Optional[Any] ) -> List[str]: __magic_name__ = RealmRetriever( block_records=self.get_dummy_block_records() , tokenizer=self.get_tokenizer() , ) return retriever def __A ( self : List[str] ) -> str: __magic_name__ = self.get_config() __magic_name__ = self.get_dummy_retriever() __magic_name__ = retriever.tokenizer __magic_name__ = np.array([0, 3] , dtype="long" ) __magic_name__ = tokenizer(["Test question"] ).input_ids __magic_name__ = tokenizer( ["the fourth"] , add_special_tokens=_lowerCamelCase , return_token_type_ids=_lowerCamelCase , return_attention_mask=_lowerCamelCase , ).input_ids __magic_name__ = config.reader_seq_len __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ = retriever( _lowerCamelCase , _lowerCamelCase , answer_ids=_lowerCamelCase , max_length=_lowerCamelCase , return_tensors="np" ) self.assertEqual(len(_lowerCamelCase ) , 2 ) self.assertEqual(len(_lowerCamelCase ) , 2 ) self.assertEqual(len(_lowerCamelCase ) , 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 : List[str] ) -> Optional[Any]: __magic_name__ = self.get_config() __magic_name__ = self.get_dummy_retriever() __magic_name__ = retriever.tokenizer __magic_name__ = np.array([0, 3, 5] , dtype="long" ) __magic_name__ = tokenizer(["Test question"] ).input_ids __magic_name__ = tokenizer( ["the fourth", "longer longer"] , add_special_tokens=_lowerCamelCase , return_token_type_ids=_lowerCamelCase , return_attention_mask=_lowerCamelCase , ).input_ids __magic_name__ = config.reader_seq_len __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ = retriever( _lowerCamelCase , _lowerCamelCase , answer_ids=_lowerCamelCase , max_length=_lowerCamelCase , return_tensors="np" ) self.assertEqual([False, True, True] , _lowerCamelCase ) self.assertEqual([[-1, -1, -1], [6, -1, -1], [6, 7, 8]] , _lowerCamelCase ) self.assertEqual([[-1, -1, -1], [7, -1, -1], [7, 8, 9]] , _lowerCamelCase ) def __A ( self : Optional[Any] ) -> Union[str, Any]: __magic_name__ = self.get_dummy_retriever() retriever.save_pretrained(os.path.join(self.tmpdirname , "realm_block_records" ) ) # Test local path __magic_name__ = 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: __magic_name__ = os.path.join( os.path.join(self.tmpdirname , "realm_block_records" ) , _REALM_BLOCK_RECORDS_FILENAME ) __magic_name__ = RealmRetriever.from_pretrained("google/realm-cc-news-pretrained-openqa" ) self.assertEqual(retriever.block_records[0] , b"This is the first record" )
664
'''simple docstring''' from __future__ import annotations from typing import Any class UpperCamelCase_ : """simple docstring""" def __init__( self : int , _lowerCamelCase : int , _lowerCamelCase : int , _lowerCamelCase : float = 0 ) -> None: __magic_name__ , __magic_name__ = row, column __magic_name__ = [[default_value for c in range(_lowerCamelCase )] for r in range(_lowerCamelCase )] def __str__( self : Optional[Any] ) -> str: __magic_name__ = f'Matrix consist of {self.row} rows and {self.column} columns\n' # Make string identifier __magic_name__ = 0 for row_vector in self.array: for obj in row_vector: __magic_name__ = max(_lowerCamelCase , len(str(_lowerCamelCase ) ) ) __magic_name__ = f'%{max_element_length}s' # Make string and return def single_line(_lowerCamelCase : list[float] ) -> str: nonlocal string_format_identifier __magic_name__ = "[" line += ", ".join(string_format_identifier % (obj,) for obj in row_vector ) line += "]" return line s += "\n".join(single_line(_lowerCamelCase ) for row_vector in self.array ) return s def __repr__( self : Optional[int] ) -> str: return str(self ) def __A ( self : Optional[Any] , _lowerCamelCase : tuple[int, int] ) -> bool: if not (isinstance(_lowerCamelCase , (list, tuple) ) and len(_lowerCamelCase ) == 2): return False elif not (0 <= loc[0] < self.row and 0 <= loc[1] < self.column): return False else: return True def __getitem__( self : Optional[int] , _lowerCamelCase : tuple[int, int] ) -> Any: assert self.validate_indicies(_lowerCamelCase ) return self.array[loc[0]][loc[1]] def __setitem__( self : Tuple , _lowerCamelCase : tuple[int, int] , _lowerCamelCase : float ) -> None: assert self.validate_indicies(_lowerCamelCase ) __magic_name__ = value def __add__( self : Union[str, Any] , _lowerCamelCase : Matrix ) -> Matrix: assert isinstance(_lowerCamelCase , _lowerCamelCase ) assert self.row == another.row and self.column == another.column # Add __magic_name__ = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): __magic_name__ = self[r, c] + another[r, c] return result def __neg__( self : int ) -> Matrix: __magic_name__ = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): __magic_name__ = -self[r, c] return result def __sub__( self : Optional[int] , _lowerCamelCase : Matrix ) -> Matrix: return self + (-another) def __mul__( self : Optional[int] , _lowerCamelCase : int | float | Matrix ) -> Matrix: if isinstance(_lowerCamelCase , (int, float) ): # Scalar multiplication __magic_name__ = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): __magic_name__ = self[r, c] * another return result elif isinstance(_lowerCamelCase , _lowerCamelCase ): # Matrix multiplication assert self.column == another.row __magic_name__ = Matrix(self.row , another.column ) for r in range(self.row ): for c in range(another.column ): for i in range(self.column ): result[r, c] += self[r, i] * another[i, c] return result else: __magic_name__ = f'Unsupported type given for another ({type(_lowerCamelCase )})' raise TypeError(_lowerCamelCase ) def __A ( self : Optional[int] ) -> Matrix: __magic_name__ = Matrix(self.column , self.row ) for r in range(self.row ): for c in range(self.column ): __magic_name__ = self[r, c] return result def __A ( self : int , _lowerCamelCase : Matrix , _lowerCamelCase : Matrix ) -> Any: assert isinstance(_lowerCamelCase , _lowerCamelCase ) and isinstance(_lowerCamelCase , _lowerCamelCase ) assert self.row == self.column == u.row == v.row # u, v should be column vector assert u.column == v.column == 1 # u, v should be column vector # Calculate __magic_name__ = v.transpose() __magic_name__ = (v_t * self * u)[0, 0] + 1 if numerator_factor == 0: return None # It's not invertable return self - ((self * u) * (v_t * self) * (1.0 / numerator_factor)) # Testing if __name__ == "__main__": def __snake_case ( ): '''simple docstring''' __magic_name__ = Matrix(3 , 3 , 0 ) for i in range(3 ): __magic_name__ = 1 print(F'a^(-1) is {ainv}' ) # u, v __magic_name__ = Matrix(3 , 1 , 0 ) __magic_name__ , __magic_name__ , __magic_name__ = 1, 2, -3 __magic_name__ = Matrix(3 , 1 , 0 ) __magic_name__ , __magic_name__ , __magic_name__ = 4, -2, 5 print(F'u is {u}' ) print(F'v is {v}' ) print(F'uv^T is {u * v.transpose()}' ) # Sherman Morrison print(F'(a + uv^T)^(-1) is {ainv.sherman_morrison(lowerCamelCase_ , lowerCamelCase_ )}' ) def __snake_case ( ): '''simple docstring''' import doctest doctest.testmod() testa()
664
1
'''simple docstring''' import PIL.Image import PIL.ImageOps from packaging import version from PIL import Image if version.parse(version.parse(PIL.__version__).base_version) >= version.parse('9.1.0'): __magic_name__ : str ={ 'linear': PIL.Image.Resampling.BILINEAR, 'bilinear': PIL.Image.Resampling.BILINEAR, 'bicubic': PIL.Image.Resampling.BICUBIC, 'lanczos': PIL.Image.Resampling.LANCZOS, 'nearest': PIL.Image.Resampling.NEAREST, } else: __magic_name__ : Tuple ={ 'linear': PIL.Image.LINEAR, 'bilinear': PIL.Image.BILINEAR, 'bicubic': PIL.Image.BICUBIC, 'lanczos': PIL.Image.LANCZOS, 'nearest': PIL.Image.NEAREST, } def __snake_case ( lowerCamelCase_ : Optional[Any] ): '''simple docstring''' __magic_name__ = (images / 2 + 0.5).clamp(0 , 1 ) __magic_name__ = images.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() __magic_name__ = numpy_to_pil(lowerCamelCase_ ) return images def __snake_case ( lowerCamelCase_ : Optional[Any] ): '''simple docstring''' if images.ndim == 3: __magic_name__ = images[None, ...] __magic_name__ = (images * 255).round().astype("uint8" ) if images.shape[-1] == 1: # special case for grayscale (single channel) images __magic_name__ = [Image.fromarray(image.squeeze() , mode="L" ) for image in images] else: __magic_name__ = [Image.fromarray(lowerCamelCase_ ) for image in images] return pil_images
664
'''simple docstring''' import argparse import logging from collections import namedtuple import torch from model_bertabs import BertAbsSummarizer from models.model_builder import AbsSummarizer # The authors' implementation from transformers import BertTokenizer logging.basicConfig(level=logging.INFO) __magic_name__ : List[Any] =logging.getLogger(__name__) __magic_name__ : int ='Hello world! cécé herlolip' __magic_name__ : List[Any] =namedtuple( 'BertAbsConfig', [ 'temp_dir', 'large', 'use_bert_emb', 'finetune_bert', 'encoder', 'share_emb', 'max_pos', 'enc_layers', 'enc_hidden_size', 'enc_heads', 'enc_ff_size', 'enc_dropout', 'dec_layers', 'dec_hidden_size', 'dec_heads', 'dec_ff_size', 'dec_dropout', ], ) def __snake_case ( lowerCamelCase_ : Optional[int] , lowerCamelCase_ : Dict ): '''simple docstring''' __magic_name__ = BertAbsConfig( temp_dir="." , finetune_bert=lowerCamelCase_ , large=lowerCamelCase_ , share_emb=lowerCamelCase_ , use_bert_emb=lowerCamelCase_ , encoder="bert" , max_pos=512 , enc_layers=6 , enc_hidden_size=512 , enc_heads=8 , enc_ff_size=512 , enc_dropout=0.2 , dec_layers=6 , dec_hidden_size=768 , dec_heads=8 , dec_ff_size=2048 , dec_dropout=0.2 , ) __magic_name__ = torch.load(lowerCamelCase_ , lambda lowerCamelCase_ , lowerCamelCase_ : storage ) __magic_name__ = AbsSummarizer(lowerCamelCase_ , torch.device("cpu" ) , lowerCamelCase_ ) original.eval() __magic_name__ = BertAbsSummarizer(lowerCamelCase_ , torch.device("cpu" ) ) new_model.eval() # ------------------- # Convert the weights # ------------------- logging.info("convert the model" ) new_model.bert.load_state_dict(original.bert.state_dict() ) new_model.decoder.load_state_dict(original.decoder.state_dict() ) new_model.generator.load_state_dict(original.generator.state_dict() ) # ---------------------------------- # Make sure the outpus are identical # ---------------------------------- logging.info("Make sure that the models' outputs are identical" ) __magic_name__ = BertTokenizer.from_pretrained("bert-base-uncased" ) # prepare the model inputs __magic_name__ = tokenizer.encode("This is sample éàalj'-." ) encoder_input_ids.extend([tokenizer.pad_token_id] * (512 - len(lowerCamelCase_ )) ) __magic_name__ = torch.tensor(lowerCamelCase_ ).unsqueeze(0 ) __magic_name__ = tokenizer.encode("This is sample 3 éàalj'-." ) decoder_input_ids.extend([tokenizer.pad_token_id] * (512 - len(lowerCamelCase_ )) ) __magic_name__ = torch.tensor(lowerCamelCase_ ).unsqueeze(0 ) # failsafe to make sure the weights reset does not affect the # loaded weights. assert torch.max(torch.abs(original.generator[0].weight - new_model.generator[0].weight ) ) == 0 # forward pass __magic_name__ = encoder_input_ids __magic_name__ = decoder_input_ids __magic_name__ = __magic_name__ = None __magic_name__ = None __magic_name__ = __magic_name__ = None __magic_name__ = __magic_name__ = None __magic_name__ = None # The original model does not apply the geneator layer immediatly but rather in # the beam search (where it combines softmax + linear layer). Since we already # apply the softmax in our generation process we only apply the linear layer here. # We make sure that the outputs of the full stack are identical __magic_name__ = original(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )[0] __magic_name__ = original.generator(lowerCamelCase_ ) __magic_name__ = new_model( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )[0] __magic_name__ = new_model.generator(lowerCamelCase_ ) __magic_name__ = torch.max(torch.abs(output_converted_model - output_original_model ) ).item() print("Maximum absolute difference beween weights: {:.2f}".format(lowerCamelCase_ ) ) __magic_name__ = torch.max(torch.abs(output_converted_generator - output_original_generator ) ).item() print("Maximum absolute difference beween weights: {:.2f}".format(lowerCamelCase_ ) ) __magic_name__ = torch.allclose(lowerCamelCase_ , lowerCamelCase_ , atol=1e-3 ) if are_identical: logging.info("all weights are equal up to 1e-3" ) else: raise ValueError("the weights are different. The new model is likely different from the original one." ) # The model has been saved with torch.save(model) and this is bound to the exact # directory structure. We save the state_dict instead. logging.info("saving the model's state dictionary" ) torch.save( new_model.state_dict() , "./bertabs-finetuned-cnndm-extractive-abstractive-summarization/pytorch_model.bin" ) if __name__ == "__main__": __magic_name__ : Dict =argparse.ArgumentParser() parser.add_argument( '--bertabs_checkpoint_path', default=None, type=str, required=True, help='Path the official PyTorch dump.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.', ) __magic_name__ : Any =parser.parse_args() convert_bertabs_checkpoints( args.bertabs_checkpoint_path, args.pytorch_dump_folder_path, )
664
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) __magic_name__ : Optional[Any] ={ 'configuration_longformer': [ 'LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LongformerConfig', 'LongformerOnnxConfig', ], 'tokenization_longformer': ['LongformerTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ : int =['LongformerTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ : Dict =[ 'LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'LongformerForMaskedLM', 'LongformerForMultipleChoice', 'LongformerForQuestionAnswering', 'LongformerForSequenceClassification', 'LongformerForTokenClassification', 'LongformerModel', 'LongformerPreTrainedModel', 'LongformerSelfAttention', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ : Tuple =[ 'TF_LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFLongformerForMaskedLM', 'TFLongformerForMultipleChoice', 'TFLongformerForQuestionAnswering', 'TFLongformerForSequenceClassification', 'TFLongformerForTokenClassification', 'TFLongformerModel', 'TFLongformerPreTrainedModel', 'TFLongformerSelfAttention', ] if TYPE_CHECKING: from .configuration_longformer import ( LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, LongformerConfig, LongformerOnnxConfig, ) from .tokenization_longformer import LongformerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_longformer_fast import LongformerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_longformer import ( LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, LongformerForMaskedLM, LongformerForMultipleChoice, LongformerForQuestionAnswering, LongformerForSequenceClassification, LongformerForTokenClassification, LongformerModel, LongformerPreTrainedModel, LongformerSelfAttention, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_longformer import ( TF_LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFLongformerForMaskedLM, TFLongformerForMultipleChoice, TFLongformerForQuestionAnswering, TFLongformerForSequenceClassification, TFLongformerForTokenClassification, TFLongformerModel, TFLongformerPreTrainedModel, TFLongformerSelfAttention, ) else: import sys __magic_name__ : int =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
664
'''simple docstring''' import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.generation import DisjunctiveConstraint @require_torch class UpperCamelCase_ ( unittest.TestCase ): """simple docstring""" def __A ( self : List[str] ) -> str: # For consistency across different places the DisjunctiveConstraint is called, # dc.token_ids is a list of integers. It is also initialized only by integers. __magic_name__ = [[1, 2, 4], [1, 2, 3, 4]] __magic_name__ = DisjunctiveConstraint(_lowerCamelCase ) self.assertTrue(isinstance(dc.token_ids , _lowerCamelCase ) ) with self.assertRaises(_lowerCamelCase ): DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]] ) ) with self.assertRaises(_lowerCamelCase ): DisjunctiveConstraint([torch.LongTensor([1, 2, 4] ), torch.LongTensor([1, 2, 3, 4, 5] )] ) def __A ( self : List[Any] ) -> str: # We can't have constraints that are complete subsets of another. This leads to a preverse # interpretation of "constraint fulfillment": does generating [1,2,3] fulfill the constraint? # It would mean that it generated [1,2] which fulfills it, but it's in the middle of potentially # fulfilling [1,2,3,4]. If we believe that [1,2,3] does fulfill the constraint, then the algorithm # will necessarily never reach [1,2,3,4], giving users a false sense of control (better to just not allow it). __magic_name__ = [[1, 2], [1, 2, 3, 4]] with self.assertRaises(_lowerCamelCase ): DisjunctiveConstraint(_lowerCamelCase ) # fails here def __A ( self : List[Any] ) -> int: __magic_name__ = [[1, 2, 3], [1, 2, 4]] __magic_name__ = DisjunctiveConstraint(_lowerCamelCase ) __magic_name__ , __magic_name__ , __magic_name__ = dc.update(1 ) __magic_name__ = stepped is True and completed is False and reset is False self.assertTrue(_lowerCamelCase ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) __magic_name__ , __magic_name__ , __magic_name__ = dc.update(2 ) __magic_name__ = stepped is True and completed is False and reset is False self.assertTrue(_lowerCamelCase ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) __magic_name__ , __magic_name__ , __magic_name__ = dc.update(3 ) __magic_name__ = stepped is True and completed is True and reset is False self.assertTrue(_lowerCamelCase ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 3] ) def __A ( self : Any ) -> Union[str, Any]: __magic_name__ = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]] __magic_name__ = DisjunctiveConstraint(_lowerCamelCase ) __magic_name__ , __magic_name__ , __magic_name__ = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) __magic_name__ , __magic_name__ , __magic_name__ = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) __magic_name__ , __magic_name__ , __magic_name__ = dc.update(4 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2, 4] ) __magic_name__ , __magic_name__ , __magic_name__ = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 4, 5] ) dc.reset() __magic_name__ , __magic_name__ , __magic_name__ = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 3 ) self.assertTrue(dc.current_seq == [1] ) __magic_name__ , __magic_name__ , __magic_name__ = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 2 ) self.assertTrue(dc.current_seq == [1, 2] ) __magic_name__ , __magic_name__ , __magic_name__ = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.remaining() == 0 ) self.assertTrue(dc.current_seq == [1, 2, 5] )
664
1
'''simple docstring''' import argparse import os import sys from unittest.mock import patch import pytorch_lightning as pl import timeout_decorator import torch from distillation import SummarizationDistiller, distill_main from finetune import SummarizationModule, main from transformers import MarianMTModel from transformers.file_utils import cached_path from transformers.testing_utils import TestCasePlus, require_torch_gpu, slow from utils import load_json __magic_name__ : List[Any] ='sshleifer/mar_enro_6_3_student' class UpperCamelCase_ ( A ): """simple docstring""" def __A ( self : Tuple ) -> Optional[Any]: super().setUp() __magic_name__ = cached_path( "https://cdn-datasets.huggingface.co/translation/wmt_en_ro-tr40k-va0.5k-te0.5k.tar.gz" , extract_compressed_file=_lowerCamelCase , ) __magic_name__ = f'{data_cached}/wmt_en_ro-tr40k-va0.5k-te0.5k' @slow @require_torch_gpu def __A ( self : str ) -> Optional[Any]: MarianMTModel.from_pretrained(_lowerCamelCase ) @slow @require_torch_gpu def __A ( self : List[str] ) -> List[Any]: __magic_name__ = { "$MAX_LEN": 64, "$BS": 64, "$GAS": 1, "$ENRO_DIR": self.data_dir, "facebook/mbart-large-cc25": MARIAN_MODEL, # "val_check_interval=0.25": "val_check_interval=1.0", "--learning_rate=3e-5": "--learning_rate 3e-4", "--num_train_epochs 6": "--num_train_epochs 1", } # Clean up bash script __magic_name__ = (self.test_file_dir / "train_mbart_cc25_enro.sh").open().read().split("finetune.py" )[1].strip() __magic_name__ = bash_script.replace("\\\n" , "" ).strip().replace("\"$@\"" , "" ) for k, v in env_vars_to_replace.items(): __magic_name__ = bash_script.replace(_lowerCamelCase , str(_lowerCamelCase ) ) __magic_name__ = self.get_auto_remove_tmp_dir() # bash_script = bash_script.replace("--fp16 ", "") __magic_name__ = f'\n --output_dir {output_dir}\n --tokenizer_name Helsinki-NLP/opus-mt-en-ro\n --sortish_sampler\n --do_predict\n --gpus 1\n --freeze_encoder\n --n_train 40000\n --n_val 500\n --n_test 500\n --fp16_opt_level O1\n --num_sanity_val_steps 0\n --eval_beams 2\n '.split() # XXX: args.gpus > 1 : handle multi_gpu in the future __magic_name__ = ["finetune.py"] + bash_script.split() + args with patch.object(_lowerCamelCase , "argv" , _lowerCamelCase ): __magic_name__ = argparse.ArgumentParser() __magic_name__ = pl.Trainer.add_argparse_args(_lowerCamelCase ) __magic_name__ = SummarizationModule.add_model_specific_args(_lowerCamelCase , os.getcwd() ) __magic_name__ = parser.parse_args() __magic_name__ = main(_lowerCamelCase ) # Check metrics __magic_name__ = load_json(model.metrics_save_path ) __magic_name__ = metrics["val"][0] __magic_name__ = metrics["val"][-1] self.assertEqual(len(metrics["val"] ) , (args.max_epochs / args.val_check_interval) ) assert isinstance(last_step_stats[f'val_avg_{model.val_metric}'] , _lowerCamelCase ) self.assertGreater(last_step_stats["val_avg_gen_time"] , 0.01 ) # model hanging on generate. Maybe bad config was saved. (XXX: old comment/assert?) self.assertLessEqual(last_step_stats["val_avg_gen_time"] , 1.0 ) # test learning requirements: # 1. BLEU improves over the course of training by more than 2 pts self.assertGreater(last_step_stats["val_avg_bleu"] - first_step_stats["val_avg_bleu"] , 2 ) # 2. BLEU finishes above 17 self.assertGreater(last_step_stats["val_avg_bleu"] , 17 ) # 3. test BLEU and val BLEU within ~1.1 pt. self.assertLess(abs(metrics["val"][-1]["val_avg_bleu"] - metrics["test"][-1]["test_avg_bleu"] ) , 1.1 ) # check lightning ckpt can be loaded and has a reasonable statedict __magic_name__ = os.listdir(_lowerCamelCase ) __magic_name__ = [x for x in contents if x.endswith(".ckpt" )][0] __magic_name__ = os.path.join(args.output_dir , _lowerCamelCase ) __magic_name__ = torch.load(_lowerCamelCase , map_location="cpu" ) __magic_name__ = "model.model.decoder.layers.0.encoder_attn_layer_norm.weight" assert expected_key in ckpt["state_dict"] assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa # TODO: turn on args.do_predict when PL bug fixed. if args.do_predict: __magic_name__ = {os.path.basename(_lowerCamelCase ) for p in contents} assert "test_generations.txt" in contents assert "test_results.txt" in contents # assert len(metrics["val"]) == desired_n_evals assert len(metrics["test"] ) == 1 class UpperCamelCase_ ( A ): """simple docstring""" @timeout_decorator.timeout(6_00 ) @slow @require_torch_gpu def __A ( self : Optional[Any] ) -> int: __magic_name__ = f'{self.test_file_dir_str}/test_data/wmt_en_ro' __magic_name__ = { "--fp16_opt_level=O1": "", "$MAX_LEN": 1_28, "$BS": 16, "$GAS": 1, "$ENRO_DIR": data_dir, "$m": "sshleifer/student_marian_en_ro_6_1", "val_check_interval=0.25": "val_check_interval=1.0", } # Clean up bash script __magic_name__ = ( (self.test_file_dir / "distil_marian_no_teacher.sh").open().read().split("distillation.py" )[1].strip() ) __magic_name__ = bash_script.replace("\\\n" , "" ).strip().replace("\"$@\"" , "" ) __magic_name__ = bash_script.replace("--fp16 " , " " ) for k, v in env_vars_to_replace.items(): __magic_name__ = bash_script.replace(_lowerCamelCase , str(_lowerCamelCase ) ) __magic_name__ = self.get_auto_remove_tmp_dir() __magic_name__ = bash_script.replace("--fp16" , "" ) __magic_name__ = 6 __magic_name__ = ( ["distillation.py"] + bash_script.split() + [ f'--output_dir={output_dir}', "--gpus=1", "--learning_rate=1e-3", f'--num_train_epochs={epochs}', "--warmup_steps=10", "--val_check_interval=1.0", "--do_predict", ] ) with patch.object(_lowerCamelCase , "argv" , _lowerCamelCase ): __magic_name__ = argparse.ArgumentParser() __magic_name__ = pl.Trainer.add_argparse_args(_lowerCamelCase ) __magic_name__ = SummarizationDistiller.add_model_specific_args(_lowerCamelCase , os.getcwd() ) __magic_name__ = parser.parse_args() # assert args.gpus == gpus THIS BREAKS for multi_gpu __magic_name__ = distill_main(_lowerCamelCase ) # Check metrics __magic_name__ = load_json(model.metrics_save_path ) __magic_name__ = metrics["val"][0] __magic_name__ = metrics["val"][-1] assert len(metrics["val"] ) >= (args.max_epochs / args.val_check_interval) # +1 accounts for val_sanity_check assert last_step_stats["val_avg_gen_time"] >= 0.01 assert first_step_stats["val_avg_bleu"] < last_step_stats["val_avg_bleu"] # model learned nothing assert 1.0 >= last_step_stats["val_avg_gen_time"] # model hanging on generate. Maybe bad config was saved. assert isinstance(last_step_stats[f'val_avg_{model.val_metric}'] , _lowerCamelCase ) # check lightning ckpt can be loaded and has a reasonable statedict __magic_name__ = os.listdir(_lowerCamelCase ) __magic_name__ = [x for x in contents if x.endswith(".ckpt" )][0] __magic_name__ = os.path.join(args.output_dir , _lowerCamelCase ) __magic_name__ = torch.load(_lowerCamelCase , map_location="cpu" ) __magic_name__ = "model.model.decoder.layers.0.encoder_attn_layer_norm.weight" assert expected_key in ckpt["state_dict"] assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa # TODO: turn on args.do_predict when PL bug fixed. if args.do_predict: __magic_name__ = {os.path.basename(_lowerCamelCase ) for p in contents} assert "test_generations.txt" in contents assert "test_results.txt" in contents # assert len(metrics["val"]) == desired_n_evals assert len(metrics["test"] ) == 1
664
'''simple docstring''' import json import os import shutil import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import AutoConfig, BertConfig, GPTaConfig from transformers.configuration_utils import PretrainedConfig from transformers.testing_utils import TOKEN, USER, is_staging_test sys.path.append(str(Path(__file__).parent.parent / 'utils')) from test_module.custom_configuration import CustomConfig # noqa E402 __magic_name__ : Dict ={ 'return_dict': False, 'output_hidden_states': True, 'output_attentions': True, 'torchscript': True, 'torch_dtype': 'float16', 'use_bfloat16': True, 'tf_legacy_loss': True, 'pruned_heads': {'a': 1}, 'tie_word_embeddings': False, 'is_decoder': True, 'cross_attention_hidden_size': 1_28, 'add_cross_attention': True, 'tie_encoder_decoder': True, 'max_length': 50, 'min_length': 3, 'do_sample': True, 'early_stopping': True, 'num_beams': 3, 'num_beam_groups': 3, 'diversity_penalty': 0.5, 'temperature': 2.0, 'top_k': 10, 'top_p': 0.7, 'typical_p': 0.2, 'repetition_penalty': 0.8, 'length_penalty': 0.8, 'no_repeat_ngram_size': 5, 'encoder_no_repeat_ngram_size': 5, 'bad_words_ids': [1, 2, 3], 'num_return_sequences': 3, 'chunk_size_feed_forward': 5, 'output_scores': True, 'return_dict_in_generate': True, 'forced_bos_token_id': 2, 'forced_eos_token_id': 3, 'remove_invalid_values': True, 'architectures': ['BertModel'], 'finetuning_task': 'translation', 'id2label': {0: 'label'}, 'label2id': {'label': '0'}, 'tokenizer_class': 'BertTokenizerFast', 'prefix': 'prefix', 'bos_token_id': 6, 'pad_token_id': 7, 'eos_token_id': 8, 'sep_token_id': 9, 'decoder_start_token_id': 10, 'exponential_decay_length_penalty': (5, 1.0_1), 'suppress_tokens': [0, 1], 'begin_suppress_tokens': 2, 'task_specific_params': {'translation': 'some_params'}, 'problem_type': 'regression', } @is_staging_test class UpperCamelCase_ ( unittest.TestCase ): """simple docstring""" @classmethod def __A ( cls : Any ) -> Union[str, Any]: __magic_name__ = TOKEN HfFolder.save_token(_lowerCamelCase ) @classmethod def __A ( cls : Any ) -> Tuple: try: delete_repo(token=cls._token , repo_id="test-config" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="valid_org/test-config-org" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="test-dynamic-config" ) except HTTPError: pass def __A ( self : Optional[Any] ) -> Dict: __magic_name__ = BertConfig( vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 ) config.push_to_hub("test-config" , use_auth_token=self._token ) __magic_name__ = BertConfig.from_pretrained(f'{USER}/test-config' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(_lowerCamelCase , getattr(_lowerCamelCase , _lowerCamelCase ) ) # Reset repo delete_repo(token=self._token , repo_id="test-config" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(_lowerCamelCase , repo_id="test-config" , push_to_hub=_lowerCamelCase , use_auth_token=self._token ) __magic_name__ = BertConfig.from_pretrained(f'{USER}/test-config' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(_lowerCamelCase , getattr(_lowerCamelCase , _lowerCamelCase ) ) def __A ( self : str ) -> Optional[int]: __magic_name__ = BertConfig( vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 ) config.push_to_hub("valid_org/test-config-org" , use_auth_token=self._token ) __magic_name__ = BertConfig.from_pretrained("valid_org/test-config-org" ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(_lowerCamelCase , getattr(_lowerCamelCase , _lowerCamelCase ) ) # Reset repo delete_repo(token=self._token , repo_id="valid_org/test-config-org" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( _lowerCamelCase , repo_id="valid_org/test-config-org" , push_to_hub=_lowerCamelCase , use_auth_token=self._token ) __magic_name__ = BertConfig.from_pretrained("valid_org/test-config-org" ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(_lowerCamelCase , getattr(_lowerCamelCase , _lowerCamelCase ) ) def __A ( self : Optional[int] ) -> Union[str, Any]: CustomConfig.register_for_auto_class() __magic_name__ = CustomConfig(attribute=42 ) config.push_to_hub("test-dynamic-config" , use_auth_token=self._token ) # This has added the proper auto_map field to the config self.assertDictEqual(config.auto_map , {"AutoConfig": "custom_configuration.CustomConfig"} ) __magic_name__ = AutoConfig.from_pretrained(f'{USER}/test-dynamic-config' , trust_remote_code=_lowerCamelCase ) # Can't make an isinstance check because the new_config is from the FakeConfig class of a dynamic module self.assertEqual(new_config.__class__.__name__ , "CustomConfig" ) self.assertEqual(new_config.attribute , 42 ) class UpperCamelCase_ ( unittest.TestCase ): """simple docstring""" def __A ( self : Optional[int] ) -> Optional[Any]: __magic_name__ = GPTaConfig() # attempt to modify each of int/float/bool/str config records and verify they were updated __magic_name__ = c.n_embd + 1 # int __magic_name__ = c.resid_pdrop + 1.0 # float __magic_name__ = not c.scale_attn_weights # bool __magic_name__ = c.summary_type + "foo" # str c.update_from_string( f'n_embd={n_embd},resid_pdrop={resid_pdrop},scale_attn_weights={scale_attn_weights},summary_type={summary_type}' ) self.assertEqual(_lowerCamelCase , c.n_embd , "mismatch for key: n_embd" ) self.assertEqual(_lowerCamelCase , c.resid_pdrop , "mismatch for key: resid_pdrop" ) self.assertEqual(_lowerCamelCase , c.scale_attn_weights , "mismatch for key: scale_attn_weights" ) self.assertEqual(_lowerCamelCase , c.summary_type , "mismatch for key: summary_type" ) def __A ( self : List[Any] ) -> Union[str, Any]: __magic_name__ = PretrainedConfig() __magic_name__ = [key for key in base_config.__dict__ if key not in config_common_kwargs] # If this part of the test fails, you have arguments to addin config_common_kwargs above. self.assertListEqual( _lowerCamelCase , ["is_encoder_decoder", "_name_or_path", "_commit_hash", "transformers_version"] ) __magic_name__ = [key for key, value in config_common_kwargs.items() if value == getattr(_lowerCamelCase , _lowerCamelCase )] if len(_lowerCamelCase ) > 0: raise ValueError( "The following keys are set with the default values in" " `test_configuration_common.config_common_kwargs` pick another value for them:" f' {", ".join(_lowerCamelCase )}.' ) def __A ( self : List[Any] ) -> List[Any]: with self.assertRaises(_lowerCamelCase ): # config is in subfolder, the following should not work without specifying the subfolder __magic_name__ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert-subfolder" ) __magic_name__ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert-subfolder" , subfolder="bert" ) self.assertIsNotNone(_lowerCamelCase ) def __A ( self : Tuple ) -> int: # A mock response for an HTTP head request to emulate server down __magic_name__ = mock.Mock() __magic_name__ = 5_00 __magic_name__ = {} __magic_name__ = HTTPError __magic_name__ = {} # Download this model to make sure it's in the cache. __magic_name__ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert" ) # Under the mock environment we get a 500 error when trying to reach the model. with mock.patch("requests.Session.request" , return_value=_lowerCamelCase ) as mock_head: __magic_name__ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert" ) # This check we did call the fake head request mock_head.assert_called() def __A ( self : Union[str, Any] ) -> Dict: # This test is for deprecated behavior and can be removed in v5 __magic_name__ = BertConfig.from_pretrained( "https://huggingface.co/hf-internal-testing/tiny-random-bert/resolve/main/config.json" ) def __A ( self : Dict ) -> Optional[int]: __magic_name__ = AutoConfig.from_pretrained("bert-base-cased" ) __magic_name__ = ["config.4.0.0.json"] with tempfile.TemporaryDirectory() as tmp_dir: configuration.save_pretrained(_lowerCamelCase ) __magic_name__ = 2 json.dump(configuration.to_dict() , open(os.path.join(_lowerCamelCase , "config.4.0.0.json" ) , "w" ) ) # This should pick the new configuration file as the version of Transformers is > 4.0.0 __magic_name__ = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertEqual(new_configuration.hidden_size , 2 ) # Will need to be adjusted if we reach v42 and this test is still here. # Should pick the old configuration file as the version of Transformers is < 4.42.0 __magic_name__ = ["config.42.0.0.json"] __magic_name__ = 7_68 configuration.save_pretrained(_lowerCamelCase ) shutil.move(os.path.join(_lowerCamelCase , "config.4.0.0.json" ) , os.path.join(_lowerCamelCase , "config.42.0.0.json" ) ) __magic_name__ = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertEqual(new_configuration.hidden_size , 7_68 ) def __A ( self : Optional[int] ) -> str: # This repo has two configuration files, one for v4.0.0 and above with a different hidden size. __magic_name__ = "hf-internal-testing/test-two-configs" import transformers as new_transformers __magic_name__ = "v4.0.0" __magic_name__ , __magic_name__ = new_transformers.models.auto.AutoConfig.from_pretrained( _lowerCamelCase , return_unused_kwargs=_lowerCamelCase ) self.assertEqual(new_configuration.hidden_size , 2 ) # This checks `_configuration_file` ia not kept in the kwargs by mistake. self.assertDictEqual(_lowerCamelCase , {} ) # Testing an older version by monkey-patching the version in the module it's used. import transformers as old_transformers __magic_name__ = "v3.0.0" __magic_name__ = old_transformers.models.auto.AutoConfig.from_pretrained(_lowerCamelCase ) self.assertEqual(old_configuration.hidden_size , 7_68 )
664
1
'''simple docstring''' import inspect import unittest from transformers import RegNetConfig, is_flax_available from transformers.testing_utils import require_flax, slow from transformers.utils import cached_property, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor if is_flax_available(): import jax import jax.numpy as jnp from transformers.models.regnet.modeling_flax_regnet import FlaxRegNetForImageClassification, FlaxRegNetModel if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class UpperCamelCase_ ( unittest.TestCase ): """simple docstring""" def __init__( self : Optional[int] , _lowerCamelCase : Tuple , _lowerCamelCase : Dict=3 , _lowerCamelCase : Union[str, Any]=32 , _lowerCamelCase : str=3 , _lowerCamelCase : List[Any]=10 , _lowerCamelCase : Dict=[10, 20, 30, 40] , _lowerCamelCase : str=[1, 1, 2, 1] , _lowerCamelCase : Dict=True , _lowerCamelCase : Dict=True , _lowerCamelCase : Optional[int]="relu" , _lowerCamelCase : Tuple=3 , _lowerCamelCase : Dict=None , ) -> str: __magic_name__ = parent __magic_name__ = batch_size __magic_name__ = image_size __magic_name__ = num_channels __magic_name__ = embeddings_size __magic_name__ = hidden_sizes __magic_name__ = depths __magic_name__ = is_training __magic_name__ = use_labels __magic_name__ = hidden_act __magic_name__ = num_labels __magic_name__ = scope __magic_name__ = len(_lowerCamelCase ) def __A ( self : List[Any] ) -> Union[str, Any]: __magic_name__ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __magic_name__ = self.get_config() return config, pixel_values def __A ( self : int ) -> Any: return RegNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , image_size=self.image_size , ) def __A ( self : Optional[int] , _lowerCamelCase : Dict , _lowerCamelCase : str ) -> Tuple: __magic_name__ = FlaxRegNetModel(config=_lowerCamelCase ) __magic_name__ = model(_lowerCamelCase ) # Output shape (b, c, h, w) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def __A ( self : List[Any] , _lowerCamelCase : Any , _lowerCamelCase : List[str] ) -> List[str]: __magic_name__ = self.num_labels __magic_name__ = FlaxRegNetForImageClassification(config=_lowerCamelCase ) __magic_name__ = model(_lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __A ( self : Optional[int] ) -> Tuple: __magic_name__ = self.prepare_config_and_inputs() __magic_name__ , __magic_name__ = config_and_inputs __magic_name__ = {"pixel_values": pixel_values} return config, inputs_dict @require_flax class UpperCamelCase_ ( A , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : str = (FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else () UpperCAmelCase__ : Tuple = False UpperCAmelCase__ : Optional[Any] = False UpperCAmelCase__ : Tuple = False def __A ( self : int ) -> None: __magic_name__ = FlaxRegNetModelTester(self ) __magic_name__ = ConfigTester(self , config_class=_lowerCamelCase , has_text_modality=_lowerCamelCase ) def __A ( self : int ) -> List[str]: self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def __A ( self : str ) -> Dict: return def __A ( self : int ) -> Optional[int]: __magic_name__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowerCamelCase ) def __A ( self : Dict ) -> Optional[Any]: __magic_name__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_lowerCamelCase ) @unittest.skip(reason="RegNet does not use inputs_embeds" ) def __A ( self : Optional[Any] ) -> Optional[int]: pass @unittest.skip(reason="RegNet does not support input and output embeddings" ) def __A ( self : Optional[int] ) -> Optional[Any]: pass def __A ( self : Dict ) -> Union[str, Any]: __magic_name__ , __magic_name__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __magic_name__ = model_class(_lowerCamelCase ) __magic_name__ = inspect.signature(model.__call__ ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __magic_name__ = [*signature.parameters.keys()] __magic_name__ = ["pixel_values"] self.assertListEqual(arg_names[:1] , _lowerCamelCase ) def __A ( self : List[Any] ) -> List[Any]: def check_hidden_states_output(_lowerCamelCase : List[str] , _lowerCamelCase : Dict , _lowerCamelCase : Union[str, Any] ): __magic_name__ = model_class(_lowerCamelCase ) __magic_name__ = model(**self._prepare_for_class(_lowerCamelCase , _lowerCamelCase ) ) __magic_name__ = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states __magic_name__ = self.model_tester.num_stages self.assertEqual(len(_lowerCamelCase ) , expected_num_stages + 1 ) __magic_name__ , __magic_name__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __magic_name__ = True check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __magic_name__ = True check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) def __A ( self : Optional[Any] ) -> List[Any]: __magic_name__ , __magic_name__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __magic_name__ = self._prepare_for_class(_lowerCamelCase , _lowerCamelCase ) __magic_name__ = model_class(_lowerCamelCase ) @jax.jit def model_jitted(_lowerCamelCase : List[Any] , **_lowerCamelCase : Tuple ): return model(pixel_values=_lowerCamelCase , **_lowerCamelCase ) with self.subTest("JIT Enabled" ): __magic_name__ = model_jitted(**_lowerCamelCase ).to_tuple() with self.subTest("JIT Disabled" ): with jax.disable_jit(): __magic_name__ = model_jitted(**_lowerCamelCase ).to_tuple() self.assertEqual(len(_lowerCamelCase ) , len(_lowerCamelCase ) ) for jitted_output, output in zip(_lowerCamelCase , _lowerCamelCase ): self.assertEqual(jitted_output.shape , output.shape ) def __snake_case ( ): '''simple docstring''' __magic_name__ = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_flax class UpperCamelCase_ ( unittest.TestCase ): """simple docstring""" @cached_property def __A ( self : List[Any] ) -> Dict: return AutoImageProcessor.from_pretrained("facebook/regnet-y-040" ) if is_vision_available() else None @slow def __A ( self : Optional[int] ) -> Optional[int]: __magic_name__ = FlaxRegNetForImageClassification.from_pretrained("facebook/regnet-y-040" ) __magic_name__ = self.default_image_processor __magic_name__ = prepare_img() __magic_name__ = image_processor(images=_lowerCamelCase , return_tensors="np" ) __magic_name__ = model(**_lowerCamelCase ) # verify the logits __magic_name__ = (1, 10_00) self.assertEqual(outputs.logits.shape , _lowerCamelCase ) __magic_name__ = jnp.array([-0.4_180, -1.5_051, -3.4_836] ) self.assertTrue(jnp.allclose(outputs.logits[0, :3] , _lowerCamelCase , atol=1e-4 ) )
664
'''simple docstring''' import unittest import numpy as np from transformers.file_utils import is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_vision from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import DPTImageProcessor class UpperCamelCase_ ( unittest.TestCase ): """simple docstring""" def __init__( self : str , _lowerCamelCase : str , _lowerCamelCase : Optional[Any]=7 , _lowerCamelCase : Optional[int]=3 , _lowerCamelCase : List[Any]=18 , _lowerCamelCase : Union[str, Any]=30 , _lowerCamelCase : Tuple=4_00 , _lowerCamelCase : Union[str, Any]=True , _lowerCamelCase : Optional[Any]=None , _lowerCamelCase : int=True , _lowerCamelCase : Dict=[0.5, 0.5, 0.5] , _lowerCamelCase : Dict=[0.5, 0.5, 0.5] , ) -> Dict: __magic_name__ = size if size is not None else {"height": 18, "width": 18} __magic_name__ = parent __magic_name__ = batch_size __magic_name__ = num_channels __magic_name__ = image_size __magic_name__ = min_resolution __magic_name__ = max_resolution __magic_name__ = do_resize __magic_name__ = size __magic_name__ = do_normalize __magic_name__ = image_mean __magic_name__ = image_std def __A ( self : int ) -> List[str]: return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, } @require_torch @require_vision class UpperCamelCase_ ( A , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Union[str, Any] = DPTImageProcessor if is_vision_available() else None def __A ( self : Dict ) -> Any: __magic_name__ = DPTImageProcessingTester(self ) @property def __A ( self : str ) -> str: return self.image_processor_tester.prepare_image_processor_dict() def __A ( self : Tuple ) -> List[str]: __magic_name__ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCamelCase , "image_mean" ) ) self.assertTrue(hasattr(_lowerCamelCase , "image_std" ) ) self.assertTrue(hasattr(_lowerCamelCase , "do_normalize" ) ) self.assertTrue(hasattr(_lowerCamelCase , "do_resize" ) ) self.assertTrue(hasattr(_lowerCamelCase , "size" ) ) def __A ( self : List[str] ) -> List[Any]: __magic_name__ = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"height": 18, "width": 18} ) __magic_name__ = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {"height": 42, "width": 42} ) def __A ( self : Union[str, Any] ) -> List[str]: # Initialize image_processing __magic_name__ = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __magic_name__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , Image.Image ) # Test not batched input __magic_name__ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) # Test batched __magic_name__ = image_processing(_lowerCamelCase , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) def __A ( self : Dict ) -> Optional[Any]: # Initialize image_processing __magic_name__ = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __magic_name__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , numpify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , np.ndarray ) # Test not batched input __magic_name__ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) # Test batched __magic_name__ = image_processing(_lowerCamelCase , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) def __A ( self : Optional[int] ) -> Dict: # Initialize image_processing __magic_name__ = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __magic_name__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , torch.Tensor ) # Test not batched input __magic_name__ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) # Test batched __magic_name__ = image_processing(_lowerCamelCase , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , )
664
1
'''simple docstring''' import torch from transformers import AutoModel class UpperCamelCase_ ( torch.nn.Module ): """simple docstring""" def __init__( self : Any , _lowerCamelCase : Optional[int]="sayef/fsner-bert-base-uncased" ) -> List[Any]: super(_lowerCamelCase , self ).__init__() __magic_name__ = AutoModel.from_pretrained(_lowerCamelCase , return_dict=_lowerCamelCase ) __magic_name__ = torch.nn.CosineSimilarity(3 , 1e-08 ) __magic_name__ = torch.nn.Softmax(dim=1 ) def __A ( self : Tuple , **_lowerCamelCase : Union[str, Any] ) -> Optional[int]: return self.bert(**_lowerCamelCase ).last_hidden_state def __A ( self : Dict , _lowerCamelCase : Dict ) -> Dict: return token_embeddings.sum(2 , keepdim=_lowerCamelCase ) def __A ( self : Optional[int] , _lowerCamelCase : Dict , _lowerCamelCase : str , _lowerCamelCase : Tuple=1 ) -> Optional[Any]: return self.softmax(T * self.cos(_lowerCamelCase , _lowerCamelCase ) ) def __A ( self : List[Any] , _lowerCamelCase : Optional[Any] , _lowerCamelCase : Optional[int] ) -> List[str]: __magic_name__ = W_supports["sizes"].tolist() __magic_name__ = W_supports["start_token_id"].item() __magic_name__ = W_supports["end_token_id"].item() del W_supports["sizes"] del W_supports["start_token_id"] del W_supports["end_token_id"] __magic_name__ = self.BERT(**_lowerCamelCase ) __magic_name__ = self.BERT(**_lowerCamelCase ) __magic_name__ = None __magic_name__ = None __magic_name__ = W_supports["input_ids"] == start_token_id __magic_name__ = W_supports["input_ids"] == end_token_id for i, size in enumerate(_lowerCamelCase ): if i == 0: __magic_name__ = 0 else: __magic_name__ = support_sizes[i - 1] __magic_name__ = S[s : s + size][start_token_masks[s : s + size]] __magic_name__ = S[s : s + size][end_token_masks[s : s + size]] __magic_name__ = torch.matmul(q[i] , s_start.T ).sum(1 ).softmax(0 ) __magic_name__ = torch.matmul(q[i] , s_end.T ).sum(1 ).softmax(0 ) if p_starts is not None: __magic_name__ = torch.vstack((p_starts, p_start) ) __magic_name__ = torch.vstack((p_ends, p_end) ) else: __magic_name__ = p_start __magic_name__ = p_end return p_starts, p_ends
664
'''simple docstring''' import numpy class UpperCamelCase_ : """simple docstring""" def __init__( self : Union[str, Any] , _lowerCamelCase : numpy.ndarray , _lowerCamelCase : numpy.ndarray ) -> None: __magic_name__ = input_array # Random initial weights are assigned where first argument is the # number of nodes in previous layer and second argument is the # number of nodes in the next layer. # Random initial weights are assigned. # self.input_array.shape[1] is used to represent number of nodes in input layer. # First hidden layer consists of 4 nodes. __magic_name__ = numpy.random.rand( self.input_array.shape[1] , 4 ) # Random initial values for the first hidden layer. # First hidden layer has 4 nodes. # Second hidden layer has 3 nodes. __magic_name__ = numpy.random.rand( 4 , 3 ) # Random initial values for the second hidden layer. # Second hidden layer has 3 nodes. # Output layer has 1 node. __magic_name__ = numpy.random.rand(3 , 1 ) # Real output values provided. __magic_name__ = output_array # Predicted output values by the neural network. # Predicted_output array initially consists of zeroes. __magic_name__ = numpy.zeros(output_array.shape ) def __A ( self : int ) -> numpy.ndarray: __magic_name__ = sigmoid( numpy.dot(self.input_array , self.input_layer_and_first_hidden_layer_weights ) ) # layer_between_first_hidden_layer_and_second_hidden_layer is the layer # connecting the first hidden set of nodes with the second hidden set of nodes. __magic_name__ = sigmoid( numpy.dot( self.layer_between_input_and_first_hidden_layer , self.first_hidden_layer_and_second_hidden_layer_weights , ) ) # layer_between_second_hidden_layer_and_output is the layer connecting # second hidden layer with the output node. __magic_name__ = sigmoid( numpy.dot( self.layer_between_first_hidden_layer_and_second_hidden_layer , self.second_hidden_layer_and_output_layer_weights , ) ) return self.layer_between_second_hidden_layer_and_output def __A ( self : Dict ) -> None: __magic_name__ = numpy.dot( self.layer_between_first_hidden_layer_and_second_hidden_layer.T , 2 * (self.output_array - self.predicted_output) * sigmoid_derivative(self.predicted_output ) , ) __magic_name__ = numpy.dot( self.layer_between_input_and_first_hidden_layer.T , numpy.dot( 2 * (self.output_array - self.predicted_output) * sigmoid_derivative(self.predicted_output ) , self.second_hidden_layer_and_output_layer_weights.T , ) * sigmoid_derivative( self.layer_between_first_hidden_layer_and_second_hidden_layer ) , ) __magic_name__ = numpy.dot( self.input_array.T , numpy.dot( numpy.dot( 2 * (self.output_array - self.predicted_output) * sigmoid_derivative(self.predicted_output ) , self.second_hidden_layer_and_output_layer_weights.T , ) * sigmoid_derivative( self.layer_between_first_hidden_layer_and_second_hidden_layer ) , self.first_hidden_layer_and_second_hidden_layer_weights.T , ) * sigmoid_derivative(self.layer_between_input_and_first_hidden_layer ) , ) self.input_layer_and_first_hidden_layer_weights += ( updated_input_layer_and_first_hidden_layer_weights ) self.first_hidden_layer_and_second_hidden_layer_weights += ( updated_first_hidden_layer_and_second_hidden_layer_weights ) self.second_hidden_layer_and_output_layer_weights += ( updated_second_hidden_layer_and_output_layer_weights ) def __A ( self : Optional[int] , _lowerCamelCase : numpy.ndarray , _lowerCamelCase : int , _lowerCamelCase : bool ) -> None: for iteration in range(1 , iterations + 1 ): __magic_name__ = self.feedforward() self.back_propagation() if give_loss: __magic_name__ = numpy.mean(numpy.square(output - self.feedforward() ) ) print(f'Iteration {iteration} Loss: {loss}' ) def __A ( self : Tuple , _lowerCamelCase : numpy.ndarray ) -> int: __magic_name__ = input_arr __magic_name__ = sigmoid( numpy.dot(self.array , self.input_layer_and_first_hidden_layer_weights ) ) __magic_name__ = sigmoid( numpy.dot( self.layer_between_input_and_first_hidden_layer , self.first_hidden_layer_and_second_hidden_layer_weights , ) ) __magic_name__ = sigmoid( numpy.dot( self.layer_between_first_hidden_layer_and_second_hidden_layer , self.second_hidden_layer_and_output_layer_weights , ) ) return int(self.layer_between_second_hidden_layer_and_output > 0.6 ) def __snake_case ( lowerCamelCase_ : numpy.ndarray ): '''simple docstring''' return 1 / (1 + numpy.exp(-value )) def __snake_case ( lowerCamelCase_ : numpy.ndarray ): '''simple docstring''' return (value) * (1 - (value)) def __snake_case ( ): '''simple docstring''' __magic_name__ = numpy.array( ( [0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1], ) , dtype=numpy.floataa , ) # True output values for the given input values. __magic_name__ = numpy.array(([0], [1], [1], [0], [1], [0], [0], [1]) , dtype=numpy.floataa ) # Calling neural network class. __magic_name__ = TwoHiddenLayerNeuralNetwork( input_array=lowerCamelCase_ , output_array=lowerCamelCase_ ) # Calling training function. # Set give_loss to True if you want to see loss in every iteration. neural_network.train(output=lowerCamelCase_ , iterations=10 , give_loss=lowerCamelCase_ ) return neural_network.predict(numpy.array(([1, 1, 1]) , dtype=numpy.floataa ) ) if __name__ == "__main__": example()
664
1
'''simple docstring''' import argparse import pathlib import fairseq import torch from fairseq.models.roberta import RobertaModel as FairseqRobertaModel from fairseq.modules import TransformerSentenceEncoderLayer from packaging import version from transformers import XLMRobertaConfig, XLMRobertaXLForMaskedLM, XLMRobertaXLForSequenceClassification from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertSelfAttention, BertSelfOutput, ) from transformers.models.roberta.modeling_roberta import RobertaAttention from transformers.utils import logging if version.parse(fairseq.__version__) < version.parse('1.0.0a'): raise Exception('requires fairseq >= 1.0.0a') logging.set_verbosity_info() __magic_name__ : Any =logging.get_logger(__name__) __magic_name__ : List[Any] ='Hello world! cécé herlolip' def __snake_case ( lowerCamelCase_ : str , lowerCamelCase_ : str , lowerCamelCase_ : bool ): '''simple docstring''' __magic_name__ = FairseqRobertaModel.from_pretrained(lowerCamelCase_ ) roberta.eval() # disable dropout __magic_name__ = roberta.model.encoder.sentence_encoder __magic_name__ = XLMRobertaConfig( vocab_size=roberta_sent_encoder.embed_tokens.num_embeddings , hidden_size=roberta.cfg.model.encoder_embed_dim , num_hidden_layers=roberta.cfg.model.encoder_layers , num_attention_heads=roberta.cfg.model.encoder_attention_heads , intermediate_size=roberta.cfg.model.encoder_ffn_embed_dim , max_position_embeddings=514 , type_vocab_size=1 , layer_norm_eps=1e-5 , ) if classification_head: __magic_name__ = roberta.model.classification_heads["mnli"].out_proj.weight.shape[0] print("Our RoBERTa config:" , lowerCamelCase_ ) __magic_name__ = XLMRobertaXLForSequenceClassification(lowerCamelCase_ ) if classification_head else XLMRobertaXLForMaskedLM(lowerCamelCase_ ) model.eval() # Now let's copy all the weights. # Embeddings __magic_name__ = roberta_sent_encoder.embed_tokens.weight __magic_name__ = roberta_sent_encoder.embed_positions.weight __magic_name__ = torch.zeros_like( model.roberta.embeddings.token_type_embeddings.weight ) # just zero them out b/c RoBERTa doesn't use them. __magic_name__ = roberta_sent_encoder.layer_norm.weight __magic_name__ = roberta_sent_encoder.layer_norm.bias for i in range(config.num_hidden_layers ): # Encoder: start of layer __magic_name__ = model.roberta.encoder.layer[i] __magic_name__ = roberta_sent_encoder.layers[i] __magic_name__ = layer.attention __magic_name__ = roberta_layer.self_attn_layer_norm.weight __magic_name__ = roberta_layer.self_attn_layer_norm.bias # self attention __magic_name__ = layer.attention.self assert ( roberta_layer.self_attn.k_proj.weight.data.shape == roberta_layer.self_attn.q_proj.weight.data.shape == roberta_layer.self_attn.v_proj.weight.data.shape == torch.Size((config.hidden_size, config.hidden_size) ) ) __magic_name__ = roberta_layer.self_attn.q_proj.weight __magic_name__ = roberta_layer.self_attn.q_proj.bias __magic_name__ = roberta_layer.self_attn.k_proj.weight __magic_name__ = roberta_layer.self_attn.k_proj.bias __magic_name__ = roberta_layer.self_attn.v_proj.weight __magic_name__ = roberta_layer.self_attn.v_proj.bias # self-attention output __magic_name__ = layer.attention.output assert self_output.dense.weight.shape == roberta_layer.self_attn.out_proj.weight.shape __magic_name__ = roberta_layer.self_attn.out_proj.weight __magic_name__ = roberta_layer.self_attn.out_proj.bias # this one is final layer norm __magic_name__ = roberta_layer.final_layer_norm.weight __magic_name__ = roberta_layer.final_layer_norm.bias # intermediate __magic_name__ = layer.intermediate assert intermediate.dense.weight.shape == roberta_layer.fca.weight.shape __magic_name__ = roberta_layer.fca.weight __magic_name__ = roberta_layer.fca.bias # output __magic_name__ = layer.output assert bert_output.dense.weight.shape == roberta_layer.fca.weight.shape __magic_name__ = roberta_layer.fca.weight __magic_name__ = roberta_layer.fca.bias # end of layer if classification_head: __magic_name__ = roberta.model.classification_heads["mnli"].dense.weight __magic_name__ = roberta.model.classification_heads["mnli"].dense.bias __magic_name__ = roberta.model.classification_heads["mnli"].out_proj.weight __magic_name__ = roberta.model.classification_heads["mnli"].out_proj.bias else: # LM Head __magic_name__ = roberta.model.encoder.lm_head.dense.weight __magic_name__ = roberta.model.encoder.lm_head.dense.bias __magic_name__ = roberta.model.encoder.lm_head.layer_norm.weight __magic_name__ = roberta.model.encoder.lm_head.layer_norm.bias __magic_name__ = roberta.model.encoder.lm_head.weight __magic_name__ = roberta.model.encoder.lm_head.bias # Let's check that we get the same results. __magic_name__ = roberta.encode(lowerCamelCase_ ).unsqueeze(0 ) # batch of size 1 __magic_name__ = model(lowerCamelCase_ )[0] if classification_head: __magic_name__ = roberta.model.classification_heads["mnli"](roberta.extract_features(lowerCamelCase_ ) ) else: __magic_name__ = roberta.model(lowerCamelCase_ )[0] print(our_output.shape , their_output.shape ) __magic_name__ = torch.max(torch.abs(our_output - their_output ) ).item() print(F'max_absolute_diff = {max_absolute_diff}' ) # ~ 1e-7 __magic_name__ = torch.allclose(lowerCamelCase_ , lowerCamelCase_ , atol=1e-3 ) print("Do both models output the same tensors?" , "🔥" if success else "💩" ) if not success: raise Exception("Something went wRoNg" ) pathlib.Path(lowerCamelCase_ ).mkdir(parents=lowerCamelCase_ , exist_ok=lowerCamelCase_ ) print(F'Saving model to {pytorch_dump_folder_path}' ) model.save_pretrained(lowerCamelCase_ ) if __name__ == "__main__": __magic_name__ : List[Any] =argparse.ArgumentParser() # Required parameters parser.add_argument( '--roberta_checkpoint_path', default=None, type=str, required=True, help='Path the official PyTorch dump.' ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) parser.add_argument( '--classification_head', action='store_true', help='Whether to convert a final classification head.' ) __magic_name__ : Dict =parser.parse_args() convert_xlm_roberta_xl_checkpoint_to_pytorch( args.roberta_checkpoint_path, args.pytorch_dump_folder_path, args.classification_head )
664
'''simple docstring''' import torch from transformers import AutoModel class UpperCamelCase_ ( torch.nn.Module ): """simple docstring""" def __init__( self : Any , _lowerCamelCase : Optional[int]="sayef/fsner-bert-base-uncased" ) -> List[Any]: super(_lowerCamelCase , self ).__init__() __magic_name__ = AutoModel.from_pretrained(_lowerCamelCase , return_dict=_lowerCamelCase ) __magic_name__ = torch.nn.CosineSimilarity(3 , 1e-08 ) __magic_name__ = torch.nn.Softmax(dim=1 ) def __A ( self : Tuple , **_lowerCamelCase : Union[str, Any] ) -> Optional[int]: return self.bert(**_lowerCamelCase ).last_hidden_state def __A ( self : Dict , _lowerCamelCase : Dict ) -> Dict: return token_embeddings.sum(2 , keepdim=_lowerCamelCase ) def __A ( self : Optional[int] , _lowerCamelCase : Dict , _lowerCamelCase : str , _lowerCamelCase : Tuple=1 ) -> Optional[Any]: return self.softmax(T * self.cos(_lowerCamelCase , _lowerCamelCase ) ) def __A ( self : List[Any] , _lowerCamelCase : Optional[Any] , _lowerCamelCase : Optional[int] ) -> List[str]: __magic_name__ = W_supports["sizes"].tolist() __magic_name__ = W_supports["start_token_id"].item() __magic_name__ = W_supports["end_token_id"].item() del W_supports["sizes"] del W_supports["start_token_id"] del W_supports["end_token_id"] __magic_name__ = self.BERT(**_lowerCamelCase ) __magic_name__ = self.BERT(**_lowerCamelCase ) __magic_name__ = None __magic_name__ = None __magic_name__ = W_supports["input_ids"] == start_token_id __magic_name__ = W_supports["input_ids"] == end_token_id for i, size in enumerate(_lowerCamelCase ): if i == 0: __magic_name__ = 0 else: __magic_name__ = support_sizes[i - 1] __magic_name__ = S[s : s + size][start_token_masks[s : s + size]] __magic_name__ = S[s : s + size][end_token_masks[s : s + size]] __magic_name__ = torch.matmul(q[i] , s_start.T ).sum(1 ).softmax(0 ) __magic_name__ = torch.matmul(q[i] , s_end.T ).sum(1 ).softmax(0 ) if p_starts is not None: __magic_name__ = torch.vstack((p_starts, p_start) ) __magic_name__ = torch.vstack((p_ends, p_end) ) else: __magic_name__ = p_start __magic_name__ = p_end return p_starts, p_ends
664
1
'''simple docstring''' import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation __magic_name__ : Union[str, Any] =logging.get_logger(__name__) __magic_name__ : List[str] ={'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'} __magic_name__ : Optional[Any] ={ 'tokenizer_file': { 'EleutherAI/gpt-neox-20b': 'https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/tokenizer.json', }, } __magic_name__ : int ={ 'gpt-neox-20b': 20_48, } class UpperCamelCase_ ( A ): """simple docstring""" UpperCAmelCase__ : str = VOCAB_FILES_NAMES UpperCAmelCase__ : Tuple = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase__ : Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase__ : Any = ['''input_ids''', '''attention_mask'''] def __init__( self : Union[str, Any] , _lowerCamelCase : Union[str, Any]=None , _lowerCamelCase : Optional[int]=None , _lowerCamelCase : Union[str, Any]=None , _lowerCamelCase : Tuple="<|endoftext|>" , _lowerCamelCase : Dict="<|endoftext|>" , _lowerCamelCase : str="<|endoftext|>" , _lowerCamelCase : List[str]=False , **_lowerCamelCase : Any , ) -> List[Any]: super().__init__( _lowerCamelCase , _lowerCamelCase , tokenizer_file=_lowerCamelCase , unk_token=_lowerCamelCase , bos_token=_lowerCamelCase , eos_token=_lowerCamelCase , add_prefix_space=_lowerCamelCase , **_lowerCamelCase , ) __magic_name__ = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("add_prefix_space" , _lowerCamelCase ) != add_prefix_space: __magic_name__ = getattr(_lowerCamelCase , pre_tok_state.pop("type" ) ) __magic_name__ = add_prefix_space __magic_name__ = pre_tok_class(**_lowerCamelCase ) __magic_name__ = add_prefix_space def __A ( self : Union[str, Any] , _lowerCamelCase : str , _lowerCamelCase : Optional[str] = None ) -> Tuple[str]: __magic_name__ = self._tokenizer.model.save(_lowerCamelCase , name=_lowerCamelCase ) return tuple(_lowerCamelCase ) def __A ( self : int , _lowerCamelCase : "Conversation" ) -> List[int]: __magic_name__ = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(_lowerCamelCase , add_special_tokens=_lowerCamelCase ) + [self.eos_token_id] ) if len(_lowerCamelCase ) > self.model_max_length: __magic_name__ = input_ids[-self.model_max_length :] return input_ids
664
'''simple docstring''' # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from ...utils import deprecate from ..controlnet.pipeline_flax_controlnet import FlaxStableDiffusionControlNetPipeline # noqa: F401 deprecate( 'stable diffusion controlnet', '0.22.0', 'Importing `FlaxStableDiffusionControlNetPipeline` from diffusers.pipelines.stable_diffusion.flax_pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import FlaxStableDiffusionControlNetPipeline` instead.', standard_warn=False, stacklevel=3, )
664
1
'''simple docstring''' import argparse import json import os from collections import OrderedDict import numpy as np import tensorflow as tf import torch def __snake_case ( lowerCamelCase_ : List[str] ): '''simple docstring''' __magic_name__ = os.path.join(args.tf_model_dir , "parameters.json" ) __magic_name__ = json.loads(open(lowerCamelCase_ ).read() ) if not params: raise ValueError( F'It seems that the json file at {parameter_file} is empty. Make sure you have a correct json file.' ) if not args.output.endswith(".pt" ): __magic_name__ = args.output + ".pt" __magic_name__ = OrderedDict() with tf.device("/CPU:0" ): __magic_name__ = tf.train.load_checkpoint(args.tf_model_dir ) __magic_name__ = reader.get_variable_to_shape_map() for key_name in shapes.keys(): __magic_name__ = reader.get_tensor(lowerCamelCase_ ).astype(np.floataa ) if key_name.endswith("/adam_m" ) or key_name.endswith("/adam_v" ): continue if key_name.startswith("pasts/" ): if key_name.startswith("pasts/mlp" ): __magic_name__ = int(key_name[9] ) elif key_name.startswith("pasts/out" ): __magic_name__ = 8 __magic_name__ = "model.sqout.%d.weight" % (player * 2) # enter to nn.Sequencial with Tanh, so 2 at a time __magic_name__ = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix __magic_name__ = torch.tensor(lowerCamelCase_ ) elif key_name.startswith("model/moe" ): __magic_name__ = int(key_name[9:].split("/" )[0] ) if key_name.endswith("/switch_gating/kernel" ): __magic_name__ = "model.blocks.%d.feed_forward.mlp.router.classifier.weight" % player __magic_name__ = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix __magic_name__ = torch.tensor(lowerCamelCase_ ) elif key_name.endswith("/softmlp/kernel" ): __magic_name__ = "model.blocks.%d.feed_forward.soft_bypass_mlp.weight" % player __magic_name__ = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix __magic_name__ = torch.tensor(lowerCamelCase_ ) elif key_name.endswith("/wo/kernel" ) or key_name.endswith("/wi/kernel" ): __magic_name__ = key_name[-9:-7] for i in range(16 ): __magic_name__ = "model.blocks.%d.feed_forward.mlp.experts.expert_%d.%s.weight" % (player, i, nlayer) __magic_name__ = ( vnp[i].transpose([1, 0] ).copy() ) # In Mesh-Tensorflow, it is one array, so it is divided __magic_name__ = torch.tensor(lowerCamelCase_ ) elif key_name.startswith("model/mlp" ): __magic_name__ = int(key_name[9:].split("/" )[0] ) if key_name.endswith("/p1/kernel" ): __magic_name__ = "model.blocks.%d.feed_forward.mlp.wi.weight" % player __magic_name__ = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix __magic_name__ = torch.tensor(lowerCamelCase_ ) elif key_name.endswith("/p1/bias" ): __magic_name__ = "model.blocks.%d.feed_forward.mlp.wi.bias" % player __magic_name__ = vnp.copy() # same because it is one dimensional __magic_name__ = torch.tensor(lowerCamelCase_ ) elif key_name.endswith("/p2/kernel" ): __magic_name__ = "model.blocks.%d.feed_forward.mlp.wo.weight" % player __magic_name__ = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix __magic_name__ = torch.tensor(lowerCamelCase_ ) elif key_name.endswith("/p2/bias" ): __magic_name__ = "model.blocks.%d.feed_forward.mlp.wo.bias" % player __magic_name__ = vnp.copy() # same because it is one dimensional __magic_name__ = torch.tensor(lowerCamelCase_ ) elif key_name.startswith("model/ln" ): __magic_name__ = int(key_name[8:].split("/" )[0] ) if key_name.endswith("/b" ): __magic_name__ = "model.blocks.%d.feed_forward.norm.bias" % player __magic_name__ = vnp.copy() # same because it is one dimensional __magic_name__ = torch.tensor(lowerCamelCase_ ) elif key_name.endswith("/g" ): __magic_name__ = "model.blocks.%d.feed_forward.norm.weight" % player __magic_name__ = vnp.copy() # same because it is one dimensional __magic_name__ = torch.tensor(lowerCamelCase_ ) elif key_name.startswith("model/att" ): __magic_name__ = int(key_name[9:].split("/" )[0] ) if key_name.endswith("/qkv/kernel" ): __magic_name__ = vnp.copy() # Compute same dimension as Mesh-tensorflow using einsum __magic_name__ = state[:, 0, :, :] __magic_name__ = state[:, 1, :, :] __magic_name__ = state[:, 2, :, :] __magic_name__ = ( state_q.reshape([state_q.shape[0], state_q.shape[1] * state_q.shape[2]] ) .transpose([1, 0] ) .copy() ) # Mesh-Tensorflow is a diagonal matrix __magic_name__ = ( state_k.reshape([state_k.shape[0], state_k.shape[1] * state_k.shape[2]] ) .transpose([1, 0] ) .copy() ) # Mesh-Tensorflow is a diagonal matrix __magic_name__ = ( state_v.reshape([state_v.shape[0], state_v.shape[1] * state_v.shape[2]] ) .transpose([1, 0] ) .copy() ) # Mesh-Tensorflow is a diagonal matrix __magic_name__ = "model.blocks.%d.self_attn.self_attn.q_proj.weight" % player __magic_name__ = torch.tensor(lowerCamelCase_ ) __magic_name__ = "model.blocks.%d.self_attn.self_attn.k_proj.weight" % player __magic_name__ = torch.tensor(lowerCamelCase_ ) __magic_name__ = "model.blocks.%d.self_attn.self_attn.v_proj.weight" % player __magic_name__ = torch.tensor(lowerCamelCase_ ) elif key_name.endswith("/o/kernel" ): __magic_name__ = "model.blocks.%d.self_attn.self_attn.out_proj.weight" % player __magic_name__ = ( vnp.reshape([vnp.shape[0] * vnp.shape[1], vnp.shape[2]] ).transpose([1, 0] ).copy() ) # Mesh-Tensorflow is a diagonal matrix __magic_name__ = torch.tensor(lowerCamelCase_ ) elif key_name.startswith("model/an" ): __magic_name__ = int(key_name[8:].split("/" )[0] ) if key_name.endswith("/b" ): __magic_name__ = "model.blocks.%d.self_attn.norm.bias" % player __magic_name__ = vnp.copy() # same because it is one dimensional __magic_name__ = torch.tensor(lowerCamelCase_ ) elif key_name.endswith("/g" ): __magic_name__ = "model.blocks.%d.self_attn.norm.weight" % player __magic_name__ = vnp.copy() # same because it is one dimensional __magic_name__ = torch.tensor(lowerCamelCase_ ) elif ( key_name.startswith("model/wte" ) or key_name.startswith("model/wpe" ) or key_name.startswith("model/ete" ) ): __magic_name__ = {"wte": "embed_tokens", "wpe": "position_embeddings", "ete": "extra_position_embeddings"}[ key_name[-3:] ] __magic_name__ = "model.%s.weight" % nlayer __magic_name__ = vnp.copy() # same in embedded __magic_name__ = torch.tensor(lowerCamelCase_ ) if key_name.startswith("model/wte" ): __magic_name__ = "lm_head.weight" __magic_name__ = vnp.copy() # same in embedded __magic_name__ = torch.tensor(lowerCamelCase_ ) elif key_name.startswith("model/wob" ): __magic_name__ = "final_logits_bias" __magic_name__ = vnp.copy() # same in embedded __magic_name__ = state.reshape((1, -1) ) __magic_name__ = torch.tensor(lowerCamelCase_ ) elif key_name == "model/dense/kernel": __magic_name__ = "model.last_project.weight" __magic_name__ = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix __magic_name__ = torch.tensor(lowerCamelCase_ ) elif key_name == "model/dense_1/bias": __magic_name__ = "model.last_project.bias" __magic_name__ = vnp.copy() # same because it is one dimensional __magic_name__ = torch.tensor(lowerCamelCase_ ) torch.save(lowerCamelCase_ , args.output ) if __name__ == "__main__": __magic_name__ : Optional[int] =argparse.ArgumentParser( description='model converter.', formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument('--tf_model_dir', metavar='PATH', type=str, required=True, help='import model') parser.add_argument('--output', metavar='PATH', type=str, required=True, help='output model') __magic_name__ : int =parser.parse_args() convert_tf_gptsan_to_pt(args)
664
'''simple docstring''' import argparse from tax import checkpoints from transformers import AutoConfig, FlaxAutoModelForSeqaSeqLM def __snake_case ( lowerCamelCase_ : Any , lowerCamelCase_ : int , lowerCamelCase_ : Optional[Any] ): '''simple docstring''' __magic_name__ = AutoConfig.from_pretrained(lowerCamelCase_ ) __magic_name__ = FlaxAutoModelForSeqaSeqLM.from_config(config=lowerCamelCase_ ) __magic_name__ = checkpoints.load_tax_checkpoint(lowerCamelCase_ ) __magic_name__ = "wi_0" in tax_model["target"]["encoder"]["layers_0"]["mlp"] if config.model_type == "t5": __magic_name__ = "SelfAttention" if config.model_type == "longt5" and config.encoder_attention_type == "local": __magic_name__ = "LocalSelfAttention" elif config.model_type == "longt5" and config.encoder_attention_type == "transient-global": __magic_name__ = "TransientGlobalSelfAttention" else: raise ValueError( "Given config is expected to have `model_type='t5'`, or `model_type='longt5` with `encoder_attention_type`" " attribute with a value from ['local', 'transient-global]." ) # Encoder for layer_index in range(config.num_layers ): __magic_name__ = F'layers_{str(lowerCamelCase_ )}' # Self-Attention __magic_name__ = tax_model["target"]["encoder"][layer_name]["attention"]["key"]["kernel"] __magic_name__ = tax_model["target"]["encoder"][layer_name]["attention"]["out"]["kernel"] __magic_name__ = tax_model["target"]["encoder"][layer_name]["attention"]["query"]["kernel"] __magic_name__ = tax_model["target"]["encoder"][layer_name]["attention"]["value"]["kernel"] # Global input layer norm if config.model_type == "longt5" and config.encoder_attention_type == "transient-global": __magic_name__ = tax_model["target"]["encoder"][layer_name]["attention"]["T5LayerNorm_0"]["scale"] # Layer Normalization __magic_name__ = tax_model["target"]["encoder"][layer_name]["pre_attention_layer_norm"]["scale"] if split_mlp_wi: __magic_name__ = tax_model["target"]["encoder"][layer_name]["mlp"]["wi_0"]["kernel"] __magic_name__ = tax_model["target"]["encoder"][layer_name]["mlp"]["wi_1"]["kernel"] else: __magic_name__ = tax_model["target"]["encoder"][layer_name]["mlp"]["wi"]["kernel"] __magic_name__ = tax_model["target"]["encoder"][layer_name]["mlp"]["wo"]["kernel"] # Layer Normalization __magic_name__ = tax_model["target"]["encoder"][layer_name]["pre_mlp_layer_norm"]["scale"] # Assigning __magic_name__ = flax_model.params["encoder"]["block"][str(lowerCamelCase_ )]["layer"] __magic_name__ = tax_attention_key __magic_name__ = tax_attention_out __magic_name__ = tax_attention_query __magic_name__ = tax_attention_value __magic_name__ = tax_attention_layer_norm # Global input layer norm if config.model_type == "longt5" and config.encoder_attention_type == "transient-global": __magic_name__ = tax_global_layer_norm if split_mlp_wi: __magic_name__ = tax_mlp_wi_a __magic_name__ = tax_mlp_wi_a else: __magic_name__ = tax_mlp_wi __magic_name__ = tax_mlp_wo __magic_name__ = tax_mlp_layer_norm __magic_name__ = flax_model_encoder_layer_block # Only for layer 0: __magic_name__ = tax_model["target"]["encoder"]["relpos_bias"]["rel_embedding"].T __magic_name__ = tax_encoder_rel_embedding # Side/global relative position_bias + layer norm if config.model_type == "longt5" and config.encoder_attention_type == "transient-global": __magic_name__ = tax_model["target"]["encoder"]["side_relpos_bias"]["rel_embedding"].T __magic_name__ = tax_encoder_global_rel_embedding # Assigning __magic_name__ = tax_model["target"]["encoder"]["encoder_norm"]["scale"] __magic_name__ = tax_encoder_norm # Decoder for layer_index in range(config.num_layers ): __magic_name__ = F'layers_{str(lowerCamelCase_ )}' # Self-Attention __magic_name__ = tax_model["target"]["decoder"][layer_name]["self_attention"]["key"]["kernel"] __magic_name__ = tax_model["target"]["decoder"][layer_name]["self_attention"]["out"]["kernel"] __magic_name__ = tax_model["target"]["decoder"][layer_name]["self_attention"]["query"]["kernel"] __magic_name__ = tax_model["target"]["decoder"][layer_name]["self_attention"]["value"]["kernel"] # Layer Normalization __magic_name__ = tax_model["target"]["decoder"][layer_name]["pre_self_attention_layer_norm"][ "scale" ] # Encoder-Decoder-Attention __magic_name__ = tax_model["target"]["decoder"][layer_name]["encoder_decoder_attention"] __magic_name__ = tax_enc_dec_attention_module["key"]["kernel"] __magic_name__ = tax_enc_dec_attention_module["out"]["kernel"] __magic_name__ = tax_enc_dec_attention_module["query"]["kernel"] __magic_name__ = tax_enc_dec_attention_module["value"]["kernel"] # Layer Normalization __magic_name__ = tax_model["target"]["decoder"][layer_name]["pre_cross_attention_layer_norm"]["scale"] # MLP if split_mlp_wi: __magic_name__ = tax_model["target"]["decoder"][layer_name]["mlp"]["wi_0"]["kernel"] __magic_name__ = tax_model["target"]["decoder"][layer_name]["mlp"]["wi_1"]["kernel"] else: __magic_name__ = tax_model["target"]["decoder"][layer_name]["mlp"]["wi"]["kernel"] __magic_name__ = tax_model["target"]["decoder"][layer_name]["mlp"]["wo"]["kernel"] # Layer Normalization __magic_name__ = tax_model["target"]["decoder"][layer_name]["pre_mlp_layer_norm"]["scale"] # Assigning __magic_name__ = flax_model.params["decoder"]["block"][str(lowerCamelCase_ )]["layer"] __magic_name__ = tax_attention_key __magic_name__ = tax_attention_out __magic_name__ = tax_attention_query __magic_name__ = tax_attention_value __magic_name__ = tax_pre_attention_layer_norm __magic_name__ = tax_enc_dec_attention_key __magic_name__ = tax_enc_dec_attention_out __magic_name__ = tax_enc_dec_attention_query __magic_name__ = tax_enc_dec_attention_value __magic_name__ = tax_cross_layer_norm if split_mlp_wi: __magic_name__ = tax_mlp_wi_a __magic_name__ = tax_mlp_wi_a else: __magic_name__ = tax_mlp_wi __magic_name__ = tax_mlp_wo __magic_name__ = txa_mlp_layer_norm __magic_name__ = flax_model_decoder_layer_block # Decoder Normalization __magic_name__ = tax_model["target"]["decoder"]["decoder_norm"]["scale"] __magic_name__ = txa_decoder_norm # Only for layer 0: __magic_name__ = tax_model["target"]["decoder"]["relpos_bias"]["rel_embedding"].T __magic_name__ = tax_decoder_rel_embedding # Token Embeddings __magic_name__ = tax_model["target"]["token_embedder"]["embedding"] __magic_name__ = txa_token_embeddings # LM Head (only in v1.1 and LongT5 checkpoints) if "logits_dense" in tax_model["target"]["decoder"]: __magic_name__ = tax_model["target"]["decoder"]["logits_dense"]["kernel"] flax_model.save_pretrained(lowerCamelCase_ ) print("T5X Model was sucessfully converted!" ) if __name__ == "__main__": __magic_name__ : Optional[Any] =argparse.ArgumentParser() # Required parameters parser.add_argument( '--t5x_checkpoint_path', default=None, type=str, required=True, help='Path the T5X checkpoint.' ) parser.add_argument('--config_name', default=None, type=str, required=True, help='Config name of LongT5/T5 model.') parser.add_argument( '--flax_dump_folder_path', default=None, type=str, required=True, help='Path to the output FLAX model.' ) __magic_name__ : Optional[int] =parser.parse_args() convert_tax_checkpoint_to_flax(args.tax_checkpoint_path, args.config_name, args.flax_dump_folder_path)
664
1
'''simple docstring''' from __future__ import annotations import queue class UpperCamelCase_ : """simple docstring""" def __init__( self : Dict , _lowerCamelCase : Union[str, Any] ) -> List[Any]: __magic_name__ = data __magic_name__ = None __magic_name__ = None def __snake_case ( ): '''simple docstring''' print("\n********Press N to stop entering at any point of time********\n" ) __magic_name__ = input("Enter the value of the root node: " ).strip().lower() __magic_name__ = queue.Queue() __magic_name__ = TreeNode(int(lowerCamelCase_ ) ) q.put(lowerCamelCase_ ) while not q.empty(): __magic_name__ = q.get() __magic_name__ = F'Enter the left node of {node_found.data}: ' __magic_name__ = input(lowerCamelCase_ ).strip().lower() or "n" if check == "n": return tree_node __magic_name__ = TreeNode(int(lowerCamelCase_ ) ) __magic_name__ = left_node q.put(lowerCamelCase_ ) __magic_name__ = F'Enter the right node of {node_found.data}: ' __magic_name__ = input(lowerCamelCase_ ).strip().lower() or "n" if check == "n": return tree_node __magic_name__ = TreeNode(int(lowerCamelCase_ ) ) __magic_name__ = right_node q.put(lowerCamelCase_ ) raise def __snake_case ( lowerCamelCase_ : TreeNode ): '''simple docstring''' if not isinstance(lowerCamelCase_ , lowerCamelCase_ ) or not node: return print(node.data , end="," ) pre_order(node.left ) pre_order(node.right ) def __snake_case ( lowerCamelCase_ : TreeNode ): '''simple docstring''' if not isinstance(lowerCamelCase_ , lowerCamelCase_ ) or not node: return in_order(node.left ) print(node.data , end="," ) in_order(node.right ) def __snake_case ( lowerCamelCase_ : TreeNode ): '''simple docstring''' if not isinstance(lowerCamelCase_ , lowerCamelCase_ ) or not node: return post_order(node.left ) post_order(node.right ) print(node.data , end="," ) def __snake_case ( lowerCamelCase_ : TreeNode ): '''simple docstring''' if not isinstance(lowerCamelCase_ , lowerCamelCase_ ) or not node: return __magic_name__ = queue.Queue() q.put(lowerCamelCase_ ) while not q.empty(): __magic_name__ = q.get() print(node_dequeued.data , end="," ) if node_dequeued.left: q.put(node_dequeued.left ) if node_dequeued.right: q.put(node_dequeued.right ) def __snake_case ( lowerCamelCase_ : TreeNode ): '''simple docstring''' if not isinstance(lowerCamelCase_ , lowerCamelCase_ ) or not node: return __magic_name__ = queue.Queue() q.put(lowerCamelCase_ ) while not q.empty(): __magic_name__ = [] while not q.empty(): __magic_name__ = q.get() print(node_dequeued.data , end="," ) if node_dequeued.left: list_.append(node_dequeued.left ) if node_dequeued.right: list_.append(node_dequeued.right ) print() for node in list_: q.put(lowerCamelCase_ ) def __snake_case ( lowerCamelCase_ : TreeNode ): '''simple docstring''' if not isinstance(lowerCamelCase_ , lowerCamelCase_ ) or not node: return __magic_name__ = [] __magic_name__ = node while n or stack: while n: # start from root node, find its left child print(n.data , end="," ) stack.append(lowerCamelCase_ ) __magic_name__ = n.left # end of while means current node doesn't have left child __magic_name__ = stack.pop() # start to traverse its right child __magic_name__ = n.right def __snake_case ( lowerCamelCase_ : TreeNode ): '''simple docstring''' if not isinstance(lowerCamelCase_ , lowerCamelCase_ ) or not node: return __magic_name__ = [] __magic_name__ = node while n or stack: while n: stack.append(lowerCamelCase_ ) __magic_name__ = n.left __magic_name__ = stack.pop() print(n.data , end="," ) __magic_name__ = n.right def __snake_case ( lowerCamelCase_ : TreeNode ): '''simple docstring''' if not isinstance(lowerCamelCase_ , lowerCamelCase_ ) or not node: return __magic_name__ , __magic_name__ = [], [] __magic_name__ = node stacka.append(lowerCamelCase_ ) while stacka: # to find the reversed order of post order, store it in stack2 __magic_name__ = stacka.pop() if n.left: stacka.append(n.left ) if n.right: stacka.append(n.right ) stacka.append(lowerCamelCase_ ) while stacka: # pop up from stack2 will be the post order print(stacka.pop().data , end="," ) def __snake_case ( lowerCamelCase_ : str = "" , lowerCamelCase_ : Optional[int]=50 , lowerCamelCase_ : Union[str, Any]="*" ): '''simple docstring''' if not s: return "\n" + width * char __magic_name__ , __magic_name__ = divmod(width - len(lowerCamelCase_ ) - 2 , 2 ) return F'{left * char} {s} {(left + extra) * char}' if __name__ == "__main__": import doctest doctest.testmod() print(prompt('Binary Tree Traversals')) __magic_name__ : TreeNode =build_tree() print(prompt('Pre Order Traversal')) pre_order(node) print(prompt() + '\n') print(prompt('In Order Traversal')) in_order(node) print(prompt() + '\n') print(prompt('Post Order Traversal')) post_order(node) print(prompt() + '\n') print(prompt('Level Order Traversal')) level_order(node) print(prompt() + '\n') print(prompt('Actual Level Order Traversal')) level_order_actual(node) print('*' * 50 + '\n') print(prompt('Pre Order Traversal - Iteration Version')) pre_order_iter(node) print(prompt() + '\n') print(prompt('In Order Traversal - Iteration Version')) in_order_iter(node) print(prompt() + '\n') print(prompt('Post Order Traversal - Iteration Version')) post_order_iter(node) print(prompt())
664
'''simple docstring''' import unittest from transformers import load_tool from transformers.utils import is_torch_available if is_torch_available(): import torch from transformers.testing_utils import require_torch from .test_tools_common import ToolTesterMixin @require_torch class UpperCamelCase_ ( unittest.TestCase , A ): """simple docstring""" def __A ( self : Optional[int] ) -> Any: __magic_name__ = load_tool("text-to-speech" ) self.tool.setup() def __A ( self : Union[str, Any] ) -> int: # SpeechT5 isn't deterministic torch.manual_seed(0 ) __magic_name__ = self.tool("hey" ) __magic_name__ = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] , torch.tensor([-0.0_005_966_668_832_115_829, -0.0_003_657_640_190_795_064, -0.00_013_439_502_799_883_485] ) , ) ) def __A ( self : List[str] ) -> int: # SpeechT5 isn't deterministic torch.manual_seed(0 ) __magic_name__ = self.tool("hey" ) __magic_name__ = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] , torch.tensor([-0.0_005_966_668_832_115_829, -0.0_003_657_640_190_795_064, -0.00_013_439_502_799_883_485] ) , ) )
664
1
'''simple docstring''' from __future__ import annotations from math import pi from typing import Protocol import matplotlib.pyplot as plt import numpy as np class UpperCamelCase_ ( A ): """simple docstring""" def __A ( self : Any , _lowerCamelCase : float ) -> float: return 0.0 def __snake_case ( lowerCamelCase_ : np.ndarray , lowerCamelCase_ : int ): '''simple docstring''' __magic_name__ = min([-20, np.min(fft_results[1 : samplerate // 2 - 1] )] ) __magic_name__ = max([20, np.max(fft_results[1 : samplerate // 2 - 1] )] ) return lowest, highest def __snake_case ( lowerCamelCase_ : FilterType , lowerCamelCase_ : int ): '''simple docstring''' __magic_name__ = 512 __magic_name__ = [1] + [0] * (size - 1) __magic_name__ = [filter_type.process(lowerCamelCase_ ) for item in inputs] __magic_name__ = [0] * (samplerate - size) # zero-padding outputs += filler __magic_name__ = np.abs(np.fft.fft(lowerCamelCase_ ) ) __magic_name__ = 20 * np.logaa(lowerCamelCase_ ) # Frequencies on log scale from 24 to nyquist frequency plt.xlim(24 , samplerate / 2 - 1 ) plt.xlabel("Frequency (Hz)" ) plt.xscale("log" ) # Display within reasonable bounds __magic_name__ = get_bounds(lowerCamelCase_ , lowerCamelCase_ ) plt.ylim(max([-80, bounds[0]] ) , min([80, bounds[1]] ) ) plt.ylabel("Gain (dB)" ) plt.plot(lowerCamelCase_ ) plt.show() def __snake_case ( lowerCamelCase_ : FilterType , lowerCamelCase_ : int ): '''simple docstring''' __magic_name__ = 512 __magic_name__ = [1] + [0] * (size - 1) __magic_name__ = [filter_type.process(lowerCamelCase_ ) for item in inputs] __magic_name__ = [0] * (samplerate - size) # zero-padding outputs += filler __magic_name__ = np.angle(np.fft.fft(lowerCamelCase_ ) ) # Frequencies on log scale from 24 to nyquist frequency plt.xlim(24 , samplerate / 2 - 1 ) plt.xlabel("Frequency (Hz)" ) plt.xscale("log" ) plt.ylim(-2 * pi , 2 * pi ) plt.ylabel("Phase shift (Radians)" ) plt.plot(np.unwrap(lowerCamelCase_ , -2 * pi ) ) plt.show()
664
'''simple docstring''' import json import multiprocessing as mp import re from collections import defaultdict from functools import partial from typing import Dict, List, Optional, Set, Tuple, Type from datasets import Dataset from datasketch import MinHash, MinHashLSH from dpu_utils.utils.iterators import ThreadedIterator from tqdm import tqdm __magic_name__ : Dict =re.compile('[^A-Za-z_0-9]') # parameters used in DuplicationIndex __magic_name__ : int =10 __magic_name__ : Union[str, Any] =2_56 def __snake_case ( lowerCamelCase_ : List[str] ): '''simple docstring''' if len(lowerCamelCase_ ) < MIN_NUM_TOKENS: return None __magic_name__ = MinHash(num_perm=lowerCamelCase_ ) for token in set(lowerCamelCase_ ): min_hash.update(token.encode() ) return min_hash def __snake_case ( lowerCamelCase_ : str ): '''simple docstring''' return {t for t in NON_ALPHA.split(lowerCamelCase_ ) if len(t.strip() ) > 0} class UpperCamelCase_ : """simple docstring""" def __init__( self : int , *, _lowerCamelCase : float = 0.85 , ) -> Optional[Any]: __magic_name__ = duplication_jaccard_threshold __magic_name__ = NUM_PERM __magic_name__ = MinHashLSH(threshold=self._duplication_jaccard_threshold , num_perm=self._num_perm ) __magic_name__ = defaultdict(_lowerCamelCase ) def __A ( self : List[Any] , _lowerCamelCase : Tuple , _lowerCamelCase : MinHash ) -> None: __magic_name__ = self._index.query(_lowerCamelCase ) if code_key in self._index.keys: print(f'Duplicate key {code_key}' ) return self._index.insert(_lowerCamelCase , _lowerCamelCase ) if len(_lowerCamelCase ) > 0: for base_duplicate in close_duplicates: if base_duplicate in self._duplicate_clusters: self._duplicate_clusters[base_duplicate].add(_lowerCamelCase ) break else: self._duplicate_clusters[close_duplicates[0]].add(_lowerCamelCase ) def __A ( self : Union[str, Any] ) -> List[List[Dict]]: __magic_name__ = [] for base, duplicates in self._duplicate_clusters.items(): __magic_name__ = [base] + list(_lowerCamelCase ) # reformat the cluster to be a list of dict __magic_name__ = [{"base_index": el[0], "repo_name": el[1], "path": el[2]} for el in cluster] duplicate_clusters.append(_lowerCamelCase ) return duplicate_clusters def __A ( self : Tuple , _lowerCamelCase : Tuple ) -> None: __magic_name__ = self.get_duplicate_clusters() with open(_lowerCamelCase , "w" ) as f: json.dump(_lowerCamelCase , _lowerCamelCase ) def __snake_case ( lowerCamelCase_ : List[Any] ): '''simple docstring''' __magic_name__ , __magic_name__ = element __magic_name__ = get_min_hash([t for t in NON_ALPHA.split(data["content"] ) if len(t.strip() ) > 0] ) if min_hash is not None: return (index, data["repo_name"], data["path"]), min_hash def __snake_case ( lowerCamelCase_ : Type[Dataset] ): '''simple docstring''' with mp.Pool() as pool: for data in pool.imap_unordered( _compute_min_hash , ThreadedIterator(lowerCamelCase_ , max_queue_size=1_0000 ) , chunksize=100 , ): if data is not None: yield data def __snake_case ( lowerCamelCase_ : Type[Dataset] , lowerCamelCase_ : float ): '''simple docstring''' __magic_name__ = DuplicationIndex(duplication_jaccard_threshold=lowerCamelCase_ ) for filename, min_hash in tqdm(ThreadedIterator(minhash_iter(enumerate(lowerCamelCase_ ) ) , max_queue_size=100 ) ): di.add(lowerCamelCase_ , lowerCamelCase_ ) # Returns a List[Cluster] where Cluster is List[str] with the filenames. return di.get_duplicate_clusters() def __snake_case ( lowerCamelCase_ : str , lowerCamelCase_ : str ): '''simple docstring''' __magic_name__ = get_tokens(lowerCamelCase_ ) __magic_name__ = get_tokens(lowerCamelCase_ ) return len(tokensa & tokensa ) / len(tokensa | tokensa ) __magic_name__ : List[str] =None def __snake_case ( lowerCamelCase_ : Dict , lowerCamelCase_ : List[Any] ): '''simple docstring''' __magic_name__ = [] for elementa in cluster: __magic_name__ = _shared_dataset[elementa["base_index"]]["content"] for elementa in extremes: __magic_name__ = _shared_dataset[elementa["base_index"]]["content"] if jaccard_similarity(lowerCamelCase_ , lowerCamelCase_ ) >= jaccard_threshold: elementa["copies"] += 1 break else: __magic_name__ = 1 extremes.append(lowerCamelCase_ ) return extremes def __snake_case ( lowerCamelCase_ : Dict , lowerCamelCase_ : Any , lowerCamelCase_ : Union[str, Any] ): '''simple docstring''' global _shared_dataset __magic_name__ = dataset __magic_name__ = [] __magic_name__ = partial(_find_cluster_extremes_shared , jaccard_threshold=lowerCamelCase_ ) with mp.Pool() as pool: for extremes in tqdm( pool.imap_unordered( lowerCamelCase_ , lowerCamelCase_ , ) , total=len(lowerCamelCase_ ) , ): extremes_list.append(lowerCamelCase_ ) return extremes_list def __snake_case ( lowerCamelCase_ : Type[Dataset] , lowerCamelCase_ : float = 0.85 ): '''simple docstring''' __magic_name__ = make_duplicate_clusters(lowerCamelCase_ , lowerCamelCase_ ) __magic_name__ = {x["base_index"] for cluster in duplicate_clusters for x in cluster} __magic_name__ = {} __magic_name__ = find_extremes(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) for extremes in extremes_clusters: for element in extremes: __magic_name__ = element __magic_name__ = duplicate_indices - set(extreme_dict.keys() ) __magic_name__ = dataset.filter(lambda lowerCamelCase_ , lowerCamelCase_ : idx not in remove_indices , with_indices=lowerCamelCase_ ) # update duplicate_clusters for cluster in duplicate_clusters: for element in cluster: __magic_name__ = element["base_index"] in extreme_dict if element["is_extreme"]: __magic_name__ = extreme_dict[element["base_index"]]["copies"] print(F'Original dataset size: {len(lowerCamelCase_ )}' ) print(F'Number of duplicate clusters: {len(lowerCamelCase_ )}' ) print(F'Files in duplicate cluster: {len(lowerCamelCase_ )}' ) print(F'Unique files in duplicate cluster: {len(lowerCamelCase_ )}' ) print(F'Filtered dataset size: {len(lowerCamelCase_ )}' ) return ds_filter, duplicate_clusters
664
1
'''simple docstring''' from timeit import timeit __magic_name__ : List[Any] ={ 'MALAYALAM': True, 'String': False, 'rotor': True, 'level': True, 'A': True, 'BB': True, 'ABC': False, 'amanaplanacanalpanama': True, # "a man a plan a canal panama" } # Ensure our test data is valid assert all((key == key[::-1]) is value for key, value in test_data.items()) def __snake_case ( lowerCamelCase_ : str ): '''simple docstring''' __magic_name__ = 0 __magic_name__ = len(lowerCamelCase_ ) - 1 while start_i < end_i: if s[start_i] == s[end_i]: start_i += 1 end_i -= 1 else: return False return True def __snake_case ( lowerCamelCase_ : str ): '''simple docstring''' __magic_name__ = len(lowerCamelCase_ ) // 2 __magic_name__ = len(lowerCamelCase_ ) # We need to traverse till half of the length of string # as we can get access of the i'th last element from # i'th index. # eg: [0,1,2,3,4,5] => 4th index can be accessed # with the help of 1st index (i==n-i-1) # where n is length of string return all(s[i] == s[n - i - 1] for i in range(lowerCamelCase_ ) ) def __snake_case ( lowerCamelCase_ : str ): '''simple docstring''' if len(lowerCamelCase_ ) <= 2: return True if s[0] == s[len(lowerCamelCase_ ) - 1]: return is_palindrome_recursive(s[1:-1] ) else: return False def __snake_case ( lowerCamelCase_ : str ): '''simple docstring''' return s == s[::-1] def __snake_case ( lowerCamelCase_ : str ): '''simple docstring''' __magic_name__ = F'all({name}(key) is value for key, value in test_data.items())' __magic_name__ = F'from __main__ import test_data, {name}' __magic_name__ = 50_0000 __magic_name__ = timeit(stmt=lowerCamelCase_ , setup=lowerCamelCase_ , number=lowerCamelCase_ ) print(F'{name:<35} finished {number:,} runs in {result:.5f} seconds' ) if __name__ == "__main__": for key, value in test_data.items(): assert is_palindrome(key) is is_palindrome_recursive(key) assert is_palindrome(key) is is_palindrome_slice(key) print(F'''{key:21} {value}''') print('a man a plan a canal panama') # finished 500,000 runs in 0.46793 seconds benchmark_function('is_palindrome_slice') # finished 500,000 runs in 0.85234 seconds benchmark_function('is_palindrome') # finished 500,000 runs in 1.32028 seconds benchmark_function('is_palindrome_recursive') # finished 500,000 runs in 2.08679 seconds benchmark_function('is_palindrome_traversal')
664
'''simple docstring''' import argparse import os import gluonnlp as nlp import mxnet as mx import numpy as np import torch from gluonnlp.base import get_home_dir from gluonnlp.model.bert import BERTEncoder from gluonnlp.model.utils import _load_vocab from gluonnlp.vocab import Vocab from packaging import version from torch import nn from transformers import BertConfig, BertForMaskedLM, BertModel, RobertaTokenizer from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertSelfAttention, BertSelfOutput, ) from transformers.utils import logging if version.parse(nlp.__version__) != version.parse('0.8.3'): raise Exception('requires gluonnlp == 0.8.3') if version.parse(mx.__version__) != version.parse('1.5.0'): raise Exception('requires mxnet == 1.5.0') logging.set_verbosity_info() __magic_name__ : Optional[int] =logging.get_logger(__name__) __magic_name__ : Tuple ='The Nymphenburg Palace is a beautiful palace in Munich!' def __snake_case ( lowerCamelCase_ : str , lowerCamelCase_ : str ): '''simple docstring''' __magic_name__ = { "attention_cell": "multi_head", "num_layers": 4, "units": 1024, "hidden_size": 768, "max_length": 512, "num_heads": 8, "scaled": True, "dropout": 0.1, "use_residual": True, "embed_size": 1024, "embed_dropout": 0.1, "word_embed": None, "layer_norm_eps": 1e-5, "token_type_vocab_size": 2, } __magic_name__ = bort_4_8_768_1024_hparams # Let's construct the original Bort model here # Taken from official BERT implementation, see: # https://github.com/alexa/bort/blob/master/bort/bort.py __magic_name__ = BERTEncoder( attention_cell=predefined_args["attention_cell"] , num_layers=predefined_args["num_layers"] , units=predefined_args["units"] , hidden_size=predefined_args["hidden_size"] , max_length=predefined_args["max_length"] , num_heads=predefined_args["num_heads"] , scaled=predefined_args["scaled"] , dropout=predefined_args["dropout"] , output_attention=lowerCamelCase_ , output_all_encodings=lowerCamelCase_ , use_residual=predefined_args["use_residual"] , activation=predefined_args.get("activation" , "gelu" ) , layer_norm_eps=predefined_args.get("layer_norm_eps" , lowerCamelCase_ ) , ) # Vocab information needs to be fetched first # It's the same as RoBERTa, so RobertaTokenizer can be used later __magic_name__ = "openwebtext_ccnews_stories_books_cased" # Specify download folder to Gluonnlp's vocab __magic_name__ = os.path.join(get_home_dir() , "models" ) __magic_name__ = _load_vocab(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , cls=lowerCamelCase_ ) __magic_name__ = nlp.model.BERTModel( lowerCamelCase_ , len(lowerCamelCase_ ) , units=predefined_args["units"] , embed_size=predefined_args["embed_size"] , embed_dropout=predefined_args["embed_dropout"] , word_embed=predefined_args["word_embed"] , use_pooler=lowerCamelCase_ , use_token_type_embed=lowerCamelCase_ , token_type_vocab_size=predefined_args["token_type_vocab_size"] , use_classifier=lowerCamelCase_ , use_decoder=lowerCamelCase_ , ) original_bort.load_parameters(lowerCamelCase_ , cast_dtype=lowerCamelCase_ , ignore_extra=lowerCamelCase_ ) __magic_name__ = original_bort._collect_params_with_prefix() # Build our config 🤗 __magic_name__ = { "architectures": ["BertForMaskedLM"], "attention_probs_dropout_prob": predefined_args["dropout"], "hidden_act": "gelu", "hidden_dropout_prob": predefined_args["dropout"], "hidden_size": predefined_args["embed_size"], "initializer_range": 0.02, "intermediate_size": predefined_args["hidden_size"], "layer_norm_eps": predefined_args["layer_norm_eps"], "max_position_embeddings": predefined_args["max_length"], "model_type": "bort", "num_attention_heads": predefined_args["num_heads"], "num_hidden_layers": predefined_args["num_layers"], "pad_token_id": 1, # 2 = BERT, 1 = RoBERTa "type_vocab_size": 1, # 2 = BERT, 1 = RoBERTa "vocab_size": len(lowerCamelCase_ ), } __magic_name__ = BertConfig.from_dict(lowerCamelCase_ ) __magic_name__ = BertForMaskedLM(lowerCamelCase_ ) hf_bort_model.eval() # Parameter mapping table (Gluonnlp to Transformers) # * denotes layer index # # | Gluon Parameter | Transformers Parameter # | -------------------------------------------------------------- | ---------------------- # | `encoder.layer_norm.beta` | `bert.embeddings.LayerNorm.bias` # | `encoder.layer_norm.gamma` | `bert.embeddings.LayerNorm.weight` # | `encoder.position_weight` | `bert.embeddings.position_embeddings.weight` # | `word_embed.0.weight` | `bert.embeddings.word_embeddings.weight` # | `encoder.transformer_cells.*.attention_cell.proj_key.bias` | `bert.encoder.layer.*.attention.self.key.bias` # | `encoder.transformer_cells.*.attention_cell.proj_key.weight` | `bert.encoder.layer.*.attention.self.key.weight` # | `encoder.transformer_cells.*.attention_cell.proj_query.bias` | `bert.encoder.layer.*.attention.self.query.bias` # | `encoder.transformer_cells.*.attention_cell.proj_query.weight` | `bert.encoder.layer.*.attention.self.query.weight` # | `encoder.transformer_cells.*.attention_cell.proj_value.bias` | `bert.encoder.layer.*.attention.self.value.bias` # | `encoder.transformer_cells.*.attention_cell.proj_value.weight` | `bert.encoder.layer.*.attention.self.value.weight` # | `encoder.transformer_cells.*.ffn.ffn_2.bias` | `bert.encoder.layer.*.attention.output.dense.bias` # | `encoder.transformer_cells.*.ffn.ffn_2.weight` | `bert.encoder.layer.*.attention.output.dense.weight` # | `encoder.transformer_cells.*.layer_norm.beta` | `bert.encoder.layer.*.attention.output.LayerNorm.bias` # | `encoder.transformer_cells.*.layer_norm.gamma` | `bert.encoder.layer.*.attention.output.LayerNorm.weight` # | `encoder.transformer_cells.*.ffn.ffn_1.bias` | `bert.encoder.layer.*.intermediate.dense.bias` # | `encoder.transformer_cells.*.ffn.ffn_1.weight` | `bert.encoder.layer.*.intermediate.dense.weight` # | `encoder.transformer_cells.*.ffn.layer_norm.beta` | `bert.encoder.layer.*.output.LayerNorm.bias` # | `encoder.transformer_cells.*.ffn.layer_norm.gamma` | `bert.encoder.layer.*.output.LayerNorm.weight` # | `encoder.transformer_cells.*.proj.bias` | `bert.encoder.layer.*.output.dense.bias` # | `encoder.transformer_cells.*.proj.weight` | `bert.encoder.layer.*.output.dense.weight` # Helper function to convert MXNET Arrays to PyTorch def to_torch(lowerCamelCase_ : Any ) -> nn.Parameter: return nn.Parameter(torch.FloatTensor(mx_array.data().asnumpy() ) ) # Check param shapes and map new HF param back def check_and_map_params(lowerCamelCase_ : Optional[int] , lowerCamelCase_ : int ): __magic_name__ = hf_param.shape __magic_name__ = to_torch(params[gluon_param] ) __magic_name__ = gluon_param.shape assert ( shape_hf == shape_gluon ), F'The gluon parameter {gluon_param} has shape {shape_gluon}, but expects shape {shape_hf} for Transformers' return gluon_param __magic_name__ = check_and_map_params( hf_bort_model.bert.embeddings.word_embeddings.weight , "word_embed.0.weight" ) __magic_name__ = check_and_map_params( hf_bort_model.bert.embeddings.position_embeddings.weight , "encoder.position_weight" ) __magic_name__ = check_and_map_params( hf_bort_model.bert.embeddings.LayerNorm.bias , "encoder.layer_norm.beta" ) __magic_name__ = check_and_map_params( hf_bort_model.bert.embeddings.LayerNorm.weight , "encoder.layer_norm.gamma" ) # Inspired by RoBERTa conversion script, we just zero them out (Bort does not use them) __magic_name__ = torch.zeros_like( hf_bort_model.bert.embeddings.token_type_embeddings.weight.data ) for i in range(hf_bort_config.num_hidden_layers ): __magic_name__ = hf_bort_model.bert.encoder.layer[i] # self attention __magic_name__ = layer.attention.self __magic_name__ = check_and_map_params( self_attn.key.bias.data , F'encoder.transformer_cells.{i}.attention_cell.proj_key.bias' ) __magic_name__ = check_and_map_params( self_attn.key.weight.data , F'encoder.transformer_cells.{i}.attention_cell.proj_key.weight' ) __magic_name__ = check_and_map_params( self_attn.query.bias.data , F'encoder.transformer_cells.{i}.attention_cell.proj_query.bias' ) __magic_name__ = check_and_map_params( self_attn.query.weight.data , F'encoder.transformer_cells.{i}.attention_cell.proj_query.weight' ) __magic_name__ = check_and_map_params( self_attn.value.bias.data , F'encoder.transformer_cells.{i}.attention_cell.proj_value.bias' ) __magic_name__ = check_and_map_params( self_attn.value.weight.data , F'encoder.transformer_cells.{i}.attention_cell.proj_value.weight' ) # self attention output __magic_name__ = layer.attention.output __magic_name__ = check_and_map_params( self_output.dense.bias , F'encoder.transformer_cells.{i}.proj.bias' ) __magic_name__ = check_and_map_params( self_output.dense.weight , F'encoder.transformer_cells.{i}.proj.weight' ) __magic_name__ = check_and_map_params( self_output.LayerNorm.bias , F'encoder.transformer_cells.{i}.layer_norm.beta' ) __magic_name__ = check_and_map_params( self_output.LayerNorm.weight , F'encoder.transformer_cells.{i}.layer_norm.gamma' ) # intermediate __magic_name__ = layer.intermediate __magic_name__ = check_and_map_params( intermediate.dense.bias , F'encoder.transformer_cells.{i}.ffn.ffn_1.bias' ) __magic_name__ = check_and_map_params( intermediate.dense.weight , F'encoder.transformer_cells.{i}.ffn.ffn_1.weight' ) # output __magic_name__ = layer.output __magic_name__ = check_and_map_params( bert_output.dense.bias , F'encoder.transformer_cells.{i}.ffn.ffn_2.bias' ) __magic_name__ = check_and_map_params( bert_output.dense.weight , F'encoder.transformer_cells.{i}.ffn.ffn_2.weight' ) __magic_name__ = check_and_map_params( bert_output.LayerNorm.bias , F'encoder.transformer_cells.{i}.ffn.layer_norm.beta' ) __magic_name__ = check_and_map_params( bert_output.LayerNorm.weight , F'encoder.transformer_cells.{i}.ffn.layer_norm.gamma' ) # Save space and energy 🎄 hf_bort_model.half() # Compare output of both models __magic_name__ = RobertaTokenizer.from_pretrained("roberta-base" ) __magic_name__ = tokenizer.encode_plus(lowerCamelCase_ )["input_ids"] # Get gluon output __magic_name__ = mx.nd.array([input_ids] ) __magic_name__ = original_bort(inputs=lowerCamelCase_ , token_types=[] ) # Get Transformer output (save and reload model again) hf_bort_model.save_pretrained(lowerCamelCase_ ) __magic_name__ = BertModel.from_pretrained(lowerCamelCase_ ) hf_bort_model.eval() __magic_name__ = tokenizer.encode_plus(lowerCamelCase_ , return_tensors="pt" ) __magic_name__ = hf_bort_model(**lowerCamelCase_ )[0] __magic_name__ = output_gluon[0].asnumpy() __magic_name__ = output_hf[0].detach().numpy() __magic_name__ = np.max(np.abs(hf_layer - gluon_layer ) ).item() __magic_name__ = np.allclose(lowerCamelCase_ , lowerCamelCase_ , atol=1e-3 ) if success: print("✔️ Both model do output the same tensors" ) else: print("❌ Both model do **NOT** output the same tensors" ) print("Absolute difference is:" , lowerCamelCase_ ) if __name__ == "__main__": __magic_name__ : int =argparse.ArgumentParser() # Required parameters parser.add_argument( '--bort_checkpoint_path', default=None, type=str, required=True, help='Path the official Bort params file.' ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) __magic_name__ : Optional[Any] =parser.parse_args() convert_bort_checkpoint_to_pytorch(args.bort_checkpoint_path, args.pytorch_dump_folder_path)
664
1
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging __magic_name__ : Union[str, Any] =logging.get_logger(__name__) __magic_name__ : str ={'vocab_file': 'spm_char.model'} __magic_name__ : Dict ={ 'vocab_file': { 'microsoft/speecht5_asr': 'https://huggingface.co/microsoft/speecht5_asr/resolve/main/spm_char.model', 'microsoft/speecht5_tts': 'https://huggingface.co/microsoft/speecht5_tts/resolve/main/spm_char.model', 'microsoft/speecht5_vc': 'https://huggingface.co/microsoft/speecht5_vc/resolve/main/spm_char.model', } } __magic_name__ : Any ={ 'microsoft/speecht5_asr': 10_24, 'microsoft/speecht5_tts': 10_24, 'microsoft/speecht5_vc': 10_24, } class UpperCamelCase_ ( A ): """simple docstring""" UpperCAmelCase__ : int = VOCAB_FILES_NAMES UpperCAmelCase__ : Optional[int] = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase__ : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase__ : Optional[Any] = ['''input_ids''', '''attention_mask'''] def __init__( self : str , _lowerCamelCase : List[Any] , _lowerCamelCase : List[str]="<s>" , _lowerCamelCase : Optional[Any]="</s>" , _lowerCamelCase : Dict="<unk>" , _lowerCamelCase : str="<pad>" , _lowerCamelCase : Optional[Dict[str, Any]] = None , **_lowerCamelCase : str , ) -> None: __magic_name__ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=_lowerCamelCase , eos_token=_lowerCamelCase , unk_token=_lowerCamelCase , pad_token=_lowerCamelCase , sp_model_kwargs=self.sp_model_kwargs , **_lowerCamelCase , ) __magic_name__ = vocab_file __magic_name__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_lowerCamelCase ) @property def __A ( self : int ) -> int: return self.sp_model.get_piece_size() def __A ( self : Any ) -> Tuple: __magic_name__ = {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 : Any ) -> List[str]: __magic_name__ = self.__dict__.copy() __magic_name__ = None return state def __setstate__( self : Union[str, Any] , _lowerCamelCase : Dict ) -> Tuple: __magic_name__ = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): __magic_name__ = {} __magic_name__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def __A ( self : str , _lowerCamelCase : str ) -> List[str]: return self.sp_model.encode(_lowerCamelCase , out_type=_lowerCamelCase ) def __A ( self : List[Any] , _lowerCamelCase : Dict ) -> List[Any]: return self.sp_model.piece_to_id(_lowerCamelCase ) def __A ( self : Optional[Any] , _lowerCamelCase : Any ) -> Optional[Any]: __magic_name__ = self.sp_model.IdToPiece(_lowerCamelCase ) return token def __A ( self : Tuple , _lowerCamelCase : List[Any] ) -> Optional[int]: __magic_name__ = [] __magic_name__ = "" for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(_lowerCamelCase ) + token __magic_name__ = [] else: current_sub_tokens.append(_lowerCamelCase ) out_string += self.sp_model.decode(_lowerCamelCase ) return out_string.strip() def __A ( self : List[Any] , _lowerCamelCase : int , _lowerCamelCase : Dict=None ) -> List[int]: if token_ids_a is None: return token_ids_a + [self.eos_token_id] # We don't expect to process pairs, but leave the pair logic for API consistency return token_ids_a + token_ids_a + [self.eos_token_id] def __A ( self : Dict , _lowerCamelCase : List[int] , _lowerCamelCase : Optional[List[int]] = None , _lowerCamelCase : bool = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_lowerCamelCase , token_ids_a=_lowerCamelCase , already_has_special_tokens=_lowerCamelCase ) __magic_name__ = [1] if token_ids_a is None: return ([0] * len(_lowerCamelCase )) + suffix_ones return ([0] * len(_lowerCamelCase )) + ([0] * len(_lowerCamelCase )) + suffix_ones def __A ( self : str , _lowerCamelCase : str , _lowerCamelCase : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(_lowerCamelCase ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return __magic_name__ = 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: __magic_name__ = self.sp_model.serialized_model_proto() fi.write(_lowerCamelCase ) return (out_vocab_file,)
664
'''simple docstring''' def __snake_case ( lowerCamelCase_ : int , lowerCamelCase_ : int ): '''simple docstring''' if a < 0 or b < 0: raise ValueError("the value of both inputs must be positive" ) __magic_name__ = str(bin(lowerCamelCase_ ) )[2:] # remove the leading "0b" __magic_name__ = str(bin(lowerCamelCase_ ) )[2:] # remove the leading "0b" __magic_name__ = max(len(lowerCamelCase_ ) , len(lowerCamelCase_ ) ) return "0b" + "".join( str(int(char_a == "1" and char_b == "1" ) ) for char_a, char_b in zip(a_binary.zfill(lowerCamelCase_ ) , b_binary.zfill(lowerCamelCase_ ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
664
1
'''simple docstring''' import faiss # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import requests # noqa: F401 # Here to have a nice missing dependency error message early on import sklearn # noqa: F401 # Here to have a nice missing dependency error message early on import tqdm # noqa: F401 # Here to have a nice missing dependency error message early on from mauve import compute_mauve # From: mauve-text import datasets __magic_name__ : Union[str, Any] ='\\n@inproceedings{pillutla-etal:mauve:neurips2021,\n title={MAUVE: Measuring the Gap Between Neural Text and Human Text using Divergence Frontiers},\n author={Pillutla, Krishna and Swayamdipta, Swabha and Zellers, Rowan and Thickstun, John and Welleck, Sean and Choi, Yejin and Harchaoui, Zaid},\n booktitle = {NeurIPS},\n year = {2021}\n}\n\n' __magic_name__ : Tuple ='\\nMAUVE is a library built on PyTorch and HuggingFace Transformers to measure the gap between neural text and human text with the eponymous MAUVE measure.\n\nMAUVE summarizes both Type I and Type II errors measured softly using Kullback–Leibler (KL) divergences.\n\nFor details, see the MAUVE paper: https://arxiv.org/abs/2102.01454 (Neurips, 2021).\n\nThis metrics is a wrapper around the official implementation of MAUVE:\nhttps://github.com/krishnap25/mauve\n' __magic_name__ : List[Any] ='\nCalculates MAUVE scores between two lists of generated text and reference text.\nArgs:\n predictions: list of generated text to score. Each predictions\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\nOptional Args:\n num_buckets: the size of the histogram to quantize P and Q. Options: \'auto\' (default) or an integer\n pca_max_data: the number data points to use for PCA dimensionality reduction prior to clustering. If -1, use all the data. Default -1\n kmeans_explained_var: amount of variance of the data to keep in dimensionality reduction by PCA. Default 0.9\n kmeans_num_redo: number of times to redo k-means clustering (the best objective is kept). Default 5\n kmeans_max_iter: maximum number of k-means iterations. Default 500\n featurize_model_name: name of the model from which features are obtained. Default \'gpt2-large\' Use one of [\'gpt2\', \'gpt2-medium\', \'gpt2-large\', \'gpt2-xl\'].\n device_id: Device for featurization. Supply a GPU id (e.g. 0 or 3) to use GPU. If no GPU with this id is found, use CPU\n max_text_length: maximum number of tokens to consider. Default 1024\n divergence_curve_discretization_size: Number of points to consider on the divergence curve. Default 25\n mauve_scaling_factor: "c" from the paper. Default 5.\n verbose: If True (default), print running time updates\n seed: random seed to initialize k-means cluster assignments.\nReturns:\n mauve: MAUVE score, a number between 0 and 1. Larger values indicate that P and Q are closer,\n frontier_integral: Frontier Integral, a number between 0 and 1. Smaller values indicate that P and Q are closer,\n divergence_curve: a numpy.ndarray of shape (m, 2); plot it with matplotlib to view the divergence curve,\n p_hist: a discrete distribution, which is a quantized version of the text distribution p_text,\n q_hist: same as above, but with q_text.\nExamples:\n\n >>> # faiss segfaults in doctest for some reason, so the .compute call is not tested with doctest\n >>> import datasets\n >>> mauve = datasets.load_metric(\'mauve\')\n >>> predictions = ["hello there", "general kenobi"]\n >>> references = ["hello there", "general kenobi"]\n >>> out = mauve.compute(predictions=predictions, references=references) # doctest: +SKIP\n >>> print(out.mauve) # doctest: +SKIP\n 1.0\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCamelCase_ ( datasets.Metric ): """simple docstring""" def __A ( self : Tuple ) -> List[Any]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage="https://github.com/krishnap25/mauve" , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Value("string" , id="sequence" ), "references": datasets.Value("string" , id="sequence" ), } ) , codebase_urls=["https://github.com/krishnap25/mauve"] , reference_urls=[ "https://arxiv.org/abs/2102.01454", "https://github.com/krishnap25/mauve", ] , ) def __A ( self : str , _lowerCamelCase : int , _lowerCamelCase : Dict , _lowerCamelCase : Dict=None , _lowerCamelCase : Optional[int]=None , _lowerCamelCase : List[Any]=None , _lowerCamelCase : int=None , _lowerCamelCase : str="auto" , _lowerCamelCase : str=-1 , _lowerCamelCase : List[Any]=0.9 , _lowerCamelCase : List[str]=5 , _lowerCamelCase : Tuple=5_00 , _lowerCamelCase : str="gpt2-large" , _lowerCamelCase : Dict=-1 , _lowerCamelCase : int=10_24 , _lowerCamelCase : str=25 , _lowerCamelCase : List[Any]=5 , _lowerCamelCase : Optional[int]=True , _lowerCamelCase : Any=25 , ) -> Tuple: __magic_name__ = compute_mauve( p_text=_lowerCamelCase , q_text=_lowerCamelCase , p_features=_lowerCamelCase , q_features=_lowerCamelCase , p_tokens=_lowerCamelCase , q_tokens=_lowerCamelCase , num_buckets=_lowerCamelCase , pca_max_data=_lowerCamelCase , kmeans_explained_var=_lowerCamelCase , kmeans_num_redo=_lowerCamelCase , kmeans_max_iter=_lowerCamelCase , featurize_model_name=_lowerCamelCase , device_id=_lowerCamelCase , max_text_length=_lowerCamelCase , divergence_curve_discretization_size=_lowerCamelCase , mauve_scaling_factor=_lowerCamelCase , verbose=_lowerCamelCase , seed=_lowerCamelCase , ) return out
664
'''simple docstring''' import functools import logging import os import sys import threading from logging import ( CRITICAL, # NOQA DEBUG, # NOQA ERROR, # NOQA FATAL, # NOQA INFO, # NOQA NOTSET, # NOQA WARN, # NOQA WARNING, # NOQA ) from typing import Optional import huggingface_hub.utils as hf_hub_utils from tqdm import auto as tqdm_lib __magic_name__ : Tuple =threading.Lock() __magic_name__ : Optional[logging.Handler] =None __magic_name__ : List[str] ={ 'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'critical': logging.CRITICAL, } __magic_name__ : str =logging.WARNING __magic_name__ : Any =True def __snake_case ( ): '''simple docstring''' __magic_name__ = os.getenv("TRANSFORMERS_VERBOSITY" , lowerCamelCase_ ) if env_level_str: if env_level_str in log_levels: return log_levels[env_level_str] else: logging.getLogger().warning( F'Unknown option TRANSFORMERS_VERBOSITY={env_level_str}, ' F'has to be one of: { ", ".join(log_levels.keys() ) }' ) return _default_log_level def __snake_case ( ): '''simple docstring''' return __name__.split("." )[0] def __snake_case ( ): '''simple docstring''' return logging.getLogger(_get_library_name() ) def __snake_case ( ): '''simple docstring''' global _default_handler with _lock: if _default_handler: # This library has already configured the library root logger. return __magic_name__ = logging.StreamHandler() # Set sys.stderr as stream. __magic_name__ = sys.stderr.flush # Apply our default configuration to the library root logger. __magic_name__ = _get_library_root_logger() library_root_logger.addHandler(_default_handler ) library_root_logger.setLevel(_get_default_logging_level() ) __magic_name__ = False def __snake_case ( ): '''simple docstring''' global _default_handler with _lock: if not _default_handler: return __magic_name__ = _get_library_root_logger() library_root_logger.removeHandler(_default_handler ) library_root_logger.setLevel(logging.NOTSET ) __magic_name__ = None def __snake_case ( ): '''simple docstring''' return log_levels def __snake_case ( lowerCamelCase_ : Optional[str] = None ): '''simple docstring''' if name is None: __magic_name__ = _get_library_name() _configure_library_root_logger() return logging.getLogger(lowerCamelCase_ ) def __snake_case ( ): '''simple docstring''' _configure_library_root_logger() return _get_library_root_logger().getEffectiveLevel() def __snake_case ( lowerCamelCase_ : int ): '''simple docstring''' _configure_library_root_logger() _get_library_root_logger().setLevel(lowerCamelCase_ ) def __snake_case ( ): '''simple docstring''' return set_verbosity(lowerCamelCase_ ) def __snake_case ( ): '''simple docstring''' return set_verbosity(lowerCamelCase_ ) def __snake_case ( ): '''simple docstring''' return set_verbosity(lowerCamelCase_ ) def __snake_case ( ): '''simple docstring''' return set_verbosity(lowerCamelCase_ ) def __snake_case ( ): '''simple docstring''' _configure_library_root_logger() assert _default_handler is not None _get_library_root_logger().removeHandler(_default_handler ) def __snake_case ( ): '''simple docstring''' _configure_library_root_logger() assert _default_handler is not None _get_library_root_logger().addHandler(_default_handler ) def __snake_case ( lowerCamelCase_ : logging.Handler ): '''simple docstring''' _configure_library_root_logger() assert handler is not None _get_library_root_logger().addHandler(lowerCamelCase_ ) def __snake_case ( lowerCamelCase_ : logging.Handler ): '''simple docstring''' _configure_library_root_logger() assert handler is not None and handler not in _get_library_root_logger().handlers _get_library_root_logger().removeHandler(lowerCamelCase_ ) def __snake_case ( ): '''simple docstring''' _configure_library_root_logger() __magic_name__ = False def __snake_case ( ): '''simple docstring''' _configure_library_root_logger() __magic_name__ = True def __snake_case ( ): '''simple docstring''' __magic_name__ = _get_library_root_logger().handlers for handler in handlers: __magic_name__ = logging.Formatter("[%(levelname)s|%(filename)s:%(lineno)s] %(asctime)s >> %(message)s" ) handler.setFormatter(lowerCamelCase_ ) def __snake_case ( ): '''simple docstring''' __magic_name__ = _get_library_root_logger().handlers for handler in handlers: handler.setFormatter(lowerCamelCase_ ) def __snake_case ( self : Union[str, Any] , *lowerCamelCase_ : str , **lowerCamelCase_ : Any ): '''simple docstring''' __magic_name__ = os.getenv("TRANSFORMERS_NO_ADVISORY_WARNINGS" , lowerCamelCase_ ) if no_advisory_warnings: return self.warning(*lowerCamelCase_ , **lowerCamelCase_ ) __magic_name__ : int =warning_advice @functools.lru_cache(lowerCamelCase_ ) def __snake_case ( self : Dict , *lowerCamelCase_ : int , **lowerCamelCase_ : int ): '''simple docstring''' self.warning(*lowerCamelCase_ , **lowerCamelCase_ ) __magic_name__ : Optional[int] =warning_once class UpperCamelCase_ : """simple docstring""" def __init__( self : int , *_lowerCamelCase : Tuple , **_lowerCamelCase : Optional[Any] ) -> Any: # pylint: disable=unused-argument __magic_name__ = args[0] if args else None def __iter__( self : int ) -> Tuple: return iter(self._iterator ) def __getattr__( self : List[Any] , _lowerCamelCase : int ) -> List[Any]: def empty_fn(*_lowerCamelCase : List[str] , **_lowerCamelCase : List[str] ): # pylint: disable=unused-argument return return empty_fn def __enter__( self : Optional[Any] ) -> Any: return self def __exit__( self : int , _lowerCamelCase : List[Any] , _lowerCamelCase : List[Any] , _lowerCamelCase : List[str] ) -> Dict: return class UpperCamelCase_ : """simple docstring""" def __call__( self : Any , *_lowerCamelCase : Optional[Any] , **_lowerCamelCase : Any ) -> List[Any]: if _tqdm_active: return tqdm_lib.tqdm(*_lowerCamelCase , **_lowerCamelCase ) else: return EmptyTqdm(*_lowerCamelCase , **_lowerCamelCase ) def __A ( self : Optional[Any] , *_lowerCamelCase : Optional[Any] , **_lowerCamelCase : Dict ) -> Union[str, Any]: __magic_name__ = None if _tqdm_active: return tqdm_lib.tqdm.set_lock(*_lowerCamelCase , **_lowerCamelCase ) def __A ( self : str ) -> Any: if _tqdm_active: return tqdm_lib.tqdm.get_lock() __magic_name__ : List[Any] =_tqdm_cls() def __snake_case ( ): '''simple docstring''' global _tqdm_active return bool(_tqdm_active ) def __snake_case ( ): '''simple docstring''' global _tqdm_active __magic_name__ = True hf_hub_utils.enable_progress_bars() def __snake_case ( ): '''simple docstring''' global _tqdm_active __magic_name__ = False hf_hub_utils.disable_progress_bars()
664
1
'''simple docstring''' import argparse import os import torch from transformers import FlavaImageCodebook, FlavaImageCodebookConfig def __snake_case ( lowerCamelCase_ : List[str] , lowerCamelCase_ : Dict , lowerCamelCase_ : Any , lowerCamelCase_ : Optional[Any] ): '''simple docstring''' __magic_name__ = s.rsplit(lowerCamelCase_ , lowerCamelCase_ ) return new.join(lowerCamelCase_ ) def __snake_case ( lowerCamelCase_ : List[str] ): '''simple docstring''' return sum(param.float().sum() if "encoder.embeddings" not in key else 0 for key, param in state_dict.items() ) def __snake_case ( lowerCamelCase_ : Optional[int] ): '''simple docstring''' __magic_name__ = {} __magic_name__ = ["group_1", "group_2", "group_3", "group_4"] for key, value in state_dict.items(): for group_key in group_keys: if group_key in key: __magic_name__ = key.replace(F'{group_key}.' , F'{group_key}.group.' ) if "res_path" in key: __magic_name__ = key.replace("res_path." , "res_path.path." ) if key.endswith(".w" ): __magic_name__ = rreplace(lowerCamelCase_ , ".w" , ".weight" , 1 ) if key.endswith(".b" ): __magic_name__ = rreplace(lowerCamelCase_ , ".b" , ".bias" , 1 ) __magic_name__ = value.float() return upgrade @torch.no_grad() def __snake_case ( lowerCamelCase_ : List[Any] , lowerCamelCase_ : Tuple , lowerCamelCase_ : int=None , lowerCamelCase_ : Any=True ): '''simple docstring''' from dall_e import Encoder __magic_name__ = Encoder() if os.path.exists(lowerCamelCase_ ): __magic_name__ = torch.load(lowerCamelCase_ ) else: __magic_name__ = torch.hub.load_state_dict_from_url(lowerCamelCase_ ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ): __magic_name__ = ckpt.state_dict() encoder.load_state_dict(lowerCamelCase_ ) if config_path is not None: __magic_name__ = FlavaImageCodebookConfig.from_pretrained(lowerCamelCase_ ) else: __magic_name__ = FlavaImageCodebookConfig() __magic_name__ = FlavaImageCodebook(lowerCamelCase_ ).eval() __magic_name__ = encoder.state_dict() __magic_name__ = upgrade_state_dict(lowerCamelCase_ ) hf_model.load_state_dict(lowerCamelCase_ ) __magic_name__ = hf_model.state_dict() __magic_name__ = count_parameters(lowerCamelCase_ ) __magic_name__ = count_parameters(lowerCamelCase_ ) assert torch.allclose(lowerCamelCase_ , lowerCamelCase_ , atol=1e-3 ) if save_checkpoint: hf_model.save_pretrained(lowerCamelCase_ ) else: return hf_state_dict if __name__ == "__main__": __magic_name__ : int =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 flava checkpoint') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') __magic_name__ : Dict =parser.parse_args() convert_dalle_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
664
'''simple docstring''' from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __magic_name__ : Union[str, Any] ={'configuration_focalnet': ['FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP', 'FocalNetConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ : str =[ 'FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST', 'FocalNetForImageClassification', 'FocalNetForMaskedImageModeling', 'FocalNetBackbone', 'FocalNetModel', 'FocalNetPreTrainedModel', ] if TYPE_CHECKING: from .configuration_focalnet import FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FocalNetConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_focalnet import ( FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST, FocalNetBackbone, FocalNetForImageClassification, FocalNetForMaskedImageModeling, FocalNetModel, FocalNetPreTrainedModel, ) else: import sys __magic_name__ : List[Any] =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
664
1
'''simple docstring''' import qiskit def __snake_case ( lowerCamelCase_ : int , lowerCamelCase_ : int ): '''simple docstring''' __magic_name__ = qiskit.Aer.get_backend("aer_simulator" ) # Create a Quantum Circuit acting on the q register __magic_name__ = qiskit.QuantumCircuit(lowerCamelCase_ , lowerCamelCase_ ) # Apply X (NOT) Gate to Qubits 0 & 1 circuit.x(0 ) circuit.x(1 ) # Map the quantum measurement to the classical bits circuit.measure([0, 1] , [0, 1] ) # Execute the circuit on the qasm simulator __magic_name__ = qiskit.execute(lowerCamelCase_ , lowerCamelCase_ , shots=1000 ) # Return the histogram data of the results of the experiment. return job.result().get_counts(lowerCamelCase_ ) if __name__ == "__main__": __magic_name__ : Dict =single_qubit_measure(2, 2) print(F'''Total count for various states are: {counts}''')
664
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) __magic_name__ : Optional[Any] ={ 'configuration_longformer': [ 'LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LongformerConfig', 'LongformerOnnxConfig', ], 'tokenization_longformer': ['LongformerTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ : int =['LongformerTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ : Dict =[ 'LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'LongformerForMaskedLM', 'LongformerForMultipleChoice', 'LongformerForQuestionAnswering', 'LongformerForSequenceClassification', 'LongformerForTokenClassification', 'LongformerModel', 'LongformerPreTrainedModel', 'LongformerSelfAttention', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ : Tuple =[ 'TF_LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFLongformerForMaskedLM', 'TFLongformerForMultipleChoice', 'TFLongformerForQuestionAnswering', 'TFLongformerForSequenceClassification', 'TFLongformerForTokenClassification', 'TFLongformerModel', 'TFLongformerPreTrainedModel', 'TFLongformerSelfAttention', ] if TYPE_CHECKING: from .configuration_longformer import ( LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, LongformerConfig, LongformerOnnxConfig, ) from .tokenization_longformer import LongformerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_longformer_fast import LongformerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_longformer import ( LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, LongformerForMaskedLM, LongformerForMultipleChoice, LongformerForQuestionAnswering, LongformerForSequenceClassification, LongformerForTokenClassification, LongformerModel, LongformerPreTrainedModel, LongformerSelfAttention, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_longformer import ( TF_LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFLongformerForMaskedLM, TFLongformerForMultipleChoice, TFLongformerForQuestionAnswering, TFLongformerForSequenceClassification, TFLongformerForTokenClassification, TFLongformerModel, TFLongformerPreTrainedModel, TFLongformerSelfAttention, ) else: import sys __magic_name__ : int =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
664
1
'''simple docstring''' def __snake_case ( lowerCamelCase_ : int ): '''simple docstring''' return number & 1 == 0 if __name__ == "__main__": import doctest doctest.testmod()
664
'''simple docstring''' import PIL.Image import PIL.ImageOps from packaging import version from PIL import Image if version.parse(version.parse(PIL.__version__).base_version) >= version.parse('9.1.0'): __magic_name__ : str ={ 'linear': PIL.Image.Resampling.BILINEAR, 'bilinear': PIL.Image.Resampling.BILINEAR, 'bicubic': PIL.Image.Resampling.BICUBIC, 'lanczos': PIL.Image.Resampling.LANCZOS, 'nearest': PIL.Image.Resampling.NEAREST, } else: __magic_name__ : Tuple ={ 'linear': PIL.Image.LINEAR, 'bilinear': PIL.Image.BILINEAR, 'bicubic': PIL.Image.BICUBIC, 'lanczos': PIL.Image.LANCZOS, 'nearest': PIL.Image.NEAREST, } def __snake_case ( lowerCamelCase_ : Optional[Any] ): '''simple docstring''' __magic_name__ = (images / 2 + 0.5).clamp(0 , 1 ) __magic_name__ = images.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() __magic_name__ = numpy_to_pil(lowerCamelCase_ ) return images def __snake_case ( lowerCamelCase_ : Optional[Any] ): '''simple docstring''' if images.ndim == 3: __magic_name__ = images[None, ...] __magic_name__ = (images * 255).round().astype("uint8" ) if images.shape[-1] == 1: # special case for grayscale (single channel) images __magic_name__ = [Image.fromarray(image.squeeze() , mode="L" ) for image in images] else: __magic_name__ = [Image.fromarray(lowerCamelCase_ ) for image in images] return pil_images
664
1
'''simple docstring''' import json import os import unittest from typing import Tuple from transformers import WavaVecaPhonemeCTCTokenizer from transformers.models.wavaveca.tokenization_wavaveca import VOCAB_FILES_NAMES from transformers.models.wavaveca_phoneme.tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizerOutput from transformers.testing_utils import require_phonemizer from ...test_tokenization_common import TokenizerTesterMixin @require_phonemizer class UpperCamelCase_ ( A , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : List[str] = WavaVecaPhonemeCTCTokenizer UpperCAmelCase__ : Optional[Any] = False def __A ( self : str ) -> Optional[Any]: super().setUp() __magic_name__ = ( "<s> <pad> </s> <unk> n s t ə l a i k d m ɛ ɾ e ɪ p o ɐ z ð f j v b ɹ ʁ ʊ iː r w ʌ u ɡ æ aɪ ʃ h ɔ ɑː " "ŋ ɚ eɪ β uː y ɑ̃ oʊ ᵻ eː θ aʊ ts oː ɔ̃ ɣ ɜ ɑ dʒ əl x ɜː ç ʒ tʃ ɔː ɑːɹ ɛ̃ ʎ ɔːɹ ʋ aː ɕ œ ø oːɹ ɲ yː " "ʔ iə i5 s. tɕ ?? nʲ ɛː œ̃ ɭ ɔø ʑ tʲ ɨ ɛɹ ts. rʲ ɪɹ ɭʲ i.5 ɔɪ q sʲ u5 ʊɹ iɜ a5 iɛ5 øː ʕ ja əɜ th ɑ5 " "oɪ dʲ ə5 tɕh ts.h mʲ ɯ dʑ vʲ e̞ tʃʲ ei5 o5 onɡ5 ɑu5 iɑ5 ai5 aɪɚ kh ə1 ʐ i2 ʉ ħ t[ aɪə ʲ ju ə2 u2 oɜ " "pː iɛɜ ou5 y5 uɜ tː uo5 d[ uoɜ tsh ɑɜ ɵ i̪5 uei5 ɟ aɜ ɑɨ i.ɜ eʊ o2 ɐ̃ ä pʲ kʲ n̩ ɒ ph ɑu2 uɨ əɪ ɫ ɬ " "yɜ bʲ ɑ2 s̪ aiɜ χ ɐ̃ʊ̃ 1 ə4 yæɜ a2 ɨː t̪ iouɜ ũ onɡɜ aɨ iɛ2 ɔɨ ɑuɜ o̞ ei2 iou2 c kː y2 ɖ oe dˤ yɛɜ " "əʊ S ɡʲ onɡ2 u\" eiɜ ʈ ɯᵝ iou5 dZ r̝̊ i.2 tS s^ ʝ yə5 iɑɜ uə5 pf ɨu iɑ2 ou2 ər2 fʲ ai2 r̝ uəɜ ɳ əɨ " "ua5 uɪ ɽ bː yu5 uo2 yɛ5 l̩ ɻ ərɜ ʂ i̪2 ouɜ uaɜ a. a.ː yæ5 dː r̩ ee ɪu ər5 i̪ ɜ æi u: i.ː t^ o1 ɪ^ " "ai ueiɜ æː ɛɪ eə i. ɴ ie ua2 ɑ1 o4 tʃː o: ɑ: u1 N i̪1 au yæ2 u. qː yəɜ y: kʰ tʃʰ iʊ sx õ uo tʰ " "uai5 bʰ u.ː uə2 ʊə d^ s̪ː yiɜ dʰ r. oe: i1 ɟː yu2 nʲʲ i̪4 uei2 tsʲ ɸ ĩ ɑ4 t̪ː eɑ u4 e: tsː ʈʰ ɡʰ " "ɯɯ dʒʲ ʂʲ X ɵː uaiɜ tɕʲ ã t^ː ẽː yɛ2 cː i.1 ɛʊ dˤdˤ dʒː i4 ɡː yi ɕʲ ɟʰ pʰ dʑʲ yuɜ ua1 ua4 æiː ɐɐ " "ui iou1 ʊː a1 iou4 cʰ iɛ1 yə2 ɖʰ ẽ ʒʲ ää ər4 iːː ɪː iɑ1 ər1 œː øi ɪuː cʰcʰ əː1 iː1 ũ kʰː o̞o̞ xʲ " "ou1 iɛ4 e̞e̞ y1 dzː dʲʲ dʰː ɯᵝɯᵝ lː uo1 i.4 i: yɛ5ʲ a4" ).split(" " ) __magic_name__ = dict(zip(_lowerCamelCase , range(len(_lowerCamelCase ) ) ) ) __magic_name__ = {"pad_token": "<pad>", "unk_token": "<unk>", "bos_token": "<s>", "eos_token": "</s>"} __magic_name__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as fp: fp.write(json.dumps(_lowerCamelCase ) + "\n" ) def __A ( self : Any , _lowerCamelCase : Union[str, Any] , _lowerCamelCase : List[Any]=False , _lowerCamelCase : int=20 , _lowerCamelCase : Optional[Any]=5 ) -> Tuple[str, list]: __magic_name__ = [(i, tokenizer.decode([i] , clean_up_tokenization_spaces=_lowerCamelCase )) for i in range(len(_lowerCamelCase ) )] __magic_name__ = list(filter(lambda _lowerCamelCase : [t[0]] == tokenizer.encode(t[1] , do_phonemize=_lowerCamelCase ) , _lowerCamelCase ) ) if max_length is not None and len(_lowerCamelCase ) > max_length: __magic_name__ = toks[:max_length] if min_length is not None and len(_lowerCamelCase ) < min_length and len(_lowerCamelCase ) > 0: while len(_lowerCamelCase ) < min_length: __magic_name__ = toks + toks # toks_str = [t[1] for t in toks] __magic_name__ = [t[0] for t in toks] # Ensure consistency __magic_name__ = tokenizer.decode(_lowerCamelCase , clean_up_tokenization_spaces=_lowerCamelCase ) if " " not in output_txt and len(_lowerCamelCase ) > 1: __magic_name__ = ( tokenizer.decode([toks_ids[0]] , clean_up_tokenization_spaces=_lowerCamelCase ) + " " + tokenizer.decode(toks_ids[1:] , clean_up_tokenization_spaces=_lowerCamelCase ) ) if with_prefix_space: __magic_name__ = " " + output_txt __magic_name__ = tokenizer.encode(_lowerCamelCase , add_special_tokens=_lowerCamelCase ) return output_txt, output_ids def __A ( self : str , **_lowerCamelCase : Tuple ) -> int: kwargs.update(self.special_tokens_map ) return WavaVecaPhonemeCTCTokenizer.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def __A ( self : Optional[int] ) -> List[Any]: __magic_name__ = self.tokenizer_class.from_pretrained("facebook/wav2vec2-lv-60-espeak-cv-ft" ) # check adding a single token tokenizer.add_tokens("xxx" ) __magic_name__ = tokenizer("m xxx ɪ" , do_phonemize=_lowerCamelCase ).input_ids self.assertEqual(_lowerCamelCase , [13, 3_92, 17] ) # xxx should be last token tokenizer.add_tokens(["aaa", "bbb", "ccc"] ) __magic_name__ = tokenizer("m aaa ɪ ccc" , do_phonemize=_lowerCamelCase ).input_ids self.assertEqual(_lowerCamelCase , [13, 3_93, 17, 3_95] ) # aaa and ccc should be after xxx and 2 after aaa __magic_name__ = tokenizer("maɪ c" , do_phonemize=_lowerCamelCase ).input_ids self.assertEqual(_lowerCamelCase , [3, 2_00] ) # mai should be <unk> (=3) def __A ( self : Tuple ) -> List[str]: __magic_name__ = self.tokenizer_class.from_pretrained("facebook/wav2vec2-lv-60-espeak-cv-ft" ) __magic_name__ = "Hello how are you" __magic_name__ = tokenizer.phonemize(_lowerCamelCase , phonemizer_lang="en-us" ) self.assertEqual(_lowerCamelCase , "h ə l oʊ h aʊ ɑːɹ j uː" ) def __A ( self : int ) -> Union[str, Any]: __magic_name__ = self.tokenizer_class.from_pretrained("facebook/wav2vec2-lv-60-espeak-cv-ft" ) __magic_name__ = "Hello how are you" __magic_name__ = tokenizer.phonemize(_lowerCamelCase , phonemizer_lang="en-us" ) self.assertEqual(tokenizer(_lowerCamelCase ).input_ids , tokenizer(_lowerCamelCase , do_phonemize=_lowerCamelCase ).input_ids ) def __A ( self : List[str] ) -> Optional[int]: __magic_name__ = self.tokenizer_class.from_pretrained("facebook/wav2vec2-lv-60-espeak-cv-ft" ) __magic_name__ = "Hello how are you" __magic_name__ = tokenizer.phonemize(_lowerCamelCase , phonemizer_lang="en-us" ) __magic_name__ = tokenizer.decode(tokenizer(_lowerCamelCase ).input_ids ) self.assertEqual(_lowerCamelCase , _lowerCamelCase ) def __A ( self : Optional[int] ) -> Dict: __magic_name__ = self.tokenizer_class.from_pretrained("facebook/wav2vec2-lv-60-espeak-cv-ft" ) __magic_name__ = [ [11, 5, 15, tokenizer.pad_token_id, 15, 8, 98], [24, 22, 5, 24, 22, 5, 77], ] __magic_name__ = tokenizer.decode(sample_ids[0] ) __magic_name__ = tokenizer.batch_decode(_lowerCamelCase ) self.assertEqual(_lowerCamelCase , batch_tokens[0] ) self.assertEqual(_lowerCamelCase , ["k s ɾ ɾ l ɭʲ", "j ð s j ð s oːɹ"] ) def __A ( self : Union[str, Any] ) -> Dict: __magic_name__ = self.tokenizer_class.from_pretrained( "facebook/wav2vec2-lv-60-espeak-cv-ft" , word_delimiter_token="|" ) tokenizer.add_tokens("|" ) __magic_name__ = "Hello how are you" __magic_name__ = tokenizer.phonemize(_lowerCamelCase , phonemizer_lang="en-us" ) self.assertEqual(_lowerCamelCase , "h ə l oʊ | h aʊ | ɑːɹ | j uː |" ) def __A ( self : Optional[int] ) -> Any: __magic_name__ = self.tokenizer_class.from_pretrained( "facebook/wav2vec2-lv-60-espeak-cv-ft" , word_delimiter_token="|" ) tokenizer.add_tokens("|" ) __magic_name__ = "Hello how are you" __magic_name__ = tokenizer.phonemize(_lowerCamelCase , phonemizer_lang="en-us" ) self.assertEqual(tokenizer(_lowerCamelCase ).input_ids , tokenizer(_lowerCamelCase , do_phonemize=_lowerCamelCase ).input_ids ) def __A ( self : List[str] ) -> Dict: __magic_name__ = self.tokenizer_class.from_pretrained( "facebook/wav2vec2-lv-60-espeak-cv-ft" , word_delimiter_token="|" ) tokenizer.add_tokens("|" ) # fmt: off __magic_name__ = [ [11, 5, 15, tokenizer.pad_token_id, tokenizer.word_delimiter_token_id, 15, 8, tokenizer.word_delimiter_token_id, 98], [tokenizer.word_delimiter_token_id, 24, 22, tokenizer.word_delimiter_token_id, 5, 24, 22, 5, 77], ] # fmt: on # decode with word_del_token filter __magic_name__ = tokenizer.decode(sample_ids[0] ) __magic_name__ = tokenizer.batch_decode(_lowerCamelCase ) self.assertEqual(_lowerCamelCase , batch_tokens[0] ) self.assertEqual(_lowerCamelCase , ["k s ɾ ɾ l ɭʲ", "j ð s j ð s oːɹ"] ) # decode with no word_del_token filter __magic_name__ = tokenizer.decode(sample_ids[0] , filter_word_delimiter_token=_lowerCamelCase ) __magic_name__ = tokenizer.batch_decode(_lowerCamelCase , filter_word_delimiter_token=_lowerCamelCase ) self.assertEqual(_lowerCamelCase , batch_tokens[0] ) self.assertEqual(_lowerCamelCase , ["k s ɾ | ɾ l | ɭʲ", "| j ð | s j ð s oːɹ"] ) def __A ( self : Optional[int] ) -> str: __magic_name__ = self.tokenizer_class.from_pretrained( "facebook/wav2vec2-lv-60-espeak-cv-ft" , word_delimiter_token="|" ) tokenizer.add_tokens("|" ) __magic_name__ = "Hello how are you" __magic_name__ = tokenizer.phonemize(_lowerCamelCase , phonemizer_lang="en-us" ) __magic_name__ = tokenizer.decode(tokenizer(_lowerCamelCase ).input_ids , filter_word_delimiter_token=_lowerCamelCase ) self.assertEqual(_lowerCamelCase , _lowerCamelCase ) def __A ( self : Optional[int] ) -> Optional[Any]: __magic_name__ = self.tokenizer_class.from_pretrained( "facebook/wav2vec2-lv-60-espeak-cv-ft" , word_delimiter_token="|" ) tokenizer.add_tokens("|" ) __magic_name__ = "Hello how are you" __magic_name__ = tokenizer.phonemize(_lowerCamelCase , phonemizer_lang="en-us" ) __magic_name__ = tokenizer.decode(tokenizer(_lowerCamelCase ).input_ids , filter_word_delimiter_token=_lowerCamelCase ) self.assertEqual(" ".join([p.strip() for p in phonemes.split(" |" )] ).strip() , _lowerCamelCase ) def __A ( self : List[Any] ) -> Optional[int]: __magic_name__ = self.tokenizer_class.from_pretrained( "facebook/wav2vec2-lv-60-espeak-cv-ft" , word_delimiter_token=_lowerCamelCase ) __magic_name__ = "Hello how are you" __magic_name__ = tokenizer(_lowerCamelCase , phonemizer_lang="en-us" ).input_ids __magic_name__ = tokenizer(_lowerCamelCase , phonemizer_lang="fr-fr" ).input_ids self.assertNotEqual(_lowerCamelCase , _lowerCamelCase ) __magic_name__ = tokenizer.decode(_lowerCamelCase ) __magic_name__ = tokenizer.decode(_lowerCamelCase ) self.assertEqual(_lowerCamelCase , "h ə l oʊ h aʊ ɑːɹ j uː" ) self.assertEqual(_lowerCamelCase , "ɛ l o h aʊ a ʁ j u" ) def __A ( self : Union[str, Any] ) -> Tuple: __magic_name__ = self.tokenizer_class.from_pretrained("facebook/wav2vec2-lv-60-espeak-cv-ft" ) __magic_name__ = "Hello how Are you" __magic_name__ = "hello how are you" __magic_name__ = tokenizer(_lowerCamelCase ).input_ids __magic_name__ = tokenizer(_lowerCamelCase ).input_ids self.assertEqual(_lowerCamelCase , _lowerCamelCase ) def __A ( self : Union[str, Any] ) -> Any: __magic_name__ = self.tokenizer_class.from_pretrained("facebook/wav2vec2-lv-60-espeak-cv-ft" ) tokenizer.add_tokens(["!", "?"] ) tokenizer.add_special_tokens({"cls_token": "$$$"} ) # fmt: off __magic_name__ = [ [11, 5, 15, tokenizer.pad_token_id, 15, 8, 98, 3_92, 3_92, 3_93, 3_92, 3_92, 3_93, 3_94, 3_94], [24, 22, 5, 24, 22, 5, 77, tokenizer.pad_token_id, 3_94, 3_94], ] # fmt: on __magic_name__ = tokenizer.batch_decode(_lowerCamelCase ) self.assertEqual(_lowerCamelCase , ["k s ɾ ɾ l ɭʲ!?!? $$$", "j ð s j ð s oːɹ $$$"] ) @staticmethod def __A ( _lowerCamelCase : List[str] , _lowerCamelCase : str ) -> Any: __magic_name__ = [d[key] for d in offsets] return retrieved_list def __A ( self : Tuple ) -> Union[str, Any]: __magic_name__ = self.get_tokenizer(word_delimiter_token="|" ) tokenizer.add_tokens("|" ) # fmt: off # ksssɾɾ|ɾɾ<pad>ɾɾ|<pad>ɾlll|ɭʲ -> k s ɾ ɾ | ɾ l | ɭʲ" __magic_name__ = [11, 5, 5, 5, 15, 15, tokenizer.pad_token_id, 15, 15, tokenizer.word_delimiter_token_id, tokenizer.pad_token_id, 15, 8, 8, 8, tokenizer.word_delimiter_token_id, 98] # fmt: on __magic_name__ = tokenizer.decode(_lowerCamelCase , output_char_offsets=_lowerCamelCase , filter_word_delimiter_token=_lowerCamelCase ) # check Wav2Vec2CTCTokenizerOutput keys for char self.assertEqual(len(outputs.keys() ) , 2 ) self.assertTrue("text" in outputs ) self.assertTrue("char_offsets" in outputs ) self.assertTrue(isinstance(_lowerCamelCase , _lowerCamelCase ) ) # check that order of chars is correct and identical for both outputs self.assertEqual(" ".join(self.get_from_offsets(outputs["char_offsets"] , "char" ) ) , outputs.text ) self.assertListEqual( self.get_from_offsets(outputs["char_offsets"] , "char" ) , ["k", "s", "ɾ", "ɾ", "|", "ɾ", "l", "|", "ɭʲ"] ) # check that offsets are actually correct for char # 0-1 is 11, 1-4 is 5, 4-6 is first 15, 6-7 is <pad> (thus not shown), 7-9 is second 15, 9-10 is word_delimiter_token, # 10-11 is <pad> (thus not shown), 11-12 is third 15, 12-15 is 8, 15-16 is word_delimiter_token, 16-17 is 98 self.assertListEqual( self.get_from_offsets(outputs["char_offsets"] , "start_offset" ) , [0, 1, 4, 7, 9, 11, 12, 15, 16] ) self.assertListEqual( self.get_from_offsets(outputs["char_offsets"] , "end_offset" ) , [1, 4, 6, 9, 10, 12, 15, 16, 17] ) def __A ( self : Any ) -> Union[str, Any]: __magic_name__ = self.get_tokenizer(word_delimiter_token="|" ) def check_list_tuples_equal(_lowerCamelCase : int , _lowerCamelCase : str ): self.assertTrue(isinstance(_lowerCamelCase , _lowerCamelCase ) ) self.assertTrue(isinstance(outputs_list[0] , _lowerCamelCase ) ) # transform list to ModelOutput __magic_name__ = WavaVecaPhonemeCTCTokenizerOutput( {k: [d[k] for d in outputs_list] for k in outputs_list[0]} ) self.assertListEqual(outputs_batch["text"] , outputs_batch_a["text"] ) def recursive_check(_lowerCamelCase : Any , _lowerCamelCase : Tuple ): if isinstance(_lowerCamelCase , _lowerCamelCase ): [recursive_check(_lowerCamelCase , _lowerCamelCase ) for la, la in zip(_lowerCamelCase , _lowerCamelCase )] self.assertEqual(_lowerCamelCase , _lowerCamelCase ) if "char_offsets" in outputs_batch: recursive_check(outputs_batch["char_offsets"] , outputs_batch_a["char_offsets"] ) # fmt: off __magic_name__ = [ [11, 5, 15, tokenizer.pad_token_id, 15, 4, 8, 98, 32, 32, 32, 32, 4, 33, tokenizer.word_delimiter_token_id, 32, 32, 33, 34, 34], [24, 22, 5, tokenizer.word_delimiter_token_id, tokenizer.word_delimiter_token_id, 24, 22, 22, 22, 4, 5, 77, tokenizer.pad_token_id, 22, 22, 4, 34, 34, 34, 34], ] # fmt: on # We assume that `decode` works as expected. All we will check now is # the output type is correct and the output is identical to `decode` # char __magic_name__ = tokenizer.batch_decode(_lowerCamelCase , output_char_offsets=_lowerCamelCase ) __magic_name__ = [tokenizer.decode(_lowerCamelCase , output_char_offsets=_lowerCamelCase ) for ids in sample_ids] check_list_tuples_equal(_lowerCamelCase , _lowerCamelCase ) @unittest.skip("Wav2Vec2PhonemeTokenizer always lower cases letters to correctly map to phonemes" ) def __A ( self : List[str] ) -> List[Any]: pass @unittest.skip("Wav2Vec2PhonemeTokenizer always puts spaces between phonemes" ) def __A ( self : int ) -> Optional[Any]: pass @unittest.skip("encodes to text to ids, but decodes ids to phonemes -> not possible to have internal consistency" ) def __A ( self : Tuple ) -> Union[str, Any]: pass @unittest.skip("Wav2Vec2PhonemeModel has no max model length => no testing" ) def __A ( self : Optional[int] ) -> Dict: pass def __A ( self : Optional[int] ) -> Optional[int]: __magic_name__ = self.get_tokenizers(do_lower_case=_lowerCamelCase ) for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): __magic_name__ = tokenizer.vocab_size __magic_name__ = len(_lowerCamelCase ) self.assertNotEqual(_lowerCamelCase , 0 ) # We usually have added tokens from the start in tests because our vocab fixtures are # smaller than the original vocabs - let's not assert this # self.assertEqual(vocab_size, all_size) __magic_name__ = ["aaaaa bbbbbb", "cccccccccdddddddd"] __magic_name__ = tokenizer.add_tokens(_lowerCamelCase ) __magic_name__ = tokenizer.vocab_size __magic_name__ = len(_lowerCamelCase ) self.assertNotEqual(_lowerCamelCase , 0 ) self.assertEqual(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(_lowerCamelCase , len(_lowerCamelCase ) ) self.assertEqual(_lowerCamelCase , all_size + len(_lowerCamelCase ) ) __magic_name__ = tokenizer.encode("aaaaa bbbbbb low cccccccccdddddddd l" , add_special_tokens=_lowerCamelCase ) self.assertGreaterEqual(len(_lowerCamelCase ) , 4 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) __magic_name__ = {"eos_token": ">>>>|||<||<<|<<", "pad_token": "<<<<<|||>|>>>>|>"} __magic_name__ = tokenizer.add_special_tokens(_lowerCamelCase ) __magic_name__ = tokenizer.vocab_size __magic_name__ = len(_lowerCamelCase ) self.assertNotEqual(_lowerCamelCase , 0 ) self.assertEqual(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(_lowerCamelCase , len(_lowerCamelCase ) ) self.assertEqual(_lowerCamelCase , all_size_a + len(_lowerCamelCase ) ) __magic_name__ = tokenizer.encode( ">>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l" , add_special_tokens=_lowerCamelCase ) self.assertGreaterEqual(len(_lowerCamelCase ) , 6 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[0] , tokens[1] ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokens[-4] ) self.assertEqual(tokens[0] , tokenizer.eos_token_id ) self.assertEqual(tokens[-3] , tokenizer.pad_token_id ) @unittest.skip("The tokenizer shouldn't be used to encode input IDs (except for labels), only to decode." ) def __A ( self : Union[str, Any] ) -> Dict: pass @unittest.skip("The tokenizer shouldn't be used to encode input IDs (except for labels), only to decode." ) def __A ( self : List[str] ) -> List[str]: pass def __A ( self : Optional[int] ) -> List[Any]: # The default common tokenizer tests assumes that the output of `convert_tokens_to_string` is a string which # is not the case for Wav2Vec2PhonemeCTCTokenizer. __magic_name__ = self.get_tokenizers(fast=_lowerCamelCase , do_lower_case=_lowerCamelCase ) for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): __magic_name__ = ["ð", "ɪ", "s", "ɪ", "z", "ɐ", "t", "ɛ", "k", "s", "t"] __magic_name__ = tokenizer.convert_tokens_to_string(_lowerCamelCase ) self.assertIsInstance(output["text"] , _lowerCamelCase )
664
'''simple docstring''' from typing import Dict import numpy as np from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException if is_tf_available(): import tensorflow as tf from ..tf_utils import stable_softmax if is_torch_available(): import torch __magic_name__ : Optional[Any] =logging.get_logger(__name__) @add_end_docstrings( A , r''' top_k (`int`, defaults to 5): The number of predictions to return. targets (`str` or `List[str]`, *optional*): When passed, the model will limit the scores to the passed targets instead of looking up in the whole vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting token will be used (with a warning, and that might be slower). ''' , ) class UpperCamelCase_ ( A ): """simple docstring""" def __A ( self : Any , _lowerCamelCase : GenericTensor ) -> np.ndarray: if self.framework == "tf": __magic_name__ = tf.where(input_ids == self.tokenizer.mask_token_id ).numpy() elif self.framework == "pt": __magic_name__ = torch.nonzero(input_ids == self.tokenizer.mask_token_id , as_tuple=_lowerCamelCase ) else: raise ValueError("Unsupported framework" ) return masked_index def __A ( self : str , _lowerCamelCase : GenericTensor ) -> np.ndarray: __magic_name__ = self.get_masked_index(_lowerCamelCase ) __magic_name__ = np.prod(masked_index.shape ) if numel < 1: raise PipelineException( "fill-mask" , self.model.base_model_prefix , f'No mask_token ({self.tokenizer.mask_token}) found on the input' , ) def __A ( self : int , _lowerCamelCase : GenericTensor ) -> Any: if isinstance(_lowerCamelCase , _lowerCamelCase ): for model_input in model_inputs: self._ensure_exactly_one_mask_token(model_input["input_ids"][0] ) else: for input_ids in model_inputs["input_ids"]: self._ensure_exactly_one_mask_token(_lowerCamelCase ) def __A ( self : List[Any] , _lowerCamelCase : str , _lowerCamelCase : Any=None , **_lowerCamelCase : List[str] ) -> Dict[str, GenericTensor]: if return_tensors is None: __magic_name__ = self.framework __magic_name__ = self.tokenizer(_lowerCamelCase , return_tensors=_lowerCamelCase ) self.ensure_exactly_one_mask_token(_lowerCamelCase ) return model_inputs def __A ( self : List[str] , _lowerCamelCase : int ) -> List[Any]: __magic_name__ = self.model(**_lowerCamelCase ) __magic_name__ = model_inputs["input_ids"] return model_outputs def __A ( self : Tuple , _lowerCamelCase : List[str] , _lowerCamelCase : List[Any]=5 , _lowerCamelCase : Dict=None ) -> Dict: # Cap top_k if there are targets if target_ids is not None and target_ids.shape[0] < top_k: __magic_name__ = target_ids.shape[0] __magic_name__ = model_outputs["input_ids"][0] __magic_name__ = model_outputs["logits"] if self.framework == "tf": __magic_name__ = tf.where(input_ids == self.tokenizer.mask_token_id ).numpy()[:, 0] __magic_name__ = outputs.numpy() __magic_name__ = outputs[0, masked_index, :] __magic_name__ = stable_softmax(_lowerCamelCase , axis=-1 ) if target_ids is not None: __magic_name__ = tf.gather_nd(tf.squeeze(_lowerCamelCase , 0 ) , target_ids.reshape(-1 , 1 ) ) __magic_name__ = tf.expand_dims(_lowerCamelCase , 0 ) __magic_name__ = tf.math.top_k(_lowerCamelCase , k=_lowerCamelCase ) __magic_name__ , __magic_name__ = topk.values.numpy(), topk.indices.numpy() else: __magic_name__ = torch.nonzero(input_ids == self.tokenizer.mask_token_id , as_tuple=_lowerCamelCase ).squeeze(-1 ) # Fill mask pipeline supports only one ${mask_token} per sample __magic_name__ = outputs[0, masked_index, :] __magic_name__ = logits.softmax(dim=-1 ) if target_ids is not None: __magic_name__ = probs[..., target_ids] __magic_name__ , __magic_name__ = probs.topk(_lowerCamelCase ) __magic_name__ = [] __magic_name__ = values.shape[0] == 1 for i, (_values, _predictions) in enumerate(zip(values.tolist() , predictions.tolist() ) ): __magic_name__ = [] for v, p in zip(_values , _predictions ): # Copy is important since we're going to modify this array in place __magic_name__ = input_ids.numpy().copy() if target_ids is not None: __magic_name__ = target_ids[p].tolist() __magic_name__ = p # Filter padding out: __magic_name__ = tokens[np.where(tokens != self.tokenizer.pad_token_id )] # Originally we skip special tokens to give readable output. # For multi masks though, the other [MASK] would be removed otherwise # making the output look odd, so we add them back __magic_name__ = self.tokenizer.decode(_lowerCamelCase , skip_special_tokens=_lowerCamelCase ) __magic_name__ = {"score": v, "token": p, "token_str": self.tokenizer.decode([p] ), "sequence": sequence} row.append(_lowerCamelCase ) result.append(_lowerCamelCase ) if single_mask: return result[0] return result def __A ( self : List[Any] , _lowerCamelCase : Any , _lowerCamelCase : List[Any]=None ) -> List[str]: if isinstance(_lowerCamelCase , _lowerCamelCase ): __magic_name__ = [targets] try: __magic_name__ = self.tokenizer.get_vocab() except Exception: __magic_name__ = {} __magic_name__ = [] for target in targets: __magic_name__ = vocab.get(_lowerCamelCase , _lowerCamelCase ) if id_ is None: __magic_name__ = self.tokenizer( _lowerCamelCase , add_special_tokens=_lowerCamelCase , return_attention_mask=_lowerCamelCase , return_token_type_ids=_lowerCamelCase , max_length=1 , truncation=_lowerCamelCase , )["input_ids"] if len(_lowerCamelCase ) == 0: logger.warning( f'The specified target token `{target}` does not exist in the model vocabulary. ' "We cannot replace it with anything meaningful, ignoring it" ) continue __magic_name__ = input_ids[0] # XXX: If users encounter this pass # it becomes pretty slow, so let's make sure # The warning enables them to fix the input to # get faster performance. logger.warning( f'The specified target token `{target}` does not exist in the model vocabulary. ' f'Replacing with `{self.tokenizer.convert_ids_to_tokens(id_ )}`.' ) target_ids.append(id_ ) __magic_name__ = list(set(_lowerCamelCase ) ) if len(_lowerCamelCase ) == 0: raise ValueError("At least one target must be provided when passed." ) __magic_name__ = np.array(_lowerCamelCase ) return target_ids def __A ( self : Optional[Any] , _lowerCamelCase : Any=None , _lowerCamelCase : int=None ) -> Tuple: __magic_name__ = {} if targets is not None: __magic_name__ = self.get_target_ids(_lowerCamelCase , _lowerCamelCase ) __magic_name__ = target_ids if top_k is not None: __magic_name__ = top_k if self.tokenizer.mask_token_id is None: raise PipelineException( "fill-mask" , self.model.base_model_prefix , "The tokenizer does not define a `mask_token`." ) return {}, {}, postprocess_params def __call__( self : int , _lowerCamelCase : Any , *_lowerCamelCase : str , **_lowerCamelCase : int ) -> Optional[int]: __magic_name__ = super().__call__(_lowerCamelCase , **_lowerCamelCase ) if isinstance(_lowerCamelCase , _lowerCamelCase ) and len(_lowerCamelCase ) == 1: return outputs[0] return outputs
664
1
'''simple docstring''' from dataclasses import dataclass from typing import Optional, Tuple, Union import flax import jax.numpy as jnp from jax import random from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .scheduling_utils_flax import FlaxSchedulerMixin @flax.struct.dataclass class UpperCamelCase_ : """simple docstring""" UpperCAmelCase__ : Optional[int] = None UpperCAmelCase__ : Optional[jnp.ndarray] = None UpperCAmelCase__ : Optional[jnp.ndarray] = None # sigma(t_i) @classmethod def __A ( cls : Tuple ) -> str: return cls() @dataclass class UpperCamelCase_ ( A ): """simple docstring""" UpperCAmelCase__ : jnp.ndarray UpperCAmelCase__ : jnp.ndarray UpperCAmelCase__ : KarrasVeSchedulerState class UpperCamelCase_ ( A , A ): """simple docstring""" @property def __A ( self : Dict ) -> Union[str, Any]: return True @register_to_config def __init__( self : Optional[Any] , _lowerCamelCase : float = 0.02 , _lowerCamelCase : float = 1_00 , _lowerCamelCase : float = 1.007 , _lowerCamelCase : float = 80 , _lowerCamelCase : float = 0.05 , _lowerCamelCase : float = 50 , ) -> List[Any]: pass def __A ( self : str ) -> Dict: return KarrasVeSchedulerState.create() def __A ( self : List[str] , _lowerCamelCase : KarrasVeSchedulerState , _lowerCamelCase : int , _lowerCamelCase : Tuple = () ) -> KarrasVeSchedulerState: __magic_name__ = jnp.arange(0 , _lowerCamelCase )[::-1].copy() __magic_name__ = [ ( self.config.sigma_max**2 * (self.config.sigma_min**2 / self.config.sigma_max**2) ** (i / (num_inference_steps - 1)) ) for i in timesteps ] return state.replace( num_inference_steps=_lowerCamelCase , schedule=jnp.array(_lowerCamelCase , dtype=jnp.floataa ) , timesteps=_lowerCamelCase , ) def __A ( self : List[Any] , _lowerCamelCase : KarrasVeSchedulerState , _lowerCamelCase : jnp.ndarray , _lowerCamelCase : float , _lowerCamelCase : random.KeyArray , ) -> Tuple[jnp.ndarray, float]: if self.config.s_min <= sigma <= self.config.s_max: __magic_name__ = min(self.config.s_churn / state.num_inference_steps , 2**0.5 - 1 ) else: __magic_name__ = 0 # sample eps ~ N(0, S_noise^2 * I) __magic_name__ = random.split(_lowerCamelCase , num=1 ) __magic_name__ = self.config.s_noise * random.normal(key=_lowerCamelCase , shape=sample.shape ) __magic_name__ = sigma + gamma * sigma __magic_name__ = sample + ((sigma_hat**2 - sigma**2) ** 0.5 * eps) return sample_hat, sigma_hat def __A ( self : Optional[int] , _lowerCamelCase : KarrasVeSchedulerState , _lowerCamelCase : jnp.ndarray , _lowerCamelCase : float , _lowerCamelCase : float , _lowerCamelCase : jnp.ndarray , _lowerCamelCase : bool = True , ) -> Union[FlaxKarrasVeOutput, Tuple]: __magic_name__ = sample_hat + sigma_hat * model_output __magic_name__ = (sample_hat - pred_original_sample) / sigma_hat __magic_name__ = sample_hat + (sigma_prev - sigma_hat) * derivative if not return_dict: return (sample_prev, derivative, state) return FlaxKarrasVeOutput(prev_sample=_lowerCamelCase , derivative=_lowerCamelCase , state=_lowerCamelCase ) def __A ( self : List[str] , _lowerCamelCase : KarrasVeSchedulerState , _lowerCamelCase : jnp.ndarray , _lowerCamelCase : float , _lowerCamelCase : float , _lowerCamelCase : jnp.ndarray , _lowerCamelCase : jnp.ndarray , _lowerCamelCase : jnp.ndarray , _lowerCamelCase : bool = True , ) -> Union[FlaxKarrasVeOutput, Tuple]: __magic_name__ = sample_prev + sigma_prev * model_output __magic_name__ = (sample_prev - pred_original_sample) / sigma_prev __magic_name__ = sample_hat + (sigma_prev - sigma_hat) * (0.5 * derivative + 0.5 * derivative_corr) if not return_dict: return (sample_prev, derivative, state) return FlaxKarrasVeOutput(prev_sample=_lowerCamelCase , derivative=_lowerCamelCase , state=_lowerCamelCase ) def __A ( self : str , _lowerCamelCase : KarrasVeSchedulerState , _lowerCamelCase : Dict , _lowerCamelCase : Optional[Any] , _lowerCamelCase : Optional[int] ) -> Union[str, Any]: raise NotImplementedError()
664
'''simple docstring''' from __future__ import annotations def __snake_case ( lowerCamelCase_ : list[int] , lowerCamelCase_ : int ): '''simple docstring''' if len(lowerCamelCase_ ) < k or k < 0: raise ValueError("Invalid Input" ) __magic_name__ = __magic_name__ = sum(array[:k] ) for i in range(len(lowerCamelCase_ ) - k ): __magic_name__ = current_sum - array[i] + array[i + k] __magic_name__ = max(lowerCamelCase_ , lowerCamelCase_ ) return max_sum if __name__ == "__main__": from doctest import testmod from random import randint testmod() __magic_name__ : List[str] =[randint(-10_00, 10_00) for i in range(1_00)] __magic_name__ : List[str] =randint(0, 1_10) print(F'''The maximum sum of {k} consecutive elements is {max_sum_in_array(array,k)}''')
664
1
'''simple docstring''' import unittest from transformers import MraConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_torch_available(): import torch from transformers import ( MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, MraModel, ) from transformers.models.mra.modeling_mra import MRA_PRETRAINED_MODEL_ARCHIVE_LIST class UpperCamelCase_ : """simple docstring""" def __init__( self : Optional[int] , _lowerCamelCase : str , _lowerCamelCase : Any=2 , _lowerCamelCase : int=8 , _lowerCamelCase : Optional[int]=True , _lowerCamelCase : Tuple=True , _lowerCamelCase : List[str]=True , _lowerCamelCase : List[str]=True , _lowerCamelCase : Optional[Any]=99 , _lowerCamelCase : List[str]=16 , _lowerCamelCase : Optional[int]=5 , _lowerCamelCase : Tuple=2 , _lowerCamelCase : Dict=36 , _lowerCamelCase : Tuple="gelu" , _lowerCamelCase : Tuple=0.0 , _lowerCamelCase : List[Any]=0.0 , _lowerCamelCase : Dict=5_12 , _lowerCamelCase : Tuple=16 , _lowerCamelCase : Dict=2 , _lowerCamelCase : List[Any]=0.02 , _lowerCamelCase : Optional[Any]=3 , _lowerCamelCase : Optional[Any]=4 , _lowerCamelCase : Any=None , ) -> int: __magic_name__ = parent __magic_name__ = batch_size __magic_name__ = seq_length __magic_name__ = is_training __magic_name__ = use_input_mask __magic_name__ = use_token_type_ids __magic_name__ = use_labels __magic_name__ = vocab_size __magic_name__ = hidden_size __magic_name__ = num_hidden_layers __magic_name__ = num_attention_heads __magic_name__ = intermediate_size __magic_name__ = hidden_act __magic_name__ = hidden_dropout_prob __magic_name__ = attention_probs_dropout_prob __magic_name__ = max_position_embeddings __magic_name__ = type_vocab_size __magic_name__ = type_sequence_label_size __magic_name__ = initializer_range __magic_name__ = num_labels __magic_name__ = num_choices __magic_name__ = scope def __A ( self : Union[str, Any] ) -> Optional[int]: __magic_name__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __magic_name__ = None if self.use_input_mask: __magic_name__ = random_attention_mask([self.batch_size, self.seq_length] ) __magic_name__ = None if self.use_token_type_ids: __magic_name__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __magic_name__ = None __magic_name__ = None __magic_name__ = None if self.use_labels: __magic_name__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __magic_name__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __magic_name__ = ids_tensor([self.batch_size] , self.num_choices ) __magic_name__ = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __A ( self : Dict ) -> List[str]: return MraConfig( 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 , ) def __A ( self : str ) -> str: __magic_name__ = self.get_config() __magic_name__ = 3_00 return config def __A ( self : Dict ) -> List[Any]: ( ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ) = self.prepare_config_and_inputs() __magic_name__ = True __magic_name__ = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __magic_name__ = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def __A ( self : List[str] , _lowerCamelCase : Tuple , _lowerCamelCase : List[Any] , _lowerCamelCase : Tuple , _lowerCamelCase : Optional[Any] , _lowerCamelCase : Optional[Any] , _lowerCamelCase : str , _lowerCamelCase : List[Any] ) -> Union[str, Any]: __magic_name__ = MraModel(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __magic_name__ = model(_lowerCamelCase , attention_mask=_lowerCamelCase , token_type_ids=_lowerCamelCase ) __magic_name__ = model(_lowerCamelCase , token_type_ids=_lowerCamelCase ) __magic_name__ = model(_lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __A ( self : int , _lowerCamelCase : List[str] , _lowerCamelCase : Optional[int] , _lowerCamelCase : Tuple , _lowerCamelCase : Dict , _lowerCamelCase : Tuple , _lowerCamelCase : Optional[int] , _lowerCamelCase : Optional[Any] , _lowerCamelCase : int , _lowerCamelCase : List[str] , ) -> Tuple: __magic_name__ = True __magic_name__ = MraModel(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __magic_name__ = model( _lowerCamelCase , attention_mask=_lowerCamelCase , token_type_ids=_lowerCamelCase , encoder_hidden_states=_lowerCamelCase , encoder_attention_mask=_lowerCamelCase , ) __magic_name__ = model( _lowerCamelCase , attention_mask=_lowerCamelCase , token_type_ids=_lowerCamelCase , encoder_hidden_states=_lowerCamelCase , ) __magic_name__ = model(_lowerCamelCase , attention_mask=_lowerCamelCase , token_type_ids=_lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __A ( self : List[Any] , _lowerCamelCase : Optional[Any] , _lowerCamelCase : Optional[int] , _lowerCamelCase : Any , _lowerCamelCase : Any , _lowerCamelCase : int , _lowerCamelCase : int , _lowerCamelCase : Dict ) -> Any: __magic_name__ = MraForMaskedLM(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __magic_name__ = model(_lowerCamelCase , attention_mask=_lowerCamelCase , token_type_ids=_lowerCamelCase , labels=_lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __A ( self : List[str] , _lowerCamelCase : Any , _lowerCamelCase : List[str] , _lowerCamelCase : Optional[int] , _lowerCamelCase : int , _lowerCamelCase : str , _lowerCamelCase : str , _lowerCamelCase : str ) -> Any: __magic_name__ = MraForQuestionAnswering(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __magic_name__ = model( _lowerCamelCase , attention_mask=_lowerCamelCase , token_type_ids=_lowerCamelCase , start_positions=_lowerCamelCase , end_positions=_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 __A ( self : Union[str, Any] , _lowerCamelCase : Dict , _lowerCamelCase : str , _lowerCamelCase : Union[str, Any] , _lowerCamelCase : Optional[Any] , _lowerCamelCase : Union[str, Any] , _lowerCamelCase : List[str] , _lowerCamelCase : str ) -> Union[str, Any]: __magic_name__ = self.num_labels __magic_name__ = MraForSequenceClassification(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __magic_name__ = model(_lowerCamelCase , attention_mask=_lowerCamelCase , token_type_ids=_lowerCamelCase , labels=_lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __A ( self : Optional[Any] , _lowerCamelCase : str , _lowerCamelCase : str , _lowerCamelCase : Optional[Any] , _lowerCamelCase : Tuple , _lowerCamelCase : List[str] , _lowerCamelCase : Optional[Any] , _lowerCamelCase : Union[str, Any] ) -> str: __magic_name__ = self.num_labels __magic_name__ = MraForTokenClassification(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __magic_name__ = model(_lowerCamelCase , attention_mask=_lowerCamelCase , token_type_ids=_lowerCamelCase , labels=_lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __A ( self : Optional[Any] , _lowerCamelCase : List[str] , _lowerCamelCase : List[str] , _lowerCamelCase : int , _lowerCamelCase : List[str] , _lowerCamelCase : List[str] , _lowerCamelCase : List[str] , _lowerCamelCase : List[str] ) -> Any: __magic_name__ = self.num_choices __magic_name__ = MraForMultipleChoice(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __magic_name__ = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __magic_name__ = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __magic_name__ = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __magic_name__ = model( _lowerCamelCase , attention_mask=_lowerCamelCase , token_type_ids=_lowerCamelCase , labels=_lowerCamelCase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __A ( self : Optional[int] ) -> int: __magic_name__ = self.prepare_config_and_inputs() ( ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ) = config_and_inputs __magic_name__ = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class UpperCamelCase_ ( A , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : str = ( ( MraModel, MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, ) if is_torch_available() else () ) UpperCAmelCase__ : List[Any] = False UpperCAmelCase__ : Tuple = False UpperCAmelCase__ : List[str] = False UpperCAmelCase__ : Any = False UpperCAmelCase__ : Union[str, Any] = () def __A ( self : int ) -> Any: __magic_name__ = MraModelTester(self ) __magic_name__ = ConfigTester(self , config_class=_lowerCamelCase , hidden_size=37 ) def __A ( self : Union[str, Any] ) -> Tuple: self.config_tester.run_common_tests() def __A ( self : Optional[int] ) -> Any: __magic_name__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowerCamelCase ) def __A ( self : Any ) -> Any: __magic_name__ = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __magic_name__ = type self.model_tester.create_and_check_model(*_lowerCamelCase ) def __A ( self : Any ) -> Tuple: __magic_name__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_lowerCamelCase ) def __A ( self : Dict ) -> List[str]: __magic_name__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*_lowerCamelCase ) def __A ( self : Any ) -> Dict: __magic_name__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*_lowerCamelCase ) def __A ( self : Dict ) -> str: __magic_name__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*_lowerCamelCase ) def __A ( self : int ) -> Union[str, Any]: __magic_name__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_lowerCamelCase ) @slow def __A ( self : str ) -> int: for model_name in MRA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __magic_name__ = MraModel.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) @unittest.skip(reason="MRA does not output attentions" ) def __A ( self : List[str] ) -> Optional[int]: return @require_torch class UpperCamelCase_ ( unittest.TestCase ): """simple docstring""" @slow def __A ( self : Optional[int] ) -> Tuple: __magic_name__ = MraModel.from_pretrained("uw-madison/mra-base-512-4" ) __magic_name__ = torch.arange(2_56 ).unsqueeze(0 ) with torch.no_grad(): __magic_name__ = model(_lowerCamelCase )[0] __magic_name__ = torch.Size((1, 2_56, 7_68) ) self.assertEqual(output.shape , _lowerCamelCase ) __magic_name__ = torch.tensor( [[[-0.0_140, 0.0_830, -0.0_381], [0.1_546, 0.1_402, 0.0_220], [0.1_162, 0.0_851, 0.0_165]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , _lowerCamelCase , atol=1e-4 ) ) @slow def __A ( self : Optional[int] ) -> Optional[Any]: __magic_name__ = MraForMaskedLM.from_pretrained("uw-madison/mra-base-512-4" ) __magic_name__ = torch.arange(2_56 ).unsqueeze(0 ) with torch.no_grad(): __magic_name__ = model(_lowerCamelCase )[0] __magic_name__ = 5_02_65 __magic_name__ = torch.Size((1, 2_56, vocab_size) ) self.assertEqual(output.shape , _lowerCamelCase ) __magic_name__ = torch.tensor( [[[9.2_595, -3.6_038, 11.8_819], [9.3_869, -3.2_693, 11.0_956], [11.8_524, -3.4_938, 13.1_210]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , _lowerCamelCase , atol=1e-4 ) ) @slow def __A ( self : Tuple ) -> List[Any]: __magic_name__ = MraForMaskedLM.from_pretrained("uw-madison/mra-base-4096-8-d3" ) __magic_name__ = torch.arange(40_96 ).unsqueeze(0 ) with torch.no_grad(): __magic_name__ = model(_lowerCamelCase )[0] __magic_name__ = 5_02_65 __magic_name__ = torch.Size((1, 40_96, vocab_size) ) self.assertEqual(output.shape , _lowerCamelCase ) __magic_name__ = torch.tensor( [[[5.4_789, -2.3_564, 7.5_064], [7.9_067, -1.3_369, 9.9_668], [9.0_712, -1.8_106, 7.0_380]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , _lowerCamelCase , atol=1e-4 ) )
664
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __magic_name__ : int =logging.get_logger(__name__) __magic_name__ : List[Any] ={} class UpperCamelCase_ ( A ): """simple docstring""" UpperCAmelCase__ : int = '''llama''' UpperCAmelCase__ : Any = ['''past_key_values'''] def __init__( self : List[Any] , _lowerCamelCase : List[Any]=3_20_00 , _lowerCamelCase : Optional[Any]=40_96 , _lowerCamelCase : Tuple=1_10_08 , _lowerCamelCase : List[Any]=32 , _lowerCamelCase : Tuple=32 , _lowerCamelCase : List[str]=None , _lowerCamelCase : str="silu" , _lowerCamelCase : Optional[Any]=20_48 , _lowerCamelCase : Optional[Any]=0.02 , _lowerCamelCase : Union[str, Any]=1e-6 , _lowerCamelCase : Optional[int]=True , _lowerCamelCase : Dict=0 , _lowerCamelCase : int=1 , _lowerCamelCase : str=2 , _lowerCamelCase : List[Any]=1 , _lowerCamelCase : Optional[int]=False , _lowerCamelCase : List[str]=None , **_lowerCamelCase : List[Any] , ) -> Any: __magic_name__ = vocab_size __magic_name__ = max_position_embeddings __magic_name__ = hidden_size __magic_name__ = intermediate_size __magic_name__ = num_hidden_layers __magic_name__ = num_attention_heads # for backward compatibility if num_key_value_heads is None: __magic_name__ = num_attention_heads __magic_name__ = num_key_value_heads __magic_name__ = hidden_act __magic_name__ = initializer_range __magic_name__ = rms_norm_eps __magic_name__ = pretraining_tp __magic_name__ = use_cache __magic_name__ = rope_scaling self._rope_scaling_validation() super().__init__( pad_token_id=_lowerCamelCase , bos_token_id=_lowerCamelCase , eos_token_id=_lowerCamelCase , tie_word_embeddings=_lowerCamelCase , **_lowerCamelCase , ) def __A ( self : Union[str, Any] ) -> List[Any]: if self.rope_scaling is None: return if not isinstance(self.rope_scaling , _lowerCamelCase ) or len(self.rope_scaling ) != 2: raise ValueError( "`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, " f'got {self.rope_scaling}' ) __magic_name__ = self.rope_scaling.get("type" , _lowerCamelCase ) __magic_name__ = self.rope_scaling.get("factor" , _lowerCamelCase ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( f'`rope_scaling`\'s name field must be one of [\'linear\', \'dynamic\'], got {rope_scaling_type}' ) if rope_scaling_factor is None or not isinstance(_lowerCamelCase , _lowerCamelCase ) or rope_scaling_factor <= 1.0: raise ValueError(f'`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}' )
664
1
'''simple docstring''' import argparse import torch from transformers import BlenderbotConfig, BlenderbotForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() __magic_name__ : List[str] =logging.get_logger(__name__) __magic_name__ : Optional[Any] =[ ['attention', 'attn'], ['encoder_attention', 'encoder_attn'], ['q_lin', 'q_proj'], ['k_lin', 'k_proj'], ['v_lin', 'v_proj'], ['out_lin', 'out_proj'], ['norm_embeddings', 'layernorm_embedding'], ['position_embeddings', 'embed_positions'], ['embeddings', 'embed_tokens'], ['ffn.lin', 'fc'], ] def __snake_case ( lowerCamelCase_ : Optional[int] ): '''simple docstring''' if k == "embeddings.weight": return "shared.weight" for parlai_name, hf_name in PATTERNS: __magic_name__ = k.replace(lowerCamelCase_ , lowerCamelCase_ ) if k.startswith("encoder" ): __magic_name__ = k.replace(".attn" , ".self_attn" ) __magic_name__ = k.replace("norm1" , "self_attn_layer_norm" ) __magic_name__ = k.replace("norm2" , "final_layer_norm" ) elif k.startswith("decoder" ): __magic_name__ = k.replace("norm1" , "self_attn_layer_norm" ) __magic_name__ = k.replace("norm2" , "encoder_attn_layer_norm" ) __magic_name__ = k.replace("norm3" , "final_layer_norm" ) return k def __snake_case ( lowerCamelCase_ : Optional[int] ): '''simple docstring''' __magic_name__ = [ "model.encoder.layernorm_embedding.weight", "model.encoder.layernorm_embedding.bias", "model.decoder.layernorm_embedding.weight", "model.decoder.layernorm_embedding.bias", ] for k in keys: __magic_name__ = sd.pop(lowerCamelCase_ ) __magic_name__ = k.replace("layernorm_embedding" , "layer_norm" ) assert new_k not in sd __magic_name__ = v __magic_name__ : Union[str, Any] =['START'] @torch.no_grad() def __snake_case ( lowerCamelCase_ : Union[str, Any] , lowerCamelCase_ : int , lowerCamelCase_ : Optional[int] ): '''simple docstring''' __magic_name__ = torch.load(lowerCamelCase_ , map_location="cpu" ) __magic_name__ = model["model"] __magic_name__ = BlenderbotConfig.from_json_file(lowerCamelCase_ ) __magic_name__ = BlenderbotForConditionalGeneration(lowerCamelCase_ ) __magic_name__ = m.model.state_dict().keys() __magic_name__ = [] __magic_name__ = {} for k, v in sd.items(): if k in IGNORE_KEYS: continue __magic_name__ = rename_state_dict_key(lowerCamelCase_ ) if new_k not in valid_keys: failures.append([k, new_k] ) else: __magic_name__ = v if cfg.normalize_before: # Blenderbot-3B checkpoints. Rename layernorm_embedding -> layer_norm rename_layernorm_keys(lowerCamelCase_ ) m.model.load_state_dict(lowerCamelCase_ , strict=lowerCamelCase_ ) m.half() m.save_pretrained(lowerCamelCase_ ) if __name__ == "__main__": __magic_name__ : Any =argparse.ArgumentParser() # Required parameters parser.add_argument('--src_path', type=str, help='like blenderbot-model.bin') parser.add_argument('--save_dir', default='hf_blenderbot', type=str, help='Where to save converted model.') parser.add_argument( '--hf_config_json', default='blenderbot-3b-config.json', type=str, help='Path to config to use' ) __magic_name__ : Optional[Any] =parser.parse_args() convert_parlai_checkpoint(args.src_path, args.save_dir, args.hf_config_json)
664
'''simple docstring''' __magic_name__ : Dict =8.3_1_4_4_6_2 # Unit - J mol-1 K-1 def __snake_case ( lowerCamelCase_ : float , lowerCamelCase_ : float , lowerCamelCase_ : float ): '''simple docstring''' if moles < 0 or kelvin < 0 or volume < 0: raise ValueError("Invalid inputs. Enter positive value." ) return moles * kelvin * UNIVERSAL_GAS_CONSTANT / volume def __snake_case ( lowerCamelCase_ : float , lowerCamelCase_ : float , lowerCamelCase_ : float ): '''simple docstring''' if moles < 0 or kelvin < 0 or pressure < 0: raise ValueError("Invalid inputs. Enter positive value." ) return moles * kelvin * UNIVERSAL_GAS_CONSTANT / pressure if __name__ == "__main__": from doctest import testmod testmod()
664
1
'''simple docstring''' import unittest from transformers import is_vision_available from transformers.pipelines import pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class UpperCamelCase_ : """simple docstring""" @staticmethod def __A ( *_lowerCamelCase : int , **_lowerCamelCase : Optional[Any] ) -> Optional[Any]: pass @is_pipeline_test @require_vision class UpperCamelCase_ ( unittest.TestCase ): """simple docstring""" @require_torch def __A ( self : str ) -> List[str]: __magic_name__ = pipeline( model="hf-internal-testing/tiny-random-clip-zero-shot-image-classification" , ) __magic_name__ = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) __magic_name__ = image_classifier(_lowerCamelCase , candidate_labels=["a", "b", "c"] ) # The floating scores are so close, we enter floating error approximation and the order is not guaranteed across # python and torch versions. self.assertIn( nested_simplify(_lowerCamelCase ) , [ [{"score": 0.333, "label": "a"}, {"score": 0.333, "label": "b"}, {"score": 0.333, "label": "c"}], [{"score": 0.333, "label": "a"}, {"score": 0.333, "label": "c"}, {"score": 0.333, "label": "b"}], ] , ) __magic_name__ = image_classifier([image] * 5 , candidate_labels=["A", "B", "C"] , batch_size=2 ) self.assertEqual( nested_simplify(_lowerCamelCase ) , [ [ {"score": 0.333, "label": ANY(_lowerCamelCase )}, {"score": 0.333, "label": ANY(_lowerCamelCase )}, {"score": 0.333, "label": ANY(_lowerCamelCase )}, ], [ {"score": 0.333, "label": ANY(_lowerCamelCase )}, {"score": 0.333, "label": ANY(_lowerCamelCase )}, {"score": 0.333, "label": ANY(_lowerCamelCase )}, ], [ {"score": 0.333, "label": ANY(_lowerCamelCase )}, {"score": 0.333, "label": ANY(_lowerCamelCase )}, {"score": 0.333, "label": ANY(_lowerCamelCase )}, ], [ {"score": 0.333, "label": ANY(_lowerCamelCase )}, {"score": 0.333, "label": ANY(_lowerCamelCase )}, {"score": 0.333, "label": ANY(_lowerCamelCase )}, ], [ {"score": 0.333, "label": ANY(_lowerCamelCase )}, {"score": 0.333, "label": ANY(_lowerCamelCase )}, {"score": 0.333, "label": ANY(_lowerCamelCase )}, ], ] , ) @require_tf def __A ( self : Dict ) -> int: __magic_name__ = pipeline( model="hf-internal-testing/tiny-random-clip-zero-shot-image-classification" , framework="tf" ) __magic_name__ = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) __magic_name__ = image_classifier(_lowerCamelCase , candidate_labels=["a", "b", "c"] ) self.assertEqual( nested_simplify(_lowerCamelCase ) , [{"score": 0.333, "label": "a"}, {"score": 0.333, "label": "b"}, {"score": 0.333, "label": "c"}] , ) __magic_name__ = image_classifier([image] * 5 , candidate_labels=["A", "B", "C"] , batch_size=2 ) self.assertEqual( nested_simplify(_lowerCamelCase ) , [ [ {"score": 0.333, "label": ANY(_lowerCamelCase )}, {"score": 0.333, "label": ANY(_lowerCamelCase )}, {"score": 0.333, "label": ANY(_lowerCamelCase )}, ], [ {"score": 0.333, "label": ANY(_lowerCamelCase )}, {"score": 0.333, "label": ANY(_lowerCamelCase )}, {"score": 0.333, "label": ANY(_lowerCamelCase )}, ], [ {"score": 0.333, "label": ANY(_lowerCamelCase )}, {"score": 0.333, "label": ANY(_lowerCamelCase )}, {"score": 0.333, "label": ANY(_lowerCamelCase )}, ], [ {"score": 0.333, "label": ANY(_lowerCamelCase )}, {"score": 0.333, "label": ANY(_lowerCamelCase )}, {"score": 0.333, "label": ANY(_lowerCamelCase )}, ], [ {"score": 0.333, "label": ANY(_lowerCamelCase )}, {"score": 0.333, "label": ANY(_lowerCamelCase )}, {"score": 0.333, "label": ANY(_lowerCamelCase )}, ], ] , ) @slow @require_torch def __A ( self : Optional[Any] ) -> List[str]: __magic_name__ = pipeline( task="zero-shot-image-classification" , model="openai/clip-vit-base-patch32" , ) # This is an image of 2 cats with remotes and no planes __magic_name__ = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) __magic_name__ = image_classifier(_lowerCamelCase , candidate_labels=["cat", "plane", "remote"] ) self.assertEqual( nested_simplify(_lowerCamelCase ) , [ {"score": 0.511, "label": "remote"}, {"score": 0.485, "label": "cat"}, {"score": 0.004, "label": "plane"}, ] , ) __magic_name__ = image_classifier([image] * 5 , candidate_labels=["cat", "plane", "remote"] , batch_size=2 ) self.assertEqual( nested_simplify(_lowerCamelCase ) , [ [ {"score": 0.511, "label": "remote"}, {"score": 0.485, "label": "cat"}, {"score": 0.004, "label": "plane"}, ], ] * 5 , ) @slow @require_tf def __A ( self : Optional[Any] ) -> str: __magic_name__ = pipeline( task="zero-shot-image-classification" , model="openai/clip-vit-base-patch32" , framework="tf" ) # This is an image of 2 cats with remotes and no planes __magic_name__ = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) __magic_name__ = image_classifier(_lowerCamelCase , candidate_labels=["cat", "plane", "remote"] ) self.assertEqual( nested_simplify(_lowerCamelCase ) , [ {"score": 0.511, "label": "remote"}, {"score": 0.485, "label": "cat"}, {"score": 0.004, "label": "plane"}, ] , ) __magic_name__ = image_classifier([image] * 5 , candidate_labels=["cat", "plane", "remote"] , batch_size=2 ) self.assertEqual( nested_simplify(_lowerCamelCase ) , [ [ {"score": 0.511, "label": "remote"}, {"score": 0.485, "label": "cat"}, {"score": 0.004, "label": "plane"}, ], ] * 5 , )
664
'''simple docstring''' import logging import os from typing import List, TextIO, Union from conllu import parse_incr from utils_ner import InputExample, Split, TokenClassificationTask __magic_name__ : List[Any] =logging.getLogger(__name__) class UpperCamelCase_ ( A ): """simple docstring""" def __init__( self : Optional[Any] , _lowerCamelCase : str=-1 ) -> List[str]: # in NER datasets, the last column is usually reserved for NER label __magic_name__ = label_idx def __A ( self : Any , _lowerCamelCase : str , _lowerCamelCase : Union[Split, str] ) -> List[InputExample]: if isinstance(_lowerCamelCase , _lowerCamelCase ): __magic_name__ = mode.value __magic_name__ = os.path.join(_lowerCamelCase , f'{mode}.txt' ) __magic_name__ = 1 __magic_name__ = [] with open(_lowerCamelCase , encoding="utf-8" ) as f: __magic_name__ = [] __magic_name__ = [] for line in f: if line.startswith("-DOCSTART-" ) or line == "" or line == "\n": if words: examples.append(InputExample(guid=f'{mode}-{guid_index}' , words=_lowerCamelCase , labels=_lowerCamelCase ) ) guid_index += 1 __magic_name__ = [] __magic_name__ = [] else: __magic_name__ = line.split(" " ) words.append(splits[0] ) if len(_lowerCamelCase ) > 1: labels.append(splits[self.label_idx].replace("\n" , "" ) ) else: # Examples could have no label for mode = "test" labels.append("O" ) if words: examples.append(InputExample(guid=f'{mode}-{guid_index}' , words=_lowerCamelCase , labels=_lowerCamelCase ) ) return examples def __A ( self : Optional[Any] , _lowerCamelCase : TextIO , _lowerCamelCase : TextIO , _lowerCamelCase : List ) -> Union[str, Any]: __magic_name__ = 0 for line in test_input_reader: if line.startswith("-DOCSTART-" ) or line == "" or line == "\n": writer.write(_lowerCamelCase ) if not preds_list[example_id]: example_id += 1 elif preds_list[example_id]: __magic_name__ = line.split()[0] + " " + preds_list[example_id].pop(0 ) + "\n" writer.write(_lowerCamelCase ) else: logger.warning("Maximum sequence length exceeded: No prediction for '%s'." , line.split()[0] ) def __A ( self : Tuple , _lowerCamelCase : str ) -> List[str]: if path: with open(_lowerCamelCase , "r" ) as f: __magic_name__ = f.read().splitlines() if "O" not in labels: __magic_name__ = ["O"] + labels return labels else: return ["O", "B-MISC", "I-MISC", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC"] class UpperCamelCase_ ( A ): """simple docstring""" def __init__( self : int ) -> str: # in CONLL2003 dataset chunk column is second-to-last super().__init__(label_idx=-2 ) def __A ( self : int , _lowerCamelCase : str ) -> List[str]: if path: with open(_lowerCamelCase , "r" ) as f: __magic_name__ = f.read().splitlines() if "O" not in labels: __magic_name__ = ["O"] + labels return labels else: return [ "O", "B-ADVP", "B-INTJ", "B-LST", "B-PRT", "B-NP", "B-SBAR", "B-VP", "B-ADJP", "B-CONJP", "B-PP", "I-ADVP", "I-INTJ", "I-LST", "I-PRT", "I-NP", "I-SBAR", "I-VP", "I-ADJP", "I-CONJP", "I-PP", ] class UpperCamelCase_ ( A ): """simple docstring""" def __A ( self : List[Any] , _lowerCamelCase : Union[str, Any] , _lowerCamelCase : Union[Split, str] ) -> List[InputExample]: if isinstance(_lowerCamelCase , _lowerCamelCase ): __magic_name__ = mode.value __magic_name__ = os.path.join(_lowerCamelCase , f'{mode}.txt' ) __magic_name__ = 1 __magic_name__ = [] with open(_lowerCamelCase , encoding="utf-8" ) as f: for sentence in parse_incr(_lowerCamelCase ): __magic_name__ = [] __magic_name__ = [] for token in sentence: words.append(token["form"] ) labels.append(token["upos"] ) assert len(_lowerCamelCase ) == len(_lowerCamelCase ) if words: examples.append(InputExample(guid=f'{mode}-{guid_index}' , words=_lowerCamelCase , labels=_lowerCamelCase ) ) guid_index += 1 return examples def __A ( self : Optional[int] , _lowerCamelCase : TextIO , _lowerCamelCase : TextIO , _lowerCamelCase : List ) -> Any: __magic_name__ = 0 for sentence in parse_incr(_lowerCamelCase ): __magic_name__ = preds_list[example_id] __magic_name__ = "" for token in sentence: out += f'{token["form"]} ({token["upos"]}|{s_p.pop(0 )}) ' out += "\n" writer.write(_lowerCamelCase ) example_id += 1 def __A ( self : Dict , _lowerCamelCase : str ) -> List[str]: if path: with open(_lowerCamelCase , "r" ) as f: return f.read().splitlines() else: return [ "ADJ", "ADP", "ADV", "AUX", "CCONJ", "DET", "INTJ", "NOUN", "NUM", "PART", "PRON", "PROPN", "PUNCT", "SCONJ", "SYM", "VERB", "X", ]
664
1
'''simple docstring''' from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class UpperCamelCase_ ( A ): """simple docstring""" UpperCAmelCase__ : str = '''ClapFeatureExtractor''' UpperCAmelCase__ : int = ('''RobertaTokenizer''', '''RobertaTokenizerFast''') def __init__( self : Tuple , _lowerCamelCase : List[str] , _lowerCamelCase : Dict ) -> List[str]: super().__init__(_lowerCamelCase , _lowerCamelCase ) def __call__( self : int , _lowerCamelCase : Optional[int]=None , _lowerCamelCase : List[str]=None , _lowerCamelCase : int=None , **_lowerCamelCase : Any ) -> Tuple: __magic_name__ = kwargs.pop("sampling_rate" , _lowerCamelCase ) if text is None and audios is None: raise ValueError("You have to specify either text or audios. Both cannot be none." ) if text is not None: __magic_name__ = self.tokenizer(_lowerCamelCase , return_tensors=_lowerCamelCase , **_lowerCamelCase ) if audios is not None: __magic_name__ = self.feature_extractor( _lowerCamelCase , sampling_rate=_lowerCamelCase , return_tensors=_lowerCamelCase , **_lowerCamelCase ) if text is not None and audios is not None: __magic_name__ = audio_features.input_features return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**_lowerCamelCase ) , tensor_type=_lowerCamelCase ) def __A ( self : Dict , *_lowerCamelCase : Optional[int] , **_lowerCamelCase : str ) -> Union[str, Any]: return self.tokenizer.batch_decode(*_lowerCamelCase , **_lowerCamelCase ) def __A ( self : List[str] , *_lowerCamelCase : List[str] , **_lowerCamelCase : Optional[int] ) -> str: return self.tokenizer.decode(*_lowerCamelCase , **_lowerCamelCase ) @property def __A ( self : int ) -> List[Any]: __magic_name__ = self.tokenizer.model_input_names __magic_name__ = self.feature_extractor.model_input_names return list(dict.fromkeys(tokenizer_input_names + feature_extractor_input_names ) )
664
'''simple docstring''' from __future__ import annotations from typing import Any class UpperCamelCase_ : """simple docstring""" def __init__( self : int , _lowerCamelCase : int , _lowerCamelCase : int , _lowerCamelCase : float = 0 ) -> None: __magic_name__ , __magic_name__ = row, column __magic_name__ = [[default_value for c in range(_lowerCamelCase )] for r in range(_lowerCamelCase )] def __str__( self : Optional[Any] ) -> str: __magic_name__ = f'Matrix consist of {self.row} rows and {self.column} columns\n' # Make string identifier __magic_name__ = 0 for row_vector in self.array: for obj in row_vector: __magic_name__ = max(_lowerCamelCase , len(str(_lowerCamelCase ) ) ) __magic_name__ = f'%{max_element_length}s' # Make string and return def single_line(_lowerCamelCase : list[float] ) -> str: nonlocal string_format_identifier __magic_name__ = "[" line += ", ".join(string_format_identifier % (obj,) for obj in row_vector ) line += "]" return line s += "\n".join(single_line(_lowerCamelCase ) for row_vector in self.array ) return s def __repr__( self : Optional[int] ) -> str: return str(self ) def __A ( self : Optional[Any] , _lowerCamelCase : tuple[int, int] ) -> bool: if not (isinstance(_lowerCamelCase , (list, tuple) ) and len(_lowerCamelCase ) == 2): return False elif not (0 <= loc[0] < self.row and 0 <= loc[1] < self.column): return False else: return True def __getitem__( self : Optional[int] , _lowerCamelCase : tuple[int, int] ) -> Any: assert self.validate_indicies(_lowerCamelCase ) return self.array[loc[0]][loc[1]] def __setitem__( self : Tuple , _lowerCamelCase : tuple[int, int] , _lowerCamelCase : float ) -> None: assert self.validate_indicies(_lowerCamelCase ) __magic_name__ = value def __add__( self : Union[str, Any] , _lowerCamelCase : Matrix ) -> Matrix: assert isinstance(_lowerCamelCase , _lowerCamelCase ) assert self.row == another.row and self.column == another.column # Add __magic_name__ = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): __magic_name__ = self[r, c] + another[r, c] return result def __neg__( self : int ) -> Matrix: __magic_name__ = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): __magic_name__ = -self[r, c] return result def __sub__( self : Optional[int] , _lowerCamelCase : Matrix ) -> Matrix: return self + (-another) def __mul__( self : Optional[int] , _lowerCamelCase : int | float | Matrix ) -> Matrix: if isinstance(_lowerCamelCase , (int, float) ): # Scalar multiplication __magic_name__ = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): __magic_name__ = self[r, c] * another return result elif isinstance(_lowerCamelCase , _lowerCamelCase ): # Matrix multiplication assert self.column == another.row __magic_name__ = Matrix(self.row , another.column ) for r in range(self.row ): for c in range(another.column ): for i in range(self.column ): result[r, c] += self[r, i] * another[i, c] return result else: __magic_name__ = f'Unsupported type given for another ({type(_lowerCamelCase )})' raise TypeError(_lowerCamelCase ) def __A ( self : Optional[int] ) -> Matrix: __magic_name__ = Matrix(self.column , self.row ) for r in range(self.row ): for c in range(self.column ): __magic_name__ = self[r, c] return result def __A ( self : int , _lowerCamelCase : Matrix , _lowerCamelCase : Matrix ) -> Any: assert isinstance(_lowerCamelCase , _lowerCamelCase ) and isinstance(_lowerCamelCase , _lowerCamelCase ) assert self.row == self.column == u.row == v.row # u, v should be column vector assert u.column == v.column == 1 # u, v should be column vector # Calculate __magic_name__ = v.transpose() __magic_name__ = (v_t * self * u)[0, 0] + 1 if numerator_factor == 0: return None # It's not invertable return self - ((self * u) * (v_t * self) * (1.0 / numerator_factor)) # Testing if __name__ == "__main__": def __snake_case ( ): '''simple docstring''' __magic_name__ = Matrix(3 , 3 , 0 ) for i in range(3 ): __magic_name__ = 1 print(F'a^(-1) is {ainv}' ) # u, v __magic_name__ = Matrix(3 , 1 , 0 ) __magic_name__ , __magic_name__ , __magic_name__ = 1, 2, -3 __magic_name__ = Matrix(3 , 1 , 0 ) __magic_name__ , __magic_name__ , __magic_name__ = 4, -2, 5 print(F'u is {u}' ) print(F'v is {v}' ) print(F'uv^T is {u * v.transpose()}' ) # Sherman Morrison print(F'(a + uv^T)^(-1) is {ainv.sherman_morrison(lowerCamelCase_ , lowerCamelCase_ )}' ) def __snake_case ( ): '''simple docstring''' import doctest doctest.testmod() testa()
664
1
'''simple docstring''' import numpy as np from scipy.spatial.distance import cdist from sklearn.metrics import fa_score import datasets __magic_name__ : Optional[Any] ='\\n @inproceedings{kakwani2020indicnlpsuite,\n title={{IndicNLPSuite: Monolingual Corpora, Evaluation Benchmarks and Pre-trained Multilingual Language Models for Indian Languages}},\n author={Divyanshu Kakwani and Anoop Kunchukuttan and Satish Golla and Gokul N.C. and Avik Bhattacharyya and Mitesh M. Khapra and Pratyush Kumar},\n year={2020},\n booktitle={Findings of EMNLP},\n}\n' __magic_name__ : Any ='\\n IndicGLUE is a natural language understanding benchmark for Indian languages. It contains a wide\n variety of tasks and covers 11 major Indian languages - as, bn, gu, hi, kn, ml, mr, or, pa, ta, te.\n' __magic_name__ : int ='\nCompute IndicGLUE evaluation metric associated to each IndicGLUE dataset.\nArgs:\n predictions: list of predictions to score (as int64),\n except for \'cvit-mkb-clsr\' where each prediction is a vector (of float32).\n references: list of ground truth labels corresponding to the predictions (as int64),\n except for \'cvit-mkb-clsr\' where each reference is a vector (of float32).\nReturns: depending on the IndicGLUE subset, one or several of:\n "accuracy": Accuracy\n "f1": F1 score\n "precision": Precision@10\nExamples:\n\n >>> indic_glue_metric = datasets.load_metric(\'indic_glue\', \'wnli\') # \'wnli\' or any of ["copa", "sna", "csqa", "wstp", "inltkh", "bbca", "iitp-mr", "iitp-pr", "actsa-sc", "md"]\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = indic_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0}\n\n >>> indic_glue_metric = datasets.load_metric(\'indic_glue\', \'wiki-ner\')\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = indic_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0, \'f1\': 1.0}\n\n >>> indic_glue_metric = datasets.load_metric(\'indic_glue\', \'cvit-mkb-clsr\')\n >>> references = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]]\n >>> predictions = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]]\n >>> results = indic_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'precision@10\': 1.0}\n\n' def __snake_case ( lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : int ): '''simple docstring''' return float((preds == labels).mean() ) def __snake_case ( lowerCamelCase_ : Union[str, Any] , lowerCamelCase_ : Dict ): '''simple docstring''' __magic_name__ = simple_accuracy(lowerCamelCase_ , lowerCamelCase_ ) __magic_name__ = float(fa_score(y_true=lowerCamelCase_ , y_pred=lowerCamelCase_ ) ) return { "accuracy": acc, "f1": fa, } def __snake_case ( lowerCamelCase_ : Any , lowerCamelCase_ : List[Any] ): '''simple docstring''' __magic_name__ = np.array(lowerCamelCase_ ) __magic_name__ = np.array(lowerCamelCase_ ) __magic_name__ = en_sentvecs.shape[0] # mean centering __magic_name__ = en_sentvecs - np.mean(lowerCamelCase_ , axis=0 ) __magic_name__ = in_sentvecs - np.mean(lowerCamelCase_ , axis=0 ) __magic_name__ = cdist(lowerCamelCase_ , lowerCamelCase_ , "cosine" ) __magic_name__ = np.array(range(lowerCamelCase_ ) ) __magic_name__ = sim.argsort(axis=1 )[:, :10] __magic_name__ = np.any(preds == actual[:, None] , axis=1 ) return float(matches.mean() ) @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCamelCase_ ( datasets.Metric ): """simple docstring""" def __A ( self : int ) -> Dict: if self.config_name not in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", "wiki-ner", ]: raise KeyError( "You should supply a configuration name selected in " "[\"wnli\", \"copa\", \"sna\", \"csqa\", \"wstp\", \"inltkh\", \"bbca\", " "\"cvit-mkb-clsr\", \"iitp-mr\", \"iitp-pr\", \"actsa-sc\", \"md\", " "\"wiki-ner\"]" ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Value("int64" ) if self.config_name != "cvit-mkb-clsr" else datasets.Sequence(datasets.Value("float32" ) ), "references": datasets.Value("int64" ) if self.config_name != "cvit-mkb-clsr" else datasets.Sequence(datasets.Value("float32" ) ), } ) , codebase_urls=[] , reference_urls=[] , format="numpy" if self.config_name != "cvit-mkb-clsr" else None , ) def __A ( self : int , _lowerCamelCase : Union[str, Any] , _lowerCamelCase : Dict ) -> int: if self.config_name == "cvit-mkb-clsr": return {"precision@10": precision_at_aa(_lowerCamelCase , _lowerCamelCase )} elif self.config_name in ["wiki-ner"]: return acc_and_fa(_lowerCamelCase , _lowerCamelCase ) elif self.config_name in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "iitp-mr", "iitp-pr", "actsa-sc", "md", ]: return {"accuracy": simple_accuracy(_lowerCamelCase , _lowerCamelCase )} else: raise KeyError( "You should supply a configuration name selected in " "[\"wnli\", \"copa\", \"sna\", \"csqa\", \"wstp\", \"inltkh\", \"bbca\", " "\"cvit-mkb-clsr\", \"iitp-mr\", \"iitp-pr\", \"actsa-sc\", \"md\", " "\"wiki-ner\"]" )
664
'''simple docstring''' import argparse import logging from collections import namedtuple import torch from model_bertabs import BertAbsSummarizer from models.model_builder import AbsSummarizer # The authors' implementation from transformers import BertTokenizer logging.basicConfig(level=logging.INFO) __magic_name__ : List[Any] =logging.getLogger(__name__) __magic_name__ : int ='Hello world! cécé herlolip' __magic_name__ : List[Any] =namedtuple( 'BertAbsConfig', [ 'temp_dir', 'large', 'use_bert_emb', 'finetune_bert', 'encoder', 'share_emb', 'max_pos', 'enc_layers', 'enc_hidden_size', 'enc_heads', 'enc_ff_size', 'enc_dropout', 'dec_layers', 'dec_hidden_size', 'dec_heads', 'dec_ff_size', 'dec_dropout', ], ) def __snake_case ( lowerCamelCase_ : Optional[int] , lowerCamelCase_ : Dict ): '''simple docstring''' __magic_name__ = BertAbsConfig( temp_dir="." , finetune_bert=lowerCamelCase_ , large=lowerCamelCase_ , share_emb=lowerCamelCase_ , use_bert_emb=lowerCamelCase_ , encoder="bert" , max_pos=512 , enc_layers=6 , enc_hidden_size=512 , enc_heads=8 , enc_ff_size=512 , enc_dropout=0.2 , dec_layers=6 , dec_hidden_size=768 , dec_heads=8 , dec_ff_size=2048 , dec_dropout=0.2 , ) __magic_name__ = torch.load(lowerCamelCase_ , lambda lowerCamelCase_ , lowerCamelCase_ : storage ) __magic_name__ = AbsSummarizer(lowerCamelCase_ , torch.device("cpu" ) , lowerCamelCase_ ) original.eval() __magic_name__ = BertAbsSummarizer(lowerCamelCase_ , torch.device("cpu" ) ) new_model.eval() # ------------------- # Convert the weights # ------------------- logging.info("convert the model" ) new_model.bert.load_state_dict(original.bert.state_dict() ) new_model.decoder.load_state_dict(original.decoder.state_dict() ) new_model.generator.load_state_dict(original.generator.state_dict() ) # ---------------------------------- # Make sure the outpus are identical # ---------------------------------- logging.info("Make sure that the models' outputs are identical" ) __magic_name__ = BertTokenizer.from_pretrained("bert-base-uncased" ) # prepare the model inputs __magic_name__ = tokenizer.encode("This is sample éàalj'-." ) encoder_input_ids.extend([tokenizer.pad_token_id] * (512 - len(lowerCamelCase_ )) ) __magic_name__ = torch.tensor(lowerCamelCase_ ).unsqueeze(0 ) __magic_name__ = tokenizer.encode("This is sample 3 éàalj'-." ) decoder_input_ids.extend([tokenizer.pad_token_id] * (512 - len(lowerCamelCase_ )) ) __magic_name__ = torch.tensor(lowerCamelCase_ ).unsqueeze(0 ) # failsafe to make sure the weights reset does not affect the # loaded weights. assert torch.max(torch.abs(original.generator[0].weight - new_model.generator[0].weight ) ) == 0 # forward pass __magic_name__ = encoder_input_ids __magic_name__ = decoder_input_ids __magic_name__ = __magic_name__ = None __magic_name__ = None __magic_name__ = __magic_name__ = None __magic_name__ = __magic_name__ = None __magic_name__ = None # The original model does not apply the geneator layer immediatly but rather in # the beam search (where it combines softmax + linear layer). Since we already # apply the softmax in our generation process we only apply the linear layer here. # We make sure that the outputs of the full stack are identical __magic_name__ = original(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )[0] __magic_name__ = original.generator(lowerCamelCase_ ) __magic_name__ = new_model( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )[0] __magic_name__ = new_model.generator(lowerCamelCase_ ) __magic_name__ = torch.max(torch.abs(output_converted_model - output_original_model ) ).item() print("Maximum absolute difference beween weights: {:.2f}".format(lowerCamelCase_ ) ) __magic_name__ = torch.max(torch.abs(output_converted_generator - output_original_generator ) ).item() print("Maximum absolute difference beween weights: {:.2f}".format(lowerCamelCase_ ) ) __magic_name__ = torch.allclose(lowerCamelCase_ , lowerCamelCase_ , atol=1e-3 ) if are_identical: logging.info("all weights are equal up to 1e-3" ) else: raise ValueError("the weights are different. The new model is likely different from the original one." ) # The model has been saved with torch.save(model) and this is bound to the exact # directory structure. We save the state_dict instead. logging.info("saving the model's state dictionary" ) torch.save( new_model.state_dict() , "./bertabs-finetuned-cnndm-extractive-abstractive-summarization/pytorch_model.bin" ) if __name__ == "__main__": __magic_name__ : Dict =argparse.ArgumentParser() parser.add_argument( '--bertabs_checkpoint_path', default=None, type=str, required=True, help='Path the official PyTorch dump.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.', ) __magic_name__ : Any =parser.parse_args() convert_bertabs_checkpoints( args.bertabs_checkpoint_path, args.pytorch_dump_folder_path, )
664
1
'''simple docstring''' import contextlib from multiprocessing import Pool, RLock from tqdm.auto import tqdm from ..utils import experimental, logging __magic_name__ : Dict =logging.get_logger(__name__) class UpperCamelCase_ : """simple docstring""" UpperCAmelCase__ : str = None @experimental def __snake_case ( lowerCamelCase_ : Dict , lowerCamelCase_ : List[str] , lowerCamelCase_ : Any , lowerCamelCase_ : List[str] , lowerCamelCase_ : str , lowerCamelCase_ : Optional[int] , lowerCamelCase_ : Union[str, Any] ): '''simple docstring''' if ParallelBackendConfig.backend_name is None: return _map_with_multiprocessing_pool( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) return _map_with_joblib(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) def __snake_case ( lowerCamelCase_ : Optional[int] , lowerCamelCase_ : Optional[int] , lowerCamelCase_ : Optional[int] , lowerCamelCase_ : List[Any] , lowerCamelCase_ : List[Any] , lowerCamelCase_ : Dict , lowerCamelCase_ : List[Any] ): '''simple docstring''' __magic_name__ = num_proc if num_proc <= len(lowerCamelCase_ ) else len(lowerCamelCase_ ) __magic_name__ = [] # We organize the splits ourselve (contiguous splits) for index in range(lowerCamelCase_ ): __magic_name__ = len(lowerCamelCase_ ) // num_proc __magic_name__ = len(lowerCamelCase_ ) % num_proc __magic_name__ = div * index + min(lowerCamelCase_ , lowerCamelCase_ ) __magic_name__ = start + div + (1 if index < mod else 0) split_kwds.append((function, iterable[start:end], types, index, disable_tqdm, desc) ) if len(lowerCamelCase_ ) != sum(len(i[1] ) for i in split_kwds ): raise ValueError( F'Error dividing inputs iterable among processes. ' F'Total number of objects {len(lowerCamelCase_ )}, ' F'length: {sum(len(i[1] ) for i in split_kwds )}' ) logger.info( F'Spawning {num_proc} processes for {len(lowerCamelCase_ )} objects in slices of {[len(i[1] ) for i in split_kwds]}' ) __magic_name__ , __magic_name__ = None, None if not disable_tqdm: __magic_name__ , __magic_name__ = (RLock(),), tqdm.set_lock with Pool(lowerCamelCase_ , initargs=lowerCamelCase_ , initializer=lowerCamelCase_ ) as pool: __magic_name__ = pool.map(lowerCamelCase_ , lowerCamelCase_ ) logger.info(F'Finished {num_proc} processes' ) __magic_name__ = [obj for proc_res in mapped for obj in proc_res] logger.info(F'Unpacked {len(lowerCamelCase_ )} objects' ) return mapped def __snake_case ( lowerCamelCase_ : Dict , lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : List[Any] , lowerCamelCase_ : Dict , lowerCamelCase_ : str , lowerCamelCase_ : int , lowerCamelCase_ : List[str] ): '''simple docstring''' import joblib with joblib.parallel_backend(ParallelBackendConfig.backend_name , n_jobs=lowerCamelCase_ ): return joblib.Parallel()( joblib.delayed(lowerCamelCase_ )((function, obj, types, None, True, None) ) for obj in iterable ) @experimental @contextlib.contextmanager def __snake_case ( lowerCamelCase_ : str ): '''simple docstring''' __magic_name__ = backend_name if backend_name == "spark": from joblibspark import register_spark register_spark() # TODO: call create_cache_and_write_probe if "download" in steps # TODO: raise NotImplementedError when Dataset.map etc is called try: yield finally: __magic_name__ = None
664
'''simple docstring''' import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.generation import DisjunctiveConstraint @require_torch class UpperCamelCase_ ( unittest.TestCase ): """simple docstring""" def __A ( self : List[str] ) -> str: # For consistency across different places the DisjunctiveConstraint is called, # dc.token_ids is a list of integers. It is also initialized only by integers. __magic_name__ = [[1, 2, 4], [1, 2, 3, 4]] __magic_name__ = DisjunctiveConstraint(_lowerCamelCase ) self.assertTrue(isinstance(dc.token_ids , _lowerCamelCase ) ) with self.assertRaises(_lowerCamelCase ): DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]] ) ) with self.assertRaises(_lowerCamelCase ): DisjunctiveConstraint([torch.LongTensor([1, 2, 4] ), torch.LongTensor([1, 2, 3, 4, 5] )] ) def __A ( self : List[Any] ) -> str: # We can't have constraints that are complete subsets of another. This leads to a preverse # interpretation of "constraint fulfillment": does generating [1,2,3] fulfill the constraint? # It would mean that it generated [1,2] which fulfills it, but it's in the middle of potentially # fulfilling [1,2,3,4]. If we believe that [1,2,3] does fulfill the constraint, then the algorithm # will necessarily never reach [1,2,3,4], giving users a false sense of control (better to just not allow it). __magic_name__ = [[1, 2], [1, 2, 3, 4]] with self.assertRaises(_lowerCamelCase ): DisjunctiveConstraint(_lowerCamelCase ) # fails here def __A ( self : List[Any] ) -> int: __magic_name__ = [[1, 2, 3], [1, 2, 4]] __magic_name__ = DisjunctiveConstraint(_lowerCamelCase ) __magic_name__ , __magic_name__ , __magic_name__ = dc.update(1 ) __magic_name__ = stepped is True and completed is False and reset is False self.assertTrue(_lowerCamelCase ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) __magic_name__ , __magic_name__ , __magic_name__ = dc.update(2 ) __magic_name__ = stepped is True and completed is False and reset is False self.assertTrue(_lowerCamelCase ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) __magic_name__ , __magic_name__ , __magic_name__ = dc.update(3 ) __magic_name__ = stepped is True and completed is True and reset is False self.assertTrue(_lowerCamelCase ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 3] ) def __A ( self : Any ) -> Union[str, Any]: __magic_name__ = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]] __magic_name__ = DisjunctiveConstraint(_lowerCamelCase ) __magic_name__ , __magic_name__ , __magic_name__ = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) __magic_name__ , __magic_name__ , __magic_name__ = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) __magic_name__ , __magic_name__ , __magic_name__ = dc.update(4 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2, 4] ) __magic_name__ , __magic_name__ , __magic_name__ = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 4, 5] ) dc.reset() __magic_name__ , __magic_name__ , __magic_name__ = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 3 ) self.assertTrue(dc.current_seq == [1] ) __magic_name__ , __magic_name__ , __magic_name__ = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 2 ) self.assertTrue(dc.current_seq == [1, 2] ) __magic_name__ , __magic_name__ , __magic_name__ = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.remaining() == 0 ) self.assertTrue(dc.current_seq == [1, 2, 5] )
664
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) __magic_name__ : Optional[int] ={ 'configuration_mobilebert': [ 'MOBILEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MobileBertConfig', 'MobileBertOnnxConfig', ], 'tokenization_mobilebert': ['MobileBertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ : Dict =['MobileBertTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ : Tuple =[ 'MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'MobileBertForMaskedLM', 'MobileBertForMultipleChoice', 'MobileBertForNextSentencePrediction', 'MobileBertForPreTraining', 'MobileBertForQuestionAnswering', 'MobileBertForSequenceClassification', 'MobileBertForTokenClassification', 'MobileBertLayer', 'MobileBertModel', 'MobileBertPreTrainedModel', 'load_tf_weights_in_mobilebert', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ : Tuple =[ 'TF_MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFMobileBertForMaskedLM', 'TFMobileBertForMultipleChoice', 'TFMobileBertForNextSentencePrediction', 'TFMobileBertForPreTraining', 'TFMobileBertForQuestionAnswering', 'TFMobileBertForSequenceClassification', 'TFMobileBertForTokenClassification', 'TFMobileBertMainLayer', 'TFMobileBertModel', 'TFMobileBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_mobilebert import ( MOBILEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileBertConfig, MobileBertOnnxConfig, ) from .tokenization_mobilebert import MobileBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mobilebert_fast import MobileBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mobilebert import ( MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, MobileBertForMaskedLM, MobileBertForMultipleChoice, MobileBertForNextSentencePrediction, MobileBertForPreTraining, MobileBertForQuestionAnswering, MobileBertForSequenceClassification, MobileBertForTokenClassification, MobileBertLayer, MobileBertModel, MobileBertPreTrainedModel, load_tf_weights_in_mobilebert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mobilebert import ( TF_MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFMobileBertForMaskedLM, TFMobileBertForMultipleChoice, TFMobileBertForNextSentencePrediction, TFMobileBertForPreTraining, TFMobileBertForQuestionAnswering, TFMobileBertForSequenceClassification, TFMobileBertForTokenClassification, TFMobileBertMainLayer, TFMobileBertModel, TFMobileBertPreTrainedModel, ) else: import sys __magic_name__ : List[str] =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
664
'''simple docstring''' import json import os import shutil import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import AutoConfig, BertConfig, GPTaConfig from transformers.configuration_utils import PretrainedConfig from transformers.testing_utils import TOKEN, USER, is_staging_test sys.path.append(str(Path(__file__).parent.parent / 'utils')) from test_module.custom_configuration import CustomConfig # noqa E402 __magic_name__ : Dict ={ 'return_dict': False, 'output_hidden_states': True, 'output_attentions': True, 'torchscript': True, 'torch_dtype': 'float16', 'use_bfloat16': True, 'tf_legacy_loss': True, 'pruned_heads': {'a': 1}, 'tie_word_embeddings': False, 'is_decoder': True, 'cross_attention_hidden_size': 1_28, 'add_cross_attention': True, 'tie_encoder_decoder': True, 'max_length': 50, 'min_length': 3, 'do_sample': True, 'early_stopping': True, 'num_beams': 3, 'num_beam_groups': 3, 'diversity_penalty': 0.5, 'temperature': 2.0, 'top_k': 10, 'top_p': 0.7, 'typical_p': 0.2, 'repetition_penalty': 0.8, 'length_penalty': 0.8, 'no_repeat_ngram_size': 5, 'encoder_no_repeat_ngram_size': 5, 'bad_words_ids': [1, 2, 3], 'num_return_sequences': 3, 'chunk_size_feed_forward': 5, 'output_scores': True, 'return_dict_in_generate': True, 'forced_bos_token_id': 2, 'forced_eos_token_id': 3, 'remove_invalid_values': True, 'architectures': ['BertModel'], 'finetuning_task': 'translation', 'id2label': {0: 'label'}, 'label2id': {'label': '0'}, 'tokenizer_class': 'BertTokenizerFast', 'prefix': 'prefix', 'bos_token_id': 6, 'pad_token_id': 7, 'eos_token_id': 8, 'sep_token_id': 9, 'decoder_start_token_id': 10, 'exponential_decay_length_penalty': (5, 1.0_1), 'suppress_tokens': [0, 1], 'begin_suppress_tokens': 2, 'task_specific_params': {'translation': 'some_params'}, 'problem_type': 'regression', } @is_staging_test class UpperCamelCase_ ( unittest.TestCase ): """simple docstring""" @classmethod def __A ( cls : Any ) -> Union[str, Any]: __magic_name__ = TOKEN HfFolder.save_token(_lowerCamelCase ) @classmethod def __A ( cls : Any ) -> Tuple: try: delete_repo(token=cls._token , repo_id="test-config" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="valid_org/test-config-org" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="test-dynamic-config" ) except HTTPError: pass def __A ( self : Optional[Any] ) -> Dict: __magic_name__ = BertConfig( vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 ) config.push_to_hub("test-config" , use_auth_token=self._token ) __magic_name__ = BertConfig.from_pretrained(f'{USER}/test-config' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(_lowerCamelCase , getattr(_lowerCamelCase , _lowerCamelCase ) ) # Reset repo delete_repo(token=self._token , repo_id="test-config" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(_lowerCamelCase , repo_id="test-config" , push_to_hub=_lowerCamelCase , use_auth_token=self._token ) __magic_name__ = BertConfig.from_pretrained(f'{USER}/test-config' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(_lowerCamelCase , getattr(_lowerCamelCase , _lowerCamelCase ) ) def __A ( self : str ) -> Optional[int]: __magic_name__ = BertConfig( vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 ) config.push_to_hub("valid_org/test-config-org" , use_auth_token=self._token ) __magic_name__ = BertConfig.from_pretrained("valid_org/test-config-org" ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(_lowerCamelCase , getattr(_lowerCamelCase , _lowerCamelCase ) ) # Reset repo delete_repo(token=self._token , repo_id="valid_org/test-config-org" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( _lowerCamelCase , repo_id="valid_org/test-config-org" , push_to_hub=_lowerCamelCase , use_auth_token=self._token ) __magic_name__ = BertConfig.from_pretrained("valid_org/test-config-org" ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(_lowerCamelCase , getattr(_lowerCamelCase , _lowerCamelCase ) ) def __A ( self : Optional[int] ) -> Union[str, Any]: CustomConfig.register_for_auto_class() __magic_name__ = CustomConfig(attribute=42 ) config.push_to_hub("test-dynamic-config" , use_auth_token=self._token ) # This has added the proper auto_map field to the config self.assertDictEqual(config.auto_map , {"AutoConfig": "custom_configuration.CustomConfig"} ) __magic_name__ = AutoConfig.from_pretrained(f'{USER}/test-dynamic-config' , trust_remote_code=_lowerCamelCase ) # Can't make an isinstance check because the new_config is from the FakeConfig class of a dynamic module self.assertEqual(new_config.__class__.__name__ , "CustomConfig" ) self.assertEqual(new_config.attribute , 42 ) class UpperCamelCase_ ( unittest.TestCase ): """simple docstring""" def __A ( self : Optional[int] ) -> Optional[Any]: __magic_name__ = GPTaConfig() # attempt to modify each of int/float/bool/str config records and verify they were updated __magic_name__ = c.n_embd + 1 # int __magic_name__ = c.resid_pdrop + 1.0 # float __magic_name__ = not c.scale_attn_weights # bool __magic_name__ = c.summary_type + "foo" # str c.update_from_string( f'n_embd={n_embd},resid_pdrop={resid_pdrop},scale_attn_weights={scale_attn_weights},summary_type={summary_type}' ) self.assertEqual(_lowerCamelCase , c.n_embd , "mismatch for key: n_embd" ) self.assertEqual(_lowerCamelCase , c.resid_pdrop , "mismatch for key: resid_pdrop" ) self.assertEqual(_lowerCamelCase , c.scale_attn_weights , "mismatch for key: scale_attn_weights" ) self.assertEqual(_lowerCamelCase , c.summary_type , "mismatch for key: summary_type" ) def __A ( self : List[Any] ) -> Union[str, Any]: __magic_name__ = PretrainedConfig() __magic_name__ = [key for key in base_config.__dict__ if key not in config_common_kwargs] # If this part of the test fails, you have arguments to addin config_common_kwargs above. self.assertListEqual( _lowerCamelCase , ["is_encoder_decoder", "_name_or_path", "_commit_hash", "transformers_version"] ) __magic_name__ = [key for key, value in config_common_kwargs.items() if value == getattr(_lowerCamelCase , _lowerCamelCase )] if len(_lowerCamelCase ) > 0: raise ValueError( "The following keys are set with the default values in" " `test_configuration_common.config_common_kwargs` pick another value for them:" f' {", ".join(_lowerCamelCase )}.' ) def __A ( self : List[Any] ) -> List[Any]: with self.assertRaises(_lowerCamelCase ): # config is in subfolder, the following should not work without specifying the subfolder __magic_name__ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert-subfolder" ) __magic_name__ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert-subfolder" , subfolder="bert" ) self.assertIsNotNone(_lowerCamelCase ) def __A ( self : Tuple ) -> int: # A mock response for an HTTP head request to emulate server down __magic_name__ = mock.Mock() __magic_name__ = 5_00 __magic_name__ = {} __magic_name__ = HTTPError __magic_name__ = {} # Download this model to make sure it's in the cache. __magic_name__ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert" ) # Under the mock environment we get a 500 error when trying to reach the model. with mock.patch("requests.Session.request" , return_value=_lowerCamelCase ) as mock_head: __magic_name__ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert" ) # This check we did call the fake head request mock_head.assert_called() def __A ( self : Union[str, Any] ) -> Dict: # This test is for deprecated behavior and can be removed in v5 __magic_name__ = BertConfig.from_pretrained( "https://huggingface.co/hf-internal-testing/tiny-random-bert/resolve/main/config.json" ) def __A ( self : Dict ) -> Optional[int]: __magic_name__ = AutoConfig.from_pretrained("bert-base-cased" ) __magic_name__ = ["config.4.0.0.json"] with tempfile.TemporaryDirectory() as tmp_dir: configuration.save_pretrained(_lowerCamelCase ) __magic_name__ = 2 json.dump(configuration.to_dict() , open(os.path.join(_lowerCamelCase , "config.4.0.0.json" ) , "w" ) ) # This should pick the new configuration file as the version of Transformers is > 4.0.0 __magic_name__ = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertEqual(new_configuration.hidden_size , 2 ) # Will need to be adjusted if we reach v42 and this test is still here. # Should pick the old configuration file as the version of Transformers is < 4.42.0 __magic_name__ = ["config.42.0.0.json"] __magic_name__ = 7_68 configuration.save_pretrained(_lowerCamelCase ) shutil.move(os.path.join(_lowerCamelCase , "config.4.0.0.json" ) , os.path.join(_lowerCamelCase , "config.42.0.0.json" ) ) __magic_name__ = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertEqual(new_configuration.hidden_size , 7_68 ) def __A ( self : Optional[int] ) -> str: # This repo has two configuration files, one for v4.0.0 and above with a different hidden size. __magic_name__ = "hf-internal-testing/test-two-configs" import transformers as new_transformers __magic_name__ = "v4.0.0" __magic_name__ , __magic_name__ = new_transformers.models.auto.AutoConfig.from_pretrained( _lowerCamelCase , return_unused_kwargs=_lowerCamelCase ) self.assertEqual(new_configuration.hidden_size , 2 ) # This checks `_configuration_file` ia not kept in the kwargs by mistake. self.assertDictEqual(_lowerCamelCase , {} ) # Testing an older version by monkey-patching the version in the module it's used. import transformers as old_transformers __magic_name__ = "v3.0.0" __magic_name__ = old_transformers.models.auto.AutoConfig.from_pretrained(_lowerCamelCase ) self.assertEqual(old_configuration.hidden_size , 7_68 )
664
1
import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ViTImageProcessor, ViTMSNConfig, ViTMSNModel from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD torch.set_grad_enabled(False) def __lowercase ( snake_case, snake_case=False ): """simple docstring""" __magic_name__ :List[Any] = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f'''module.blocks.{i}.norm1.weight''', f'''vit.encoder.layer.{i}.layernorm_before.weight''') ) rename_keys.append((f'''module.blocks.{i}.norm1.bias''', f'''vit.encoder.layer.{i}.layernorm_before.bias''') ) rename_keys.append( (f'''module.blocks.{i}.attn.proj.weight''', f'''vit.encoder.layer.{i}.attention.output.dense.weight''') ) rename_keys.append((f'''module.blocks.{i}.attn.proj.bias''', f'''vit.encoder.layer.{i}.attention.output.dense.bias''') ) rename_keys.append((f'''module.blocks.{i}.norm2.weight''', f'''vit.encoder.layer.{i}.layernorm_after.weight''') ) rename_keys.append((f'''module.blocks.{i}.norm2.bias''', f'''vit.encoder.layer.{i}.layernorm_after.bias''') ) rename_keys.append((f'''module.blocks.{i}.mlp.fc1.weight''', f'''vit.encoder.layer.{i}.intermediate.dense.weight''') ) rename_keys.append((f'''module.blocks.{i}.mlp.fc1.bias''', f'''vit.encoder.layer.{i}.intermediate.dense.bias''') ) rename_keys.append((f'''module.blocks.{i}.mlp.fc2.weight''', f'''vit.encoder.layer.{i}.output.dense.weight''') ) rename_keys.append((f'''module.blocks.{i}.mlp.fc2.bias''', f'''vit.encoder.layer.{i}.output.dense.bias''') ) # projection layer + position embeddings rename_keys.extend( [ ('''module.cls_token''', '''vit.embeddings.cls_token'''), ('''module.patch_embed.proj.weight''', '''vit.embeddings.patch_embeddings.projection.weight'''), ('''module.patch_embed.proj.bias''', '''vit.embeddings.patch_embeddings.projection.bias'''), ('''module.pos_embed''', '''vit.embeddings.position_embeddings'''), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ('''module.norm.weight''', '''layernorm.weight'''), ('''module.norm.bias''', '''layernorm.bias'''), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" __magic_name__ :List[str] = [(pair[0], pair[1][4:]) if pair[1].startswith('''vit''' ) else pair for pair in rename_keys] else: # layernorm + classification head rename_keys.extend( [ ('''norm.weight''', '''vit.layernorm.weight'''), ('''norm.bias''', '''vit.layernorm.bias'''), ('''head.weight''', '''classifier.weight'''), ('''head.bias''', '''classifier.bias'''), ] ) return rename_keys def __lowercase ( snake_case, snake_case, snake_case=False ): """simple docstring""" for i in range(config.num_hidden_layers ): if base_model: __magic_name__ :List[Any] = '''''' else: __magic_name__ :Any = '''vit.''' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) __magic_name__ :Any = state_dict.pop(f'''module.blocks.{i}.attn.qkv.weight''' ) __magic_name__ :Dict = state_dict.pop(f'''module.blocks.{i}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict __magic_name__ :Union[str, Any] = in_proj_weight[ : config.hidden_size, : ] __magic_name__ :Dict = in_proj_bias[: config.hidden_size] __magic_name__ :Optional[Any] = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] __magic_name__ :Optional[Any] = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] __magic_name__ :List[str] = in_proj_weight[ -config.hidden_size :, : ] __magic_name__ :List[str] = in_proj_bias[-config.hidden_size :] def __lowercase ( snake_case ): """simple docstring""" __magic_name__ :Any = ['''head.weight''', '''head.bias'''] for k in ignore_keys: state_dict.pop(snake_case, snake_case ) def __lowercase ( snake_case ): """simple docstring""" __magic_name__ :int = [ '''module.fc.fc1.weight''', '''module.fc.fc1.bias''', '''module.fc.bn1.weight''', '''module.fc.bn1.bias''', '''module.fc.bn1.running_mean''', '''module.fc.bn1.running_var''', '''module.fc.bn1.num_batches_tracked''', '''module.fc.fc2.weight''', '''module.fc.fc2.bias''', '''module.fc.bn2.weight''', '''module.fc.bn2.bias''', '''module.fc.bn2.running_mean''', '''module.fc.bn2.running_var''', '''module.fc.bn2.num_batches_tracked''', '''module.fc.fc3.weight''', '''module.fc.fc3.bias''', ] for k in ignore_keys: state_dict.pop(snake_case, snake_case ) def __lowercase ( snake_case, snake_case, snake_case ): """simple docstring""" __magic_name__ :Any = dct.pop(snake_case ) __magic_name__ :Tuple = val def __lowercase ( snake_case, snake_case ): """simple docstring""" __magic_name__ :Optional[Any] = ViTMSNConfig() __magic_name__ :Optional[int] = 1_0_0_0 __magic_name__ :Optional[int] = '''datasets/huggingface/label-files''' __magic_name__ :Optional[Any] = '''imagenet-1k-id2label.json''' __magic_name__ :List[str] = json.load(open(hf_hub_download(snake_case, snake_case ), '''r''' ) ) __magic_name__ :Union[str, Any] = {int(snake_case ): v for k, v in idalabel.items()} __magic_name__ :List[str] = idalabel __magic_name__ :List[Any] = {v: k for k, v in idalabel.items()} if "s16" in checkpoint_url: __magic_name__ :Any = 3_8_4 __magic_name__ :Optional[Any] = 1_5_3_6 __magic_name__ :List[Any] = 6 elif "l16" in checkpoint_url: __magic_name__ :Optional[Any] = 1_0_2_4 __magic_name__ :List[Any] = 4_0_9_6 __magic_name__ :Optional[int] = 2_4 __magic_name__ :str = 1_6 __magic_name__ :Dict = 0.1 elif "b4" in checkpoint_url: __magic_name__ :int = 4 elif "l7" in checkpoint_url: __magic_name__ :Dict = 7 __magic_name__ :List[Any] = 1_0_2_4 __magic_name__ :Optional[Any] = 4_0_9_6 __magic_name__ :Union[str, Any] = 2_4 __magic_name__ :Dict = 1_6 __magic_name__ :List[Any] = 0.1 __magic_name__ :List[Any] = ViTMSNModel(snake_case ) __magic_name__ :Union[str, Any] = torch.hub.load_state_dict_from_url(snake_case, map_location='''cpu''' )['''target_encoder'''] __magic_name__ :Any = ViTImageProcessor(size=config.image_size ) remove_projection_head(snake_case ) __magic_name__ :str = create_rename_keys(snake_case, base_model=snake_case ) for src, dest in rename_keys: rename_key(snake_case, snake_case, snake_case ) read_in_q_k_v(snake_case, snake_case, base_model=snake_case ) model.load_state_dict(snake_case ) model.eval() __magic_name__ :Optional[Any] = '''http://images.cocodataset.org/val2017/000000039769.jpg''' __magic_name__ :Optional[Any] = Image.open(requests.get(snake_case, stream=snake_case ).raw ) __magic_name__ :Union[str, Any] = ViTImageProcessor( size=config.image_size, image_mean=snake_case, image_std=snake_case ) __magic_name__ :List[str] = image_processor(images=snake_case, return_tensors='''pt''' ) # forward pass torch.manual_seed(2 ) __magic_name__ :Optional[Any] = model(**snake_case ) __magic_name__ :Optional[Any] = outputs.last_hidden_state # The following Colab Notebook was used to generate these outputs: # https://colab.research.google.com/gist/sayakpaul/3672419a04f5997827503fd84079bdd1/scratchpad.ipynb if "s16" in checkpoint_url: __magic_name__ :Optional[int] = torch.tensor([[-1.0915, -1.4876, -1.1809]] ) elif "b16" in checkpoint_url: __magic_name__ :int = torch.tensor([[14.2889, -18.9045, 11.7281]] ) elif "l16" in checkpoint_url: __magic_name__ :Dict = torch.tensor([[41.5028, -22.8681, 45.6475]] ) elif "b4" in checkpoint_url: __magic_name__ :int = torch.tensor([[-4.3868, 5.2932, -0.4137]] ) else: __magic_name__ :int = torch.tensor([[-0.1792, -0.6465, 2.4263]] ) # verify logits assert torch.allclose(last_hidden_state[:, 0, :3], snake_case, atol=1E-4 ) print(f'''Saving model to {pytorch_dump_folder_path}''' ) model.save_pretrained(snake_case ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(snake_case ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : List[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( """--checkpoint_url""", default="""https://dl.fbaipublicfiles.com/msn/vits16_800ep.pth.tar""", type=str, help="""URL of the checkpoint you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) SCREAMING_SNAKE_CASE__ : Optional[int] = parser.parse_args() convert_vit_msn_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
0
'''simple docstring''' import unittest import numpy as np from transformers.file_utils import is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_vision from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import DPTImageProcessor class UpperCamelCase_ ( unittest.TestCase ): """simple docstring""" def __init__( self : str , _lowerCamelCase : str , _lowerCamelCase : Optional[Any]=7 , _lowerCamelCase : Optional[int]=3 , _lowerCamelCase : List[Any]=18 , _lowerCamelCase : Union[str, Any]=30 , _lowerCamelCase : Tuple=4_00 , _lowerCamelCase : Union[str, Any]=True , _lowerCamelCase : Optional[Any]=None , _lowerCamelCase : int=True , _lowerCamelCase : Dict=[0.5, 0.5, 0.5] , _lowerCamelCase : Dict=[0.5, 0.5, 0.5] , ) -> Dict: __magic_name__ = size if size is not None else {"height": 18, "width": 18} __magic_name__ = parent __magic_name__ = batch_size __magic_name__ = num_channels __magic_name__ = image_size __magic_name__ = min_resolution __magic_name__ = max_resolution __magic_name__ = do_resize __magic_name__ = size __magic_name__ = do_normalize __magic_name__ = image_mean __magic_name__ = image_std def __A ( self : int ) -> List[str]: return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, } @require_torch @require_vision class UpperCamelCase_ ( A , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Union[str, Any] = DPTImageProcessor if is_vision_available() else None def __A ( self : Dict ) -> Any: __magic_name__ = DPTImageProcessingTester(self ) @property def __A ( self : str ) -> str: return self.image_processor_tester.prepare_image_processor_dict() def __A ( self : Tuple ) -> List[str]: __magic_name__ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCamelCase , "image_mean" ) ) self.assertTrue(hasattr(_lowerCamelCase , "image_std" ) ) self.assertTrue(hasattr(_lowerCamelCase , "do_normalize" ) ) self.assertTrue(hasattr(_lowerCamelCase , "do_resize" ) ) self.assertTrue(hasattr(_lowerCamelCase , "size" ) ) def __A ( self : List[str] ) -> List[Any]: __magic_name__ = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"height": 18, "width": 18} ) __magic_name__ = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {"height": 42, "width": 42} ) def __A ( self : Union[str, Any] ) -> List[str]: # Initialize image_processing __magic_name__ = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __magic_name__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , Image.Image ) # Test not batched input __magic_name__ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) # Test batched __magic_name__ = image_processing(_lowerCamelCase , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) def __A ( self : Dict ) -> Optional[Any]: # Initialize image_processing __magic_name__ = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __magic_name__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , numpify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , np.ndarray ) # Test not batched input __magic_name__ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) # Test batched __magic_name__ = image_processing(_lowerCamelCase , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) def __A ( self : Optional[int] ) -> Dict: # Initialize image_processing __magic_name__ = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __magic_name__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , torch.Tensor ) # Test not batched input __magic_name__ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) # Test batched __magic_name__ = image_processing(_lowerCamelCase , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , )
664
0
import logging import os import sys from dataclasses import dataclass, field from importlib import import_module from typing import Dict, List, Optional, Tuple import numpy as np from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score from torch import nn from utils_ner import Split, TokenClassificationDataset, TokenClassificationTask import transformers from transformers import ( AutoConfig, AutoModelForTokenClassification, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process __snake_case = logging.getLogger(__name__) @dataclass class __lowerCamelCase : _lowercase = field( metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""} ) _lowercase = field( default=_a , metadata={"""help""": """Pretrained config name or path if not the same as model_name"""} ) _lowercase = field( default="""NER""" , metadata={"""help""": """Task type to fine tune in training (e.g. NER, POS, etc)"""} ) _lowercase = field( default=_a , metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""} ) _lowercase = field(default=_a , metadata={"""help""": """Set this flag to use fast tokenization."""} ) # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script, # or just modify its tokenizer_config.json. _lowercase = field( default=_a , metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""} , ) @dataclass class __lowerCamelCase : _lowercase = field( metadata={"""help""": """The input data dir. Should contain the .txt files for a CoNLL-2003-formatted task."""} ) _lowercase = field( default=_a , metadata={"""help""": """Path to a file containing all labels. If not specified, CoNLL-2003 labels are used."""} , ) _lowercase = 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.""" ) } , ) _lowercase = field( default=_a , metadata={"""help""": """Overwrite the cached training and evaluation sets"""} ) def _A ( ) -> str: """simple docstring""" __UpperCamelCase = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('.json' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. __UpperCamelCase, __UpperCamelCase, __UpperCamelCase = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: __UpperCamelCase, __UpperCamelCase, __UpperCamelCase = parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( f'''Output directory ({training_args.output_dir}) already exists and is not empty. Use''' ' --overwrite_output_dir to overcome.' ) __UpperCamelCase = import_module('tasks' ) try: __UpperCamelCase = getattr(_lowercase , model_args.task_type ) __UpperCamelCase = token_classification_task_clazz() except AttributeError: raise ValueError( f'''Task {model_args.task_type} needs to be defined as a TokenClassificationTask subclass in {module}. ''' f'''Available tasks classes are: {TokenClassificationTask.__subclasses__()}''' ) # Setup logging logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' , datefmt='%m/%d/%Y %H:%M:%S' , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( 'Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s' , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.local_rank != -1 ) , training_args.fpaa , ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info('Training/evaluation parameters %s' , _lowercase ) # Set seed set_seed(training_args.seed ) # Prepare CONLL-2003 task __UpperCamelCase = token_classification_task.get_labels(data_args.labels ) __UpperCamelCase = dict(enumerate(_lowercase ) ) __UpperCamelCase = len(_lowercase ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. __UpperCamelCase = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=_lowercase , idalabel=_lowercase , labelaid={label: i for i, label in enumerate(_lowercase )} , cache_dir=model_args.cache_dir , ) __UpperCamelCase = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast , ) __UpperCamelCase = AutoModelForTokenClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool('.ckpt' in model_args.model_name_or_path ) , config=_lowercase , cache_dir=model_args.cache_dir , ) # Get datasets __UpperCamelCase = ( TokenClassificationDataset( token_classification_task=_lowercase , data_dir=data_args.data_dir , tokenizer=_lowercase , labels=_lowercase , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.train , ) if training_args.do_train else None ) __UpperCamelCase = ( TokenClassificationDataset( token_classification_task=_lowercase , data_dir=data_args.data_dir , tokenizer=_lowercase , labels=_lowercase , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.dev , ) if training_args.do_eval else None ) def align_predictions(_lowercase , _lowercase ) -> Tuple[List[int], List[int]]: __UpperCamelCase = np.argmax(_lowercase , axis=2 ) __UpperCamelCase, __UpperCamelCase = preds.shape __UpperCamelCase = [[] for _ in range(_lowercase )] __UpperCamelCase = [[] for _ in range(_lowercase )] for i in range(_lowercase ): for j in range(_lowercase ): if label_ids[i, j] != nn.CrossEntropyLoss().ignore_index: out_label_list[i].append(label_map[label_ids[i][j]] ) preds_list[i].append(label_map[preds[i][j]] ) return preds_list, out_label_list def compute_metrics(_lowercase ) -> Dict: __UpperCamelCase, __UpperCamelCase = align_predictions(p.predictions , p.label_ids ) return { "accuracy_score": accuracy_score(_lowercase , _lowercase ), "precision": precision_score(_lowercase , _lowercase ), "recall": recall_score(_lowercase , _lowercase ), "f1": fa_score(_lowercase , _lowercase ), } # Data collator __UpperCamelCase = DataCollatorWithPadding(_lowercase , pad_to_multiple_of=8 ) if training_args.fpaa else None # Initialize our Trainer __UpperCamelCase = Trainer( model=_lowercase , args=_lowercase , train_dataset=_lowercase , eval_dataset=_lowercase , compute_metrics=_lowercase , data_collator=_lowercase , ) # Training if training_args.do_train: trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_process_zero(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation __UpperCamelCase = {} if training_args.do_eval: logger.info('*** Evaluate ***' ) __UpperCamelCase = trainer.evaluate() __UpperCamelCase = os.path.join(training_args.output_dir , 'eval_results.txt' ) if trainer.is_world_process_zero(): with open(_lowercase , 'w' ) as writer: logger.info('***** Eval results *****' ) for key, value in result.items(): logger.info(' %s = %s' , _lowercase , _lowercase ) writer.write('%s = %s\n' % (key, value) ) results.update(_lowercase ) # Predict if training_args.do_predict: __UpperCamelCase = TokenClassificationDataset( token_classification_task=_lowercase , data_dir=data_args.data_dir , tokenizer=_lowercase , labels=_lowercase , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.test , ) __UpperCamelCase, __UpperCamelCase, __UpperCamelCase = trainer.predict(_lowercase ) __UpperCamelCase, __UpperCamelCase = align_predictions(_lowercase , _lowercase ) __UpperCamelCase = os.path.join(training_args.output_dir , 'test_results.txt' ) if trainer.is_world_process_zero(): with open(_lowercase , 'w' ) as writer: for key, value in metrics.items(): logger.info(' %s = %s' , _lowercase , _lowercase ) writer.write('%s = %s\n' % (key, value) ) # Save predictions __UpperCamelCase = os.path.join(training_args.output_dir , 'test_predictions.txt' ) if trainer.is_world_process_zero(): with open(_lowercase , 'w' ) as writer: with open(os.path.join(data_args.data_dir , 'test.txt' ) , 'r' ) as f: token_classification_task.write_predictions_to_file(_lowercase , _lowercase , _lowercase ) return results def _A ( _lowercase ) -> Dict: """simple docstring""" main() if __name__ == "__main__": main()
1
'''simple docstring''' import numpy class UpperCamelCase_ : """simple docstring""" def __init__( self : Union[str, Any] , _lowerCamelCase : numpy.ndarray , _lowerCamelCase : numpy.ndarray ) -> None: __magic_name__ = input_array # Random initial weights are assigned where first argument is the # number of nodes in previous layer and second argument is the # number of nodes in the next layer. # Random initial weights are assigned. # self.input_array.shape[1] is used to represent number of nodes in input layer. # First hidden layer consists of 4 nodes. __magic_name__ = numpy.random.rand( self.input_array.shape[1] , 4 ) # Random initial values for the first hidden layer. # First hidden layer has 4 nodes. # Second hidden layer has 3 nodes. __magic_name__ = numpy.random.rand( 4 , 3 ) # Random initial values for the second hidden layer. # Second hidden layer has 3 nodes. # Output layer has 1 node. __magic_name__ = numpy.random.rand(3 , 1 ) # Real output values provided. __magic_name__ = output_array # Predicted output values by the neural network. # Predicted_output array initially consists of zeroes. __magic_name__ = numpy.zeros(output_array.shape ) def __A ( self : int ) -> numpy.ndarray: __magic_name__ = sigmoid( numpy.dot(self.input_array , self.input_layer_and_first_hidden_layer_weights ) ) # layer_between_first_hidden_layer_and_second_hidden_layer is the layer # connecting the first hidden set of nodes with the second hidden set of nodes. __magic_name__ = sigmoid( numpy.dot( self.layer_between_input_and_first_hidden_layer , self.first_hidden_layer_and_second_hidden_layer_weights , ) ) # layer_between_second_hidden_layer_and_output is the layer connecting # second hidden layer with the output node. __magic_name__ = sigmoid( numpy.dot( self.layer_between_first_hidden_layer_and_second_hidden_layer , self.second_hidden_layer_and_output_layer_weights , ) ) return self.layer_between_second_hidden_layer_and_output def __A ( self : Dict ) -> None: __magic_name__ = numpy.dot( self.layer_between_first_hidden_layer_and_second_hidden_layer.T , 2 * (self.output_array - self.predicted_output) * sigmoid_derivative(self.predicted_output ) , ) __magic_name__ = numpy.dot( self.layer_between_input_and_first_hidden_layer.T , numpy.dot( 2 * (self.output_array - self.predicted_output) * sigmoid_derivative(self.predicted_output ) , self.second_hidden_layer_and_output_layer_weights.T , ) * sigmoid_derivative( self.layer_between_first_hidden_layer_and_second_hidden_layer ) , ) __magic_name__ = numpy.dot( self.input_array.T , numpy.dot( numpy.dot( 2 * (self.output_array - self.predicted_output) * sigmoid_derivative(self.predicted_output ) , self.second_hidden_layer_and_output_layer_weights.T , ) * sigmoid_derivative( self.layer_between_first_hidden_layer_and_second_hidden_layer ) , self.first_hidden_layer_and_second_hidden_layer_weights.T , ) * sigmoid_derivative(self.layer_between_input_and_first_hidden_layer ) , ) self.input_layer_and_first_hidden_layer_weights += ( updated_input_layer_and_first_hidden_layer_weights ) self.first_hidden_layer_and_second_hidden_layer_weights += ( updated_first_hidden_layer_and_second_hidden_layer_weights ) self.second_hidden_layer_and_output_layer_weights += ( updated_second_hidden_layer_and_output_layer_weights ) def __A ( self : Optional[int] , _lowerCamelCase : numpy.ndarray , _lowerCamelCase : int , _lowerCamelCase : bool ) -> None: for iteration in range(1 , iterations + 1 ): __magic_name__ = self.feedforward() self.back_propagation() if give_loss: __magic_name__ = numpy.mean(numpy.square(output - self.feedforward() ) ) print(f'Iteration {iteration} Loss: {loss}' ) def __A ( self : Tuple , _lowerCamelCase : numpy.ndarray ) -> int: __magic_name__ = input_arr __magic_name__ = sigmoid( numpy.dot(self.array , self.input_layer_and_first_hidden_layer_weights ) ) __magic_name__ = sigmoid( numpy.dot( self.layer_between_input_and_first_hidden_layer , self.first_hidden_layer_and_second_hidden_layer_weights , ) ) __magic_name__ = sigmoid( numpy.dot( self.layer_between_first_hidden_layer_and_second_hidden_layer , self.second_hidden_layer_and_output_layer_weights , ) ) return int(self.layer_between_second_hidden_layer_and_output > 0.6 ) def __snake_case ( lowerCamelCase_ : numpy.ndarray ): '''simple docstring''' return 1 / (1 + numpy.exp(-value )) def __snake_case ( lowerCamelCase_ : numpy.ndarray ): '''simple docstring''' return (value) * (1 - (value)) def __snake_case ( ): '''simple docstring''' __magic_name__ = numpy.array( ( [0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1], ) , dtype=numpy.floataa , ) # True output values for the given input values. __magic_name__ = numpy.array(([0], [1], [1], [0], [1], [0], [0], [1]) , dtype=numpy.floataa ) # Calling neural network class. __magic_name__ = TwoHiddenLayerNeuralNetwork( input_array=lowerCamelCase_ , output_array=lowerCamelCase_ ) # Calling training function. # Set give_loss to True if you want to see loss in every iteration. neural_network.train(output=lowerCamelCase_ , iterations=10 , give_loss=lowerCamelCase_ ) return neural_network.predict(numpy.array(([1, 1, 1]) , dtype=numpy.floataa ) ) if __name__ == "__main__": example()
664
0
import os import unicodedata 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 UpperCAmelCase_ = logging.get_logger(__name__) UpperCAmelCase_ = {"""vocab_file""": """spiece.model"""} UpperCAmelCase_ = { """vocab_file""": { """albert-base-v1""": """https://huggingface.co/albert-base-v1/resolve/main/spiece.model""", """albert-large-v1""": """https://huggingface.co/albert-large-v1/resolve/main/spiece.model""", """albert-xlarge-v1""": """https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model""", """albert-xxlarge-v1""": """https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model""", """albert-base-v2""": """https://huggingface.co/albert-base-v2/resolve/main/spiece.model""", """albert-large-v2""": """https://huggingface.co/albert-large-v2/resolve/main/spiece.model""", """albert-xlarge-v2""": """https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model""", """albert-xxlarge-v2""": """https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model""", } } UpperCAmelCase_ = { """albert-base-v1""": 5_1_2, """albert-large-v1""": 5_1_2, """albert-xlarge-v1""": 5_1_2, """albert-xxlarge-v1""": 5_1_2, """albert-base-v2""": 5_1_2, """albert-large-v2""": 5_1_2, """albert-xlarge-v2""": 5_1_2, """albert-xxlarge-v2""": 5_1_2, } UpperCAmelCase_ = """▁""" class lowerCamelCase__ ( _A): """simple docstring""" a__ : Tuple = VOCAB_FILES_NAMES a__ : str = PRETRAINED_VOCAB_FILES_MAP a__ : int = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : Dict , __lowerCAmelCase : List[str] , __lowerCAmelCase : Optional[int]=True , __lowerCAmelCase : Tuple=True , __lowerCAmelCase : Optional[Any]=False , __lowerCAmelCase : Optional[Any]="[CLS]" , __lowerCAmelCase : List[Any]="[SEP]" , __lowerCAmelCase : List[str]="<unk>" , __lowerCAmelCase : str="[SEP]" , __lowerCAmelCase : Optional[Any]="<pad>" , __lowerCAmelCase : int="[CLS]" , __lowerCAmelCase : List[str]="[MASK]" , __lowerCAmelCase : Optional[Dict[str, Any]] = None , **__lowerCAmelCase : List[Any] , ) -> None: # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. _A = ( AddedToken(__lowerCAmelCase , lstrip=__lowerCAmelCase , rstrip=__lowerCAmelCase , normalized=__lowerCAmelCase ) if isinstance(__lowerCAmelCase , __lowerCAmelCase ) else mask_token ) _A = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=__lowerCAmelCase , remove_space=__lowerCAmelCase , keep_accents=__lowerCAmelCase , bos_token=__lowerCAmelCase , eos_token=__lowerCAmelCase , unk_token=__lowerCAmelCase , sep_token=__lowerCAmelCase , pad_token=__lowerCAmelCase , cls_token=__lowerCAmelCase , mask_token=__lowerCAmelCase , sp_model_kwargs=self.sp_model_kwargs , **__lowerCAmelCase , ) _A = do_lower_case _A = remove_space _A = keep_accents _A = vocab_file _A = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(__lowerCAmelCase ) @property def snake_case_ ( self : List[Any] ) -> int: return len(self.sp_model ) def snake_case_ ( self : Optional[int] ) -> List[str]: _A = {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 : str ) -> str: _A = self.__dict__.copy() _A = None return state def __setstate__( self : Dict , __lowerCAmelCase : Dict ) -> Tuple: _A = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): _A = {} _A = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def snake_case_ ( self : str , __lowerCAmelCase : str ) -> Any: if self.remove_space: _A = ''' '''.join(inputs.strip().split() ) else: _A = inputs _A = outputs.replace('''``''' , '''"''' ).replace('''\'\'''' , '''"''' ) if not self.keep_accents: _A = unicodedata.normalize('''NFKD''' , __lowerCAmelCase ) _A = ''''''.join([c for c in outputs if not unicodedata.combining(__lowerCAmelCase )] ) if self.do_lower_case: _A = outputs.lower() return outputs def snake_case_ ( self : Union[str, Any] , __lowerCAmelCase : str ) -> List[str]: _A = self.preprocess_text(__lowerCAmelCase ) _A = self.sp_model.encode(__lowerCAmelCase , out_type=__lowerCAmelCase ) _A = [] for piece in pieces: if len(__lowerCAmelCase ) > 1 and piece[-1] == str(''',''' ) and piece[-2].isdigit(): _A = self.sp_model.EncodeAsPieces(piece[:-1].replace(__lowerCAmelCase , '''''' ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: _A = cur_pieces[1:] else: _A = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(__lowerCAmelCase ) else: new_pieces.append(__lowerCAmelCase ) return new_pieces def snake_case_ ( self : str , __lowerCAmelCase : Optional[int] ) -> Dict: return self.sp_model.PieceToId(__lowerCAmelCase ) def snake_case_ ( self : Optional[Any] , __lowerCAmelCase : Optional[int] ) -> List[Any]: return self.sp_model.IdToPiece(__lowerCAmelCase ) def snake_case_ ( self : Dict , __lowerCAmelCase : Optional[Any] ) -> Optional[Any]: _A = [] _A = '''''' _A = 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 _A = True _A = [] else: current_sub_tokens.append(__lowerCAmelCase ) _A = False out_string += self.sp_model.decode(__lowerCAmelCase ) return out_string.strip() def snake_case_ ( self : Dict , __lowerCAmelCase : List[int] , __lowerCAmelCase : Optional[List[int]] = None ) -> List[int]: _A = [self.sep_token_id] _A = [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 snake_case_ ( self : Dict , __lowerCAmelCase : List[int] , __lowerCAmelCase : Optional[List[int]] = None , __lowerCAmelCase : bool = False ) -> List[int]: 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 not None: return [1] + ([0] * len(__lowerCAmelCase )) + [1] + ([0] * len(__lowerCAmelCase )) + [1] return [1] + ([0] * len(__lowerCAmelCase )) + [1] def snake_case_ ( self : str , __lowerCAmelCase : List[int] , __lowerCAmelCase : Optional[List[int]] = None ) -> List[int]: _A = [self.sep_token_id] _A = [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 snake_case_ ( self : Tuple , __lowerCAmelCase : str , __lowerCAmelCase : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(__lowerCAmelCase ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return _A = 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: _A = self.sp_model.serialized_model_proto() fi.write(__lowerCAmelCase ) return (out_vocab_file,)
2
'''simple docstring''' import torch from transformers import AutoModel class UpperCamelCase_ ( torch.nn.Module ): """simple docstring""" def __init__( self : Any , _lowerCamelCase : Optional[int]="sayef/fsner-bert-base-uncased" ) -> List[Any]: super(_lowerCamelCase , self ).__init__() __magic_name__ = AutoModel.from_pretrained(_lowerCamelCase , return_dict=_lowerCamelCase ) __magic_name__ = torch.nn.CosineSimilarity(3 , 1e-08 ) __magic_name__ = torch.nn.Softmax(dim=1 ) def __A ( self : Tuple , **_lowerCamelCase : Union[str, Any] ) -> Optional[int]: return self.bert(**_lowerCamelCase ).last_hidden_state def __A ( self : Dict , _lowerCamelCase : Dict ) -> Dict: return token_embeddings.sum(2 , keepdim=_lowerCamelCase ) def __A ( self : Optional[int] , _lowerCamelCase : Dict , _lowerCamelCase : str , _lowerCamelCase : Tuple=1 ) -> Optional[Any]: return self.softmax(T * self.cos(_lowerCamelCase , _lowerCamelCase ) ) def __A ( self : List[Any] , _lowerCamelCase : Optional[Any] , _lowerCamelCase : Optional[int] ) -> List[str]: __magic_name__ = W_supports["sizes"].tolist() __magic_name__ = W_supports["start_token_id"].item() __magic_name__ = W_supports["end_token_id"].item() del W_supports["sizes"] del W_supports["start_token_id"] del W_supports["end_token_id"] __magic_name__ = self.BERT(**_lowerCamelCase ) __magic_name__ = self.BERT(**_lowerCamelCase ) __magic_name__ = None __magic_name__ = None __magic_name__ = W_supports["input_ids"] == start_token_id __magic_name__ = W_supports["input_ids"] == end_token_id for i, size in enumerate(_lowerCamelCase ): if i == 0: __magic_name__ = 0 else: __magic_name__ = support_sizes[i - 1] __magic_name__ = S[s : s + size][start_token_masks[s : s + size]] __magic_name__ = S[s : s + size][end_token_masks[s : s + size]] __magic_name__ = torch.matmul(q[i] , s_start.T ).sum(1 ).softmax(0 ) __magic_name__ = torch.matmul(q[i] , s_end.T ).sum(1 ).softmax(0 ) if p_starts is not None: __magic_name__ = torch.vstack((p_starts, p_start) ) __magic_name__ = torch.vstack((p_ends, p_end) ) else: __magic_name__ = p_start __magic_name__ = p_end return p_starts, p_ends
664
0
'''simple docstring''' import enum import warnings from ..tokenization_utils import TruncationStrategy from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING lowerCAmelCase : Dict = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE__ ( enum.Enum): lowerCAmelCase_ = 0 lowerCAmelCase_ = 1 @add_end_docstrings(snake_case_) class SCREAMING_SNAKE_CASE__ ( snake_case_): lowerCAmelCase_ = """generated""" def __init__( self , *A_ , **A_ )-> Optional[int]: '''simple docstring''' super().__init__(*A_ , **A_ ) self.check_model_type( TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING if self.framework == 'tf' else MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING ) def UpperCAmelCase_ ( self , A_=None , A_=None , A_=None , A_=None , A_=None , A_=None , **A_ , )-> Optional[Any]: '''simple docstring''' UpperCamelCase = {} if truncation is not None: UpperCamelCase = truncation UpperCamelCase = generate_kwargs UpperCamelCase = {} if return_tensors is not None and return_type is None: UpperCamelCase = ReturnType.TENSORS if return_tensors else ReturnType.TEXT if return_type is not None: UpperCamelCase = return_type if clean_up_tokenization_spaces is not None: UpperCamelCase = clean_up_tokenization_spaces if stop_sequence is not None: UpperCamelCase = self.tokenizer.encode(A_ , add_special_tokens=A_ ) if len(A_ ) > 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 = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def UpperCAmelCase_ ( self , A_ , A_ , A_ )-> Optional[int]: '''simple docstring''' return True def UpperCAmelCase_ ( self , *A_ , A_ )-> Any: '''simple docstring''' UpperCamelCase = self.model.config.prefix if self.model.config.prefix is not None else '' if isinstance(args[0] , A_ ): if self.tokenizer.pad_token_id is None: raise ValueError('Please make sure that the tokenizer has a pad_token_id when using a batch input' ) UpperCamelCase = ([prefix + arg for arg in args[0]],) UpperCamelCase = True elif isinstance(args[0] , A_ ): UpperCamelCase = (prefix + args[0],) UpperCamelCase = False else: raise ValueError( F''' `args[0]`: {args[0]} have the wrong format. The should be either of type `str` or type `list`''' ) UpperCamelCase = self.tokenizer(*A_ , padding=A_ , truncation=A_ , return_tensors=self.framework ) # This is produced by tokenizers but is an invalid generate kwargs if "token_type_ids" in inputs: del inputs["token_type_ids"] return inputs def __call__( self , *A_ , **A_ )-> Union[str, Any]: '''simple docstring''' UpperCamelCase = super().__call__(*A_ , **A_ ) if ( isinstance(args[0] , A_ ) and all(isinstance(A_ , A_ ) for el in args[0] ) and all(len(A_ ) == 1 for res in result ) ): return [res[0] for res in result] return result def UpperCAmelCase_ ( self , A_ , A_=TruncationStrategy.DO_NOT_TRUNCATE , **A_ )-> Any: '''simple docstring''' UpperCamelCase = self._parse_and_tokenize(A_ , truncation=A_ , **A_ ) return inputs def UpperCAmelCase_ ( self , A_ , **A_ )-> int: '''simple docstring''' if self.framework == "pt": UpperCamelCase , UpperCamelCase = model_inputs['input_ids'].shape elif self.framework == "tf": UpperCamelCase , UpperCamelCase = tf.shape(model_inputs['input_ids'] ).numpy() UpperCamelCase = generate_kwargs.get('min_length' , self.model.config.min_length ) UpperCamelCase = generate_kwargs.get('max_length' , self.model.config.max_length ) self.check_inputs(A_ , generate_kwargs['min_length'] , generate_kwargs['max_length'] ) UpperCamelCase = self.model.generate(**A_ , **A_ ) UpperCamelCase = output_ids.shape[0] if self.framework == "pt": UpperCamelCase = output_ids.reshape(A_ , out_b // in_b , *output_ids.shape[1:] ) elif self.framework == "tf": UpperCamelCase = tf.reshape(A_ , (in_b, out_b // in_b, *output_ids.shape[1:]) ) return {"output_ids": output_ids} def UpperCAmelCase_ ( self , A_ , A_=ReturnType.TEXT , A_=False )-> Optional[Any]: '''simple docstring''' UpperCamelCase = [] for output_ids in model_outputs["output_ids"][0]: if return_type == ReturnType.TENSORS: UpperCamelCase = {F'''{self.return_name}_token_ids''': output_ids} elif return_type == ReturnType.TEXT: UpperCamelCase = { F'''{self.return_name}_text''': self.tokenizer.decode( A_ , skip_special_tokens=A_ , clean_up_tokenization_spaces=A_ , ) } records.append(A_ ) return records @add_end_docstrings(snake_case_) class SCREAMING_SNAKE_CASE__ ( snake_case_): lowerCAmelCase_ = """summary""" def __call__( self , *A_ , **A_ )-> Optional[int]: '''simple docstring''' return super().__call__(*A_ , **A_ ) def UpperCAmelCase_ ( self , A_ , A_ , A_ )-> bool: '''simple docstring''' if max_length < min_length: logger.warning(F'''Your min_length={min_length} must be inferior than your max_length={max_length}.''' ) if input_length < max_length: logger.warning( F'''Your max_length is set to {max_length}, but your input_length is only {input_length}. Since this is ''' 'a summarization task, where outputs shorter than the input are typically wanted, you might ' F'''consider decreasing max_length manually, e.g. summarizer(\'...\', max_length={input_length//2})''' ) @add_end_docstrings(snake_case_) class SCREAMING_SNAKE_CASE__ ( snake_case_): lowerCAmelCase_ = """translation""" def UpperCAmelCase_ ( self , A_ , A_ , A_ )-> List[Any]: '''simple docstring''' if input_length > 0.9 * max_length: logger.warning( F'''Your input_length: {input_length} is bigger than 0.9 * max_length: {max_length}. You might consider ''' 'increasing your max_length manually, e.g. translator(\'...\', max_length=400)' ) return True def UpperCAmelCase_ ( self , *A_ , A_=TruncationStrategy.DO_NOT_TRUNCATE , A_=None , A_=None )-> Dict: '''simple docstring''' if getattr(self.tokenizer , '_build_translation_inputs' , A_ ): return self.tokenizer._build_translation_inputs( *A_ , return_tensors=self.framework , truncation=A_ , src_lang=A_ , tgt_lang=A_ ) else: return super()._parse_and_tokenize(*A_ , truncation=A_ ) def UpperCAmelCase_ ( self , A_=None , A_=None , **A_ )-> str: '''simple docstring''' UpperCamelCase , UpperCamelCase , UpperCamelCase = super()._sanitize_parameters(**A_ ) if src_lang is not None: UpperCamelCase = src_lang if tgt_lang is not None: UpperCamelCase = tgt_lang if src_lang is None and tgt_lang is None: # Backward compatibility, direct arguments use is preferred. UpperCamelCase = kwargs.get('task' , self.task ) UpperCamelCase = task.split('_' ) if task and len(A_ ) == 4: # translation, XX, to YY UpperCamelCase = items[1] UpperCamelCase = items[3] return preprocess_params, forward_params, postprocess_params def __call__( self , *A_ , **A_ )-> Any: '''simple docstring''' return super().__call__(*A_ , **A_ )
3
'''simple docstring''' # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from ...utils import deprecate from ..controlnet.pipeline_flax_controlnet import FlaxStableDiffusionControlNetPipeline # noqa: F401 deprecate( 'stable diffusion controlnet', '0.22.0', 'Importing `FlaxStableDiffusionControlNetPipeline` from diffusers.pipelines.stable_diffusion.flax_pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import FlaxStableDiffusionControlNetPipeline` instead.', standard_warn=False, stacklevel=3, )
664
0
"""simple docstring""" __UpperCamelCase : Union[str, Any] = ''' # Transformers installation ! pip install transformers datasets # To install from source instead of the last release, comment the command above and uncomment the following one. # ! pip install git+https://github.com/huggingface/transformers.git ''' __UpperCamelCase : Any = [{'''type''': '''code''', '''content''': INSTALL_CONTENT}] __UpperCamelCase : List[str] = { '''{processor_class}''': '''FakeProcessorClass''', '''{model_class}''': '''FakeModelClass''', '''{object_class}''': '''FakeObjectClass''', }
4
'''simple docstring''' import argparse from tax import checkpoints from transformers import AutoConfig, FlaxAutoModelForSeqaSeqLM def __snake_case ( lowerCamelCase_ : Any , lowerCamelCase_ : int , lowerCamelCase_ : Optional[Any] ): '''simple docstring''' __magic_name__ = AutoConfig.from_pretrained(lowerCamelCase_ ) __magic_name__ = FlaxAutoModelForSeqaSeqLM.from_config(config=lowerCamelCase_ ) __magic_name__ = checkpoints.load_tax_checkpoint(lowerCamelCase_ ) __magic_name__ = "wi_0" in tax_model["target"]["encoder"]["layers_0"]["mlp"] if config.model_type == "t5": __magic_name__ = "SelfAttention" if config.model_type == "longt5" and config.encoder_attention_type == "local": __magic_name__ = "LocalSelfAttention" elif config.model_type == "longt5" and config.encoder_attention_type == "transient-global": __magic_name__ = "TransientGlobalSelfAttention" else: raise ValueError( "Given config is expected to have `model_type='t5'`, or `model_type='longt5` with `encoder_attention_type`" " attribute with a value from ['local', 'transient-global]." ) # Encoder for layer_index in range(config.num_layers ): __magic_name__ = F'layers_{str(lowerCamelCase_ )}' # Self-Attention __magic_name__ = tax_model["target"]["encoder"][layer_name]["attention"]["key"]["kernel"] __magic_name__ = tax_model["target"]["encoder"][layer_name]["attention"]["out"]["kernel"] __magic_name__ = tax_model["target"]["encoder"][layer_name]["attention"]["query"]["kernel"] __magic_name__ = tax_model["target"]["encoder"][layer_name]["attention"]["value"]["kernel"] # Global input layer norm if config.model_type == "longt5" and config.encoder_attention_type == "transient-global": __magic_name__ = tax_model["target"]["encoder"][layer_name]["attention"]["T5LayerNorm_0"]["scale"] # Layer Normalization __magic_name__ = tax_model["target"]["encoder"][layer_name]["pre_attention_layer_norm"]["scale"] if split_mlp_wi: __magic_name__ = tax_model["target"]["encoder"][layer_name]["mlp"]["wi_0"]["kernel"] __magic_name__ = tax_model["target"]["encoder"][layer_name]["mlp"]["wi_1"]["kernel"] else: __magic_name__ = tax_model["target"]["encoder"][layer_name]["mlp"]["wi"]["kernel"] __magic_name__ = tax_model["target"]["encoder"][layer_name]["mlp"]["wo"]["kernel"] # Layer Normalization __magic_name__ = tax_model["target"]["encoder"][layer_name]["pre_mlp_layer_norm"]["scale"] # Assigning __magic_name__ = flax_model.params["encoder"]["block"][str(lowerCamelCase_ )]["layer"] __magic_name__ = tax_attention_key __magic_name__ = tax_attention_out __magic_name__ = tax_attention_query __magic_name__ = tax_attention_value __magic_name__ = tax_attention_layer_norm # Global input layer norm if config.model_type == "longt5" and config.encoder_attention_type == "transient-global": __magic_name__ = tax_global_layer_norm if split_mlp_wi: __magic_name__ = tax_mlp_wi_a __magic_name__ = tax_mlp_wi_a else: __magic_name__ = tax_mlp_wi __magic_name__ = tax_mlp_wo __magic_name__ = tax_mlp_layer_norm __magic_name__ = flax_model_encoder_layer_block # Only for layer 0: __magic_name__ = tax_model["target"]["encoder"]["relpos_bias"]["rel_embedding"].T __magic_name__ = tax_encoder_rel_embedding # Side/global relative position_bias + layer norm if config.model_type == "longt5" and config.encoder_attention_type == "transient-global": __magic_name__ = tax_model["target"]["encoder"]["side_relpos_bias"]["rel_embedding"].T __magic_name__ = tax_encoder_global_rel_embedding # Assigning __magic_name__ = tax_model["target"]["encoder"]["encoder_norm"]["scale"] __magic_name__ = tax_encoder_norm # Decoder for layer_index in range(config.num_layers ): __magic_name__ = F'layers_{str(lowerCamelCase_ )}' # Self-Attention __magic_name__ = tax_model["target"]["decoder"][layer_name]["self_attention"]["key"]["kernel"] __magic_name__ = tax_model["target"]["decoder"][layer_name]["self_attention"]["out"]["kernel"] __magic_name__ = tax_model["target"]["decoder"][layer_name]["self_attention"]["query"]["kernel"] __magic_name__ = tax_model["target"]["decoder"][layer_name]["self_attention"]["value"]["kernel"] # Layer Normalization __magic_name__ = tax_model["target"]["decoder"][layer_name]["pre_self_attention_layer_norm"][ "scale" ] # Encoder-Decoder-Attention __magic_name__ = tax_model["target"]["decoder"][layer_name]["encoder_decoder_attention"] __magic_name__ = tax_enc_dec_attention_module["key"]["kernel"] __magic_name__ = tax_enc_dec_attention_module["out"]["kernel"] __magic_name__ = tax_enc_dec_attention_module["query"]["kernel"] __magic_name__ = tax_enc_dec_attention_module["value"]["kernel"] # Layer Normalization __magic_name__ = tax_model["target"]["decoder"][layer_name]["pre_cross_attention_layer_norm"]["scale"] # MLP if split_mlp_wi: __magic_name__ = tax_model["target"]["decoder"][layer_name]["mlp"]["wi_0"]["kernel"] __magic_name__ = tax_model["target"]["decoder"][layer_name]["mlp"]["wi_1"]["kernel"] else: __magic_name__ = tax_model["target"]["decoder"][layer_name]["mlp"]["wi"]["kernel"] __magic_name__ = tax_model["target"]["decoder"][layer_name]["mlp"]["wo"]["kernel"] # Layer Normalization __magic_name__ = tax_model["target"]["decoder"][layer_name]["pre_mlp_layer_norm"]["scale"] # Assigning __magic_name__ = flax_model.params["decoder"]["block"][str(lowerCamelCase_ )]["layer"] __magic_name__ = tax_attention_key __magic_name__ = tax_attention_out __magic_name__ = tax_attention_query __magic_name__ = tax_attention_value __magic_name__ = tax_pre_attention_layer_norm __magic_name__ = tax_enc_dec_attention_key __magic_name__ = tax_enc_dec_attention_out __magic_name__ = tax_enc_dec_attention_query __magic_name__ = tax_enc_dec_attention_value __magic_name__ = tax_cross_layer_norm if split_mlp_wi: __magic_name__ = tax_mlp_wi_a __magic_name__ = tax_mlp_wi_a else: __magic_name__ = tax_mlp_wi __magic_name__ = tax_mlp_wo __magic_name__ = txa_mlp_layer_norm __magic_name__ = flax_model_decoder_layer_block # Decoder Normalization __magic_name__ = tax_model["target"]["decoder"]["decoder_norm"]["scale"] __magic_name__ = txa_decoder_norm # Only for layer 0: __magic_name__ = tax_model["target"]["decoder"]["relpos_bias"]["rel_embedding"].T __magic_name__ = tax_decoder_rel_embedding # Token Embeddings __magic_name__ = tax_model["target"]["token_embedder"]["embedding"] __magic_name__ = txa_token_embeddings # LM Head (only in v1.1 and LongT5 checkpoints) if "logits_dense" in tax_model["target"]["decoder"]: __magic_name__ = tax_model["target"]["decoder"]["logits_dense"]["kernel"] flax_model.save_pretrained(lowerCamelCase_ ) print("T5X Model was sucessfully converted!" ) if __name__ == "__main__": __magic_name__ : Optional[Any] =argparse.ArgumentParser() # Required parameters parser.add_argument( '--t5x_checkpoint_path', default=None, type=str, required=True, help='Path the T5X checkpoint.' ) parser.add_argument('--config_name', default=None, type=str, required=True, help='Config name of LongT5/T5 model.') parser.add_argument( '--flax_dump_folder_path', default=None, type=str, required=True, help='Path to the output FLAX model.' ) __magic_name__ : Optional[int] =parser.parse_args() convert_tax_checkpoint_to_flax(args.tax_checkpoint_path, args.config_name, args.flax_dump_folder_path)
664
0
'''simple docstring''' from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer from ...configuration_utils import PretrainedConfig from ...file_utils import TensorType, is_torch_available from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast from ...onnx.utils import compute_effective_axis_dimension from ...utils import logging _lowercase = logging.get_logger(__name__) _lowercase = { """facebook/blenderbot_small-90M""": """https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/config.json""", # See all BlenderbotSmall models at https://huggingface.co/models?filter=blenderbot_small } class UpperCAmelCase_ ( _SCREAMING_SNAKE_CASE ): '''simple docstring''' _lowercase : str = '''blenderbot-small''' _lowercase : List[Any] = ['''past_key_values'''] _lowercase : List[Any] = {'''num_attention_heads''': '''encoder_attention_heads''', '''hidden_size''': '''d_model'''} def __init__( self , _lowercase=50_265 , _lowercase=512 , _lowercase=8 , _lowercase=2_048 , _lowercase=16 , _lowercase=8 , _lowercase=2_048 , _lowercase=16 , _lowercase=0.0 , _lowercase=0.0 , _lowercase=True , _lowercase=True , _lowercase="gelu" , _lowercase=512 , _lowercase=0.1 , _lowercase=0.0 , _lowercase=0.0 , _lowercase=0.02 , _lowercase=1 , _lowercase=False , _lowercase=0 , _lowercase=1 , _lowercase=2 , _lowercase=2 , **_lowercase , ): """simple docstring""" _lowerCAmelCase = vocab_size _lowerCAmelCase = max_position_embeddings _lowerCAmelCase = d_model _lowerCAmelCase = encoder_ffn_dim _lowerCAmelCase = encoder_layers _lowerCAmelCase = encoder_attention_heads _lowerCAmelCase = decoder_ffn_dim _lowerCAmelCase = decoder_layers _lowerCAmelCase = decoder_attention_heads _lowerCAmelCase = dropout _lowerCAmelCase = attention_dropout _lowerCAmelCase = activation_dropout _lowerCAmelCase = activation_function _lowerCAmelCase = init_std _lowerCAmelCase = encoder_layerdrop _lowerCAmelCase = decoder_layerdrop _lowerCAmelCase = use_cache _lowerCAmelCase = encoder_layers _lowerCAmelCase = scale_embedding # scale factor will be sqrt(d_model) if True super().__init__( pad_token_id=_lowercase , bos_token_id=_lowercase , eos_token_id=_lowercase , is_encoder_decoder=_lowercase , decoder_start_token_id=_lowercase , forced_eos_token_id=_lowercase , **_lowercase , ) class UpperCAmelCase_ ( _SCREAMING_SNAKE_CASE ): '''simple docstring''' @property def _lowercase ( self ): """simple docstring""" if self.task in ["default", "seq2seq-lm"]: _lowerCAmelCase = OrderedDict( [ ("""input_ids""", {0: """batch""", 1: """encoder_sequence"""}), ("""attention_mask""", {0: """batch""", 1: """encoder_sequence"""}), ] ) if self.use_past: _lowerCAmelCase = {0: """batch"""} _lowerCAmelCase = {0: """batch""", 1: """past_decoder_sequence + sequence"""} else: _lowerCAmelCase = {0: """batch""", 1: """decoder_sequence"""} _lowerCAmelCase = {0: """batch""", 1: """decoder_sequence"""} if self.use_past: self.fill_with_past_key_values_(_lowercase , direction="""inputs""" ) elif self.task == "causal-lm": # TODO: figure this case out. _lowerCAmelCase = OrderedDict( [ ("""input_ids""", {0: """batch""", 1: """encoder_sequence"""}), ("""attention_mask""", {0: """batch""", 1: """encoder_sequence"""}), ] ) if self.use_past: _lowerCAmelCase , _lowerCAmelCase = self.num_layers for i in range(_lowercase ): _lowerCAmelCase = {0: """batch""", 2: """past_sequence + sequence"""} _lowerCAmelCase = {0: """batch""", 2: """past_sequence + sequence"""} else: _lowerCAmelCase = OrderedDict( [ ("""input_ids""", {0: """batch""", 1: """encoder_sequence"""}), ("""attention_mask""", {0: """batch""", 1: """encoder_sequence"""}), ("""decoder_input_ids""", {0: """batch""", 1: """decoder_sequence"""}), ("""decoder_attention_mask""", {0: """batch""", 1: """decoder_sequence"""}), ] ) return common_inputs @property def _lowercase ( self ): """simple docstring""" if self.task in ["default", "seq2seq-lm"]: _lowerCAmelCase = super().outputs else: _lowerCAmelCase = super(_lowercase , self ).outputs if self.use_past: _lowerCAmelCase , _lowerCAmelCase = self.num_layers for i in range(_lowercase ): _lowerCAmelCase = {0: """batch""", 2: """past_sequence + sequence"""} _lowerCAmelCase = {0: """batch""", 2: """past_sequence + sequence"""} return common_outputs def _lowercase ( self , _lowercase , _lowercase = -1 , _lowercase = -1 , _lowercase = False , _lowercase = None , ): """simple docstring""" _lowerCAmelCase = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( _lowercase , _lowercase , _lowercase , _lowercase , _lowercase ) # Generate decoder inputs _lowerCAmelCase = seq_length if not self.use_past else 1 _lowerCAmelCase = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( _lowercase , _lowercase , _lowercase , _lowercase , _lowercase ) _lowerCAmelCase = {F'decoder_{name}': tensor for name, tensor in decoder_inputs.items()} _lowerCAmelCase = dict(**_lowercase , **_lowercase ) if self.use_past: if not is_torch_available(): raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed.""" ) else: import torch _lowerCAmelCase , _lowerCAmelCase = common_inputs["""input_ids"""].shape _lowerCAmelCase = common_inputs["""decoder_input_ids"""].shape[1] _lowerCAmelCase , _lowerCAmelCase = self.num_attention_heads _lowerCAmelCase = ( batch, num_encoder_attention_heads, encoder_seq_length, self._config.hidden_size // num_encoder_attention_heads, ) _lowerCAmelCase = decoder_seq_length + 3 _lowerCAmelCase = ( batch, num_decoder_attention_heads, decoder_past_length, self._config.hidden_size // num_decoder_attention_heads, ) _lowerCAmelCase = torch.cat( [common_inputs["""decoder_attention_mask"""], torch.ones(_lowercase , _lowercase )] , dim=1 ) _lowerCAmelCase = [] # If the number of encoder and decoder layers are present in the model configuration, both are considered _lowerCAmelCase , _lowerCAmelCase = self.num_layers _lowerCAmelCase = min(_lowercase , _lowercase ) _lowerCAmelCase = max(_lowercase , _lowercase ) - min_num_layers _lowerCAmelCase = """encoder""" if num_encoder_layers > num_decoder_layers else """decoder""" for _ in range(_lowercase ): common_inputs["past_key_values"].append( ( torch.zeros(_lowercase ), torch.zeros(_lowercase ), torch.zeros(_lowercase ), torch.zeros(_lowercase ), ) ) # TODO: test this. _lowerCAmelCase = encoder_shape if remaining_side_name == """encoder""" else decoder_shape for _ in range(_lowercase , _lowercase ): common_inputs["past_key_values"].append((torch.zeros(_lowercase ), torch.zeros(_lowercase )) ) return common_inputs def _lowercase ( self , _lowercase , _lowercase = -1 , _lowercase = -1 , _lowercase = False , _lowercase = None , ): """simple docstring""" _lowerCAmelCase = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( _lowercase , _lowercase , _lowercase , _lowercase , _lowercase ) if self.use_past: if not is_torch_available(): raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed.""" ) else: import torch _lowerCAmelCase , _lowerCAmelCase = common_inputs["""input_ids"""].shape # Not using the same length for past_key_values _lowerCAmelCase = seqlen + 2 _lowerCAmelCase , _lowerCAmelCase = self.num_layers _lowerCAmelCase , _lowerCAmelCase = self.num_attention_heads _lowerCAmelCase = ( batch, num_encoder_attention_heads, past_key_values_length, self._config.hidden_size // num_encoder_attention_heads, ) _lowerCAmelCase = common_inputs["""attention_mask"""].dtype _lowerCAmelCase = torch.cat( [common_inputs["""attention_mask"""], torch.ones(_lowercase , _lowercase , dtype=_lowercase )] , dim=1 ) _lowerCAmelCase = [ (torch.zeros(_lowercase ), torch.zeros(_lowercase )) for _ in range(_lowercase ) ] return common_inputs def _lowercase ( self , _lowercase , _lowercase = -1 , _lowercase = -1 , _lowercase = False , _lowercase = None , ): """simple docstring""" _lowerCAmelCase = compute_effective_axis_dimension( _lowercase , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX _lowerCAmelCase = tokenizer.num_special_tokens_to_add(_lowercase ) _lowerCAmelCase = compute_effective_axis_dimension( _lowercase , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=_lowercase ) # Generate dummy inputs according to compute batch and sequence _lowerCAmelCase = [""" """.join([tokenizer.unk_token] ) * seq_length] * batch_size _lowerCAmelCase = dict(tokenizer(_lowercase , return_tensors=_lowercase ) ) return common_inputs def _lowercase ( self , _lowercase , _lowercase = -1 , _lowercase = -1 , _lowercase = False , _lowercase = None , ): """simple docstring""" if self.task in ["default", "seq2seq-lm"]: _lowerCAmelCase = self._generate_dummy_inputs_for_default_and_seqaseq_lm( _lowercase , batch_size=_lowercase , seq_length=_lowercase , is_pair=_lowercase , framework=_lowercase ) elif self.task == "causal-lm": _lowerCAmelCase = self._generate_dummy_inputs_for_causal_lm( _lowercase , batch_size=_lowercase , seq_length=_lowercase , is_pair=_lowercase , framework=_lowercase ) else: _lowerCAmelCase = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( _lowercase , batch_size=_lowercase , seq_length=_lowercase , is_pair=_lowercase , framework=_lowercase ) return common_inputs def _lowercase ( self , _lowercase , _lowercase , _lowercase , _lowercase ): """simple docstring""" if self.task in ["default", "seq2seq-lm"]: _lowerCAmelCase = super()._flatten_past_key_values_(_lowercase , _lowercase , _lowercase , _lowercase ) else: _lowerCAmelCase = super(_lowercase , self )._flatten_past_key_values_( _lowercase , _lowercase , _lowercase , _lowercase )
5
'''simple docstring''' import unittest from transformers import load_tool from transformers.utils import is_torch_available if is_torch_available(): import torch from transformers.testing_utils import require_torch from .test_tools_common import ToolTesterMixin @require_torch class UpperCamelCase_ ( unittest.TestCase , A ): """simple docstring""" def __A ( self : Optional[int] ) -> Any: __magic_name__ = load_tool("text-to-speech" ) self.tool.setup() def __A ( self : Union[str, Any] ) -> int: # SpeechT5 isn't deterministic torch.manual_seed(0 ) __magic_name__ = self.tool("hey" ) __magic_name__ = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] , torch.tensor([-0.0_005_966_668_832_115_829, -0.0_003_657_640_190_795_064, -0.00_013_439_502_799_883_485] ) , ) ) def __A ( self : List[str] ) -> int: # SpeechT5 isn't deterministic torch.manual_seed(0 ) __magic_name__ = self.tool("hey" ) __magic_name__ = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] , torch.tensor([-0.0_005_966_668_832_115_829, -0.0_003_657_640_190_795_064, -0.00_013_439_502_799_883_485] ) , ) )
664
0
import operator def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list , UpperCamelCase__: bool = False , UpperCamelCase__: list | None = None ): SCREAMING_SNAKE_CASE__ = operator.lt if reverse else operator.gt SCREAMING_SNAKE_CASE__ = solution or [] if not arr: return solution SCREAMING_SNAKE_CASE__ = [arr.pop(0 )] for i, item in enumerate(UpperCamelCase__ ): if _operator(UpperCamelCase__ , sublist[-1] ): sublist.append(UpperCamelCase__ ) arr.pop(UpperCamelCase__ ) # merging sublist into solution list if not solution: solution.extend(UpperCamelCase__ ) else: while sublist: SCREAMING_SNAKE_CASE__ = sublist.pop(0 ) for i, xx in enumerate(UpperCamelCase__ ): if not _operator(UpperCamelCase__ , UpperCamelCase__ ): solution.insert(UpperCamelCase__ , UpperCamelCase__ ) break else: solution.append(UpperCamelCase__ ) strand_sort(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) return solution if __name__ == "__main__": assert strand_sort([4, 3, 5, 1, 2]) == [1, 2, 3, 4, 5] assert strand_sort([4, 3, 5, 1, 2], reverse=True) == [5, 4, 3, 2, 1]
6
'''simple docstring''' import json import multiprocessing as mp import re from collections import defaultdict from functools import partial from typing import Dict, List, Optional, Set, Tuple, Type from datasets import Dataset from datasketch import MinHash, MinHashLSH from dpu_utils.utils.iterators import ThreadedIterator from tqdm import tqdm __magic_name__ : Dict =re.compile('[^A-Za-z_0-9]') # parameters used in DuplicationIndex __magic_name__ : int =10 __magic_name__ : Union[str, Any] =2_56 def __snake_case ( lowerCamelCase_ : List[str] ): '''simple docstring''' if len(lowerCamelCase_ ) < MIN_NUM_TOKENS: return None __magic_name__ = MinHash(num_perm=lowerCamelCase_ ) for token in set(lowerCamelCase_ ): min_hash.update(token.encode() ) return min_hash def __snake_case ( lowerCamelCase_ : str ): '''simple docstring''' return {t for t in NON_ALPHA.split(lowerCamelCase_ ) if len(t.strip() ) > 0} class UpperCamelCase_ : """simple docstring""" def __init__( self : int , *, _lowerCamelCase : float = 0.85 , ) -> Optional[Any]: __magic_name__ = duplication_jaccard_threshold __magic_name__ = NUM_PERM __magic_name__ = MinHashLSH(threshold=self._duplication_jaccard_threshold , num_perm=self._num_perm ) __magic_name__ = defaultdict(_lowerCamelCase ) def __A ( self : List[Any] , _lowerCamelCase : Tuple , _lowerCamelCase : MinHash ) -> None: __magic_name__ = self._index.query(_lowerCamelCase ) if code_key in self._index.keys: print(f'Duplicate key {code_key}' ) return self._index.insert(_lowerCamelCase , _lowerCamelCase ) if len(_lowerCamelCase ) > 0: for base_duplicate in close_duplicates: if base_duplicate in self._duplicate_clusters: self._duplicate_clusters[base_duplicate].add(_lowerCamelCase ) break else: self._duplicate_clusters[close_duplicates[0]].add(_lowerCamelCase ) def __A ( self : Union[str, Any] ) -> List[List[Dict]]: __magic_name__ = [] for base, duplicates in self._duplicate_clusters.items(): __magic_name__ = [base] + list(_lowerCamelCase ) # reformat the cluster to be a list of dict __magic_name__ = [{"base_index": el[0], "repo_name": el[1], "path": el[2]} for el in cluster] duplicate_clusters.append(_lowerCamelCase ) return duplicate_clusters def __A ( self : Tuple , _lowerCamelCase : Tuple ) -> None: __magic_name__ = self.get_duplicate_clusters() with open(_lowerCamelCase , "w" ) as f: json.dump(_lowerCamelCase , _lowerCamelCase ) def __snake_case ( lowerCamelCase_ : List[Any] ): '''simple docstring''' __magic_name__ , __magic_name__ = element __magic_name__ = get_min_hash([t for t in NON_ALPHA.split(data["content"] ) if len(t.strip() ) > 0] ) if min_hash is not None: return (index, data["repo_name"], data["path"]), min_hash def __snake_case ( lowerCamelCase_ : Type[Dataset] ): '''simple docstring''' with mp.Pool() as pool: for data in pool.imap_unordered( _compute_min_hash , ThreadedIterator(lowerCamelCase_ , max_queue_size=1_0000 ) , chunksize=100 , ): if data is not None: yield data def __snake_case ( lowerCamelCase_ : Type[Dataset] , lowerCamelCase_ : float ): '''simple docstring''' __magic_name__ = DuplicationIndex(duplication_jaccard_threshold=lowerCamelCase_ ) for filename, min_hash in tqdm(ThreadedIterator(minhash_iter(enumerate(lowerCamelCase_ ) ) , max_queue_size=100 ) ): di.add(lowerCamelCase_ , lowerCamelCase_ ) # Returns a List[Cluster] where Cluster is List[str] with the filenames. return di.get_duplicate_clusters() def __snake_case ( lowerCamelCase_ : str , lowerCamelCase_ : str ): '''simple docstring''' __magic_name__ = get_tokens(lowerCamelCase_ ) __magic_name__ = get_tokens(lowerCamelCase_ ) return len(tokensa & tokensa ) / len(tokensa | tokensa ) __magic_name__ : List[str] =None def __snake_case ( lowerCamelCase_ : Dict , lowerCamelCase_ : List[Any] ): '''simple docstring''' __magic_name__ = [] for elementa in cluster: __magic_name__ = _shared_dataset[elementa["base_index"]]["content"] for elementa in extremes: __magic_name__ = _shared_dataset[elementa["base_index"]]["content"] if jaccard_similarity(lowerCamelCase_ , lowerCamelCase_ ) >= jaccard_threshold: elementa["copies"] += 1 break else: __magic_name__ = 1 extremes.append(lowerCamelCase_ ) return extremes def __snake_case ( lowerCamelCase_ : Dict , lowerCamelCase_ : Any , lowerCamelCase_ : Union[str, Any] ): '''simple docstring''' global _shared_dataset __magic_name__ = dataset __magic_name__ = [] __magic_name__ = partial(_find_cluster_extremes_shared , jaccard_threshold=lowerCamelCase_ ) with mp.Pool() as pool: for extremes in tqdm( pool.imap_unordered( lowerCamelCase_ , lowerCamelCase_ , ) , total=len(lowerCamelCase_ ) , ): extremes_list.append(lowerCamelCase_ ) return extremes_list def __snake_case ( lowerCamelCase_ : Type[Dataset] , lowerCamelCase_ : float = 0.85 ): '''simple docstring''' __magic_name__ = make_duplicate_clusters(lowerCamelCase_ , lowerCamelCase_ ) __magic_name__ = {x["base_index"] for cluster in duplicate_clusters for x in cluster} __magic_name__ = {} __magic_name__ = find_extremes(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) for extremes in extremes_clusters: for element in extremes: __magic_name__ = element __magic_name__ = duplicate_indices - set(extreme_dict.keys() ) __magic_name__ = dataset.filter(lambda lowerCamelCase_ , lowerCamelCase_ : idx not in remove_indices , with_indices=lowerCamelCase_ ) # update duplicate_clusters for cluster in duplicate_clusters: for element in cluster: __magic_name__ = element["base_index"] in extreme_dict if element["is_extreme"]: __magic_name__ = extreme_dict[element["base_index"]]["copies"] print(F'Original dataset size: {len(lowerCamelCase_ )}' ) print(F'Number of duplicate clusters: {len(lowerCamelCase_ )}' ) print(F'Files in duplicate cluster: {len(lowerCamelCase_ )}' ) print(F'Unique files in duplicate cluster: {len(lowerCamelCase_ )}' ) print(F'Filtered dataset size: {len(lowerCamelCase_ )}' ) return ds_filter, duplicate_clusters
664
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available a = { '''configuration_graphormer''': ['''GRAPHORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GraphormerConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a = [ '''GRAPHORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GraphormerForGraphClassification''', '''GraphormerModel''', '''GraphormerPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_graphormer import GRAPHORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, GraphormerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_graphormer import ( GRAPHORMER_PRETRAINED_MODEL_ARCHIVE_LIST, GraphormerForGraphClassification, GraphormerModel, GraphormerPreTrainedModel, ) else: import sys a = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
7
'''simple docstring''' import argparse import os import gluonnlp as nlp import mxnet as mx import numpy as np import torch from gluonnlp.base import get_home_dir from gluonnlp.model.bert import BERTEncoder from gluonnlp.model.utils import _load_vocab from gluonnlp.vocab import Vocab from packaging import version from torch import nn from transformers import BertConfig, BertForMaskedLM, BertModel, RobertaTokenizer from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertSelfAttention, BertSelfOutput, ) from transformers.utils import logging if version.parse(nlp.__version__) != version.parse('0.8.3'): raise Exception('requires gluonnlp == 0.8.3') if version.parse(mx.__version__) != version.parse('1.5.0'): raise Exception('requires mxnet == 1.5.0') logging.set_verbosity_info() __magic_name__ : Optional[int] =logging.get_logger(__name__) __magic_name__ : Tuple ='The Nymphenburg Palace is a beautiful palace in Munich!' def __snake_case ( lowerCamelCase_ : str , lowerCamelCase_ : str ): '''simple docstring''' __magic_name__ = { "attention_cell": "multi_head", "num_layers": 4, "units": 1024, "hidden_size": 768, "max_length": 512, "num_heads": 8, "scaled": True, "dropout": 0.1, "use_residual": True, "embed_size": 1024, "embed_dropout": 0.1, "word_embed": None, "layer_norm_eps": 1e-5, "token_type_vocab_size": 2, } __magic_name__ = bort_4_8_768_1024_hparams # Let's construct the original Bort model here # Taken from official BERT implementation, see: # https://github.com/alexa/bort/blob/master/bort/bort.py __magic_name__ = BERTEncoder( attention_cell=predefined_args["attention_cell"] , num_layers=predefined_args["num_layers"] , units=predefined_args["units"] , hidden_size=predefined_args["hidden_size"] , max_length=predefined_args["max_length"] , num_heads=predefined_args["num_heads"] , scaled=predefined_args["scaled"] , dropout=predefined_args["dropout"] , output_attention=lowerCamelCase_ , output_all_encodings=lowerCamelCase_ , use_residual=predefined_args["use_residual"] , activation=predefined_args.get("activation" , "gelu" ) , layer_norm_eps=predefined_args.get("layer_norm_eps" , lowerCamelCase_ ) , ) # Vocab information needs to be fetched first # It's the same as RoBERTa, so RobertaTokenizer can be used later __magic_name__ = "openwebtext_ccnews_stories_books_cased" # Specify download folder to Gluonnlp's vocab __magic_name__ = os.path.join(get_home_dir() , "models" ) __magic_name__ = _load_vocab(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , cls=lowerCamelCase_ ) __magic_name__ = nlp.model.BERTModel( lowerCamelCase_ , len(lowerCamelCase_ ) , units=predefined_args["units"] , embed_size=predefined_args["embed_size"] , embed_dropout=predefined_args["embed_dropout"] , word_embed=predefined_args["word_embed"] , use_pooler=lowerCamelCase_ , use_token_type_embed=lowerCamelCase_ , token_type_vocab_size=predefined_args["token_type_vocab_size"] , use_classifier=lowerCamelCase_ , use_decoder=lowerCamelCase_ , ) original_bort.load_parameters(lowerCamelCase_ , cast_dtype=lowerCamelCase_ , ignore_extra=lowerCamelCase_ ) __magic_name__ = original_bort._collect_params_with_prefix() # Build our config 🤗 __magic_name__ = { "architectures": ["BertForMaskedLM"], "attention_probs_dropout_prob": predefined_args["dropout"], "hidden_act": "gelu", "hidden_dropout_prob": predefined_args["dropout"], "hidden_size": predefined_args["embed_size"], "initializer_range": 0.02, "intermediate_size": predefined_args["hidden_size"], "layer_norm_eps": predefined_args["layer_norm_eps"], "max_position_embeddings": predefined_args["max_length"], "model_type": "bort", "num_attention_heads": predefined_args["num_heads"], "num_hidden_layers": predefined_args["num_layers"], "pad_token_id": 1, # 2 = BERT, 1 = RoBERTa "type_vocab_size": 1, # 2 = BERT, 1 = RoBERTa "vocab_size": len(lowerCamelCase_ ), } __magic_name__ = BertConfig.from_dict(lowerCamelCase_ ) __magic_name__ = BertForMaskedLM(lowerCamelCase_ ) hf_bort_model.eval() # Parameter mapping table (Gluonnlp to Transformers) # * denotes layer index # # | Gluon Parameter | Transformers Parameter # | -------------------------------------------------------------- | ---------------------- # | `encoder.layer_norm.beta` | `bert.embeddings.LayerNorm.bias` # | `encoder.layer_norm.gamma` | `bert.embeddings.LayerNorm.weight` # | `encoder.position_weight` | `bert.embeddings.position_embeddings.weight` # | `word_embed.0.weight` | `bert.embeddings.word_embeddings.weight` # | `encoder.transformer_cells.*.attention_cell.proj_key.bias` | `bert.encoder.layer.*.attention.self.key.bias` # | `encoder.transformer_cells.*.attention_cell.proj_key.weight` | `bert.encoder.layer.*.attention.self.key.weight` # | `encoder.transformer_cells.*.attention_cell.proj_query.bias` | `bert.encoder.layer.*.attention.self.query.bias` # | `encoder.transformer_cells.*.attention_cell.proj_query.weight` | `bert.encoder.layer.*.attention.self.query.weight` # | `encoder.transformer_cells.*.attention_cell.proj_value.bias` | `bert.encoder.layer.*.attention.self.value.bias` # | `encoder.transformer_cells.*.attention_cell.proj_value.weight` | `bert.encoder.layer.*.attention.self.value.weight` # | `encoder.transformer_cells.*.ffn.ffn_2.bias` | `bert.encoder.layer.*.attention.output.dense.bias` # | `encoder.transformer_cells.*.ffn.ffn_2.weight` | `bert.encoder.layer.*.attention.output.dense.weight` # | `encoder.transformer_cells.*.layer_norm.beta` | `bert.encoder.layer.*.attention.output.LayerNorm.bias` # | `encoder.transformer_cells.*.layer_norm.gamma` | `bert.encoder.layer.*.attention.output.LayerNorm.weight` # | `encoder.transformer_cells.*.ffn.ffn_1.bias` | `bert.encoder.layer.*.intermediate.dense.bias` # | `encoder.transformer_cells.*.ffn.ffn_1.weight` | `bert.encoder.layer.*.intermediate.dense.weight` # | `encoder.transformer_cells.*.ffn.layer_norm.beta` | `bert.encoder.layer.*.output.LayerNorm.bias` # | `encoder.transformer_cells.*.ffn.layer_norm.gamma` | `bert.encoder.layer.*.output.LayerNorm.weight` # | `encoder.transformer_cells.*.proj.bias` | `bert.encoder.layer.*.output.dense.bias` # | `encoder.transformer_cells.*.proj.weight` | `bert.encoder.layer.*.output.dense.weight` # Helper function to convert MXNET Arrays to PyTorch def to_torch(lowerCamelCase_ : Any ) -> nn.Parameter: return nn.Parameter(torch.FloatTensor(mx_array.data().asnumpy() ) ) # Check param shapes and map new HF param back def check_and_map_params(lowerCamelCase_ : Optional[int] , lowerCamelCase_ : int ): __magic_name__ = hf_param.shape __magic_name__ = to_torch(params[gluon_param] ) __magic_name__ = gluon_param.shape assert ( shape_hf == shape_gluon ), F'The gluon parameter {gluon_param} has shape {shape_gluon}, but expects shape {shape_hf} for Transformers' return gluon_param __magic_name__ = check_and_map_params( hf_bort_model.bert.embeddings.word_embeddings.weight , "word_embed.0.weight" ) __magic_name__ = check_and_map_params( hf_bort_model.bert.embeddings.position_embeddings.weight , "encoder.position_weight" ) __magic_name__ = check_and_map_params( hf_bort_model.bert.embeddings.LayerNorm.bias , "encoder.layer_norm.beta" ) __magic_name__ = check_and_map_params( hf_bort_model.bert.embeddings.LayerNorm.weight , "encoder.layer_norm.gamma" ) # Inspired by RoBERTa conversion script, we just zero them out (Bort does not use them) __magic_name__ = torch.zeros_like( hf_bort_model.bert.embeddings.token_type_embeddings.weight.data ) for i in range(hf_bort_config.num_hidden_layers ): __magic_name__ = hf_bort_model.bert.encoder.layer[i] # self attention __magic_name__ = layer.attention.self __magic_name__ = check_and_map_params( self_attn.key.bias.data , F'encoder.transformer_cells.{i}.attention_cell.proj_key.bias' ) __magic_name__ = check_and_map_params( self_attn.key.weight.data , F'encoder.transformer_cells.{i}.attention_cell.proj_key.weight' ) __magic_name__ = check_and_map_params( self_attn.query.bias.data , F'encoder.transformer_cells.{i}.attention_cell.proj_query.bias' ) __magic_name__ = check_and_map_params( self_attn.query.weight.data , F'encoder.transformer_cells.{i}.attention_cell.proj_query.weight' ) __magic_name__ = check_and_map_params( self_attn.value.bias.data , F'encoder.transformer_cells.{i}.attention_cell.proj_value.bias' ) __magic_name__ = check_and_map_params( self_attn.value.weight.data , F'encoder.transformer_cells.{i}.attention_cell.proj_value.weight' ) # self attention output __magic_name__ = layer.attention.output __magic_name__ = check_and_map_params( self_output.dense.bias , F'encoder.transformer_cells.{i}.proj.bias' ) __magic_name__ = check_and_map_params( self_output.dense.weight , F'encoder.transformer_cells.{i}.proj.weight' ) __magic_name__ = check_and_map_params( self_output.LayerNorm.bias , F'encoder.transformer_cells.{i}.layer_norm.beta' ) __magic_name__ = check_and_map_params( self_output.LayerNorm.weight , F'encoder.transformer_cells.{i}.layer_norm.gamma' ) # intermediate __magic_name__ = layer.intermediate __magic_name__ = check_and_map_params( intermediate.dense.bias , F'encoder.transformer_cells.{i}.ffn.ffn_1.bias' ) __magic_name__ = check_and_map_params( intermediate.dense.weight , F'encoder.transformer_cells.{i}.ffn.ffn_1.weight' ) # output __magic_name__ = layer.output __magic_name__ = check_and_map_params( bert_output.dense.bias , F'encoder.transformer_cells.{i}.ffn.ffn_2.bias' ) __magic_name__ = check_and_map_params( bert_output.dense.weight , F'encoder.transformer_cells.{i}.ffn.ffn_2.weight' ) __magic_name__ = check_and_map_params( bert_output.LayerNorm.bias , F'encoder.transformer_cells.{i}.ffn.layer_norm.beta' ) __magic_name__ = check_and_map_params( bert_output.LayerNorm.weight , F'encoder.transformer_cells.{i}.ffn.layer_norm.gamma' ) # Save space and energy 🎄 hf_bort_model.half() # Compare output of both models __magic_name__ = RobertaTokenizer.from_pretrained("roberta-base" ) __magic_name__ = tokenizer.encode_plus(lowerCamelCase_ )["input_ids"] # Get gluon output __magic_name__ = mx.nd.array([input_ids] ) __magic_name__ = original_bort(inputs=lowerCamelCase_ , token_types=[] ) # Get Transformer output (save and reload model again) hf_bort_model.save_pretrained(lowerCamelCase_ ) __magic_name__ = BertModel.from_pretrained(lowerCamelCase_ ) hf_bort_model.eval() __magic_name__ = tokenizer.encode_plus(lowerCamelCase_ , return_tensors="pt" ) __magic_name__ = hf_bort_model(**lowerCamelCase_ )[0] __magic_name__ = output_gluon[0].asnumpy() __magic_name__ = output_hf[0].detach().numpy() __magic_name__ = np.max(np.abs(hf_layer - gluon_layer ) ).item() __magic_name__ = np.allclose(lowerCamelCase_ , lowerCamelCase_ , atol=1e-3 ) if success: print("✔️ Both model do output the same tensors" ) else: print("❌ Both model do **NOT** output the same tensors" ) print("Absolute difference is:" , lowerCamelCase_ ) if __name__ == "__main__": __magic_name__ : int =argparse.ArgumentParser() # Required parameters parser.add_argument( '--bort_checkpoint_path', default=None, type=str, required=True, help='Path the official Bort params file.' ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) __magic_name__ : Optional[Any] =parser.parse_args() convert_bort_checkpoint_to_pytorch(args.bort_checkpoint_path, args.pytorch_dump_folder_path)
664
0
'''simple docstring''' def _lowerCAmelCase ( __snake_case : int = 50 ) -> int: __A : Optional[Any] = [1] * (length + 1) for row_length in range(length + 1 ): for tile_length in range(2 , 5 ): for tile_start in range(row_length - tile_length + 1 ): ways_number[row_length] += ways_number[ row_length - tile_start - tile_length ] return ways_number[length] if __name__ == "__main__": print(f"""{solution() = }""")
8
'''simple docstring''' def __snake_case ( lowerCamelCase_ : int , lowerCamelCase_ : int ): '''simple docstring''' if a < 0 or b < 0: raise ValueError("the value of both inputs must be positive" ) __magic_name__ = str(bin(lowerCamelCase_ ) )[2:] # remove the leading "0b" __magic_name__ = str(bin(lowerCamelCase_ ) )[2:] # remove the leading "0b" __magic_name__ = max(len(lowerCamelCase_ ) , len(lowerCamelCase_ ) ) return "0b" + "".join( str(int(char_a == "1" and char_b == "1" ) ) for char_a, char_b in zip(a_binary.zfill(lowerCamelCase_ ) , b_binary.zfill(lowerCamelCase_ ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
664
0
from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = { '''sayakpaul/vit-msn-base''': '''https://huggingface.co/sayakpaul/vit-msn-base/resolve/main/config.json''', # See all ViT MSN models at https://huggingface.co/models?filter=vit_msn } class __lowerCAmelCase ( UpperCAmelCase_ ): """simple docstring""" A__ : Optional[Any] = "vit_msn" def __init__( self : Tuple , _snake_case : Any=7_68 , _snake_case : List[str]=12 , _snake_case : Dict=12 , _snake_case : str=30_72 , _snake_case : str="gelu" , _snake_case : Tuple=0.0 , _snake_case : Dict=0.0 , _snake_case : int=0.02 , _snake_case : Any=1E-06 , _snake_case : str=2_24 , _snake_case : List[str]=16 , _snake_case : Optional[int]=3 , _snake_case : Optional[Any]=True , **_snake_case : Dict , ): """simple docstring""" super().__init__(**_snake_case ) A__ = hidden_size A__ = num_hidden_layers A__ = num_attention_heads A__ = intermediate_size A__ = hidden_act A__ = hidden_dropout_prob A__ = attention_probs_dropout_prob A__ = initializer_range A__ = layer_norm_eps A__ = image_size A__ = patch_size A__ = num_channels A__ = qkv_bias
9
'''simple docstring''' import functools import logging import os import sys import threading from logging import ( CRITICAL, # NOQA DEBUG, # NOQA ERROR, # NOQA FATAL, # NOQA INFO, # NOQA NOTSET, # NOQA WARN, # NOQA WARNING, # NOQA ) from typing import Optional import huggingface_hub.utils as hf_hub_utils from tqdm import auto as tqdm_lib __magic_name__ : Tuple =threading.Lock() __magic_name__ : Optional[logging.Handler] =None __magic_name__ : List[str] ={ 'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'critical': logging.CRITICAL, } __magic_name__ : str =logging.WARNING __magic_name__ : Any =True def __snake_case ( ): '''simple docstring''' __magic_name__ = os.getenv("TRANSFORMERS_VERBOSITY" , lowerCamelCase_ ) if env_level_str: if env_level_str in log_levels: return log_levels[env_level_str] else: logging.getLogger().warning( F'Unknown option TRANSFORMERS_VERBOSITY={env_level_str}, ' F'has to be one of: { ", ".join(log_levels.keys() ) }' ) return _default_log_level def __snake_case ( ): '''simple docstring''' return __name__.split("." )[0] def __snake_case ( ): '''simple docstring''' return logging.getLogger(_get_library_name() ) def __snake_case ( ): '''simple docstring''' global _default_handler with _lock: if _default_handler: # This library has already configured the library root logger. return __magic_name__ = logging.StreamHandler() # Set sys.stderr as stream. __magic_name__ = sys.stderr.flush # Apply our default configuration to the library root logger. __magic_name__ = _get_library_root_logger() library_root_logger.addHandler(_default_handler ) library_root_logger.setLevel(_get_default_logging_level() ) __magic_name__ = False def __snake_case ( ): '''simple docstring''' global _default_handler with _lock: if not _default_handler: return __magic_name__ = _get_library_root_logger() library_root_logger.removeHandler(_default_handler ) library_root_logger.setLevel(logging.NOTSET ) __magic_name__ = None def __snake_case ( ): '''simple docstring''' return log_levels def __snake_case ( lowerCamelCase_ : Optional[str] = None ): '''simple docstring''' if name is None: __magic_name__ = _get_library_name() _configure_library_root_logger() return logging.getLogger(lowerCamelCase_ ) def __snake_case ( ): '''simple docstring''' _configure_library_root_logger() return _get_library_root_logger().getEffectiveLevel() def __snake_case ( lowerCamelCase_ : int ): '''simple docstring''' _configure_library_root_logger() _get_library_root_logger().setLevel(lowerCamelCase_ ) def __snake_case ( ): '''simple docstring''' return set_verbosity(lowerCamelCase_ ) def __snake_case ( ): '''simple docstring''' return set_verbosity(lowerCamelCase_ ) def __snake_case ( ): '''simple docstring''' return set_verbosity(lowerCamelCase_ ) def __snake_case ( ): '''simple docstring''' return set_verbosity(lowerCamelCase_ ) def __snake_case ( ): '''simple docstring''' _configure_library_root_logger() assert _default_handler is not None _get_library_root_logger().removeHandler(_default_handler ) def __snake_case ( ): '''simple docstring''' _configure_library_root_logger() assert _default_handler is not None _get_library_root_logger().addHandler(_default_handler ) def __snake_case ( lowerCamelCase_ : logging.Handler ): '''simple docstring''' _configure_library_root_logger() assert handler is not None _get_library_root_logger().addHandler(lowerCamelCase_ ) def __snake_case ( lowerCamelCase_ : logging.Handler ): '''simple docstring''' _configure_library_root_logger() assert handler is not None and handler not in _get_library_root_logger().handlers _get_library_root_logger().removeHandler(lowerCamelCase_ ) def __snake_case ( ): '''simple docstring''' _configure_library_root_logger() __magic_name__ = False def __snake_case ( ): '''simple docstring''' _configure_library_root_logger() __magic_name__ = True def __snake_case ( ): '''simple docstring''' __magic_name__ = _get_library_root_logger().handlers for handler in handlers: __magic_name__ = logging.Formatter("[%(levelname)s|%(filename)s:%(lineno)s] %(asctime)s >> %(message)s" ) handler.setFormatter(lowerCamelCase_ ) def __snake_case ( ): '''simple docstring''' __magic_name__ = _get_library_root_logger().handlers for handler in handlers: handler.setFormatter(lowerCamelCase_ ) def __snake_case ( self : Union[str, Any] , *lowerCamelCase_ : str , **lowerCamelCase_ : Any ): '''simple docstring''' __magic_name__ = os.getenv("TRANSFORMERS_NO_ADVISORY_WARNINGS" , lowerCamelCase_ ) if no_advisory_warnings: return self.warning(*lowerCamelCase_ , **lowerCamelCase_ ) __magic_name__ : int =warning_advice @functools.lru_cache(lowerCamelCase_ ) def __snake_case ( self : Dict , *lowerCamelCase_ : int , **lowerCamelCase_ : int ): '''simple docstring''' self.warning(*lowerCamelCase_ , **lowerCamelCase_ ) __magic_name__ : Optional[int] =warning_once class UpperCamelCase_ : """simple docstring""" def __init__( self : int , *_lowerCamelCase : Tuple , **_lowerCamelCase : Optional[Any] ) -> Any: # pylint: disable=unused-argument __magic_name__ = args[0] if args else None def __iter__( self : int ) -> Tuple: return iter(self._iterator ) def __getattr__( self : List[Any] , _lowerCamelCase : int ) -> List[Any]: def empty_fn(*_lowerCamelCase : List[str] , **_lowerCamelCase : List[str] ): # pylint: disable=unused-argument return return empty_fn def __enter__( self : Optional[Any] ) -> Any: return self def __exit__( self : int , _lowerCamelCase : List[Any] , _lowerCamelCase : List[Any] , _lowerCamelCase : List[str] ) -> Dict: return class UpperCamelCase_ : """simple docstring""" def __call__( self : Any , *_lowerCamelCase : Optional[Any] , **_lowerCamelCase : Any ) -> List[Any]: if _tqdm_active: return tqdm_lib.tqdm(*_lowerCamelCase , **_lowerCamelCase ) else: return EmptyTqdm(*_lowerCamelCase , **_lowerCamelCase ) def __A ( self : Optional[Any] , *_lowerCamelCase : Optional[Any] , **_lowerCamelCase : Dict ) -> Union[str, Any]: __magic_name__ = None if _tqdm_active: return tqdm_lib.tqdm.set_lock(*_lowerCamelCase , **_lowerCamelCase ) def __A ( self : str ) -> Any: if _tqdm_active: return tqdm_lib.tqdm.get_lock() __magic_name__ : List[Any] =_tqdm_cls() def __snake_case ( ): '''simple docstring''' global _tqdm_active return bool(_tqdm_active ) def __snake_case ( ): '''simple docstring''' global _tqdm_active __magic_name__ = True hf_hub_utils.enable_progress_bars() def __snake_case ( ): '''simple docstring''' global _tqdm_active __magic_name__ = False hf_hub_utils.disable_progress_bars()
664
0
from __future__ import annotations import unittest from transformers import DebertaVaConfig, 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 ( TFDebertaVaForMaskedLM, TFDebertaVaForQuestionAnswering, TFDebertaVaForSequenceClassification, TFDebertaVaForTokenClassification, TFDebertaVaModel, ) class lowerCAmelCase_ : def __init__( self : Dict , _A : Optional[Any] , _A : Dict=13 , _A : int=7 , _A : List[str]=True , _A : Optional[int]=True , _A : Union[str, Any]=True , _A : Optional[Any]=True , _A : List[Any]=99 , _A : Any=32 , _A : Union[str, Any]=2 , _A : Optional[int]=4 , _A : int=37 , _A : Any="gelu" , _A : int=0.1 , _A : Dict=0.1 , _A : Any=512 , _A : List[Any]=16 , _A : Tuple=2 , _A : List[Any]=0.02 , _A : List[Any]=False , _A : int=True , _A : Union[str, Any]="None" , _A : Optional[Any]=3 , _A : Dict=4 , _A : Any=None , ): _UpperCamelCase = parent _UpperCamelCase = batch_size _UpperCamelCase = seq_length _UpperCamelCase = is_training _UpperCamelCase = use_input_mask _UpperCamelCase = use_token_type_ids _UpperCamelCase = use_labels _UpperCamelCase = vocab_size _UpperCamelCase = hidden_size _UpperCamelCase = num_hidden_layers _UpperCamelCase = num_attention_heads _UpperCamelCase = intermediate_size _UpperCamelCase = hidden_act _UpperCamelCase = hidden_dropout_prob _UpperCamelCase = attention_probs_dropout_prob _UpperCamelCase = max_position_embeddings _UpperCamelCase = type_vocab_size _UpperCamelCase = type_sequence_label_size _UpperCamelCase = initializer_range _UpperCamelCase = num_labels _UpperCamelCase = num_choices _UpperCamelCase = relative_attention _UpperCamelCase = position_biased_input _UpperCamelCase = pos_att_type _UpperCamelCase = scope def UpperCamelCase_ ( self : Dict ): _UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _UpperCamelCase = None if self.use_input_mask: _UpperCamelCase = random_attention_mask([self.batch_size, self.seq_length] ) _UpperCamelCase = None if self.use_token_type_ids: _UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _UpperCamelCase = None _UpperCamelCase = None _UpperCamelCase = None if self.use_labels: _UpperCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _UpperCamelCase = DebertaVaConfig( 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 , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , initializer_range=self.initializer_range , return_dict=_A , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCamelCase_ ( self : List[str] , _A : Optional[Any] , _A : Tuple , _A : Optional[Any] , _A : str , _A : str , _A : Optional[Any] , _A : Dict ): _UpperCamelCase = TFDebertaVaModel(config=_A ) _UpperCamelCase = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} _UpperCamelCase = [input_ids, input_mask] _UpperCamelCase = model(_A ) _UpperCamelCase = model(_A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCamelCase_ ( self : Optional[Any] , _A : int , _A : List[str] , _A : str , _A : Tuple , _A : List[Any] , _A : Dict , _A : Union[str, Any] ): _UpperCamelCase = TFDebertaVaForMaskedLM(config=_A ) _UpperCamelCase = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } _UpperCamelCase = model(_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCamelCase_ ( self : int , _A : str , _A : str , _A : Union[str, Any] , _A : int , _A : Optional[Any] , _A : str , _A : Dict ): _UpperCamelCase = self.num_labels _UpperCamelCase = TFDebertaVaForSequenceClassification(config=_A ) _UpperCamelCase = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } _UpperCamelCase = model(_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCamelCase_ ( self : List[Any] , _A : List[str] , _A : Tuple , _A : int , _A : int , _A : Tuple , _A : Tuple , _A : int ): _UpperCamelCase = self.num_labels _UpperCamelCase = TFDebertaVaForTokenClassification(config=_A ) _UpperCamelCase = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } _UpperCamelCase = model(_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCamelCase_ ( self : Dict , _A : Any , _A : Union[str, Any] , _A : List[str] , _A : Dict , _A : Tuple , _A : Any , _A : Union[str, Any] ): _UpperCamelCase = TFDebertaVaForQuestionAnswering(config=_A ) _UpperCamelCase = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } _UpperCamelCase = model(_A ) 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] ): _UpperCamelCase = self.prepare_config_and_inputs() ( ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ) = config_and_inputs _UpperCamelCase = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_tf class lowerCAmelCase_ ( __lowercase, __lowercase, unittest.TestCase ): UpperCAmelCase = ( ( TFDebertaVaModel, TFDebertaVaForMaskedLM, TFDebertaVaForQuestionAnswering, TFDebertaVaForSequenceClassification, TFDebertaVaForTokenClassification, ) if is_tf_available() else () ) UpperCAmelCase = ( { "feature-extraction": TFDebertaVaModel, "fill-mask": TFDebertaVaForMaskedLM, "question-answering": TFDebertaVaForQuestionAnswering, "text-classification": TFDebertaVaForSequenceClassification, "token-classification": TFDebertaVaForTokenClassification, "zero-shot": TFDebertaVaForSequenceClassification, } if is_tf_available() else {} ) UpperCAmelCase = False UpperCAmelCase = False def UpperCamelCase_ ( self : Tuple ): _UpperCamelCase = TFDebertaVaModelTester(self ) _UpperCamelCase = ConfigTester(self , config_class=_A , hidden_size=37 ) def UpperCamelCase_ ( self : Dict ): self.config_tester.run_common_tests() def UpperCamelCase_ ( self : Optional[Any] ): _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_A ) def UpperCamelCase_ ( self : Dict ): _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_A ) def UpperCamelCase_ ( self : Dict ): _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*_A ) def UpperCamelCase_ ( self : Tuple ): _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*_A ) def UpperCamelCase_ ( self : Optional[Any] ): _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_A ) @slow def UpperCamelCase_ ( self : int ): _UpperCamelCase = TFDebertaVaModel.from_pretrained('''kamalkraj/deberta-v2-xlarge''' ) self.assertIsNotNone(_A ) @require_tf class lowerCAmelCase_ ( unittest.TestCase ): @unittest.skip(reason='''Model not available yet''' ) def UpperCamelCase_ ( self : int ): pass @slow def UpperCamelCase_ ( self : List[str] ): _UpperCamelCase = TFDebertaVaModel.from_pretrained('''kamalkraj/deberta-v2-xlarge''' ) _UpperCamelCase = tf.constant([[0, 3_1414, 232, 328, 740, 1140, 1_2695, 69, 4_6078, 1588, 2]] ) _UpperCamelCase = tf.constant([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) _UpperCamelCase = model(_A , attention_mask=_A )[0] _UpperCamelCase = tf.constant( [[[0.2356, 0.1948, 0.0369], [-0.1063, 0.3586, -0.5152], [-0.6399, -0.0259, -0.2525]]] ) tf.debugging.assert_near(output[:, 1:4, 1:4] , _A , atol=1e-4 )
10
'''simple docstring''' from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __magic_name__ : Union[str, Any] ={'configuration_focalnet': ['FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP', 'FocalNetConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ : str =[ 'FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST', 'FocalNetForImageClassification', 'FocalNetForMaskedImageModeling', 'FocalNetBackbone', 'FocalNetModel', 'FocalNetPreTrainedModel', ] if TYPE_CHECKING: from .configuration_focalnet import FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FocalNetConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_focalnet import ( FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST, FocalNetBackbone, FocalNetForImageClassification, FocalNetForMaskedImageModeling, FocalNetModel, FocalNetPreTrainedModel, ) else: import sys __magic_name__ : List[Any] =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
664
0
'''simple docstring''' # Lint as: python3 import sys from collections.abc import Mapping from typing import TYPE_CHECKING, Dict, Optional import numpy as np import pyarrow as pa from .. import config from ..utils.logging import get_logger from ..utils.py_utils import map_nested from .formatting import TensorFormatter if TYPE_CHECKING: import jax import jaxlib lowercase_ = get_logger() lowercase_ = None class __A ( TensorFormatter[Mapping, 'jax.Array', Mapping] ): '''simple docstring''' def __init__(self , A=None , A=None , **A ) -> List[str]: """simple docstring""" super().__init__(features=A ) import jax from jaxlib.xla_client import Device if isinstance(A , A ): raise ValueError( f'''Expected {device} to be a `str` not {type(A )}, as `jaxlib.xla_extension.Device` ''' '''is not serializable neither with `pickle` nor with `dill`. Instead you can surround ''' '''the device with `str()` to get its string identifier that will be internally mapped ''' '''to the actual `jaxlib.xla_extension.Device`.''' ) _a = device if isinstance(A , A ) else str(jax.devices()[0] ) # using global variable since `jaxlib.xla_extension.Device` is not serializable neither # with `pickle` nor with `dill`, so we need to use a global variable instead global DEVICE_MAPPING if DEVICE_MAPPING is None: _a = self._map_devices_to_str() if self.device not in list(DEVICE_MAPPING.keys() ): logger.warning( f'''Device with string identifier {self.device} not listed among the available ''' f'''devices: {list(DEVICE_MAPPING.keys() )}, so falling back to the default ''' f'''device: {str(jax.devices()[0] )}.''' ) _a = str(jax.devices()[0] ) _a = jnp_array_kwargs @staticmethod def a__ () -> Dict[str, "jaxlib.xla_extension.Device"]: """simple docstring""" import jax return {str(A ): device for device in jax.devices()} def a__ (self , A ) -> int: """simple docstring""" import jax import jax.numpy as jnp if isinstance(A , A ) and column: if all( isinstance(A , jax.Array ) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column ): return jnp.stack(A , axis=0 ) return column def a__ (self , A ) -> str: """simple docstring""" import jax import jax.numpy as jnp if isinstance(A , (str, bytes, type(A )) ): return value elif isinstance(A , (np.character, np.ndarray) ) and np.issubdtype(value.dtype , np.character ): return value.tolist() _a = {} if isinstance(A , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.integer ): # the default int precision depends on the jax config # see https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#double-64bit-precision if jax.config.jax_enable_xaa: _a = {'''dtype''': jnp.intaa} else: _a = {'''dtype''': jnp.intaa} elif isinstance(A , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.floating ): _a = {'''dtype''': jnp.floataa} elif config.PIL_AVAILABLE and "PIL" in sys.modules: import PIL.Image if isinstance(A , PIL.Image.Image ): _a = np.asarray(A ) # using global variable since `jaxlib.xla_extension.Device` is not serializable neither # with `pickle` nor with `dill`, so we need to use a global variable instead global DEVICE_MAPPING if DEVICE_MAPPING is None: _a = self._map_devices_to_str() with jax.default_device(DEVICE_MAPPING[self.device] ): # calling jnp.array on a np.ndarray does copy the data # see https://github.com/google/jax/issues/4486 return jnp.array(A , **{**default_dtype, **self.jnp_array_kwargs} ) def a__ (self , A ) -> Optional[int]: """simple docstring""" import jax # support for torch, tf, jax etc. if config.TORCH_AVAILABLE and "torch" in sys.modules: import torch if isinstance(A , torch.Tensor ): return self._tensorize(data_struct.detach().cpu().numpy()[()] ) if hasattr(A , '''__array__''' ) and not isinstance(A , jax.Array ): _a = data_struct.__array__() # support for nested types like struct of list of struct if isinstance(A , np.ndarray ): if data_struct.dtype == object: # jax arrays cannot be instantied from an array of objects return self._consolidate([self.recursive_tensorize(A ) for substruct in data_struct] ) elif isinstance(A , (list, tuple) ): return self._consolidate([self.recursive_tensorize(A ) for substruct in data_struct] ) return self._tensorize(A ) def a__ (self , A ) -> Dict: """simple docstring""" return map_nested(self._recursive_tensorize , A , map_list=A ) def a__ (self , A ) -> Mapping: """simple docstring""" _a = self.numpy_arrow_extractor().extract_row(A ) _a = self.python_features_decoder.decode_row(A ) return self.recursive_tensorize(A ) def a__ (self , A ) -> "jax.Array": """simple docstring""" _a = self.numpy_arrow_extractor().extract_column(A ) _a = self.python_features_decoder.decode_column(A , pa_table.column_names[0] ) _a = self.recursive_tensorize(A ) _a = self._consolidate(A ) return column def a__ (self , A ) -> Mapping: """simple docstring""" _a = self.numpy_arrow_extractor().extract_batch(A ) _a = self.python_features_decoder.decode_batch(A ) _a = self.recursive_tensorize(A ) for column_name in batch: _a = self._consolidate(batch[column_name] ) return batch
11
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) __magic_name__ : Optional[Any] ={ 'configuration_longformer': [ 'LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LongformerConfig', 'LongformerOnnxConfig', ], 'tokenization_longformer': ['LongformerTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ : int =['LongformerTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ : Dict =[ 'LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'LongformerForMaskedLM', 'LongformerForMultipleChoice', 'LongformerForQuestionAnswering', 'LongformerForSequenceClassification', 'LongformerForTokenClassification', 'LongformerModel', 'LongformerPreTrainedModel', 'LongformerSelfAttention', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ : Tuple =[ 'TF_LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFLongformerForMaskedLM', 'TFLongformerForMultipleChoice', 'TFLongformerForQuestionAnswering', 'TFLongformerForSequenceClassification', 'TFLongformerForTokenClassification', 'TFLongformerModel', 'TFLongformerPreTrainedModel', 'TFLongformerSelfAttention', ] if TYPE_CHECKING: from .configuration_longformer import ( LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, LongformerConfig, LongformerOnnxConfig, ) from .tokenization_longformer import LongformerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_longformer_fast import LongformerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_longformer import ( LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, LongformerForMaskedLM, LongformerForMultipleChoice, LongformerForQuestionAnswering, LongformerForSequenceClassification, LongformerForTokenClassification, LongformerModel, LongformerPreTrainedModel, LongformerSelfAttention, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_longformer import ( TF_LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFLongformerForMaskedLM, TFLongformerForMultipleChoice, TFLongformerForQuestionAnswering, TFLongformerForSequenceClassification, TFLongformerForTokenClassification, TFLongformerModel, TFLongformerPreTrainedModel, TFLongformerSelfAttention, ) else: import sys __magic_name__ : int =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
664
0
from __future__ import annotations from typing import TypedDict class _snake_case ( UpperCAmelCase_ ): __lowerCAmelCase : str __lowerCAmelCase : int def UpperCamelCase ( lowercase_ ) -> list[str]: '''simple docstring''' if not isinstance(lowercase_ , lowercase_ ): raise TypeError("""The parameter s type must be str.""" ) return [s[i:] + s[:i] for i in range(len(lowercase_ ) )] def UpperCamelCase ( lowercase_ ) -> BWTTransformDict: '''simple docstring''' if not isinstance(lowercase_ , lowercase_ ): raise TypeError("""The parameter s type must be str.""" ) if not s: raise ValueError("""The parameter s must not be empty.""" ) lowercase__ : List[str] = all_rotations(lowercase_ ) rotations.sort() # sort the list of rotations in alphabetically order # make a string composed of the last char of each rotation lowercase__ : BWTTransformDict = { "bwt_string": "".join([word[-1] for word in rotations] ), "idx_original_string": rotations.index(lowercase_ ), } return response def UpperCamelCase ( lowercase_ , lowercase_ ) -> str: '''simple docstring''' if not isinstance(lowercase_ , lowercase_ ): raise TypeError("""The parameter bwt_string type must be str.""" ) if not bwt_string: raise ValueError("""The parameter bwt_string must not be empty.""" ) try: lowercase__ : Optional[Any] = int(lowercase_ ) except ValueError: raise TypeError( """The parameter idx_original_string type must be int or passive""" """ of cast to int.""" ) if idx_original_string < 0: raise ValueError("""The parameter idx_original_string must not be lower than 0.""" ) if idx_original_string >= len(lowercase_ ): raise ValueError( """The parameter idx_original_string must be lower than""" """ len(bwt_string).""" ) lowercase__ : str = [""""""] * len(lowercase_ ) for _ in range(len(lowercase_ ) ): for i in range(len(lowercase_ ) ): lowercase__ : List[Any] = bwt_string[i] + ordered_rotations[i] ordered_rotations.sort() return ordered_rotations[idx_original_string] if __name__ == "__main__": lowerCamelCase__ : Tuple = """Provide a string that I will generate its BWT transform: """ lowerCamelCase__ : Dict = input(entry_msg).strip() lowerCamelCase__ : int = bwt_transform(s) print( f'''Burrows Wheeler transform for string \'{s}\' results ''' f'''in \'{result["bwt_string"]}\'''' ) lowerCamelCase__ : List[str] = reverse_bwt(result["""bwt_string"""], result["""idx_original_string"""]) print( f'''Reversing Burrows Wheeler transform for entry \'{result["bwt_string"]}\' ''' f'''we get original string \'{original_string}\'''' )
12
'''simple docstring''' import PIL.Image import PIL.ImageOps from packaging import version from PIL import Image if version.parse(version.parse(PIL.__version__).base_version) >= version.parse('9.1.0'): __magic_name__ : str ={ 'linear': PIL.Image.Resampling.BILINEAR, 'bilinear': PIL.Image.Resampling.BILINEAR, 'bicubic': PIL.Image.Resampling.BICUBIC, 'lanczos': PIL.Image.Resampling.LANCZOS, 'nearest': PIL.Image.Resampling.NEAREST, } else: __magic_name__ : Tuple ={ 'linear': PIL.Image.LINEAR, 'bilinear': PIL.Image.BILINEAR, 'bicubic': PIL.Image.BICUBIC, 'lanczos': PIL.Image.LANCZOS, 'nearest': PIL.Image.NEAREST, } def __snake_case ( lowerCamelCase_ : Optional[Any] ): '''simple docstring''' __magic_name__ = (images / 2 + 0.5).clamp(0 , 1 ) __magic_name__ = images.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() __magic_name__ = numpy_to_pil(lowerCamelCase_ ) return images def __snake_case ( lowerCamelCase_ : Optional[Any] ): '''simple docstring''' if images.ndim == 3: __magic_name__ = images[None, ...] __magic_name__ = (images * 255).round().astype("uint8" ) if images.shape[-1] == 1: # special case for grayscale (single channel) images __magic_name__ = [Image.fromarray(image.squeeze() , mode="L" ) for image in images] else: __magic_name__ = [Image.fromarray(lowerCamelCase_ ) for image in images] return pil_images
664
0
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_distilbert import DistilBertTokenizer A__ : List[str] = logging.get_logger(__name__) A__ : Optional[Any] = {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""} A__ : Any = { """vocab_file""": { """distilbert-base-uncased""": """https://huggingface.co/distilbert-base-uncased/resolve/main/vocab.txt""", """distilbert-base-uncased-distilled-squad""": ( """https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/vocab.txt""" ), """distilbert-base-cased""": """https://huggingface.co/distilbert-base-cased/resolve/main/vocab.txt""", """distilbert-base-cased-distilled-squad""": ( """https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/vocab.txt""" ), """distilbert-base-german-cased""": """https://huggingface.co/distilbert-base-german-cased/resolve/main/vocab.txt""", """distilbert-base-multilingual-cased""": ( """https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/vocab.txt""" ), }, """tokenizer_file""": { """distilbert-base-uncased""": """https://huggingface.co/distilbert-base-uncased/resolve/main/tokenizer.json""", """distilbert-base-uncased-distilled-squad""": ( """https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/tokenizer.json""" ), """distilbert-base-cased""": """https://huggingface.co/distilbert-base-cased/resolve/main/tokenizer.json""", """distilbert-base-cased-distilled-squad""": ( """https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/tokenizer.json""" ), """distilbert-base-german-cased""": ( """https://huggingface.co/distilbert-base-german-cased/resolve/main/tokenizer.json""" ), """distilbert-base-multilingual-cased""": ( """https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/tokenizer.json""" ), }, } A__ : str = { """distilbert-base-uncased""": 512, """distilbert-base-uncased-distilled-squad""": 512, """distilbert-base-cased""": 512, """distilbert-base-cased-distilled-squad""": 512, """distilbert-base-german-cased""": 512, """distilbert-base-multilingual-cased""": 512, } A__ : Any = { """distilbert-base-uncased""": {"""do_lower_case""": True}, """distilbert-base-uncased-distilled-squad""": {"""do_lower_case""": True}, """distilbert-base-cased""": {"""do_lower_case""": False}, """distilbert-base-cased-distilled-squad""": {"""do_lower_case""": False}, """distilbert-base-german-cased""": {"""do_lower_case""": False}, """distilbert-base-multilingual-cased""": {"""do_lower_case""": False}, } class UpperCAmelCase_ (_UpperCAmelCase ): """simple docstring""" lowerCamelCase : List[str] = VOCAB_FILES_NAMES lowerCamelCase : Dict = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase : Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase : Any = PRETRAINED_INIT_CONFIGURATION lowerCamelCase : Any = ['input_ids', 'attention_mask'] lowerCamelCase : Optional[Any] = DistilBertTokenizer def __init__( self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_="[UNK]" , SCREAMING_SNAKE_CASE_="[SEP]" , SCREAMING_SNAKE_CASE_="[PAD]" , SCREAMING_SNAKE_CASE_="[CLS]" , SCREAMING_SNAKE_CASE_="[MASK]" , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ , ) -> Union[str, Any]: super().__init__( SCREAMING_SNAKE_CASE_ , tokenizer_file=SCREAMING_SNAKE_CASE_ , do_lower_case=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_ , tokenize_chinese_chars=SCREAMING_SNAKE_CASE_ , strip_accents=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) __lowerCamelCase : List[Any] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('lowercase' , SCREAMING_SNAKE_CASE_ ) != do_lower_case or normalizer_state.get('strip_accents' , SCREAMING_SNAKE_CASE_ ) != strip_accents or normalizer_state.get('handle_chinese_chars' , SCREAMING_SNAKE_CASE_ ) != tokenize_chinese_chars ): __lowerCamelCase : List[Any] = getattr(SCREAMING_SNAKE_CASE_ , normalizer_state.pop('type' ) ) __lowerCamelCase : Optional[Any] = do_lower_case __lowerCamelCase : Dict = strip_accents __lowerCamelCase : Optional[Any] = tokenize_chinese_chars __lowerCamelCase : Tuple = normalizer_class(**SCREAMING_SNAKE_CASE_ ) __lowerCamelCase : Optional[int] = do_lower_case def lowercase_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None ) -> Any: __lowerCamelCase : Optional[int] = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def lowercase_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ) -> List[int]: __lowerCamelCase : Dict = [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] def lowercase_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ) -> Tuple[str]: __lowerCamelCase : List[Any] = self._tokenizer.model.save(SCREAMING_SNAKE_CASE_ , name=SCREAMING_SNAKE_CASE_ ) return tuple(SCREAMING_SNAKE_CASE_ )
13
'''simple docstring''' from typing import Dict import numpy as np from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException if is_tf_available(): import tensorflow as tf from ..tf_utils import stable_softmax if is_torch_available(): import torch __magic_name__ : Optional[Any] =logging.get_logger(__name__) @add_end_docstrings( A , r''' top_k (`int`, defaults to 5): The number of predictions to return. targets (`str` or `List[str]`, *optional*): When passed, the model will limit the scores to the passed targets instead of looking up in the whole vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting token will be used (with a warning, and that might be slower). ''' , ) class UpperCamelCase_ ( A ): """simple docstring""" def __A ( self : Any , _lowerCamelCase : GenericTensor ) -> np.ndarray: if self.framework == "tf": __magic_name__ = tf.where(input_ids == self.tokenizer.mask_token_id ).numpy() elif self.framework == "pt": __magic_name__ = torch.nonzero(input_ids == self.tokenizer.mask_token_id , as_tuple=_lowerCamelCase ) else: raise ValueError("Unsupported framework" ) return masked_index def __A ( self : str , _lowerCamelCase : GenericTensor ) -> np.ndarray: __magic_name__ = self.get_masked_index(_lowerCamelCase ) __magic_name__ = np.prod(masked_index.shape ) if numel < 1: raise PipelineException( "fill-mask" , self.model.base_model_prefix , f'No mask_token ({self.tokenizer.mask_token}) found on the input' , ) def __A ( self : int , _lowerCamelCase : GenericTensor ) -> Any: if isinstance(_lowerCamelCase , _lowerCamelCase ): for model_input in model_inputs: self._ensure_exactly_one_mask_token(model_input["input_ids"][0] ) else: for input_ids in model_inputs["input_ids"]: self._ensure_exactly_one_mask_token(_lowerCamelCase ) def __A ( self : List[Any] , _lowerCamelCase : str , _lowerCamelCase : Any=None , **_lowerCamelCase : List[str] ) -> Dict[str, GenericTensor]: if return_tensors is None: __magic_name__ = self.framework __magic_name__ = self.tokenizer(_lowerCamelCase , return_tensors=_lowerCamelCase ) self.ensure_exactly_one_mask_token(_lowerCamelCase ) return model_inputs def __A ( self : List[str] , _lowerCamelCase : int ) -> List[Any]: __magic_name__ = self.model(**_lowerCamelCase ) __magic_name__ = model_inputs["input_ids"] return model_outputs def __A ( self : Tuple , _lowerCamelCase : List[str] , _lowerCamelCase : List[Any]=5 , _lowerCamelCase : Dict=None ) -> Dict: # Cap top_k if there are targets if target_ids is not None and target_ids.shape[0] < top_k: __magic_name__ = target_ids.shape[0] __magic_name__ = model_outputs["input_ids"][0] __magic_name__ = model_outputs["logits"] if self.framework == "tf": __magic_name__ = tf.where(input_ids == self.tokenizer.mask_token_id ).numpy()[:, 0] __magic_name__ = outputs.numpy() __magic_name__ = outputs[0, masked_index, :] __magic_name__ = stable_softmax(_lowerCamelCase , axis=-1 ) if target_ids is not None: __magic_name__ = tf.gather_nd(tf.squeeze(_lowerCamelCase , 0 ) , target_ids.reshape(-1 , 1 ) ) __magic_name__ = tf.expand_dims(_lowerCamelCase , 0 ) __magic_name__ = tf.math.top_k(_lowerCamelCase , k=_lowerCamelCase ) __magic_name__ , __magic_name__ = topk.values.numpy(), topk.indices.numpy() else: __magic_name__ = torch.nonzero(input_ids == self.tokenizer.mask_token_id , as_tuple=_lowerCamelCase ).squeeze(-1 ) # Fill mask pipeline supports only one ${mask_token} per sample __magic_name__ = outputs[0, masked_index, :] __magic_name__ = logits.softmax(dim=-1 ) if target_ids is not None: __magic_name__ = probs[..., target_ids] __magic_name__ , __magic_name__ = probs.topk(_lowerCamelCase ) __magic_name__ = [] __magic_name__ = values.shape[0] == 1 for i, (_values, _predictions) in enumerate(zip(values.tolist() , predictions.tolist() ) ): __magic_name__ = [] for v, p in zip(_values , _predictions ): # Copy is important since we're going to modify this array in place __magic_name__ = input_ids.numpy().copy() if target_ids is not None: __magic_name__ = target_ids[p].tolist() __magic_name__ = p # Filter padding out: __magic_name__ = tokens[np.where(tokens != self.tokenizer.pad_token_id )] # Originally we skip special tokens to give readable output. # For multi masks though, the other [MASK] would be removed otherwise # making the output look odd, so we add them back __magic_name__ = self.tokenizer.decode(_lowerCamelCase , skip_special_tokens=_lowerCamelCase ) __magic_name__ = {"score": v, "token": p, "token_str": self.tokenizer.decode([p] ), "sequence": sequence} row.append(_lowerCamelCase ) result.append(_lowerCamelCase ) if single_mask: return result[0] return result def __A ( self : List[Any] , _lowerCamelCase : Any , _lowerCamelCase : List[Any]=None ) -> List[str]: if isinstance(_lowerCamelCase , _lowerCamelCase ): __magic_name__ = [targets] try: __magic_name__ = self.tokenizer.get_vocab() except Exception: __magic_name__ = {} __magic_name__ = [] for target in targets: __magic_name__ = vocab.get(_lowerCamelCase , _lowerCamelCase ) if id_ is None: __magic_name__ = self.tokenizer( _lowerCamelCase , add_special_tokens=_lowerCamelCase , return_attention_mask=_lowerCamelCase , return_token_type_ids=_lowerCamelCase , max_length=1 , truncation=_lowerCamelCase , )["input_ids"] if len(_lowerCamelCase ) == 0: logger.warning( f'The specified target token `{target}` does not exist in the model vocabulary. ' "We cannot replace it with anything meaningful, ignoring it" ) continue __magic_name__ = input_ids[0] # XXX: If users encounter this pass # it becomes pretty slow, so let's make sure # The warning enables them to fix the input to # get faster performance. logger.warning( f'The specified target token `{target}` does not exist in the model vocabulary. ' f'Replacing with `{self.tokenizer.convert_ids_to_tokens(id_ )}`.' ) target_ids.append(id_ ) __magic_name__ = list(set(_lowerCamelCase ) ) if len(_lowerCamelCase ) == 0: raise ValueError("At least one target must be provided when passed." ) __magic_name__ = np.array(_lowerCamelCase ) return target_ids def __A ( self : Optional[Any] , _lowerCamelCase : Any=None , _lowerCamelCase : int=None ) -> Tuple: __magic_name__ = {} if targets is not None: __magic_name__ = self.get_target_ids(_lowerCamelCase , _lowerCamelCase ) __magic_name__ = target_ids if top_k is not None: __magic_name__ = top_k if self.tokenizer.mask_token_id is None: raise PipelineException( "fill-mask" , self.model.base_model_prefix , "The tokenizer does not define a `mask_token`." ) return {}, {}, postprocess_params def __call__( self : int , _lowerCamelCase : Any , *_lowerCamelCase : str , **_lowerCamelCase : int ) -> Optional[int]: __magic_name__ = super().__call__(_lowerCamelCase , **_lowerCamelCase ) if isinstance(_lowerCamelCase , _lowerCamelCase ) and len(_lowerCamelCase ) == 1: return outputs[0] return outputs
664
0
from __future__ import annotations def __UpperCAmelCase ( __a : list ,__a : int ,__a : int ,__a : int ) -> list: """simple docstring""" _a : List[str] = [] _a , _a : int = input_list[low:mid], input_list[mid : high + 1] while left and right: result.append((left if left[0] <= right[0] else right).pop(0 ) ) _a : Optional[Any] = result + left + right return input_list def __UpperCAmelCase ( __a : list ) -> list: """simple docstring""" if len(__a ) <= 1: return input_list _a : Union[str, Any] = list(__a ) # iteration for two-way merging _a : Any = 2 while p <= len(__a ): # getting low, high and middle value for merge-sort of single list for i in range(0 ,len(__a ) ,__a ): _a : str = i _a : Union[str, Any] = i + p - 1 _a : Any = (low + high + 1) // 2 _a : Tuple = merge(__a ,__a ,__a ,__a ) # final merge of last two parts if p * 2 >= len(__a ): _a : List[Any] = i _a : Any = merge(__a ,0 ,__a ,len(__a ) - 1 ) break p *= 2 return input_list if __name__ == "__main__": a__ = input('''Enter numbers separated by a comma:\n''').strip() if user_input == "": a__ = [] else: a__ = [int(item.strip()) for item in user_input.split(''',''')] print(iter_merge_sort(unsorted))
14
'''simple docstring''' from __future__ import annotations def __snake_case ( lowerCamelCase_ : list[int] , lowerCamelCase_ : int ): '''simple docstring''' if len(lowerCamelCase_ ) < k or k < 0: raise ValueError("Invalid Input" ) __magic_name__ = __magic_name__ = sum(array[:k] ) for i in range(len(lowerCamelCase_ ) - k ): __magic_name__ = current_sum - array[i] + array[i + k] __magic_name__ = max(lowerCamelCase_ , lowerCamelCase_ ) return max_sum if __name__ == "__main__": from doctest import testmod from random import randint testmod() __magic_name__ : List[str] =[randint(-10_00, 10_00) for i in range(1_00)] __magic_name__ : List[str] =randint(0, 1_10) print(F'''The maximum sum of {k} consecutive elements is {max_sum_in_array(array,k)}''')
664
0
import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ConvNextConfig, SegformerImageProcessor, UperNetConfig, UperNetForSemanticSegmentation def UpperCamelCase ( __magic_name__ : List[Any] ) -> Optional[Any]: """simple docstring""" lowercase__ = 384 if "tiny" in model_name: lowercase__ = [3, 3, 9, 3] lowercase__ = [96, 192, 384, 768] if "small" in model_name: lowercase__ = [3, 3, 27, 3] lowercase__ = [96, 192, 384, 768] if "base" in model_name: lowercase__ = [3, 3, 27, 3] lowercase__ = [128, 256, 512, 1024] lowercase__ = 512 if "large" in model_name: lowercase__ = [3, 3, 27, 3] lowercase__ = [192, 384, 768, 1536] lowercase__ = 768 if "xlarge" in model_name: lowercase__ = [3, 3, 27, 3] lowercase__ = [256, 512, 1024, 2048] lowercase__ = 1024 # set label information lowercase__ = 150 lowercase__ = """huggingface/label-files""" lowercase__ = """ade20k-id2label.json""" lowercase__ = json.load(open(hf_hub_download(__magic_name__ , __magic_name__ , repo_type="""dataset""" ) , """r""" ) ) lowercase__ = {int(__magic_name__ ): v for k, v in idalabel.items()} lowercase__ = {v: k for k, v in idalabel.items()} lowercase__ = ConvNextConfig( depths=__magic_name__ , hidden_sizes=__magic_name__ , out_features=["""stage1""", """stage2""", """stage3""", """stage4"""] ) lowercase__ = UperNetConfig( backbone_config=__magic_name__ , auxiliary_in_channels=__magic_name__ , num_labels=__magic_name__ , idalabel=__magic_name__ , labelaid=__magic_name__ , ) return config def UpperCamelCase ( __magic_name__ : Optional[Any] ) -> str: """simple docstring""" lowercase__ = [] # fmt: off # stem rename_keys.append(("""backbone.downsample_layers.0.0.weight""", """backbone.embeddings.patch_embeddings.weight""") ) rename_keys.append(("""backbone.downsample_layers.0.0.bias""", """backbone.embeddings.patch_embeddings.bias""") ) rename_keys.append(("""backbone.downsample_layers.0.1.weight""", """backbone.embeddings.layernorm.weight""") ) rename_keys.append(("""backbone.downsample_layers.0.1.bias""", """backbone.embeddings.layernorm.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.stages.{i}.{j}.gamma''', f'''backbone.encoder.stages.{i}.layers.{j}.layer_scale_parameter''') ) rename_keys.append((f'''backbone.stages.{i}.{j}.depthwise_conv.weight''', f'''backbone.encoder.stages.{i}.layers.{j}.dwconv.weight''') ) rename_keys.append((f'''backbone.stages.{i}.{j}.depthwise_conv.bias''', f'''backbone.encoder.stages.{i}.layers.{j}.dwconv.bias''') ) rename_keys.append((f'''backbone.stages.{i}.{j}.norm.weight''', f'''backbone.encoder.stages.{i}.layers.{j}.layernorm.weight''') ) rename_keys.append((f'''backbone.stages.{i}.{j}.norm.bias''', f'''backbone.encoder.stages.{i}.layers.{j}.layernorm.bias''') ) rename_keys.append((f'''backbone.stages.{i}.{j}.pointwise_conv1.weight''', f'''backbone.encoder.stages.{i}.layers.{j}.pwconv1.weight''') ) rename_keys.append((f'''backbone.stages.{i}.{j}.pointwise_conv1.bias''', f'''backbone.encoder.stages.{i}.layers.{j}.pwconv1.bias''') ) rename_keys.append((f'''backbone.stages.{i}.{j}.pointwise_conv2.weight''', f'''backbone.encoder.stages.{i}.layers.{j}.pwconv2.weight''') ) rename_keys.append((f'''backbone.stages.{i}.{j}.pointwise_conv2.bias''', f'''backbone.encoder.stages.{i}.layers.{j}.pwconv2.bias''') ) if i > 0: rename_keys.append((f'''backbone.downsample_layers.{i}.0.weight''', f'''backbone.encoder.stages.{i}.downsampling_layer.0.weight''') ) rename_keys.append((f'''backbone.downsample_layers.{i}.0.bias''', f'''backbone.encoder.stages.{i}.downsampling_layer.0.bias''') ) rename_keys.append((f'''backbone.downsample_layers.{i}.1.weight''', f'''backbone.encoder.stages.{i}.downsampling_layer.1.weight''') ) rename_keys.append((f'''backbone.downsample_layers.{i}.1.bias''', f'''backbone.encoder.stages.{i}.downsampling_layer.1.bias''') ) rename_keys.append((f'''backbone.norm{i}.weight''', f'''backbone.hidden_states_norms.stage{i+1}.weight''') ) rename_keys.append((f'''backbone.norm{i}.bias''', f'''backbone.hidden_states_norms.stage{i+1}.bias''') ) # decode head rename_keys.extend( [ ("""decode_head.conv_seg.weight""", """decode_head.classifier.weight"""), ("""decode_head.conv_seg.bias""", """decode_head.classifier.bias"""), ("""auxiliary_head.conv_seg.weight""", """auxiliary_head.classifier.weight"""), ("""auxiliary_head.conv_seg.bias""", """auxiliary_head.classifier.bias"""), ] ) # fmt: on return rename_keys def UpperCamelCase ( __magic_name__ : Optional[int] , __magic_name__ : str , __magic_name__ : List[str] ) -> Union[str, Any]: """simple docstring""" lowercase__ = dct.pop(__magic_name__ ) lowercase__ = val def UpperCamelCase ( __magic_name__ : Optional[int] , __magic_name__ : Optional[Any] , __magic_name__ : Union[str, Any] ) -> str: """simple docstring""" lowercase__ = { """upernet-convnext-tiny""": """https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_tiny_fp16_512x512_160k_ade20k/upernet_convnext_tiny_fp16_512x512_160k_ade20k_20220227_124553-cad485de.pth""", """upernet-convnext-small""": """https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_small_fp16_512x512_160k_ade20k/upernet_convnext_small_fp16_512x512_160k_ade20k_20220227_131208-1b1e394f.pth""", """upernet-convnext-base""": """https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_base_fp16_512x512_160k_ade20k/upernet_convnext_base_fp16_512x512_160k_ade20k_20220227_181227-02a24fc6.pth""", """upernet-convnext-large""": """https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_large_fp16_640x640_160k_ade20k/upernet_convnext_large_fp16_640x640_160k_ade20k_20220226_040532-e57aa54d.pth""", """upernet-convnext-xlarge""": """https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_xlarge_fp16_640x640_160k_ade20k/upernet_convnext_xlarge_fp16_640x640_160k_ade20k_20220226_080344-95fc38c2.pth""", } lowercase__ = model_name_to_url[model_name] lowercase__ = torch.hub.load_state_dict_from_url(__magic_name__ , map_location="""cpu""" )["""state_dict"""] lowercase__ = get_upernet_config(__magic_name__ ) lowercase__ = UperNetForSemanticSegmentation(__magic_name__ ) model.eval() # replace "bn" => "batch_norm" for key in state_dict.copy().keys(): lowercase__ = state_dict.pop(__magic_name__ ) if "bn" in key: lowercase__ = key.replace("""bn""" , """batch_norm""" ) lowercase__ = val # rename keys lowercase__ = create_rename_keys(__magic_name__ ) for src, dest in rename_keys: rename_key(__magic_name__ , __magic_name__ , __magic_name__ ) model.load_state_dict(__magic_name__ ) # verify on image lowercase__ = """https://huggingface.co/datasets/hf-internal-testing/fixtures_ade20k/resolve/main/ADE_val_00000001.jpg""" lowercase__ = Image.open(requests.get(__magic_name__ , stream=__magic_name__ ).raw ).convert("""RGB""" ) lowercase__ = SegformerImageProcessor() lowercase__ = processor(__magic_name__ , return_tensors="""pt""" ).pixel_values with torch.no_grad(): lowercase__ = model(__magic_name__ ) if model_name == "upernet-convnext-tiny": lowercase__ = torch.tensor( [[-8.8_1_1_0, -8.8_1_1_0, -8.6_5_2_1], [-8.8_1_1_0, -8.8_1_1_0, -8.6_5_2_1], [-8.7_7_4_6, -8.7_7_4_6, -8.6_1_3_0]] ) elif model_name == "upernet-convnext-small": lowercase__ = torch.tensor( [[-8.8_2_3_6, -8.8_2_3_6, -8.6_7_7_1], [-8.8_2_3_6, -8.8_2_3_6, -8.6_7_7_1], [-8.7_6_3_8, -8.7_6_3_8, -8.6_2_4_0]] ) elif model_name == "upernet-convnext-base": lowercase__ = torch.tensor( [[-8.8_5_5_8, -8.8_5_5_8, -8.6_9_0_5], [-8.8_5_5_8, -8.8_5_5_8, -8.6_9_0_5], [-8.7_6_6_9, -8.7_6_6_9, -8.6_0_2_1]] ) elif model_name == "upernet-convnext-large": lowercase__ = torch.tensor( [[-8.6_6_6_0, -8.6_6_6_0, -8.6_2_1_0], [-8.6_6_6_0, -8.6_6_6_0, -8.6_2_1_0], [-8.6_3_1_0, -8.6_3_1_0, -8.5_9_6_4]] ) elif model_name == "upernet-convnext-xlarge": lowercase__ = torch.tensor( [[-8.4_9_8_0, -8.4_9_8_0, -8.3_9_7_7], [-8.4_9_8_0, -8.4_9_8_0, -8.3_9_7_7], [-8.4_3_7_9, -8.4_3_7_9, -8.3_4_1_2]] ) print("""Logits:""" , outputs.logits[0, 0, :3, :3] ) assert torch.allclose(outputs.logits[0, 0, :3, :3] , __magic_name__ , atol=1E-4 ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: print(f'''Saving model {model_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(__magic_name__ ) print(f'''Saving processor to {pytorch_dump_folder_path}''' ) processor.save_pretrained(__magic_name__ ) if push_to_hub: print(f'''Pushing model and processor for {model_name} to hub''' ) model.push_to_hub(f'''openmmlab/{model_name}''' ) processor.push_to_hub(f'''openmmlab/{model_name}''' ) if __name__ == "__main__": A : Any = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='upernet-convnext-tiny', type=str, choices=[F'upernet-convnext-{size}' for size in ['tiny', 'small', 'base', 'large', 'xlarge']], help='Name of the ConvNext UperNet 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.' ) A : Union[str, Any] = parser.parse_args() convert_upernet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
15
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __magic_name__ : int =logging.get_logger(__name__) __magic_name__ : List[Any] ={} class UpperCamelCase_ ( A ): """simple docstring""" UpperCAmelCase__ : int = '''llama''' UpperCAmelCase__ : Any = ['''past_key_values'''] def __init__( self : List[Any] , _lowerCamelCase : List[Any]=3_20_00 , _lowerCamelCase : Optional[Any]=40_96 , _lowerCamelCase : Tuple=1_10_08 , _lowerCamelCase : List[Any]=32 , _lowerCamelCase : Tuple=32 , _lowerCamelCase : List[str]=None , _lowerCamelCase : str="silu" , _lowerCamelCase : Optional[Any]=20_48 , _lowerCamelCase : Optional[Any]=0.02 , _lowerCamelCase : Union[str, Any]=1e-6 , _lowerCamelCase : Optional[int]=True , _lowerCamelCase : Dict=0 , _lowerCamelCase : int=1 , _lowerCamelCase : str=2 , _lowerCamelCase : List[Any]=1 , _lowerCamelCase : Optional[int]=False , _lowerCamelCase : List[str]=None , **_lowerCamelCase : List[Any] , ) -> Any: __magic_name__ = vocab_size __magic_name__ = max_position_embeddings __magic_name__ = hidden_size __magic_name__ = intermediate_size __magic_name__ = num_hidden_layers __magic_name__ = num_attention_heads # for backward compatibility if num_key_value_heads is None: __magic_name__ = num_attention_heads __magic_name__ = num_key_value_heads __magic_name__ = hidden_act __magic_name__ = initializer_range __magic_name__ = rms_norm_eps __magic_name__ = pretraining_tp __magic_name__ = use_cache __magic_name__ = rope_scaling self._rope_scaling_validation() super().__init__( pad_token_id=_lowerCamelCase , bos_token_id=_lowerCamelCase , eos_token_id=_lowerCamelCase , tie_word_embeddings=_lowerCamelCase , **_lowerCamelCase , ) def __A ( self : Union[str, Any] ) -> List[Any]: if self.rope_scaling is None: return if not isinstance(self.rope_scaling , _lowerCamelCase ) or len(self.rope_scaling ) != 2: raise ValueError( "`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, " f'got {self.rope_scaling}' ) __magic_name__ = self.rope_scaling.get("type" , _lowerCamelCase ) __magic_name__ = self.rope_scaling.get("factor" , _lowerCamelCase ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( f'`rope_scaling`\'s name field must be one of [\'linear\', \'dynamic\'], got {rope_scaling_type}' ) if rope_scaling_factor is None or not isinstance(_lowerCamelCase , _lowerCamelCase ) or rope_scaling_factor <= 1.0: raise ValueError(f'`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}' )
664
0
from __future__ import annotations import inspect import unittest import numpy as np from transformers import ResNetConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFResNetForImageClassification, TFResNetModel from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class _SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : Union[str, Any] , __lowerCamelCase : str , __lowerCamelCase : Optional[Any]=3 , __lowerCamelCase : Any=32 , __lowerCamelCase : Tuple=3 , __lowerCamelCase : Optional[int]=10 , __lowerCamelCase : int=[10, 20, 30, 40] , __lowerCamelCase : str=[1, 1, 2, 1] , __lowerCamelCase : str=True , __lowerCamelCase : Union[str, Any]=True , __lowerCamelCase : List[Any]="relu" , __lowerCamelCase : List[Any]=3 , __lowerCamelCase : Union[str, Any]=None , ): SCREAMING_SNAKE_CASE = parent SCREAMING_SNAKE_CASE = batch_size SCREAMING_SNAKE_CASE = image_size SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = embeddings_size SCREAMING_SNAKE_CASE = hidden_sizes SCREAMING_SNAKE_CASE = depths SCREAMING_SNAKE_CASE = is_training SCREAMING_SNAKE_CASE = use_labels SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = num_labels SCREAMING_SNAKE_CASE = scope SCREAMING_SNAKE_CASE = len(__lowerCamelCase ) def _snake_case ( self : str ): SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE = None if self.use_labels: SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_labels ) SCREAMING_SNAKE_CASE = self.get_config() return config, pixel_values, labels def _snake_case ( self : List[str] ): return ResNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , image_size=self.image_size , ) def _snake_case ( self : Dict , __lowerCamelCase : List[str] , __lowerCamelCase : List[Any] , __lowerCamelCase : Optional[int] ): SCREAMING_SNAKE_CASE = TFResNetModel(config=__lowerCamelCase ) SCREAMING_SNAKE_CASE = model(__lowerCamelCase ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def _snake_case ( self : Optional[int] , __lowerCamelCase : str , __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[int] ): SCREAMING_SNAKE_CASE = self.num_labels SCREAMING_SNAKE_CASE = TFResNetForImageClassification(__lowerCamelCase ) SCREAMING_SNAKE_CASE = model(__lowerCamelCase , labels=__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _snake_case ( self : List[Any] ): SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = config_and_inputs SCREAMING_SNAKE_CASE = {"pixel_values": pixel_values} return config, inputs_dict @require_tf class _SCREAMING_SNAKE_CASE ( __snake_case , __snake_case , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else () lowerCamelCase__ = ( {"feature-extraction": TFResNetModel, "image-classification": TFResNetForImageClassification} if is_tf_available() else {} ) lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False def _snake_case ( self : Any ): SCREAMING_SNAKE_CASE = TFResNetModelTester(self ) SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=__lowerCamelCase , has_text_modality=__lowerCamelCase ) def _snake_case ( self : int ): self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _snake_case ( self : List[str] ): return @unittest.skip(reason="ResNet does not use inputs_embeds" ) def _snake_case ( self : List[str] ): pass @unittest.skip(reason="ResNet does not support input and output embeddings" ) def _snake_case ( self : Any ): pass def _snake_case ( self : Any ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ) SCREAMING_SNAKE_CASE = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE = ["pixel_values"] self.assertListEqual(arg_names[:1] , __lowerCamelCase ) def _snake_case ( self : Optional[int] ): SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCamelCase ) def _snake_case ( self : Any ): def check_hidden_states_output(__lowerCamelCase : Any , __lowerCamelCase : Optional[int] , __lowerCamelCase : Union[str, Any] ): SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ) SCREAMING_SNAKE_CASE = model(**self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) SCREAMING_SNAKE_CASE = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states SCREAMING_SNAKE_CASE = self.model_tester.num_stages self.assertEqual(len(__lowerCamelCase ) , expected_num_stages + 1 ) # ResNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = ["basic", "bottleneck"] for model_class in self.all_model_classes: for layer_type in layers_type: SCREAMING_SNAKE_CASE = layer_type SCREAMING_SNAKE_CASE = True check_hidden_states_output(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE = True check_hidden_states_output(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) def _snake_case ( self : Optional[int] ): SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__lowerCamelCase ) @slow def _snake_case ( self : int ): for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE = TFResNetModel.from_pretrained(__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) def __a ( ): SCREAMING_SNAKE_CASE = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_tf @require_vision class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @cached_property def _snake_case ( self : Optional[int] ): return ( AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def _snake_case ( self : str ): SCREAMING_SNAKE_CASE = TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) SCREAMING_SNAKE_CASE = self.default_image_processor SCREAMING_SNAKE_CASE = prepare_img() SCREAMING_SNAKE_CASE = image_processor(images=__lowerCamelCase , return_tensors="tf" ) # forward pass SCREAMING_SNAKE_CASE = model(**__lowerCamelCase ) # verify the logits SCREAMING_SNAKE_CASE = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , __lowerCamelCase ) SCREAMING_SNAKE_CASE = tf.constant([-11.1_069, -9.7_877, -8.3_777] ) self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , __lowerCamelCase , atol=1e-4 ) )
16
'''simple docstring''' __magic_name__ : Dict =8.3_1_4_4_6_2 # Unit - J mol-1 K-1 def __snake_case ( lowerCamelCase_ : float , lowerCamelCase_ : float , lowerCamelCase_ : float ): '''simple docstring''' if moles < 0 or kelvin < 0 or volume < 0: raise ValueError("Invalid inputs. Enter positive value." ) return moles * kelvin * UNIVERSAL_GAS_CONSTANT / volume def __snake_case ( lowerCamelCase_ : float , lowerCamelCase_ : float , lowerCamelCase_ : float ): '''simple docstring''' if moles < 0 or kelvin < 0 or pressure < 0: raise ValueError("Invalid inputs. Enter positive value." ) return moles * kelvin * UNIVERSAL_GAS_CONSTANT / pressure if __name__ == "__main__": from doctest import testmod testmod()
664
0
from __future__ import annotations import inspect import unittest from typing import List, Tuple from transformers import RegNetConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFRegNetForImageClassification, TFRegNetModel if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class lowerCamelCase_ : def __init__( self : Union[str, Any] , __A : Dict , __A : List[str]=3 , __A : List[Any]=32 , __A : int=3 , __A : str=10 , __A : List[Any]=[10, 20, 30, 40] , __A : Union[str, Any]=[1, 1, 2, 1] , __A : Any=True , __A : Optional[int]=True , __A : int="relu" , __A : Dict=3 , __A : Dict=None , ): __A : Tuple = parent __A : int = batch_size __A : List[str] = image_size __A : Tuple = num_channels __A : Tuple = embeddings_size __A : Optional[Any] = hidden_sizes __A : str = depths __A : Optional[int] = is_training __A : Tuple = use_labels __A : Optional[int] = hidden_act __A : Tuple = num_labels __A : Optional[int] = scope __A : List[Any] = len(__A ) def lowerCAmelCase_ ( self : Dict ): __A : int = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __A : Optional[Any] = None if self.use_labels: __A : List[Any] = ids_tensor([self.batch_size] , self.num_labels ) __A : int = self.get_config() return config, pixel_values, labels def lowerCAmelCase_ ( self : int ): return RegNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , ) def lowerCAmelCase_ ( self : str , __A : Optional[Any] , __A : Tuple , __A : List[str] ): __A : List[Any] = TFRegNetModel(config=__A ) __A : int = model(__A , training=__A ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def lowerCAmelCase_ ( self : Dict , __A : str , __A : Tuple , __A : List[Any] ): __A : Optional[Any] = self.num_labels __A : Optional[int] = TFRegNetForImageClassification(__A ) __A : List[Any] = model(__A , labels=__A , training=__A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCAmelCase_ ( self : str ): __A : int = self.prepare_config_and_inputs() __A , __A , __A : List[Any] = config_and_inputs __A : str = {"""pixel_values""": pixel_values} return config, inputs_dict @require_tf class lowerCamelCase_ ( _lowercase , _lowercase , unittest.TestCase ): _lowercase : Optional[Any] = (TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else () _lowercase : Tuple = ( {'''feature-extraction''': TFRegNetModel, '''image-classification''': TFRegNetForImageClassification} if is_tf_available() else {} ) _lowercase : Union[str, Any] = False _lowercase : Any = False _lowercase : Optional[int] = False _lowercase : Optional[Any] = False _lowercase : Union[str, Any] = False def lowerCAmelCase_ ( self : Dict ): __A : Tuple = TFRegNetModelTester(self ) __A : int = ConfigTester(self , config_class=__A , has_text_modality=__A ) def lowerCAmelCase_ ( self : List[str] ): return @unittest.skip(reason="""RegNet does not use inputs_embeds""" ) def lowerCAmelCase_ ( self : List[Any] ): pass @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices("""GPU""" ) ) == 0 , reason="""TF does not support backprop for grouped convolutions on CPU.""" , ) @slow def lowerCAmelCase_ ( self : Dict ): super().test_keras_fit() @unittest.skip(reason="""RegNet does not support input and output embeddings""" ) def lowerCAmelCase_ ( self : Optional[int] ): pass def lowerCAmelCase_ ( self : str ): __A , __A : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __A : Dict = model_class(__A ) __A : str = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __A : Optional[int] = [*signature.parameters.keys()] __A : Any = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , __A ) def lowerCAmelCase_ ( self : Any ): __A : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__A ) def lowerCAmelCase_ ( self : List[str] ): def check_hidden_states_output(__A : Optional[int] , __A : str , __A : str ): __A : Tuple = model_class(__A ) __A : List[str] = model(**self._prepare_for_class(__A , __A ) , training=__A ) __A : List[Any] = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states __A : int = self.model_tester.num_stages self.assertEqual(len(__A ) , expected_num_stages + 1 ) # RegNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 2, self.model_tester.image_size // 2] , ) __A , __A : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() __A : List[Any] = ["""basic""", """bottleneck"""] for model_class in self.all_model_classes: for layer_type in layers_type: __A : List[Any] = layer_type __A : Optional[int] = True check_hidden_states_output(__A , __A , __A ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __A : str = True check_hidden_states_output(__A , __A , __A ) def lowerCAmelCase_ ( self : Dict ): __A , __A : Any = self.model_tester.prepare_config_and_inputs_for_common() def check_equivalence(__A : int , __A : Any , __A : List[Any] , __A : Any={} ): __A : List[str] = model(__A , return_dict=__A , **__A ) __A : Tuple = model(__A , return_dict=__A , **__A ).to_tuple() def recursive_check(__A : Dict , __A : int ): if isinstance(__A , (List, Tuple) ): for tuple_iterable_value, dict_iterable_value in zip(__A , __A ): recursive_check(__A , __A ) elif tuple_object is None: return else: self.assertTrue( all(tf.equal(__A , __A ) ) , msg=( """Tuple and dict output are not equal. Difference:""" F""" {tf.math.reduce_max(tf.abs(tuple_object - dict_object ) )}""" ) , ) recursive_check(__A , __A ) for model_class in self.all_model_classes: __A : Optional[int] = model_class(__A ) __A : Optional[Any] = self._prepare_for_class(__A , __A ) __A : Tuple = self._prepare_for_class(__A , __A ) check_equivalence(__A , __A , __A ) __A : Dict = self._prepare_for_class(__A , __A , return_labels=__A ) __A : List[Any] = self._prepare_for_class(__A , __A , return_labels=__A ) check_equivalence(__A , __A , __A ) __A : int = self._prepare_for_class(__A , __A ) __A : Optional[int] = self._prepare_for_class(__A , __A ) check_equivalence(__A , __A , __A , {"""output_hidden_states""": True} ) __A : int = self._prepare_for_class(__A , __A , return_labels=__A ) __A : List[Any] = self._prepare_for_class(__A , __A , return_labels=__A ) check_equivalence(__A , __A , __A , {"""output_hidden_states""": True} ) def lowerCAmelCase_ ( self : List[str] ): __A : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__A ) @slow def lowerCAmelCase_ ( self : int ): for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __A : List[str] = TFRegNetModel.from_pretrained(__A ) self.assertIsNotNone(__A ) def __SCREAMING_SNAKE_CASE ( ) -> List[str]: __A : Dict = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_tf @require_vision class lowerCamelCase_ ( unittest.TestCase ): @cached_property def lowerCAmelCase_ ( self : Union[str, Any] ): return ( AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def lowerCAmelCase_ ( self : str ): __A : Union[str, Any] = TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) __A : Tuple = self.default_image_processor __A : str = prepare_img() __A : Optional[int] = image_processor(images=__A , return_tensors="""tf""" ) # forward pass __A : Any = model(**__A , training=__A ) # verify the logits __A : List[str] = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , __A ) __A : List[Any] = tf.constant([-0.4_1_8_0, -1.5_0_5_1, -3.4_8_3_6] ) tf.debugging.assert_near(outputs.logits[0, :3] , __A , atol=1e-4 )
17
'''simple docstring''' import logging import os from typing import List, TextIO, Union from conllu import parse_incr from utils_ner import InputExample, Split, TokenClassificationTask __magic_name__ : List[Any] =logging.getLogger(__name__) class UpperCamelCase_ ( A ): """simple docstring""" def __init__( self : Optional[Any] , _lowerCamelCase : str=-1 ) -> List[str]: # in NER datasets, the last column is usually reserved for NER label __magic_name__ = label_idx def __A ( self : Any , _lowerCamelCase : str , _lowerCamelCase : Union[Split, str] ) -> List[InputExample]: if isinstance(_lowerCamelCase , _lowerCamelCase ): __magic_name__ = mode.value __magic_name__ = os.path.join(_lowerCamelCase , f'{mode}.txt' ) __magic_name__ = 1 __magic_name__ = [] with open(_lowerCamelCase , encoding="utf-8" ) as f: __magic_name__ = [] __magic_name__ = [] for line in f: if line.startswith("-DOCSTART-" ) or line == "" or line == "\n": if words: examples.append(InputExample(guid=f'{mode}-{guid_index}' , words=_lowerCamelCase , labels=_lowerCamelCase ) ) guid_index += 1 __magic_name__ = [] __magic_name__ = [] else: __magic_name__ = line.split(" " ) words.append(splits[0] ) if len(_lowerCamelCase ) > 1: labels.append(splits[self.label_idx].replace("\n" , "" ) ) else: # Examples could have no label for mode = "test" labels.append("O" ) if words: examples.append(InputExample(guid=f'{mode}-{guid_index}' , words=_lowerCamelCase , labels=_lowerCamelCase ) ) return examples def __A ( self : Optional[Any] , _lowerCamelCase : TextIO , _lowerCamelCase : TextIO , _lowerCamelCase : List ) -> Union[str, Any]: __magic_name__ = 0 for line in test_input_reader: if line.startswith("-DOCSTART-" ) or line == "" or line == "\n": writer.write(_lowerCamelCase ) if not preds_list[example_id]: example_id += 1 elif preds_list[example_id]: __magic_name__ = line.split()[0] + " " + preds_list[example_id].pop(0 ) + "\n" writer.write(_lowerCamelCase ) else: logger.warning("Maximum sequence length exceeded: No prediction for '%s'." , line.split()[0] ) def __A ( self : Tuple , _lowerCamelCase : str ) -> List[str]: if path: with open(_lowerCamelCase , "r" ) as f: __magic_name__ = f.read().splitlines() if "O" not in labels: __magic_name__ = ["O"] + labels return labels else: return ["O", "B-MISC", "I-MISC", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC"] class UpperCamelCase_ ( A ): """simple docstring""" def __init__( self : int ) -> str: # in CONLL2003 dataset chunk column is second-to-last super().__init__(label_idx=-2 ) def __A ( self : int , _lowerCamelCase : str ) -> List[str]: if path: with open(_lowerCamelCase , "r" ) as f: __magic_name__ = f.read().splitlines() if "O" not in labels: __magic_name__ = ["O"] + labels return labels else: return [ "O", "B-ADVP", "B-INTJ", "B-LST", "B-PRT", "B-NP", "B-SBAR", "B-VP", "B-ADJP", "B-CONJP", "B-PP", "I-ADVP", "I-INTJ", "I-LST", "I-PRT", "I-NP", "I-SBAR", "I-VP", "I-ADJP", "I-CONJP", "I-PP", ] class UpperCamelCase_ ( A ): """simple docstring""" def __A ( self : List[Any] , _lowerCamelCase : Union[str, Any] , _lowerCamelCase : Union[Split, str] ) -> List[InputExample]: if isinstance(_lowerCamelCase , _lowerCamelCase ): __magic_name__ = mode.value __magic_name__ = os.path.join(_lowerCamelCase , f'{mode}.txt' ) __magic_name__ = 1 __magic_name__ = [] with open(_lowerCamelCase , encoding="utf-8" ) as f: for sentence in parse_incr(_lowerCamelCase ): __magic_name__ = [] __magic_name__ = [] for token in sentence: words.append(token["form"] ) labels.append(token["upos"] ) assert len(_lowerCamelCase ) == len(_lowerCamelCase ) if words: examples.append(InputExample(guid=f'{mode}-{guid_index}' , words=_lowerCamelCase , labels=_lowerCamelCase ) ) guid_index += 1 return examples def __A ( self : Optional[int] , _lowerCamelCase : TextIO , _lowerCamelCase : TextIO , _lowerCamelCase : List ) -> Any: __magic_name__ = 0 for sentence in parse_incr(_lowerCamelCase ): __magic_name__ = preds_list[example_id] __magic_name__ = "" for token in sentence: out += f'{token["form"]} ({token["upos"]}|{s_p.pop(0 )}) ' out += "\n" writer.write(_lowerCamelCase ) example_id += 1 def __A ( self : Dict , _lowerCamelCase : str ) -> List[str]: if path: with open(_lowerCamelCase , "r" ) as f: return f.read().splitlines() else: return [ "ADJ", "ADP", "ADV", "AUX", "CCONJ", "DET", "INTJ", "NOUN", "NUM", "PART", "PRON", "PROPN", "PUNCT", "SCONJ", "SYM", "VERB", "X", ]
664
0
'''simple docstring''' 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() _SCREAMING_SNAKE_CASE = logging.get_logger(__name__) def __a(SCREAMING_SNAKE_CASE_ : Dict ): '''simple docstring''' _lowerCAmelCase = ASTConfig() if "10-10" in model_name: pass elif "speech-commands" in model_name: _lowerCAmelCase = 128 elif "12-12" in model_name: _lowerCAmelCase = 12 _lowerCAmelCase = 12 elif "14-14" in model_name: _lowerCAmelCase = 14 _lowerCAmelCase = 14 elif "16-16" in model_name: _lowerCAmelCase = 16 _lowerCAmelCase = 16 else: raise ValueError("Model not supported" ) _lowerCAmelCase = "huggingface/label-files" if "speech-commands" in model_name: _lowerCAmelCase = 35 _lowerCAmelCase = "speech-commands-v2-id2label.json" else: _lowerCAmelCase = 527 _lowerCAmelCase = "audioset-id2label.json" _lowerCAmelCase = json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , repo_type="dataset" ) , "r" ) ) _lowerCAmelCase = {int(SCREAMING_SNAKE_CASE_ ): v for k, v in idalabel.items()} _lowerCAmelCase = idalabel _lowerCAmelCase = {v: k for k, v in idalabel.items()} return config def __a(SCREAMING_SNAKE_CASE_ : str ): '''simple docstring''' if "module.v" in name: _lowerCAmelCase = name.replace("module.v" , "audio_spectrogram_transformer" ) if "cls_token" in name: _lowerCAmelCase = name.replace("cls_token" , "embeddings.cls_token" ) if "dist_token" in name: _lowerCAmelCase = name.replace("dist_token" , "embeddings.distillation_token" ) if "pos_embed" in name: _lowerCAmelCase = name.replace("pos_embed" , "embeddings.position_embeddings" ) if "patch_embed.proj" in name: _lowerCAmelCase = name.replace("patch_embed.proj" , "embeddings.patch_embeddings.projection" ) # transformer blocks if "blocks" in name: _lowerCAmelCase = name.replace("blocks" , "encoder.layer" ) if "attn.proj" in name: _lowerCAmelCase = name.replace("attn.proj" , "attention.output.dense" ) if "attn" in name: _lowerCAmelCase = name.replace("attn" , "attention.self" ) if "norm1" in name: _lowerCAmelCase = name.replace("norm1" , "layernorm_before" ) if "norm2" in name: _lowerCAmelCase = name.replace("norm2" , "layernorm_after" ) if "mlp.fc1" in name: _lowerCAmelCase = name.replace("mlp.fc1" , "intermediate.dense" ) if "mlp.fc2" in name: _lowerCAmelCase = name.replace("mlp.fc2" , "output.dense" ) # final layernorm if "audio_spectrogram_transformer.norm" in name: _lowerCAmelCase = name.replace("audio_spectrogram_transformer.norm" , "audio_spectrogram_transformer.layernorm" ) # classifier head if "module.mlp_head.0" in name: _lowerCAmelCase = name.replace("module.mlp_head.0" , "classifier.layernorm" ) if "module.mlp_head.1" in name: _lowerCAmelCase = name.replace("module.mlp_head.1" , "classifier.dense" ) return name def __a(SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Any ): '''simple docstring''' for key in orig_state_dict.copy().keys(): _lowerCAmelCase = orig_state_dict.pop(SCREAMING_SNAKE_CASE_ ) if "qkv" in key: _lowerCAmelCase = key.split("." ) _lowerCAmelCase = int(key_split[3] ) _lowerCAmelCase = config.hidden_size if "weight" in key: _lowerCAmelCase = val[:dim, :] _lowerCAmelCase = val[dim : dim * 2, :] _lowerCAmelCase = val[-dim:, :] else: _lowerCAmelCase = val[:dim] _lowerCAmelCase = val[dim : dim * 2] _lowerCAmelCase = val[-dim:] else: _lowerCAmelCase = val return orig_state_dict def __a(SCREAMING_SNAKE_CASE_ : Any ): '''simple docstring''' _lowerCAmelCase = [ "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_ : Any , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : Optional[int]=False ): '''simple docstring''' _lowerCAmelCase = get_audio_spectrogram_transformer_config(SCREAMING_SNAKE_CASE_ ) _lowerCAmelCase = { "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 _lowerCAmelCase = model_name_to_url[model_name] _lowerCAmelCase = torch.hub.load_state_dict_from_url(SCREAMING_SNAKE_CASE_ , map_location="cpu" ) # remove some keys remove_keys(SCREAMING_SNAKE_CASE_ ) # rename some keys _lowerCAmelCase = convert_state_dict(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # load 🤗 model _lowerCAmelCase = 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 _lowerCAmelCase = -4.267_7393 if "speech-commands" not in model_name else -6.84_5978 _lowerCAmelCase = 4.568_9974 if "speech-commands" not in model_name else 5.565_4526 _lowerCAmelCase = 1024 if "speech-commands" not in model_name else 128 _lowerCAmelCase = ASTFeatureExtractor(mean=SCREAMING_SNAKE_CASE_ , std=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ ) if "speech-commands" in model_name: _lowerCAmelCase = load_dataset("speech_commands" , "v0.02" , split="validation" ) _lowerCAmelCase = dataset[0]["audio"]["array"] else: _lowerCAmelCase = hf_hub_download( repo_id="nielsr/audio-spectogram-transformer-checkpoint" , filename="sample_audio.flac" , repo_type="dataset" , ) _lowerCAmelCase , _lowerCAmelCase = torchaudio.load(SCREAMING_SNAKE_CASE_ ) _lowerCAmelCase = waveform.squeeze().numpy() _lowerCAmelCase = feature_extractor(SCREAMING_SNAKE_CASE_ , sampling_rate=16000 , return_tensors="pt" ) # forward pass _lowerCAmelCase = model(**SCREAMING_SNAKE_CASE_ ) _lowerCAmelCase = outputs.logits if model_name == "ast-finetuned-audioset-10-10-0.4593": _lowerCAmelCase = torch.tensor([-0.8760, -7.0042, -8.6602] ) elif model_name == "ast-finetuned-audioset-10-10-0.450": _lowerCAmelCase = torch.tensor([-1.1986, -7.0903, -8.2718] ) elif model_name == "ast-finetuned-audioset-10-10-0.448": _lowerCAmelCase = torch.tensor([-2.6128, -8.0080, -9.4344] ) elif model_name == "ast-finetuned-audioset-10-10-0.448-v2": _lowerCAmelCase = torch.tensor([-1.5080, -7.4534, -8.8917] ) elif model_name == "ast-finetuned-audioset-12-12-0.447": _lowerCAmelCase = torch.tensor([-0.5050, -6.5833, -8.0843] ) elif model_name == "ast-finetuned-audioset-14-14-0.443": _lowerCAmelCase = torch.tensor([-0.3826, -7.0336, -8.2413] ) elif model_name == "ast-finetuned-audioset-16-16-0.442": _lowerCAmelCase = torch.tensor([-1.2113, -6.9101, -8.3470] ) elif model_name == "ast-finetuned-speech-commands-v2": _lowerCAmelCase = torch.tensor([6.1589, -8.0566, -8.7984] ) 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__": _SCREAMING_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." ) _SCREAMING_SNAKE_CASE = parser.parse_args() convert_audio_spectrogram_transformer_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
18
'''simple docstring''' from __future__ import annotations from typing import Any class UpperCamelCase_ : """simple docstring""" def __init__( self : int , _lowerCamelCase : int , _lowerCamelCase : int , _lowerCamelCase : float = 0 ) -> None: __magic_name__ , __magic_name__ = row, column __magic_name__ = [[default_value for c in range(_lowerCamelCase )] for r in range(_lowerCamelCase )] def __str__( self : Optional[Any] ) -> str: __magic_name__ = f'Matrix consist of {self.row} rows and {self.column} columns\n' # Make string identifier __magic_name__ = 0 for row_vector in self.array: for obj in row_vector: __magic_name__ = max(_lowerCamelCase , len(str(_lowerCamelCase ) ) ) __magic_name__ = f'%{max_element_length}s' # Make string and return def single_line(_lowerCamelCase : list[float] ) -> str: nonlocal string_format_identifier __magic_name__ = "[" line += ", ".join(string_format_identifier % (obj,) for obj in row_vector ) line += "]" return line s += "\n".join(single_line(_lowerCamelCase ) for row_vector in self.array ) return s def __repr__( self : Optional[int] ) -> str: return str(self ) def __A ( self : Optional[Any] , _lowerCamelCase : tuple[int, int] ) -> bool: if not (isinstance(_lowerCamelCase , (list, tuple) ) and len(_lowerCamelCase ) == 2): return False elif not (0 <= loc[0] < self.row and 0 <= loc[1] < self.column): return False else: return True def __getitem__( self : Optional[int] , _lowerCamelCase : tuple[int, int] ) -> Any: assert self.validate_indicies(_lowerCamelCase ) return self.array[loc[0]][loc[1]] def __setitem__( self : Tuple , _lowerCamelCase : tuple[int, int] , _lowerCamelCase : float ) -> None: assert self.validate_indicies(_lowerCamelCase ) __magic_name__ = value def __add__( self : Union[str, Any] , _lowerCamelCase : Matrix ) -> Matrix: assert isinstance(_lowerCamelCase , _lowerCamelCase ) assert self.row == another.row and self.column == another.column # Add __magic_name__ = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): __magic_name__ = self[r, c] + another[r, c] return result def __neg__( self : int ) -> Matrix: __magic_name__ = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): __magic_name__ = -self[r, c] return result def __sub__( self : Optional[int] , _lowerCamelCase : Matrix ) -> Matrix: return self + (-another) def __mul__( self : Optional[int] , _lowerCamelCase : int | float | Matrix ) -> Matrix: if isinstance(_lowerCamelCase , (int, float) ): # Scalar multiplication __magic_name__ = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): __magic_name__ = self[r, c] * another return result elif isinstance(_lowerCamelCase , _lowerCamelCase ): # Matrix multiplication assert self.column == another.row __magic_name__ = Matrix(self.row , another.column ) for r in range(self.row ): for c in range(another.column ): for i in range(self.column ): result[r, c] += self[r, i] * another[i, c] return result else: __magic_name__ = f'Unsupported type given for another ({type(_lowerCamelCase )})' raise TypeError(_lowerCamelCase ) def __A ( self : Optional[int] ) -> Matrix: __magic_name__ = Matrix(self.column , self.row ) for r in range(self.row ): for c in range(self.column ): __magic_name__ = self[r, c] return result def __A ( self : int , _lowerCamelCase : Matrix , _lowerCamelCase : Matrix ) -> Any: assert isinstance(_lowerCamelCase , _lowerCamelCase ) and isinstance(_lowerCamelCase , _lowerCamelCase ) assert self.row == self.column == u.row == v.row # u, v should be column vector assert u.column == v.column == 1 # u, v should be column vector # Calculate __magic_name__ = v.transpose() __magic_name__ = (v_t * self * u)[0, 0] + 1 if numerator_factor == 0: return None # It's not invertable return self - ((self * u) * (v_t * self) * (1.0 / numerator_factor)) # Testing if __name__ == "__main__": def __snake_case ( ): '''simple docstring''' __magic_name__ = Matrix(3 , 3 , 0 ) for i in range(3 ): __magic_name__ = 1 print(F'a^(-1) is {ainv}' ) # u, v __magic_name__ = Matrix(3 , 1 , 0 ) __magic_name__ , __magic_name__ , __magic_name__ = 1, 2, -3 __magic_name__ = Matrix(3 , 1 , 0 ) __magic_name__ , __magic_name__ , __magic_name__ = 4, -2, 5 print(F'u is {u}' ) print(F'v is {v}' ) print(F'uv^T is {u * v.transpose()}' ) # Sherman Morrison print(F'(a + uv^T)^(-1) is {ainv.sherman_morrison(lowerCamelCase_ , lowerCamelCase_ )}' ) def __snake_case ( ): '''simple docstring''' import doctest doctest.testmod() testa()
664
0
"""simple docstring""" _a = 8.314_4598 def lowerCamelCase__ ( __snake_case, __snake_case ) -> float: """simple docstring""" if temperature < 0: raise Exception('''Temperature cannot be less than 0 K''' ) if molar_mass <= 0: raise Exception('''Molar mass cannot be less than or equal to 0 kg/mol''' ) else: return (3 * UNIVERSAL_GAS_CONSTANT * temperature / molar_mass) ** 0.5 if __name__ == "__main__": import doctest # run doctest doctest.testmod() # example _a = 300 _a = 28 _a = rms_speed_of_molecule(temperature, molar_mass) print(F"""Vrms of Nitrogen gas at 300 K is {vrms} m/s""")
19
'''simple docstring''' import argparse import logging from collections import namedtuple import torch from model_bertabs import BertAbsSummarizer from models.model_builder import AbsSummarizer # The authors' implementation from transformers import BertTokenizer logging.basicConfig(level=logging.INFO) __magic_name__ : List[Any] =logging.getLogger(__name__) __magic_name__ : int ='Hello world! cécé herlolip' __magic_name__ : List[Any] =namedtuple( 'BertAbsConfig', [ 'temp_dir', 'large', 'use_bert_emb', 'finetune_bert', 'encoder', 'share_emb', 'max_pos', 'enc_layers', 'enc_hidden_size', 'enc_heads', 'enc_ff_size', 'enc_dropout', 'dec_layers', 'dec_hidden_size', 'dec_heads', 'dec_ff_size', 'dec_dropout', ], ) def __snake_case ( lowerCamelCase_ : Optional[int] , lowerCamelCase_ : Dict ): '''simple docstring''' __magic_name__ = BertAbsConfig( temp_dir="." , finetune_bert=lowerCamelCase_ , large=lowerCamelCase_ , share_emb=lowerCamelCase_ , use_bert_emb=lowerCamelCase_ , encoder="bert" , max_pos=512 , enc_layers=6 , enc_hidden_size=512 , enc_heads=8 , enc_ff_size=512 , enc_dropout=0.2 , dec_layers=6 , dec_hidden_size=768 , dec_heads=8 , dec_ff_size=2048 , dec_dropout=0.2 , ) __magic_name__ = torch.load(lowerCamelCase_ , lambda lowerCamelCase_ , lowerCamelCase_ : storage ) __magic_name__ = AbsSummarizer(lowerCamelCase_ , torch.device("cpu" ) , lowerCamelCase_ ) original.eval() __magic_name__ = BertAbsSummarizer(lowerCamelCase_ , torch.device("cpu" ) ) new_model.eval() # ------------------- # Convert the weights # ------------------- logging.info("convert the model" ) new_model.bert.load_state_dict(original.bert.state_dict() ) new_model.decoder.load_state_dict(original.decoder.state_dict() ) new_model.generator.load_state_dict(original.generator.state_dict() ) # ---------------------------------- # Make sure the outpus are identical # ---------------------------------- logging.info("Make sure that the models' outputs are identical" ) __magic_name__ = BertTokenizer.from_pretrained("bert-base-uncased" ) # prepare the model inputs __magic_name__ = tokenizer.encode("This is sample éàalj'-." ) encoder_input_ids.extend([tokenizer.pad_token_id] * (512 - len(lowerCamelCase_ )) ) __magic_name__ = torch.tensor(lowerCamelCase_ ).unsqueeze(0 ) __magic_name__ = tokenizer.encode("This is sample 3 éàalj'-." ) decoder_input_ids.extend([tokenizer.pad_token_id] * (512 - len(lowerCamelCase_ )) ) __magic_name__ = torch.tensor(lowerCamelCase_ ).unsqueeze(0 ) # failsafe to make sure the weights reset does not affect the # loaded weights. assert torch.max(torch.abs(original.generator[0].weight - new_model.generator[0].weight ) ) == 0 # forward pass __magic_name__ = encoder_input_ids __magic_name__ = decoder_input_ids __magic_name__ = __magic_name__ = None __magic_name__ = None __magic_name__ = __magic_name__ = None __magic_name__ = __magic_name__ = None __magic_name__ = None # The original model does not apply the geneator layer immediatly but rather in # the beam search (where it combines softmax + linear layer). Since we already # apply the softmax in our generation process we only apply the linear layer here. # We make sure that the outputs of the full stack are identical __magic_name__ = original(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )[0] __magic_name__ = original.generator(lowerCamelCase_ ) __magic_name__ = new_model( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )[0] __magic_name__ = new_model.generator(lowerCamelCase_ ) __magic_name__ = torch.max(torch.abs(output_converted_model - output_original_model ) ).item() print("Maximum absolute difference beween weights: {:.2f}".format(lowerCamelCase_ ) ) __magic_name__ = torch.max(torch.abs(output_converted_generator - output_original_generator ) ).item() print("Maximum absolute difference beween weights: {:.2f}".format(lowerCamelCase_ ) ) __magic_name__ = torch.allclose(lowerCamelCase_ , lowerCamelCase_ , atol=1e-3 ) if are_identical: logging.info("all weights are equal up to 1e-3" ) else: raise ValueError("the weights are different. The new model is likely different from the original one." ) # The model has been saved with torch.save(model) and this is bound to the exact # directory structure. We save the state_dict instead. logging.info("saving the model's state dictionary" ) torch.save( new_model.state_dict() , "./bertabs-finetuned-cnndm-extractive-abstractive-summarization/pytorch_model.bin" ) if __name__ == "__main__": __magic_name__ : Dict =argparse.ArgumentParser() parser.add_argument( '--bertabs_checkpoint_path', default=None, type=str, required=True, help='Path the official PyTorch dump.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.', ) __magic_name__ : Any =parser.parse_args() convert_bertabs_checkpoints( args.bertabs_checkpoint_path, args.pytorch_dump_folder_path, )
664
0