code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
import os UpperCamelCase__ : Optional[int] = {"""I""": 1, """V""": 5, """X""": 10, """L""": 50, """C""": 100, """D""": 500, """M""": 1_000} def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> int: """simple docstring""" a = 0 a = 0 while index < len(snake_case_ ) - 1: a = SYMBOLS[numerals[index]] a = SYMBOLS[numerals[index + 1]] if current_value < next_value: total_value -= current_value else: total_value += current_value index += 1 total_value += SYMBOLS[numerals[index]] return total_value def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> str: """simple docstring""" a = '''''' a = num // 1_0_0_0 numerals += m_count * "M" num %= 1_0_0_0 a = num // 1_0_0 if c_count == 9: numerals += "CM" c_count -= 9 elif c_count == 4: numerals += "CD" c_count -= 4 if c_count >= 5: numerals += "D" c_count -= 5 numerals += c_count * "C" num %= 1_0_0 a = num // 1_0 if x_count == 9: numerals += "XC" x_count -= 9 elif x_count == 4: numerals += "XL" x_count -= 4 if x_count >= 5: numerals += "L" x_count -= 5 numerals += x_count * "X" num %= 1_0 if num == 9: numerals += "IX" num -= 9 elif num == 4: numerals += "IV" num -= 4 if num >= 5: numerals += "V" num -= 5 numerals += num * "I" return numerals def SCREAMING_SNAKE_CASE__ ( snake_case_ = "/p089_roman.txt" ) -> int: """simple docstring""" a = 0 with open(os.path.dirname(snake_case_ ) + roman_numerals_filename ) as filea: a = filea.readlines() for line in lines: a = line.strip() a = parse_roman_numerals(snake_case_ ) a = generate_roman_numerals(snake_case_ ) savings += len(snake_case_ ) - len(snake_case_ ) return savings if __name__ == "__main__": print(F"{solution() = }")
330
def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> Union[str, Any]: """simple docstring""" stooge(snake_case_, 0, len(snake_case_ ) - 1 ) return arr def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_ ) -> Optional[Any]: """simple docstring""" if i >= h: return # If first element is smaller than the last then swap them if arr[i] > arr[h]: a , a = arr[h], arr[i] # If there are more than 2 elements in the array if h - i + 1 > 2: a = (int)((h - i + 1) / 3 ) # Recursively sort first 2/3 elements stooge(snake_case_, snake_case_, (h - t) ) # Recursively sort last 2/3 elements stooge(snake_case_, i + t, (snake_case_) ) # Recursively sort first 2/3 elements stooge(snake_case_, snake_case_, (h - t) ) if __name__ == "__main__": UpperCamelCase__ : Dict = input("""Enter numbers separated by a comma:\n""").strip() UpperCamelCase__ : Optional[int] = [int(item) for item in user_input.split(""",""")] print(stooge_sort(unsorted))
330
1
def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> list: """simple docstring""" for i in range(len(snake_case_ ) - 1, 0, -1 ): a = False for j in range(snake_case_, 0, -1 ): if unsorted[j] < unsorted[j - 1]: a , a = unsorted[j - 1], unsorted[j] a = True for j in range(snake_case_ ): if unsorted[j] > unsorted[j + 1]: a , a = unsorted[j + 1], unsorted[j] a = True if not swapped: break return unsorted if __name__ == "__main__": import doctest doctest.testmod() UpperCamelCase__ : Optional[Any] = input("""Enter numbers separated by a comma:\n""").strip() UpperCamelCase__ : str = [int(item) for item in user_input.split(""",""")] print(F"{cocktail_shaker_sort(unsorted) = }")
330
import json import os import re import unicodedata from json.encoder import INFINITY from typing import Any, Dict, List, Optional, Tuple, Union import numpy as np import regex from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, is_flax_available, is_tf_available, is_torch_available, logging from ...utils.generic import _is_jax, _is_numpy UpperCamelCase__ : Any = logging.get_logger(__name__) UpperCamelCase__ : Optional[Any] = { """artists_file""": """artists.json""", """lyrics_file""": """lyrics.json""", """genres_file""": """genres.json""", } UpperCamelCase__ : Union[str, Any] = { """artists_file""": { """jukebox""": """https://huggingface.co/ArthurZ/jukebox/blob/main/artists.json""", }, """genres_file""": { """jukebox""": """https://huggingface.co/ArthurZ/jukebox/blob/main/genres.json""", }, """lyrics_file""": { """jukebox""": """https://huggingface.co/ArthurZ/jukebox/blob/main/lyrics.json""", }, } UpperCamelCase__ : str = { """jukebox""": 512, } class lowerCamelCase_ ( a_ ): SCREAMING_SNAKE_CASE_ = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE_ = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE_ = PRETRAINED_LYRIC_TOKENS_SIZES SCREAMING_SNAKE_CASE_ = ['input_ids', 'attention_mask'] def __init__( self : Optional[Any] ,__lowerCamelCase : Optional[Any] ,__lowerCamelCase : List[Any] ,__lowerCamelCase : Tuple ,__lowerCamelCase : Union[str, Any]=["v3", "v2", "v2"] ,__lowerCamelCase : List[Any]=5_12 ,__lowerCamelCase : Tuple=5 ,__lowerCamelCase : List[Any]="<|endoftext|>" ,**__lowerCamelCase : List[str] ,): '''simple docstring''' a = AddedToken(__lowerCamelCase ,lstrip=__lowerCamelCase ,rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase ,__lowerCamelCase ) else unk_token super().__init__( unk_token=__lowerCamelCase ,n_genres=__lowerCamelCase ,version=__lowerCamelCase ,max_n_lyric_tokens=__lowerCamelCase ,**__lowerCamelCase ,) a = version a = max_n_lyric_tokens a = n_genres with open(__lowerCamelCase ,encoding='''utf-8''' ) as vocab_handle: a = json.load(__lowerCamelCase ) with open(__lowerCamelCase ,encoding='''utf-8''' ) as vocab_handle: a = json.load(__lowerCamelCase ) with open(__lowerCamelCase ,encoding='''utf-8''' ) as vocab_handle: a = json.load(__lowerCamelCase ) a = r'''[^A-Za-z0-9.,:;!?\-\'\"()\[\] \t\n]+''' # In v2, we had a n_vocab=80 and in v3 we missed + and so n_vocab=79 of characters. if len(self.lyrics_encoder ) == 79: a = oov.replace(r'''\-\'''' ,r'''\-+\'''' ) a = regex.compile(__lowerCamelCase ) a = {v: k for k, v in self.artists_encoder.items()} a = {v: k for k, v in self.genres_encoder.items()} a = {v: k for k, v in self.lyrics_encoder.items()} @property def SCREAMING_SNAKE_CASE_ ( self : str ): '''simple docstring''' return len(self.artists_encoder ) + len(self.genres_encoder ) + len(self.lyrics_encoder ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ): '''simple docstring''' return dict(self.artists_encoder ,self.genres_encoder ,self.lyrics_encoder ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ,__lowerCamelCase : Optional[int] ,__lowerCamelCase : Optional[Any] ,__lowerCamelCase : List[Any] ): '''simple docstring''' a = [self.artists_encoder.get(__lowerCamelCase ,0 ) for artist in list_artists] for genres in range(len(__lowerCamelCase ) ): a = [self.genres_encoder.get(__lowerCamelCase ,0 ) for genre in list_genres[genres]] a = list_genres[genres] + [-1] * (self.n_genres - len(list_genres[genres] )) a = [[self.lyrics_encoder.get(__lowerCamelCase ,0 ) for character in list_lyrics[0]], [], []] return artists_id, list_genres, lyric_ids def SCREAMING_SNAKE_CASE_ ( self : Tuple ,__lowerCamelCase : List[str] ): '''simple docstring''' return list(__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ,__lowerCamelCase : List[Any] ,__lowerCamelCase : Any ,__lowerCamelCase : Optional[int] ,**__lowerCamelCase : Optional[Any] ): '''simple docstring''' a , a , a = self.prepare_for_tokenization(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ) a = self._tokenize(__lowerCamelCase ) return artist, genre, lyrics def SCREAMING_SNAKE_CASE_ ( self : int ,__lowerCamelCase : str ,__lowerCamelCase : str ,__lowerCamelCase : str ,__lowerCamelCase : bool = False ): '''simple docstring''' for idx in range(len(self.version ) ): if self.version[idx] == "v3": a = artists[idx].lower() a = [genres[idx].lower()] else: a = self._normalize(artists[idx] ) + '''.v2''' a = [ self._normalize(__lowerCamelCase ) + '''.v2''' for genre in genres[idx].split('''_''' ) ] # split is for the full dictionary with combined genres if self.version[0] == "v2": a = regex.compile(r'''[^A-Za-z0-9.,:;!?\-\'\"()\[\] \t\n]+''' ) a = '''ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,:;!?-+\'\"()[] \t\n''' a = {vocab[index]: index + 1 for index in range(len(__lowerCamelCase ) )} a = 0 a = len(__lowerCamelCase ) + 1 a = self.vocab a = {v: k for k, v in self.vocab.items()} a = '''''' else: a = regex.compile(r'''[^A-Za-z0-9.,:;!?\-+\'\"()\[\] \t\n]+''' ) a = self._run_strip_accents(__lowerCamelCase ) a = lyrics.replace('''\\''' ,'''\n''' ) a = self.out_of_vocab.sub('''''' ,__lowerCamelCase ), [], [] return artists, genres, lyrics def SCREAMING_SNAKE_CASE_ ( self : str ,__lowerCamelCase : int ): '''simple docstring''' a = unicodedata.normalize('''NFD''' ,__lowerCamelCase ) a = [] for char in text: a = unicodedata.category(__lowerCamelCase ) if cat == "Mn": continue output.append(__lowerCamelCase ) return "".join(__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ,__lowerCamelCase : str ): '''simple docstring''' a = ( [chr(__lowerCamelCase ) for i in range(ord('''a''' ) ,ord('''z''' ) + 1 )] + [chr(__lowerCamelCase ) for i in range(ord('''A''' ) ,ord('''Z''' ) + 1 )] + [chr(__lowerCamelCase ) for i in range(ord('''0''' ) ,ord('''9''' ) + 1 )] + ['''.'''] ) a = frozenset(__lowerCamelCase ) a = re.compile(r'''_+''' ) a = ''''''.join([c if c in accepted else '''_''' for c in text.lower()] ) a = pattern.sub('''_''' ,__lowerCamelCase ).strip('''_''' ) return text def SCREAMING_SNAKE_CASE_ ( self : List[str] ,__lowerCamelCase : List[str] ): '''simple docstring''' return " ".join(__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : Any ,__lowerCamelCase : str ,__lowerCamelCase : Optional[Union[str, TensorType]] = None ,__lowerCamelCase : bool = False ): '''simple docstring''' if not isinstance(__lowerCamelCase ,__lowerCamelCase ): a = TensorType(__lowerCamelCase ) # Get a function reference for the correct framework if tensor_type == TensorType.TENSORFLOW: if not is_tf_available(): raise ImportError( '''Unable to convert output to TensorFlow tensors format, TensorFlow is not installed.''' ) import tensorflow as tf a = tf.constant a = tf.is_tensor elif tensor_type == TensorType.PYTORCH: if not is_torch_available(): raise ImportError('''Unable to convert output to PyTorch tensors format, PyTorch is not installed.''' ) import torch a = torch.tensor a = torch.is_tensor elif tensor_type == TensorType.JAX: if not is_flax_available(): raise ImportError('''Unable to convert output to JAX tensors format, JAX is not installed.''' ) import jax.numpy as jnp # noqa: F811 a = jnp.array a = _is_jax else: a = np.asarray a = _is_numpy # Do the tensor conversion in batch try: if prepend_batch_axis: a = [inputs] if not is_tensor(__lowerCamelCase ): a = as_tensor(__lowerCamelCase ) except: # noqa E722 raise ValueError( '''Unable to create tensor, you should probably activate truncation and/or padding ''' '''with \'padding=True\' \'truncation=True\' to have batched tensors with the same length.''' ) return inputs def __call__( self : Tuple ,__lowerCamelCase : Tuple ,__lowerCamelCase : Optional[int] ,__lowerCamelCase : List[str]="" ,__lowerCamelCase : List[Any]="pt" ): '''simple docstring''' a = [0, 0, 0] a = [artist] * len(self.version ) a = [genres] * len(self.version ) a , a , a = self.tokenize(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ) a , a , a = self._convert_token_to_id(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ) a = [-INFINITY] * len(full_tokens[-1] ) a = [ self.convert_to_tensors( [input_ids + [artists_id[i]] + genres_ids[i] + full_tokens[i]] ,tensor_type=__lowerCamelCase ) for i in range(len(self.version ) ) ] return BatchEncoding({'''input_ids''': input_ids, '''attention_masks''': attention_masks} ) def SCREAMING_SNAKE_CASE_ ( self : int ,__lowerCamelCase : str ,__lowerCamelCase : Optional[str] = None ): '''simple docstring''' 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['''artists_file'''] ) with open(__lowerCamelCase ,'''w''' ,encoding='''utf-8''' ) as f: f.write(json.dumps(self.artists_encoder ,ensure_ascii=__lowerCamelCase ) ) a = os.path.join( __lowerCamelCase ,(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''genres_file'''] ) with open(__lowerCamelCase ,'''w''' ,encoding='''utf-8''' ) as f: f.write(json.dumps(self.genres_encoder ,ensure_ascii=__lowerCamelCase ) ) a = os.path.join( __lowerCamelCase ,(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''lyrics_file'''] ) with open(__lowerCamelCase ,'''w''' ,encoding='''utf-8''' ) as f: f.write(json.dumps(self.lyrics_encoder ,ensure_ascii=__lowerCamelCase ) ) return (artists_file, genres_file, lyrics_file) def SCREAMING_SNAKE_CASE_ ( self : Any ,__lowerCamelCase : Any ,__lowerCamelCase : Any ,__lowerCamelCase : str ): '''simple docstring''' a = self.artists_decoder.get(__lowerCamelCase ) a = [self.genres_decoder.get(__lowerCamelCase ) for genre in genres_index] a = [self.lyrics_decoder.get(__lowerCamelCase ) for character in lyric_index] return artist, genres, lyrics
330
1
from numpy import exp, pi, sqrt def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ = 0.0, snake_case_ = 1.0 ) -> int: """simple docstring""" return 1 / sqrt(2 * pi * sigma**2 ) * exp(-((x - mu) ** 2) / (2 * sigma**2) ) if __name__ == "__main__": import doctest doctest.testmod()
330
# This script creates a super tiny model that is useful inside tests, when we just want to test that # the machinery works, without needing to the check the quality of the outcomes. # # This version creates a tiny vocab first, and then a tiny model - so the outcome is truly tiny - # all files ~60KB. As compared to taking a full-size model, reducing to the minimum its layers and # emb dimensions, but keeping the full vocab + merges files, leading to ~3MB in total for all files. # The latter is done by `fsmt-make-super-tiny-model.py`. # # It will be used then as "stas/tiny-wmt19-en-ru" from pathlib import Path import json import tempfile from transformers import FSMTTokenizer, FSMTConfig, FSMTForConditionalGeneration from transformers.models.fsmt.tokenization_fsmt import VOCAB_FILES_NAMES UpperCamelCase__ : Optional[Any] = """tiny-wmt19-en-ru""" # Build # borrowed from a test UpperCamelCase__ : Any = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """w</w>""", """r</w>""", """t</w>""", """lo""", """low""", """er</w>""", """low</w>""", """lowest</w>""", """newer</w>""", """wider</w>""", """<unk>""", ] UpperCamelCase__ : List[Any] = dict(zip(vocab, range(len(vocab)))) UpperCamelCase__ : Any = ["""l o 123""", """lo w 1456""", """e r</w> 1789""", """"""] with tempfile.TemporaryDirectory() as tmpdirname: UpperCamelCase__ : Optional[Any] = Path(tmpdirname) UpperCamelCase__ : Tuple = build_dir / VOCAB_FILES_NAMES["""src_vocab_file"""] UpperCamelCase__ : int = build_dir / VOCAB_FILES_NAMES["""tgt_vocab_file"""] UpperCamelCase__ : Union[str, Any] = build_dir / VOCAB_FILES_NAMES["""merges_file"""] with open(src_vocab_file, """w""") as fp: fp.write(json.dumps(vocab_tokens)) with open(tgt_vocab_file, """w""") as fp: fp.write(json.dumps(vocab_tokens)) with open(merges_file, """w""") as fp: fp.write("""\n""".join(merges)) UpperCamelCase__ : Dict = FSMTTokenizer( langs=["""en""", """ru"""], src_vocab_size=len(vocab), tgt_vocab_size=len(vocab), src_vocab_file=src_vocab_file, tgt_vocab_file=tgt_vocab_file, merges_file=merges_file, ) UpperCamelCase__ : Union[str, Any] = FSMTConfig( langs=["""ru""", """en"""], src_vocab_size=1_000, tgt_vocab_size=1_000, d_model=4, encoder_layers=1, decoder_layers=1, encoder_ffn_dim=4, decoder_ffn_dim=4, encoder_attention_heads=1, decoder_attention_heads=1, ) UpperCamelCase__ : Union[str, Any] = FSMTForConditionalGeneration(config) print(F"num of params {tiny_model.num_parameters()}") # Test UpperCamelCase__ : List[str] = tokenizer(["""Making tiny model"""], return_tensors="""pt""") UpperCamelCase__ : Tuple = tiny_model(**batch) print("""test output:""", len(outputs.logits[0])) # Save tiny_model.half() # makes it smaller tiny_model.save_pretrained(mname_tiny) tokenizer.save_pretrained(mname_tiny) print(F"Generated {mname_tiny}") # Upload # transformers-cli upload tiny-wmt19-en-ru
330
1
def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> List[Any]: """simple docstring""" a , a = [], [] while len(snake_case_ ) > 1: a , a = min(snake_case_ ), max(snake_case_ ) start.append(snake_case_ ) end.append(snake_case_ ) collection.remove(snake_case_ ) collection.remove(snake_case_ ) end.reverse() return start + collection + end if __name__ == "__main__": UpperCamelCase__ : List[Any] = input("""Enter numbers separated by a comma:\n""").strip() UpperCamelCase__ : List[Any] = [int(item) for item in user_input.split(""",""")] print(*merge_sort(unsorted), sep=""",""")
330
import inspect import os import torch from transformers import AutoModel from transformers.testing_utils import mockenv_context from transformers.trainer_utils import set_seed import accelerate from accelerate.accelerator import Accelerator from accelerate.state import AcceleratorState from accelerate.test_utils.testing import ( AccelerateTestCase, TempDirTestCase, execute_subprocess_async, require_cuda, require_fsdp, require_multi_gpu, slow, ) from accelerate.utils.constants import ( FSDP_AUTO_WRAP_POLICY, FSDP_BACKWARD_PREFETCH, FSDP_SHARDING_STRATEGY, FSDP_STATE_DICT_TYPE, ) from accelerate.utils.dataclasses import FullyShardedDataParallelPlugin from accelerate.utils.other import patch_environment set_seed(42) UpperCamelCase__ : Optional[Any] = """bert-base-cased""" UpperCamelCase__ : int = """fp16""" UpperCamelCase__ : str = """bf16""" UpperCamelCase__ : List[Any] = [FPaa, BFaa] @require_fsdp @require_cuda class lowerCamelCase_ ( a_ ): def SCREAMING_SNAKE_CASE_ ( self : int ): '''simple docstring''' super().setUp() a = dict( ACCELERATE_USE_FSDP='''true''' ,MASTER_ADDR='''localhost''' ,MASTER_PORT='''10999''' ,RANK='''0''' ,LOCAL_RANK='''0''' ,WORLD_SIZE='''1''' ,) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ): '''simple docstring''' from torch.distributed.fsdp.fully_sharded_data_parallel import ShardingStrategy for i, strategy in enumerate(__lowerCamelCase ): a = self.dist_env.copy() a = F"""{i + 1}""" a = strategy with mockenv_context(**__lowerCamelCase ): a = FullyShardedDataParallelPlugin() self.assertEqual(fsdp_plugin.sharding_strategy ,ShardingStrategy(i + 1 ) ) def SCREAMING_SNAKE_CASE_ ( self : Any ): '''simple docstring''' from torch.distributed.fsdp.fully_sharded_data_parallel import BackwardPrefetch for i, prefetch_policy in enumerate(__lowerCamelCase ): a = self.dist_env.copy() a = prefetch_policy with mockenv_context(**__lowerCamelCase ): a = FullyShardedDataParallelPlugin() if prefetch_policy == "NO_PREFETCH": self.assertIsNone(fsdp_plugin.backward_prefetch ) else: self.assertEqual(fsdp_plugin.backward_prefetch ,BackwardPrefetch(i + 1 ) ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ): '''simple docstring''' from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType for i, state_dict_type in enumerate(__lowerCamelCase ): a = self.dist_env.copy() a = state_dict_type with mockenv_context(**__lowerCamelCase ): a = FullyShardedDataParallelPlugin() self.assertEqual(fsdp_plugin.state_dict_type ,StateDictType(i + 1 ) ) if state_dict_type == "FULL_STATE_DICT": self.assertTrue(fsdp_plugin.state_dict_config.offload_to_cpu ) self.assertTrue(fsdp_plugin.state_dict_config.ranka_only ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ): '''simple docstring''' a = AutoModel.from_pretrained(__lowerCamelCase ) for policy in FSDP_AUTO_WRAP_POLICY: a = self.dist_env.copy() a = policy if policy == "TRANSFORMER_BASED_WRAP": a = '''BertLayer''' elif policy == "SIZE_BASED_WRAP": a = '''2000''' with mockenv_context(**__lowerCamelCase ): a = FullyShardedDataParallelPlugin() fsdp_plugin.set_auto_wrap_policy(__lowerCamelCase ) if policy == "NO_WRAP": self.assertIsNone(fsdp_plugin.auto_wrap_policy ) else: self.assertIsNotNone(fsdp_plugin.auto_wrap_policy ) a = self.dist_env.copy() a = '''TRANSFORMER_BASED_WRAP''' a = '''T5Layer''' with mockenv_context(**__lowerCamelCase ): a = FullyShardedDataParallelPlugin() with self.assertRaises(__lowerCamelCase ) as cm: fsdp_plugin.set_auto_wrap_policy(__lowerCamelCase ) self.assertTrue('''Could not find the transformer layer class to wrap in the model.''' in str(cm.exception ) ) a = self.dist_env.copy() a = '''SIZE_BASED_WRAP''' a = '''0''' with mockenv_context(**__lowerCamelCase ): a = FullyShardedDataParallelPlugin() fsdp_plugin.set_auto_wrap_policy(__lowerCamelCase ) self.assertIsNone(fsdp_plugin.auto_wrap_policy ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ): '''simple docstring''' from torch.distributed.fsdp.fully_sharded_data_parallel import MixedPrecision from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler for mp_dtype in dtypes: a = self.dist_env.copy() a = mp_dtype with mockenv_context(**__lowerCamelCase ): a = Accelerator() if mp_dtype == "fp16": a = torch.floataa elif mp_dtype == "bf16": a = torch.bfloataa a = MixedPrecision(param_dtype=__lowerCamelCase ,reduce_dtype=__lowerCamelCase ,buffer_dtype=__lowerCamelCase ) self.assertEqual(accelerator.state.fsdp_plugin.mixed_precision_policy ,__lowerCamelCase ) if mp_dtype == FPaa: self.assertTrue(isinstance(accelerator.scaler ,__lowerCamelCase ) ) elif mp_dtype == BFaa: self.assertIsNone(accelerator.scaler ) AcceleratorState._reset_state(__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ): '''simple docstring''' from torch.distributed.fsdp.fully_sharded_data_parallel import CPUOffload for flag in [True, False]: a = self.dist_env.copy() a = str(__lowerCamelCase ).lower() with mockenv_context(**__lowerCamelCase ): a = FullyShardedDataParallelPlugin() self.assertEqual(fsdp_plugin.cpu_offload ,CPUOffload(offload_params=__lowerCamelCase ) ) @require_fsdp @require_multi_gpu @slow class lowerCamelCase_ ( a_ ): def SCREAMING_SNAKE_CASE_ ( self : List[Any] ): '''simple docstring''' super().setUp() a = 0.82 a = [ '''fsdp_shard_grad_op_transformer_based_wrap''', '''fsdp_full_shard_transformer_based_wrap''', ] a = { '''multi_gpu_fp16''': 32_00, '''fsdp_shard_grad_op_transformer_based_wrap_fp16''': 20_00, '''fsdp_full_shard_transformer_based_wrap_fp16''': 19_00, # Disabling below test as it overwhelms the RAM memory usage # on CI self-hosted runner leading to tests getting killed. # "fsdp_full_shard_cpu_offload_transformer_based_wrap_fp32": 1500, # fp16 was leading to indefinite hang } a = 1_60 a = 1_60 a = inspect.getfile(accelerate.test_utils ) a = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''external_deps'''] ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ): '''simple docstring''' a = os.path.join(self.test_scripts_folder ,'''test_performance.py''' ) a = ['''accelerate''', '''launch''', '''--num_processes=2''', '''--num_machines=1''', '''--machine_rank=0''', '''--use_fsdp'''] for config in self.performance_configs: a = cmd.copy() for i, strategy in enumerate(__lowerCamelCase ): if strategy.lower() in config: cmd_config.append(F"""--fsdp_sharding_strategy={i+1}""" ) break if "fp32" in config: cmd_config.append('''--mixed_precision=no''' ) else: cmd_config.append('''--mixed_precision=fp16''' ) if "cpu_offload" in config: cmd_config.append('''--fsdp_offload_params=True''' ) for policy in FSDP_AUTO_WRAP_POLICY: if policy.lower() in config: cmd_config.append(F"""--fsdp_auto_wrap_policy={policy}""" ) break if policy == "TRANSFORMER_BASED_WRAP": cmd_config.append('''--fsdp_transformer_layer_cls_to_wrap=BertLayer''' ) elif policy == "SIZE_BASED_WRAP": cmd_config.append('''--fsdp_min_num_params=2000''' ) cmd_config.extend( [ self.test_file_path, F"""--output_dir={self.tmpdir}""", F"""--performance_lower_bound={self.performance_lower_bound}""", ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__lowerCamelCase ,env=os.environ.copy() ) def SCREAMING_SNAKE_CASE_ ( self : Any ): '''simple docstring''' a = os.path.join(self.test_scripts_folder ,'''test_checkpointing.py''' ) a = [ '''accelerate''', '''launch''', '''--num_processes=2''', '''--num_machines=1''', '''--machine_rank=0''', '''--use_fsdp''', '''--mixed_precision=fp16''', '''--fsdp_transformer_layer_cls_to_wrap=BertLayer''', ] for i, strategy in enumerate(__lowerCamelCase ): a = cmd.copy() cmd_config.append(F"""--fsdp_sharding_strategy={i+1}""" ) if strategy != "FULL_SHARD": continue a = len(__lowerCamelCase ) for state_dict_type in FSDP_STATE_DICT_TYPE: a = cmd_config[:state_dict_config_index] cmd_config.append(F"""--fsdp_state_dict_type={state_dict_type}""" ) cmd_config.extend( [ self.test_file_path, F"""--output_dir={self.tmpdir}""", '''--partial_train_epoch=1''', ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__lowerCamelCase ,env=os.environ.copy() ) a = cmd_config[:-1] a = os.path.join(self.tmpdir ,'''epoch_0''' ) cmd_config.extend( [ F"""--resume_from_checkpoint={resume_from_checkpoint}""", ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__lowerCamelCase ,env=os.environ.copy() ) def SCREAMING_SNAKE_CASE_ ( self : int ): '''simple docstring''' a = os.path.join(self.test_scripts_folder ,'''test_peak_memory_usage.py''' ) a = [ '''accelerate''', '''launch''', '''--num_processes=2''', '''--num_machines=1''', '''--machine_rank=0''', ] for spec, peak_mem_upper_bound in self.peak_memory_usage_upper_bound.items(): a = cmd.copy() if "fp16" in spec: cmd_config.extend(['''--mixed_precision=fp16'''] ) else: cmd_config.extend(['''--mixed_precision=no'''] ) if "multi_gpu" in spec: continue else: cmd_config.extend(['''--use_fsdp'''] ) for i, strategy in enumerate(__lowerCamelCase ): if strategy.lower() in spec: cmd_config.append(F"""--fsdp_sharding_strategy={i+1}""" ) break if "cpu_offload" in spec: cmd_config.append('''--fsdp_offload_params=True''' ) for policy in FSDP_AUTO_WRAP_POLICY: if policy.lower() in spec: cmd_config.append(F"""--fsdp_auto_wrap_policy={policy}""" ) break if policy == "TRANSFORMER_BASED_WRAP": cmd_config.append('''--fsdp_transformer_layer_cls_to_wrap=BertLayer''' ) elif policy == "SIZE_BASED_WRAP": cmd_config.append('''--fsdp_min_num_params=2000''' ) cmd_config.extend( [ self.test_file_path, F"""--output_dir={self.tmpdir}""", F"""--peak_memory_upper_bound={peak_mem_upper_bound}""", F"""--n_train={self.n_train}""", F"""--n_val={self.n_val}""", ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__lowerCamelCase ,env=os.environ.copy() )
330
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available UpperCamelCase__ : Union[str, Any] = { """configuration_altclip""": [ """ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP""", """AltCLIPConfig""", """AltCLIPTextConfig""", """AltCLIPVisionConfig""", ], """processing_altclip""": ["""AltCLIPProcessor"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ : Any = [ """ALTCLIP_PRETRAINED_MODEL_ARCHIVE_LIST""", """AltCLIPPreTrainedModel""", """AltCLIPModel""", """AltCLIPTextModel""", """AltCLIPVisionModel""", ] if TYPE_CHECKING: from .configuration_altclip import ( ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, AltCLIPConfig, AltCLIPTextConfig, AltCLIPVisionConfig, ) from .processing_altclip import AltCLIPProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_altclip import ( ALTCLIP_PRETRAINED_MODEL_ARCHIVE_LIST, AltCLIPModel, AltCLIPPreTrainedModel, AltCLIPTextModel, AltCLIPVisionModel, ) else: import sys UpperCamelCase__ : Any = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
330
from __future__ import annotations import os from collections.abc import Mapping UpperCamelCase__ : Any = tuple[int, int] class lowerCamelCase_ : def __init__( self : Optional[Any] ,__lowerCamelCase : set[int] ,__lowerCamelCase : Mapping[EdgeT, int] ): '''simple docstring''' a = vertices a = { (min(__lowerCamelCase ), max(__lowerCamelCase )): weight for edge, weight in edges.items() } def SCREAMING_SNAKE_CASE_ ( self : str ,__lowerCamelCase : EdgeT ,__lowerCamelCase : int ): '''simple docstring''' self.vertices.add(edge[0] ) self.vertices.add(edge[1] ) a = weight def SCREAMING_SNAKE_CASE_ ( self : Dict ): '''simple docstring''' a = Graph({min(self.vertices )} ,{} ) a = 42 a = 42 a = 42 a = 42 while len(subgraph.vertices ) < len(self.vertices ): a = max(self.edges.values() ) + 1 for edge, weight in self.edges.items(): if (edge[0] in subgraph.vertices) ^ (edge[1] in subgraph.vertices): if weight < min_weight: a = edge a = weight subgraph.add_edge(__lowerCamelCase ,__lowerCamelCase ) return subgraph def SCREAMING_SNAKE_CASE__ ( snake_case_ = "p107_network.txt" ) -> int: """simple docstring""" a = os.path.abspath(os.path.dirname(snake_case_ ) ) a = os.path.join(snake_case_, snake_case_ ) a = {} a = 42 a = 42 a = 42 with open(snake_case_ ) as f: a = f.read().strip().split('''\n''' ) a = [line.split(''',''' ) for line in data] for edgea in range(1, len(snake_case_ ) ): for edgea in range(snake_case_ ): if adjaceny_matrix[edgea][edgea] != "-": a = int(adjaceny_matrix[edgea][edgea] ) a = Graph(set(range(len(snake_case_ ) ) ), snake_case_ ) a = graph.prims_algorithm() a = sum(graph.edges.values() ) a = sum(subgraph.edges.values() ) return initial_total - optimal_total if __name__ == "__main__": print(F"{solution() = }")
330
1
from typing import Any def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> list[Any]: """simple docstring""" if not input_list: return [] a = [input_list.count(snake_case_ ) for value in input_list] a = max(snake_case_ ) # Gets the maximum count in the input list. # Gets values of modes return sorted({input_list[i] for i, value in enumerate(snake_case_ ) if value == y} ) if __name__ == "__main__": import doctest doctest.testmod()
330
from typing import Optional, Tuple, Union import tensorflow as tf from ...activations_tf import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_tf_outputs import ( TFBaseModelOutputWithNoAttention, TFBaseModelOutputWithPoolingAndNoAttention, TFSequenceClassifierOutput, ) from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs from ...tf_utils import shape_list from ...utils import logging from .configuration_regnet import RegNetConfig UpperCamelCase__ : List[Any] = logging.get_logger(__name__) # General docstring UpperCamelCase__ : List[Any] = """RegNetConfig""" # Base docstring UpperCamelCase__ : Dict = """facebook/regnet-y-040""" UpperCamelCase__ : int = [1, 1_088, 7, 7] # Image classification docstring UpperCamelCase__ : Optional[Any] = """facebook/regnet-y-040""" UpperCamelCase__ : Dict = """tabby, tabby cat""" UpperCamelCase__ : Dict = [ """facebook/regnet-y-040""", # See all regnet models at https://huggingface.co/models?filter=regnet ] class lowerCamelCase_ ( tf.keras.layers.Layer ): def __init__( self : List[str] ,__lowerCamelCase : int ,__lowerCamelCase : int = 3 ,__lowerCamelCase : int = 1 ,__lowerCamelCase : int = 1 ,__lowerCamelCase : Optional[str] = "relu" ,**__lowerCamelCase : str ,): '''simple docstring''' super().__init__(**__lowerCamelCase ) # The padding and conv has been verified in # https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb a = tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2 ) a = tf.keras.layers.ConvaD( filters=__lowerCamelCase ,kernel_size=__lowerCamelCase ,strides=__lowerCamelCase ,padding='''VALID''' ,groups=__lowerCamelCase ,use_bias=__lowerCamelCase ,name='''convolution''' ,) a = tf.keras.layers.BatchNormalization(epsilon=1e-5 ,momentum=0.9 ,name='''normalization''' ) a = ACTaFN[activation] if activation is not None else tf.identity def SCREAMING_SNAKE_CASE_ ( self : str ,__lowerCamelCase : List[str] ): '''simple docstring''' a = self.convolution(self.padding(__lowerCamelCase ) ) a = self.normalization(__lowerCamelCase ) a = self.activation(__lowerCamelCase ) return hidden_state class lowerCamelCase_ ( tf.keras.layers.Layer ): def __init__( self : Any ,__lowerCamelCase : RegNetConfig ,**__lowerCamelCase : List[Any] ): '''simple docstring''' super().__init__(**__lowerCamelCase ) a = config.num_channels a = TFRegNetConvLayer( out_channels=config.embedding_size ,kernel_size=3 ,stride=2 ,activation=config.hidden_act ,name='''embedder''' ,) def SCREAMING_SNAKE_CASE_ ( self : Any ,__lowerCamelCase : Optional[Any] ): '''simple docstring''' a = shape_list(__lowerCamelCase )[1] if tf.executing_eagerly() and num_channels != self.num_channels: raise ValueError( '''Make sure that the channel dimension of the pixel values match with the one set in the configuration.''' ) # When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format. # So change the input format from `NCHW` to `NHWC`. # shape = (batch_size, in_height, in_width, in_channels=num_channels) a = tf.transpose(__lowerCamelCase ,perm=(0, 2, 3, 1) ) a = self.embedder(__lowerCamelCase ) return hidden_state class lowerCamelCase_ ( tf.keras.layers.Layer ): def __init__( self : str ,__lowerCamelCase : int ,__lowerCamelCase : int = 2 ,**__lowerCamelCase : Tuple ): '''simple docstring''' super().__init__(**__lowerCamelCase ) a = tf.keras.layers.ConvaD( filters=__lowerCamelCase ,kernel_size=1 ,strides=__lowerCamelCase ,use_bias=__lowerCamelCase ,name='''convolution''' ) a = tf.keras.layers.BatchNormalization(epsilon=1e-5 ,momentum=0.9 ,name='''normalization''' ) def SCREAMING_SNAKE_CASE_ ( self : Dict ,__lowerCamelCase : tf.Tensor ,__lowerCamelCase : bool = False ): '''simple docstring''' return self.normalization(self.convolution(__lowerCamelCase ) ,training=__lowerCamelCase ) class lowerCamelCase_ ( tf.keras.layers.Layer ): def __init__( self : List[Any] ,__lowerCamelCase : int ,__lowerCamelCase : int ,**__lowerCamelCase : str ): '''simple docstring''' super().__init__(**__lowerCamelCase ) a = tf.keras.layers.GlobalAveragePoolingaD(keepdims=__lowerCamelCase ,name='''pooler''' ) a = [ tf.keras.layers.ConvaD(filters=__lowerCamelCase ,kernel_size=1 ,activation='''relu''' ,name='''attention.0''' ), tf.keras.layers.ConvaD(filters=__lowerCamelCase ,kernel_size=1 ,activation='''sigmoid''' ,name='''attention.2''' ), ] def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ,__lowerCamelCase : Optional[Any] ): '''simple docstring''' a = self.pooler(__lowerCamelCase ) for layer_module in self.attention: a = layer_module(__lowerCamelCase ) a = hidden_state * pooled return hidden_state class lowerCamelCase_ ( tf.keras.layers.Layer ): def __init__( self : Union[str, Any] ,__lowerCamelCase : RegNetConfig ,__lowerCamelCase : int ,__lowerCamelCase : int ,__lowerCamelCase : int = 1 ,**__lowerCamelCase : Dict ): '''simple docstring''' super().__init__(**__lowerCamelCase ) a = in_channels != out_channels or stride != 1 a = max(1 ,out_channels // config.groups_width ) a = ( TFRegNetShortCut(__lowerCamelCase ,stride=__lowerCamelCase ,name='''shortcut''' ) if should_apply_shortcut else tf.keras.layers.Activation('''linear''' ,name='''shortcut''' ) ) # `self.layers` instead of `self.layer` because that is a reserved argument. a = [ TFRegNetConvLayer(__lowerCamelCase ,kernel_size=1 ,activation=config.hidden_act ,name='''layer.0''' ), TFRegNetConvLayer( __lowerCamelCase ,stride=__lowerCamelCase ,groups=__lowerCamelCase ,activation=config.hidden_act ,name='''layer.1''' ), TFRegNetConvLayer(__lowerCamelCase ,kernel_size=1 ,activation=__lowerCamelCase ,name='''layer.2''' ), ] a = ACTaFN[config.hidden_act] def SCREAMING_SNAKE_CASE_ ( self : List[str] ,__lowerCamelCase : Union[str, Any] ): '''simple docstring''' a = hidden_state for layer_module in self.layers: a = layer_module(__lowerCamelCase ) a = self.shortcut(__lowerCamelCase ) hidden_state += residual a = self.activation(__lowerCamelCase ) return hidden_state class lowerCamelCase_ ( tf.keras.layers.Layer ): def __init__( self : Dict ,__lowerCamelCase : RegNetConfig ,__lowerCamelCase : int ,__lowerCamelCase : int ,__lowerCamelCase : int = 1 ,**__lowerCamelCase : List[str] ): '''simple docstring''' super().__init__(**__lowerCamelCase ) a = in_channels != out_channels or stride != 1 a = max(1 ,out_channels // config.groups_width ) a = ( TFRegNetShortCut(__lowerCamelCase ,stride=__lowerCamelCase ,name='''shortcut''' ) if should_apply_shortcut else tf.keras.layers.Activation('''linear''' ,name='''shortcut''' ) ) a = [ TFRegNetConvLayer(__lowerCamelCase ,kernel_size=1 ,activation=config.hidden_act ,name='''layer.0''' ), TFRegNetConvLayer( __lowerCamelCase ,stride=__lowerCamelCase ,groups=__lowerCamelCase ,activation=config.hidden_act ,name='''layer.1''' ), TFRegNetSELayer(__lowerCamelCase ,reduced_channels=int(round(in_channels / 4 ) ) ,name='''layer.2''' ), TFRegNetConvLayer(__lowerCamelCase ,kernel_size=1 ,activation=__lowerCamelCase ,name='''layer.3''' ), ] a = ACTaFN[config.hidden_act] def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ,__lowerCamelCase : str ): '''simple docstring''' a = hidden_state for layer_module in self.layers: a = layer_module(__lowerCamelCase ) a = self.shortcut(__lowerCamelCase ) hidden_state += residual a = self.activation(__lowerCamelCase ) return hidden_state class lowerCamelCase_ ( tf.keras.layers.Layer ): def __init__( self : Optional[int] ,__lowerCamelCase : RegNetConfig ,__lowerCamelCase : int ,__lowerCamelCase : int ,__lowerCamelCase : int = 2 ,__lowerCamelCase : int = 2 ,**__lowerCamelCase : Optional[Any] ): '''simple docstring''' super().__init__(**__lowerCamelCase ) a = TFRegNetXLayer if config.layer_type == '''x''' else TFRegNetYLayer a = [ # downsampling is done in the first layer with stride of 2 layer(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ,stride=__lowerCamelCase ,name='''layers.0''' ), *[layer(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ,name=F"""layers.{i+1}""" ) for i in range(depth - 1 )], ] def SCREAMING_SNAKE_CASE_ ( self : Tuple ,__lowerCamelCase : int ): '''simple docstring''' for layer_module in self.layers: a = layer_module(__lowerCamelCase ) return hidden_state class lowerCamelCase_ ( tf.keras.layers.Layer ): def __init__( self : Union[str, Any] ,__lowerCamelCase : RegNetConfig ,**__lowerCamelCase : Optional[Any] ): '''simple docstring''' super().__init__(**__lowerCamelCase ) a = [] # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( TFRegNetStage( __lowerCamelCase ,config.embedding_size ,config.hidden_sizes[0] ,stride=2 if config.downsample_in_first_stage else 1 ,depth=config.depths[0] ,name='''stages.0''' ,) ) a = zip(config.hidden_sizes ,config.hidden_sizes[1:] ) for i, ((in_channels, out_channels), depth) in enumerate(zip(__lowerCamelCase ,config.depths[1:] ) ): self.stages.append(TFRegNetStage(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ,depth=__lowerCamelCase ,name=F"""stages.{i+1}""" ) ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ,__lowerCamelCase : tf.Tensor ,__lowerCamelCase : bool = False ,__lowerCamelCase : bool = True ): '''simple docstring''' a = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: a = hidden_states + (hidden_state,) a = stage_module(__lowerCamelCase ) if output_hidden_states: a = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return TFBaseModelOutputWithNoAttention(last_hidden_state=__lowerCamelCase ,hidden_states=__lowerCamelCase ) @keras_serializable class lowerCamelCase_ ( tf.keras.layers.Layer ): SCREAMING_SNAKE_CASE_ = RegNetConfig def __init__( self : Dict ,__lowerCamelCase : Optional[int] ,**__lowerCamelCase : Optional[Any] ): '''simple docstring''' super().__init__(**__lowerCamelCase ) a = config a = TFRegNetEmbeddings(__lowerCamelCase ,name='''embedder''' ) a = TFRegNetEncoder(__lowerCamelCase ,name='''encoder''' ) a = tf.keras.layers.GlobalAveragePoolingaD(keepdims=__lowerCamelCase ,name='''pooler''' ) @unpack_inputs def SCREAMING_SNAKE_CASE_ ( self : Tuple ,__lowerCamelCase : tf.Tensor ,__lowerCamelCase : Optional[bool] = None ,__lowerCamelCase : Optional[bool] = None ,__lowerCamelCase : bool = False ,): '''simple docstring''' a = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) a = return_dict if return_dict is not None else self.config.use_return_dict a = self.embedder(__lowerCamelCase ,training=__lowerCamelCase ) a = self.encoder( __lowerCamelCase ,output_hidden_states=__lowerCamelCase ,return_dict=__lowerCamelCase ,training=__lowerCamelCase ) a = encoder_outputs[0] a = self.pooler(__lowerCamelCase ) # Change to NCHW output format have uniformity in the modules a = tf.transpose(__lowerCamelCase ,perm=(0, 3, 1, 2) ) a = tf.transpose(__lowerCamelCase ,perm=(0, 3, 1, 2) ) # Change the other hidden state outputs to NCHW as well if output_hidden_states: a = tuple([tf.transpose(__lowerCamelCase ,perm=(0, 3, 1, 2) ) for h in encoder_outputs[1]] ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=__lowerCamelCase ,pooler_output=__lowerCamelCase ,hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states ,) class lowerCamelCase_ ( a_ ): SCREAMING_SNAKE_CASE_ = RegNetConfig SCREAMING_SNAKE_CASE_ = 'regnet' SCREAMING_SNAKE_CASE_ = 'pixel_values' @property def SCREAMING_SNAKE_CASE_ ( self : str ): '''simple docstring''' return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 2_24, 2_24) ,dtype=tf.floataa )} UpperCamelCase__ : Union[str, Any] = R""" Parameters: This model is a Tensorflow [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and behavior. config ([`RegNetConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights. """ UpperCamelCase__ : List[str] = R""" Args: pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`ConveNextImageProcessor.__call__`] for details. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. """ @add_start_docstrings( 'The bare RegNet model outputting raw features without any specific head on top.' , a_ , ) class lowerCamelCase_ ( a_ ): def __init__( self : Optional[int] ,__lowerCamelCase : RegNetConfig ,*__lowerCamelCase : int ,**__lowerCamelCase : Union[str, Any] ): '''simple docstring''' super().__init__(__lowerCamelCase ,*__lowerCamelCase ,**__lowerCamelCase ) a = TFRegNetMainLayer(__lowerCamelCase ,name='''regnet''' ) @unpack_inputs @add_start_docstrings_to_model_forward(__lowerCamelCase ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC ,output_type=__lowerCamelCase ,config_class=_CONFIG_FOR_DOC ,modality='''vision''' ,expected_output=_EXPECTED_OUTPUT_SHAPE ,) def SCREAMING_SNAKE_CASE_ ( self : Any ,__lowerCamelCase : tf.Tensor ,__lowerCamelCase : Optional[bool] = None ,__lowerCamelCase : Optional[bool] = None ,__lowerCamelCase : List[str]=False ,): '''simple docstring''' a = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) a = return_dict if return_dict is not None else self.config.use_return_dict a = self.regnet( pixel_values=__lowerCamelCase ,output_hidden_states=__lowerCamelCase ,return_dict=__lowerCamelCase ,training=__lowerCamelCase ,) if not return_dict: return (outputs[0],) + outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=outputs.last_hidden_state ,pooler_output=outputs.pooler_output ,hidden_states=outputs.hidden_states ,) @add_start_docstrings( '\n RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n ' , a_ , ) class lowerCamelCase_ ( a_ , a_ ): def __init__( self : Optional[int] ,__lowerCamelCase : RegNetConfig ,*__lowerCamelCase : str ,**__lowerCamelCase : Any ): '''simple docstring''' super().__init__(__lowerCamelCase ,*__lowerCamelCase ,**__lowerCamelCase ) a = config.num_labels a = TFRegNetMainLayer(__lowerCamelCase ,name='''regnet''' ) # classification head a = [ tf.keras.layers.Flatten(), tf.keras.layers.Dense(config.num_labels ,name='''classifier.1''' ) if config.num_labels > 0 else tf.identity, ] @unpack_inputs @add_start_docstrings_to_model_forward(__lowerCamelCase ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT ,output_type=__lowerCamelCase ,config_class=_CONFIG_FOR_DOC ,expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT ,) def SCREAMING_SNAKE_CASE_ ( self : Tuple ,__lowerCamelCase : tf.Tensor = None ,__lowerCamelCase : tf.Tensor = None ,__lowerCamelCase : bool = None ,__lowerCamelCase : bool = None ,__lowerCamelCase : Dict=False ,): '''simple docstring''' a = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) a = return_dict if return_dict is not None else self.config.use_return_dict a = self.regnet( __lowerCamelCase ,output_hidden_states=__lowerCamelCase ,return_dict=__lowerCamelCase ,training=__lowerCamelCase ) a = outputs.pooler_output if return_dict else outputs[1] a = self.classifier[0](__lowerCamelCase ) a = self.classifier[1](__lowerCamelCase ) a = None if labels is None else self.hf_compute_loss(labels=__lowerCamelCase ,logits=__lowerCamelCase ) if not return_dict: a = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return TFSequenceClassifierOutput(loss=__lowerCamelCase ,logits=__lowerCamelCase ,hidden_states=outputs.hidden_states )
330
1
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase__ : Union[str, Any] = logging.get_logger(__name__) UpperCamelCase__ : Optional[Any] = { """google/realm-cc-news-pretrained-embedder""": ( """https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/config.json""" ), """google/realm-cc-news-pretrained-encoder""": ( """https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/config.json""" ), """google/realm-cc-news-pretrained-scorer""": ( """https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/config.json""" ), """google/realm-cc-news-pretrained-openqa""": ( """https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/config.json""" ), """google/realm-orqa-nq-openqa""": """https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/config.json""", """google/realm-orqa-nq-reader""": """https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/config.json""", """google/realm-orqa-wq-openqa""": """https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/config.json""", """google/realm-orqa-wq-reader""": """https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/config.json""", # See all REALM models at https://huggingface.co/models?filter=realm } class lowerCamelCase_ ( a_ ): SCREAMING_SNAKE_CASE_ = 'realm' def __init__( self : Optional[Any] ,__lowerCamelCase : Any=3_05_22 ,__lowerCamelCase : Optional[Any]=7_68 ,__lowerCamelCase : Tuple=1_28 ,__lowerCamelCase : Optional[int]=12 ,__lowerCamelCase : int=12 ,__lowerCamelCase : Any=8 ,__lowerCamelCase : List[Any]=30_72 ,__lowerCamelCase : Optional[int]="gelu_new" ,__lowerCamelCase : Dict=0.1 ,__lowerCamelCase : Any=0.1 ,__lowerCamelCase : int=5_12 ,__lowerCamelCase : Dict=2 ,__lowerCamelCase : Dict=0.02 ,__lowerCamelCase : Any=1e-12 ,__lowerCamelCase : Optional[int]=2_56 ,__lowerCamelCase : List[Any]=10 ,__lowerCamelCase : List[Any]=1e-3 ,__lowerCamelCase : Any=5 ,__lowerCamelCase : str=3_20 ,__lowerCamelCase : Optional[int]=13_35_37_18 ,__lowerCamelCase : str=50_00 ,__lowerCamelCase : Any=1 ,__lowerCamelCase : Optional[int]=0 ,__lowerCamelCase : Optional[Any]=2 ,**__lowerCamelCase : int ,): '''simple docstring''' super().__init__(pad_token_id=__lowerCamelCase ,bos_token_id=__lowerCamelCase ,eos_token_id=__lowerCamelCase ,**__lowerCamelCase ) # Common config a = vocab_size a = max_position_embeddings a = hidden_size a = retriever_proj_size a = num_hidden_layers a = num_attention_heads a = num_candidates a = intermediate_size a = hidden_act a = hidden_dropout_prob a = attention_probs_dropout_prob a = initializer_range a = type_vocab_size a = layer_norm_eps # Reader config a = span_hidden_size a = max_span_width a = reader_layer_norm_eps a = reader_beam_size a = reader_seq_len # Retrieval config a = num_block_records a = searcher_beam_size
330
from typing import List from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase__ : Union[str, Any] = logging.get_logger(__name__) UpperCamelCase__ : List[str] = { """snap-research/efficientformer-l1-300""": ( """https://huggingface.co/snap-research/efficientformer-l1-300/resolve/main/config.json""" ), } class lowerCamelCase_ ( a_ ): SCREAMING_SNAKE_CASE_ = 'efficientformer' def __init__( self : Optional[int] ,__lowerCamelCase : List[int] = [3, 2, 6, 4] ,__lowerCamelCase : List[int] = [48, 96, 2_24, 4_48] ,__lowerCamelCase : List[bool] = [True, True, True, True] ,__lowerCamelCase : int = 4_48 ,__lowerCamelCase : int = 32 ,__lowerCamelCase : int = 4 ,__lowerCamelCase : int = 7 ,__lowerCamelCase : int = 5 ,__lowerCamelCase : int = 8 ,__lowerCamelCase : int = 4 ,__lowerCamelCase : float = 0.0 ,__lowerCamelCase : int = 16 ,__lowerCamelCase : int = 3 ,__lowerCamelCase : int = 3 ,__lowerCamelCase : int = 3 ,__lowerCamelCase : int = 2 ,__lowerCamelCase : int = 1 ,__lowerCamelCase : float = 0.0 ,__lowerCamelCase : int = 1 ,__lowerCamelCase : bool = True ,__lowerCamelCase : bool = True ,__lowerCamelCase : float = 1e-5 ,__lowerCamelCase : str = "gelu" ,__lowerCamelCase : float = 0.02 ,__lowerCamelCase : float = 1e-12 ,__lowerCamelCase : int = 2_24 ,__lowerCamelCase : float = 1e-05 ,**__lowerCamelCase : Dict ,): '''simple docstring''' super().__init__(**__lowerCamelCase ) a = hidden_act a = hidden_dropout_prob a = hidden_sizes a = num_hidden_layers a = num_attention_heads a = initializer_range a = layer_norm_eps a = patch_size a = num_channels a = depths a = mlp_expansion_ratio a = downsamples a = dim a = key_dim a = attention_ratio a = resolution a = pool_size a = downsample_patch_size a = downsample_stride a = downsample_pad a = drop_path_rate a = num_metaad_blocks a = distillation a = use_layer_scale a = layer_scale_init_value a = image_size a = batch_norm_eps
330
1
import warnings warnings.warn( """memory_utils has been reorganized to utils.memory. Import `find_executable_batchsize` from the main `__init__`: """ """`from accelerate import find_executable_batch_size` to avoid this warning.""", FutureWarning, )
330
import argparse from typing import Dict import tensorflow as tf import torch from tqdm import tqdm from transformers import BigBirdPegasusConfig, BigBirdPegasusForConditionalGeneration UpperCamelCase__ : Any = [ # tf -> hf ("""/""", """."""), ("""layer_""", """layers."""), ("""kernel""", """weight"""), ("""beta""", """bias"""), ("""gamma""", """weight"""), ("""pegasus""", """model"""), ] UpperCamelCase__ : Optional[Any] = [ (""".output.dense""", """.fc2"""), ("""intermediate.LayerNorm""", """final_layer_norm"""), ("""intermediate.dense""", """fc1"""), ] UpperCamelCase__ : Optional[Any] = ( INIT_COMMON + [ ("""attention.self.LayerNorm""", """self_attn_layer_norm"""), ("""attention.output.dense""", """self_attn.out_proj"""), ("""attention.self""", """self_attn"""), ("""attention.encdec.LayerNorm""", """encoder_attn_layer_norm"""), ("""attention.encdec_output.dense""", """encoder_attn.out_proj"""), ("""attention.encdec""", """encoder_attn"""), ("""key""", """k_proj"""), ("""value""", """v_proj"""), ("""query""", """q_proj"""), ("""decoder.LayerNorm""", """decoder.layernorm_embedding"""), ] + END_COMMON ) UpperCamelCase__ : List[str] = ( INIT_COMMON + [ ("""embeddings.word_embeddings""", """shared.weight"""), ("""embeddings.position_embeddings""", """embed_positions.weight"""), ("""attention.self.LayerNorm""", """self_attn_layer_norm"""), ("""attention.output.dense""", """self_attn.output"""), ("""attention.self""", """self_attn.self"""), ("""encoder.LayerNorm""", """encoder.layernorm_embedding"""), ] + END_COMMON ) UpperCamelCase__ : Optional[int] = [ """encdec/key/bias""", """encdec/query/bias""", """encdec/value/bias""", """self/key/bias""", """self/query/bias""", """self/value/bias""", """encdec_output/dense/bias""", """attention/output/dense/bias""", ] def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> List[Any]: """simple docstring""" for tf_name, hf_name in patterns: a = k.replace(snake_case_, snake_case_ ) return k def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> BigBirdPegasusForConditionalGeneration: """simple docstring""" a = BigBirdPegasusConfig(**snake_case_ ) a = BigBirdPegasusForConditionalGeneration(snake_case_ ) a = torch_model.state_dict() a = {} # separating decoder weights a = {k: tf_weights[k] for k in tf_weights if k.startswith('''pegasus/decoder''' )} a = {k: tf_weights[k] for k in tf_weights if not k.startswith('''pegasus/decoder''' )} for k, v in tqdm(decoder_weights.items(), '''tf -> hf conversion''' ): a = [k.endswith(snake_case_ ) for ending in KEYS_TO_IGNORE] if any(snake_case_ ): continue a = DECODER_PATTERNS a = rename_state_dict_key(snake_case_, snake_case_ ) if new_k not in state_dict: raise ValueError(f"""could not find new key {new_k} in state dict. (converted from {k})""" ) if any(True if i in k else False for i in ['''dense''', '''query''', '''key''', '''value'''] ): a = v.T a = torch.from_numpy(snake_case_ ) assert v.shape == state_dict[new_k].shape, f"""{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}""" for k, v in tqdm(remaining_weights.items(), '''tf -> hf conversion''' ): a = [k.endswith(snake_case_ ) for ending in KEYS_TO_IGNORE] if any(snake_case_ ): continue a = REMAINING_PATTERNS a = rename_state_dict_key(snake_case_, snake_case_ ) if new_k not in state_dict and k != "pegasus/embeddings/position_embeddings": raise ValueError(f"""could not find new key {new_k} in state dict. (converted from {k})""" ) if any(True if i in k else False for i in ['''dense''', '''query''', '''key''', '''value'''] ): a = v.T a = torch.from_numpy(snake_case_ ) if k != "pegasus/embeddings/position_embeddings": assert v.shape == state_dict[new_k].shape, f"""{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}""" a = mapping['''model.embed_positions.weight'''] a = mapping.pop('''model.embed_positions.weight''' ) a , a = torch_model.load_state_dict(snake_case_, strict=snake_case_ ) a = [ k for k in missing if k not in [ '''final_logits_bias''', '''model.encoder.embed_tokens.weight''', '''model.decoder.embed_tokens.weight''', '''lm_head.weight''', ] ] assert unexpected_missing == [], f"""no matches found for the following torch keys {unexpected_missing}""" assert extra == [], f"""no matches found for the following tf keys {extra}""" return torch_model def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> Dict: """simple docstring""" a = tf.train.list_variables(snake_case_ ) a = {} a = ['''global_step'''] for name, shape in tqdm(snake_case_, desc='''converting tf checkpoint to dict''' ): a = any(pat in name for pat in ignore_name ) if skip_key: continue a = tf.train.load_variable(snake_case_, snake_case_ ) a = array return tf_weights def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_ ) -> int: """simple docstring""" a = get_tf_weights_as_numpy(snake_case_ ) a = convert_bigbird_pegasus(snake_case_, snake_case_ ) torch_model.save_pretrained(snake_case_ ) if __name__ == "__main__": UpperCamelCase__ : str = argparse.ArgumentParser() parser.add_argument("""--tf_ckpt_path""", type=str, help="""passed to tf.train.list_variables""") parser.add_argument("""--save_dir""", default=None, type=str, help="""Path to the output PyTorch model.""") UpperCamelCase__ : int = parser.parse_args() UpperCamelCase__ : Tuple = {} convert_bigbird_pegasus_ckpt_to_pytorch(args.tf_ckpt_path, args.save_dir, config_update=config_update)
330
1
import unittest from parameterized import parameterized from transformers import OpenLlamaConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import OpenLlamaForCausalLM, OpenLlamaForSequenceClassification, OpenLlamaModel class lowerCamelCase_ : def __init__( self : Any ,__lowerCamelCase : Any ,__lowerCamelCase : Tuple=13 ,__lowerCamelCase : str=7 ,__lowerCamelCase : Tuple=True ,__lowerCamelCase : Optional[Any]=True ,__lowerCamelCase : Optional[int]=False ,__lowerCamelCase : Dict=True ,__lowerCamelCase : List[Any]=99 ,__lowerCamelCase : int=32 ,__lowerCamelCase : Dict=5 ,__lowerCamelCase : Optional[int]=4 ,__lowerCamelCase : Optional[int]=37 ,__lowerCamelCase : Tuple="gelu" ,__lowerCamelCase : int=0.1 ,__lowerCamelCase : str=0.1 ,__lowerCamelCase : List[Any]=5_12 ,__lowerCamelCase : Any=16 ,__lowerCamelCase : List[Any]=2 ,__lowerCamelCase : Union[str, Any]=0.02 ,__lowerCamelCase : Any=3 ,__lowerCamelCase : str=4 ,__lowerCamelCase : int=None ,): '''simple docstring''' a = parent a = batch_size a = seq_length a = is_training a = use_input_mask a = use_token_type_ids a = use_labels a = vocab_size 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 = max_position_embeddings a = type_vocab_size a = type_sequence_label_size a = initializer_range a = num_labels a = num_choices a = scope def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ): '''simple docstring''' a = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) a = None if self.use_input_mask: a = random_attention_mask([self.batch_size, self.seq_length] ) a = None if self.use_token_type_ids: a = ids_tensor([self.batch_size, self.seq_length] ,self.type_vocab_size ) a = None a = None a = None if self.use_labels: a = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) a = ids_tensor([self.batch_size, self.seq_length] ,self.num_labels ) a = ids_tensor([self.batch_size] ,self.num_choices ) a = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE_ ( self : Any ): '''simple docstring''' return OpenLlamaConfig( 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 ,use_stable_embedding=__lowerCamelCase ,) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ,__lowerCamelCase : Optional[int] ,__lowerCamelCase : Dict ,__lowerCamelCase : List[Any] ,__lowerCamelCase : List[str] ,__lowerCamelCase : Union[str, Any] ,__lowerCamelCase : List[Any] ,__lowerCamelCase : List[str] ): '''simple docstring''' a = OpenLlamaModel(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() a = model(__lowerCamelCase ,attention_mask=__lowerCamelCase ) a = model(__lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ,__lowerCamelCase : List[str] ,__lowerCamelCase : List[str] ,__lowerCamelCase : Any ,__lowerCamelCase : str ,__lowerCamelCase : List[Any] ,__lowerCamelCase : List[str] ,__lowerCamelCase : Dict ,__lowerCamelCase : Tuple ,__lowerCamelCase : Tuple ,): '''simple docstring''' a = True a = OpenLlamaModel(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() a = model( __lowerCamelCase ,attention_mask=__lowerCamelCase ,encoder_hidden_states=__lowerCamelCase ,encoder_attention_mask=__lowerCamelCase ,) a = model( __lowerCamelCase ,attention_mask=__lowerCamelCase ,encoder_hidden_states=__lowerCamelCase ,) a = model(__lowerCamelCase ,attention_mask=__lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ,__lowerCamelCase : Union[str, Any] ,__lowerCamelCase : str ,__lowerCamelCase : List[Any] ,__lowerCamelCase : Optional[int] ,__lowerCamelCase : List[Any] ,__lowerCamelCase : Any ,__lowerCamelCase : Union[str, Any] ,__lowerCamelCase : Optional[int] ,__lowerCamelCase : Optional[int] ,): '''simple docstring''' a = OpenLlamaForCausalLM(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() a = model(__lowerCamelCase ,attention_mask=__lowerCamelCase ,labels=__lowerCamelCase ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE_ ( self : int ,__lowerCamelCase : int ,__lowerCamelCase : Tuple ,__lowerCamelCase : Tuple ,__lowerCamelCase : Optional[Any] ,__lowerCamelCase : List[Any] ,__lowerCamelCase : List[Any] ,__lowerCamelCase : int ,__lowerCamelCase : Any ,__lowerCamelCase : List[str] ,): '''simple docstring''' a = True a = True a = OpenLlamaForCausalLM(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() # first forward pass a = model( __lowerCamelCase ,attention_mask=__lowerCamelCase ,encoder_hidden_states=__lowerCamelCase ,encoder_attention_mask=__lowerCamelCase ,use_cache=__lowerCamelCase ,) a = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids a = ids_tensor((self.batch_size, 3) ,config.vocab_size ) a = ids_tensor((self.batch_size, 3) ,vocab_size=2 ) # append to next input_ids and a = torch.cat([input_ids, next_tokens] ,dim=-1 ) a = torch.cat([input_mask, next_mask] ,dim=-1 ) a = model( __lowerCamelCase ,attention_mask=__lowerCamelCase ,encoder_hidden_states=__lowerCamelCase ,encoder_attention_mask=__lowerCamelCase ,output_hidden_states=__lowerCamelCase ,)['''hidden_states'''][0] a = model( __lowerCamelCase ,attention_mask=__lowerCamelCase ,encoder_hidden_states=__lowerCamelCase ,encoder_attention_mask=__lowerCamelCase ,past_key_values=__lowerCamelCase ,output_hidden_states=__lowerCamelCase ,)['''hidden_states'''][0] # select random slice a = ids_tensor((1,) ,output_from_past.shape[-1] ).item() a = output_from_no_past[:, -3:, random_slice_idx].detach() a = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(__lowerCamelCase ,__lowerCamelCase ,atol=1e-3 ) ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ): '''simple docstring''' a = self.prepare_config_and_inputs() ( ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ) = config_and_inputs a = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class lowerCamelCase_ ( a_ , a_ , a_ , unittest.TestCase ): SCREAMING_SNAKE_CASE_ = ( (OpenLlamaModel, OpenLlamaForCausalLM, OpenLlamaForSequenceClassification) if is_torch_available() else () ) SCREAMING_SNAKE_CASE_ = (OpenLlamaForCausalLM,) if is_torch_available() else () SCREAMING_SNAKE_CASE_ = ( { 'feature-extraction': OpenLlamaModel, 'text-classification': OpenLlamaForSequenceClassification, 'text-generation': OpenLlamaForCausalLM, 'zero-shot': OpenLlamaForSequenceClassification, } if is_torch_available() else {} ) SCREAMING_SNAKE_CASE_ = False SCREAMING_SNAKE_CASE_ = False def SCREAMING_SNAKE_CASE_ ( self : List[str] ): '''simple docstring''' a = OpenLlamaModelTester(self ) a = ConfigTester(self ,config_class=__lowerCamelCase ,hidden_size=37 ) def SCREAMING_SNAKE_CASE_ ( self : int ): '''simple docstring''' self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE_ ( self : int ): '''simple docstring''' a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ): '''simple docstring''' a = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: a = type self.model_tester.create_and_check_model(*__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ): '''simple docstring''' a , a = self.model_tester.prepare_config_and_inputs_for_common() a = 3 a = input_dict['''input_ids'''] a = input_ids.ne(1 ).to(__lowerCamelCase ) a = ids_tensor([self.model_tester.batch_size] ,self.model_tester.type_sequence_label_size ) a = OpenLlamaForSequenceClassification(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() a = model(__lowerCamelCase ,attention_mask=__lowerCamelCase ,labels=__lowerCamelCase ) self.assertEqual(result.logits.shape ,(self.model_tester.batch_size, self.model_tester.num_labels) ) def SCREAMING_SNAKE_CASE_ ( self : str ): '''simple docstring''' a , a = self.model_tester.prepare_config_and_inputs_for_common() a = 3 a = '''single_label_classification''' a = input_dict['''input_ids'''] a = input_ids.ne(1 ).to(__lowerCamelCase ) a = ids_tensor([self.model_tester.batch_size] ,self.model_tester.type_sequence_label_size ) a = OpenLlamaForSequenceClassification(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() a = model(__lowerCamelCase ,attention_mask=__lowerCamelCase ,labels=__lowerCamelCase ) self.assertEqual(result.logits.shape ,(self.model_tester.batch_size, self.model_tester.num_labels) ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ): '''simple docstring''' a , a = self.model_tester.prepare_config_and_inputs_for_common() a = 3 a = '''multi_label_classification''' a = input_dict['''input_ids'''] a = input_ids.ne(1 ).to(__lowerCamelCase ) a = ids_tensor( [self.model_tester.batch_size, config.num_labels] ,self.model_tester.type_sequence_label_size ).to(torch.float ) a = OpenLlamaForSequenceClassification(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() a = model(__lowerCamelCase ,attention_mask=__lowerCamelCase ,labels=__lowerCamelCase ) self.assertEqual(result.logits.shape ,(self.model_tester.batch_size, self.model_tester.num_labels) ) @unittest.skip('''Open-Llama buffers include complex numbers, which breaks this test''' ) def SCREAMING_SNAKE_CASE_ ( self : str ): '''simple docstring''' pass @parameterized.expand([('''linear''',), ('''dynamic''',)] ) def SCREAMING_SNAKE_CASE_ ( self : str ,__lowerCamelCase : List[Any] ): '''simple docstring''' a , a = self.model_tester.prepare_config_and_inputs_for_common() a = ids_tensor([1, 10] ,config.vocab_size ) a = ids_tensor([1, int(config.max_position_embeddings * 1.5 )] ,config.vocab_size ) set_seed(42 ) # Fixed seed at init time so the two models get the same random weights a = OpenLlamaModel(__lowerCamelCase ) original_model.to(__lowerCamelCase ) original_model.eval() a = original_model(__lowerCamelCase ).last_hidden_state a = original_model(__lowerCamelCase ).last_hidden_state set_seed(42 ) # Fixed seed at init time so the two models get the same random weights a = {'''type''': scaling_type, '''factor''': 10.0} a = OpenLlamaModel(__lowerCamelCase ) scaled_model.to(__lowerCamelCase ) scaled_model.eval() a = scaled_model(__lowerCamelCase ).last_hidden_state a = scaled_model(__lowerCamelCase ).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(__lowerCamelCase ,__lowerCamelCase ,atol=1e-5 ) ) else: self.assertFalse(torch.allclose(__lowerCamelCase ,__lowerCamelCase ,atol=1e-5 ) ) # The output should be different for long inputs self.assertFalse(torch.allclose(__lowerCamelCase ,__lowerCamelCase ,atol=1e-5 ) )
330
import re def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> str: """simple docstring""" if len(re.findall('''[ATCG]''', snake_case_ ) ) != len(snake_case_ ): raise ValueError('''Invalid Strand''' ) return dna.translate(dna.maketrans('''ATCG''', '''TAGC''' ) ) if __name__ == "__main__": import doctest doctest.testmod()
330
1
import collections import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_flax_cross_test, require_flax, require_torch, require_vision, slow, torch_device, ) from transformers.utils import is_flax_available, is_torch_available, is_vision_available from ...test_modeling_flax_common import floats_tensor, ids_tensor, random_attention_mask from ..bert.test_modeling_flax_bert import FlaxBertModelTester from ..clip.test_modeling_flax_clip import FlaxCLIPVisionModelTester from ..vit.test_modeling_flax_vit import FlaxViTModelTester if is_flax_available(): from transformers import ( FlaxBertModel, FlaxCLIPVisionModel, FlaxVisionTextDualEncoderModel, FlaxViTModel, VisionTextDualEncoderConfig, VisionTextDualEncoderProcessor, ) from transformers.modeling_flax_pytorch_utils import ( convert_pytorch_state_dict_to_flax, load_flax_weights_in_pytorch_model, ) if is_torch_available(): import torch from transformers import VisionTextDualEncoderModel if is_vision_available(): from PIL import Image def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> str: """simple docstring""" if isinstance(snake_case_, collections.abc.Iterable ): return x return (x, x) @require_flax class lowerCamelCase_ : def SCREAMING_SNAKE_CASE_ ( self : Tuple ,__lowerCamelCase : Tuple ,__lowerCamelCase : Union[str, Any] ): '''simple docstring''' pass def SCREAMING_SNAKE_CASE_ ( self : List[Any] ): '''simple docstring''' pass def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ): '''simple docstring''' pass def SCREAMING_SNAKE_CASE_ ( self : List[str] ,__lowerCamelCase : np.ndarray ,__lowerCamelCase : np.ndarray ,__lowerCamelCase : float ): '''simple docstring''' a = np.abs((a - b) ).max() self.assertLessEqual(__lowerCamelCase ,__lowerCamelCase ,F"""Difference between torch and flax is {diff} (>= {tol}).""" ) def SCREAMING_SNAKE_CASE_ ( self : int ,__lowerCamelCase : List[str] ,__lowerCamelCase : Any ,__lowerCamelCase : Optional[int] ,__lowerCamelCase : Any ,__lowerCamelCase : Optional[Any]=None ,**__lowerCamelCase : Dict ): '''simple docstring''' a = VisionTextDualEncoderConfig.from_vision_text_configs(__lowerCamelCase ,__lowerCamelCase ) a = FlaxVisionTextDualEncoderModel(__lowerCamelCase ) a = model(input_ids=__lowerCamelCase ,pixel_values=__lowerCamelCase ,attention_mask=__lowerCamelCase ) self.assertEqual(output['''text_embeds'''].shape ,(input_ids.shape[0], config.projection_dim) ) self.assertEqual(output['''image_embeds'''].shape ,(pixel_values.shape[0], config.projection_dim) ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ,__lowerCamelCase : Union[str, Any] ,__lowerCamelCase : str ,__lowerCamelCase : Optional[int] ,__lowerCamelCase : str ,__lowerCamelCase : Any=None ,**__lowerCamelCase : str ): '''simple docstring''' a , a = self.get_vision_text_model(__lowerCamelCase ,__lowerCamelCase ) a = {'''vision_model''': vision_model, '''text_model''': text_model} a = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**__lowerCamelCase ) a = model(input_ids=__lowerCamelCase ,pixel_values=__lowerCamelCase ,attention_mask=__lowerCamelCase ) self.assertEqual(output['''text_embeds'''].shape ,(input_ids.shape[0], model.config.projection_dim) ) self.assertEqual(output['''image_embeds'''].shape ,(pixel_values.shape[0], model.config.projection_dim) ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ,__lowerCamelCase : int ,__lowerCamelCase : Optional[Any] ,__lowerCamelCase : Optional[int] ,__lowerCamelCase : Any ,__lowerCamelCase : Union[str, Any]=None ,**__lowerCamelCase : Optional[Any] ): '''simple docstring''' a , a = self.get_vision_text_model(__lowerCamelCase ,__lowerCamelCase ) a = {'''vision_model''': vision_model, '''text_model''': text_model} a = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**__lowerCamelCase ) a = model(input_ids=__lowerCamelCase ,pixel_values=__lowerCamelCase ,attention_mask=__lowerCamelCase ) a = output[0] with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(__lowerCamelCase ) a = FlaxVisionTextDualEncoderModel.from_pretrained(__lowerCamelCase ) a = model(input_ids=__lowerCamelCase ,pixel_values=__lowerCamelCase ,attention_mask=__lowerCamelCase ) a = after_output[0] a = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(__lowerCamelCase ,1e-3 ) def SCREAMING_SNAKE_CASE_ ( self : Dict ,__lowerCamelCase : List[str] ,__lowerCamelCase : str ,__lowerCamelCase : Tuple ,__lowerCamelCase : Any ,__lowerCamelCase : Any=None ,**__lowerCamelCase : str ): '''simple docstring''' a , a = self.get_vision_text_model(__lowerCamelCase ,__lowerCamelCase ) a = {'''vision_model''': vision_model, '''text_model''': text_model} a = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**__lowerCamelCase ) a = model( input_ids=__lowerCamelCase ,pixel_values=__lowerCamelCase ,attention_mask=__lowerCamelCase ,output_attentions=__lowerCamelCase ) a = output.vision_model_output.attentions self.assertEqual(len(__lowerCamelCase ) ,vision_config.num_hidden_layers ) # in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token) a = to_atuple(vision_model.config.image_size ) a = to_atuple(vision_model.config.patch_size ) a = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) a = num_patches + 1 self.assertEqual(vision_attentions[0].shape[-3:] ,(vision_config.num_attention_heads, seq_len, seq_len) ) a = output.text_model_output.attentions self.assertEqual(len(__lowerCamelCase ) ,text_config.num_hidden_layers ) self.assertEqual( text_attentions[0].shape[-3:] ,(text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1]) ,) def SCREAMING_SNAKE_CASE_ ( self : Tuple ,__lowerCamelCase : Tuple ,__lowerCamelCase : Optional[Any] ,__lowerCamelCase : Tuple ): '''simple docstring''' pt_model.to(__lowerCamelCase ) pt_model.eval() # prepare inputs a = inputs_dict a = {k: torch.tensor(v.tolist() ) for k, v in flax_inputs.items()} with torch.no_grad(): a = pt_model(**__lowerCamelCase ).to_tuple() a = fx_model(**__lowerCamelCase ).to_tuple() self.assertEqual(len(__lowerCamelCase ) ,len(__lowerCamelCase ) ,'''Output lengths differ between Flax and PyTorch''' ) for fx_output, pt_output in zip(fx_outputs[:4] ,pt_outputs[:4] ): self.assert_almost_equals(__lowerCamelCase ,pt_output.numpy() ,4e-2 ) # PT -> Flax with tempfile.TemporaryDirectory() as tmpdirname: pt_model.save_pretrained(__lowerCamelCase ) a = FlaxVisionTextDualEncoderModel.from_pretrained(__lowerCamelCase ,from_pt=__lowerCamelCase ) a = fx_model_loaded(**__lowerCamelCase ).to_tuple() self.assertEqual(len(__lowerCamelCase ) ,len(__lowerCamelCase ) ,'''Output lengths differ between Flax and PyTorch''' ) for fx_output_loaded, pt_output in zip(fx_outputs_loaded[:4] ,pt_outputs[:4] ): self.assert_almost_equals(__lowerCamelCase ,pt_output.numpy() ,4e-2 ) # Flax -> PT with tempfile.TemporaryDirectory() as tmpdirname: fx_model.save_pretrained(__lowerCamelCase ) a = VisionTextDualEncoderModel.from_pretrained(__lowerCamelCase ,from_flax=__lowerCamelCase ) pt_model_loaded.to(__lowerCamelCase ) pt_model_loaded.eval() with torch.no_grad(): a = pt_model_loaded(**__lowerCamelCase ).to_tuple() self.assertEqual(len(__lowerCamelCase ) ,len(__lowerCamelCase ) ,'''Output lengths differ between Flax and PyTorch''' ) for fx_output, pt_output_loaded in zip(fx_outputs[:4] ,pt_outputs_loaded[:4] ): self.assert_almost_equals(__lowerCamelCase ,pt_output_loaded.numpy() ,4e-2 ) def SCREAMING_SNAKE_CASE_ ( self : str ,__lowerCamelCase : Optional[int] ,__lowerCamelCase : Union[str, Any] ,__lowerCamelCase : Optional[Any] ): '''simple docstring''' a = VisionTextDualEncoderConfig.from_vision_text_configs(__lowerCamelCase ,__lowerCamelCase ) a = VisionTextDualEncoderModel(__lowerCamelCase ) a = FlaxVisionTextDualEncoderModel(__lowerCamelCase ) a = convert_pytorch_state_dict_to_flax(pt_model.state_dict() ,__lowerCamelCase ) a = fx_state self.check_pt_flax_equivalence(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ,__lowerCamelCase : Any ,__lowerCamelCase : Union[str, Any] ,__lowerCamelCase : Any ): '''simple docstring''' a = VisionTextDualEncoderConfig.from_vision_text_configs(__lowerCamelCase ,__lowerCamelCase ) a = VisionTextDualEncoderModel(__lowerCamelCase ) a = FlaxVisionTextDualEncoderModel(__lowerCamelCase ) a = load_flax_weights_in_pytorch_model(__lowerCamelCase ,fx_model.params ) self.check_pt_flax_equivalence(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ): '''simple docstring''' a = self.prepare_config_and_inputs() self.check_model_from_pretrained_configs(**__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ): '''simple docstring''' a = self.prepare_config_and_inputs() self.check_vision_text_dual_encoder_from_pretrained(**__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ): '''simple docstring''' a = self.prepare_config_and_inputs() self.check_save_load(**__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ): '''simple docstring''' a = self.prepare_config_and_inputs() self.check_vision_text_output_attention(**__lowerCamelCase ) @is_pt_flax_cross_test def SCREAMING_SNAKE_CASE_ ( self : List[Any] ): '''simple docstring''' a = self.prepare_config_and_inputs() a = config_inputs_dict.pop('''vision_config''' ) a = config_inputs_dict.pop('''text_config''' ) a = config_inputs_dict self.check_equivalence_pt_to_flax(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ) self.check_equivalence_flax_to_pt(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self : Tuple ): '''simple docstring''' a , a = self.get_pretrained_model_and_inputs() a = model_a(**__lowerCamelCase ) a = outputs[0] with tempfile.TemporaryDirectory() as tmp_dirname: model_a.save_pretrained(__lowerCamelCase ) a = FlaxVisionTextDualEncoderModel.from_pretrained(__lowerCamelCase ) a = model_a(**__lowerCamelCase ) a = after_outputs[0] a = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(__lowerCamelCase ,1e-5 ) @require_flax class lowerCamelCase_ ( a_ , unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self : List[Any] ): '''simple docstring''' a = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained( '''hf-internal-testing/tiny-random-vit''' ,'''hf-internal-testing/tiny-bert''' ,vision_from_pt=__lowerCamelCase ,text_from_pt=__lowerCamelCase ,) a = 13 a = floats_tensor( [ batch_size, model.config.vision_config.num_channels, model.config.vision_config.image_size, model.config.vision_config.image_size, ] ) a = ids_tensor([batch_size, 4] ,model.config.text_config.vocab_size ) a = random_attention_mask([batch_size, 4] ) a = {'''pixel_values''': pixel_values, '''input_ids''': input_ids, '''attention_mask''': attention_mask} return model, inputs def SCREAMING_SNAKE_CASE_ ( self : int ,__lowerCamelCase : List[str] ,__lowerCamelCase : Tuple ): '''simple docstring''' a = FlaxViTModel(__lowerCamelCase ) a = FlaxBertModel(__lowerCamelCase ) return vision_model, text_model def SCREAMING_SNAKE_CASE_ ( self : Dict ): '''simple docstring''' a = FlaxViTModelTester(self ) a = FlaxBertModelTester(self ) a = vit_model_tester.prepare_config_and_inputs() a = bert_model_tester.prepare_config_and_inputs() a , a = vision_config_and_inputs a , a , a , a = text_config_and_inputs # make sure that cross attention layers are added return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": attention_mask, "input_ids": input_ids, "token_type_ids": token_type_ids, } @require_torch class lowerCamelCase_ ( a_ , unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ): '''simple docstring''' a = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained( '''hf-internal-testing/tiny-random-clip''' ,'''hf-internal-testing/tiny-bert''' ,vision_from_pt=__lowerCamelCase ,text_from_pt=__lowerCamelCase ,) a = 13 a = floats_tensor( [ batch_size, model.config.vision_config.num_channels, model.config.vision_config.image_size, model.config.vision_config.image_size, ] ) a = ids_tensor([batch_size, 4] ,model.config.text_config.vocab_size ) a = random_attention_mask([batch_size, 4] ) a = {'''pixel_values''': pixel_values, '''input_ids''': input_ids, '''attention_mask''': attention_mask} return model, inputs def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ,__lowerCamelCase : str ,__lowerCamelCase : List[str] ): '''simple docstring''' a = FlaxCLIPVisionModel(__lowerCamelCase ) a = FlaxBertModel(__lowerCamelCase ) return vision_model, text_model def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ): '''simple docstring''' a = FlaxCLIPVisionModelTester(self ) a = FlaxBertModelTester(self ) a = clip_model_tester.prepare_config_and_inputs() a = bert_model_tester.prepare_config_and_inputs() a , a = vision_config_and_inputs a , a , a , a = text_config_and_inputs # make sure that cross attention layers are added return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": attention_mask, "input_ids": input_ids, "token_type_ids": token_type_ids, } @require_flax @require_vision class lowerCamelCase_ ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ): '''simple docstring''' a = FlaxVisionTextDualEncoderModel.from_pretrained('''clip-italian/clip-italian''' ,logit_scale_init_value=1.0 ) a = VisionTextDualEncoderProcessor.from_pretrained('''clip-italian/clip-italian''' ) a = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) a = processor( text=['''una foto di un gatto''', '''una foto di un cane'''] ,images=__lowerCamelCase ,padding=__lowerCamelCase ,return_tensors='''np''' ) a = model(**__lowerCamelCase ) # verify the logits self.assertEqual(outputs.logits_per_image.shape ,(inputs.pixel_values.shape[0], inputs.input_ids.shape[0]) ) self.assertEqual( outputs.logits_per_text.shape ,(inputs.input_ids.shape[0], inputs.pixel_values.shape[0]) ,) a = np.array([[1.2_284_727, 0.3_104_122]] ) self.assertTrue(np.allclose(outputs.logits_per_image ,__lowerCamelCase ,atol=1e-3 ) )
330
from __future__ import annotations from collections.abc import Sequence from typing import Literal def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> str | Literal[False]: """simple docstring""" a = list(snake_case_ ) a = list(snake_case_ ) a = 0 for i in range(len(snake_case_ ) ): if lista[i] != lista[i]: count += 1 a = '''_''' if count > 1: return False else: return "".join(snake_case_ ) def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> list[str]: """simple docstring""" a = [] while True: a = ['''$'''] * len(snake_case_ ) a = [] for i in range(len(snake_case_ ) ): for j in range(i + 1, len(snake_case_ ) ): a = compare_string(binary[i], binary[j] ) if k is False: a = '''*''' a = '''*''' temp.append('''X''' ) for i in range(len(snake_case_ ) ): if checka[i] == "$": pi.append(binary[i] ) if len(snake_case_ ) == 0: return pi a = list(set(snake_case_ ) ) def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> list[str]: """simple docstring""" a = [] for minterm in minterms: a = '''''' for _ in range(snake_case_ ): a = str(minterm % 2 ) + string minterm //= 2 temp.append(snake_case_ ) return temp def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_ ) -> bool: """simple docstring""" a = list(snake_case_ ) a = list(snake_case_ ) a = 0 for i in range(len(snake_case_ ) ): if lista[i] != lista[i]: count_n += 1 return count_n == count def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> list[str]: """simple docstring""" a = [] a = [0] * len(snake_case_ ) for i in range(len(chart[0] ) ): a = 0 a = -1 for j in range(len(snake_case_ ) ): if chart[j][i] == 1: count += 1 a = j if count == 1: a = 1 for i in range(len(snake_case_ ) ): if select[i] == 1: for j in range(len(chart[0] ) ): if chart[i][j] == 1: for k in range(len(snake_case_ ) ): a = 0 temp.append(prime_implicants[i] ) while True: a = 0 a = -1 a = 0 for i in range(len(snake_case_ ) ): a = chart[i].count(1 ) if count_n > max_n: a = count_n a = i if max_n == 0: return temp temp.append(prime_implicants[rem] ) for i in range(len(chart[0] ) ): if chart[rem][i] == 1: for j in range(len(snake_case_ ) ): a = 0 def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> list[list[int]]: """simple docstring""" a = [[0 for x in range(len(snake_case_ ) )] for x in range(len(snake_case_ ) )] for i in range(len(snake_case_ ) ): a = prime_implicants[i].count('''_''' ) for j in range(len(snake_case_ ) ): if is_for_table(prime_implicants[i], binary[j], snake_case_ ): a = 1 return chart def SCREAMING_SNAKE_CASE__ ( ) -> None: """simple docstring""" a = int(input('''Enter the no. of variables\n''' ) ) a = [ float(snake_case_ ) for x in input( '''Enter the decimal representation of Minterms \'Spaces Separated\'\n''' ).split() ] a = decimal_to_binary(snake_case_, snake_case_ ) a = check(snake_case_ ) print('''Prime Implicants are:''' ) print(snake_case_ ) a = prime_implicant_chart(snake_case_, snake_case_ ) a = selection(snake_case_, snake_case_ ) print('''Essential Prime Implicants are:''' ) print(snake_case_ ) if __name__ == "__main__": import doctest doctest.testmod() main()
330
1
def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> list[list[int]]: """simple docstring""" a = [] if len(snake_case_ ) == 1: return [nums.copy()] for _ in range(len(snake_case_ ) ): a = nums.pop(0 ) a = permute(snake_case_ ) for perm in permutations: perm.append(snake_case_ ) result.extend(snake_case_ ) nums.append(snake_case_ ) return result def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> List[Any]: """simple docstring""" def backtrack(snake_case_ ): if start == len(snake_case_ ) - 1: output.append(nums[:] ) else: for i in range(snake_case_, len(snake_case_ ) ): a , a = nums[i], nums[start] backtrack(start + 1 ) a , a = nums[i], nums[start] # backtrack a = [] backtrack(0 ) return output if __name__ == "__main__": import doctest # use res to print the data in permute2 function UpperCamelCase__ : str = permutea([1, 2, 3]) print(res) doctest.testmod()
330
from typing import List, Union import numpy as np from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_DEPTH_ESTIMATION_MAPPING UpperCamelCase__ : List[str] = logging.get_logger(__name__) @add_end_docstrings(a_ ) class lowerCamelCase_ ( a_ ): def __init__( self : int ,*__lowerCamelCase : str ,**__lowerCamelCase : Optional[Any] ): '''simple docstring''' super().__init__(*__lowerCamelCase ,**__lowerCamelCase ) requires_backends(self ,'''vision''' ) self.check_model_type(__lowerCamelCase ) def __call__( self : int ,__lowerCamelCase : Union[str, List[str], "Image.Image", List["Image.Image"]] ,**__lowerCamelCase : str ): '''simple docstring''' return super().__call__(__lowerCamelCase ,**__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : Any ,**__lowerCamelCase : Dict ): '''simple docstring''' return {}, {}, {} def SCREAMING_SNAKE_CASE_ ( self : int ,__lowerCamelCase : Union[str, Any] ): '''simple docstring''' a = load_image(__lowerCamelCase ) a = image.size a = self.image_processor(images=__lowerCamelCase ,return_tensors=self.framework ) return model_inputs def SCREAMING_SNAKE_CASE_ ( self : str ,__lowerCamelCase : Union[str, Any] ): '''simple docstring''' a = self.model(**__lowerCamelCase ) return model_outputs def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ,__lowerCamelCase : Union[str, Any] ): '''simple docstring''' a = model_outputs.predicted_depth a = torch.nn.functional.interpolate( predicted_depth.unsqueeze(1 ) ,size=self.image_size[::-1] ,mode='''bicubic''' ,align_corners=__lowerCamelCase ) a = prediction.squeeze().cpu().numpy() a = (output * 2_55 / np.max(__lowerCamelCase )).astype('''uint8''' ) a = Image.fromarray(__lowerCamelCase ) a = {} a = predicted_depth a = depth return output_dict
330
1
from collections import defaultdict def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> bool: """simple docstring""" a = first_str.lower().strip() a = second_str.lower().strip() # Remove whitespace a = first_str.replace(''' ''', '''''' ) a = second_str.replace(''' ''', '''''' ) # Strings of different lengths are not anagrams if len(snake_case_ ) != len(snake_case_ ): return False # Default values for count should be 0 a = defaultdict(snake_case_ ) # For each character in input strings, # increment count in the corresponding for i in range(len(snake_case_ ) ): count[first_str[i]] += 1 count[second_str[i]] -= 1 return all(_count == 0 for _count in count.values() ) if __name__ == "__main__": from doctest import testmod testmod() UpperCamelCase__ : int = input("""Enter the first string """).strip() UpperCamelCase__ : Union[str, Any] = input("""Enter the second string """).strip() UpperCamelCase__ : str = check_anagrams(input_a, input_b) print(F"{input_a} and {input_b} are {'' if status else 'not '}anagrams.")
330
from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Features, Value from .base import TaskTemplate @dataclass(frozen=a_ ) class lowerCamelCase_ ( a_ ): SCREAMING_SNAKE_CASE_ = field(default='language-modeling' , metadata={'include_in_asdict_even_if_is_default': True} ) SCREAMING_SNAKE_CASE_ = Features({'text': Value('string' )} ) SCREAMING_SNAKE_CASE_ = Features({} ) SCREAMING_SNAKE_CASE_ = "text" @property def SCREAMING_SNAKE_CASE_ ( self : int ): '''simple docstring''' return {self.text_column: "text"}
330
1
from . import ( albert, align, altclip, audio_spectrogram_transformer, auto, autoformer, bark, bart, barthez, bartpho, beit, bert, bert_generation, bert_japanese, bertweet, big_bird, bigbird_pegasus, biogpt, bit, blenderbot, blenderbot_small, blip, blip_a, bloom, bridgetower, byta, camembert, canine, chinese_clip, clap, clip, clipseg, codegen, conditional_detr, convbert, convnext, convnextva, cpm, cpmant, ctrl, cvt, dataavec, deberta, deberta_va, decision_transformer, deformable_detr, deit, deprecated, deta, detr, dialogpt, dinat, distilbert, dit, donut, dpr, dpt, efficientformer, efficientnet, electra, encodec, encoder_decoder, ernie, ernie_m, esm, falcon, flaubert, flava, fnet, focalnet, fsmt, funnel, git, glpn, gpta, gpt_bigcode, gpt_neo, gpt_neox, gpt_neox_japanese, gpt_swa, gptj, gptsan_japanese, graphormer, groupvit, herbert, hubert, ibert, imagegpt, informer, instructblip, jukebox, layoutlm, layoutlmva, layoutlmva, layoutxlm, led, levit, lilt, llama, longformer, longta, luke, lxmert, mam_aaa, marian, markuplm, maskaformer, maskformer, mbart, mbartaa, mega, megatron_bert, megatron_gpta, mgp_str, mluke, mobilebert, mobilenet_va, mobilenet_va, mobilevit, mobilevitva, mpnet, mra, mta, musicgen, mvp, nat, nezha, nllb, nllb_moe, nystromformer, oneformer, open_llama, openai, opt, owlvit, pegasus, pegasus_x, perceiver, phobert, pixastruct, plbart, poolformer, prophetnet, qdqbert, rag, realm, reformer, regnet, rembert, resnet, roberta, roberta_prelayernorm, roc_bert, roformer, rwkv, sam, segformer, sew, sew_d, speech_encoder_decoder, speech_to_text, speech_to_text_a, speechta, splinter, squeezebert, swiftformer, swin, swinasr, swinva, switch_transformers, ta, table_transformer, tapas, time_series_transformer, timesformer, timm_backbone, transfo_xl, trocr, tvlt, umta, unispeech, unispeech_sat, upernet, videomae, vilt, vision_encoder_decoder, vision_text_dual_encoder, visual_bert, vit, vit_hybrid, vit_mae, vit_msn, vivit, wavaveca, wavaveca_conformer, wavaveca_phoneme, wavaveca_with_lm, wavlm, whisper, x_clip, xglm, xlm, xlm_prophetnet, xlm_roberta, xlm_roberta_xl, xlnet, xmod, yolos, yoso, )
330
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCamelCase__ : Union[str, Any] = logging.get_logger(__name__) UpperCamelCase__ : Union[str, Any] = { """hustvl/yolos-small""": """https://huggingface.co/hustvl/yolos-small/resolve/main/config.json""", # See all YOLOS models at https://huggingface.co/models?filter=yolos } class lowerCamelCase_ ( a_ ): SCREAMING_SNAKE_CASE_ = 'yolos' def __init__( self : Union[str, Any] ,__lowerCamelCase : int=7_68 ,__lowerCamelCase : Dict=12 ,__lowerCamelCase : Union[str, Any]=12 ,__lowerCamelCase : List[Any]=30_72 ,__lowerCamelCase : int="gelu" ,__lowerCamelCase : int=0.0 ,__lowerCamelCase : str=0.0 ,__lowerCamelCase : Optional[Any]=0.02 ,__lowerCamelCase : int=1e-12 ,__lowerCamelCase : Any=[5_12, 8_64] ,__lowerCamelCase : Tuple=16 ,__lowerCamelCase : int=3 ,__lowerCamelCase : Tuple=True ,__lowerCamelCase : Optional[int]=1_00 ,__lowerCamelCase : List[Any]=True ,__lowerCamelCase : List[str]=False ,__lowerCamelCase : int=1 ,__lowerCamelCase : List[Any]=5 ,__lowerCamelCase : Optional[int]=2 ,__lowerCamelCase : int=5 ,__lowerCamelCase : str=2 ,__lowerCamelCase : Tuple=0.1 ,**__lowerCamelCase : List[Any] ,): '''simple docstring''' super().__init__(**__lowerCamelCase ) 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 a = num_detection_tokens a = use_mid_position_embeddings a = auxiliary_loss # Hungarian matcher a = class_cost a = bbox_cost a = giou_cost # Loss coefficients a = bbox_loss_coefficient a = giou_loss_coefficient a = eos_coefficient class lowerCamelCase_ ( a_ ): SCREAMING_SNAKE_CASE_ = version.parse('1.11' ) @property def SCREAMING_SNAKE_CASE_ ( self : str ): '''simple docstring''' return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) @property def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ): '''simple docstring''' return 1e-4 @property def SCREAMING_SNAKE_CASE_ ( self : str ): '''simple docstring''' return 12
330
1
import argparse import os # New Code # import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils import find_executable_batch_size ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to ensure out-of-memory errors never # interrupt training, and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## UpperCamelCase__ : Union[str, Any] = 16 UpperCamelCase__ : Dict = 32 def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ = 1_6 ) -> Tuple: """simple docstring""" a = AutoTokenizer.from_pretrained('''bert-base-cased''' ) a = load_dataset('''glue''', '''mrpc''' ) def tokenize_function(snake_case_ ): # max_length=None => use the model max length (it's actually the default) a = tokenizer(examples['''sentence1'''], examples['''sentence2'''], truncation=snake_case_, max_length=snake_case_ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): a = datasets.map( snake_case_, batched=snake_case_, remove_columns=['''idx''', '''sentence1''', '''sentence2'''], ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library a = tokenized_datasets.rename_column('''label''', '''labels''' ) def collate_fn(snake_case_ ): # On TPU it's best to pad everything to the same length or training will be very slow. a = 1_2_8 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": a = 1_6 elif accelerator.mixed_precision != "no": a = 8 else: a = None return tokenizer.pad( snake_case_, padding='''longest''', max_length=snake_case_, pad_to_multiple_of=snake_case_, return_tensors='''pt''', ) # Instantiate dataloaders. a = DataLoader( tokenized_datasets['''train'''], shuffle=snake_case_, collate_fn=snake_case_, batch_size=snake_case_ ) a = DataLoader( tokenized_datasets['''validation'''], shuffle=snake_case_, collate_fn=snake_case_, batch_size=snake_case_ ) return train_dataloader, eval_dataloader # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""", None) == "1": from accelerate.test_utils.training import mocked_dataloaders UpperCamelCase__ : int = mocked_dataloaders # noqa: F811 def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> List[Any]: """simple docstring""" if os.environ.get('''TESTING_MOCKED_DATALOADERS''', snake_case_ ) == "1": a = 2 # Initialize accelerator a = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs a = config['''lr'''] a = int(config['''num_epochs'''] ) a = int(config['''seed'''] ) a = int(config['''batch_size'''] ) a = evaluate.load('''glue''', '''mrpc''' ) # New Code # # We now can define an inner training loop function. It should take a batch size as the only parameter, # and build the dataloaders in there. # It also gets our decorator @find_executable_batch_size(starting_batch_size=snake_case_ ) def inner_training_loop(snake_case_ ): # And now just move everything below under this function # We need to bring in the Accelerator object from earlier nonlocal accelerator # And reset all of its attributes that could hold onto any memory: accelerator.free_memory() # Then we can declare the model, optimizer, and everything else: set_seed(snake_case_ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) a = AutoModelForSequenceClassification.from_pretrained('''bert-base-cased''', return_dict=snake_case_ ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). a = model.to(accelerator.device ) # Instantiate optimizer a = AdamW(params=model.parameters(), lr=snake_case_ ) a , a = get_dataloaders(snake_case_, snake_case_ ) # Instantiate scheduler a = get_linear_schedule_with_warmup( optimizer=snake_case_, num_warmup_steps=1_0_0, num_training_steps=(len(snake_case_ ) * num_epochs), ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. a , a , a , a , a = accelerator.prepare( snake_case_, snake_case_, snake_case_, snake_case_, snake_case_ ) # Now we train the model for epoch in range(snake_case_ ): model.train() for step, batch in enumerate(snake_case_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) a = model(**snake_case_ ) a = outputs.loss accelerator.backward(snake_case_ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(snake_case_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): a = model(**snake_case_ ) a = outputs.logits.argmax(dim=-1 ) a , a = accelerator.gather_for_metrics((predictions, batch['''labels''']) ) metric.add_batch( predictions=snake_case_, references=snake_case_, ) a = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f"""epoch {epoch}:""", snake_case_ ) # New Code # # And call it at the end with no arguments # Note: You could also refactor this outside of your training loop function inner_training_loop() def SCREAMING_SNAKE_CASE__ ( ) -> Tuple: """simple docstring""" a = argparse.ArgumentParser(description='''Simple example of training script.''' ) parser.add_argument( '''--mixed_precision''', type=snake_case_, default=snake_case_, choices=['''no''', '''fp16''', '''bf16''', '''fp8'''], help='''Whether to use mixed precision. Choose''' '''between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.''' '''and an Nvidia Ampere GPU.''', ) parser.add_argument('''--cpu''', action='''store_true''', help='''If passed, will train on the CPU.''' ) a = parser.parse_args() a = {'''lr''': 2e-5, '''num_epochs''': 3, '''seed''': 4_2, '''batch_size''': 1_6} training_function(snake_case_, snake_case_ ) if __name__ == "__main__": main()
330
def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> int: """simple docstring""" a = '''''' for i in table: res += inp[i - 1] return res def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> int: """simple docstring""" return data[1:] + data[0] def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> List[str]: """simple docstring""" a = '''''' for i in range(len(snake_case_ ) ): if a[i] == b[i]: res += "0" else: res += "1" return res def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> Dict: """simple docstring""" a = int('''0b''' + data[0] + data[-1], 2 ) a = int('''0b''' + data[1:3], 2 ) return bin(s[row][col] )[2:] def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_, snake_case_, snake_case_ ) -> Optional[int]: """simple docstring""" a = message[:4] a = message[4:] a = apply_table(snake_case_, snake_case_ ) a = xor(snake_case_, snake_case_ ) a = apply_sbox(snake_case_, temp[:4] ) # noqa: E741 a = apply_sbox(snake_case_, temp[4:] ) a = '''0''' * (2 - len(snake_case_ )) + l # noqa: E741 a = '''0''' * (2 - len(snake_case_ )) + r a = apply_table(l + r, snake_case_ ) a = xor(snake_case_, snake_case_ ) return temp + right if __name__ == "__main__": UpperCamelCase__ : int = input("""Enter 10 bit key: """) UpperCamelCase__ : Union[str, Any] = input("""Enter 8 bit message: """) UpperCamelCase__ : Dict = [6, 3, 7, 4, 8, 5, 10, 9] UpperCamelCase__ : Union[str, Any] = [3, 5, 2, 7, 4, 10, 1, 9, 8, 6] UpperCamelCase__ : Optional[int] = [2, 4, 3, 1] UpperCamelCase__ : List[Any] = [2, 6, 3, 1, 4, 8, 5, 7] UpperCamelCase__ : str = [4, 1, 3, 5, 7, 2, 8, 6] UpperCamelCase__ : List[Any] = [4, 1, 2, 3, 2, 3, 4, 1] UpperCamelCase__ : int = [[1, 0, 3, 2], [3, 2, 1, 0], [0, 2, 1, 3], [3, 1, 3, 2]] UpperCamelCase__ : Dict = [[0, 1, 2, 3], [2, 0, 1, 3], [3, 0, 1, 0], [2, 1, 0, 3]] # key generation UpperCamelCase__ : Optional[Any] = apply_table(key, paa_table) UpperCamelCase__ : str = temp[:5] UpperCamelCase__ : List[Any] = temp[5:] UpperCamelCase__ : Dict = left_shift(left) UpperCamelCase__ : Any = left_shift(right) UpperCamelCase__ : Optional[Any] = apply_table(left + right, pa_table) UpperCamelCase__ : List[str] = left_shift(left) UpperCamelCase__ : int = left_shift(right) UpperCamelCase__ : List[str] = left_shift(left) UpperCamelCase__ : Dict = left_shift(right) UpperCamelCase__ : List[str] = apply_table(left + right, pa_table) # encryption UpperCamelCase__ : Tuple = apply_table(message, IP) UpperCamelCase__ : Optional[Any] = function(expansion, sa, sa, keya, temp) UpperCamelCase__ : Optional[int] = temp[4:] + temp[:4] UpperCamelCase__ : Any = function(expansion, sa, sa, keya, temp) UpperCamelCase__ : Tuple = apply_table(temp, IP_inv) print("""Cipher text is:""", CT) # decryption UpperCamelCase__ : Union[str, Any] = apply_table(CT, IP) UpperCamelCase__ : List[str] = function(expansion, sa, sa, keya, temp) UpperCamelCase__ : Optional[Any] = temp[4:] + temp[:4] UpperCamelCase__ : Optional[int] = function(expansion, sa, sa, keya, temp) UpperCamelCase__ : Any = apply_table(temp, IP_inv) print("""Plain text after decypting is:""", PT)
330
1
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCamelCase__ : Union[str, Any] = logging.get_logger(__name__) UpperCamelCase__ : Union[str, Any] = { """hustvl/yolos-small""": """https://huggingface.co/hustvl/yolos-small/resolve/main/config.json""", # See all YOLOS models at https://huggingface.co/models?filter=yolos } class lowerCamelCase_ ( a_ ): SCREAMING_SNAKE_CASE_ = 'yolos' def __init__( self : Union[str, Any] ,__lowerCamelCase : int=7_68 ,__lowerCamelCase : Dict=12 ,__lowerCamelCase : Union[str, Any]=12 ,__lowerCamelCase : List[Any]=30_72 ,__lowerCamelCase : int="gelu" ,__lowerCamelCase : int=0.0 ,__lowerCamelCase : str=0.0 ,__lowerCamelCase : Optional[Any]=0.02 ,__lowerCamelCase : int=1e-12 ,__lowerCamelCase : Any=[5_12, 8_64] ,__lowerCamelCase : Tuple=16 ,__lowerCamelCase : int=3 ,__lowerCamelCase : Tuple=True ,__lowerCamelCase : Optional[int]=1_00 ,__lowerCamelCase : List[Any]=True ,__lowerCamelCase : List[str]=False ,__lowerCamelCase : int=1 ,__lowerCamelCase : List[Any]=5 ,__lowerCamelCase : Optional[int]=2 ,__lowerCamelCase : int=5 ,__lowerCamelCase : str=2 ,__lowerCamelCase : Tuple=0.1 ,**__lowerCamelCase : List[Any] ,): '''simple docstring''' super().__init__(**__lowerCamelCase ) 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 a = num_detection_tokens a = use_mid_position_embeddings a = auxiliary_loss # Hungarian matcher a = class_cost a = bbox_cost a = giou_cost # Loss coefficients a = bbox_loss_coefficient a = giou_loss_coefficient a = eos_coefficient class lowerCamelCase_ ( a_ ): SCREAMING_SNAKE_CASE_ = version.parse('1.11' ) @property def SCREAMING_SNAKE_CASE_ ( self : str ): '''simple docstring''' return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) @property def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ): '''simple docstring''' return 1e-4 @property def SCREAMING_SNAKE_CASE_ ( self : str ): '''simple docstring''' return 12
330
import unittest from transformers import AutoTokenizer, is_flax_available from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, slow if is_flax_available(): import jax.numpy as jnp from transformers import FlaxXLMRobertaModel @require_sentencepiece @require_tokenizers @require_flax class lowerCamelCase_ ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE_ ( self : Tuple ): '''simple docstring''' a = FlaxXLMRobertaModel.from_pretrained('''xlm-roberta-base''' ) a = AutoTokenizer.from_pretrained('''xlm-roberta-base''' ) a = '''The dog is cute and lives in the garden house''' a = jnp.array([tokenizer.encode(__lowerCamelCase )] ) a = (1, 12, 7_68) # batch_size, sequence_length, embedding_vector_dim a = jnp.array( [[-0.0_101, 0.1_218, -0.0_803, 0.0_801, 0.1_327, 0.0_776, -0.1_215, 0.2_383, 0.3_338, 0.3_106, 0.0_300, 0.0_252]] ) a = model(__lowerCamelCase )['''last_hidden_state'''] self.assertEqual(output.shape ,__lowerCamelCase ) # compare the actual values for a slice of last dim self.assertTrue(jnp.allclose(output[:, :, -1] ,__lowerCamelCase ,atol=1e-3 ) )
330
1
import pytest import datasets.config from datasets.utils.info_utils import is_small_dataset @pytest.mark.parametrize('''dataset_size''', [None, 4_0_0 * 2**2_0, 6_0_0 * 2**2_0] ) @pytest.mark.parametrize('''input_in_memory_max_size''', ['''default''', 0, 1_0_0 * 2**2_0, 9_0_0 * 2**2_0] ) def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_ ) -> str: """simple docstring""" if input_in_memory_max_size != "default": monkeypatch.setattr(datasets.config, '''IN_MEMORY_MAX_SIZE''', snake_case_ ) a = datasets.config.IN_MEMORY_MAX_SIZE if input_in_memory_max_size == "default": assert in_memory_max_size == 0 else: assert in_memory_max_size == input_in_memory_max_size if dataset_size and in_memory_max_size: a = dataset_size < in_memory_max_size else: a = False a = is_small_dataset(snake_case_ ) assert result == expected
330
import argparse import os # New Code # import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils import find_executable_batch_size ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to ensure out-of-memory errors never # interrupt training, and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## UpperCamelCase__ : Union[str, Any] = 16 UpperCamelCase__ : Dict = 32 def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ = 1_6 ) -> Tuple: """simple docstring""" a = AutoTokenizer.from_pretrained('''bert-base-cased''' ) a = load_dataset('''glue''', '''mrpc''' ) def tokenize_function(snake_case_ ): # max_length=None => use the model max length (it's actually the default) a = tokenizer(examples['''sentence1'''], examples['''sentence2'''], truncation=snake_case_, max_length=snake_case_ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): a = datasets.map( snake_case_, batched=snake_case_, remove_columns=['''idx''', '''sentence1''', '''sentence2'''], ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library a = tokenized_datasets.rename_column('''label''', '''labels''' ) def collate_fn(snake_case_ ): # On TPU it's best to pad everything to the same length or training will be very slow. a = 1_2_8 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": a = 1_6 elif accelerator.mixed_precision != "no": a = 8 else: a = None return tokenizer.pad( snake_case_, padding='''longest''', max_length=snake_case_, pad_to_multiple_of=snake_case_, return_tensors='''pt''', ) # Instantiate dataloaders. a = DataLoader( tokenized_datasets['''train'''], shuffle=snake_case_, collate_fn=snake_case_, batch_size=snake_case_ ) a = DataLoader( tokenized_datasets['''validation'''], shuffle=snake_case_, collate_fn=snake_case_, batch_size=snake_case_ ) return train_dataloader, eval_dataloader # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""", None) == "1": from accelerate.test_utils.training import mocked_dataloaders UpperCamelCase__ : int = mocked_dataloaders # noqa: F811 def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> List[Any]: """simple docstring""" if os.environ.get('''TESTING_MOCKED_DATALOADERS''', snake_case_ ) == "1": a = 2 # Initialize accelerator a = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs a = config['''lr'''] a = int(config['''num_epochs'''] ) a = int(config['''seed'''] ) a = int(config['''batch_size'''] ) a = evaluate.load('''glue''', '''mrpc''' ) # New Code # # We now can define an inner training loop function. It should take a batch size as the only parameter, # and build the dataloaders in there. # It also gets our decorator @find_executable_batch_size(starting_batch_size=snake_case_ ) def inner_training_loop(snake_case_ ): # And now just move everything below under this function # We need to bring in the Accelerator object from earlier nonlocal accelerator # And reset all of its attributes that could hold onto any memory: accelerator.free_memory() # Then we can declare the model, optimizer, and everything else: set_seed(snake_case_ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) a = AutoModelForSequenceClassification.from_pretrained('''bert-base-cased''', return_dict=snake_case_ ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). a = model.to(accelerator.device ) # Instantiate optimizer a = AdamW(params=model.parameters(), lr=snake_case_ ) a , a = get_dataloaders(snake_case_, snake_case_ ) # Instantiate scheduler a = get_linear_schedule_with_warmup( optimizer=snake_case_, num_warmup_steps=1_0_0, num_training_steps=(len(snake_case_ ) * num_epochs), ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. a , a , a , a , a = accelerator.prepare( snake_case_, snake_case_, snake_case_, snake_case_, snake_case_ ) # Now we train the model for epoch in range(snake_case_ ): model.train() for step, batch in enumerate(snake_case_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) a = model(**snake_case_ ) a = outputs.loss accelerator.backward(snake_case_ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(snake_case_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): a = model(**snake_case_ ) a = outputs.logits.argmax(dim=-1 ) a , a = accelerator.gather_for_metrics((predictions, batch['''labels''']) ) metric.add_batch( predictions=snake_case_, references=snake_case_, ) a = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f"""epoch {epoch}:""", snake_case_ ) # New Code # # And call it at the end with no arguments # Note: You could also refactor this outside of your training loop function inner_training_loop() def SCREAMING_SNAKE_CASE__ ( ) -> Tuple: """simple docstring""" a = argparse.ArgumentParser(description='''Simple example of training script.''' ) parser.add_argument( '''--mixed_precision''', type=snake_case_, default=snake_case_, choices=['''no''', '''fp16''', '''bf16''', '''fp8'''], help='''Whether to use mixed precision. Choose''' '''between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.''' '''and an Nvidia Ampere GPU.''', ) parser.add_argument('''--cpu''', action='''store_true''', help='''If passed, will train on the CPU.''' ) a = parser.parse_args() a = {'''lr''': 2e-5, '''num_epochs''': 3, '''seed''': 4_2, '''batch_size''': 1_6} training_function(snake_case_, snake_case_ ) if __name__ == "__main__": main()
330
1
import pytest from datasets import inspect_metric, list_metrics, load_metric @pytest.fixture def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> List[str]: """simple docstring""" monkeypatch.setattr('''datasets.utils.deprecation_utils._emitted_deprecation_warnings''', set() ) @pytest.fixture def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> Optional[int]: """simple docstring""" class lowerCamelCase_ : def __init__( self : Dict ,__lowerCamelCase : List[str] ): '''simple docstring''' a = metric_id class lowerCamelCase_ : SCREAMING_SNAKE_CASE_ = [MetricMock(a_ ) for metric_id in ['accuracy', 'mse', 'precision', 'codeparrot/apps_metric']] def SCREAMING_SNAKE_CASE_ ( self : Dict ): '''simple docstring''' return self._metrics monkeypatch.setattr('''datasets.inspect.huggingface_hub''', HfhMock() ) @pytest.mark.parametrize( '''func, args''', [(load_metric, ('''metrics/mse''',)), (list_metrics, ()), (inspect_metric, ('''metrics/mse''', '''tmp_path'''))] ) def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_, snake_case_, snake_case_ ) -> Tuple: """simple docstring""" if "tmp_path" in args: a = tuple(arg if arg != '''tmp_path''' else tmp_path for arg in args ) with pytest.warns(snake_case_, match='''https://huggingface.co/docs/evaluate''' ): func(*snake_case_ )
330
import argparse import fairseq import torch from transformers import UniSpeechSatConfig, UniSpeechSatForCTC, UniSpeechSatForPreTraining, logging logging.set_verbosity_info() UpperCamelCase__ : Optional[int] = logging.get_logger(__name__) UpperCamelCase__ : str = { """post_extract_proj""": """feature_projection.projection""", """encoder.pos_conv.0""": """encoder.pos_conv_embed.conv""", """self_attn.k_proj""": """encoder.layers.*.attention.k_proj""", """self_attn.v_proj""": """encoder.layers.*.attention.v_proj""", """self_attn.q_proj""": """encoder.layers.*.attention.q_proj""", """self_attn.out_proj""": """encoder.layers.*.attention.out_proj""", """self_attn_layer_norm""": """encoder.layers.*.layer_norm""", """fc1""": """encoder.layers.*.feed_forward.intermediate_dense""", """fc2""": """encoder.layers.*.feed_forward.output_dense""", """final_layer_norm""": """encoder.layers.*.final_layer_norm""", """encoder.layer_norm""": """encoder.layer_norm""", """encoder.layer_norm_for_extract""": """layer_norm_for_extract""", """w2v_model.layer_norm""": """feature_projection.layer_norm""", """quantizer.weight_proj""": """quantizer.weight_proj""", """quantizer.vars""": """quantizer.codevectors""", """project_q""": """project_q""", """final_proj""": """project_hid""", """w2v_encoder.proj""": """lm_head""", """label_embs_concat""": """label_embeddings_concat""", """mask_emb""": """masked_spec_embed""", """spk_proj""": """speaker_proj""", } UpperCamelCase__ : Optional[Any] = [ """lm_head""", """quantizer.weight_proj""", """quantizer.codevectors""", """project_q""", """project_hid""", """label_embeddings_concat""", """speaker_proj""", """layer_norm_for_extract""", ] def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_, snake_case_, snake_case_ ) -> List[Any]: """simple docstring""" for attribute in key.split('''.''' ): a = getattr(snake_case_, snake_case_ ) if weight_type is not None: a = getattr(snake_case_, snake_case_ ).shape else: a = hf_pointer.shape if hf_shape != value.shape: raise ValueError( f"""Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be""" f""" {value.shape} for {full_name}""" ) if weight_type == "weight": a = value elif weight_type == "weight_g": a = value elif weight_type == "weight_v": a = value elif weight_type == "bias": a = value else: a = value logger.info(f"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" ) def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> Union[str, Any]: """simple docstring""" a = [] a = fairseq_model.state_dict() a = hf_model.unispeech_sat.feature_extractor for name, value in fairseq_dict.items(): a = False if "conv_layers" in name: load_conv_layer( snake_case_, snake_case_, snake_case_, snake_case_, hf_model.config.feat_extract_norm == '''group''', ) a = True else: for key, mapped_key in MAPPING.items(): a = '''unispeech_sat.''' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split('''w2v_model.''' )[-1] == name.split('''.''' )[0]: if "layer_norm_for_extract" in name and (".".join(name.split('''.''' )[:-1] ) != key): # special case since naming is very similar continue a = True if "*" in mapped_key: a = name.split(snake_case_ )[0].split('''.''' )[-2] a = mapped_key.replace('''*''', snake_case_ ) if "weight_g" in name: a = '''weight_g''' elif "weight_v" in name: a = '''weight_v''' elif "bias" in name: a = '''bias''' elif "weight" in name: # TODO: don't match quantizer.weight_proj a = '''weight''' else: a = None set_recursively(snake_case_, snake_case_, snake_case_, snake_case_, snake_case_ ) continue if not is_used: unused_weights.append(snake_case_ ) logger.warning(f"""Unused weights: {unused_weights}""" ) def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_, snake_case_, snake_case_ ) -> Union[str, Any]: """simple docstring""" a = full_name.split('''conv_layers.''' )[-1] a = name.split('''.''' ) a = int(items[0] ) a = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) a = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) a = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor[layer_id].layer_norm.bias.data.shape} was found.""" ) a = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.""" ) a = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(snake_case_ ) @torch.no_grad() def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_=None, snake_case_=None, snake_case_=True ) -> Union[str, Any]: """simple docstring""" if config_path is not None: a = UniSpeechSatConfig.from_pretrained(snake_case_ ) else: a = UniSpeechSatConfig() a = '''''' if is_finetuned: a = UniSpeechSatForCTC(snake_case_ ) else: a = UniSpeechSatForPreTraining(snake_case_ ) a , a , a = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path], arg_overrides={'''data''': '''/'''.join(dict_path.split('''/''' )[:-1] )} ) a = model[0].eval() recursively_load_weights(snake_case_, snake_case_ ) hf_wavavec.save_pretrained(snake_case_ ) if __name__ == "__main__": UpperCamelCase__ : Optional[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 fairseq checkpoint""") parser.add_argument("""--dict_path""", default=None, type=str, help="""Path to dict of fine-tuned model""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") parser.add_argument( """--not_finetuned""", action="""store_true""", help="""Whether the model to convert is a fine-tuned model or not""" ) UpperCamelCase__ : int = parser.parse_args() convert_unispeech_sat_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
330
1
def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> bool: """simple docstring""" a = n ** (1 / 3) return (val * val * val) == n if __name__ == "__main__": print(perfect_cube(27)) print(perfect_cube(4))
330
import pytest from datasets import inspect_metric, list_metrics, load_metric @pytest.fixture def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> List[str]: """simple docstring""" monkeypatch.setattr('''datasets.utils.deprecation_utils._emitted_deprecation_warnings''', set() ) @pytest.fixture def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> Optional[int]: """simple docstring""" class lowerCamelCase_ : def __init__( self : Dict ,__lowerCamelCase : List[str] ): '''simple docstring''' a = metric_id class lowerCamelCase_ : SCREAMING_SNAKE_CASE_ = [MetricMock(a_ ) for metric_id in ['accuracy', 'mse', 'precision', 'codeparrot/apps_metric']] def SCREAMING_SNAKE_CASE_ ( self : Dict ): '''simple docstring''' return self._metrics monkeypatch.setattr('''datasets.inspect.huggingface_hub''', HfhMock() ) @pytest.mark.parametrize( '''func, args''', [(load_metric, ('''metrics/mse''',)), (list_metrics, ()), (inspect_metric, ('''metrics/mse''', '''tmp_path'''))] ) def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_, snake_case_, snake_case_ ) -> Tuple: """simple docstring""" if "tmp_path" in args: a = tuple(arg if arg != '''tmp_path''' else tmp_path for arg in args ) with pytest.warns(snake_case_, match='''https://huggingface.co/docs/evaluate''' ): func(*snake_case_ )
330
1
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase__ : Union[str, Any] = logging.get_logger(__name__) UpperCamelCase__ : List[str] = { """microsoft/unispeech-sat-base-100h-libri-ft""": ( """https://huggingface.co/microsoft/unispeech-sat-base-100h-libri-ft/resolve/main/config.json""" ), # See all UniSpeechSat models at https://huggingface.co/models?filter=unispeech_sat } class lowerCamelCase_ ( a_ ): SCREAMING_SNAKE_CASE_ = 'unispeech-sat' def __init__( self : Tuple ,__lowerCamelCase : str=32 ,__lowerCamelCase : Any=7_68 ,__lowerCamelCase : Union[str, Any]=12 ,__lowerCamelCase : Any=12 ,__lowerCamelCase : List[str]=30_72 ,__lowerCamelCase : List[str]="gelu" ,__lowerCamelCase : Optional[int]=0.1 ,__lowerCamelCase : Optional[int]=0.1 ,__lowerCamelCase : List[Any]=0.1 ,__lowerCamelCase : Union[str, Any]=0.0 ,__lowerCamelCase : List[str]=0.0 ,__lowerCamelCase : Dict=0.1 ,__lowerCamelCase : Tuple=0.1 ,__lowerCamelCase : Optional[int]=0.02 ,__lowerCamelCase : List[str]=1e-5 ,__lowerCamelCase : Optional[int]="group" ,__lowerCamelCase : Dict="gelu" ,__lowerCamelCase : int=(5_12, 5_12, 5_12, 5_12, 5_12, 5_12, 5_12) ,__lowerCamelCase : str=(5, 2, 2, 2, 2, 2, 2) ,__lowerCamelCase : Optional[int]=(10, 3, 3, 3, 3, 2, 2) ,__lowerCamelCase : Optional[Any]=False ,__lowerCamelCase : List[Any]=1_28 ,__lowerCamelCase : Any=16 ,__lowerCamelCase : List[Any]=False ,__lowerCamelCase : str=True ,__lowerCamelCase : str=0.05 ,__lowerCamelCase : str=10 ,__lowerCamelCase : Optional[int]=2 ,__lowerCamelCase : Any=0.0 ,__lowerCamelCase : Optional[Any]=10 ,__lowerCamelCase : str=0 ,__lowerCamelCase : Optional[int]=3_20 ,__lowerCamelCase : List[Any]=2 ,__lowerCamelCase : List[Any]=0.1 ,__lowerCamelCase : Union[str, Any]=1_00 ,__lowerCamelCase : Optional[Any]=2_56 ,__lowerCamelCase : Tuple=2_56 ,__lowerCamelCase : List[Any]=0.1 ,__lowerCamelCase : int="mean" ,__lowerCamelCase : Optional[int]=False ,__lowerCamelCase : int=False ,__lowerCamelCase : List[Any]=2_56 ,__lowerCamelCase : List[str]=(5_12, 5_12, 5_12, 5_12, 15_00) ,__lowerCamelCase : Optional[int]=(5, 3, 3, 1, 1) ,__lowerCamelCase : List[Any]=(1, 2, 3, 1, 1) ,__lowerCamelCase : str=5_12 ,__lowerCamelCase : Union[str, Any]=0 ,__lowerCamelCase : int=1 ,__lowerCamelCase : str=2 ,__lowerCamelCase : List[str]=5_04 ,**__lowerCamelCase : List[str] ,): '''simple docstring''' super().__init__(**__lowerCamelCase ,pad_token_id=__lowerCamelCase ,bos_token_id=__lowerCamelCase ,eos_token_id=__lowerCamelCase ) a = hidden_size a = feat_extract_norm a = feat_extract_activation a = list(__lowerCamelCase ) a = list(__lowerCamelCase ) a = list(__lowerCamelCase ) a = conv_bias a = num_conv_pos_embeddings a = num_conv_pos_embedding_groups a = len(self.conv_dim ) a = num_hidden_layers a = intermediate_size a = hidden_act a = num_attention_heads a = hidden_dropout a = attention_dropout a = activation_dropout a = feat_proj_dropout a = final_dropout a = layerdrop a = layer_norm_eps a = initializer_range a = vocab_size a = num_clusters a = do_stable_layer_norm a = use_weighted_layer_sum if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( '''Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==''' ''' `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =''' F""" {len(self.conv_dim )}`, `len(config.conv_stride) = {len(self.conv_stride )}`,""" F""" `len(config.conv_kernel) = {len(self.conv_kernel )}`.""" ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 a = apply_spec_augment a = mask_time_prob a = mask_time_length a = mask_time_min_masks a = mask_feature_prob a = mask_feature_length a = mask_feature_min_masks # parameters for pretraining with codevector quantized representations a = num_codevectors_per_group a = num_codevector_groups a = contrastive_logits_temperature a = feat_quantizer_dropout a = num_negatives a = codevector_dim a = proj_codevector_dim a = diversity_loss_weight # ctc loss a = ctc_loss_reduction a = ctc_zero_infinity # SequenceClassification-specific parameter. Feel free to ignore for other classes. a = classifier_proj_size # XVector-specific parameters. Feel free to ignore for other classes. a = list(__lowerCamelCase ) a = list(__lowerCamelCase ) a = list(__lowerCamelCase ) a = xvector_output_dim @property def SCREAMING_SNAKE_CASE_ ( self : int ): '''simple docstring''' return functools.reduce(operator.mul ,self.conv_stride ,1 )
330
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase__ : str = logging.get_logger(__name__) UpperCamelCase__ : Optional[int] = { """studio-ousia/luke-base""": """https://huggingface.co/studio-ousia/luke-base/resolve/main/config.json""", """studio-ousia/luke-large""": """https://huggingface.co/studio-ousia/luke-large/resolve/main/config.json""", } class lowerCamelCase_ ( a_ ): SCREAMING_SNAKE_CASE_ = 'luke' def __init__( self : Dict ,__lowerCamelCase : Optional[Any]=5_02_67 ,__lowerCamelCase : str=50_00_00 ,__lowerCamelCase : Any=7_68 ,__lowerCamelCase : int=2_56 ,__lowerCamelCase : Optional[int]=12 ,__lowerCamelCase : Tuple=12 ,__lowerCamelCase : Any=30_72 ,__lowerCamelCase : Any="gelu" ,__lowerCamelCase : Any=0.1 ,__lowerCamelCase : Tuple=0.1 ,__lowerCamelCase : Tuple=5_12 ,__lowerCamelCase : int=2 ,__lowerCamelCase : Optional[int]=0.02 ,__lowerCamelCase : List[Any]=1e-12 ,__lowerCamelCase : Dict=True ,__lowerCamelCase : Tuple=None ,__lowerCamelCase : Any=1 ,__lowerCamelCase : Dict=0 ,__lowerCamelCase : Any=2 ,**__lowerCamelCase : str ,): '''simple docstring''' super().__init__(pad_token_id=__lowerCamelCase ,bos_token_id=__lowerCamelCase ,eos_token_id=__lowerCamelCase ,**__lowerCamelCase ) a = vocab_size a = entity_vocab_size a = hidden_size a = entity_emb_size a = num_hidden_layers a = num_attention_heads a = hidden_act a = intermediate_size a = hidden_dropout_prob a = attention_probs_dropout_prob a = max_position_embeddings a = type_vocab_size a = initializer_range a = layer_norm_eps a = use_entity_aware_attention a = classifier_dropout
330
1
import copy import os import cva import numpy as np from matplotlib import pyplot as plt class lowerCamelCase_ : def __init__( self : Any ): '''simple docstring''' a = '''''' a = '''''' a = [] a = 0 a = 2_56 a = 0 a = 0 a = 0 a = 0 def SCREAMING_SNAKE_CASE_ ( self : Any ,__lowerCamelCase : Tuple ): '''simple docstring''' a = cva.imread(__lowerCamelCase ,0 ) a = copy.deepcopy(self.img ) a , a , a = plt.hist(self.img.ravel() ,2_56 ,[0, 2_56] ,label='''x''' ) a = np.sum(__lowerCamelCase ) for i in range(len(__lowerCamelCase ) ): a = x[i] / self.k self.sk += prk a = (self.L - 1) * self.sk if self.rem != 0: a = int(last % last ) a = int(last + 1 if self.rem >= 0.5 else last ) self.last_list.append(__lowerCamelCase ) a = int(np.ma.count(self.img ) / self.img[1].size ) a = self.img[1].size for i in range(self.number_of_cols ): for j in range(self.number_of_rows ): a = self.img[j][i] if num != self.last_list[num]: a = self.last_list[num] cva.imwrite('''output_data/output.jpg''' ,self.img ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ): '''simple docstring''' plt.hist(self.img.ravel() ,2_56 ,[0, 2_56] ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ): '''simple docstring''' cva.imshow('''Output-Image''' ,self.img ) cva.imshow('''Input-Image''' ,self.original_image ) cva.waitKey(50_00 ) cva.destroyAllWindows() if __name__ == "__main__": UpperCamelCase__ : Optional[Any] = os.path.join(os.path.basename(__file__), """image_data/input.jpg""") UpperCamelCase__ : Tuple = ConstantStretch() stretcher.stretch(file_path) stretcher.plot_histogram() stretcher.show_image()
330
import numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler from tensorflow.keras.layers import LSTM, Dense from tensorflow.keras.models import Sequential if __name__ == "__main__": UpperCamelCase__ : Optional[int] = pd.read_csv("""sample_data.csv""", header=None) UpperCamelCase__ : Tuple = df.shape[:1][0] # If you're using some other dataset input the target column UpperCamelCase__ : List[Any] = df.iloc[:, 1:2] UpperCamelCase__ : Union[str, Any] = actual_data.values.reshape(len_data, 1) UpperCamelCase__ : List[Any] = MinMaxScaler().fit_transform(actual_data) UpperCamelCase__ : Optional[Any] = 10 UpperCamelCase__ : int = 5 UpperCamelCase__ : List[str] = 20 UpperCamelCase__ : Optional[int] = len_data - periods * look_back UpperCamelCase__ : Union[str, Any] = actual_data[:division] UpperCamelCase__ : str = actual_data[division - look_back :] UpperCamelCase__ , UpperCamelCase__ : Union[str, Any] = [], [] UpperCamelCase__ , UpperCamelCase__ : str = [], [] for i in range(0, len(train_data) - forward_days - look_back + 1): train_x.append(train_data[i : i + look_back]) train_y.append(train_data[i + look_back : i + look_back + forward_days]) for i in range(0, len(test_data) - forward_days - look_back + 1): test_x.append(test_data[i : i + look_back]) test_y.append(test_data[i + look_back : i + look_back + forward_days]) UpperCamelCase__ : List[str] = np.array(train_x) UpperCamelCase__ : Optional[Any] = np.array(test_x) UpperCamelCase__ : Tuple = np.array([list(i.ravel()) for i in train_y]) UpperCamelCase__ : Optional[Any] = np.array([list(i.ravel()) for i in test_y]) UpperCamelCase__ : Union[str, Any] = Sequential() model.add(LSTM(128, input_shape=(look_back, 1), return_sequences=True)) model.add(LSTM(64, input_shape=(128, 1))) model.add(Dense(forward_days)) model.compile(loss="""mean_squared_error""", optimizer="""adam""") UpperCamelCase__ : Tuple = model.fit( x_train, y_train, epochs=150, verbose=1, shuffle=True, batch_size=4 ) UpperCamelCase__ : Tuple = model.predict(x_test)
330
1
from typing import List, Union import numpy as np from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_DEPTH_ESTIMATION_MAPPING UpperCamelCase__ : List[str] = logging.get_logger(__name__) @add_end_docstrings(a_ ) class lowerCamelCase_ ( a_ ): def __init__( self : int ,*__lowerCamelCase : str ,**__lowerCamelCase : Optional[Any] ): '''simple docstring''' super().__init__(*__lowerCamelCase ,**__lowerCamelCase ) requires_backends(self ,'''vision''' ) self.check_model_type(__lowerCamelCase ) def __call__( self : int ,__lowerCamelCase : Union[str, List[str], "Image.Image", List["Image.Image"]] ,**__lowerCamelCase : str ): '''simple docstring''' return super().__call__(__lowerCamelCase ,**__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : Any ,**__lowerCamelCase : Dict ): '''simple docstring''' return {}, {}, {} def SCREAMING_SNAKE_CASE_ ( self : int ,__lowerCamelCase : Union[str, Any] ): '''simple docstring''' a = load_image(__lowerCamelCase ) a = image.size a = self.image_processor(images=__lowerCamelCase ,return_tensors=self.framework ) return model_inputs def SCREAMING_SNAKE_CASE_ ( self : str ,__lowerCamelCase : Union[str, Any] ): '''simple docstring''' a = self.model(**__lowerCamelCase ) return model_outputs def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ,__lowerCamelCase : Union[str, Any] ): '''simple docstring''' a = model_outputs.predicted_depth a = torch.nn.functional.interpolate( predicted_depth.unsqueeze(1 ) ,size=self.image_size[::-1] ,mode='''bicubic''' ,align_corners=__lowerCamelCase ) a = prediction.squeeze().cpu().numpy() a = (output * 2_55 / np.max(__lowerCamelCase )).astype('''uint8''' ) a = Image.fromarray(__lowerCamelCase ) a = {} a = predicted_depth a = depth return output_dict
330
import os import time import pytest from datasets.utils.filelock import FileLock, Timeout def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> Tuple: """simple docstring""" a = FileLock(str(tmpdir / '''foo.lock''' ) ) a = FileLock(str(tmpdir / '''foo.lock''' ) ) a = 0.01 with locka.acquire(): with pytest.raises(snake_case_ ): a = time.time() locka.acquire(snake_case_ ) assert time.time() - _start > timeout def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> Optional[int]: """simple docstring""" a = '''a''' * 1_0_0_0 + '''.lock''' a = FileLock(str(tmpdir / filename ) ) assert locka._lock_file.endswith('''.lock''' ) assert not locka._lock_file.endswith(snake_case_ ) assert len(os.path.basename(locka._lock_file ) ) <= 2_5_5 a = FileLock(tmpdir / filename ) with locka.acquire(): with pytest.raises(snake_case_ ): locka.acquire(0 )
330
1
class lowerCamelCase_ : def __init__( self : Union[str, Any] ,__lowerCamelCase : Dict ,__lowerCamelCase : Any ,__lowerCamelCase : Dict ): '''simple docstring''' a = None a = None a = graph self._normalize_graph(__lowerCamelCase ,__lowerCamelCase ) a = len(__lowerCamelCase ) a = None def SCREAMING_SNAKE_CASE_ ( self : List[str] ,__lowerCamelCase : List[str] ,__lowerCamelCase : int ): '''simple docstring''' if sources is int: a = [sources] if sinks is int: a = [sinks] if len(__lowerCamelCase ) == 0 or len(__lowerCamelCase ) == 0: return a = sources[0] a = sinks[0] # make fake vertex if there are more # than one source or sink if len(__lowerCamelCase ) > 1 or len(__lowerCamelCase ) > 1: a = 0 for i in sources: max_input_flow += sum(self.graph[i] ) a = len(self.graph ) + 1 for room in self.graph: room.insert(0 ,0 ) self.graph.insert(0 ,[0] * size ) for i in sources: a = max_input_flow a = 0 a = len(self.graph ) + 1 for room in self.graph: room.append(0 ) self.graph.append([0] * size ) for i in sinks: a = max_input_flow a = size - 1 def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ): '''simple docstring''' if self.maximum_flow_algorithm is None: raise Exception('''You need to set maximum flow algorithm before.''' ) if self.source_index is None or self.sink_index is None: return 0 self.maximum_flow_algorithm.execute() return self.maximum_flow_algorithm.getMaximumFlow() def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ,__lowerCamelCase : List[Any] ): '''simple docstring''' a = algorithm(self ) class lowerCamelCase_ : def __init__( self : int ,__lowerCamelCase : int ): '''simple docstring''' a = flow_network a = flow_network.verticesCount a = flow_network.sourceIndex a = flow_network.sinkIndex # it's just a reference, so you shouldn't change # it in your algorithms, use deep copy before doing that a = flow_network.graph a = False def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ): '''simple docstring''' if not self.executed: self._algorithm() a = True def SCREAMING_SNAKE_CASE_ ( self : str ): '''simple docstring''' pass class lowerCamelCase_ ( a_ ): def __init__( self : Any ,__lowerCamelCase : str ): '''simple docstring''' super().__init__(__lowerCamelCase ) # use this to save your result a = -1 def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ): '''simple docstring''' if not self.executed: raise Exception('''You should execute algorithm before using its result!''' ) return self.maximum_flow class lowerCamelCase_ ( a_ ): def __init__( self : Optional[Any] ,__lowerCamelCase : List[str] ): '''simple docstring''' super().__init__(__lowerCamelCase ) a = [[0] * self.verticies_count for i in range(self.verticies_count )] a = [0] * self.verticies_count a = [0] * self.verticies_count def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ): '''simple docstring''' a = self.verticies_count # push some substance to graph for nextvertex_index, bandwidth in enumerate(self.graph[self.source_index] ): self.preflow[self.source_index][nextvertex_index] += bandwidth self.preflow[nextvertex_index][self.source_index] -= bandwidth self.excesses[nextvertex_index] += bandwidth # Relabel-to-front selection rule a = [ i for i in range(self.verticies_count ) if i != self.source_index and i != self.sink_index ] # move through list a = 0 while i < len(__lowerCamelCase ): a = vertices_list[i] a = self.heights[vertex_index] self.process_vertex(__lowerCamelCase ) if self.heights[vertex_index] > previous_height: # if it was relabeled, swap elements # and start from 0 index vertices_list.insert(0 ,vertices_list.pop(__lowerCamelCase ) ) a = 0 else: i += 1 a = sum(self.preflow[self.source_index] ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ,__lowerCamelCase : int ): '''simple docstring''' while self.excesses[vertex_index] > 0: for neighbour_index in range(self.verticies_count ): # if it's neighbour and current vertex is higher if ( self.graph[vertex_index][neighbour_index] - self.preflow[vertex_index][neighbour_index] > 0 and self.heights[vertex_index] > self.heights[neighbour_index] ): self.push(__lowerCamelCase ,__lowerCamelCase ) self.relabel(__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ,__lowerCamelCase : str ,__lowerCamelCase : Optional[Any] ): '''simple docstring''' a = min( self.excesses[from_index] ,self.graph[from_index][to_index] - self.preflow[from_index][to_index] ,) self.preflow[from_index][to_index] += preflow_delta self.preflow[to_index][from_index] -= preflow_delta self.excesses[from_index] -= preflow_delta self.excesses[to_index] += preflow_delta def SCREAMING_SNAKE_CASE_ ( self : Any ,__lowerCamelCase : Tuple ): '''simple docstring''' a = None for to_index in range(self.verticies_count ): if ( self.graph[vertex_index][to_index] - self.preflow[vertex_index][to_index] > 0 ) and (min_height is None or self.heights[to_index] < min_height): a = self.heights[to_index] if min_height is not None: a = min_height + 1 if __name__ == "__main__": UpperCamelCase__ : Union[str, Any] = [0] UpperCamelCase__ : List[Any] = [3] # graph = [ # [0, 0, 4, 6, 0, 0], # [0, 0, 5, 2, 0, 0], # [0, 0, 0, 0, 4, 4], # [0, 0, 0, 0, 6, 6], # [0, 0, 0, 0, 0, 0], # [0, 0, 0, 0, 0, 0], # ] UpperCamelCase__ : List[Any] = [[0, 7, 0, 0], [0, 0, 6, 0], [0, 0, 0, 8], [9, 0, 0, 0]] # prepare our network UpperCamelCase__ : Tuple = FlowNetwork(graph, entrances, exits) # set algorithm flow_network.set_maximum_flow_algorithm(PushRelabelExecutor) # and calculate UpperCamelCase__ : str = flow_network.find_maximum_flow() print(F"maximum flow is {maximum_flow}")
330
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase__ : Optional[int] = logging.get_logger(__name__) UpperCamelCase__ : Dict = { """facebook/vit-mae-base""": """https://huggingface.co/facebook/vit-mae-base/resolve/main/config.json""", # See all ViT MAE models at https://huggingface.co/models?filter=vit-mae } class lowerCamelCase_ ( a_ ): SCREAMING_SNAKE_CASE_ = 'vit_mae' def __init__( self : Dict ,__lowerCamelCase : Any=7_68 ,__lowerCamelCase : Optional[Any]=12 ,__lowerCamelCase : List[str]=12 ,__lowerCamelCase : Optional[int]=30_72 ,__lowerCamelCase : int="gelu" ,__lowerCamelCase : Union[str, Any]=0.0 ,__lowerCamelCase : Optional[int]=0.0 ,__lowerCamelCase : Dict=0.02 ,__lowerCamelCase : List[Any]=1e-12 ,__lowerCamelCase : Dict=2_24 ,__lowerCamelCase : str=16 ,__lowerCamelCase : Union[str, Any]=3 ,__lowerCamelCase : Optional[Any]=True ,__lowerCamelCase : Dict=16 ,__lowerCamelCase : List[str]=5_12 ,__lowerCamelCase : int=8 ,__lowerCamelCase : int=20_48 ,__lowerCamelCase : Optional[Any]=0.75 ,__lowerCamelCase : int=False ,**__lowerCamelCase : Any ,): '''simple docstring''' super().__init__(**__lowerCamelCase ) 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 a = decoder_num_attention_heads a = decoder_hidden_size a = decoder_num_hidden_layers a = decoder_intermediate_size a = mask_ratio a = norm_pix_loss
330
1
import os import sys import unittest UpperCamelCase__ : str = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, """utils""")) import check_dummies # noqa: E402 from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init # noqa: E402 # Align TRANSFORMERS_PATH in check_dummies with the current path UpperCamelCase__ : Dict = os.path.join(git_repo_path, """src""", """transformers""") UpperCamelCase__ : Optional[Any] = """ {0} = None """ UpperCamelCase__ : Union[str, Any] = """ class {0}(metaclass=DummyObject): _backends = {1} def __init__(self, *args, **kwargs): requires_backends(self, {1}) """ UpperCamelCase__ : int = """ def {0}(*args, **kwargs): requires_backends({0}, {1}) """ class lowerCamelCase_ ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self : Any ): '''simple docstring''' a = find_backend(''' _import_structure["models.albert"].append("AlbertTokenizerFast")''' ) self.assertIsNone(__lowerCamelCase ) a = find_backend(''' if not is_tokenizers_available():''' ) self.assertEqual(__lowerCamelCase ,'''tokenizers''' ) a = find_backend(''' if not is_tensorflow_text_available():''' ) self.assertEqual(__lowerCamelCase ,'''tensorflow_text''' ) a = find_backend(''' if not (is_sentencepiece_available() and is_tokenizers_available()):''' ) self.assertEqual(__lowerCamelCase ,'''sentencepiece_and_tokenizers''' ) a = find_backend( ''' if not (is_sentencepiece_available() and is_tensorflow_text_available()):''' ) self.assertEqual(__lowerCamelCase ,'''sentencepiece_and_tensorflow_text''' ) a = find_backend( ''' if not (is_sentencepiece_available() and is_tokenizers_available() and is_vision_available()):''' ) self.assertEqual(__lowerCamelCase ,'''sentencepiece_and_tokenizers_and_vision''' ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ): '''simple docstring''' a = read_init() # We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects self.assertIn('''torch''' ,__lowerCamelCase ) self.assertIn('''tensorflow_text''' ,__lowerCamelCase ) self.assertIn('''sentencepiece_and_tokenizers''' ,__lowerCamelCase ) # Likewise, we can't assert on the exact content of a key self.assertIn('''BertModel''' ,objects['''torch'''] ) self.assertIn('''TFBertModel''' ,objects['''tf'''] ) self.assertIn('''FlaxBertModel''' ,objects['''flax'''] ) self.assertIn('''BertModel''' ,objects['''torch'''] ) self.assertIn('''TFBertTokenizer''' ,objects['''tensorflow_text'''] ) self.assertIn('''convert_slow_tokenizer''' ,objects['''sentencepiece_and_tokenizers'''] ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ): '''simple docstring''' a = create_dummy_object('''CONSTANT''' ,'''\'torch\'''' ) self.assertEqual(__lowerCamelCase ,'''\nCONSTANT = None\n''' ) a = create_dummy_object('''function''' ,'''\'torch\'''' ) self.assertEqual( __lowerCamelCase ,'''\ndef function(*args, **kwargs):\n requires_backends(function, \'torch\')\n''' ) a = ''' class FakeClass(metaclass=DummyObject): _backends = \'torch\' def __init__(self, *args, **kwargs): requires_backends(self, \'torch\') ''' a = create_dummy_object('''FakeClass''' ,'''\'torch\'''' ) self.assertEqual(__lowerCamelCase ,__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ): '''simple docstring''' a = '''# This file is autogenerated by the command `make fix-copies`, do not edit. from ..utils import DummyObject, requires_backends CONSTANT = None def function(*args, **kwargs): requires_backends(function, ["torch"]) class FakeClass(metaclass=DummyObject): _backends = ["torch"] def __init__(self, *args, **kwargs): requires_backends(self, ["torch"]) ''' a = create_dummy_files({'''torch''': ['''CONSTANT''', '''function''', '''FakeClass''']} ) self.assertEqual(dummy_files['''torch'''] ,__lowerCamelCase )
330
def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> Union[str, Any]: """simple docstring""" stooge(snake_case_, 0, len(snake_case_ ) - 1 ) return arr def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_ ) -> Optional[Any]: """simple docstring""" if i >= h: return # If first element is smaller than the last then swap them if arr[i] > arr[h]: a , a = arr[h], arr[i] # If there are more than 2 elements in the array if h - i + 1 > 2: a = (int)((h - i + 1) / 3 ) # Recursively sort first 2/3 elements stooge(snake_case_, snake_case_, (h - t) ) # Recursively sort last 2/3 elements stooge(snake_case_, i + t, (snake_case_) ) # Recursively sort first 2/3 elements stooge(snake_case_, snake_case_, (h - t) ) if __name__ == "__main__": UpperCamelCase__ : Dict = input("""Enter numbers separated by a comma:\n""").strip() UpperCamelCase__ : Optional[int] = [int(item) for item in user_input.split(""",""")] print(stooge_sort(unsorted))
330
1
import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DiffusionPipeline, EulerDiscreteScheduler, StableDiffusionXLImgaImgPipeline, UNetaDConditionModel, ) from diffusers.utils import floats_tensor, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowerCamelCase_ ( a_ , a_ , unittest.TestCase ): SCREAMING_SNAKE_CASE_ = StableDiffusionXLImgaImgPipeline SCREAMING_SNAKE_CASE_ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'height', 'width'} SCREAMING_SNAKE_CASE_ = PipelineTesterMixin.required_optional_params - {'latents'} SCREAMING_SNAKE_CASE_ = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS SCREAMING_SNAKE_CASE_ = IMAGE_TO_IMAGE_IMAGE_PARAMS SCREAMING_SNAKE_CASE_ = IMAGE_TO_IMAGE_IMAGE_PARAMS def SCREAMING_SNAKE_CASE_ ( self : str ): '''simple docstring''' torch.manual_seed(0 ) a = UNetaDConditionModel( block_out_channels=(32, 64) ,layers_per_block=2 ,sample_size=32 ,in_channels=4 ,out_channels=4 ,down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') ,up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''') ,attention_head_dim=(2, 4) ,use_linear_projection=__lowerCamelCase ,addition_embed_type='''text_time''' ,addition_time_embed_dim=8 ,transformer_layers_per_block=(1, 2) ,projection_class_embeddings_input_dim=80 ,cross_attention_dim=64 ,) a = EulerDiscreteScheduler( beta_start=0.00_085 ,beta_end=0.012 ,steps_offset=1 ,beta_schedule='''scaled_linear''' ,timestep_spacing='''leading''' ,) torch.manual_seed(0 ) a = AutoencoderKL( block_out_channels=[32, 64] ,in_channels=3 ,out_channels=3 ,down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] ,up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] ,latent_channels=4 ,sample_size=1_28 ,) torch.manual_seed(0 ) a = 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=32 ,) a = CLIPTextModel(__lowerCamelCase ) a = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ,local_files_only=__lowerCamelCase ) a = CLIPTextModelWithProjection(__lowerCamelCase ) a = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ,local_files_only=__lowerCamelCase ) a = { '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''text_encoder_2''': text_encoder_a, '''tokenizer_2''': tokenizer_a, # "safety_checker": None, # "feature_extractor": None, } return components def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ,__lowerCamelCase : Tuple ,__lowerCamelCase : Optional[int]=0 ): '''simple docstring''' a = floats_tensor((1, 3, 32, 32) ,rng=random.Random(__lowerCamelCase ) ).to(__lowerCamelCase ) a = image / 2 + 0.5 if str(__lowerCamelCase ).startswith('''mps''' ): a = torch.manual_seed(__lowerCamelCase ) else: a = torch.Generator(device=__lowerCamelCase ).manual_seed(__lowerCamelCase ) a = { '''prompt''': '''A painting of a squirrel eating a burger''', '''image''': image, '''generator''': generator, '''num_inference_steps''': 2, '''guidance_scale''': 5.0, '''output_type''': '''numpy''', '''strength''': 0.75, } return inputs def SCREAMING_SNAKE_CASE_ ( self : int ): '''simple docstring''' a = '''cpu''' # ensure determinism for the device-dependent torch.Generator a = self.get_dummy_components() a = StableDiffusionXLImgaImgPipeline(**__lowerCamelCase ) a = sd_pipe.to(__lowerCamelCase ) sd_pipe.set_progress_bar_config(disable=__lowerCamelCase ) a = self.get_dummy_inputs(__lowerCamelCase ) a = sd_pipe(**__lowerCamelCase ).images a = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) a = np.array([0.4_656, 0.4_840, 0.4_439, 0.6_698, 0.5_574, 0.4_524, 0.5_799, 0.5_943, 0.5_165] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def SCREAMING_SNAKE_CASE_ ( self : List[str] ): '''simple docstring''' super().test_attention_slicing_forward_pass(expected_max_diff=3e-3 ) def SCREAMING_SNAKE_CASE_ ( self : Dict ): '''simple docstring''' super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) def SCREAMING_SNAKE_CASE_ ( self : Dict ): '''simple docstring''' pass def SCREAMING_SNAKE_CASE_ ( self : Tuple ): '''simple docstring''' a = self.get_dummy_components() a = StableDiffusionXLImgaImgPipeline(**__lowerCamelCase ) a = sd_pipe.to(__lowerCamelCase ) a = sd_pipe.to(__lowerCamelCase ) sd_pipe.set_progress_bar_config(disable=__lowerCamelCase ) # forward without prompt embeds a = self.get_dummy_inputs(__lowerCamelCase ) a = 3 * ['''this is a negative prompt'''] a = negative_prompt a = 3 * [inputs['''prompt''']] a = sd_pipe(**__lowerCamelCase ) a = output.images[0, -3:, -3:, -1] # forward with prompt embeds a = self.get_dummy_inputs(__lowerCamelCase ) a = 3 * ['''this is a negative prompt'''] a = 3 * [inputs.pop('''prompt''' )] ( ( a ) , ( a ) , ( a ) , ( a ) , ) = sd_pipe.encode_prompt(__lowerCamelCase ,negative_prompt=__lowerCamelCase ) a = sd_pipe( **__lowerCamelCase ,prompt_embeds=__lowerCamelCase ,negative_prompt_embeds=__lowerCamelCase ,pooled_prompt_embeds=__lowerCamelCase ,negative_pooled_prompt_embeds=__lowerCamelCase ,) a = output.images[0, -3:, -3:, -1] # make sure that it's equal assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1e-4 @slow @require_torch_gpu class lowerCamelCase_ ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self : str ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE_ ( self : List[Any] ,__lowerCamelCase : Union[str, Any] ,__lowerCamelCase : Union[str, Any]="cpu" ,__lowerCamelCase : Union[str, Any]=torch.floataa ,__lowerCamelCase : Union[str, Any]=0 ): '''simple docstring''' a = torch.Generator(device=__lowerCamelCase ).manual_seed(__lowerCamelCase ) a = np.random.RandomState(__lowerCamelCase ).standard_normal((1, 4, 64, 64) ) a = torch.from_numpy(__lowerCamelCase ).to(device=__lowerCamelCase ,dtype=__lowerCamelCase ) a = { '''prompt''': '''a photograph of an astronaut riding a horse''', '''latents''': latents, '''generator''': generator, '''num_inference_steps''': 3, '''guidance_scale''': 7.5, '''output_type''': '''numpy''', } return inputs def SCREAMING_SNAKE_CASE_ ( self : Any ): '''simple docstring''' a = DiffusionPipeline.from_pretrained('''stabilityai/stable-diffusion-2-base''' ) pipe.to(__lowerCamelCase ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) a = self.get_inputs(__lowerCamelCase ) a = pipe(**__lowerCamelCase ).images a = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 5_12, 5_12, 3) a = np.array([0.49_493, 0.47_896, 0.40_798, 0.54_214, 0.53_212, 0.48_202, 0.47_656, 0.46_329, 0.48_506] ) assert np.abs(image_slice - expected_slice ).max() < 7e-3
330
import json import os import re import unicodedata from json.encoder import INFINITY from typing import Any, Dict, List, Optional, Tuple, Union import numpy as np import regex from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, is_flax_available, is_tf_available, is_torch_available, logging from ...utils.generic import _is_jax, _is_numpy UpperCamelCase__ : Any = logging.get_logger(__name__) UpperCamelCase__ : Optional[Any] = { """artists_file""": """artists.json""", """lyrics_file""": """lyrics.json""", """genres_file""": """genres.json""", } UpperCamelCase__ : Union[str, Any] = { """artists_file""": { """jukebox""": """https://huggingface.co/ArthurZ/jukebox/blob/main/artists.json""", }, """genres_file""": { """jukebox""": """https://huggingface.co/ArthurZ/jukebox/blob/main/genres.json""", }, """lyrics_file""": { """jukebox""": """https://huggingface.co/ArthurZ/jukebox/blob/main/lyrics.json""", }, } UpperCamelCase__ : str = { """jukebox""": 512, } class lowerCamelCase_ ( a_ ): SCREAMING_SNAKE_CASE_ = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE_ = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE_ = PRETRAINED_LYRIC_TOKENS_SIZES SCREAMING_SNAKE_CASE_ = ['input_ids', 'attention_mask'] def __init__( self : Optional[Any] ,__lowerCamelCase : Optional[Any] ,__lowerCamelCase : List[Any] ,__lowerCamelCase : Tuple ,__lowerCamelCase : Union[str, Any]=["v3", "v2", "v2"] ,__lowerCamelCase : List[Any]=5_12 ,__lowerCamelCase : Tuple=5 ,__lowerCamelCase : List[Any]="<|endoftext|>" ,**__lowerCamelCase : List[str] ,): '''simple docstring''' a = AddedToken(__lowerCamelCase ,lstrip=__lowerCamelCase ,rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase ,__lowerCamelCase ) else unk_token super().__init__( unk_token=__lowerCamelCase ,n_genres=__lowerCamelCase ,version=__lowerCamelCase ,max_n_lyric_tokens=__lowerCamelCase ,**__lowerCamelCase ,) a = version a = max_n_lyric_tokens a = n_genres with open(__lowerCamelCase ,encoding='''utf-8''' ) as vocab_handle: a = json.load(__lowerCamelCase ) with open(__lowerCamelCase ,encoding='''utf-8''' ) as vocab_handle: a = json.load(__lowerCamelCase ) with open(__lowerCamelCase ,encoding='''utf-8''' ) as vocab_handle: a = json.load(__lowerCamelCase ) a = r'''[^A-Za-z0-9.,:;!?\-\'\"()\[\] \t\n]+''' # In v2, we had a n_vocab=80 and in v3 we missed + and so n_vocab=79 of characters. if len(self.lyrics_encoder ) == 79: a = oov.replace(r'''\-\'''' ,r'''\-+\'''' ) a = regex.compile(__lowerCamelCase ) a = {v: k for k, v in self.artists_encoder.items()} a = {v: k for k, v in self.genres_encoder.items()} a = {v: k for k, v in self.lyrics_encoder.items()} @property def SCREAMING_SNAKE_CASE_ ( self : str ): '''simple docstring''' return len(self.artists_encoder ) + len(self.genres_encoder ) + len(self.lyrics_encoder ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ): '''simple docstring''' return dict(self.artists_encoder ,self.genres_encoder ,self.lyrics_encoder ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ,__lowerCamelCase : Optional[int] ,__lowerCamelCase : Optional[Any] ,__lowerCamelCase : List[Any] ): '''simple docstring''' a = [self.artists_encoder.get(__lowerCamelCase ,0 ) for artist in list_artists] for genres in range(len(__lowerCamelCase ) ): a = [self.genres_encoder.get(__lowerCamelCase ,0 ) for genre in list_genres[genres]] a = list_genres[genres] + [-1] * (self.n_genres - len(list_genres[genres] )) a = [[self.lyrics_encoder.get(__lowerCamelCase ,0 ) for character in list_lyrics[0]], [], []] return artists_id, list_genres, lyric_ids def SCREAMING_SNAKE_CASE_ ( self : Tuple ,__lowerCamelCase : List[str] ): '''simple docstring''' return list(__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ,__lowerCamelCase : List[Any] ,__lowerCamelCase : Any ,__lowerCamelCase : Optional[int] ,**__lowerCamelCase : Optional[Any] ): '''simple docstring''' a , a , a = self.prepare_for_tokenization(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ) a = self._tokenize(__lowerCamelCase ) return artist, genre, lyrics def SCREAMING_SNAKE_CASE_ ( self : int ,__lowerCamelCase : str ,__lowerCamelCase : str ,__lowerCamelCase : str ,__lowerCamelCase : bool = False ): '''simple docstring''' for idx in range(len(self.version ) ): if self.version[idx] == "v3": a = artists[idx].lower() a = [genres[idx].lower()] else: a = self._normalize(artists[idx] ) + '''.v2''' a = [ self._normalize(__lowerCamelCase ) + '''.v2''' for genre in genres[idx].split('''_''' ) ] # split is for the full dictionary with combined genres if self.version[0] == "v2": a = regex.compile(r'''[^A-Za-z0-9.,:;!?\-\'\"()\[\] \t\n]+''' ) a = '''ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,:;!?-+\'\"()[] \t\n''' a = {vocab[index]: index + 1 for index in range(len(__lowerCamelCase ) )} a = 0 a = len(__lowerCamelCase ) + 1 a = self.vocab a = {v: k for k, v in self.vocab.items()} a = '''''' else: a = regex.compile(r'''[^A-Za-z0-9.,:;!?\-+\'\"()\[\] \t\n]+''' ) a = self._run_strip_accents(__lowerCamelCase ) a = lyrics.replace('''\\''' ,'''\n''' ) a = self.out_of_vocab.sub('''''' ,__lowerCamelCase ), [], [] return artists, genres, lyrics def SCREAMING_SNAKE_CASE_ ( self : str ,__lowerCamelCase : int ): '''simple docstring''' a = unicodedata.normalize('''NFD''' ,__lowerCamelCase ) a = [] for char in text: a = unicodedata.category(__lowerCamelCase ) if cat == "Mn": continue output.append(__lowerCamelCase ) return "".join(__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ,__lowerCamelCase : str ): '''simple docstring''' a = ( [chr(__lowerCamelCase ) for i in range(ord('''a''' ) ,ord('''z''' ) + 1 )] + [chr(__lowerCamelCase ) for i in range(ord('''A''' ) ,ord('''Z''' ) + 1 )] + [chr(__lowerCamelCase ) for i in range(ord('''0''' ) ,ord('''9''' ) + 1 )] + ['''.'''] ) a = frozenset(__lowerCamelCase ) a = re.compile(r'''_+''' ) a = ''''''.join([c if c in accepted else '''_''' for c in text.lower()] ) a = pattern.sub('''_''' ,__lowerCamelCase ).strip('''_''' ) return text def SCREAMING_SNAKE_CASE_ ( self : List[str] ,__lowerCamelCase : List[str] ): '''simple docstring''' return " ".join(__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : Any ,__lowerCamelCase : str ,__lowerCamelCase : Optional[Union[str, TensorType]] = None ,__lowerCamelCase : bool = False ): '''simple docstring''' if not isinstance(__lowerCamelCase ,__lowerCamelCase ): a = TensorType(__lowerCamelCase ) # Get a function reference for the correct framework if tensor_type == TensorType.TENSORFLOW: if not is_tf_available(): raise ImportError( '''Unable to convert output to TensorFlow tensors format, TensorFlow is not installed.''' ) import tensorflow as tf a = tf.constant a = tf.is_tensor elif tensor_type == TensorType.PYTORCH: if not is_torch_available(): raise ImportError('''Unable to convert output to PyTorch tensors format, PyTorch is not installed.''' ) import torch a = torch.tensor a = torch.is_tensor elif tensor_type == TensorType.JAX: if not is_flax_available(): raise ImportError('''Unable to convert output to JAX tensors format, JAX is not installed.''' ) import jax.numpy as jnp # noqa: F811 a = jnp.array a = _is_jax else: a = np.asarray a = _is_numpy # Do the tensor conversion in batch try: if prepend_batch_axis: a = [inputs] if not is_tensor(__lowerCamelCase ): a = as_tensor(__lowerCamelCase ) except: # noqa E722 raise ValueError( '''Unable to create tensor, you should probably activate truncation and/or padding ''' '''with \'padding=True\' \'truncation=True\' to have batched tensors with the same length.''' ) return inputs def __call__( self : Tuple ,__lowerCamelCase : Tuple ,__lowerCamelCase : Optional[int] ,__lowerCamelCase : List[str]="" ,__lowerCamelCase : List[Any]="pt" ): '''simple docstring''' a = [0, 0, 0] a = [artist] * len(self.version ) a = [genres] * len(self.version ) a , a , a = self.tokenize(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ) a , a , a = self._convert_token_to_id(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ) a = [-INFINITY] * len(full_tokens[-1] ) a = [ self.convert_to_tensors( [input_ids + [artists_id[i]] + genres_ids[i] + full_tokens[i]] ,tensor_type=__lowerCamelCase ) for i in range(len(self.version ) ) ] return BatchEncoding({'''input_ids''': input_ids, '''attention_masks''': attention_masks} ) def SCREAMING_SNAKE_CASE_ ( self : int ,__lowerCamelCase : str ,__lowerCamelCase : Optional[str] = None ): '''simple docstring''' 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['''artists_file'''] ) with open(__lowerCamelCase ,'''w''' ,encoding='''utf-8''' ) as f: f.write(json.dumps(self.artists_encoder ,ensure_ascii=__lowerCamelCase ) ) a = os.path.join( __lowerCamelCase ,(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''genres_file'''] ) with open(__lowerCamelCase ,'''w''' ,encoding='''utf-8''' ) as f: f.write(json.dumps(self.genres_encoder ,ensure_ascii=__lowerCamelCase ) ) a = os.path.join( __lowerCamelCase ,(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''lyrics_file'''] ) with open(__lowerCamelCase ,'''w''' ,encoding='''utf-8''' ) as f: f.write(json.dumps(self.lyrics_encoder ,ensure_ascii=__lowerCamelCase ) ) return (artists_file, genres_file, lyrics_file) def SCREAMING_SNAKE_CASE_ ( self : Any ,__lowerCamelCase : Any ,__lowerCamelCase : Any ,__lowerCamelCase : str ): '''simple docstring''' a = self.artists_decoder.get(__lowerCamelCase ) a = [self.genres_decoder.get(__lowerCamelCase ) for genre in genres_index] a = [self.lyrics_decoder.get(__lowerCamelCase ) for character in lyric_index] return artist, genres, lyrics
330
1
from unittest.mock import patch import pyspark from datasets.packaged_modules.spark.spark import ( Spark, SparkExamplesIterable, _generate_iterable_examples, ) from ..utils import ( require_dill_gt_0_3_2, require_not_windows, ) def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> Any: """simple docstring""" a = [] for part_id in partition_order: a = df.where(f"""SPARK_PARTITION_ID() = {part_id}""" ).collect() for row_idx, row in enumerate(snake_case_ ): expected_row_ids_and_row_dicts.append((f"""{part_id}_{row_idx}""", row.asDict()) ) return expected_row_ids_and_row_dicts @require_not_windows @require_dill_gt_0_3_2 def SCREAMING_SNAKE_CASE__ ( ) -> List[str]: """simple docstring""" a = pyspark.sql.SparkSession.builder.master('''local[*]''' ).appName('''pyspark''' ).getOrCreate() a = spark.range(1_0_0 ).repartition(1 ) a = Spark(snake_case_ ) # The id ints will be converted to Pyarrow int64s, so each row will be 8 bytes. Setting a max_shard_size of 16 means # that each partition can hold 2 rows. spark_builder._repartition_df_if_needed(max_shard_size=1_6 ) # Given that the dataframe has 100 rows and each partition has 2 rows, we expect 50 partitions. assert spark_builder.df.rdd.getNumPartitions() == 5_0 @require_not_windows @require_dill_gt_0_3_2 def SCREAMING_SNAKE_CASE__ ( ) -> List[Any]: """simple docstring""" a = pyspark.sql.SparkSession.builder.master('''local[*]''' ).appName('''pyspark''' ).getOrCreate() a = spark.range(1_0 ).repartition(2 ) a = [1, 0] a = _generate_iterable_examples(snake_case_, snake_case_ ) # Reverse the partitions. a = _get_expected_row_ids_and_row_dicts_for_partition_order(snake_case_, snake_case_ ) for i, (row_id, row_dict) in enumerate(generate_fn() ): a , a = expected_row_ids_and_row_dicts[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def SCREAMING_SNAKE_CASE__ ( ) -> Optional[int]: """simple docstring""" a = pyspark.sql.SparkSession.builder.master('''local[*]''' ).appName('''pyspark''' ).getOrCreate() a = spark.range(1_0 ).repartition(1 ) a = SparkExamplesIterable(snake_case_ ) assert it.n_shards == 1 for i, (row_id, row_dict) in enumerate(snake_case_ ): assert row_id == f"""0_{i}""" assert row_dict == {"id": i} @require_not_windows @require_dill_gt_0_3_2 def SCREAMING_SNAKE_CASE__ ( ) -> Any: """simple docstring""" a = pyspark.sql.SparkSession.builder.master('''local[*]''' ).appName('''pyspark''' ).getOrCreate() a = spark.range(3_0 ).repartition(3 ) # Mock the generator so that shuffle reverses the partition indices. with patch('''numpy.random.Generator''' ) as generator_mock: a = lambda snake_case_ : x.reverse() a = _get_expected_row_ids_and_row_dicts_for_partition_order(snake_case_, [2, 1, 0] ) a = SparkExamplesIterable(snake_case_ ).shuffle_data_sources(snake_case_ ) assert shuffled_it.n_shards == 3 for i, (row_id, row_dict) in enumerate(snake_case_ ): a , a = expected_row_ids_and_row_dicts[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def SCREAMING_SNAKE_CASE__ ( ) -> str: """simple docstring""" a = pyspark.sql.SparkSession.builder.master('''local[*]''' ).appName('''pyspark''' ).getOrCreate() a = spark.range(2_0 ).repartition(4 ) # Partitions 0 and 2 a = SparkExamplesIterable(snake_case_ ).shard_data_sources(worker_id=0, num_workers=2 ) assert shard_it_a.n_shards == 2 a = _get_expected_row_ids_and_row_dicts_for_partition_order(snake_case_, [0, 2] ) for i, (row_id, row_dict) in enumerate(snake_case_ ): a , a = expected_row_ids_and_row_dicts_a[i] assert row_id == expected_row_id assert row_dict == expected_row_dict # Partitions 1 and 3 a = SparkExamplesIterable(snake_case_ ).shard_data_sources(worker_id=1, num_workers=2 ) assert shard_it_a.n_shards == 2 a = _get_expected_row_ids_and_row_dicts_for_partition_order(snake_case_, [1, 3] ) for i, (row_id, row_dict) in enumerate(snake_case_ ): a , a = expected_row_ids_and_row_dicts_a[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def SCREAMING_SNAKE_CASE__ ( ) -> Optional[int]: """simple docstring""" a = pyspark.sql.SparkSession.builder.master('''local[*]''' ).appName('''pyspark''' ).getOrCreate() a = spark.range(1_0_0 ).repartition(1 ) a = Spark(snake_case_ ) # Choose a small max_shard_size for maximum partitioning. spark_builder._repartition_df_if_needed(max_shard_size=1 ) # The new number of partitions should not be greater than the number of rows. assert spark_builder.df.rdd.getNumPartitions() == 1_0_0
330
# This script creates a super tiny model that is useful inside tests, when we just want to test that # the machinery works, without needing to the check the quality of the outcomes. # # This version creates a tiny vocab first, and then a tiny model - so the outcome is truly tiny - # all files ~60KB. As compared to taking a full-size model, reducing to the minimum its layers and # emb dimensions, but keeping the full vocab + merges files, leading to ~3MB in total for all files. # The latter is done by `fsmt-make-super-tiny-model.py`. # # It will be used then as "stas/tiny-wmt19-en-ru" from pathlib import Path import json import tempfile from transformers import FSMTTokenizer, FSMTConfig, FSMTForConditionalGeneration from transformers.models.fsmt.tokenization_fsmt import VOCAB_FILES_NAMES UpperCamelCase__ : Optional[Any] = """tiny-wmt19-en-ru""" # Build # borrowed from a test UpperCamelCase__ : Any = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """w</w>""", """r</w>""", """t</w>""", """lo""", """low""", """er</w>""", """low</w>""", """lowest</w>""", """newer</w>""", """wider</w>""", """<unk>""", ] UpperCamelCase__ : List[Any] = dict(zip(vocab, range(len(vocab)))) UpperCamelCase__ : Any = ["""l o 123""", """lo w 1456""", """e r</w> 1789""", """"""] with tempfile.TemporaryDirectory() as tmpdirname: UpperCamelCase__ : Optional[Any] = Path(tmpdirname) UpperCamelCase__ : Tuple = build_dir / VOCAB_FILES_NAMES["""src_vocab_file"""] UpperCamelCase__ : int = build_dir / VOCAB_FILES_NAMES["""tgt_vocab_file"""] UpperCamelCase__ : Union[str, Any] = build_dir / VOCAB_FILES_NAMES["""merges_file"""] with open(src_vocab_file, """w""") as fp: fp.write(json.dumps(vocab_tokens)) with open(tgt_vocab_file, """w""") as fp: fp.write(json.dumps(vocab_tokens)) with open(merges_file, """w""") as fp: fp.write("""\n""".join(merges)) UpperCamelCase__ : Dict = FSMTTokenizer( langs=["""en""", """ru"""], src_vocab_size=len(vocab), tgt_vocab_size=len(vocab), src_vocab_file=src_vocab_file, tgt_vocab_file=tgt_vocab_file, merges_file=merges_file, ) UpperCamelCase__ : Union[str, Any] = FSMTConfig( langs=["""ru""", """en"""], src_vocab_size=1_000, tgt_vocab_size=1_000, d_model=4, encoder_layers=1, decoder_layers=1, encoder_ffn_dim=4, decoder_ffn_dim=4, encoder_attention_heads=1, decoder_attention_heads=1, ) UpperCamelCase__ : Union[str, Any] = FSMTForConditionalGeneration(config) print(F"num of params {tiny_model.num_parameters()}") # Test UpperCamelCase__ : List[str] = tokenizer(["""Making tiny model"""], return_tensors="""pt""") UpperCamelCase__ : Tuple = tiny_model(**batch) print("""test output:""", len(outputs.logits[0])) # Save tiny_model.half() # makes it smaller tiny_model.save_pretrained(mname_tiny) tokenizer.save_pretrained(mname_tiny) print(F"Generated {mname_tiny}") # Upload # transformers-cli upload tiny-wmt19-en-ru
330
1
import importlib import os from dataclasses import dataclass from enum import Enum from typing import Any, Dict, Optional, Union import torch from ..utils import BaseOutput UpperCamelCase__ : Dict = """scheduler_config.json""" class lowerCamelCase_ ( a_ ): SCREAMING_SNAKE_CASE_ = 1 SCREAMING_SNAKE_CASE_ = 2 SCREAMING_SNAKE_CASE_ = 3 SCREAMING_SNAKE_CASE_ = 4 SCREAMING_SNAKE_CASE_ = 5 SCREAMING_SNAKE_CASE_ = 6 SCREAMING_SNAKE_CASE_ = 7 SCREAMING_SNAKE_CASE_ = 8 SCREAMING_SNAKE_CASE_ = 9 SCREAMING_SNAKE_CASE_ = 10 SCREAMING_SNAKE_CASE_ = 11 SCREAMING_SNAKE_CASE_ = 12 SCREAMING_SNAKE_CASE_ = 13 SCREAMING_SNAKE_CASE_ = 14 @dataclass class lowerCamelCase_ ( a_ ): SCREAMING_SNAKE_CASE_ = 42 class lowerCamelCase_ : SCREAMING_SNAKE_CASE_ = SCHEDULER_CONFIG_NAME SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = True @classmethod def SCREAMING_SNAKE_CASE_ ( cls : Dict ,__lowerCamelCase : Dict[str, Any] = None ,__lowerCamelCase : Optional[str] = None ,__lowerCamelCase : List[Any]=False ,**__lowerCamelCase : Any ,): '''simple docstring''' a , a , a = cls.load_config( pretrained_model_name_or_path=__lowerCamelCase ,subfolder=__lowerCamelCase ,return_unused_kwargs=__lowerCamelCase ,return_commit_hash=__lowerCamelCase ,**__lowerCamelCase ,) return cls.from_config(__lowerCamelCase ,return_unused_kwargs=__lowerCamelCase ,**__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : str ,__lowerCamelCase : Union[str, os.PathLike] ,__lowerCamelCase : bool = False ,**__lowerCamelCase : Optional[Any] ): '''simple docstring''' self.save_config(save_directory=__lowerCamelCase ,push_to_hub=__lowerCamelCase ,**__lowerCamelCase ) @property def SCREAMING_SNAKE_CASE_ ( self : Tuple ): '''simple docstring''' return self._get_compatibles() @classmethod def SCREAMING_SNAKE_CASE_ ( cls : Optional[Any] ): '''simple docstring''' a = list(set([cls.__name__] + cls._compatibles ) ) a = importlib.import_module(__name__.split('''.''' )[0] ) a = [ getattr(__lowerCamelCase ,__lowerCamelCase ) for c in compatible_classes_str if hasattr(__lowerCamelCase ,__lowerCamelCase ) ] return compatible_classes
330
import inspect import os import torch from transformers import AutoModel from transformers.testing_utils import mockenv_context from transformers.trainer_utils import set_seed import accelerate from accelerate.accelerator import Accelerator from accelerate.state import AcceleratorState from accelerate.test_utils.testing import ( AccelerateTestCase, TempDirTestCase, execute_subprocess_async, require_cuda, require_fsdp, require_multi_gpu, slow, ) from accelerate.utils.constants import ( FSDP_AUTO_WRAP_POLICY, FSDP_BACKWARD_PREFETCH, FSDP_SHARDING_STRATEGY, FSDP_STATE_DICT_TYPE, ) from accelerate.utils.dataclasses import FullyShardedDataParallelPlugin from accelerate.utils.other import patch_environment set_seed(42) UpperCamelCase__ : Optional[Any] = """bert-base-cased""" UpperCamelCase__ : int = """fp16""" UpperCamelCase__ : str = """bf16""" UpperCamelCase__ : List[Any] = [FPaa, BFaa] @require_fsdp @require_cuda class lowerCamelCase_ ( a_ ): def SCREAMING_SNAKE_CASE_ ( self : int ): '''simple docstring''' super().setUp() a = dict( ACCELERATE_USE_FSDP='''true''' ,MASTER_ADDR='''localhost''' ,MASTER_PORT='''10999''' ,RANK='''0''' ,LOCAL_RANK='''0''' ,WORLD_SIZE='''1''' ,) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ): '''simple docstring''' from torch.distributed.fsdp.fully_sharded_data_parallel import ShardingStrategy for i, strategy in enumerate(__lowerCamelCase ): a = self.dist_env.copy() a = F"""{i + 1}""" a = strategy with mockenv_context(**__lowerCamelCase ): a = FullyShardedDataParallelPlugin() self.assertEqual(fsdp_plugin.sharding_strategy ,ShardingStrategy(i + 1 ) ) def SCREAMING_SNAKE_CASE_ ( self : Any ): '''simple docstring''' from torch.distributed.fsdp.fully_sharded_data_parallel import BackwardPrefetch for i, prefetch_policy in enumerate(__lowerCamelCase ): a = self.dist_env.copy() a = prefetch_policy with mockenv_context(**__lowerCamelCase ): a = FullyShardedDataParallelPlugin() if prefetch_policy == "NO_PREFETCH": self.assertIsNone(fsdp_plugin.backward_prefetch ) else: self.assertEqual(fsdp_plugin.backward_prefetch ,BackwardPrefetch(i + 1 ) ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ): '''simple docstring''' from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType for i, state_dict_type in enumerate(__lowerCamelCase ): a = self.dist_env.copy() a = state_dict_type with mockenv_context(**__lowerCamelCase ): a = FullyShardedDataParallelPlugin() self.assertEqual(fsdp_plugin.state_dict_type ,StateDictType(i + 1 ) ) if state_dict_type == "FULL_STATE_DICT": self.assertTrue(fsdp_plugin.state_dict_config.offload_to_cpu ) self.assertTrue(fsdp_plugin.state_dict_config.ranka_only ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ): '''simple docstring''' a = AutoModel.from_pretrained(__lowerCamelCase ) for policy in FSDP_AUTO_WRAP_POLICY: a = self.dist_env.copy() a = policy if policy == "TRANSFORMER_BASED_WRAP": a = '''BertLayer''' elif policy == "SIZE_BASED_WRAP": a = '''2000''' with mockenv_context(**__lowerCamelCase ): a = FullyShardedDataParallelPlugin() fsdp_plugin.set_auto_wrap_policy(__lowerCamelCase ) if policy == "NO_WRAP": self.assertIsNone(fsdp_plugin.auto_wrap_policy ) else: self.assertIsNotNone(fsdp_plugin.auto_wrap_policy ) a = self.dist_env.copy() a = '''TRANSFORMER_BASED_WRAP''' a = '''T5Layer''' with mockenv_context(**__lowerCamelCase ): a = FullyShardedDataParallelPlugin() with self.assertRaises(__lowerCamelCase ) as cm: fsdp_plugin.set_auto_wrap_policy(__lowerCamelCase ) self.assertTrue('''Could not find the transformer layer class to wrap in the model.''' in str(cm.exception ) ) a = self.dist_env.copy() a = '''SIZE_BASED_WRAP''' a = '''0''' with mockenv_context(**__lowerCamelCase ): a = FullyShardedDataParallelPlugin() fsdp_plugin.set_auto_wrap_policy(__lowerCamelCase ) self.assertIsNone(fsdp_plugin.auto_wrap_policy ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ): '''simple docstring''' from torch.distributed.fsdp.fully_sharded_data_parallel import MixedPrecision from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler for mp_dtype in dtypes: a = self.dist_env.copy() a = mp_dtype with mockenv_context(**__lowerCamelCase ): a = Accelerator() if mp_dtype == "fp16": a = torch.floataa elif mp_dtype == "bf16": a = torch.bfloataa a = MixedPrecision(param_dtype=__lowerCamelCase ,reduce_dtype=__lowerCamelCase ,buffer_dtype=__lowerCamelCase ) self.assertEqual(accelerator.state.fsdp_plugin.mixed_precision_policy ,__lowerCamelCase ) if mp_dtype == FPaa: self.assertTrue(isinstance(accelerator.scaler ,__lowerCamelCase ) ) elif mp_dtype == BFaa: self.assertIsNone(accelerator.scaler ) AcceleratorState._reset_state(__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ): '''simple docstring''' from torch.distributed.fsdp.fully_sharded_data_parallel import CPUOffload for flag in [True, False]: a = self.dist_env.copy() a = str(__lowerCamelCase ).lower() with mockenv_context(**__lowerCamelCase ): a = FullyShardedDataParallelPlugin() self.assertEqual(fsdp_plugin.cpu_offload ,CPUOffload(offload_params=__lowerCamelCase ) ) @require_fsdp @require_multi_gpu @slow class lowerCamelCase_ ( a_ ): def SCREAMING_SNAKE_CASE_ ( self : List[Any] ): '''simple docstring''' super().setUp() a = 0.82 a = [ '''fsdp_shard_grad_op_transformer_based_wrap''', '''fsdp_full_shard_transformer_based_wrap''', ] a = { '''multi_gpu_fp16''': 32_00, '''fsdp_shard_grad_op_transformer_based_wrap_fp16''': 20_00, '''fsdp_full_shard_transformer_based_wrap_fp16''': 19_00, # Disabling below test as it overwhelms the RAM memory usage # on CI self-hosted runner leading to tests getting killed. # "fsdp_full_shard_cpu_offload_transformer_based_wrap_fp32": 1500, # fp16 was leading to indefinite hang } a = 1_60 a = 1_60 a = inspect.getfile(accelerate.test_utils ) a = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''external_deps'''] ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ): '''simple docstring''' a = os.path.join(self.test_scripts_folder ,'''test_performance.py''' ) a = ['''accelerate''', '''launch''', '''--num_processes=2''', '''--num_machines=1''', '''--machine_rank=0''', '''--use_fsdp'''] for config in self.performance_configs: a = cmd.copy() for i, strategy in enumerate(__lowerCamelCase ): if strategy.lower() in config: cmd_config.append(F"""--fsdp_sharding_strategy={i+1}""" ) break if "fp32" in config: cmd_config.append('''--mixed_precision=no''' ) else: cmd_config.append('''--mixed_precision=fp16''' ) if "cpu_offload" in config: cmd_config.append('''--fsdp_offload_params=True''' ) for policy in FSDP_AUTO_WRAP_POLICY: if policy.lower() in config: cmd_config.append(F"""--fsdp_auto_wrap_policy={policy}""" ) break if policy == "TRANSFORMER_BASED_WRAP": cmd_config.append('''--fsdp_transformer_layer_cls_to_wrap=BertLayer''' ) elif policy == "SIZE_BASED_WRAP": cmd_config.append('''--fsdp_min_num_params=2000''' ) cmd_config.extend( [ self.test_file_path, F"""--output_dir={self.tmpdir}""", F"""--performance_lower_bound={self.performance_lower_bound}""", ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__lowerCamelCase ,env=os.environ.copy() ) def SCREAMING_SNAKE_CASE_ ( self : Any ): '''simple docstring''' a = os.path.join(self.test_scripts_folder ,'''test_checkpointing.py''' ) a = [ '''accelerate''', '''launch''', '''--num_processes=2''', '''--num_machines=1''', '''--machine_rank=0''', '''--use_fsdp''', '''--mixed_precision=fp16''', '''--fsdp_transformer_layer_cls_to_wrap=BertLayer''', ] for i, strategy in enumerate(__lowerCamelCase ): a = cmd.copy() cmd_config.append(F"""--fsdp_sharding_strategy={i+1}""" ) if strategy != "FULL_SHARD": continue a = len(__lowerCamelCase ) for state_dict_type in FSDP_STATE_DICT_TYPE: a = cmd_config[:state_dict_config_index] cmd_config.append(F"""--fsdp_state_dict_type={state_dict_type}""" ) cmd_config.extend( [ self.test_file_path, F"""--output_dir={self.tmpdir}""", '''--partial_train_epoch=1''', ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__lowerCamelCase ,env=os.environ.copy() ) a = cmd_config[:-1] a = os.path.join(self.tmpdir ,'''epoch_0''' ) cmd_config.extend( [ F"""--resume_from_checkpoint={resume_from_checkpoint}""", ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__lowerCamelCase ,env=os.environ.copy() ) def SCREAMING_SNAKE_CASE_ ( self : int ): '''simple docstring''' a = os.path.join(self.test_scripts_folder ,'''test_peak_memory_usage.py''' ) a = [ '''accelerate''', '''launch''', '''--num_processes=2''', '''--num_machines=1''', '''--machine_rank=0''', ] for spec, peak_mem_upper_bound in self.peak_memory_usage_upper_bound.items(): a = cmd.copy() if "fp16" in spec: cmd_config.extend(['''--mixed_precision=fp16'''] ) else: cmd_config.extend(['''--mixed_precision=no'''] ) if "multi_gpu" in spec: continue else: cmd_config.extend(['''--use_fsdp'''] ) for i, strategy in enumerate(__lowerCamelCase ): if strategy.lower() in spec: cmd_config.append(F"""--fsdp_sharding_strategy={i+1}""" ) break if "cpu_offload" in spec: cmd_config.append('''--fsdp_offload_params=True''' ) for policy in FSDP_AUTO_WRAP_POLICY: if policy.lower() in spec: cmd_config.append(F"""--fsdp_auto_wrap_policy={policy}""" ) break if policy == "TRANSFORMER_BASED_WRAP": cmd_config.append('''--fsdp_transformer_layer_cls_to_wrap=BertLayer''' ) elif policy == "SIZE_BASED_WRAP": cmd_config.append('''--fsdp_min_num_params=2000''' ) cmd_config.extend( [ self.test_file_path, F"""--output_dir={self.tmpdir}""", F"""--peak_memory_upper_bound={peak_mem_upper_bound}""", F"""--n_train={self.n_train}""", F"""--n_val={self.n_val}""", ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__lowerCamelCase ,env=os.environ.copy() )
330
1
import math from enum import Enum from typing import Optional, Union from torch.optim import Optimizer from torch.optim.lr_scheduler import LambdaLR from .utils import logging UpperCamelCase__ : str = logging.get_logger(__name__) class lowerCamelCase_ ( a_ ): SCREAMING_SNAKE_CASE_ = 'linear' SCREAMING_SNAKE_CASE_ = 'cosine' SCREAMING_SNAKE_CASE_ = 'cosine_with_restarts' SCREAMING_SNAKE_CASE_ = 'polynomial' SCREAMING_SNAKE_CASE_ = 'constant' SCREAMING_SNAKE_CASE_ = 'constant_with_warmup' SCREAMING_SNAKE_CASE_ = 'piecewise_constant' def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ = -1 ) -> int: """simple docstring""" return LambdaLR(snake_case_, lambda snake_case_ : 1, last_epoch=snake_case_ ) def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_ = -1 ) -> Union[str, Any]: """simple docstring""" def lr_lambda(snake_case_ ): if current_step < num_warmup_steps: return float(snake_case_ ) / float(max(1.0, snake_case_ ) ) return 1.0 return LambdaLR(snake_case_, snake_case_, last_epoch=snake_case_ ) def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_ = -1 ) -> Tuple: """simple docstring""" a = {} a = step_rules.split(''',''' ) for rule_str in rule_list[:-1]: a , a = rule_str.split(''':''' ) a = int(snake_case_ ) a = float(snake_case_ ) a = value a = float(rule_list[-1] ) def create_rules_function(snake_case_, snake_case_ ): def rule_func(snake_case_ ) -> float: a = sorted(rules_dict.keys() ) for i, sorted_step in enumerate(snake_case_ ): if steps < sorted_step: return rules_dict[sorted_steps[i]] return last_lr_multiple return rule_func a = create_rules_function(snake_case_, snake_case_ ) return LambdaLR(snake_case_, snake_case_, last_epoch=snake_case_ ) def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_, snake_case_=-1 ) -> Optional[Any]: """simple docstring""" def lr_lambda(snake_case_ ): if current_step < num_warmup_steps: return float(snake_case_ ) / float(max(1, snake_case_ ) ) return max( 0.0, float(num_training_steps - current_step ) / float(max(1, num_training_steps - num_warmup_steps ) ) ) return LambdaLR(snake_case_, snake_case_, snake_case_ ) def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_, snake_case_ = 0.5, snake_case_ = -1 ) -> Union[str, Any]: """simple docstring""" def lr_lambda(snake_case_ ): if current_step < num_warmup_steps: return float(snake_case_ ) / float(max(1, snake_case_ ) ) a = float(current_step - num_warmup_steps ) / float(max(1, num_training_steps - num_warmup_steps ) ) return max(0.0, 0.5 * (1.0 + math.cos(math.pi * float(snake_case_ ) * 2.0 * progress )) ) return LambdaLR(snake_case_, snake_case_, snake_case_ ) def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_, snake_case_ = 1, snake_case_ = -1 ) -> Tuple: """simple docstring""" def lr_lambda(snake_case_ ): if current_step < num_warmup_steps: return float(snake_case_ ) / float(max(1, snake_case_ ) ) a = float(current_step - num_warmup_steps ) / float(max(1, num_training_steps - num_warmup_steps ) ) if progress >= 1.0: return 0.0 return max(0.0, 0.5 * (1.0 + math.cos(math.pi * ((float(snake_case_ ) * progress) % 1.0) )) ) return LambdaLR(snake_case_, snake_case_, snake_case_ ) def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_, snake_case_=1e-7, snake_case_=1.0, snake_case_=-1 ) -> int: """simple docstring""" a = optimizer.defaults['''lr'''] if not (lr_init > lr_end): raise ValueError(f"""lr_end ({lr_end}) must be be smaller than initial lr ({lr_init})""" ) def lr_lambda(snake_case_ ): if current_step < num_warmup_steps: return float(snake_case_ ) / float(max(1, snake_case_ ) ) elif current_step > num_training_steps: return lr_end / lr_init # as LambdaLR multiplies by lr_init else: a = lr_init - lr_end a = num_training_steps - num_warmup_steps a = 1 - (current_step - num_warmup_steps) / decay_steps a = lr_range * pct_remaining**power + lr_end return decay / lr_init # as LambdaLR multiplies by lr_init return LambdaLR(snake_case_, snake_case_, snake_case_ ) UpperCamelCase__ : Dict = { SchedulerType.LINEAR: get_linear_schedule_with_warmup, SchedulerType.COSINE: get_cosine_schedule_with_warmup, SchedulerType.COSINE_WITH_RESTARTS: get_cosine_with_hard_restarts_schedule_with_warmup, SchedulerType.POLYNOMIAL: get_polynomial_decay_schedule_with_warmup, SchedulerType.CONSTANT: get_constant_schedule, SchedulerType.CONSTANT_WITH_WARMUP: get_constant_schedule_with_warmup, SchedulerType.PIECEWISE_CONSTANT: get_piecewise_constant_schedule, } def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_ = None, snake_case_ = None, snake_case_ = None, snake_case_ = 1, snake_case_ = 1.0, snake_case_ = -1, ) -> List[Any]: """simple docstring""" a = SchedulerType(snake_case_ ) a = TYPE_TO_SCHEDULER_FUNCTION[name] if name == SchedulerType.CONSTANT: return schedule_func(snake_case_, last_epoch=snake_case_ ) if name == SchedulerType.PIECEWISE_CONSTANT: return schedule_func(snake_case_, step_rules=snake_case_, last_epoch=snake_case_ ) # All other schedulers require `num_warmup_steps` if num_warmup_steps is None: raise ValueError(f"""{name} requires `num_warmup_steps`, please provide that argument.""" ) if name == SchedulerType.CONSTANT_WITH_WARMUP: return schedule_func(snake_case_, num_warmup_steps=snake_case_, last_epoch=snake_case_ ) # All other schedulers require `num_training_steps` if num_training_steps is None: raise ValueError(f"""{name} requires `num_training_steps`, please provide that argument.""" ) if name == SchedulerType.COSINE_WITH_RESTARTS: return schedule_func( snake_case_, num_warmup_steps=snake_case_, num_training_steps=snake_case_, num_cycles=snake_case_, last_epoch=snake_case_, ) if name == SchedulerType.POLYNOMIAL: return schedule_func( snake_case_, num_warmup_steps=snake_case_, num_training_steps=snake_case_, power=snake_case_, last_epoch=snake_case_, ) return schedule_func( snake_case_, num_warmup_steps=snake_case_, num_training_steps=snake_case_, last_epoch=snake_case_ )
330
from __future__ import annotations import os from collections.abc import Mapping UpperCamelCase__ : Any = tuple[int, int] class lowerCamelCase_ : def __init__( self : Optional[Any] ,__lowerCamelCase : set[int] ,__lowerCamelCase : Mapping[EdgeT, int] ): '''simple docstring''' a = vertices a = { (min(__lowerCamelCase ), max(__lowerCamelCase )): weight for edge, weight in edges.items() } def SCREAMING_SNAKE_CASE_ ( self : str ,__lowerCamelCase : EdgeT ,__lowerCamelCase : int ): '''simple docstring''' self.vertices.add(edge[0] ) self.vertices.add(edge[1] ) a = weight def SCREAMING_SNAKE_CASE_ ( self : Dict ): '''simple docstring''' a = Graph({min(self.vertices )} ,{} ) a = 42 a = 42 a = 42 a = 42 while len(subgraph.vertices ) < len(self.vertices ): a = max(self.edges.values() ) + 1 for edge, weight in self.edges.items(): if (edge[0] in subgraph.vertices) ^ (edge[1] in subgraph.vertices): if weight < min_weight: a = edge a = weight subgraph.add_edge(__lowerCamelCase ,__lowerCamelCase ) return subgraph def SCREAMING_SNAKE_CASE__ ( snake_case_ = "p107_network.txt" ) -> int: """simple docstring""" a = os.path.abspath(os.path.dirname(snake_case_ ) ) a = os.path.join(snake_case_, snake_case_ ) a = {} a = 42 a = 42 a = 42 with open(snake_case_ ) as f: a = f.read().strip().split('''\n''' ) a = [line.split(''',''' ) for line in data] for edgea in range(1, len(snake_case_ ) ): for edgea in range(snake_case_ ): if adjaceny_matrix[edgea][edgea] != "-": a = int(adjaceny_matrix[edgea][edgea] ) a = Graph(set(range(len(snake_case_ ) ) ), snake_case_ ) a = graph.prims_algorithm() a = sum(graph.edges.values() ) a = sum(subgraph.edges.values() ) return initial_total - optimal_total if __name__ == "__main__": print(F"{solution() = }")
330
1
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse from ...utils.dataclasses import ( ComputeEnvironment, DistributedType, DynamoBackend, PrecisionType, SageMakerDistributedType, ) from ..menu import BulletMenu UpperCamelCase__ : Optional[int] = [ """EAGER""", """AOT_EAGER""", """INDUCTOR""", """NVFUSER""", """AOT_NVFUSER""", """AOT_CUDAGRAPHS""", """OFI""", """FX2TRT""", """ONNXRT""", """IPEX""", ] def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_=None, snake_case_=None, snake_case_=None ) -> int: """simple docstring""" a = True while ask_again: a = input(snake_case_ ) try: if default is not None and len(snake_case_ ) == 0: return default return convert_value(snake_case_ ) if convert_value is not None else result except Exception: if error_message is not None: print(snake_case_ ) def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_=[], snake_case_=None, snake_case_=0 ) -> int: """simple docstring""" a = BulletMenu(snake_case_, snake_case_ ) a = menu.run(default_choice=snake_case_ ) return convert_value(snake_case_ ) if convert_value is not None else result def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> Optional[int]: """simple docstring""" a = int(snake_case_ ) return ComputeEnvironment(['''LOCAL_MACHINE''', '''AMAZON_SAGEMAKER'''][value] ) def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> int: """simple docstring""" a = int(snake_case_ ) return DistributedType(['''NO''', '''MULTI_CPU''', '''MULTI_XPU''', '''MULTI_GPU''', '''MULTI_NPU''', '''TPU'''][value] ) def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> Tuple: """simple docstring""" a = int(snake_case_ ) return DynamoBackend(DYNAMO_BACKENDS[value] ).value def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> int: """simple docstring""" a = int(snake_case_ ) return PrecisionType(['''no''', '''fp16''', '''bf16''', '''fp8'''][value] ) def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> Optional[Any]: """simple docstring""" a = int(snake_case_ ) return SageMakerDistributedType(['''NO''', '''DATA_PARALLEL''', '''MODEL_PARALLEL'''][value] ) def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> List[str]: """simple docstring""" return {"yes": True, "no": False}[value.lower()] class lowerCamelCase_ ( argparse.RawDescriptionHelpFormatter ): def SCREAMING_SNAKE_CASE_ ( self : str ,__lowerCamelCase : Optional[Any] ,__lowerCamelCase : List[Any] ,__lowerCamelCase : List[str] ,__lowerCamelCase : Optional[int] ): '''simple docstring''' a = super()._format_usage(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ) a = usage.replace('''<command> [<args>] ''' ,'''''' ) return usage
330
from typing import Optional, Tuple, Union import tensorflow as tf from ...activations_tf import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_tf_outputs import ( TFBaseModelOutputWithNoAttention, TFBaseModelOutputWithPoolingAndNoAttention, TFSequenceClassifierOutput, ) from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs from ...tf_utils import shape_list from ...utils import logging from .configuration_regnet import RegNetConfig UpperCamelCase__ : List[Any] = logging.get_logger(__name__) # General docstring UpperCamelCase__ : List[Any] = """RegNetConfig""" # Base docstring UpperCamelCase__ : Dict = """facebook/regnet-y-040""" UpperCamelCase__ : int = [1, 1_088, 7, 7] # Image classification docstring UpperCamelCase__ : Optional[Any] = """facebook/regnet-y-040""" UpperCamelCase__ : Dict = """tabby, tabby cat""" UpperCamelCase__ : Dict = [ """facebook/regnet-y-040""", # See all regnet models at https://huggingface.co/models?filter=regnet ] class lowerCamelCase_ ( tf.keras.layers.Layer ): def __init__( self : List[str] ,__lowerCamelCase : int ,__lowerCamelCase : int = 3 ,__lowerCamelCase : int = 1 ,__lowerCamelCase : int = 1 ,__lowerCamelCase : Optional[str] = "relu" ,**__lowerCamelCase : str ,): '''simple docstring''' super().__init__(**__lowerCamelCase ) # The padding and conv has been verified in # https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb a = tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2 ) a = tf.keras.layers.ConvaD( filters=__lowerCamelCase ,kernel_size=__lowerCamelCase ,strides=__lowerCamelCase ,padding='''VALID''' ,groups=__lowerCamelCase ,use_bias=__lowerCamelCase ,name='''convolution''' ,) a = tf.keras.layers.BatchNormalization(epsilon=1e-5 ,momentum=0.9 ,name='''normalization''' ) a = ACTaFN[activation] if activation is not None else tf.identity def SCREAMING_SNAKE_CASE_ ( self : str ,__lowerCamelCase : List[str] ): '''simple docstring''' a = self.convolution(self.padding(__lowerCamelCase ) ) a = self.normalization(__lowerCamelCase ) a = self.activation(__lowerCamelCase ) return hidden_state class lowerCamelCase_ ( tf.keras.layers.Layer ): def __init__( self : Any ,__lowerCamelCase : RegNetConfig ,**__lowerCamelCase : List[Any] ): '''simple docstring''' super().__init__(**__lowerCamelCase ) a = config.num_channels a = TFRegNetConvLayer( out_channels=config.embedding_size ,kernel_size=3 ,stride=2 ,activation=config.hidden_act ,name='''embedder''' ,) def SCREAMING_SNAKE_CASE_ ( self : Any ,__lowerCamelCase : Optional[Any] ): '''simple docstring''' a = shape_list(__lowerCamelCase )[1] if tf.executing_eagerly() and num_channels != self.num_channels: raise ValueError( '''Make sure that the channel dimension of the pixel values match with the one set in the configuration.''' ) # When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format. # So change the input format from `NCHW` to `NHWC`. # shape = (batch_size, in_height, in_width, in_channels=num_channels) a = tf.transpose(__lowerCamelCase ,perm=(0, 2, 3, 1) ) a = self.embedder(__lowerCamelCase ) return hidden_state class lowerCamelCase_ ( tf.keras.layers.Layer ): def __init__( self : str ,__lowerCamelCase : int ,__lowerCamelCase : int = 2 ,**__lowerCamelCase : Tuple ): '''simple docstring''' super().__init__(**__lowerCamelCase ) a = tf.keras.layers.ConvaD( filters=__lowerCamelCase ,kernel_size=1 ,strides=__lowerCamelCase ,use_bias=__lowerCamelCase ,name='''convolution''' ) a = tf.keras.layers.BatchNormalization(epsilon=1e-5 ,momentum=0.9 ,name='''normalization''' ) def SCREAMING_SNAKE_CASE_ ( self : Dict ,__lowerCamelCase : tf.Tensor ,__lowerCamelCase : bool = False ): '''simple docstring''' return self.normalization(self.convolution(__lowerCamelCase ) ,training=__lowerCamelCase ) class lowerCamelCase_ ( tf.keras.layers.Layer ): def __init__( self : List[Any] ,__lowerCamelCase : int ,__lowerCamelCase : int ,**__lowerCamelCase : str ): '''simple docstring''' super().__init__(**__lowerCamelCase ) a = tf.keras.layers.GlobalAveragePoolingaD(keepdims=__lowerCamelCase ,name='''pooler''' ) a = [ tf.keras.layers.ConvaD(filters=__lowerCamelCase ,kernel_size=1 ,activation='''relu''' ,name='''attention.0''' ), tf.keras.layers.ConvaD(filters=__lowerCamelCase ,kernel_size=1 ,activation='''sigmoid''' ,name='''attention.2''' ), ] def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ,__lowerCamelCase : Optional[Any] ): '''simple docstring''' a = self.pooler(__lowerCamelCase ) for layer_module in self.attention: a = layer_module(__lowerCamelCase ) a = hidden_state * pooled return hidden_state class lowerCamelCase_ ( tf.keras.layers.Layer ): def __init__( self : Union[str, Any] ,__lowerCamelCase : RegNetConfig ,__lowerCamelCase : int ,__lowerCamelCase : int ,__lowerCamelCase : int = 1 ,**__lowerCamelCase : Dict ): '''simple docstring''' super().__init__(**__lowerCamelCase ) a = in_channels != out_channels or stride != 1 a = max(1 ,out_channels // config.groups_width ) a = ( TFRegNetShortCut(__lowerCamelCase ,stride=__lowerCamelCase ,name='''shortcut''' ) if should_apply_shortcut else tf.keras.layers.Activation('''linear''' ,name='''shortcut''' ) ) # `self.layers` instead of `self.layer` because that is a reserved argument. a = [ TFRegNetConvLayer(__lowerCamelCase ,kernel_size=1 ,activation=config.hidden_act ,name='''layer.0''' ), TFRegNetConvLayer( __lowerCamelCase ,stride=__lowerCamelCase ,groups=__lowerCamelCase ,activation=config.hidden_act ,name='''layer.1''' ), TFRegNetConvLayer(__lowerCamelCase ,kernel_size=1 ,activation=__lowerCamelCase ,name='''layer.2''' ), ] a = ACTaFN[config.hidden_act] def SCREAMING_SNAKE_CASE_ ( self : List[str] ,__lowerCamelCase : Union[str, Any] ): '''simple docstring''' a = hidden_state for layer_module in self.layers: a = layer_module(__lowerCamelCase ) a = self.shortcut(__lowerCamelCase ) hidden_state += residual a = self.activation(__lowerCamelCase ) return hidden_state class lowerCamelCase_ ( tf.keras.layers.Layer ): def __init__( self : Dict ,__lowerCamelCase : RegNetConfig ,__lowerCamelCase : int ,__lowerCamelCase : int ,__lowerCamelCase : int = 1 ,**__lowerCamelCase : List[str] ): '''simple docstring''' super().__init__(**__lowerCamelCase ) a = in_channels != out_channels or stride != 1 a = max(1 ,out_channels // config.groups_width ) a = ( TFRegNetShortCut(__lowerCamelCase ,stride=__lowerCamelCase ,name='''shortcut''' ) if should_apply_shortcut else tf.keras.layers.Activation('''linear''' ,name='''shortcut''' ) ) a = [ TFRegNetConvLayer(__lowerCamelCase ,kernel_size=1 ,activation=config.hidden_act ,name='''layer.0''' ), TFRegNetConvLayer( __lowerCamelCase ,stride=__lowerCamelCase ,groups=__lowerCamelCase ,activation=config.hidden_act ,name='''layer.1''' ), TFRegNetSELayer(__lowerCamelCase ,reduced_channels=int(round(in_channels / 4 ) ) ,name='''layer.2''' ), TFRegNetConvLayer(__lowerCamelCase ,kernel_size=1 ,activation=__lowerCamelCase ,name='''layer.3''' ), ] a = ACTaFN[config.hidden_act] def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ,__lowerCamelCase : str ): '''simple docstring''' a = hidden_state for layer_module in self.layers: a = layer_module(__lowerCamelCase ) a = self.shortcut(__lowerCamelCase ) hidden_state += residual a = self.activation(__lowerCamelCase ) return hidden_state class lowerCamelCase_ ( tf.keras.layers.Layer ): def __init__( self : Optional[int] ,__lowerCamelCase : RegNetConfig ,__lowerCamelCase : int ,__lowerCamelCase : int ,__lowerCamelCase : int = 2 ,__lowerCamelCase : int = 2 ,**__lowerCamelCase : Optional[Any] ): '''simple docstring''' super().__init__(**__lowerCamelCase ) a = TFRegNetXLayer if config.layer_type == '''x''' else TFRegNetYLayer a = [ # downsampling is done in the first layer with stride of 2 layer(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ,stride=__lowerCamelCase ,name='''layers.0''' ), *[layer(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ,name=F"""layers.{i+1}""" ) for i in range(depth - 1 )], ] def SCREAMING_SNAKE_CASE_ ( self : Tuple ,__lowerCamelCase : int ): '''simple docstring''' for layer_module in self.layers: a = layer_module(__lowerCamelCase ) return hidden_state class lowerCamelCase_ ( tf.keras.layers.Layer ): def __init__( self : Union[str, Any] ,__lowerCamelCase : RegNetConfig ,**__lowerCamelCase : Optional[Any] ): '''simple docstring''' super().__init__(**__lowerCamelCase ) a = [] # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( TFRegNetStage( __lowerCamelCase ,config.embedding_size ,config.hidden_sizes[0] ,stride=2 if config.downsample_in_first_stage else 1 ,depth=config.depths[0] ,name='''stages.0''' ,) ) a = zip(config.hidden_sizes ,config.hidden_sizes[1:] ) for i, ((in_channels, out_channels), depth) in enumerate(zip(__lowerCamelCase ,config.depths[1:] ) ): self.stages.append(TFRegNetStage(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ,depth=__lowerCamelCase ,name=F"""stages.{i+1}""" ) ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ,__lowerCamelCase : tf.Tensor ,__lowerCamelCase : bool = False ,__lowerCamelCase : bool = True ): '''simple docstring''' a = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: a = hidden_states + (hidden_state,) a = stage_module(__lowerCamelCase ) if output_hidden_states: a = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return TFBaseModelOutputWithNoAttention(last_hidden_state=__lowerCamelCase ,hidden_states=__lowerCamelCase ) @keras_serializable class lowerCamelCase_ ( tf.keras.layers.Layer ): SCREAMING_SNAKE_CASE_ = RegNetConfig def __init__( self : Dict ,__lowerCamelCase : Optional[int] ,**__lowerCamelCase : Optional[Any] ): '''simple docstring''' super().__init__(**__lowerCamelCase ) a = config a = TFRegNetEmbeddings(__lowerCamelCase ,name='''embedder''' ) a = TFRegNetEncoder(__lowerCamelCase ,name='''encoder''' ) a = tf.keras.layers.GlobalAveragePoolingaD(keepdims=__lowerCamelCase ,name='''pooler''' ) @unpack_inputs def SCREAMING_SNAKE_CASE_ ( self : Tuple ,__lowerCamelCase : tf.Tensor ,__lowerCamelCase : Optional[bool] = None ,__lowerCamelCase : Optional[bool] = None ,__lowerCamelCase : bool = False ,): '''simple docstring''' a = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) a = return_dict if return_dict is not None else self.config.use_return_dict a = self.embedder(__lowerCamelCase ,training=__lowerCamelCase ) a = self.encoder( __lowerCamelCase ,output_hidden_states=__lowerCamelCase ,return_dict=__lowerCamelCase ,training=__lowerCamelCase ) a = encoder_outputs[0] a = self.pooler(__lowerCamelCase ) # Change to NCHW output format have uniformity in the modules a = tf.transpose(__lowerCamelCase ,perm=(0, 3, 1, 2) ) a = tf.transpose(__lowerCamelCase ,perm=(0, 3, 1, 2) ) # Change the other hidden state outputs to NCHW as well if output_hidden_states: a = tuple([tf.transpose(__lowerCamelCase ,perm=(0, 3, 1, 2) ) for h in encoder_outputs[1]] ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=__lowerCamelCase ,pooler_output=__lowerCamelCase ,hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states ,) class lowerCamelCase_ ( a_ ): SCREAMING_SNAKE_CASE_ = RegNetConfig SCREAMING_SNAKE_CASE_ = 'regnet' SCREAMING_SNAKE_CASE_ = 'pixel_values' @property def SCREAMING_SNAKE_CASE_ ( self : str ): '''simple docstring''' return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 2_24, 2_24) ,dtype=tf.floataa )} UpperCamelCase__ : Union[str, Any] = R""" Parameters: This model is a Tensorflow [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and behavior. config ([`RegNetConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights. """ UpperCamelCase__ : List[str] = R""" Args: pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`ConveNextImageProcessor.__call__`] for details. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. """ @add_start_docstrings( 'The bare RegNet model outputting raw features without any specific head on top.' , a_ , ) class lowerCamelCase_ ( a_ ): def __init__( self : Optional[int] ,__lowerCamelCase : RegNetConfig ,*__lowerCamelCase : int ,**__lowerCamelCase : Union[str, Any] ): '''simple docstring''' super().__init__(__lowerCamelCase ,*__lowerCamelCase ,**__lowerCamelCase ) a = TFRegNetMainLayer(__lowerCamelCase ,name='''regnet''' ) @unpack_inputs @add_start_docstrings_to_model_forward(__lowerCamelCase ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC ,output_type=__lowerCamelCase ,config_class=_CONFIG_FOR_DOC ,modality='''vision''' ,expected_output=_EXPECTED_OUTPUT_SHAPE ,) def SCREAMING_SNAKE_CASE_ ( self : Any ,__lowerCamelCase : tf.Tensor ,__lowerCamelCase : Optional[bool] = None ,__lowerCamelCase : Optional[bool] = None ,__lowerCamelCase : List[str]=False ,): '''simple docstring''' a = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) a = return_dict if return_dict is not None else self.config.use_return_dict a = self.regnet( pixel_values=__lowerCamelCase ,output_hidden_states=__lowerCamelCase ,return_dict=__lowerCamelCase ,training=__lowerCamelCase ,) if not return_dict: return (outputs[0],) + outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=outputs.last_hidden_state ,pooler_output=outputs.pooler_output ,hidden_states=outputs.hidden_states ,) @add_start_docstrings( '\n RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n ' , a_ , ) class lowerCamelCase_ ( a_ , a_ ): def __init__( self : Optional[int] ,__lowerCamelCase : RegNetConfig ,*__lowerCamelCase : str ,**__lowerCamelCase : Any ): '''simple docstring''' super().__init__(__lowerCamelCase ,*__lowerCamelCase ,**__lowerCamelCase ) a = config.num_labels a = TFRegNetMainLayer(__lowerCamelCase ,name='''regnet''' ) # classification head a = [ tf.keras.layers.Flatten(), tf.keras.layers.Dense(config.num_labels ,name='''classifier.1''' ) if config.num_labels > 0 else tf.identity, ] @unpack_inputs @add_start_docstrings_to_model_forward(__lowerCamelCase ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT ,output_type=__lowerCamelCase ,config_class=_CONFIG_FOR_DOC ,expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT ,) def SCREAMING_SNAKE_CASE_ ( self : Tuple ,__lowerCamelCase : tf.Tensor = None ,__lowerCamelCase : tf.Tensor = None ,__lowerCamelCase : bool = None ,__lowerCamelCase : bool = None ,__lowerCamelCase : Dict=False ,): '''simple docstring''' a = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) a = return_dict if return_dict is not None else self.config.use_return_dict a = self.regnet( __lowerCamelCase ,output_hidden_states=__lowerCamelCase ,return_dict=__lowerCamelCase ,training=__lowerCamelCase ) a = outputs.pooler_output if return_dict else outputs[1] a = self.classifier[0](__lowerCamelCase ) a = self.classifier[1](__lowerCamelCase ) a = None if labels is None else self.hf_compute_loss(labels=__lowerCamelCase ,logits=__lowerCamelCase ) if not return_dict: a = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return TFSequenceClassifierOutput(loss=__lowerCamelCase ,logits=__lowerCamelCase ,hidden_states=outputs.hidden_states )
330
1
# 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, )
330
from typing import List from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase__ : Union[str, Any] = logging.get_logger(__name__) UpperCamelCase__ : List[str] = { """snap-research/efficientformer-l1-300""": ( """https://huggingface.co/snap-research/efficientformer-l1-300/resolve/main/config.json""" ), } class lowerCamelCase_ ( a_ ): SCREAMING_SNAKE_CASE_ = 'efficientformer' def __init__( self : Optional[int] ,__lowerCamelCase : List[int] = [3, 2, 6, 4] ,__lowerCamelCase : List[int] = [48, 96, 2_24, 4_48] ,__lowerCamelCase : List[bool] = [True, True, True, True] ,__lowerCamelCase : int = 4_48 ,__lowerCamelCase : int = 32 ,__lowerCamelCase : int = 4 ,__lowerCamelCase : int = 7 ,__lowerCamelCase : int = 5 ,__lowerCamelCase : int = 8 ,__lowerCamelCase : int = 4 ,__lowerCamelCase : float = 0.0 ,__lowerCamelCase : int = 16 ,__lowerCamelCase : int = 3 ,__lowerCamelCase : int = 3 ,__lowerCamelCase : int = 3 ,__lowerCamelCase : int = 2 ,__lowerCamelCase : int = 1 ,__lowerCamelCase : float = 0.0 ,__lowerCamelCase : int = 1 ,__lowerCamelCase : bool = True ,__lowerCamelCase : bool = True ,__lowerCamelCase : float = 1e-5 ,__lowerCamelCase : str = "gelu" ,__lowerCamelCase : float = 0.02 ,__lowerCamelCase : float = 1e-12 ,__lowerCamelCase : int = 2_24 ,__lowerCamelCase : float = 1e-05 ,**__lowerCamelCase : Dict ,): '''simple docstring''' super().__init__(**__lowerCamelCase ) a = hidden_act a = hidden_dropout_prob a = hidden_sizes a = num_hidden_layers a = num_attention_heads a = initializer_range a = layer_norm_eps a = patch_size a = num_channels a = depths a = mlp_expansion_ratio a = downsamples a = dim a = key_dim a = attention_ratio a = resolution a = pool_size a = downsample_patch_size a = downsample_stride a = downsample_pad a = drop_path_rate a = num_metaad_blocks a = distillation a = use_layer_scale a = layer_scale_init_value a = image_size a = batch_norm_eps
330
1
import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionTextToImagePipeline from diffusers.utils.testing_utils import nightly, require_torch_gpu, torch_device UpperCamelCase__ : Any = False class lowerCamelCase_ ( unittest.TestCase ): pass @nightly @require_torch_gpu class lowerCamelCase_ ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self : Any ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE_ ( self : Tuple ): '''simple docstring''' a = VersatileDiffusionTextToImagePipeline.from_pretrained('''shi-labs/versatile-diffusion''' ) # remove text_unet pipe.remove_unused_weights() pipe.to(__lowerCamelCase ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) a = '''A painting of a squirrel eating a burger ''' a = torch.manual_seed(0 ) a = pipe( prompt=__lowerCamelCase ,generator=__lowerCamelCase ,guidance_scale=7.5 ,num_inference_steps=2 ,output_type='''numpy''' ).images with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(__lowerCamelCase ) a = VersatileDiffusionTextToImagePipeline.from_pretrained(__lowerCamelCase ) pipe.to(__lowerCamelCase ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) a = generator.manual_seed(0 ) a = pipe( prompt=__lowerCamelCase ,generator=__lowerCamelCase ,guidance_scale=7.5 ,num_inference_steps=2 ,output_type='''numpy''' ).images assert np.abs(image - new_image ).sum() < 1e-5, "Models don't have the same forward pass" def SCREAMING_SNAKE_CASE_ ( self : Any ): '''simple docstring''' a = VersatileDiffusionTextToImagePipeline.from_pretrained( '''shi-labs/versatile-diffusion''' ,torch_dtype=torch.floataa ) pipe.to(__lowerCamelCase ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) a = '''A painting of a squirrel eating a burger ''' a = torch.manual_seed(0 ) a = pipe( prompt=__lowerCamelCase ,generator=__lowerCamelCase ,guidance_scale=7.5 ,num_inference_steps=50 ,output_type='''numpy''' ).images a = image[0, 2_53:2_56, 2_53:2_56, -1] assert image.shape == (1, 5_12, 5_12, 3) a = np.array([0.3_367, 0.3_169, 0.2_656, 0.3_870, 0.4_790, 0.3_796, 0.4_009, 0.4_878, 0.4_778] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
330
import argparse from typing import Dict import tensorflow as tf import torch from tqdm import tqdm from transformers import BigBirdPegasusConfig, BigBirdPegasusForConditionalGeneration UpperCamelCase__ : Any = [ # tf -> hf ("""/""", """."""), ("""layer_""", """layers."""), ("""kernel""", """weight"""), ("""beta""", """bias"""), ("""gamma""", """weight"""), ("""pegasus""", """model"""), ] UpperCamelCase__ : Optional[Any] = [ (""".output.dense""", """.fc2"""), ("""intermediate.LayerNorm""", """final_layer_norm"""), ("""intermediate.dense""", """fc1"""), ] UpperCamelCase__ : Optional[Any] = ( INIT_COMMON + [ ("""attention.self.LayerNorm""", """self_attn_layer_norm"""), ("""attention.output.dense""", """self_attn.out_proj"""), ("""attention.self""", """self_attn"""), ("""attention.encdec.LayerNorm""", """encoder_attn_layer_norm"""), ("""attention.encdec_output.dense""", """encoder_attn.out_proj"""), ("""attention.encdec""", """encoder_attn"""), ("""key""", """k_proj"""), ("""value""", """v_proj"""), ("""query""", """q_proj"""), ("""decoder.LayerNorm""", """decoder.layernorm_embedding"""), ] + END_COMMON ) UpperCamelCase__ : List[str] = ( INIT_COMMON + [ ("""embeddings.word_embeddings""", """shared.weight"""), ("""embeddings.position_embeddings""", """embed_positions.weight"""), ("""attention.self.LayerNorm""", """self_attn_layer_norm"""), ("""attention.output.dense""", """self_attn.output"""), ("""attention.self""", """self_attn.self"""), ("""encoder.LayerNorm""", """encoder.layernorm_embedding"""), ] + END_COMMON ) UpperCamelCase__ : Optional[int] = [ """encdec/key/bias""", """encdec/query/bias""", """encdec/value/bias""", """self/key/bias""", """self/query/bias""", """self/value/bias""", """encdec_output/dense/bias""", """attention/output/dense/bias""", ] def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> List[Any]: """simple docstring""" for tf_name, hf_name in patterns: a = k.replace(snake_case_, snake_case_ ) return k def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> BigBirdPegasusForConditionalGeneration: """simple docstring""" a = BigBirdPegasusConfig(**snake_case_ ) a = BigBirdPegasusForConditionalGeneration(snake_case_ ) a = torch_model.state_dict() a = {} # separating decoder weights a = {k: tf_weights[k] for k in tf_weights if k.startswith('''pegasus/decoder''' )} a = {k: tf_weights[k] for k in tf_weights if not k.startswith('''pegasus/decoder''' )} for k, v in tqdm(decoder_weights.items(), '''tf -> hf conversion''' ): a = [k.endswith(snake_case_ ) for ending in KEYS_TO_IGNORE] if any(snake_case_ ): continue a = DECODER_PATTERNS a = rename_state_dict_key(snake_case_, snake_case_ ) if new_k not in state_dict: raise ValueError(f"""could not find new key {new_k} in state dict. (converted from {k})""" ) if any(True if i in k else False for i in ['''dense''', '''query''', '''key''', '''value'''] ): a = v.T a = torch.from_numpy(snake_case_ ) assert v.shape == state_dict[new_k].shape, f"""{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}""" for k, v in tqdm(remaining_weights.items(), '''tf -> hf conversion''' ): a = [k.endswith(snake_case_ ) for ending in KEYS_TO_IGNORE] if any(snake_case_ ): continue a = REMAINING_PATTERNS a = rename_state_dict_key(snake_case_, snake_case_ ) if new_k not in state_dict and k != "pegasus/embeddings/position_embeddings": raise ValueError(f"""could not find new key {new_k} in state dict. (converted from {k})""" ) if any(True if i in k else False for i in ['''dense''', '''query''', '''key''', '''value'''] ): a = v.T a = torch.from_numpy(snake_case_ ) if k != "pegasus/embeddings/position_embeddings": assert v.shape == state_dict[new_k].shape, f"""{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}""" a = mapping['''model.embed_positions.weight'''] a = mapping.pop('''model.embed_positions.weight''' ) a , a = torch_model.load_state_dict(snake_case_, strict=snake_case_ ) a = [ k for k in missing if k not in [ '''final_logits_bias''', '''model.encoder.embed_tokens.weight''', '''model.decoder.embed_tokens.weight''', '''lm_head.weight''', ] ] assert unexpected_missing == [], f"""no matches found for the following torch keys {unexpected_missing}""" assert extra == [], f"""no matches found for the following tf keys {extra}""" return torch_model def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> Dict: """simple docstring""" a = tf.train.list_variables(snake_case_ ) a = {} a = ['''global_step'''] for name, shape in tqdm(snake_case_, desc='''converting tf checkpoint to dict''' ): a = any(pat in name for pat in ignore_name ) if skip_key: continue a = tf.train.load_variable(snake_case_, snake_case_ ) a = array return tf_weights def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_ ) -> int: """simple docstring""" a = get_tf_weights_as_numpy(snake_case_ ) a = convert_bigbird_pegasus(snake_case_, snake_case_ ) torch_model.save_pretrained(snake_case_ ) if __name__ == "__main__": UpperCamelCase__ : str = argparse.ArgumentParser() parser.add_argument("""--tf_ckpt_path""", type=str, help="""passed to tf.train.list_variables""") parser.add_argument("""--save_dir""", default=None, type=str, help="""Path to the output PyTorch model.""") UpperCamelCase__ : int = parser.parse_args() UpperCamelCase__ : Tuple = {} convert_bigbird_pegasus_ckpt_to_pytorch(args.tf_ckpt_path, args.save_dir, config_update=config_update)
330
1
UpperCamelCase__ : str = { """A""": ["""B""", """C""", """E"""], """B""": ["""A""", """D""", """E"""], """C""": ["""A""", """F""", """G"""], """D""": ["""B"""], """E""": ["""A""", """B""", """D"""], """F""": ["""C"""], """G""": ["""C"""], } def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_ ) -> list[str]: """simple docstring""" a = set() # keep track of all the paths to be checked a = [[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 a = queue.pop(0 ) # get the last node from the path a = path[-1] if node not in explored: a = graph[node] # go through all neighbour nodes, construct a new path and # push it into the queue for neighbour in neighbours: a = list(snake_case_ ) new_path.append(snake_case_ ) queue.append(snake_case_ ) # return path if neighbour is goal if neighbour == goal: return new_path # mark node as explored explored.add(snake_case_ ) # in case there's no path between the 2 nodes return [] def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_ ) -> int: """simple docstring""" if not graph or start not in graph or target not in graph: return -1 if start == target: return 0 a = [start] a = set(snake_case_ ) # Keep tab on distances from `start` node. a = {start: 0, target: -1} while queue: a = queue.pop(0 ) if node == target: a = ( dist[node] if dist[target] == -1 else min(dist[target], dist[node] ) ) for adjacent in graph[node]: if adjacent not in visited: visited.add(snake_case_ ) queue.append(snake_case_ ) a = 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
330
import re def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> str: """simple docstring""" if len(re.findall('''[ATCG]''', snake_case_ ) ) != len(snake_case_ ): raise ValueError('''Invalid Strand''' ) return dna.translate(dna.maketrans('''ATCG''', '''TAGC''' ) ) if __name__ == "__main__": import doctest doctest.testmod()
330
1
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase__ : List[Any] = logging.get_logger(__name__) UpperCamelCase__ : int = { """microsoft/swinv2-tiny-patch4-window8-256""": ( """https://huggingface.co/microsoft/swinv2-tiny-patch4-window8-256/resolve/main/config.json""" ), } class lowerCamelCase_ ( a_ ): SCREAMING_SNAKE_CASE_ = 'swinv2' SCREAMING_SNAKE_CASE_ = { 'num_attention_heads': 'num_heads', 'num_hidden_layers': 'num_layers', } def __init__( self : Any ,__lowerCamelCase : Union[str, Any]=2_24 ,__lowerCamelCase : Any=4 ,__lowerCamelCase : int=3 ,__lowerCamelCase : List[Any]=96 ,__lowerCamelCase : str=[2, 2, 6, 2] ,__lowerCamelCase : Any=[3, 6, 12, 24] ,__lowerCamelCase : Dict=7 ,__lowerCamelCase : Optional[Any]=4.0 ,__lowerCamelCase : Any=True ,__lowerCamelCase : Optional[Any]=0.0 ,__lowerCamelCase : Dict=0.0 ,__lowerCamelCase : Optional[Any]=0.1 ,__lowerCamelCase : Dict="gelu" ,__lowerCamelCase : List[Any]=False ,__lowerCamelCase : Dict=0.02 ,__lowerCamelCase : List[str]=1e-5 ,__lowerCamelCase : Any=32 ,**__lowerCamelCase : List[Any] ,): '''simple docstring''' super().__init__(**__lowerCamelCase ) a = image_size a = patch_size a = num_channels a = embed_dim a = depths a = len(__lowerCamelCase ) a = num_heads a = window_size a = mlp_ratio a = qkv_bias a = hidden_dropout_prob a = attention_probs_dropout_prob a = drop_path_rate a = hidden_act a = use_absolute_embeddings a = layer_norm_eps a = initializer_range a = encoder_stride # we set the hidden_size attribute in order to make Swinv2 work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model a = int(embed_dim * 2 ** (len(__lowerCamelCase ) - 1) ) a = (0, 0, 0, 0)
330
from __future__ import annotations from collections.abc import Sequence from typing import Literal def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> str | Literal[False]: """simple docstring""" a = list(snake_case_ ) a = list(snake_case_ ) a = 0 for i in range(len(snake_case_ ) ): if lista[i] != lista[i]: count += 1 a = '''_''' if count > 1: return False else: return "".join(snake_case_ ) def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> list[str]: """simple docstring""" a = [] while True: a = ['''$'''] * len(snake_case_ ) a = [] for i in range(len(snake_case_ ) ): for j in range(i + 1, len(snake_case_ ) ): a = compare_string(binary[i], binary[j] ) if k is False: a = '''*''' a = '''*''' temp.append('''X''' ) for i in range(len(snake_case_ ) ): if checka[i] == "$": pi.append(binary[i] ) if len(snake_case_ ) == 0: return pi a = list(set(snake_case_ ) ) def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> list[str]: """simple docstring""" a = [] for minterm in minterms: a = '''''' for _ in range(snake_case_ ): a = str(minterm % 2 ) + string minterm //= 2 temp.append(snake_case_ ) return temp def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_ ) -> bool: """simple docstring""" a = list(snake_case_ ) a = list(snake_case_ ) a = 0 for i in range(len(snake_case_ ) ): if lista[i] != lista[i]: count_n += 1 return count_n == count def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> list[str]: """simple docstring""" a = [] a = [0] * len(snake_case_ ) for i in range(len(chart[0] ) ): a = 0 a = -1 for j in range(len(snake_case_ ) ): if chart[j][i] == 1: count += 1 a = j if count == 1: a = 1 for i in range(len(snake_case_ ) ): if select[i] == 1: for j in range(len(chart[0] ) ): if chart[i][j] == 1: for k in range(len(snake_case_ ) ): a = 0 temp.append(prime_implicants[i] ) while True: a = 0 a = -1 a = 0 for i in range(len(snake_case_ ) ): a = chart[i].count(1 ) if count_n > max_n: a = count_n a = i if max_n == 0: return temp temp.append(prime_implicants[rem] ) for i in range(len(chart[0] ) ): if chart[rem][i] == 1: for j in range(len(snake_case_ ) ): a = 0 def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> list[list[int]]: """simple docstring""" a = [[0 for x in range(len(snake_case_ ) )] for x in range(len(snake_case_ ) )] for i in range(len(snake_case_ ) ): a = prime_implicants[i].count('''_''' ) for j in range(len(snake_case_ ) ): if is_for_table(prime_implicants[i], binary[j], snake_case_ ): a = 1 return chart def SCREAMING_SNAKE_CASE__ ( ) -> None: """simple docstring""" a = int(input('''Enter the no. of variables\n''' ) ) a = [ float(snake_case_ ) for x in input( '''Enter the decimal representation of Minterms \'Spaces Separated\'\n''' ).split() ] a = decimal_to_binary(snake_case_, snake_case_ ) a = check(snake_case_ ) print('''Prime Implicants are:''' ) print(snake_case_ ) a = prime_implicant_chart(snake_case_, snake_case_ ) a = selection(snake_case_, snake_case_ ) print('''Essential Prime Implicants are:''' ) print(snake_case_ ) if __name__ == "__main__": import doctest doctest.testmod() main()
330
1
# Lint as: python3 import dataclasses import re from dataclasses import dataclass from functools import total_ordering from typing import Optional, Union UpperCamelCase__ : Optional[Any] = re.compile(R"""^(?P<major>\d+)""" R"""\.(?P<minor>\d+)""" R"""\.(?P<patch>\d+)$""") @total_ordering @dataclass class lowerCamelCase_ : SCREAMING_SNAKE_CASE_ = 42 SCREAMING_SNAKE_CASE_ = None SCREAMING_SNAKE_CASE_ = None SCREAMING_SNAKE_CASE_ = None SCREAMING_SNAKE_CASE_ = None def SCREAMING_SNAKE_CASE_ ( self : List[str] ): '''simple docstring''' a , a , a = _str_to_version_tuple(self.version_str ) def __repr__( self : Any ): '''simple docstring''' return F"""{self.tuple[0]}.{self.tuple[1]}.{self.tuple[2]}""" @property def SCREAMING_SNAKE_CASE_ ( self : List[str] ): '''simple docstring''' return self.major, self.minor, self.patch def SCREAMING_SNAKE_CASE_ ( self : List[Any] ,__lowerCamelCase : Union[str, Any] ): '''simple docstring''' if isinstance(__lowerCamelCase ,__lowerCamelCase ): return Version(__lowerCamelCase ) elif isinstance(__lowerCamelCase ,__lowerCamelCase ): return other raise TypeError(F"""{other} (type {type(__lowerCamelCase )}) cannot be compared to version.""" ) def __eq__( self : Union[str, Any] ,__lowerCamelCase : int ): '''simple docstring''' try: a = self._validate_operand(__lowerCamelCase ) except (TypeError, ValueError): return False else: return self.tuple == other.tuple def __lt__( self : Optional[Any] ,__lowerCamelCase : List[Any] ): '''simple docstring''' a = self._validate_operand(__lowerCamelCase ) return self.tuple < other.tuple def __hash__( self : str ): '''simple docstring''' return hash(_version_tuple_to_str(self.tuple ) ) @classmethod def SCREAMING_SNAKE_CASE_ ( cls : List[Any] ,__lowerCamelCase : Union[str, Any] ): '''simple docstring''' a = {f.name for f in dataclasses.fields(cls )} return cls(**{k: v for k, v in dic.items() if k in field_names} ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ): '''simple docstring''' return self.version_str def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> Union[str, Any]: """simple docstring""" a = _VERSION_REG.match(snake_case_ ) if not res: raise ValueError(f"""Invalid version '{version_str}'. Format should be x.y.z with {{x,y,z}} being digits.""" ) return tuple(int(snake_case_ ) for v in [res.group('''major''' ), res.group('''minor''' ), res.group('''patch''' )] ) def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> int: """simple docstring""" return ".".join(str(snake_case_ ) for v in version_tuple )
330
from typing import List, Union import numpy as np from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_DEPTH_ESTIMATION_MAPPING UpperCamelCase__ : List[str] = logging.get_logger(__name__) @add_end_docstrings(a_ ) class lowerCamelCase_ ( a_ ): def __init__( self : int ,*__lowerCamelCase : str ,**__lowerCamelCase : Optional[Any] ): '''simple docstring''' super().__init__(*__lowerCamelCase ,**__lowerCamelCase ) requires_backends(self ,'''vision''' ) self.check_model_type(__lowerCamelCase ) def __call__( self : int ,__lowerCamelCase : Union[str, List[str], "Image.Image", List["Image.Image"]] ,**__lowerCamelCase : str ): '''simple docstring''' return super().__call__(__lowerCamelCase ,**__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : Any ,**__lowerCamelCase : Dict ): '''simple docstring''' return {}, {}, {} def SCREAMING_SNAKE_CASE_ ( self : int ,__lowerCamelCase : Union[str, Any] ): '''simple docstring''' a = load_image(__lowerCamelCase ) a = image.size a = self.image_processor(images=__lowerCamelCase ,return_tensors=self.framework ) return model_inputs def SCREAMING_SNAKE_CASE_ ( self : str ,__lowerCamelCase : Union[str, Any] ): '''simple docstring''' a = self.model(**__lowerCamelCase ) return model_outputs def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ,__lowerCamelCase : Union[str, Any] ): '''simple docstring''' a = model_outputs.predicted_depth a = torch.nn.functional.interpolate( predicted_depth.unsqueeze(1 ) ,size=self.image_size[::-1] ,mode='''bicubic''' ,align_corners=__lowerCamelCase ) a = prediction.squeeze().cpu().numpy() a = (output * 2_55 / np.max(__lowerCamelCase )).astype('''uint8''' ) a = Image.fromarray(__lowerCamelCase ) a = {} a = predicted_depth a = depth return output_dict
330
1
def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_ ) -> float: """simple docstring""" if principal <= 0: raise Exception('''Principal borrowed must be > 0''' ) if rate_per_annum < 0: raise Exception('''Rate of interest must be >= 0''' ) if years_to_repay <= 0 or not isinstance(snake_case_, snake_case_ ): raise Exception('''Years to repay must be an integer > 0''' ) # Yearly rate is divided by 12 to get monthly rate a = rate_per_annum / 1_2 # Years to repay is multiplied by 12 to get number of payments as payment is monthly a = years_to_repay * 1_2 return ( principal * rate_per_month * (1 + rate_per_month) ** number_of_payments / ((1 + rate_per_month) ** number_of_payments - 1) ) if __name__ == "__main__": import doctest doctest.testmod()
330
from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Features, Value from .base import TaskTemplate @dataclass(frozen=a_ ) class lowerCamelCase_ ( a_ ): SCREAMING_SNAKE_CASE_ = field(default='language-modeling' , metadata={'include_in_asdict_even_if_is_default': True} ) SCREAMING_SNAKE_CASE_ = Features({'text': Value('string' )} ) SCREAMING_SNAKE_CASE_ = Features({} ) SCREAMING_SNAKE_CASE_ = "text" @property def SCREAMING_SNAKE_CASE_ ( self : int ): '''simple docstring''' return {self.text_column: "text"}
330
1
import dataclasses import json import warnings from dataclasses import dataclass, field from time import time from typing import List from ..utils import logging UpperCamelCase__ : List[Any] = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE__ ( snake_case_=None, snake_case_=None ) -> Union[str, Any]: """simple docstring""" return field(default_factory=lambda: default, metadata=snake_case_ ) @dataclass class lowerCamelCase_ : SCREAMING_SNAKE_CASE_ = list_field( default=[] , metadata={ 'help': ( 'Model checkpoints to be provided to the AutoModel classes. Leave blank to benchmark the base version' ' of all available models' ) } , ) SCREAMING_SNAKE_CASE_ = list_field( default=[8] , metadata={'help': 'List of batch sizes for which memory and time performance will be evaluated'} ) SCREAMING_SNAKE_CASE_ = list_field( default=[8, 32, 1_28, 5_12] , metadata={'help': 'List of sequence lengths for which memory and time performance will be evaluated'} , ) SCREAMING_SNAKE_CASE_ = field( default=a_ , metadata={'help': 'Whether to benchmark inference of model. Inference can be disabled via --no-inference.'} , ) SCREAMING_SNAKE_CASE_ = field( default=a_ , metadata={'help': 'Whether to run on available cuda devices. Cuda can be disabled via --no-cuda.'} , ) SCREAMING_SNAKE_CASE_ = field( default=a_ , metadata={'help': 'Whether to run on available tpu devices. TPU can be disabled via --no-tpu.'} ) SCREAMING_SNAKE_CASE_ = field(default=a_ , metadata={'help': 'Use FP16 to accelerate inference.'} ) SCREAMING_SNAKE_CASE_ = field(default=a_ , metadata={'help': 'Benchmark training of model'} ) SCREAMING_SNAKE_CASE_ = field(default=a_ , metadata={'help': 'Verbose memory tracing'} ) SCREAMING_SNAKE_CASE_ = field( default=a_ , metadata={'help': 'Whether to perform speed measurements. Speed measurements can be disabled via --no-speed.'} , ) SCREAMING_SNAKE_CASE_ = field( default=a_ , metadata={ 'help': 'Whether to perform memory measurements. Memory measurements can be disabled via --no-memory' } , ) SCREAMING_SNAKE_CASE_ = field(default=a_ , metadata={'help': 'Trace memory line by line'} ) SCREAMING_SNAKE_CASE_ = field(default=a_ , metadata={'help': 'Save result to a CSV file'} ) SCREAMING_SNAKE_CASE_ = field(default=a_ , metadata={'help': 'Save all print statements in a log file'} ) SCREAMING_SNAKE_CASE_ = field(default=a_ , metadata={'help': 'Whether to print environment information'} ) SCREAMING_SNAKE_CASE_ = field( default=a_ , metadata={ 'help': ( 'Whether to use multiprocessing for memory and speed measurement. It is highly recommended to use' ' multiprocessing for accurate CPU and GPU memory measurements. This option should only be disabled' ' for debugging / testing and on TPU.' ) } , ) SCREAMING_SNAKE_CASE_ = field( default=f"inference_time_{round(time() )}.csv" , metadata={'help': 'CSV filename used if saving time results to csv.'} , ) SCREAMING_SNAKE_CASE_ = field( default=f"inference_memory_{round(time() )}.csv" , metadata={'help': 'CSV filename used if saving memory results to csv.'} , ) SCREAMING_SNAKE_CASE_ = field( default=f"train_time_{round(time() )}.csv" , metadata={'help': 'CSV filename used if saving time results to csv for training.'} , ) SCREAMING_SNAKE_CASE_ = field( default=f"train_memory_{round(time() )}.csv" , metadata={'help': 'CSV filename used if saving memory results to csv for training.'} , ) SCREAMING_SNAKE_CASE_ = field( default=f"env_info_{round(time() )}.csv" , metadata={'help': 'CSV filename used if saving environment information.'} , ) SCREAMING_SNAKE_CASE_ = field( default=f"log_{round(time() )}.csv" , metadata={'help': 'Log filename used if print statements are saved in log.'} , ) SCREAMING_SNAKE_CASE_ = field(default=3 , metadata={'help': 'Times an experiment will be run.'} ) SCREAMING_SNAKE_CASE_ = field( default=a_ , metadata={ 'help': ( 'Instead of loading the model as defined in `config.architectures` if exists, just load the pretrain' ' model weights.' ) } , ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ): '''simple docstring''' warnings.warn( F"""The class {self.__class__} is deprecated. Hugging Face Benchmarking utils""" ''' are deprecated in general and it is advised to use external Benchmarking libraries ''' ''' to benchmark Transformer models.''' ,__lowerCamelCase ,) def SCREAMING_SNAKE_CASE_ ( self : Any ): '''simple docstring''' return json.dumps(dataclasses.asdict(self ) ,indent=2 ) @property def SCREAMING_SNAKE_CASE_ ( self : str ): '''simple docstring''' if len(self.models ) <= 0: raise ValueError( '''Please make sure you provide at least one model name / model identifier, *e.g.* `--models''' ''' bert-base-cased` or `args.models = [\'bert-base-cased\'].''' ) return self.models @property def SCREAMING_SNAKE_CASE_ ( self : str ): '''simple docstring''' if not self.multi_process: return False elif self.is_tpu: logger.info('''Multiprocessing is currently not possible on TPU.''' ) return False else: return True
330
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCamelCase__ : Union[str, Any] = logging.get_logger(__name__) UpperCamelCase__ : Union[str, Any] = { """hustvl/yolos-small""": """https://huggingface.co/hustvl/yolos-small/resolve/main/config.json""", # See all YOLOS models at https://huggingface.co/models?filter=yolos } class lowerCamelCase_ ( a_ ): SCREAMING_SNAKE_CASE_ = 'yolos' def __init__( self : Union[str, Any] ,__lowerCamelCase : int=7_68 ,__lowerCamelCase : Dict=12 ,__lowerCamelCase : Union[str, Any]=12 ,__lowerCamelCase : List[Any]=30_72 ,__lowerCamelCase : int="gelu" ,__lowerCamelCase : int=0.0 ,__lowerCamelCase : str=0.0 ,__lowerCamelCase : Optional[Any]=0.02 ,__lowerCamelCase : int=1e-12 ,__lowerCamelCase : Any=[5_12, 8_64] ,__lowerCamelCase : Tuple=16 ,__lowerCamelCase : int=3 ,__lowerCamelCase : Tuple=True ,__lowerCamelCase : Optional[int]=1_00 ,__lowerCamelCase : List[Any]=True ,__lowerCamelCase : List[str]=False ,__lowerCamelCase : int=1 ,__lowerCamelCase : List[Any]=5 ,__lowerCamelCase : Optional[int]=2 ,__lowerCamelCase : int=5 ,__lowerCamelCase : str=2 ,__lowerCamelCase : Tuple=0.1 ,**__lowerCamelCase : List[Any] ,): '''simple docstring''' super().__init__(**__lowerCamelCase ) 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 a = num_detection_tokens a = use_mid_position_embeddings a = auxiliary_loss # Hungarian matcher a = class_cost a = bbox_cost a = giou_cost # Loss coefficients a = bbox_loss_coefficient a = giou_loss_coefficient a = eos_coefficient class lowerCamelCase_ ( a_ ): SCREAMING_SNAKE_CASE_ = version.parse('1.11' ) @property def SCREAMING_SNAKE_CASE_ ( self : str ): '''simple docstring''' return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) @property def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ): '''simple docstring''' return 1e-4 @property def SCREAMING_SNAKE_CASE_ ( self : str ): '''simple docstring''' return 12
330
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCamelCase__ : Union[str, Any] = { """configuration_lxmert""": ["""LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """LxmertConfig"""], """tokenization_lxmert""": ["""LxmertTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ : List[Any] = ["""LxmertTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ : List[str] = [ """LxmertEncoder""", """LxmertForPreTraining""", """LxmertForQuestionAnswering""", """LxmertModel""", """LxmertPreTrainedModel""", """LxmertVisualFeatureEncoder""", """LxmertXLayer""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ : Tuple = [ """TF_LXMERT_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFLxmertForPreTraining""", """TFLxmertMainLayer""", """TFLxmertModel""", """TFLxmertPreTrainedModel""", """TFLxmertVisualFeatureEncoder""", ] if TYPE_CHECKING: from .configuration_lxmert import LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, LxmertConfig from .tokenization_lxmert import LxmertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_lxmert_fast import LxmertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_lxmert import ( LxmertEncoder, LxmertForPreTraining, LxmertForQuestionAnswering, LxmertModel, LxmertPreTrainedModel, LxmertVisualFeatureEncoder, LxmertXLayer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_lxmert import ( TF_LXMERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFLxmertForPreTraining, TFLxmertMainLayer, TFLxmertModel, TFLxmertPreTrainedModel, TFLxmertVisualFeatureEncoder, ) else: import sys UpperCamelCase__ : Tuple = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
330
def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> int: """simple docstring""" a = '''''' for i in table: res += inp[i - 1] return res def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> int: """simple docstring""" return data[1:] + data[0] def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> List[str]: """simple docstring""" a = '''''' for i in range(len(snake_case_ ) ): if a[i] == b[i]: res += "0" else: res += "1" return res def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> Dict: """simple docstring""" a = int('''0b''' + data[0] + data[-1], 2 ) a = int('''0b''' + data[1:3], 2 ) return bin(s[row][col] )[2:] def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_, snake_case_, snake_case_ ) -> Optional[int]: """simple docstring""" a = message[:4] a = message[4:] a = apply_table(snake_case_, snake_case_ ) a = xor(snake_case_, snake_case_ ) a = apply_sbox(snake_case_, temp[:4] ) # noqa: E741 a = apply_sbox(snake_case_, temp[4:] ) a = '''0''' * (2 - len(snake_case_ )) + l # noqa: E741 a = '''0''' * (2 - len(snake_case_ )) + r a = apply_table(l + r, snake_case_ ) a = xor(snake_case_, snake_case_ ) return temp + right if __name__ == "__main__": UpperCamelCase__ : int = input("""Enter 10 bit key: """) UpperCamelCase__ : Union[str, Any] = input("""Enter 8 bit message: """) UpperCamelCase__ : Dict = [6, 3, 7, 4, 8, 5, 10, 9] UpperCamelCase__ : Union[str, Any] = [3, 5, 2, 7, 4, 10, 1, 9, 8, 6] UpperCamelCase__ : Optional[int] = [2, 4, 3, 1] UpperCamelCase__ : List[Any] = [2, 6, 3, 1, 4, 8, 5, 7] UpperCamelCase__ : str = [4, 1, 3, 5, 7, 2, 8, 6] UpperCamelCase__ : List[Any] = [4, 1, 2, 3, 2, 3, 4, 1] UpperCamelCase__ : int = [[1, 0, 3, 2], [3, 2, 1, 0], [0, 2, 1, 3], [3, 1, 3, 2]] UpperCamelCase__ : Dict = [[0, 1, 2, 3], [2, 0, 1, 3], [3, 0, 1, 0], [2, 1, 0, 3]] # key generation UpperCamelCase__ : Optional[Any] = apply_table(key, paa_table) UpperCamelCase__ : str = temp[:5] UpperCamelCase__ : List[Any] = temp[5:] UpperCamelCase__ : Dict = left_shift(left) UpperCamelCase__ : Any = left_shift(right) UpperCamelCase__ : Optional[Any] = apply_table(left + right, pa_table) UpperCamelCase__ : List[str] = left_shift(left) UpperCamelCase__ : int = left_shift(right) UpperCamelCase__ : List[str] = left_shift(left) UpperCamelCase__ : Dict = left_shift(right) UpperCamelCase__ : List[str] = apply_table(left + right, pa_table) # encryption UpperCamelCase__ : Tuple = apply_table(message, IP) UpperCamelCase__ : Optional[Any] = function(expansion, sa, sa, keya, temp) UpperCamelCase__ : Optional[int] = temp[4:] + temp[:4] UpperCamelCase__ : Any = function(expansion, sa, sa, keya, temp) UpperCamelCase__ : Tuple = apply_table(temp, IP_inv) print("""Cipher text is:""", CT) # decryption UpperCamelCase__ : Union[str, Any] = apply_table(CT, IP) UpperCamelCase__ : List[str] = function(expansion, sa, sa, keya, temp) UpperCamelCase__ : Optional[Any] = temp[4:] + temp[:4] UpperCamelCase__ : Optional[int] = function(expansion, sa, sa, keya, temp) UpperCamelCase__ : Any = apply_table(temp, IP_inv) print("""Plain text after decypting is:""", PT)
330
1
import argparse import collections import numpy as np import torch from flax import traverse_util from tax import checkpoints from transformers import MTaConfig, UMTaEncoderModel, UMTaForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_ ) -> Union[str, Any]: """simple docstring""" return params[f"""{prefix}/{prefix}/relpos_bias/rel_embedding"""][:, i, :] def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_, snake_case_="attention" ) -> str: """simple docstring""" a = a = np.ascontiguousarray(params[f"""{prefix}/{prefix}/{layer_name}/key/kernel"""][:, i, :, :] ) a = k_tmp.reshape(k_tmp.shape[0], k_tmp.shape[1] * k_tmp.shape[2] ) a = np.ascontiguousarray(params[f"""{prefix}/{prefix}/{layer_name}/out/kernel"""][:, i, :, :] ) a = o_tmp.reshape(o_tmp.shape[0] * o_tmp.shape[1], o_tmp.shape[2] ) a = np.ascontiguousarray(params[f"""{prefix}/{prefix}/{layer_name}/query/kernel"""][:, i, :, :] ) a = q_tmp.reshape(q_tmp.shape[0], q_tmp.shape[1] * q_tmp.shape[2] ) a = np.ascontiguousarray(params[f"""{prefix}/{prefix}/{layer_name}/value/kernel"""][:, i, :, :] ) a = v_tmp.reshape(v_tmp.shape[0], v_tmp.shape[1] * v_tmp.shape[2] ) return k, o, q, v def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_, snake_case_=False ) -> Union[str, Any]: """simple docstring""" if split_mlp_wi: a = params[f"""{prefix}/{prefix}/mlp/wi_0/kernel"""][:, i, :] a = params[f"""{prefix}/{prefix}/mlp/wi_1/kernel"""][:, i, :] a = (wi_a, wi_a) else: a = params[f"""{prefix}/{prefix}/mlp/wi/kernel"""][:, i, :] a = params[f"""{prefix}/{prefix}/mlp/wo/kernel"""][:, i, :] return wi, wo def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_, snake_case_ ) -> Tuple: """simple docstring""" return params[f"""{prefix}/{prefix}/{layer_name}/scale"""][:, i] def SCREAMING_SNAKE_CASE__ ( snake_case_, *, snake_case_, snake_case_, snake_case_ = False ) -> Optional[Any]: """simple docstring""" a = traverse_util.flatten_dict(variables['''target'''] ) a = {'''/'''.join(snake_case_ ): v for k, v in old.items()} # v1.1 models have a gated GeLU with wi_0 and wi_1 instead of wi a = '''encoder/encoder/mlp/wi_0/kernel''' in old print('''Split MLP:''', snake_case_ ) a = collections.OrderedDict() # Shared embeddings. a = old['''token_embedder/embedding'''] # Encoder. for i in range(snake_case_ ): # Block i, layer 0 (Self Attention). a = tax_layer_norm_lookup(snake_case_, snake_case_, '''encoder''', '''pre_attention_layer_norm''' ) a , a , a , a = tax_attention_lookup(snake_case_, snake_case_, '''encoder''', '''attention''' ) a = layer_norm a = k.T a = o.T a = q.T a = v.T # Block i, layer 1 (MLP). a = tax_layer_norm_lookup(snake_case_, snake_case_, '''encoder''', '''pre_mlp_layer_norm''' ) a , a = tax_mlp_lookup(snake_case_, snake_case_, '''encoder''', snake_case_ ) a = layer_norm if split_mlp_wi: a = wi[0].T a = wi[1].T else: a = wi.T a = wo.T if scalable_attention: # convert the rel_embedding of each layer a = tax_relpos_bias_lookup( snake_case_, snake_case_, '''encoder''' ).T a = old['''encoder/encoder_norm/scale'''] if not scalable_attention: a = tax_relpos_bias_lookup( snake_case_, 0, '''encoder''' ).T a = tax_relpos_bias_lookup( snake_case_, 0, '''decoder''' ).T if not is_encoder_only: # Decoder. for i in range(snake_case_ ): # Block i, layer 0 (Self Attention). a = tax_layer_norm_lookup(snake_case_, snake_case_, '''decoder''', '''pre_self_attention_layer_norm''' ) a , a , a , a = tax_attention_lookup(snake_case_, snake_case_, '''decoder''', '''self_attention''' ) a = layer_norm a = k.T a = o.T a = q.T a = v.T # Block i, layer 1 (Cross Attention). a = tax_layer_norm_lookup(snake_case_, snake_case_, '''decoder''', '''pre_cross_attention_layer_norm''' ) a , a , a , a = tax_attention_lookup(snake_case_, snake_case_, '''decoder''', '''encoder_decoder_attention''' ) a = layer_norm a = k.T a = o.T a = q.T a = v.T # Block i, layer 2 (MLP). a = tax_layer_norm_lookup(snake_case_, snake_case_, '''decoder''', '''pre_mlp_layer_norm''' ) a , a = tax_mlp_lookup(snake_case_, snake_case_, '''decoder''', snake_case_ ) a = layer_norm if split_mlp_wi: a = wi[0].T a = wi[1].T else: a = wi.T a = wo.T if scalable_attention: # convert the rel_embedding of each layer a = tax_relpos_bias_lookup(snake_case_, snake_case_, '''decoder''' ).T a = old['''decoder/decoder_norm/scale'''] # LM Head (only in v1.1 checkpoints, in v1.0 embeddings are used instead) if "decoder/logits_dense/kernel" in old: a = old['''decoder/logits_dense/kernel'''].T return new def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> Tuple: """simple docstring""" a = collections.OrderedDict([(k, torch.from_numpy(v.copy() )) for (k, v) in converted_params.items()] ) # Add what is missing. if "encoder.embed_tokens.weight" not in state_dict: a = state_dict['''shared.weight'''] if not is_encoder_only: if "decoder.embed_tokens.weight" not in state_dict: a = state_dict['''shared.weight'''] if "lm_head.weight" not in state_dict: # For old 1.0 models. print('''Using shared word embeddings as lm_head.''' ) a = state_dict['''shared.weight'''] return state_dict def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_, snake_case_, snake_case_ ) -> List[str]: """simple docstring""" a = checkpoints.load_tax_checkpoint(snake_case_ ) a = convert_tax_to_pytorch( snake_case_, num_layers=config.num_layers, is_encoder_only=snake_case_, scalable_attention=snake_case_ ) a = make_state_dict(snake_case_, snake_case_ ) model.load_state_dict(snake_case_, strict=snake_case_ ) def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_, snake_case_ = False, snake_case_ = False, ) -> List[str]: """simple docstring""" a = MTaConfig.from_json_file(snake_case_ ) print(f"""Building PyTorch model from configuration: {config}""" ) # Non-v1.1 checkpoints could also use T5Model, but this works for all. # The v1.0 checkpoints will simply have an LM head that is the word embeddings. if is_encoder_only: a = UMTaEncoderModel(snake_case_ ) else: a = UMTaForConditionalGeneration(snake_case_ ) # Load weights from tf checkpoint load_tax_weights_in_ta(snake_case_, snake_case_, snake_case_, snake_case_, snake_case_ ) # Save pytorch-model print(f"""Save PyTorch model to {pytorch_dump_path}""" ) model.save_pretrained(snake_case_ ) # Verify that we can load the checkpoint. model.from_pretrained(snake_case_ ) print('''Done''' ) if __name__ == "__main__": UpperCamelCase__ : Union[str, Any] = argparse.ArgumentParser(description="""Converts a native T5X checkpoint into a PyTorch checkpoint.""") # Required parameters parser.add_argument( """--t5x_checkpoint_path""", default=None, type=str, required=True, help="""Path to the T5X checkpoint.""" ) parser.add_argument( """--config_file""", default=None, type=str, required=True, help="""The config json file corresponding to the pre-trained T5 model.\nThis specifies the model architecture.""", ) parser.add_argument( """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) parser.add_argument( """--is_encoder_only""", action="""store_true""", help="""Check if the model is encoder-decoder model""", default=False ) parser.add_argument( """--scalable_attention""", action="""store_true""", help="""Whether the model uses scaled attention (umt5 model)""", default=False, ) UpperCamelCase__ : Optional[int] = parser.parse_args() convert_tax_checkpoint_to_pytorch( args.tax_checkpoint_path, args.config_file, args.pytorch_dump_path, args.is_encoder_only, args.scalable_attention, )
330
import unittest from transformers import AutoTokenizer, is_flax_available from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, slow if is_flax_available(): import jax.numpy as jnp from transformers import FlaxXLMRobertaModel @require_sentencepiece @require_tokenizers @require_flax class lowerCamelCase_ ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE_ ( self : Tuple ): '''simple docstring''' a = FlaxXLMRobertaModel.from_pretrained('''xlm-roberta-base''' ) a = AutoTokenizer.from_pretrained('''xlm-roberta-base''' ) a = '''The dog is cute and lives in the garden house''' a = jnp.array([tokenizer.encode(__lowerCamelCase )] ) a = (1, 12, 7_68) # batch_size, sequence_length, embedding_vector_dim a = jnp.array( [[-0.0_101, 0.1_218, -0.0_803, 0.0_801, 0.1_327, 0.0_776, -0.1_215, 0.2_383, 0.3_338, 0.3_106, 0.0_300, 0.0_252]] ) a = model(__lowerCamelCase )['''last_hidden_state'''] self.assertEqual(output.shape ,__lowerCamelCase ) # compare the actual values for a slice of last dim self.assertTrue(jnp.allclose(output[:, :, -1] ,__lowerCamelCase ,atol=1e-3 ) )
330
1
import os import time import pytest from datasets.utils.filelock import FileLock, Timeout def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> Tuple: """simple docstring""" a = FileLock(str(tmpdir / '''foo.lock''' ) ) a = FileLock(str(tmpdir / '''foo.lock''' ) ) a = 0.01 with locka.acquire(): with pytest.raises(snake_case_ ): a = time.time() locka.acquire(snake_case_ ) assert time.time() - _start > timeout def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> Optional[int]: """simple docstring""" a = '''a''' * 1_0_0_0 + '''.lock''' a = FileLock(str(tmpdir / filename ) ) assert locka._lock_file.endswith('''.lock''' ) assert not locka._lock_file.endswith(snake_case_ ) assert len(os.path.basename(locka._lock_file ) ) <= 2_5_5 a = FileLock(tmpdir / filename ) with locka.acquire(): with pytest.raises(snake_case_ ): locka.acquire(0 )
330
import argparse import os # New Code # import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils import find_executable_batch_size ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to ensure out-of-memory errors never # interrupt training, and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## UpperCamelCase__ : Union[str, Any] = 16 UpperCamelCase__ : Dict = 32 def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ = 1_6 ) -> Tuple: """simple docstring""" a = AutoTokenizer.from_pretrained('''bert-base-cased''' ) a = load_dataset('''glue''', '''mrpc''' ) def tokenize_function(snake_case_ ): # max_length=None => use the model max length (it's actually the default) a = tokenizer(examples['''sentence1'''], examples['''sentence2'''], truncation=snake_case_, max_length=snake_case_ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): a = datasets.map( snake_case_, batched=snake_case_, remove_columns=['''idx''', '''sentence1''', '''sentence2'''], ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library a = tokenized_datasets.rename_column('''label''', '''labels''' ) def collate_fn(snake_case_ ): # On TPU it's best to pad everything to the same length or training will be very slow. a = 1_2_8 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": a = 1_6 elif accelerator.mixed_precision != "no": a = 8 else: a = None return tokenizer.pad( snake_case_, padding='''longest''', max_length=snake_case_, pad_to_multiple_of=snake_case_, return_tensors='''pt''', ) # Instantiate dataloaders. a = DataLoader( tokenized_datasets['''train'''], shuffle=snake_case_, collate_fn=snake_case_, batch_size=snake_case_ ) a = DataLoader( tokenized_datasets['''validation'''], shuffle=snake_case_, collate_fn=snake_case_, batch_size=snake_case_ ) return train_dataloader, eval_dataloader # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""", None) == "1": from accelerate.test_utils.training import mocked_dataloaders UpperCamelCase__ : int = mocked_dataloaders # noqa: F811 def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> List[Any]: """simple docstring""" if os.environ.get('''TESTING_MOCKED_DATALOADERS''', snake_case_ ) == "1": a = 2 # Initialize accelerator a = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs a = config['''lr'''] a = int(config['''num_epochs'''] ) a = int(config['''seed'''] ) a = int(config['''batch_size'''] ) a = evaluate.load('''glue''', '''mrpc''' ) # New Code # # We now can define an inner training loop function. It should take a batch size as the only parameter, # and build the dataloaders in there. # It also gets our decorator @find_executable_batch_size(starting_batch_size=snake_case_ ) def inner_training_loop(snake_case_ ): # And now just move everything below under this function # We need to bring in the Accelerator object from earlier nonlocal accelerator # And reset all of its attributes that could hold onto any memory: accelerator.free_memory() # Then we can declare the model, optimizer, and everything else: set_seed(snake_case_ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) a = AutoModelForSequenceClassification.from_pretrained('''bert-base-cased''', return_dict=snake_case_ ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). a = model.to(accelerator.device ) # Instantiate optimizer a = AdamW(params=model.parameters(), lr=snake_case_ ) a , a = get_dataloaders(snake_case_, snake_case_ ) # Instantiate scheduler a = get_linear_schedule_with_warmup( optimizer=snake_case_, num_warmup_steps=1_0_0, num_training_steps=(len(snake_case_ ) * num_epochs), ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. a , a , a , a , a = accelerator.prepare( snake_case_, snake_case_, snake_case_, snake_case_, snake_case_ ) # Now we train the model for epoch in range(snake_case_ ): model.train() for step, batch in enumerate(snake_case_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) a = model(**snake_case_ ) a = outputs.loss accelerator.backward(snake_case_ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(snake_case_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): a = model(**snake_case_ ) a = outputs.logits.argmax(dim=-1 ) a , a = accelerator.gather_for_metrics((predictions, batch['''labels''']) ) metric.add_batch( predictions=snake_case_, references=snake_case_, ) a = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f"""epoch {epoch}:""", snake_case_ ) # New Code # # And call it at the end with no arguments # Note: You could also refactor this outside of your training loop function inner_training_loop() def SCREAMING_SNAKE_CASE__ ( ) -> Tuple: """simple docstring""" a = argparse.ArgumentParser(description='''Simple example of training script.''' ) parser.add_argument( '''--mixed_precision''', type=snake_case_, default=snake_case_, choices=['''no''', '''fp16''', '''bf16''', '''fp8'''], help='''Whether to use mixed precision. Choose''' '''between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.''' '''and an Nvidia Ampere GPU.''', ) parser.add_argument('''--cpu''', action='''store_true''', help='''If passed, will train on the CPU.''' ) a = parser.parse_args() a = {'''lr''': 2e-5, '''num_epochs''': 3, '''seed''': 4_2, '''batch_size''': 1_6} training_function(snake_case_, snake_case_ ) if __name__ == "__main__": main()
330
1
from string import ascii_lowercase, ascii_uppercase def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> str: """simple docstring""" if not sentence: return "" a = dict(zip(snake_case_, snake_case_ ) ) return lower_to_upper.get(sentence[0], sentence[0] ) + sentence[1:] if __name__ == "__main__": from doctest import testmod testmod()
330
import argparse import fairseq import torch from transformers import UniSpeechSatConfig, UniSpeechSatForCTC, UniSpeechSatForPreTraining, logging logging.set_verbosity_info() UpperCamelCase__ : Optional[int] = logging.get_logger(__name__) UpperCamelCase__ : str = { """post_extract_proj""": """feature_projection.projection""", """encoder.pos_conv.0""": """encoder.pos_conv_embed.conv""", """self_attn.k_proj""": """encoder.layers.*.attention.k_proj""", """self_attn.v_proj""": """encoder.layers.*.attention.v_proj""", """self_attn.q_proj""": """encoder.layers.*.attention.q_proj""", """self_attn.out_proj""": """encoder.layers.*.attention.out_proj""", """self_attn_layer_norm""": """encoder.layers.*.layer_norm""", """fc1""": """encoder.layers.*.feed_forward.intermediate_dense""", """fc2""": """encoder.layers.*.feed_forward.output_dense""", """final_layer_norm""": """encoder.layers.*.final_layer_norm""", """encoder.layer_norm""": """encoder.layer_norm""", """encoder.layer_norm_for_extract""": """layer_norm_for_extract""", """w2v_model.layer_norm""": """feature_projection.layer_norm""", """quantizer.weight_proj""": """quantizer.weight_proj""", """quantizer.vars""": """quantizer.codevectors""", """project_q""": """project_q""", """final_proj""": """project_hid""", """w2v_encoder.proj""": """lm_head""", """label_embs_concat""": """label_embeddings_concat""", """mask_emb""": """masked_spec_embed""", """spk_proj""": """speaker_proj""", } UpperCamelCase__ : Optional[Any] = [ """lm_head""", """quantizer.weight_proj""", """quantizer.codevectors""", """project_q""", """project_hid""", """label_embeddings_concat""", """speaker_proj""", """layer_norm_for_extract""", ] def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_, snake_case_, snake_case_ ) -> List[Any]: """simple docstring""" for attribute in key.split('''.''' ): a = getattr(snake_case_, snake_case_ ) if weight_type is not None: a = getattr(snake_case_, snake_case_ ).shape else: a = hf_pointer.shape if hf_shape != value.shape: raise ValueError( f"""Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be""" f""" {value.shape} for {full_name}""" ) if weight_type == "weight": a = value elif weight_type == "weight_g": a = value elif weight_type == "weight_v": a = value elif weight_type == "bias": a = value else: a = value logger.info(f"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" ) def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> Union[str, Any]: """simple docstring""" a = [] a = fairseq_model.state_dict() a = hf_model.unispeech_sat.feature_extractor for name, value in fairseq_dict.items(): a = False if "conv_layers" in name: load_conv_layer( snake_case_, snake_case_, snake_case_, snake_case_, hf_model.config.feat_extract_norm == '''group''', ) a = True else: for key, mapped_key in MAPPING.items(): a = '''unispeech_sat.''' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split('''w2v_model.''' )[-1] == name.split('''.''' )[0]: if "layer_norm_for_extract" in name and (".".join(name.split('''.''' )[:-1] ) != key): # special case since naming is very similar continue a = True if "*" in mapped_key: a = name.split(snake_case_ )[0].split('''.''' )[-2] a = mapped_key.replace('''*''', snake_case_ ) if "weight_g" in name: a = '''weight_g''' elif "weight_v" in name: a = '''weight_v''' elif "bias" in name: a = '''bias''' elif "weight" in name: # TODO: don't match quantizer.weight_proj a = '''weight''' else: a = None set_recursively(snake_case_, snake_case_, snake_case_, snake_case_, snake_case_ ) continue if not is_used: unused_weights.append(snake_case_ ) logger.warning(f"""Unused weights: {unused_weights}""" ) def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_, snake_case_, snake_case_ ) -> Union[str, Any]: """simple docstring""" a = full_name.split('''conv_layers.''' )[-1] a = name.split('''.''' ) a = int(items[0] ) a = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) a = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) a = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor[layer_id].layer_norm.bias.data.shape} was found.""" ) a = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.""" ) a = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(snake_case_ ) @torch.no_grad() def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_=None, snake_case_=None, snake_case_=True ) -> Union[str, Any]: """simple docstring""" if config_path is not None: a = UniSpeechSatConfig.from_pretrained(snake_case_ ) else: a = UniSpeechSatConfig() a = '''''' if is_finetuned: a = UniSpeechSatForCTC(snake_case_ ) else: a = UniSpeechSatForPreTraining(snake_case_ ) a , a , a = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path], arg_overrides={'''data''': '''/'''.join(dict_path.split('''/''' )[:-1] )} ) a = model[0].eval() recursively_load_weights(snake_case_, snake_case_ ) hf_wavavec.save_pretrained(snake_case_ ) if __name__ == "__main__": UpperCamelCase__ : Optional[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 fairseq checkpoint""") parser.add_argument("""--dict_path""", default=None, type=str, help="""Path to dict of fine-tuned model""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") parser.add_argument( """--not_finetuned""", action="""store_true""", help="""Whether the model to convert is a fine-tuned model or not""" ) UpperCamelCase__ : int = parser.parse_args() convert_unispeech_sat_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
330
1
from .glue import GlueDataset, GlueDataTrainingArguments from .language_modeling import ( LineByLineTextDataset, LineByLineWithRefDataset, LineByLineWithSOPTextDataset, TextDataset, TextDatasetForNextSentencePrediction, ) from .squad import SquadDataset, SquadDataTrainingArguments
330
import pytest from datasets import inspect_metric, list_metrics, load_metric @pytest.fixture def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> List[str]: """simple docstring""" monkeypatch.setattr('''datasets.utils.deprecation_utils._emitted_deprecation_warnings''', set() ) @pytest.fixture def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> Optional[int]: """simple docstring""" class lowerCamelCase_ : def __init__( self : Dict ,__lowerCamelCase : List[str] ): '''simple docstring''' a = metric_id class lowerCamelCase_ : SCREAMING_SNAKE_CASE_ = [MetricMock(a_ ) for metric_id in ['accuracy', 'mse', 'precision', 'codeparrot/apps_metric']] def SCREAMING_SNAKE_CASE_ ( self : Dict ): '''simple docstring''' return self._metrics monkeypatch.setattr('''datasets.inspect.huggingface_hub''', HfhMock() ) @pytest.mark.parametrize( '''func, args''', [(load_metric, ('''metrics/mse''',)), (list_metrics, ()), (inspect_metric, ('''metrics/mse''', '''tmp_path'''))] ) def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_, snake_case_, snake_case_ ) -> Tuple: """simple docstring""" if "tmp_path" in args: a = tuple(arg if arg != '''tmp_path''' else tmp_path for arg in args ) with pytest.warns(snake_case_, match='''https://huggingface.co/docs/evaluate''' ): func(*snake_case_ )
330
1
import numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler from tensorflow.keras.layers import LSTM, Dense from tensorflow.keras.models import Sequential if __name__ == "__main__": UpperCamelCase__ : Optional[int] = pd.read_csv("""sample_data.csv""", header=None) UpperCamelCase__ : Tuple = df.shape[:1][0] # If you're using some other dataset input the target column UpperCamelCase__ : List[Any] = df.iloc[:, 1:2] UpperCamelCase__ : Union[str, Any] = actual_data.values.reshape(len_data, 1) UpperCamelCase__ : List[Any] = MinMaxScaler().fit_transform(actual_data) UpperCamelCase__ : Optional[Any] = 10 UpperCamelCase__ : int = 5 UpperCamelCase__ : List[str] = 20 UpperCamelCase__ : Optional[int] = len_data - periods * look_back UpperCamelCase__ : Union[str, Any] = actual_data[:division] UpperCamelCase__ : str = actual_data[division - look_back :] UpperCamelCase__ , UpperCamelCase__ : Union[str, Any] = [], [] UpperCamelCase__ , UpperCamelCase__ : str = [], [] for i in range(0, len(train_data) - forward_days - look_back + 1): train_x.append(train_data[i : i + look_back]) train_y.append(train_data[i + look_back : i + look_back + forward_days]) for i in range(0, len(test_data) - forward_days - look_back + 1): test_x.append(test_data[i : i + look_back]) test_y.append(test_data[i + look_back : i + look_back + forward_days]) UpperCamelCase__ : List[str] = np.array(train_x) UpperCamelCase__ : Optional[Any] = np.array(test_x) UpperCamelCase__ : Tuple = np.array([list(i.ravel()) for i in train_y]) UpperCamelCase__ : Optional[Any] = np.array([list(i.ravel()) for i in test_y]) UpperCamelCase__ : Union[str, Any] = Sequential() model.add(LSTM(128, input_shape=(look_back, 1), return_sequences=True)) model.add(LSTM(64, input_shape=(128, 1))) model.add(Dense(forward_days)) model.compile(loss="""mean_squared_error""", optimizer="""adam""") UpperCamelCase__ : Tuple = model.fit( x_train, y_train, epochs=150, verbose=1, shuffle=True, batch_size=4 ) UpperCamelCase__ : Tuple = model.predict(x_test)
330
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase__ : str = logging.get_logger(__name__) UpperCamelCase__ : Optional[int] = { """studio-ousia/luke-base""": """https://huggingface.co/studio-ousia/luke-base/resolve/main/config.json""", """studio-ousia/luke-large""": """https://huggingface.co/studio-ousia/luke-large/resolve/main/config.json""", } class lowerCamelCase_ ( a_ ): SCREAMING_SNAKE_CASE_ = 'luke' def __init__( self : Dict ,__lowerCamelCase : Optional[Any]=5_02_67 ,__lowerCamelCase : str=50_00_00 ,__lowerCamelCase : Any=7_68 ,__lowerCamelCase : int=2_56 ,__lowerCamelCase : Optional[int]=12 ,__lowerCamelCase : Tuple=12 ,__lowerCamelCase : Any=30_72 ,__lowerCamelCase : Any="gelu" ,__lowerCamelCase : Any=0.1 ,__lowerCamelCase : Tuple=0.1 ,__lowerCamelCase : Tuple=5_12 ,__lowerCamelCase : int=2 ,__lowerCamelCase : Optional[int]=0.02 ,__lowerCamelCase : List[Any]=1e-12 ,__lowerCamelCase : Dict=True ,__lowerCamelCase : Tuple=None ,__lowerCamelCase : Any=1 ,__lowerCamelCase : Dict=0 ,__lowerCamelCase : Any=2 ,**__lowerCamelCase : str ,): '''simple docstring''' super().__init__(pad_token_id=__lowerCamelCase ,bos_token_id=__lowerCamelCase ,eos_token_id=__lowerCamelCase ,**__lowerCamelCase ) a = vocab_size a = entity_vocab_size a = hidden_size a = entity_emb_size a = num_hidden_layers a = num_attention_heads a = hidden_act a = intermediate_size a = hidden_dropout_prob a = attention_probs_dropout_prob a = max_position_embeddings a = type_vocab_size a = initializer_range a = layer_norm_eps a = use_entity_aware_attention a = classifier_dropout
330
1
import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, UNetaDConditionModel, VideoToVideoSDPipeline, ) from diffusers.utils import floats_tensor, is_xformers_available, skip_mps from diffusers.utils.testing_utils import enable_full_determinism, slow, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class lowerCamelCase_ ( a_ , unittest.TestCase ): SCREAMING_SNAKE_CASE_ = VideoToVideoSDPipeline SCREAMING_SNAKE_CASE_ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS.union({'video'} ) - {'image', 'width', 'height'} SCREAMING_SNAKE_CASE_ = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'video'} ) - {'image'} SCREAMING_SNAKE_CASE_ = PipelineTesterMixin.required_optional_params - {'latents'} SCREAMING_SNAKE_CASE_ = False # No `output_type`. SCREAMING_SNAKE_CASE_ = frozenset( [ 'num_inference_steps', 'generator', 'latents', 'return_dict', 'callback', 'callback_steps', ] ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ): '''simple docstring''' torch.manual_seed(0 ) a = UNetaDConditionModel( block_out_channels=(32, 64, 64, 64) ,layers_per_block=2 ,sample_size=32 ,in_channels=4 ,out_channels=4 ,down_block_types=('''CrossAttnDownBlock3D''', '''CrossAttnDownBlock3D''', '''CrossAttnDownBlock3D''', '''DownBlock3D''') ,up_block_types=('''UpBlock3D''', '''CrossAttnUpBlock3D''', '''CrossAttnUpBlock3D''', '''CrossAttnUpBlock3D''') ,cross_attention_dim=32 ,attention_head_dim=4 ,) a = DDIMScheduler( beta_start=0.00_085 ,beta_end=0.012 ,beta_schedule='''scaled_linear''' ,clip_sample=__lowerCamelCase ,set_alpha_to_one=__lowerCamelCase ,) torch.manual_seed(0 ) a = AutoencoderKL( block_out_channels=[32, 64] ,in_channels=3 ,out_channels=3 ,down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] ,up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] ,latent_channels=4 ,sample_size=1_28 ,) torch.manual_seed(0 ) a = 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 ,) a = CLIPTextModel(__lowerCamelCase ) a = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) a = { '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, } return components def SCREAMING_SNAKE_CASE_ ( self : int ,__lowerCamelCase : Optional[Any] ,__lowerCamelCase : List[str]=0 ): '''simple docstring''' a = floats_tensor((1, 3, 3, 32, 32) ,rng=random.Random(__lowerCamelCase ) ).to(__lowerCamelCase ) if str(__lowerCamelCase ).startswith('''mps''' ): a = torch.manual_seed(__lowerCamelCase ) else: a = torch.Generator(device=__lowerCamelCase ).manual_seed(__lowerCamelCase ) a = { '''prompt''': '''A painting of a squirrel eating a burger''', '''video''': video, '''generator''': generator, '''num_inference_steps''': 2, '''guidance_scale''': 6.0, '''output_type''': '''pt''', } return inputs def SCREAMING_SNAKE_CASE_ ( self : List[Any] ): '''simple docstring''' a = '''cpu''' # ensure determinism for the device-dependent torch.Generator a = self.get_dummy_components() a = VideoToVideoSDPipeline(**__lowerCamelCase ) a = sd_pipe.to(__lowerCamelCase ) sd_pipe.set_progress_bar_config(disable=__lowerCamelCase ) a = self.get_dummy_inputs(__lowerCamelCase ) a = '''np''' a = sd_pipe(**__lowerCamelCase ).frames a = frames[0][-3:, -3:, -1] assert frames[0].shape == (32, 32, 3) a = np.array([1_06, 1_17, 1_13, 1_74, 1_37, 1_12, 1_48, 1_51, 1_31] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @unittest.skipIf( torch_device != '''cuda''' or not is_xformers_available() ,reason='''XFormers attention is only available with CUDA and `xformers` installed''' ,) def SCREAMING_SNAKE_CASE_ ( self : Dict ): '''simple docstring''' self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=__lowerCamelCase ,expected_max_diff=5e-3 ) @unittest.skip(reason='''Batching needs to be properly figured out first for this pipeline.''' ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ): '''simple docstring''' pass @unittest.skip(reason='''Batching needs to be properly figured out first for this pipeline.''' ) def SCREAMING_SNAKE_CASE_ ( self : int ): '''simple docstring''' pass @unittest.skip(reason='''`num_images_per_prompt` argument is not supported for this pipeline.''' ) def SCREAMING_SNAKE_CASE_ ( self : str ): '''simple docstring''' pass def SCREAMING_SNAKE_CASE_ ( self : Tuple ): '''simple docstring''' return super().test_progress_bar() @slow @skip_mps class lowerCamelCase_ ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ): '''simple docstring''' a = VideoToVideoSDPipeline.from_pretrained('''cerspense/zeroscope_v2_XL''' ,torch_dtype=torch.floataa ) pipe.enable_model_cpu_offload() # 10 frames a = torch.Generator(device='''cpu''' ).manual_seed(0 ) a = torch.randn((1, 10, 3, 10_24, 5_76) ,generator=__lowerCamelCase ) a = video.to('''cuda''' ) a = '''Spiderman is surfing''' a = pipe(__lowerCamelCase ,video=__lowerCamelCase ,generator=__lowerCamelCase ,num_inference_steps=3 ,output_type='''pt''' ).frames a = np.array([-1.0_458_984, -1.1_279_297, -0.9_663_086, -0.91_503_906, -0.75_097_656] ) assert np.abs(video_frames.cpu().numpy()[0, 0, 0, 0, -5:] - expected_array ).sum() < 1e-2
330
import numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler from tensorflow.keras.layers import LSTM, Dense from tensorflow.keras.models import Sequential if __name__ == "__main__": UpperCamelCase__ : Optional[int] = pd.read_csv("""sample_data.csv""", header=None) UpperCamelCase__ : Tuple = df.shape[:1][0] # If you're using some other dataset input the target column UpperCamelCase__ : List[Any] = df.iloc[:, 1:2] UpperCamelCase__ : Union[str, Any] = actual_data.values.reshape(len_data, 1) UpperCamelCase__ : List[Any] = MinMaxScaler().fit_transform(actual_data) UpperCamelCase__ : Optional[Any] = 10 UpperCamelCase__ : int = 5 UpperCamelCase__ : List[str] = 20 UpperCamelCase__ : Optional[int] = len_data - periods * look_back UpperCamelCase__ : Union[str, Any] = actual_data[:division] UpperCamelCase__ : str = actual_data[division - look_back :] UpperCamelCase__ , UpperCamelCase__ : Union[str, Any] = [], [] UpperCamelCase__ , UpperCamelCase__ : str = [], [] for i in range(0, len(train_data) - forward_days - look_back + 1): train_x.append(train_data[i : i + look_back]) train_y.append(train_data[i + look_back : i + look_back + forward_days]) for i in range(0, len(test_data) - forward_days - look_back + 1): test_x.append(test_data[i : i + look_back]) test_y.append(test_data[i + look_back : i + look_back + forward_days]) UpperCamelCase__ : List[str] = np.array(train_x) UpperCamelCase__ : Optional[Any] = np.array(test_x) UpperCamelCase__ : Tuple = np.array([list(i.ravel()) for i in train_y]) UpperCamelCase__ : Optional[Any] = np.array([list(i.ravel()) for i in test_y]) UpperCamelCase__ : Union[str, Any] = Sequential() model.add(LSTM(128, input_shape=(look_back, 1), return_sequences=True)) model.add(LSTM(64, input_shape=(128, 1))) model.add(Dense(forward_days)) model.compile(loss="""mean_squared_error""", optimizer="""adam""") UpperCamelCase__ : Tuple = model.fit( x_train, y_train, epochs=150, verbose=1, shuffle=True, batch_size=4 ) UpperCamelCase__ : Tuple = model.predict(x_test)
330
1
from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_pool as _descriptor_pool from google.protobuf import symbol_database as _symbol_database from google.protobuf.internal import builder as _builder # @@protoc_insertion_point(imports) UpperCamelCase__ : int = _symbol_database.Default() UpperCamelCase__ : Any = _descriptor_pool.Default().AddSerializedFile( b"""\n\x19sentencepiece_model.proto\x12\rsentencepiece\"\x80\x0c\n\x0bTrainerSpec\x12\r\n\x05input\x18\x01 \x03(\t\x12\x14\n\x0cinput_format\x18\x07 \x01(\t\x12\x14\n\x0cmodel_prefix\x18\x02 \x01(\t\x12\x41\n\nmodel_type\x18\x03 \x01(\x0e\x32$.sentencepiece.TrainerSpec.ModelType:\x07UNIGRAM\x12\x18\n\nvocab_size\x18\x04 \x01(\x05:\x04\x38\x30\x30\x30\x12\x17\n\x0f\x61\x63\x63\x65pt_language\x18\x05 \x03(\t\x12 \n\x15self_test_sample_size\x18\x06 \x01(\x05:\x01\x30\x12*\n\x1b\x65nable_differential_privacy\x18\x32 \x01(\x08:\x05\x66\x61lse\x12+\n differential_privacy_noise_level\x18\x33 \x01(\x02:\x01\x30\x12\x32\n\'differential_privacy_clipping_threshold\x18\x34 \x01(\x04:\x01\x30\x12\"\n\x12\x63haracter_coverage\x18\n \x01(\x02:\x06\x30.9995\x12\x1e\n\x13input_sentence_size\x18\x0b \x01(\x04:\x01\x30\x12$\n\x16shuffle_input_sentence\x18\x13 \x01(\x08:\x04true\x12 \n\x14mining_sentence_size\x18\x0c \x01(\x05\x42\x02\x18\x01\x12\"\n\x16training_sentence_size\x18\r \x01(\x05\x42\x02\x18\x01\x12(\n\x17seed_sentencepiece_size\x18\x0e \x01(\x05:\x07\x31\x30\x30\x30\x30\x30\x30\x12\x1e\n\x10shrinking_factor\x18\x0f \x01(\x02:\x04\x30.75\x12!\n\x13max_sentence_length\x18\x12 \x01(\x05:\x04\x34\x31\x39\x32\x12\x17\n\x0bnum_threads\x18\x10 \x01(\x05:\x02\x31\x36\x12\x1d\n\x12num_sub_iterations\x18\x11 \x01(\x05:\x01\x32\x12$\n\x18max_sentencepiece_length\x18\x14 \x01(\x05:\x02\x31\x36\x12%\n\x17split_by_unicode_script\x18\x15 \x01(\x08:\x04true\x12\x1d\n\x0fsplit_by_number\x18\x17 \x01(\x08:\x04true\x12!\n\x13split_by_whitespace\x18\x16 \x01(\x08:\x04true\x12)\n\x1atreat_whitespace_as_suffix\x18\x18 \x01(\x08:\x05\x66\x61lse\x12+\n\x1c\x61llow_whitespace_only_pieces\x18\x1a \x01(\x08:\x05\x66\x61lse\x12\x1b\n\x0csplit_digits\x18\x19 \x01(\x08:\x05\x66\x61lse\x12#\n\x19pretokenization_delimiter\x18\x35 \x01(\t:\x00\x12\x17\n\x0f\x63ontrol_symbols\x18\x1e \x03(\t\x12\x1c\n\x14user_defined_symbols\x18\x1f \x03(\t\x12\x16\n\x0erequired_chars\x18$ \x01(\t\x12\x1c\n\rbyte_fallback\x18# \x01(\x08:\x05\x66\x61lse\x12+\n\x1dvocabulary_output_piece_score\x18 \x01(\x08:\x04true\x12\x1e\n\x10hard_vocab_limit\x18! \x01(\x08:\x04true\x12\x1c\n\ruse_all_vocab\x18\" \x01(\x08:\x05\x66\x61lse\x12\x11\n\x06unk_id\x18( \x01(\x05:\x01\x30\x12\x11\n\x06\x62os_id\x18) \x01(\x05:\x01\x31\x12\x11\n\x06\x65os_id\x18* \x01(\x05:\x01\x32\x12\x12\n\x06pad_id\x18+ \x01(\x05:\x02-1\x12\x18\n\tunk_piece\x18- \x01(\t:\x05<unk>\x12\x16\n\tbos_piece\x18. \x01(\t:\x03<s>\x12\x17\n\teos_piece\x18/ \x01(\t:\x04</s>\x12\x18\n\tpad_piece\x18\x30 \x01(\t:\x05<pad>\x12\x1a\n\x0bunk_surface\x18, \x01(\t:\x05 \xe2\x81\x87 \x12+\n\x1ctrain_extremely_large_corpus\x18\x31 \x01(\x08:\x05\x66\x61lse\"5\n\tModelType\x12\x0b\n\x07UNIGRAM\x10\x01\x12\x07\n\x03\x42PE\x10\x02\x12\x08\n\x04WORD\x10\x03\x12\x08\n\x04\x43HAR\x10\x04*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\"\xd1\x01\n\x0eNormalizerSpec\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x1c\n\x14precompiled_charsmap\x18\x02 \x01(\x0c\x12\x1e\n\x10\x61\x64\x64_dummy_prefix\x18\x03 \x01(\x08:\x04true\x12&\n\x18remove_extra_whitespaces\x18\x04 \x01(\x08:\x04true\x12 \n\x12\x65scape_whitespaces\x18\x05 \x01(\x08:\x04true\x12\x1e\n\x16normalization_rule_tsv\x18\x06 \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\"y\n\x0cSelfTestData\x12\x33\n\x07samples\x18\x01 \x03(\x0b\x32\".sentencepiece.SelfTestData.Sample\x1a)\n\x06Sample\x12\r\n\x05input\x18\x01 \x01(\t\x12\x10\n\x08\x65xpected\x18\x02 \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\"\xfe\x03\n\nModelProto\x12\x37\n\x06pieces\x18\x01 \x03(\x0b\x32\'.sentencepiece.ModelProto.SentencePiece\x12\x30\n\x0ctrainer_spec\x18\x02 \x01(\x0b\x32\x1a.sentencepiece.TrainerSpec\x12\x36\n\x0fnormalizer_spec\x18\x03 \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x12\x33\n\x0eself_test_data\x18\x04 \x01(\x0b\x32\x1b.sentencepiece.SelfTestData\x12\x38\n\x11\x64\x65normalizer_spec\x18\x05 \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x1a\xd2\x01\n\rSentencePiece\x12\r\n\x05piece\x18\x01 \x01(\t\x12\r\n\x05score\x18\x02 \x01(\x02\x12\x42\n\x04type\x18\x03 \x01(\x0e\x32,.sentencepiece.ModelProto.SentencePiece.Type:\x06NORMAL\"T\n\x04Type\x12\n\n\x06NORMAL\x10\x01\x12\x0b\n\x07UNKNOWN\x10\x02\x12\x0b\n\x07\x43ONTROL\x10\x03\x12\x10\n\x0cUSER_DEFINED\x10\x04\x12\x08\n\x04\x42YTE\x10\x06\x12\n\n\x06UNUSED\x10\x05*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\x42\x02H\x03""" ) UpperCamelCase__ : List[Any] = globals() _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, """sentencepiece_model_pb2""", _globals) if _descriptor._USE_C_DESCRIPTORS is False: UpperCamelCase__ : Tuple = None UpperCamelCase__ : Optional[Any] = b"""H\003""" # (generated by protobuf compiler, but `_TRAINERSPEC` is not defined) # _TRAINERSPEC.fields_by_name["mining_sentence_size"]._options = None # _TRAINERSPEC.fields_by_name["mining_sentence_size"]._serialized_options = b"\030\001" # _TRAINERSPEC.fields_by_name["training_sentence_size"]._options = None # _TRAINERSPEC.fields_by_name["training_sentence_size"]._serialized_options = b"\030\001" UpperCamelCase__ : Dict = 45 UpperCamelCase__ : Dict = 1_581 UpperCamelCase__ : Optional[Any] = 1_517 UpperCamelCase__ : Any = 1_570 UpperCamelCase__ : Any = 1_584 UpperCamelCase__ : List[Any] = 1_793 UpperCamelCase__ : Tuple = 1_795 UpperCamelCase__ : int = 1_916 UpperCamelCase__ : List[str] = 1_864 UpperCamelCase__ : Tuple = 1_905 UpperCamelCase__ : List[str] = 1_919 UpperCamelCase__ : List[str] = 2_429 UpperCamelCase__ : List[Any] = 2_208 UpperCamelCase__ : str = 2_418 UpperCamelCase__ : Union[str, Any] = 2_323 UpperCamelCase__ : Optional[int] = 2_407 # @@protoc_insertion_point(module_scope)
330
import os import time import pytest from datasets.utils.filelock import FileLock, Timeout def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> Tuple: """simple docstring""" a = FileLock(str(tmpdir / '''foo.lock''' ) ) a = FileLock(str(tmpdir / '''foo.lock''' ) ) a = 0.01 with locka.acquire(): with pytest.raises(snake_case_ ): a = time.time() locka.acquire(snake_case_ ) assert time.time() - _start > timeout def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> Optional[int]: """simple docstring""" a = '''a''' * 1_0_0_0 + '''.lock''' a = FileLock(str(tmpdir / filename ) ) assert locka._lock_file.endswith('''.lock''' ) assert not locka._lock_file.endswith(snake_case_ ) assert len(os.path.basename(locka._lock_file ) ) <= 2_5_5 a = FileLock(tmpdir / filename ) with locka.acquire(): with pytest.raises(snake_case_ ): locka.acquire(0 )
330
1
from typing import Optional, Tuple, Union import tensorflow as tf from ...activations_tf import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_tf_outputs import ( TFBaseModelOutputWithNoAttention, TFBaseModelOutputWithPoolingAndNoAttention, TFSequenceClassifierOutput, ) from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs from ...tf_utils import shape_list from ...utils import logging from .configuration_regnet import RegNetConfig UpperCamelCase__ : List[Any] = logging.get_logger(__name__) # General docstring UpperCamelCase__ : List[Any] = """RegNetConfig""" # Base docstring UpperCamelCase__ : Dict = """facebook/regnet-y-040""" UpperCamelCase__ : int = [1, 1_088, 7, 7] # Image classification docstring UpperCamelCase__ : Optional[Any] = """facebook/regnet-y-040""" UpperCamelCase__ : Dict = """tabby, tabby cat""" UpperCamelCase__ : Dict = [ """facebook/regnet-y-040""", # See all regnet models at https://huggingface.co/models?filter=regnet ] class lowerCamelCase_ ( tf.keras.layers.Layer ): def __init__( self : List[str] ,__lowerCamelCase : int ,__lowerCamelCase : int = 3 ,__lowerCamelCase : int = 1 ,__lowerCamelCase : int = 1 ,__lowerCamelCase : Optional[str] = "relu" ,**__lowerCamelCase : str ,): '''simple docstring''' super().__init__(**__lowerCamelCase ) # The padding and conv has been verified in # https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb a = tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2 ) a = tf.keras.layers.ConvaD( filters=__lowerCamelCase ,kernel_size=__lowerCamelCase ,strides=__lowerCamelCase ,padding='''VALID''' ,groups=__lowerCamelCase ,use_bias=__lowerCamelCase ,name='''convolution''' ,) a = tf.keras.layers.BatchNormalization(epsilon=1e-5 ,momentum=0.9 ,name='''normalization''' ) a = ACTaFN[activation] if activation is not None else tf.identity def SCREAMING_SNAKE_CASE_ ( self : str ,__lowerCamelCase : List[str] ): '''simple docstring''' a = self.convolution(self.padding(__lowerCamelCase ) ) a = self.normalization(__lowerCamelCase ) a = self.activation(__lowerCamelCase ) return hidden_state class lowerCamelCase_ ( tf.keras.layers.Layer ): def __init__( self : Any ,__lowerCamelCase : RegNetConfig ,**__lowerCamelCase : List[Any] ): '''simple docstring''' super().__init__(**__lowerCamelCase ) a = config.num_channels a = TFRegNetConvLayer( out_channels=config.embedding_size ,kernel_size=3 ,stride=2 ,activation=config.hidden_act ,name='''embedder''' ,) def SCREAMING_SNAKE_CASE_ ( self : Any ,__lowerCamelCase : Optional[Any] ): '''simple docstring''' a = shape_list(__lowerCamelCase )[1] if tf.executing_eagerly() and num_channels != self.num_channels: raise ValueError( '''Make sure that the channel dimension of the pixel values match with the one set in the configuration.''' ) # When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format. # So change the input format from `NCHW` to `NHWC`. # shape = (batch_size, in_height, in_width, in_channels=num_channels) a = tf.transpose(__lowerCamelCase ,perm=(0, 2, 3, 1) ) a = self.embedder(__lowerCamelCase ) return hidden_state class lowerCamelCase_ ( tf.keras.layers.Layer ): def __init__( self : str ,__lowerCamelCase : int ,__lowerCamelCase : int = 2 ,**__lowerCamelCase : Tuple ): '''simple docstring''' super().__init__(**__lowerCamelCase ) a = tf.keras.layers.ConvaD( filters=__lowerCamelCase ,kernel_size=1 ,strides=__lowerCamelCase ,use_bias=__lowerCamelCase ,name='''convolution''' ) a = tf.keras.layers.BatchNormalization(epsilon=1e-5 ,momentum=0.9 ,name='''normalization''' ) def SCREAMING_SNAKE_CASE_ ( self : Dict ,__lowerCamelCase : tf.Tensor ,__lowerCamelCase : bool = False ): '''simple docstring''' return self.normalization(self.convolution(__lowerCamelCase ) ,training=__lowerCamelCase ) class lowerCamelCase_ ( tf.keras.layers.Layer ): def __init__( self : List[Any] ,__lowerCamelCase : int ,__lowerCamelCase : int ,**__lowerCamelCase : str ): '''simple docstring''' super().__init__(**__lowerCamelCase ) a = tf.keras.layers.GlobalAveragePoolingaD(keepdims=__lowerCamelCase ,name='''pooler''' ) a = [ tf.keras.layers.ConvaD(filters=__lowerCamelCase ,kernel_size=1 ,activation='''relu''' ,name='''attention.0''' ), tf.keras.layers.ConvaD(filters=__lowerCamelCase ,kernel_size=1 ,activation='''sigmoid''' ,name='''attention.2''' ), ] def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ,__lowerCamelCase : Optional[Any] ): '''simple docstring''' a = self.pooler(__lowerCamelCase ) for layer_module in self.attention: a = layer_module(__lowerCamelCase ) a = hidden_state * pooled return hidden_state class lowerCamelCase_ ( tf.keras.layers.Layer ): def __init__( self : Union[str, Any] ,__lowerCamelCase : RegNetConfig ,__lowerCamelCase : int ,__lowerCamelCase : int ,__lowerCamelCase : int = 1 ,**__lowerCamelCase : Dict ): '''simple docstring''' super().__init__(**__lowerCamelCase ) a = in_channels != out_channels or stride != 1 a = max(1 ,out_channels // config.groups_width ) a = ( TFRegNetShortCut(__lowerCamelCase ,stride=__lowerCamelCase ,name='''shortcut''' ) if should_apply_shortcut else tf.keras.layers.Activation('''linear''' ,name='''shortcut''' ) ) # `self.layers` instead of `self.layer` because that is a reserved argument. a = [ TFRegNetConvLayer(__lowerCamelCase ,kernel_size=1 ,activation=config.hidden_act ,name='''layer.0''' ), TFRegNetConvLayer( __lowerCamelCase ,stride=__lowerCamelCase ,groups=__lowerCamelCase ,activation=config.hidden_act ,name='''layer.1''' ), TFRegNetConvLayer(__lowerCamelCase ,kernel_size=1 ,activation=__lowerCamelCase ,name='''layer.2''' ), ] a = ACTaFN[config.hidden_act] def SCREAMING_SNAKE_CASE_ ( self : List[str] ,__lowerCamelCase : Union[str, Any] ): '''simple docstring''' a = hidden_state for layer_module in self.layers: a = layer_module(__lowerCamelCase ) a = self.shortcut(__lowerCamelCase ) hidden_state += residual a = self.activation(__lowerCamelCase ) return hidden_state class lowerCamelCase_ ( tf.keras.layers.Layer ): def __init__( self : Dict ,__lowerCamelCase : RegNetConfig ,__lowerCamelCase : int ,__lowerCamelCase : int ,__lowerCamelCase : int = 1 ,**__lowerCamelCase : List[str] ): '''simple docstring''' super().__init__(**__lowerCamelCase ) a = in_channels != out_channels or stride != 1 a = max(1 ,out_channels // config.groups_width ) a = ( TFRegNetShortCut(__lowerCamelCase ,stride=__lowerCamelCase ,name='''shortcut''' ) if should_apply_shortcut else tf.keras.layers.Activation('''linear''' ,name='''shortcut''' ) ) a = [ TFRegNetConvLayer(__lowerCamelCase ,kernel_size=1 ,activation=config.hidden_act ,name='''layer.0''' ), TFRegNetConvLayer( __lowerCamelCase ,stride=__lowerCamelCase ,groups=__lowerCamelCase ,activation=config.hidden_act ,name='''layer.1''' ), TFRegNetSELayer(__lowerCamelCase ,reduced_channels=int(round(in_channels / 4 ) ) ,name='''layer.2''' ), TFRegNetConvLayer(__lowerCamelCase ,kernel_size=1 ,activation=__lowerCamelCase ,name='''layer.3''' ), ] a = ACTaFN[config.hidden_act] def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ,__lowerCamelCase : str ): '''simple docstring''' a = hidden_state for layer_module in self.layers: a = layer_module(__lowerCamelCase ) a = self.shortcut(__lowerCamelCase ) hidden_state += residual a = self.activation(__lowerCamelCase ) return hidden_state class lowerCamelCase_ ( tf.keras.layers.Layer ): def __init__( self : Optional[int] ,__lowerCamelCase : RegNetConfig ,__lowerCamelCase : int ,__lowerCamelCase : int ,__lowerCamelCase : int = 2 ,__lowerCamelCase : int = 2 ,**__lowerCamelCase : Optional[Any] ): '''simple docstring''' super().__init__(**__lowerCamelCase ) a = TFRegNetXLayer if config.layer_type == '''x''' else TFRegNetYLayer a = [ # downsampling is done in the first layer with stride of 2 layer(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ,stride=__lowerCamelCase ,name='''layers.0''' ), *[layer(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ,name=F"""layers.{i+1}""" ) for i in range(depth - 1 )], ] def SCREAMING_SNAKE_CASE_ ( self : Tuple ,__lowerCamelCase : int ): '''simple docstring''' for layer_module in self.layers: a = layer_module(__lowerCamelCase ) return hidden_state class lowerCamelCase_ ( tf.keras.layers.Layer ): def __init__( self : Union[str, Any] ,__lowerCamelCase : RegNetConfig ,**__lowerCamelCase : Optional[Any] ): '''simple docstring''' super().__init__(**__lowerCamelCase ) a = [] # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( TFRegNetStage( __lowerCamelCase ,config.embedding_size ,config.hidden_sizes[0] ,stride=2 if config.downsample_in_first_stage else 1 ,depth=config.depths[0] ,name='''stages.0''' ,) ) a = zip(config.hidden_sizes ,config.hidden_sizes[1:] ) for i, ((in_channels, out_channels), depth) in enumerate(zip(__lowerCamelCase ,config.depths[1:] ) ): self.stages.append(TFRegNetStage(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ,depth=__lowerCamelCase ,name=F"""stages.{i+1}""" ) ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ,__lowerCamelCase : tf.Tensor ,__lowerCamelCase : bool = False ,__lowerCamelCase : bool = True ): '''simple docstring''' a = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: a = hidden_states + (hidden_state,) a = stage_module(__lowerCamelCase ) if output_hidden_states: a = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return TFBaseModelOutputWithNoAttention(last_hidden_state=__lowerCamelCase ,hidden_states=__lowerCamelCase ) @keras_serializable class lowerCamelCase_ ( tf.keras.layers.Layer ): SCREAMING_SNAKE_CASE_ = RegNetConfig def __init__( self : Dict ,__lowerCamelCase : Optional[int] ,**__lowerCamelCase : Optional[Any] ): '''simple docstring''' super().__init__(**__lowerCamelCase ) a = config a = TFRegNetEmbeddings(__lowerCamelCase ,name='''embedder''' ) a = TFRegNetEncoder(__lowerCamelCase ,name='''encoder''' ) a = tf.keras.layers.GlobalAveragePoolingaD(keepdims=__lowerCamelCase ,name='''pooler''' ) @unpack_inputs def SCREAMING_SNAKE_CASE_ ( self : Tuple ,__lowerCamelCase : tf.Tensor ,__lowerCamelCase : Optional[bool] = None ,__lowerCamelCase : Optional[bool] = None ,__lowerCamelCase : bool = False ,): '''simple docstring''' a = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) a = return_dict if return_dict is not None else self.config.use_return_dict a = self.embedder(__lowerCamelCase ,training=__lowerCamelCase ) a = self.encoder( __lowerCamelCase ,output_hidden_states=__lowerCamelCase ,return_dict=__lowerCamelCase ,training=__lowerCamelCase ) a = encoder_outputs[0] a = self.pooler(__lowerCamelCase ) # Change to NCHW output format have uniformity in the modules a = tf.transpose(__lowerCamelCase ,perm=(0, 3, 1, 2) ) a = tf.transpose(__lowerCamelCase ,perm=(0, 3, 1, 2) ) # Change the other hidden state outputs to NCHW as well if output_hidden_states: a = tuple([tf.transpose(__lowerCamelCase ,perm=(0, 3, 1, 2) ) for h in encoder_outputs[1]] ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=__lowerCamelCase ,pooler_output=__lowerCamelCase ,hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states ,) class lowerCamelCase_ ( a_ ): SCREAMING_SNAKE_CASE_ = RegNetConfig SCREAMING_SNAKE_CASE_ = 'regnet' SCREAMING_SNAKE_CASE_ = 'pixel_values' @property def SCREAMING_SNAKE_CASE_ ( self : str ): '''simple docstring''' return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 2_24, 2_24) ,dtype=tf.floataa )} UpperCamelCase__ : Union[str, Any] = R""" Parameters: This model is a Tensorflow [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and behavior. config ([`RegNetConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights. """ UpperCamelCase__ : List[str] = R""" Args: pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`ConveNextImageProcessor.__call__`] for details. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. """ @add_start_docstrings( 'The bare RegNet model outputting raw features without any specific head on top.' , a_ , ) class lowerCamelCase_ ( a_ ): def __init__( self : Optional[int] ,__lowerCamelCase : RegNetConfig ,*__lowerCamelCase : int ,**__lowerCamelCase : Union[str, Any] ): '''simple docstring''' super().__init__(__lowerCamelCase ,*__lowerCamelCase ,**__lowerCamelCase ) a = TFRegNetMainLayer(__lowerCamelCase ,name='''regnet''' ) @unpack_inputs @add_start_docstrings_to_model_forward(__lowerCamelCase ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC ,output_type=__lowerCamelCase ,config_class=_CONFIG_FOR_DOC ,modality='''vision''' ,expected_output=_EXPECTED_OUTPUT_SHAPE ,) def SCREAMING_SNAKE_CASE_ ( self : Any ,__lowerCamelCase : tf.Tensor ,__lowerCamelCase : Optional[bool] = None ,__lowerCamelCase : Optional[bool] = None ,__lowerCamelCase : List[str]=False ,): '''simple docstring''' a = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) a = return_dict if return_dict is not None else self.config.use_return_dict a = self.regnet( pixel_values=__lowerCamelCase ,output_hidden_states=__lowerCamelCase ,return_dict=__lowerCamelCase ,training=__lowerCamelCase ,) if not return_dict: return (outputs[0],) + outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=outputs.last_hidden_state ,pooler_output=outputs.pooler_output ,hidden_states=outputs.hidden_states ,) @add_start_docstrings( '\n RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n ' , a_ , ) class lowerCamelCase_ ( a_ , a_ ): def __init__( self : Optional[int] ,__lowerCamelCase : RegNetConfig ,*__lowerCamelCase : str ,**__lowerCamelCase : Any ): '''simple docstring''' super().__init__(__lowerCamelCase ,*__lowerCamelCase ,**__lowerCamelCase ) a = config.num_labels a = TFRegNetMainLayer(__lowerCamelCase ,name='''regnet''' ) # classification head a = [ tf.keras.layers.Flatten(), tf.keras.layers.Dense(config.num_labels ,name='''classifier.1''' ) if config.num_labels > 0 else tf.identity, ] @unpack_inputs @add_start_docstrings_to_model_forward(__lowerCamelCase ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT ,output_type=__lowerCamelCase ,config_class=_CONFIG_FOR_DOC ,expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT ,) def SCREAMING_SNAKE_CASE_ ( self : Tuple ,__lowerCamelCase : tf.Tensor = None ,__lowerCamelCase : tf.Tensor = None ,__lowerCamelCase : bool = None ,__lowerCamelCase : bool = None ,__lowerCamelCase : Dict=False ,): '''simple docstring''' a = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) a = return_dict if return_dict is not None else self.config.use_return_dict a = self.regnet( __lowerCamelCase ,output_hidden_states=__lowerCamelCase ,return_dict=__lowerCamelCase ,training=__lowerCamelCase ) a = outputs.pooler_output if return_dict else outputs[1] a = self.classifier[0](__lowerCamelCase ) a = self.classifier[1](__lowerCamelCase ) a = None if labels is None else self.hf_compute_loss(labels=__lowerCamelCase ,logits=__lowerCamelCase ) if not return_dict: a = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return TFSequenceClassifierOutput(loss=__lowerCamelCase ,logits=__lowerCamelCase ,hidden_states=outputs.hidden_states )
330
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase__ : Optional[int] = logging.get_logger(__name__) UpperCamelCase__ : Dict = { """facebook/vit-mae-base""": """https://huggingface.co/facebook/vit-mae-base/resolve/main/config.json""", # See all ViT MAE models at https://huggingface.co/models?filter=vit-mae } class lowerCamelCase_ ( a_ ): SCREAMING_SNAKE_CASE_ = 'vit_mae' def __init__( self : Dict ,__lowerCamelCase : Any=7_68 ,__lowerCamelCase : Optional[Any]=12 ,__lowerCamelCase : List[str]=12 ,__lowerCamelCase : Optional[int]=30_72 ,__lowerCamelCase : int="gelu" ,__lowerCamelCase : Union[str, Any]=0.0 ,__lowerCamelCase : Optional[int]=0.0 ,__lowerCamelCase : Dict=0.02 ,__lowerCamelCase : List[Any]=1e-12 ,__lowerCamelCase : Dict=2_24 ,__lowerCamelCase : str=16 ,__lowerCamelCase : Union[str, Any]=3 ,__lowerCamelCase : Optional[Any]=True ,__lowerCamelCase : Dict=16 ,__lowerCamelCase : List[str]=5_12 ,__lowerCamelCase : int=8 ,__lowerCamelCase : int=20_48 ,__lowerCamelCase : Optional[Any]=0.75 ,__lowerCamelCase : int=False ,**__lowerCamelCase : Any ,): '''simple docstring''' super().__init__(**__lowerCamelCase ) 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 a = decoder_num_attention_heads a = decoder_hidden_size a = decoder_num_hidden_layers a = decoder_intermediate_size a = mask_ratio a = norm_pix_loss
330
1
import uuid from typing import Any, Dict, List, Optional, Union 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 if is_torch_available(): import torch UpperCamelCase__ : Dict = logging.get_logger(__name__) class lowerCamelCase_ : def __init__( self : Optional[int] ,__lowerCamelCase : str = None ,__lowerCamelCase : uuid.UUID = None ,__lowerCamelCase : Optional[Any]=None ,__lowerCamelCase : List[str]=None ): '''simple docstring''' if not conversation_id: a = uuid.uuida() if past_user_inputs is None: a = [] if generated_responses is None: a = [] a = conversation_id a = past_user_inputs a = generated_responses a = text def __eq__( self : str ,__lowerCamelCase : Any ): '''simple docstring''' if not isinstance(__lowerCamelCase ,__lowerCamelCase ): return False if self.uuid == other.uuid: return True return ( self.new_user_input == other.new_user_input and self.past_user_inputs == other.past_user_inputs and self.generated_responses == other.generated_responses ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ,__lowerCamelCase : str ,__lowerCamelCase : bool = False ): '''simple docstring''' if self.new_user_input: if overwrite: logger.warning( F"""User input added while unprocessed input was existing: \"{self.new_user_input}\" was overwritten """ F"""with: \"{text}\".""" ) a = text else: logger.warning( F"""User input added while unprocessed input was existing: \"{self.new_user_input}\" new input """ F"""ignored: \"{text}\". Set `overwrite` to True to overwrite unprocessed user input""" ) else: a = text def SCREAMING_SNAKE_CASE_ ( self : List[str] ): '''simple docstring''' if self.new_user_input: self.past_user_inputs.append(self.new_user_input ) a = None def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ,__lowerCamelCase : str ): '''simple docstring''' self.generated_responses.append(__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : int ): '''simple docstring''' for user_input, generated_response in zip(self.past_user_inputs ,self.generated_responses ): yield True, user_input yield False, generated_response if self.new_user_input: yield True, self.new_user_input def __repr__( self : Tuple ): '''simple docstring''' a = F"""Conversation id: {self.uuid} \n""" for is_user, text in self.iter_texts(): a = '''user''' if is_user else '''bot''' output += F"""{name} >> {text} \n""" return output @add_end_docstrings( a_ , R'\n min_length_for_response (`int`, *optional*, defaults to 32):\n The minimum length (in number of tokens) for a response.\n minimum_tokens (`int`, *optional*, defaults to 10):\n The minimum length of tokens to leave for a response.\n ' , ) class lowerCamelCase_ ( a_ ): def __init__( self : Any ,*__lowerCamelCase : Union[str, Any] ,**__lowerCamelCase : Optional[Any] ): '''simple docstring''' super().__init__(*__lowerCamelCase ,**__lowerCamelCase ) if self.tokenizer.pad_token_id is None: a = self.tokenizer.eos_token def SCREAMING_SNAKE_CASE_ ( self : str ,__lowerCamelCase : Tuple=None ,__lowerCamelCase : str=None ,__lowerCamelCase : int=None ,**__lowerCamelCase : Dict ): '''simple docstring''' a = {} a = {} a = {} if min_length_for_response is not None: a = min_length_for_response if minimum_tokens is not None: a = minimum_tokens if "max_length" in generate_kwargs: a = generate_kwargs['''max_length'''] # self.max_length = generate_kwargs.get("max_length", self.model.config.max_length) if clean_up_tokenization_spaces is not None: a = clean_up_tokenization_spaces if generate_kwargs: forward_params.update(__lowerCamelCase ) return preprocess_params, forward_params, postprocess_params def __call__( self : List[Any] ,__lowerCamelCase : Union[Conversation, List[Conversation]] ,__lowerCamelCase : Union[str, Any]=0 ,**__lowerCamelCase : Dict ): '''simple docstring''' a = super().__call__(__lowerCamelCase ,num_workers=__lowerCamelCase ,**__lowerCamelCase ) if isinstance(__lowerCamelCase ,__lowerCamelCase ) and len(__lowerCamelCase ) == 1: return outputs[0] return outputs def SCREAMING_SNAKE_CASE_ ( self : Any ,__lowerCamelCase : Conversation ,__lowerCamelCase : int=32 ): '''simple docstring''' if not isinstance(__lowerCamelCase ,__lowerCamelCase ): raise ValueError('''ConversationalPipeline, expects Conversation as inputs''' ) if conversation.new_user_input is None: raise ValueError( F"""Conversation with UUID {type(conversation.uuid )} does not contain new user input to process. """ '''Add user inputs with the conversation\'s `add_user_input` method''' ) if hasattr(self.tokenizer ,'''_build_conversation_input_ids''' ): a = self.tokenizer._build_conversation_input_ids(__lowerCamelCase ) else: # If the tokenizer cannot handle conversations, we default to only the old version a = self._legacy_parse_and_tokenize(__lowerCamelCase ) if self.framework == "pt": a = torch.LongTensor([input_ids] ) elif self.framework == "tf": a = tf.constant([input_ids] ) return {"input_ids": input_ids, "conversation": conversation} def SCREAMING_SNAKE_CASE_ ( self : Any ,__lowerCamelCase : Tuple ,__lowerCamelCase : Dict=10 ,**__lowerCamelCase : Dict ): '''simple docstring''' a = generate_kwargs.get('''max_length''' ,self.model.config.max_length ) a = model_inputs['''input_ids'''].shape[1] if max_length - minimum_tokens < n: logger.warning(F"""Conversation input is to long ({n}), trimming it to ({max_length} - {minimum_tokens})""" ) a = max_length - minimum_tokens a = model_inputs['''input_ids'''][:, -trim:] if "attention_mask" in model_inputs: a = model_inputs['''attention_mask'''][:, -trim:] a = model_inputs.pop('''conversation''' ) a = max_length a = self.model.generate(**__lowerCamelCase ,**__lowerCamelCase ) if self.model.config.is_encoder_decoder: a = 1 else: a = n return {"output_ids": output_ids[:, start_position:], "conversation": conversation} def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ,__lowerCamelCase : Optional[int] ,__lowerCamelCase : int=True ): '''simple docstring''' a = model_outputs['''output_ids'''] a = self.tokenizer.decode( output_ids[0] ,skip_special_tokens=__lowerCamelCase ,clean_up_tokenization_spaces=__lowerCamelCase ,) a = model_outputs['''conversation'''] conversation.mark_processed() conversation.append_response(__lowerCamelCase ) return conversation def SCREAMING_SNAKE_CASE_ ( self : List[str] ,__lowerCamelCase : Conversation ): '''simple docstring''' a = self.tokenizer.eos_token_id a = [] for is_user, text in conversation.iter_texts(): if eos_token_id is not None: input_ids.extend(self.tokenizer.encode(__lowerCamelCase ,add_special_tokens=__lowerCamelCase ) + [eos_token_id] ) else: input_ids.extend(self.tokenizer.encode(__lowerCamelCase ,add_special_tokens=__lowerCamelCase ) ) if len(__lowerCamelCase ) > self.tokenizer.model_max_length: a = input_ids[-self.tokenizer.model_max_length :] return input_ids
330
def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> Union[str, Any]: """simple docstring""" stooge(snake_case_, 0, len(snake_case_ ) - 1 ) return arr def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_ ) -> Optional[Any]: """simple docstring""" if i >= h: return # If first element is smaller than the last then swap them if arr[i] > arr[h]: a , a = arr[h], arr[i] # If there are more than 2 elements in the array if h - i + 1 > 2: a = (int)((h - i + 1) / 3 ) # Recursively sort first 2/3 elements stooge(snake_case_, snake_case_, (h - t) ) # Recursively sort last 2/3 elements stooge(snake_case_, i + t, (snake_case_) ) # Recursively sort first 2/3 elements stooge(snake_case_, snake_case_, (h - t) ) if __name__ == "__main__": UpperCamelCase__ : Dict = input("""Enter numbers separated by a comma:\n""").strip() UpperCamelCase__ : Optional[int] = [int(item) for item in user_input.split(""",""")] print(stooge_sort(unsorted))
330
1
import colorsys from PIL import Image # type: ignore def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_ ) -> float: """simple docstring""" a = x a = y for step in range(snake_case_ ): # noqa: B007 a = a * a - b * b + x a = 2 * a * b + y a = a_new # divergence happens for all complex number with an absolute value # greater than 4 if a * a + b * b > 4: break return step / (max_step - 1) def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> tuple: """simple docstring""" if distance == 1: return (0, 0, 0) else: return (2_5_5, 2_5_5, 2_5_5) def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> tuple: """simple docstring""" if distance == 1: return (0, 0, 0) else: return tuple(round(i * 2_5_5 ) for i in colorsys.hsv_to_rgb(snake_case_, 1, 1 ) ) def SCREAMING_SNAKE_CASE__ ( snake_case_ = 8_0_0, snake_case_ = 6_0_0, snake_case_ = -0.6, snake_case_ = 0, snake_case_ = 3.2, snake_case_ = 5_0, snake_case_ = True, ) -> Image.Image: """simple docstring""" a = Image.new('''RGB''', (image_width, image_height) ) a = img.load() # loop through the image-coordinates for image_x in range(snake_case_ ): for image_y in range(snake_case_ ): # determine the figure-coordinates based on the image-coordinates a = figure_width / image_width * image_height a = figure_center_x + (image_x / image_width - 0.5) * figure_width a = figure_center_y + (image_y / image_height - 0.5) * figure_height a = get_distance(snake_case_, snake_case_, snake_case_ ) # color the corresponding pixel based on the selected coloring-function if use_distance_color_coding: a = get_color_coded_rgb(snake_case_ ) else: a = get_black_and_white_rgb(snake_case_ ) return img if __name__ == "__main__": import doctest doctest.testmod() # colored version, full figure UpperCamelCase__ : Tuple = get_image() # uncomment for colored version, different section, zoomed in # img = get_image(figure_center_x = -0.6, figure_center_y = -0.4, # figure_width = 0.8) # uncomment for black and white version, full figure # img = get_image(use_distance_color_coding = False) # uncomment to save the image # img.save("mandelbrot.png") img.show()
330
import json import os import re import unicodedata from json.encoder import INFINITY from typing import Any, Dict, List, Optional, Tuple, Union import numpy as np import regex from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, is_flax_available, is_tf_available, is_torch_available, logging from ...utils.generic import _is_jax, _is_numpy UpperCamelCase__ : Any = logging.get_logger(__name__) UpperCamelCase__ : Optional[Any] = { """artists_file""": """artists.json""", """lyrics_file""": """lyrics.json""", """genres_file""": """genres.json""", } UpperCamelCase__ : Union[str, Any] = { """artists_file""": { """jukebox""": """https://huggingface.co/ArthurZ/jukebox/blob/main/artists.json""", }, """genres_file""": { """jukebox""": """https://huggingface.co/ArthurZ/jukebox/blob/main/genres.json""", }, """lyrics_file""": { """jukebox""": """https://huggingface.co/ArthurZ/jukebox/blob/main/lyrics.json""", }, } UpperCamelCase__ : str = { """jukebox""": 512, } class lowerCamelCase_ ( a_ ): SCREAMING_SNAKE_CASE_ = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE_ = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE_ = PRETRAINED_LYRIC_TOKENS_SIZES SCREAMING_SNAKE_CASE_ = ['input_ids', 'attention_mask'] def __init__( self : Optional[Any] ,__lowerCamelCase : Optional[Any] ,__lowerCamelCase : List[Any] ,__lowerCamelCase : Tuple ,__lowerCamelCase : Union[str, Any]=["v3", "v2", "v2"] ,__lowerCamelCase : List[Any]=5_12 ,__lowerCamelCase : Tuple=5 ,__lowerCamelCase : List[Any]="<|endoftext|>" ,**__lowerCamelCase : List[str] ,): '''simple docstring''' a = AddedToken(__lowerCamelCase ,lstrip=__lowerCamelCase ,rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase ,__lowerCamelCase ) else unk_token super().__init__( unk_token=__lowerCamelCase ,n_genres=__lowerCamelCase ,version=__lowerCamelCase ,max_n_lyric_tokens=__lowerCamelCase ,**__lowerCamelCase ,) a = version a = max_n_lyric_tokens a = n_genres with open(__lowerCamelCase ,encoding='''utf-8''' ) as vocab_handle: a = json.load(__lowerCamelCase ) with open(__lowerCamelCase ,encoding='''utf-8''' ) as vocab_handle: a = json.load(__lowerCamelCase ) with open(__lowerCamelCase ,encoding='''utf-8''' ) as vocab_handle: a = json.load(__lowerCamelCase ) a = r'''[^A-Za-z0-9.,:;!?\-\'\"()\[\] \t\n]+''' # In v2, we had a n_vocab=80 and in v3 we missed + and so n_vocab=79 of characters. if len(self.lyrics_encoder ) == 79: a = oov.replace(r'''\-\'''' ,r'''\-+\'''' ) a = regex.compile(__lowerCamelCase ) a = {v: k for k, v in self.artists_encoder.items()} a = {v: k for k, v in self.genres_encoder.items()} a = {v: k for k, v in self.lyrics_encoder.items()} @property def SCREAMING_SNAKE_CASE_ ( self : str ): '''simple docstring''' return len(self.artists_encoder ) + len(self.genres_encoder ) + len(self.lyrics_encoder ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ): '''simple docstring''' return dict(self.artists_encoder ,self.genres_encoder ,self.lyrics_encoder ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ,__lowerCamelCase : Optional[int] ,__lowerCamelCase : Optional[Any] ,__lowerCamelCase : List[Any] ): '''simple docstring''' a = [self.artists_encoder.get(__lowerCamelCase ,0 ) for artist in list_artists] for genres in range(len(__lowerCamelCase ) ): a = [self.genres_encoder.get(__lowerCamelCase ,0 ) for genre in list_genres[genres]] a = list_genres[genres] + [-1] * (self.n_genres - len(list_genres[genres] )) a = [[self.lyrics_encoder.get(__lowerCamelCase ,0 ) for character in list_lyrics[0]], [], []] return artists_id, list_genres, lyric_ids def SCREAMING_SNAKE_CASE_ ( self : Tuple ,__lowerCamelCase : List[str] ): '''simple docstring''' return list(__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ,__lowerCamelCase : List[Any] ,__lowerCamelCase : Any ,__lowerCamelCase : Optional[int] ,**__lowerCamelCase : Optional[Any] ): '''simple docstring''' a , a , a = self.prepare_for_tokenization(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ) a = self._tokenize(__lowerCamelCase ) return artist, genre, lyrics def SCREAMING_SNAKE_CASE_ ( self : int ,__lowerCamelCase : str ,__lowerCamelCase : str ,__lowerCamelCase : str ,__lowerCamelCase : bool = False ): '''simple docstring''' for idx in range(len(self.version ) ): if self.version[idx] == "v3": a = artists[idx].lower() a = [genres[idx].lower()] else: a = self._normalize(artists[idx] ) + '''.v2''' a = [ self._normalize(__lowerCamelCase ) + '''.v2''' for genre in genres[idx].split('''_''' ) ] # split is for the full dictionary with combined genres if self.version[0] == "v2": a = regex.compile(r'''[^A-Za-z0-9.,:;!?\-\'\"()\[\] \t\n]+''' ) a = '''ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,:;!?-+\'\"()[] \t\n''' a = {vocab[index]: index + 1 for index in range(len(__lowerCamelCase ) )} a = 0 a = len(__lowerCamelCase ) + 1 a = self.vocab a = {v: k for k, v in self.vocab.items()} a = '''''' else: a = regex.compile(r'''[^A-Za-z0-9.,:;!?\-+\'\"()\[\] \t\n]+''' ) a = self._run_strip_accents(__lowerCamelCase ) a = lyrics.replace('''\\''' ,'''\n''' ) a = self.out_of_vocab.sub('''''' ,__lowerCamelCase ), [], [] return artists, genres, lyrics def SCREAMING_SNAKE_CASE_ ( self : str ,__lowerCamelCase : int ): '''simple docstring''' a = unicodedata.normalize('''NFD''' ,__lowerCamelCase ) a = [] for char in text: a = unicodedata.category(__lowerCamelCase ) if cat == "Mn": continue output.append(__lowerCamelCase ) return "".join(__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ,__lowerCamelCase : str ): '''simple docstring''' a = ( [chr(__lowerCamelCase ) for i in range(ord('''a''' ) ,ord('''z''' ) + 1 )] + [chr(__lowerCamelCase ) for i in range(ord('''A''' ) ,ord('''Z''' ) + 1 )] + [chr(__lowerCamelCase ) for i in range(ord('''0''' ) ,ord('''9''' ) + 1 )] + ['''.'''] ) a = frozenset(__lowerCamelCase ) a = re.compile(r'''_+''' ) a = ''''''.join([c if c in accepted else '''_''' for c in text.lower()] ) a = pattern.sub('''_''' ,__lowerCamelCase ).strip('''_''' ) return text def SCREAMING_SNAKE_CASE_ ( self : List[str] ,__lowerCamelCase : List[str] ): '''simple docstring''' return " ".join(__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : Any ,__lowerCamelCase : str ,__lowerCamelCase : Optional[Union[str, TensorType]] = None ,__lowerCamelCase : bool = False ): '''simple docstring''' if not isinstance(__lowerCamelCase ,__lowerCamelCase ): a = TensorType(__lowerCamelCase ) # Get a function reference for the correct framework if tensor_type == TensorType.TENSORFLOW: if not is_tf_available(): raise ImportError( '''Unable to convert output to TensorFlow tensors format, TensorFlow is not installed.''' ) import tensorflow as tf a = tf.constant a = tf.is_tensor elif tensor_type == TensorType.PYTORCH: if not is_torch_available(): raise ImportError('''Unable to convert output to PyTorch tensors format, PyTorch is not installed.''' ) import torch a = torch.tensor a = torch.is_tensor elif tensor_type == TensorType.JAX: if not is_flax_available(): raise ImportError('''Unable to convert output to JAX tensors format, JAX is not installed.''' ) import jax.numpy as jnp # noqa: F811 a = jnp.array a = _is_jax else: a = np.asarray a = _is_numpy # Do the tensor conversion in batch try: if prepend_batch_axis: a = [inputs] if not is_tensor(__lowerCamelCase ): a = as_tensor(__lowerCamelCase ) except: # noqa E722 raise ValueError( '''Unable to create tensor, you should probably activate truncation and/or padding ''' '''with \'padding=True\' \'truncation=True\' to have batched tensors with the same length.''' ) return inputs def __call__( self : Tuple ,__lowerCamelCase : Tuple ,__lowerCamelCase : Optional[int] ,__lowerCamelCase : List[str]="" ,__lowerCamelCase : List[Any]="pt" ): '''simple docstring''' a = [0, 0, 0] a = [artist] * len(self.version ) a = [genres] * len(self.version ) a , a , a = self.tokenize(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ) a , a , a = self._convert_token_to_id(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ) a = [-INFINITY] * len(full_tokens[-1] ) a = [ self.convert_to_tensors( [input_ids + [artists_id[i]] + genres_ids[i] + full_tokens[i]] ,tensor_type=__lowerCamelCase ) for i in range(len(self.version ) ) ] return BatchEncoding({'''input_ids''': input_ids, '''attention_masks''': attention_masks} ) def SCREAMING_SNAKE_CASE_ ( self : int ,__lowerCamelCase : str ,__lowerCamelCase : Optional[str] = None ): '''simple docstring''' 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['''artists_file'''] ) with open(__lowerCamelCase ,'''w''' ,encoding='''utf-8''' ) as f: f.write(json.dumps(self.artists_encoder ,ensure_ascii=__lowerCamelCase ) ) a = os.path.join( __lowerCamelCase ,(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''genres_file'''] ) with open(__lowerCamelCase ,'''w''' ,encoding='''utf-8''' ) as f: f.write(json.dumps(self.genres_encoder ,ensure_ascii=__lowerCamelCase ) ) a = os.path.join( __lowerCamelCase ,(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''lyrics_file'''] ) with open(__lowerCamelCase ,'''w''' ,encoding='''utf-8''' ) as f: f.write(json.dumps(self.lyrics_encoder ,ensure_ascii=__lowerCamelCase ) ) return (artists_file, genres_file, lyrics_file) def SCREAMING_SNAKE_CASE_ ( self : Any ,__lowerCamelCase : Any ,__lowerCamelCase : Any ,__lowerCamelCase : str ): '''simple docstring''' a = self.artists_decoder.get(__lowerCamelCase ) a = [self.genres_decoder.get(__lowerCamelCase ) for genre in genres_index] a = [self.lyrics_decoder.get(__lowerCamelCase ) for character in lyric_index] return artist, genres, lyrics
330
1
from __future__ import annotations from collections.abc import Iterator from typing import Generic, TypeVar UpperCamelCase__ : Any = TypeVar("""T""") class lowerCamelCase_ ( Generic[T] ): def __init__( self : Any ,__lowerCamelCase : T ): '''simple docstring''' a = data a = None def __str__( self : Any ): '''simple docstring''' return F"""{self.data}""" class lowerCamelCase_ ( Generic[T] ): def __init__( self : Union[str, Any] ): '''simple docstring''' a = None def __iter__( self : List[str] ): '''simple docstring''' a = self.top while node: yield node.data a = node.next def __str__( self : str ): '''simple docstring''' return "->".join([str(__lowerCamelCase ) for item in self] ) def __len__( self : Optional[int] ): '''simple docstring''' return len(tuple(iter(self ) ) ) def SCREAMING_SNAKE_CASE_ ( self : Any ): '''simple docstring''' return self.top is None def SCREAMING_SNAKE_CASE_ ( self : int ,__lowerCamelCase : T ): '''simple docstring''' a = Node(__lowerCamelCase ) if not self.is_empty(): a = self.top a = node def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ): '''simple docstring''' if self.is_empty(): raise IndexError('''pop from empty stack''' ) assert isinstance(self.top ,__lowerCamelCase ) a = self.top a = self.top.next return pop_node.data def SCREAMING_SNAKE_CASE_ ( self : int ): '''simple docstring''' if self.is_empty(): raise IndexError('''peek from empty stack''' ) assert self.top is not None return self.top.data def SCREAMING_SNAKE_CASE_ ( self : Dict ): '''simple docstring''' a = None if __name__ == "__main__": from doctest import testmod testmod()
330
# This script creates a super tiny model that is useful inside tests, when we just want to test that # the machinery works, without needing to the check the quality of the outcomes. # # This version creates a tiny vocab first, and then a tiny model - so the outcome is truly tiny - # all files ~60KB. As compared to taking a full-size model, reducing to the minimum its layers and # emb dimensions, but keeping the full vocab + merges files, leading to ~3MB in total for all files. # The latter is done by `fsmt-make-super-tiny-model.py`. # # It will be used then as "stas/tiny-wmt19-en-ru" from pathlib import Path import json import tempfile from transformers import FSMTTokenizer, FSMTConfig, FSMTForConditionalGeneration from transformers.models.fsmt.tokenization_fsmt import VOCAB_FILES_NAMES UpperCamelCase__ : Optional[Any] = """tiny-wmt19-en-ru""" # Build # borrowed from a test UpperCamelCase__ : Any = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """w</w>""", """r</w>""", """t</w>""", """lo""", """low""", """er</w>""", """low</w>""", """lowest</w>""", """newer</w>""", """wider</w>""", """<unk>""", ] UpperCamelCase__ : List[Any] = dict(zip(vocab, range(len(vocab)))) UpperCamelCase__ : Any = ["""l o 123""", """lo w 1456""", """e r</w> 1789""", """"""] with tempfile.TemporaryDirectory() as tmpdirname: UpperCamelCase__ : Optional[Any] = Path(tmpdirname) UpperCamelCase__ : Tuple = build_dir / VOCAB_FILES_NAMES["""src_vocab_file"""] UpperCamelCase__ : int = build_dir / VOCAB_FILES_NAMES["""tgt_vocab_file"""] UpperCamelCase__ : Union[str, Any] = build_dir / VOCAB_FILES_NAMES["""merges_file"""] with open(src_vocab_file, """w""") as fp: fp.write(json.dumps(vocab_tokens)) with open(tgt_vocab_file, """w""") as fp: fp.write(json.dumps(vocab_tokens)) with open(merges_file, """w""") as fp: fp.write("""\n""".join(merges)) UpperCamelCase__ : Dict = FSMTTokenizer( langs=["""en""", """ru"""], src_vocab_size=len(vocab), tgt_vocab_size=len(vocab), src_vocab_file=src_vocab_file, tgt_vocab_file=tgt_vocab_file, merges_file=merges_file, ) UpperCamelCase__ : Union[str, Any] = FSMTConfig( langs=["""ru""", """en"""], src_vocab_size=1_000, tgt_vocab_size=1_000, d_model=4, encoder_layers=1, decoder_layers=1, encoder_ffn_dim=4, decoder_ffn_dim=4, encoder_attention_heads=1, decoder_attention_heads=1, ) UpperCamelCase__ : Union[str, Any] = FSMTForConditionalGeneration(config) print(F"num of params {tiny_model.num_parameters()}") # Test UpperCamelCase__ : List[str] = tokenizer(["""Making tiny model"""], return_tensors="""pt""") UpperCamelCase__ : Tuple = tiny_model(**batch) print("""test output:""", len(outputs.logits[0])) # Save tiny_model.half() # makes it smaller tiny_model.save_pretrained(mname_tiny) tokenizer.save_pretrained(mname_tiny) print(F"Generated {mname_tiny}") # Upload # transformers-cli upload tiny-wmt19-en-ru
330
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCamelCase__ : List[str] = { """configuration_git""": ["""GIT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GitConfig""", """GitVisionConfig"""], """processing_git""": ["""GitProcessor"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ : Dict = [ """GIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """GitForCausalLM""", """GitModel""", """GitPreTrainedModel""", """GitVisionModel""", ] if TYPE_CHECKING: from .configuration_git import GIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GitConfig, GitVisionConfig from .processing_git import GitProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_git import ( GIT_PRETRAINED_MODEL_ARCHIVE_LIST, GitForCausalLM, GitModel, GitPreTrainedModel, GitVisionModel, ) else: import sys UpperCamelCase__ : Optional[int] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
330
import inspect import os import torch from transformers import AutoModel from transformers.testing_utils import mockenv_context from transformers.trainer_utils import set_seed import accelerate from accelerate.accelerator import Accelerator from accelerate.state import AcceleratorState from accelerate.test_utils.testing import ( AccelerateTestCase, TempDirTestCase, execute_subprocess_async, require_cuda, require_fsdp, require_multi_gpu, slow, ) from accelerate.utils.constants import ( FSDP_AUTO_WRAP_POLICY, FSDP_BACKWARD_PREFETCH, FSDP_SHARDING_STRATEGY, FSDP_STATE_DICT_TYPE, ) from accelerate.utils.dataclasses import FullyShardedDataParallelPlugin from accelerate.utils.other import patch_environment set_seed(42) UpperCamelCase__ : Optional[Any] = """bert-base-cased""" UpperCamelCase__ : int = """fp16""" UpperCamelCase__ : str = """bf16""" UpperCamelCase__ : List[Any] = [FPaa, BFaa] @require_fsdp @require_cuda class lowerCamelCase_ ( a_ ): def SCREAMING_SNAKE_CASE_ ( self : int ): '''simple docstring''' super().setUp() a = dict( ACCELERATE_USE_FSDP='''true''' ,MASTER_ADDR='''localhost''' ,MASTER_PORT='''10999''' ,RANK='''0''' ,LOCAL_RANK='''0''' ,WORLD_SIZE='''1''' ,) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ): '''simple docstring''' from torch.distributed.fsdp.fully_sharded_data_parallel import ShardingStrategy for i, strategy in enumerate(__lowerCamelCase ): a = self.dist_env.copy() a = F"""{i + 1}""" a = strategy with mockenv_context(**__lowerCamelCase ): a = FullyShardedDataParallelPlugin() self.assertEqual(fsdp_plugin.sharding_strategy ,ShardingStrategy(i + 1 ) ) def SCREAMING_SNAKE_CASE_ ( self : Any ): '''simple docstring''' from torch.distributed.fsdp.fully_sharded_data_parallel import BackwardPrefetch for i, prefetch_policy in enumerate(__lowerCamelCase ): a = self.dist_env.copy() a = prefetch_policy with mockenv_context(**__lowerCamelCase ): a = FullyShardedDataParallelPlugin() if prefetch_policy == "NO_PREFETCH": self.assertIsNone(fsdp_plugin.backward_prefetch ) else: self.assertEqual(fsdp_plugin.backward_prefetch ,BackwardPrefetch(i + 1 ) ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ): '''simple docstring''' from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType for i, state_dict_type in enumerate(__lowerCamelCase ): a = self.dist_env.copy() a = state_dict_type with mockenv_context(**__lowerCamelCase ): a = FullyShardedDataParallelPlugin() self.assertEqual(fsdp_plugin.state_dict_type ,StateDictType(i + 1 ) ) if state_dict_type == "FULL_STATE_DICT": self.assertTrue(fsdp_plugin.state_dict_config.offload_to_cpu ) self.assertTrue(fsdp_plugin.state_dict_config.ranka_only ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ): '''simple docstring''' a = AutoModel.from_pretrained(__lowerCamelCase ) for policy in FSDP_AUTO_WRAP_POLICY: a = self.dist_env.copy() a = policy if policy == "TRANSFORMER_BASED_WRAP": a = '''BertLayer''' elif policy == "SIZE_BASED_WRAP": a = '''2000''' with mockenv_context(**__lowerCamelCase ): a = FullyShardedDataParallelPlugin() fsdp_plugin.set_auto_wrap_policy(__lowerCamelCase ) if policy == "NO_WRAP": self.assertIsNone(fsdp_plugin.auto_wrap_policy ) else: self.assertIsNotNone(fsdp_plugin.auto_wrap_policy ) a = self.dist_env.copy() a = '''TRANSFORMER_BASED_WRAP''' a = '''T5Layer''' with mockenv_context(**__lowerCamelCase ): a = FullyShardedDataParallelPlugin() with self.assertRaises(__lowerCamelCase ) as cm: fsdp_plugin.set_auto_wrap_policy(__lowerCamelCase ) self.assertTrue('''Could not find the transformer layer class to wrap in the model.''' in str(cm.exception ) ) a = self.dist_env.copy() a = '''SIZE_BASED_WRAP''' a = '''0''' with mockenv_context(**__lowerCamelCase ): a = FullyShardedDataParallelPlugin() fsdp_plugin.set_auto_wrap_policy(__lowerCamelCase ) self.assertIsNone(fsdp_plugin.auto_wrap_policy ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ): '''simple docstring''' from torch.distributed.fsdp.fully_sharded_data_parallel import MixedPrecision from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler for mp_dtype in dtypes: a = self.dist_env.copy() a = mp_dtype with mockenv_context(**__lowerCamelCase ): a = Accelerator() if mp_dtype == "fp16": a = torch.floataa elif mp_dtype == "bf16": a = torch.bfloataa a = MixedPrecision(param_dtype=__lowerCamelCase ,reduce_dtype=__lowerCamelCase ,buffer_dtype=__lowerCamelCase ) self.assertEqual(accelerator.state.fsdp_plugin.mixed_precision_policy ,__lowerCamelCase ) if mp_dtype == FPaa: self.assertTrue(isinstance(accelerator.scaler ,__lowerCamelCase ) ) elif mp_dtype == BFaa: self.assertIsNone(accelerator.scaler ) AcceleratorState._reset_state(__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ): '''simple docstring''' from torch.distributed.fsdp.fully_sharded_data_parallel import CPUOffload for flag in [True, False]: a = self.dist_env.copy() a = str(__lowerCamelCase ).lower() with mockenv_context(**__lowerCamelCase ): a = FullyShardedDataParallelPlugin() self.assertEqual(fsdp_plugin.cpu_offload ,CPUOffload(offload_params=__lowerCamelCase ) ) @require_fsdp @require_multi_gpu @slow class lowerCamelCase_ ( a_ ): def SCREAMING_SNAKE_CASE_ ( self : List[Any] ): '''simple docstring''' super().setUp() a = 0.82 a = [ '''fsdp_shard_grad_op_transformer_based_wrap''', '''fsdp_full_shard_transformer_based_wrap''', ] a = { '''multi_gpu_fp16''': 32_00, '''fsdp_shard_grad_op_transformer_based_wrap_fp16''': 20_00, '''fsdp_full_shard_transformer_based_wrap_fp16''': 19_00, # Disabling below test as it overwhelms the RAM memory usage # on CI self-hosted runner leading to tests getting killed. # "fsdp_full_shard_cpu_offload_transformer_based_wrap_fp32": 1500, # fp16 was leading to indefinite hang } a = 1_60 a = 1_60 a = inspect.getfile(accelerate.test_utils ) a = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''external_deps'''] ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ): '''simple docstring''' a = os.path.join(self.test_scripts_folder ,'''test_performance.py''' ) a = ['''accelerate''', '''launch''', '''--num_processes=2''', '''--num_machines=1''', '''--machine_rank=0''', '''--use_fsdp'''] for config in self.performance_configs: a = cmd.copy() for i, strategy in enumerate(__lowerCamelCase ): if strategy.lower() in config: cmd_config.append(F"""--fsdp_sharding_strategy={i+1}""" ) break if "fp32" in config: cmd_config.append('''--mixed_precision=no''' ) else: cmd_config.append('''--mixed_precision=fp16''' ) if "cpu_offload" in config: cmd_config.append('''--fsdp_offload_params=True''' ) for policy in FSDP_AUTO_WRAP_POLICY: if policy.lower() in config: cmd_config.append(F"""--fsdp_auto_wrap_policy={policy}""" ) break if policy == "TRANSFORMER_BASED_WRAP": cmd_config.append('''--fsdp_transformer_layer_cls_to_wrap=BertLayer''' ) elif policy == "SIZE_BASED_WRAP": cmd_config.append('''--fsdp_min_num_params=2000''' ) cmd_config.extend( [ self.test_file_path, F"""--output_dir={self.tmpdir}""", F"""--performance_lower_bound={self.performance_lower_bound}""", ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__lowerCamelCase ,env=os.environ.copy() ) def SCREAMING_SNAKE_CASE_ ( self : Any ): '''simple docstring''' a = os.path.join(self.test_scripts_folder ,'''test_checkpointing.py''' ) a = [ '''accelerate''', '''launch''', '''--num_processes=2''', '''--num_machines=1''', '''--machine_rank=0''', '''--use_fsdp''', '''--mixed_precision=fp16''', '''--fsdp_transformer_layer_cls_to_wrap=BertLayer''', ] for i, strategy in enumerate(__lowerCamelCase ): a = cmd.copy() cmd_config.append(F"""--fsdp_sharding_strategy={i+1}""" ) if strategy != "FULL_SHARD": continue a = len(__lowerCamelCase ) for state_dict_type in FSDP_STATE_DICT_TYPE: a = cmd_config[:state_dict_config_index] cmd_config.append(F"""--fsdp_state_dict_type={state_dict_type}""" ) cmd_config.extend( [ self.test_file_path, F"""--output_dir={self.tmpdir}""", '''--partial_train_epoch=1''', ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__lowerCamelCase ,env=os.environ.copy() ) a = cmd_config[:-1] a = os.path.join(self.tmpdir ,'''epoch_0''' ) cmd_config.extend( [ F"""--resume_from_checkpoint={resume_from_checkpoint}""", ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__lowerCamelCase ,env=os.environ.copy() ) def SCREAMING_SNAKE_CASE_ ( self : int ): '''simple docstring''' a = os.path.join(self.test_scripts_folder ,'''test_peak_memory_usage.py''' ) a = [ '''accelerate''', '''launch''', '''--num_processes=2''', '''--num_machines=1''', '''--machine_rank=0''', ] for spec, peak_mem_upper_bound in self.peak_memory_usage_upper_bound.items(): a = cmd.copy() if "fp16" in spec: cmd_config.extend(['''--mixed_precision=fp16'''] ) else: cmd_config.extend(['''--mixed_precision=no'''] ) if "multi_gpu" in spec: continue else: cmd_config.extend(['''--use_fsdp'''] ) for i, strategy in enumerate(__lowerCamelCase ): if strategy.lower() in spec: cmd_config.append(F"""--fsdp_sharding_strategy={i+1}""" ) break if "cpu_offload" in spec: cmd_config.append('''--fsdp_offload_params=True''' ) for policy in FSDP_AUTO_WRAP_POLICY: if policy.lower() in spec: cmd_config.append(F"""--fsdp_auto_wrap_policy={policy}""" ) break if policy == "TRANSFORMER_BASED_WRAP": cmd_config.append('''--fsdp_transformer_layer_cls_to_wrap=BertLayer''' ) elif policy == "SIZE_BASED_WRAP": cmd_config.append('''--fsdp_min_num_params=2000''' ) cmd_config.extend( [ self.test_file_path, F"""--output_dir={self.tmpdir}""", F"""--peak_memory_upper_bound={peak_mem_upper_bound}""", F"""--n_train={self.n_train}""", F"""--n_val={self.n_val}""", ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__lowerCamelCase ,env=os.environ.copy() )
330
1
import random import unittest import torch from diffusers import IFImgaImgSuperResolutionPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin from . import IFPipelineTesterMixin @skip_mps class lowerCamelCase_ ( a_ , a_ , unittest.TestCase ): SCREAMING_SNAKE_CASE_ = IFImgaImgSuperResolutionPipeline SCREAMING_SNAKE_CASE_ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'width', 'height'} SCREAMING_SNAKE_CASE_ = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'original_image'} ) SCREAMING_SNAKE_CASE_ = PipelineTesterMixin.required_optional_params - {'latents'} def SCREAMING_SNAKE_CASE_ ( self : Any ): '''simple docstring''' return self._get_superresolution_dummy_components() def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ,__lowerCamelCase : Union[str, Any] ,__lowerCamelCase : List[Any]=0 ): '''simple docstring''' if str(__lowerCamelCase ).startswith('''mps''' ): a = torch.manual_seed(__lowerCamelCase ) else: a = torch.Generator(device=__lowerCamelCase ).manual_seed(__lowerCamelCase ) a = floats_tensor((1, 3, 32, 32) ,rng=random.Random(__lowerCamelCase ) ).to(__lowerCamelCase ) a = floats_tensor((1, 3, 16, 16) ,rng=random.Random(__lowerCamelCase ) ).to(__lowerCamelCase ) a = { '''prompt''': '''A painting of a squirrel eating a burger''', '''image''': image, '''original_image''': original_image, '''generator''': generator, '''num_inference_steps''': 2, '''output_type''': '''numpy''', } return inputs @unittest.skipIf( torch_device != '''cuda''' or not is_xformers_available() ,reason='''XFormers attention is only available with CUDA and `xformers` installed''' ,) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ): '''simple docstring''' self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3 ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ): '''simple docstring''' self._test_save_load_optional_components() @unittest.skipIf(torch_device != '''cuda''' ,reason='''float16 requires CUDA''' ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ): '''simple docstring''' super().test_save_load_floataa(expected_max_diff=1e-1 ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ): '''simple docstring''' self._test_attention_slicing_forward_pass(expected_max_diff=1e-2 ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ): '''simple docstring''' self._test_save_load_local() def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ): '''simple docstring''' self._test_inference_batch_single_identical( expected_max_diff=1e-2 ,)
330
from __future__ import annotations import os from collections.abc import Mapping UpperCamelCase__ : Any = tuple[int, int] class lowerCamelCase_ : def __init__( self : Optional[Any] ,__lowerCamelCase : set[int] ,__lowerCamelCase : Mapping[EdgeT, int] ): '''simple docstring''' a = vertices a = { (min(__lowerCamelCase ), max(__lowerCamelCase )): weight for edge, weight in edges.items() } def SCREAMING_SNAKE_CASE_ ( self : str ,__lowerCamelCase : EdgeT ,__lowerCamelCase : int ): '''simple docstring''' self.vertices.add(edge[0] ) self.vertices.add(edge[1] ) a = weight def SCREAMING_SNAKE_CASE_ ( self : Dict ): '''simple docstring''' a = Graph({min(self.vertices )} ,{} ) a = 42 a = 42 a = 42 a = 42 while len(subgraph.vertices ) < len(self.vertices ): a = max(self.edges.values() ) + 1 for edge, weight in self.edges.items(): if (edge[0] in subgraph.vertices) ^ (edge[1] in subgraph.vertices): if weight < min_weight: a = edge a = weight subgraph.add_edge(__lowerCamelCase ,__lowerCamelCase ) return subgraph def SCREAMING_SNAKE_CASE__ ( snake_case_ = "p107_network.txt" ) -> int: """simple docstring""" a = os.path.abspath(os.path.dirname(snake_case_ ) ) a = os.path.join(snake_case_, snake_case_ ) a = {} a = 42 a = 42 a = 42 with open(snake_case_ ) as f: a = f.read().strip().split('''\n''' ) a = [line.split(''',''' ) for line in data] for edgea in range(1, len(snake_case_ ) ): for edgea in range(snake_case_ ): if adjaceny_matrix[edgea][edgea] != "-": a = int(adjaceny_matrix[edgea][edgea] ) a = Graph(set(range(len(snake_case_ ) ) ), snake_case_ ) a = graph.prims_algorithm() a = sum(graph.edges.values() ) a = sum(subgraph.edges.values() ) return initial_total - optimal_total if __name__ == "__main__": print(F"{solution() = }")
330
1
from typing import List, Optional, Union import numpy as np from ....audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function from ....feature_extraction_sequence_utils import SequenceFeatureExtractor from ....feature_extraction_utils import BatchFeature from ....file_utils import PaddingStrategy, TensorType from ....utils import logging UpperCamelCase__ : Any = logging.get_logger(__name__) class lowerCamelCase_ ( a_ ): SCREAMING_SNAKE_CASE_ = ['input_features', 'attention_mask'] def __init__( self : int ,__lowerCamelCase : Union[str, Any]=80 ,__lowerCamelCase : Union[str, Any]=1_60_00 ,__lowerCamelCase : str=0.0 ,__lowerCamelCase : List[str]=10 ,__lowerCamelCase : Tuple=25 ,__lowerCamelCase : Tuple="hamming_window" ,__lowerCamelCase : int=32_768.0 ,__lowerCamelCase : Optional[int]=0.97 ,__lowerCamelCase : Union[str, Any]=1.0 ,__lowerCamelCase : Tuple=True ,__lowerCamelCase : Dict=True ,__lowerCamelCase : int=False ,**__lowerCamelCase : Dict ,): '''simple docstring''' super().__init__(feature_size=__lowerCamelCase ,sampling_rate=__lowerCamelCase ,padding_value=__lowerCamelCase ,**__lowerCamelCase ) a = feature_size a = sampling_rate a = padding_value a = hop_length a = win_length a = frame_signal_scale a = preemphasis_coeff a = mel_floor a = normalize_means a = normalize_vars a = win_function a = return_attention_mask a = win_length * sampling_rate // 10_00 a = hop_length * sampling_rate // 10_00 a = optimal_fft_length(self.sample_size ) a = (self.n_fft // 2) + 1 def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ,__lowerCamelCase : np.array ): '''simple docstring''' if self.win_function == "hamming_window": a = window_function(window_length=self.sample_size ,name=self.win_function ,periodic=__lowerCamelCase ) else: a = window_function(window_length=self.sample_size ,name=self.win_function ) a = mel_filter_bank( num_frequency_bins=self.n_freqs ,num_mel_filters=self.feature_size ,min_frequency=0.0 ,max_frequency=self.sampling_rate / 2.0 ,sampling_rate=self.sampling_rate ,) a = spectrogram( one_waveform * self.frame_signal_scale ,window=__lowerCamelCase ,frame_length=self.sample_size ,hop_length=self.sample_stride ,fft_length=self.n_fft ,center=__lowerCamelCase ,preemphasis=self.preemphasis_coeff ,mel_filters=__lowerCamelCase ,mel_floor=self.mel_floor ,log_mel='''log''' ,) return msfc_features.T def SCREAMING_SNAKE_CASE_ ( self : List[Any] ,__lowerCamelCase : int ,__lowerCamelCase : Any ,__lowerCamelCase : Any ): '''simple docstring''' if self.normalize_means: a = x[:input_length].mean(axis=0 ) a = np.subtract(__lowerCamelCase ,__lowerCamelCase ) if self.normalize_vars: a = x[:input_length].std(axis=0 ) a = np.divide(__lowerCamelCase ,__lowerCamelCase ) if input_length < x.shape[0]: a = padding_value # make sure array is in float32 a = x.astype(np.floataa ) return x def SCREAMING_SNAKE_CASE_ ( self : List[str] ,__lowerCamelCase : List[np.ndarray] ,__lowerCamelCase : Optional[np.ndarray] = None ): '''simple docstring''' a = attention_mask.sum(-1 ) if attention_mask is not None else [x.shape[0] for x in input_features] return [self._normalize_one(__lowerCamelCase ,__lowerCamelCase ,self.padding_value ) for x, n in zip(__lowerCamelCase ,__lowerCamelCase )] def __call__( self : Any ,__lowerCamelCase : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] ,__lowerCamelCase : Union[bool, str, PaddingStrategy] = False ,__lowerCamelCase : Optional[int] = None ,__lowerCamelCase : bool = False ,__lowerCamelCase : Optional[int] = None ,__lowerCamelCase : Optional[bool] = None ,__lowerCamelCase : Optional[Union[str, TensorType]] = None ,__lowerCamelCase : Optional[int] = None ,**__lowerCamelCase : Any ,): '''simple docstring''' if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( F"""The model corresponding to this feature extractor: {self} was trained using a sampling rate of""" F""" {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with""" F""" {self.sampling_rate} and not {sampling_rate}.""" ) else: logger.warning( '''It is strongly recommended to pass the ``sampling_rate`` argument to this function. ''' '''Failing to do so can result in silent errors that might be hard to debug.''' ) a = isinstance(__lowerCamelCase ,np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(F"""Only mono-channel audio is supported for input to {self}""" ) a = is_batched_numpy or ( isinstance(__lowerCamelCase ,(list, tuple) ) and (isinstance(raw_speech[0] ,(np.ndarray, tuple, list) )) ) if is_batched: a = [np.asarray(__lowerCamelCase ,dtype=np.floataa ) for speech in raw_speech] elif not is_batched and not isinstance(__lowerCamelCase ,np.ndarray ): a = np.asarray(__lowerCamelCase ,dtype=np.floataa ) elif isinstance(__lowerCamelCase ,np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): a = raw_speech.astype(np.floataa ) # always return batch if not is_batched: a = [raw_speech] # extract fbank features a = [self._extract_mfsc_features(__lowerCamelCase ) for one_waveform in raw_speech] # convert into correct format for padding a = BatchFeature({'''input_features''': features} ) a = self.pad( __lowerCamelCase ,padding=__lowerCamelCase ,max_length=__lowerCamelCase ,truncation=__lowerCamelCase ,pad_to_multiple_of=__lowerCamelCase ,return_attention_mask=__lowerCamelCase ,**__lowerCamelCase ,) # make sure list is in array format a = padded_inputs.get('''input_features''' ) if isinstance(input_features[0] ,__lowerCamelCase ): a = [np.asarray(__lowerCamelCase ,dtype=np.floataa ) for feature in input_features] a = padded_inputs.get('''attention_mask''' ) if attention_mask is not None: a = [np.asarray(__lowerCamelCase ,dtype=np.intaa ) for array in attention_mask] if self.normalize_means or self.normalize_vars: a = ( np.array(__lowerCamelCase ,dtype=np.intaa ) if self._get_padding_strategies(__lowerCamelCase ,max_length=__lowerCamelCase ) is not PaddingStrategy.DO_NOT_PAD and padding else None ) a = self.normalize( padded_inputs['''input_features'''] ,attention_mask=__lowerCamelCase ) if return_tensors is not None: a = padded_inputs.convert_to_tensors(__lowerCamelCase ) return padded_inputs
330
from typing import Optional, Tuple, Union import tensorflow as tf from ...activations_tf import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_tf_outputs import ( TFBaseModelOutputWithNoAttention, TFBaseModelOutputWithPoolingAndNoAttention, TFSequenceClassifierOutput, ) from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs from ...tf_utils import shape_list from ...utils import logging from .configuration_regnet import RegNetConfig UpperCamelCase__ : List[Any] = logging.get_logger(__name__) # General docstring UpperCamelCase__ : List[Any] = """RegNetConfig""" # Base docstring UpperCamelCase__ : Dict = """facebook/regnet-y-040""" UpperCamelCase__ : int = [1, 1_088, 7, 7] # Image classification docstring UpperCamelCase__ : Optional[Any] = """facebook/regnet-y-040""" UpperCamelCase__ : Dict = """tabby, tabby cat""" UpperCamelCase__ : Dict = [ """facebook/regnet-y-040""", # See all regnet models at https://huggingface.co/models?filter=regnet ] class lowerCamelCase_ ( tf.keras.layers.Layer ): def __init__( self : List[str] ,__lowerCamelCase : int ,__lowerCamelCase : int = 3 ,__lowerCamelCase : int = 1 ,__lowerCamelCase : int = 1 ,__lowerCamelCase : Optional[str] = "relu" ,**__lowerCamelCase : str ,): '''simple docstring''' super().__init__(**__lowerCamelCase ) # The padding and conv has been verified in # https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb a = tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2 ) a = tf.keras.layers.ConvaD( filters=__lowerCamelCase ,kernel_size=__lowerCamelCase ,strides=__lowerCamelCase ,padding='''VALID''' ,groups=__lowerCamelCase ,use_bias=__lowerCamelCase ,name='''convolution''' ,) a = tf.keras.layers.BatchNormalization(epsilon=1e-5 ,momentum=0.9 ,name='''normalization''' ) a = ACTaFN[activation] if activation is not None else tf.identity def SCREAMING_SNAKE_CASE_ ( self : str ,__lowerCamelCase : List[str] ): '''simple docstring''' a = self.convolution(self.padding(__lowerCamelCase ) ) a = self.normalization(__lowerCamelCase ) a = self.activation(__lowerCamelCase ) return hidden_state class lowerCamelCase_ ( tf.keras.layers.Layer ): def __init__( self : Any ,__lowerCamelCase : RegNetConfig ,**__lowerCamelCase : List[Any] ): '''simple docstring''' super().__init__(**__lowerCamelCase ) a = config.num_channels a = TFRegNetConvLayer( out_channels=config.embedding_size ,kernel_size=3 ,stride=2 ,activation=config.hidden_act ,name='''embedder''' ,) def SCREAMING_SNAKE_CASE_ ( self : Any ,__lowerCamelCase : Optional[Any] ): '''simple docstring''' a = shape_list(__lowerCamelCase )[1] if tf.executing_eagerly() and num_channels != self.num_channels: raise ValueError( '''Make sure that the channel dimension of the pixel values match with the one set in the configuration.''' ) # When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format. # So change the input format from `NCHW` to `NHWC`. # shape = (batch_size, in_height, in_width, in_channels=num_channels) a = tf.transpose(__lowerCamelCase ,perm=(0, 2, 3, 1) ) a = self.embedder(__lowerCamelCase ) return hidden_state class lowerCamelCase_ ( tf.keras.layers.Layer ): def __init__( self : str ,__lowerCamelCase : int ,__lowerCamelCase : int = 2 ,**__lowerCamelCase : Tuple ): '''simple docstring''' super().__init__(**__lowerCamelCase ) a = tf.keras.layers.ConvaD( filters=__lowerCamelCase ,kernel_size=1 ,strides=__lowerCamelCase ,use_bias=__lowerCamelCase ,name='''convolution''' ) a = tf.keras.layers.BatchNormalization(epsilon=1e-5 ,momentum=0.9 ,name='''normalization''' ) def SCREAMING_SNAKE_CASE_ ( self : Dict ,__lowerCamelCase : tf.Tensor ,__lowerCamelCase : bool = False ): '''simple docstring''' return self.normalization(self.convolution(__lowerCamelCase ) ,training=__lowerCamelCase ) class lowerCamelCase_ ( tf.keras.layers.Layer ): def __init__( self : List[Any] ,__lowerCamelCase : int ,__lowerCamelCase : int ,**__lowerCamelCase : str ): '''simple docstring''' super().__init__(**__lowerCamelCase ) a = tf.keras.layers.GlobalAveragePoolingaD(keepdims=__lowerCamelCase ,name='''pooler''' ) a = [ tf.keras.layers.ConvaD(filters=__lowerCamelCase ,kernel_size=1 ,activation='''relu''' ,name='''attention.0''' ), tf.keras.layers.ConvaD(filters=__lowerCamelCase ,kernel_size=1 ,activation='''sigmoid''' ,name='''attention.2''' ), ] def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ,__lowerCamelCase : Optional[Any] ): '''simple docstring''' a = self.pooler(__lowerCamelCase ) for layer_module in self.attention: a = layer_module(__lowerCamelCase ) a = hidden_state * pooled return hidden_state class lowerCamelCase_ ( tf.keras.layers.Layer ): def __init__( self : Union[str, Any] ,__lowerCamelCase : RegNetConfig ,__lowerCamelCase : int ,__lowerCamelCase : int ,__lowerCamelCase : int = 1 ,**__lowerCamelCase : Dict ): '''simple docstring''' super().__init__(**__lowerCamelCase ) a = in_channels != out_channels or stride != 1 a = max(1 ,out_channels // config.groups_width ) a = ( TFRegNetShortCut(__lowerCamelCase ,stride=__lowerCamelCase ,name='''shortcut''' ) if should_apply_shortcut else tf.keras.layers.Activation('''linear''' ,name='''shortcut''' ) ) # `self.layers` instead of `self.layer` because that is a reserved argument. a = [ TFRegNetConvLayer(__lowerCamelCase ,kernel_size=1 ,activation=config.hidden_act ,name='''layer.0''' ), TFRegNetConvLayer( __lowerCamelCase ,stride=__lowerCamelCase ,groups=__lowerCamelCase ,activation=config.hidden_act ,name='''layer.1''' ), TFRegNetConvLayer(__lowerCamelCase ,kernel_size=1 ,activation=__lowerCamelCase ,name='''layer.2''' ), ] a = ACTaFN[config.hidden_act] def SCREAMING_SNAKE_CASE_ ( self : List[str] ,__lowerCamelCase : Union[str, Any] ): '''simple docstring''' a = hidden_state for layer_module in self.layers: a = layer_module(__lowerCamelCase ) a = self.shortcut(__lowerCamelCase ) hidden_state += residual a = self.activation(__lowerCamelCase ) return hidden_state class lowerCamelCase_ ( tf.keras.layers.Layer ): def __init__( self : Dict ,__lowerCamelCase : RegNetConfig ,__lowerCamelCase : int ,__lowerCamelCase : int ,__lowerCamelCase : int = 1 ,**__lowerCamelCase : List[str] ): '''simple docstring''' super().__init__(**__lowerCamelCase ) a = in_channels != out_channels or stride != 1 a = max(1 ,out_channels // config.groups_width ) a = ( TFRegNetShortCut(__lowerCamelCase ,stride=__lowerCamelCase ,name='''shortcut''' ) if should_apply_shortcut else tf.keras.layers.Activation('''linear''' ,name='''shortcut''' ) ) a = [ TFRegNetConvLayer(__lowerCamelCase ,kernel_size=1 ,activation=config.hidden_act ,name='''layer.0''' ), TFRegNetConvLayer( __lowerCamelCase ,stride=__lowerCamelCase ,groups=__lowerCamelCase ,activation=config.hidden_act ,name='''layer.1''' ), TFRegNetSELayer(__lowerCamelCase ,reduced_channels=int(round(in_channels / 4 ) ) ,name='''layer.2''' ), TFRegNetConvLayer(__lowerCamelCase ,kernel_size=1 ,activation=__lowerCamelCase ,name='''layer.3''' ), ] a = ACTaFN[config.hidden_act] def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ,__lowerCamelCase : str ): '''simple docstring''' a = hidden_state for layer_module in self.layers: a = layer_module(__lowerCamelCase ) a = self.shortcut(__lowerCamelCase ) hidden_state += residual a = self.activation(__lowerCamelCase ) return hidden_state class lowerCamelCase_ ( tf.keras.layers.Layer ): def __init__( self : Optional[int] ,__lowerCamelCase : RegNetConfig ,__lowerCamelCase : int ,__lowerCamelCase : int ,__lowerCamelCase : int = 2 ,__lowerCamelCase : int = 2 ,**__lowerCamelCase : Optional[Any] ): '''simple docstring''' super().__init__(**__lowerCamelCase ) a = TFRegNetXLayer if config.layer_type == '''x''' else TFRegNetYLayer a = [ # downsampling is done in the first layer with stride of 2 layer(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ,stride=__lowerCamelCase ,name='''layers.0''' ), *[layer(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ,name=F"""layers.{i+1}""" ) for i in range(depth - 1 )], ] def SCREAMING_SNAKE_CASE_ ( self : Tuple ,__lowerCamelCase : int ): '''simple docstring''' for layer_module in self.layers: a = layer_module(__lowerCamelCase ) return hidden_state class lowerCamelCase_ ( tf.keras.layers.Layer ): def __init__( self : Union[str, Any] ,__lowerCamelCase : RegNetConfig ,**__lowerCamelCase : Optional[Any] ): '''simple docstring''' super().__init__(**__lowerCamelCase ) a = [] # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( TFRegNetStage( __lowerCamelCase ,config.embedding_size ,config.hidden_sizes[0] ,stride=2 if config.downsample_in_first_stage else 1 ,depth=config.depths[0] ,name='''stages.0''' ,) ) a = zip(config.hidden_sizes ,config.hidden_sizes[1:] ) for i, ((in_channels, out_channels), depth) in enumerate(zip(__lowerCamelCase ,config.depths[1:] ) ): self.stages.append(TFRegNetStage(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ,depth=__lowerCamelCase ,name=F"""stages.{i+1}""" ) ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ,__lowerCamelCase : tf.Tensor ,__lowerCamelCase : bool = False ,__lowerCamelCase : bool = True ): '''simple docstring''' a = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: a = hidden_states + (hidden_state,) a = stage_module(__lowerCamelCase ) if output_hidden_states: a = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return TFBaseModelOutputWithNoAttention(last_hidden_state=__lowerCamelCase ,hidden_states=__lowerCamelCase ) @keras_serializable class lowerCamelCase_ ( tf.keras.layers.Layer ): SCREAMING_SNAKE_CASE_ = RegNetConfig def __init__( self : Dict ,__lowerCamelCase : Optional[int] ,**__lowerCamelCase : Optional[Any] ): '''simple docstring''' super().__init__(**__lowerCamelCase ) a = config a = TFRegNetEmbeddings(__lowerCamelCase ,name='''embedder''' ) a = TFRegNetEncoder(__lowerCamelCase ,name='''encoder''' ) a = tf.keras.layers.GlobalAveragePoolingaD(keepdims=__lowerCamelCase ,name='''pooler''' ) @unpack_inputs def SCREAMING_SNAKE_CASE_ ( self : Tuple ,__lowerCamelCase : tf.Tensor ,__lowerCamelCase : Optional[bool] = None ,__lowerCamelCase : Optional[bool] = None ,__lowerCamelCase : bool = False ,): '''simple docstring''' a = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) a = return_dict if return_dict is not None else self.config.use_return_dict a = self.embedder(__lowerCamelCase ,training=__lowerCamelCase ) a = self.encoder( __lowerCamelCase ,output_hidden_states=__lowerCamelCase ,return_dict=__lowerCamelCase ,training=__lowerCamelCase ) a = encoder_outputs[0] a = self.pooler(__lowerCamelCase ) # Change to NCHW output format have uniformity in the modules a = tf.transpose(__lowerCamelCase ,perm=(0, 3, 1, 2) ) a = tf.transpose(__lowerCamelCase ,perm=(0, 3, 1, 2) ) # Change the other hidden state outputs to NCHW as well if output_hidden_states: a = tuple([tf.transpose(__lowerCamelCase ,perm=(0, 3, 1, 2) ) for h in encoder_outputs[1]] ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=__lowerCamelCase ,pooler_output=__lowerCamelCase ,hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states ,) class lowerCamelCase_ ( a_ ): SCREAMING_SNAKE_CASE_ = RegNetConfig SCREAMING_SNAKE_CASE_ = 'regnet' SCREAMING_SNAKE_CASE_ = 'pixel_values' @property def SCREAMING_SNAKE_CASE_ ( self : str ): '''simple docstring''' return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 2_24, 2_24) ,dtype=tf.floataa )} UpperCamelCase__ : Union[str, Any] = R""" Parameters: This model is a Tensorflow [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and behavior. config ([`RegNetConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights. """ UpperCamelCase__ : List[str] = R""" Args: pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`ConveNextImageProcessor.__call__`] for details. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. """ @add_start_docstrings( 'The bare RegNet model outputting raw features without any specific head on top.' , a_ , ) class lowerCamelCase_ ( a_ ): def __init__( self : Optional[int] ,__lowerCamelCase : RegNetConfig ,*__lowerCamelCase : int ,**__lowerCamelCase : Union[str, Any] ): '''simple docstring''' super().__init__(__lowerCamelCase ,*__lowerCamelCase ,**__lowerCamelCase ) a = TFRegNetMainLayer(__lowerCamelCase ,name='''regnet''' ) @unpack_inputs @add_start_docstrings_to_model_forward(__lowerCamelCase ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC ,output_type=__lowerCamelCase ,config_class=_CONFIG_FOR_DOC ,modality='''vision''' ,expected_output=_EXPECTED_OUTPUT_SHAPE ,) def SCREAMING_SNAKE_CASE_ ( self : Any ,__lowerCamelCase : tf.Tensor ,__lowerCamelCase : Optional[bool] = None ,__lowerCamelCase : Optional[bool] = None ,__lowerCamelCase : List[str]=False ,): '''simple docstring''' a = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) a = return_dict if return_dict is not None else self.config.use_return_dict a = self.regnet( pixel_values=__lowerCamelCase ,output_hidden_states=__lowerCamelCase ,return_dict=__lowerCamelCase ,training=__lowerCamelCase ,) if not return_dict: return (outputs[0],) + outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=outputs.last_hidden_state ,pooler_output=outputs.pooler_output ,hidden_states=outputs.hidden_states ,) @add_start_docstrings( '\n RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n ' , a_ , ) class lowerCamelCase_ ( a_ , a_ ): def __init__( self : Optional[int] ,__lowerCamelCase : RegNetConfig ,*__lowerCamelCase : str ,**__lowerCamelCase : Any ): '''simple docstring''' super().__init__(__lowerCamelCase ,*__lowerCamelCase ,**__lowerCamelCase ) a = config.num_labels a = TFRegNetMainLayer(__lowerCamelCase ,name='''regnet''' ) # classification head a = [ tf.keras.layers.Flatten(), tf.keras.layers.Dense(config.num_labels ,name='''classifier.1''' ) if config.num_labels > 0 else tf.identity, ] @unpack_inputs @add_start_docstrings_to_model_forward(__lowerCamelCase ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT ,output_type=__lowerCamelCase ,config_class=_CONFIG_FOR_DOC ,expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT ,) def SCREAMING_SNAKE_CASE_ ( self : Tuple ,__lowerCamelCase : tf.Tensor = None ,__lowerCamelCase : tf.Tensor = None ,__lowerCamelCase : bool = None ,__lowerCamelCase : bool = None ,__lowerCamelCase : Dict=False ,): '''simple docstring''' a = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) a = return_dict if return_dict is not None else self.config.use_return_dict a = self.regnet( __lowerCamelCase ,output_hidden_states=__lowerCamelCase ,return_dict=__lowerCamelCase ,training=__lowerCamelCase ) a = outputs.pooler_output if return_dict else outputs[1] a = self.classifier[0](__lowerCamelCase ) a = self.classifier[1](__lowerCamelCase ) a = None if labels is None else self.hf_compute_loss(labels=__lowerCamelCase ,logits=__lowerCamelCase ) if not return_dict: a = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return TFSequenceClassifierOutput(loss=__lowerCamelCase ,logits=__lowerCamelCase ,hidden_states=outputs.hidden_states )
330
1
import argparse import dataclasses import json import logging import os import shutil from typing import List, Optional import datasets from accelerate import Accelerator from datasets import load_dataset from finetuning import finetune from tqdm.auto import tqdm import transformers from transformers import AutoConfig, set_seed from transformers.trainer_utils import IntervalStrategy UpperCamelCase__ : Optional[int] = logging.getLogger(__name__) UpperCamelCase__ : List[Any] = """pytorch_model.bin""" @dataclasses.dataclass class lowerCamelCase_ : SCREAMING_SNAKE_CASE_ = dataclasses.field( metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models.'} ) SCREAMING_SNAKE_CASE_ = dataclasses.field( default=a_ , metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co.'} , ) @dataclasses.dataclass class lowerCamelCase_ : SCREAMING_SNAKE_CASE_ = dataclasses.field(metadata={'help': 'A csv or a json file containing the training data.'} ) SCREAMING_SNAKE_CASE_ = dataclasses.field(metadata={'help': 'A csv or a json file containing the data to predict on.'} ) SCREAMING_SNAKE_CASE_ = dataclasses.field( default=a_ , metadata={'help': 'A csv or a json file containing the validation data.'} ) SCREAMING_SNAKE_CASE_ = dataclasses.field( default=a_ , metadata={'help': 'The name of the task to train on.'} , ) SCREAMING_SNAKE_CASE_ = dataclasses.field( default=a_ , metadata={'help': 'The list of labels for the task.'} ) @dataclasses.dataclass class lowerCamelCase_ : SCREAMING_SNAKE_CASE_ = dataclasses.field( metadata={'help': 'The output directory where the model predictions and checkpoints will be written.'} ) SCREAMING_SNAKE_CASE_ = dataclasses.field( default='accuracy' , metadata={'help': 'The evaluation metric used for the task.'} ) SCREAMING_SNAKE_CASE_ = dataclasses.field( default='no' , metadata={ 'help': 'The evaluation strategy to adopt during training. Possible values are: ["no", "step", "epoch]' } , ) SCREAMING_SNAKE_CASE_ = dataclasses.field( default=10 , metadata={'help': 'Number of evaluation calls with no improvement after which training will be stopped.'} , ) SCREAMING_SNAKE_CASE_ = dataclasses.field( default=0.0 , metadata={ 'help': 'How much the specified evaluation metric must improve to satisfy early stopping conditions.' } , ) SCREAMING_SNAKE_CASE_ = dataclasses.field( default=a_ , metadata={'help': 'Whether to filter the pseudo-labeled data based on the confidence score.'} , ) SCREAMING_SNAKE_CASE_ = dataclasses.field( default=a_ , metadata={'help': 'Whether to filter the pseudo-labeled data based on the validation performance.'} , ) SCREAMING_SNAKE_CASE_ = dataclasses.field( default=a_ , metadata={'help': 'Whether to fine-tune on labeled data after pseudo training.'} , ) SCREAMING_SNAKE_CASE_ = dataclasses.field( default=0.0 , metadata={'help': 'Confidence threshold for pseudo-labeled data filtering.'} , ) SCREAMING_SNAKE_CASE_ = dataclasses.field( default=1_00 , metadata={'help': 'Number of evaluation calls with no improvement after which training will be stopped.'} , ) SCREAMING_SNAKE_CASE_ = dataclasses.field( default=a_ , metadata={'help': 'Random seed for initialization.'} , ) def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_, snake_case_, snake_case_, snake_case_ ) -> Dict: """simple docstring""" a = datasets.concatenate_datasets([infer_input, infer_output], axis=1 ) if args.do_filter_by_confidence: a = dataset.filter(lambda snake_case_ : example["probability"] > args.confidence_threshold ) if args.do_filter_by_val_performance: assert eval_result >= 0.0 and eval_result <= 1.0 a = int(eval_result * len(snake_case_ ) ) print(snake_case_ ) a = dataset.sort('''probability''', reverse=snake_case_ ) a = dataset.select(range(snake_case_ ) ) a = dataset.remove_columns(['''label''', '''probability'''] ) a = dataset.rename_column('''prediction''', '''label''' ) a = dataset.map(lambda snake_case_ : {"label": idalabel[example["label"]]} ) a = dataset.shuffle(seed=args.seed ) a = os.path.join(snake_case_, f"""train_pseudo.{args.data_file_extension}""" ) if args.data_file_extension == "csv": dataset.to_csv(snake_case_, index=snake_case_ ) else: dataset.to_json(snake_case_ ) def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_, snake_case_, **snake_case_ ) -> Optional[Any]: """simple docstring""" a = Accelerator() # Make one log on every process with the configuration for debugging. logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO, ) logger.info(accelerator.state ) # Setup logging, we only want one process per machine to log things on the # screen. accelerator.is_local_main_process is only True for one process per # machine. logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR ) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_info() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() a = STModelArguments(model_name_or_path=snake_case_ ) a = STDataArguments(train_file=snake_case_, infer_file=snake_case_ ) a = STTrainingArguments(output_dir=snake_case_ ) a = argparse.Namespace() for arg_class in (model_args, data_args, training_args): for key, value in vars(snake_case_ ).items(): setattr(snake_case_, snake_case_, snake_case_ ) for key, value in kwargs.items(): if hasattr(snake_case_, snake_case_ ): setattr(snake_case_, snake_case_, snake_case_ ) # Sanity checks a = {} a = None # You need to provide the training data and the data to predict on assert args.train_file is not None assert args.infer_file is not None a = args.train_file a = args.infer_file if args.evaluation_strategy != IntervalStrategy.NO.value: assert args.eval_file is not None a = args.eval_file for key in data_files: a = data_files[key].split('''.''' )[-1] assert extension in ["csv", "json"], f"""`{key}_file` should be a csv or a json file.""" if args.data_file_extension is None: a = extension else: assert extension == args.data_file_extension, f"""`{key}_file` should be a {args.data_file_extension} file`.""" assert ( args.eval_metric in datasets.list_metrics() ), f"""{args.eval_metric} not in the list of supported metrics {datasets.list_metrics()}.""" # If passed along, set the training seed now. if args.seed is not None: set_seed(args.seed ) logger.info('''Creating the initial data directory for self-training...''' ) a = f"""{args.output_dir}/self-train_iter-{{}}""".format a = data_dir_format(0 ) if accelerator.is_main_process: if args.output_dir is not None: os.makedirs(args.output_dir, exist_ok=snake_case_ ) os.makedirs(snake_case_, exist_ok=snake_case_ ) accelerator.wait_for_everyone() a = None a = None a = 0 a = False # Show the progress bar a = tqdm(range(args.max_selftrain_iterations ), disable=not accelerator.is_local_main_process ) # Self-train for iteration in range(0, int(args.max_selftrain_iterations ) ): a = data_dir_format(snake_case_ ) assert os.path.exists(snake_case_ ) # Stage 1: initial fine-tuning for iteration = 0 or pseudo-training for # iteration > 0 a = os.path.join(snake_case_, '''stage-1''' ) a = { '''accelerator''': accelerator, '''model_name_or_path''': args.model_name_or_path, '''cache_dir''': args.cache_dir, '''do_train''': True, '''train_file''': data_files['''train'''] if iteration == 0 else data_files['''train_pseudo'''], '''do_eval''': True if args.eval_file is not None else False, '''eval_file''': data_files['''eval'''], '''do_predict''': True, '''infer_file''': data_files['''infer'''], '''task_name''': args.task_name, '''label_list''': args.label_list, '''output_dir''': current_output_dir, '''eval_metric''': args.eval_metric, '''evaluation_strategy''': args.evaluation_strategy, '''early_stopping_patience''': args.early_stopping_patience, '''early_stopping_threshold''': args.early_stopping_threshold, '''seed''': args.seed, } # Add additional training arguments for key, value in kwargs.items(): if key not in arguments_dict and not hasattr(snake_case_, snake_case_ ): arguments_dict.update({key: value} ) a = os.path.join(snake_case_, '''best-checkpoint''', snake_case_ ) if os.path.exists(snake_case_ ): logger.info( '''Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 1.''', snake_case_, snake_case_, ) else: logger.info('''***** Running self-training: iteration: %d, stage: 1 *****''', snake_case_ ) finetune(**snake_case_ ) accelerator.wait_for_everyone() assert os.path.exists(snake_case_ ) logger.info('''Self-training job completed: iteration: %d, stage: 1.''', snake_case_ ) if iteration > 0 and args.finetune_on_labeled_data: # Stage 2 (optional): fine-tuning on the original labeled data a = os.path.join(snake_case_, '''best-checkpoint''' ) a = os.path.join(snake_case_, '''stage-2''' ) # Update arguments_dict a = model_path a = data_files['''train'''] a = current_output_dir a = os.path.join(snake_case_, '''best-checkpoint''', snake_case_ ) if os.path.exists(snake_case_ ): logger.info( '''Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 2.''', snake_case_, snake_case_, ) else: logger.info('''***** Running self-training: iteration: %d, stage: 2 *****''', snake_case_ ) finetune(**snake_case_ ) accelerator.wait_for_everyone() assert os.path.exists(snake_case_ ) logger.info('''Self-training job completed: iteration: %d, stage: 2.''', snake_case_ ) a = iteration a = data_dir_format(iteration + 1 ) a = AutoConfig.from_pretrained(os.path.join(snake_case_, '''best-checkpoint''' ) ) a = config.idalabel a = os.path.join(snake_case_, '''eval_results_best-checkpoint.json''' ) a = os.path.join(snake_case_, '''test_results_best-checkpoint.json''' ) assert os.path.exists(snake_case_ ) with open(snake_case_, '''r''' ) as f: a = float(json.load(snake_case_ )[args.eval_metric] ) a = os.path.join(snake_case_, '''infer_output_best-checkpoint.csv''' ) assert os.path.exists(snake_case_ ) # Loading the dataset from local csv or json files. a = load_dataset(args.data_file_extension, data_files={'''data''': data_files['''infer''']} )['''data'''] a = load_dataset('''csv''', data_files={'''data''': infer_output_file} )['''data'''] if accelerator.is_main_process: os.makedirs(snake_case_, exist_ok=snake_case_ ) shutil.copy(snake_case_, os.path.join(snake_case_, f"""eval_results_iter-{iteration}.json""" ) ) if os.path.exists(snake_case_ ): shutil.copy(snake_case_, os.path.join(snake_case_, f"""test_results_iter-{iteration}.json""" ) ) create_pseudo_labeled_data(snake_case_, snake_case_, snake_case_, snake_case_, snake_case_, snake_case_ ) accelerator.wait_for_everyone() a = os.path.join(snake_case_, f"""train_pseudo.{args.data_file_extension}""" ) if args.evaluation_strategy != IntervalStrategy.NO.value: a = eval_result if best_iteration is None: a = new_iteration a = new_eval_result else: if new_eval_result - best_eval_result > args.early_stopping_threshold: a = new_iteration a = new_eval_result a = 0 else: if new_eval_result == best_eval_result: a = new_iteration a = new_eval_result early_stopping_patience_counter += 1 if early_stopping_patience_counter >= args.early_stopping_patience: a = True progress_bar.update(1 ) if should_training_stop: break if best_iteration is not None: # Save the best iteration logger.info('''Best iteration: %d''', snake_case_ ) logger.info('''Best evaluation result: %s = %f''', args.eval_metric, snake_case_ ) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(snake_case_, f"""eval_results_iter-{iteration}.json""" ), os.path.join(snake_case_, '''eval_results_best-iteration.json''' ), ) else: # Assume that the last iteration is the best logger.info('''Best iteration: %d''', args.max_selftrain_iterations - 1 ) logger.info('''Best evaluation result: %s = %f''', args.eval_metric, snake_case_ ) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(snake_case_, f"""eval_results_iter-{args.max_selftrain_iterations - 1}.json""" ), os.path.join(snake_case_, '''eval_results_best-iteration.json''' ), )
330
from typing import List from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase__ : Union[str, Any] = logging.get_logger(__name__) UpperCamelCase__ : List[str] = { """snap-research/efficientformer-l1-300""": ( """https://huggingface.co/snap-research/efficientformer-l1-300/resolve/main/config.json""" ), } class lowerCamelCase_ ( a_ ): SCREAMING_SNAKE_CASE_ = 'efficientformer' def __init__( self : Optional[int] ,__lowerCamelCase : List[int] = [3, 2, 6, 4] ,__lowerCamelCase : List[int] = [48, 96, 2_24, 4_48] ,__lowerCamelCase : List[bool] = [True, True, True, True] ,__lowerCamelCase : int = 4_48 ,__lowerCamelCase : int = 32 ,__lowerCamelCase : int = 4 ,__lowerCamelCase : int = 7 ,__lowerCamelCase : int = 5 ,__lowerCamelCase : int = 8 ,__lowerCamelCase : int = 4 ,__lowerCamelCase : float = 0.0 ,__lowerCamelCase : int = 16 ,__lowerCamelCase : int = 3 ,__lowerCamelCase : int = 3 ,__lowerCamelCase : int = 3 ,__lowerCamelCase : int = 2 ,__lowerCamelCase : int = 1 ,__lowerCamelCase : float = 0.0 ,__lowerCamelCase : int = 1 ,__lowerCamelCase : bool = True ,__lowerCamelCase : bool = True ,__lowerCamelCase : float = 1e-5 ,__lowerCamelCase : str = "gelu" ,__lowerCamelCase : float = 0.02 ,__lowerCamelCase : float = 1e-12 ,__lowerCamelCase : int = 2_24 ,__lowerCamelCase : float = 1e-05 ,**__lowerCamelCase : Dict ,): '''simple docstring''' super().__init__(**__lowerCamelCase ) a = hidden_act a = hidden_dropout_prob a = hidden_sizes a = num_hidden_layers a = num_attention_heads a = initializer_range a = layer_norm_eps a = patch_size a = num_channels a = depths a = mlp_expansion_ratio a = downsamples a = dim a = key_dim a = attention_ratio a = resolution a = pool_size a = downsample_patch_size a = downsample_stride a = downsample_pad a = drop_path_rate a = num_metaad_blocks a = distillation a = use_layer_scale a = layer_scale_init_value a = image_size a = batch_norm_eps
330
1
def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> int: """simple docstring""" a = '''''' for i in table: res += inp[i - 1] return res def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> int: """simple docstring""" return data[1:] + data[0] def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> List[str]: """simple docstring""" a = '''''' for i in range(len(snake_case_ ) ): if a[i] == b[i]: res += "0" else: res += "1" return res def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> Dict: """simple docstring""" a = int('''0b''' + data[0] + data[-1], 2 ) a = int('''0b''' + data[1:3], 2 ) return bin(s[row][col] )[2:] def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_, snake_case_, snake_case_ ) -> Optional[int]: """simple docstring""" a = message[:4] a = message[4:] a = apply_table(snake_case_, snake_case_ ) a = xor(snake_case_, snake_case_ ) a = apply_sbox(snake_case_, temp[:4] ) # noqa: E741 a = apply_sbox(snake_case_, temp[4:] ) a = '''0''' * (2 - len(snake_case_ )) + l # noqa: E741 a = '''0''' * (2 - len(snake_case_ )) + r a = apply_table(l + r, snake_case_ ) a = xor(snake_case_, snake_case_ ) return temp + right if __name__ == "__main__": UpperCamelCase__ : int = input("""Enter 10 bit key: """) UpperCamelCase__ : Union[str, Any] = input("""Enter 8 bit message: """) UpperCamelCase__ : Dict = [6, 3, 7, 4, 8, 5, 10, 9] UpperCamelCase__ : Union[str, Any] = [3, 5, 2, 7, 4, 10, 1, 9, 8, 6] UpperCamelCase__ : Optional[int] = [2, 4, 3, 1] UpperCamelCase__ : List[Any] = [2, 6, 3, 1, 4, 8, 5, 7] UpperCamelCase__ : str = [4, 1, 3, 5, 7, 2, 8, 6] UpperCamelCase__ : List[Any] = [4, 1, 2, 3, 2, 3, 4, 1] UpperCamelCase__ : int = [[1, 0, 3, 2], [3, 2, 1, 0], [0, 2, 1, 3], [3, 1, 3, 2]] UpperCamelCase__ : Dict = [[0, 1, 2, 3], [2, 0, 1, 3], [3, 0, 1, 0], [2, 1, 0, 3]] # key generation UpperCamelCase__ : Optional[Any] = apply_table(key, paa_table) UpperCamelCase__ : str = temp[:5] UpperCamelCase__ : List[Any] = temp[5:] UpperCamelCase__ : Dict = left_shift(left) UpperCamelCase__ : Any = left_shift(right) UpperCamelCase__ : Optional[Any] = apply_table(left + right, pa_table) UpperCamelCase__ : List[str] = left_shift(left) UpperCamelCase__ : int = left_shift(right) UpperCamelCase__ : List[str] = left_shift(left) UpperCamelCase__ : Dict = left_shift(right) UpperCamelCase__ : List[str] = apply_table(left + right, pa_table) # encryption UpperCamelCase__ : Tuple = apply_table(message, IP) UpperCamelCase__ : Optional[Any] = function(expansion, sa, sa, keya, temp) UpperCamelCase__ : Optional[int] = temp[4:] + temp[:4] UpperCamelCase__ : Any = function(expansion, sa, sa, keya, temp) UpperCamelCase__ : Tuple = apply_table(temp, IP_inv) print("""Cipher text is:""", CT) # decryption UpperCamelCase__ : Union[str, Any] = apply_table(CT, IP) UpperCamelCase__ : List[str] = function(expansion, sa, sa, keya, temp) UpperCamelCase__ : Optional[Any] = temp[4:] + temp[:4] UpperCamelCase__ : Optional[int] = function(expansion, sa, sa, keya, temp) UpperCamelCase__ : Any = apply_table(temp, IP_inv) print("""Plain text after decypting is:""", PT)
330
import argparse from typing import Dict import tensorflow as tf import torch from tqdm import tqdm from transformers import BigBirdPegasusConfig, BigBirdPegasusForConditionalGeneration UpperCamelCase__ : Any = [ # tf -> hf ("""/""", """."""), ("""layer_""", """layers."""), ("""kernel""", """weight"""), ("""beta""", """bias"""), ("""gamma""", """weight"""), ("""pegasus""", """model"""), ] UpperCamelCase__ : Optional[Any] = [ (""".output.dense""", """.fc2"""), ("""intermediate.LayerNorm""", """final_layer_norm"""), ("""intermediate.dense""", """fc1"""), ] UpperCamelCase__ : Optional[Any] = ( INIT_COMMON + [ ("""attention.self.LayerNorm""", """self_attn_layer_norm"""), ("""attention.output.dense""", """self_attn.out_proj"""), ("""attention.self""", """self_attn"""), ("""attention.encdec.LayerNorm""", """encoder_attn_layer_norm"""), ("""attention.encdec_output.dense""", """encoder_attn.out_proj"""), ("""attention.encdec""", """encoder_attn"""), ("""key""", """k_proj"""), ("""value""", """v_proj"""), ("""query""", """q_proj"""), ("""decoder.LayerNorm""", """decoder.layernorm_embedding"""), ] + END_COMMON ) UpperCamelCase__ : List[str] = ( INIT_COMMON + [ ("""embeddings.word_embeddings""", """shared.weight"""), ("""embeddings.position_embeddings""", """embed_positions.weight"""), ("""attention.self.LayerNorm""", """self_attn_layer_norm"""), ("""attention.output.dense""", """self_attn.output"""), ("""attention.self""", """self_attn.self"""), ("""encoder.LayerNorm""", """encoder.layernorm_embedding"""), ] + END_COMMON ) UpperCamelCase__ : Optional[int] = [ """encdec/key/bias""", """encdec/query/bias""", """encdec/value/bias""", """self/key/bias""", """self/query/bias""", """self/value/bias""", """encdec_output/dense/bias""", """attention/output/dense/bias""", ] def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> List[Any]: """simple docstring""" for tf_name, hf_name in patterns: a = k.replace(snake_case_, snake_case_ ) return k def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> BigBirdPegasusForConditionalGeneration: """simple docstring""" a = BigBirdPegasusConfig(**snake_case_ ) a = BigBirdPegasusForConditionalGeneration(snake_case_ ) a = torch_model.state_dict() a = {} # separating decoder weights a = {k: tf_weights[k] for k in tf_weights if k.startswith('''pegasus/decoder''' )} a = {k: tf_weights[k] for k in tf_weights if not k.startswith('''pegasus/decoder''' )} for k, v in tqdm(decoder_weights.items(), '''tf -> hf conversion''' ): a = [k.endswith(snake_case_ ) for ending in KEYS_TO_IGNORE] if any(snake_case_ ): continue a = DECODER_PATTERNS a = rename_state_dict_key(snake_case_, snake_case_ ) if new_k not in state_dict: raise ValueError(f"""could not find new key {new_k} in state dict. (converted from {k})""" ) if any(True if i in k else False for i in ['''dense''', '''query''', '''key''', '''value'''] ): a = v.T a = torch.from_numpy(snake_case_ ) assert v.shape == state_dict[new_k].shape, f"""{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}""" for k, v in tqdm(remaining_weights.items(), '''tf -> hf conversion''' ): a = [k.endswith(snake_case_ ) for ending in KEYS_TO_IGNORE] if any(snake_case_ ): continue a = REMAINING_PATTERNS a = rename_state_dict_key(snake_case_, snake_case_ ) if new_k not in state_dict and k != "pegasus/embeddings/position_embeddings": raise ValueError(f"""could not find new key {new_k} in state dict. (converted from {k})""" ) if any(True if i in k else False for i in ['''dense''', '''query''', '''key''', '''value'''] ): a = v.T a = torch.from_numpy(snake_case_ ) if k != "pegasus/embeddings/position_embeddings": assert v.shape == state_dict[new_k].shape, f"""{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}""" a = mapping['''model.embed_positions.weight'''] a = mapping.pop('''model.embed_positions.weight''' ) a , a = torch_model.load_state_dict(snake_case_, strict=snake_case_ ) a = [ k for k in missing if k not in [ '''final_logits_bias''', '''model.encoder.embed_tokens.weight''', '''model.decoder.embed_tokens.weight''', '''lm_head.weight''', ] ] assert unexpected_missing == [], f"""no matches found for the following torch keys {unexpected_missing}""" assert extra == [], f"""no matches found for the following tf keys {extra}""" return torch_model def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> Dict: """simple docstring""" a = tf.train.list_variables(snake_case_ ) a = {} a = ['''global_step'''] for name, shape in tqdm(snake_case_, desc='''converting tf checkpoint to dict''' ): a = any(pat in name for pat in ignore_name ) if skip_key: continue a = tf.train.load_variable(snake_case_, snake_case_ ) a = array return tf_weights def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_ ) -> int: """simple docstring""" a = get_tf_weights_as_numpy(snake_case_ ) a = convert_bigbird_pegasus(snake_case_, snake_case_ ) torch_model.save_pretrained(snake_case_ ) if __name__ == "__main__": UpperCamelCase__ : str = argparse.ArgumentParser() parser.add_argument("""--tf_ckpt_path""", type=str, help="""passed to tf.train.list_variables""") parser.add_argument("""--save_dir""", default=None, type=str, help="""Path to the output PyTorch model.""") UpperCamelCase__ : int = parser.parse_args() UpperCamelCase__ : Tuple = {} convert_bigbird_pegasus_ckpt_to_pytorch(args.tf_ckpt_path, args.save_dir, config_update=config_update)
330
1
def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> Union[str, Any]: """simple docstring""" stooge(snake_case_, 0, len(snake_case_ ) - 1 ) return arr def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_ ) -> Optional[Any]: """simple docstring""" if i >= h: return # If first element is smaller than the last then swap them if arr[i] > arr[h]: a , a = arr[h], arr[i] # If there are more than 2 elements in the array if h - i + 1 > 2: a = (int)((h - i + 1) / 3 ) # Recursively sort first 2/3 elements stooge(snake_case_, snake_case_, (h - t) ) # Recursively sort last 2/3 elements stooge(snake_case_, i + t, (snake_case_) ) # Recursively sort first 2/3 elements stooge(snake_case_, snake_case_, (h - t) ) if __name__ == "__main__": UpperCamelCase__ : Dict = input("""Enter numbers separated by a comma:\n""").strip() UpperCamelCase__ : Optional[int] = [int(item) for item in user_input.split(""",""")] print(stooge_sort(unsorted))
330
import re def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> str: """simple docstring""" if len(re.findall('''[ATCG]''', snake_case_ ) ) != len(snake_case_ ): raise ValueError('''Invalid Strand''' ) return dna.translate(dna.maketrans('''ATCG''', '''TAGC''' ) ) if __name__ == "__main__": import doctest doctest.testmod()
330
1
from ...processing_utils import ProcessorMixin class lowerCamelCase_ ( a_ ): SCREAMING_SNAKE_CASE_ = ['image_processor', 'feature_extractor'] SCREAMING_SNAKE_CASE_ = 'TvltImageProcessor' SCREAMING_SNAKE_CASE_ = 'TvltFeatureExtractor' def __init__( self : List[Any] ,__lowerCamelCase : Optional[Any] ,__lowerCamelCase : str ): '''simple docstring''' super().__init__(image_processor=__lowerCamelCase ,feature_extractor=__lowerCamelCase ) a = image_processor a = feature_extractor def __call__( self : Dict ,__lowerCamelCase : Optional[int]=None ,__lowerCamelCase : Optional[int]=None ,__lowerCamelCase : Optional[int]=None ,__lowerCamelCase : List[str]=None ,__lowerCamelCase : Dict=False ,__lowerCamelCase : Union[str, Any]=False ,*__lowerCamelCase : Tuple ,**__lowerCamelCase : List[str] ,): '''simple docstring''' if images is None and audio is None: raise ValueError('''You need to specify either an `images` or `audio` input to process.''' ) a = None if images is not None: a = self.image_processor(__lowerCamelCase ,mask_pixel=__lowerCamelCase ,*__lowerCamelCase ,**__lowerCamelCase ) if images_mixed is not None: a = self.image_processor(__lowerCamelCase ,is_mixed=__lowerCamelCase ,*__lowerCamelCase ,**__lowerCamelCase ) if audio is not None: a = self.feature_extractor( __lowerCamelCase ,*__lowerCamelCase ,sampling_rate=__lowerCamelCase ,mask_audio=__lowerCamelCase ,**__lowerCamelCase ) a = {} if audio is not None: output_dict.update(__lowerCamelCase ) if images is not None: output_dict.update(__lowerCamelCase ) if images_mixed_dict is not None: output_dict.update(__lowerCamelCase ) return output_dict @property def SCREAMING_SNAKE_CASE_ ( self : Dict ): '''simple docstring''' a = self.image_processor.model_input_names a = self.feature_extractor.model_input_names return list(dict.fromkeys(image_processor_input_names + feature_extractor_input_names ) )
330
from __future__ import annotations from collections.abc import Sequence from typing import Literal def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> str | Literal[False]: """simple docstring""" a = list(snake_case_ ) a = list(snake_case_ ) a = 0 for i in range(len(snake_case_ ) ): if lista[i] != lista[i]: count += 1 a = '''_''' if count > 1: return False else: return "".join(snake_case_ ) def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> list[str]: """simple docstring""" a = [] while True: a = ['''$'''] * len(snake_case_ ) a = [] for i in range(len(snake_case_ ) ): for j in range(i + 1, len(snake_case_ ) ): a = compare_string(binary[i], binary[j] ) if k is False: a = '''*''' a = '''*''' temp.append('''X''' ) for i in range(len(snake_case_ ) ): if checka[i] == "$": pi.append(binary[i] ) if len(snake_case_ ) == 0: return pi a = list(set(snake_case_ ) ) def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> list[str]: """simple docstring""" a = [] for minterm in minterms: a = '''''' for _ in range(snake_case_ ): a = str(minterm % 2 ) + string minterm //= 2 temp.append(snake_case_ ) return temp def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_ ) -> bool: """simple docstring""" a = list(snake_case_ ) a = list(snake_case_ ) a = 0 for i in range(len(snake_case_ ) ): if lista[i] != lista[i]: count_n += 1 return count_n == count def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> list[str]: """simple docstring""" a = [] a = [0] * len(snake_case_ ) for i in range(len(chart[0] ) ): a = 0 a = -1 for j in range(len(snake_case_ ) ): if chart[j][i] == 1: count += 1 a = j if count == 1: a = 1 for i in range(len(snake_case_ ) ): if select[i] == 1: for j in range(len(chart[0] ) ): if chart[i][j] == 1: for k in range(len(snake_case_ ) ): a = 0 temp.append(prime_implicants[i] ) while True: a = 0 a = -1 a = 0 for i in range(len(snake_case_ ) ): a = chart[i].count(1 ) if count_n > max_n: a = count_n a = i if max_n == 0: return temp temp.append(prime_implicants[rem] ) for i in range(len(chart[0] ) ): if chart[rem][i] == 1: for j in range(len(snake_case_ ) ): a = 0 def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> list[list[int]]: """simple docstring""" a = [[0 for x in range(len(snake_case_ ) )] for x in range(len(snake_case_ ) )] for i in range(len(snake_case_ ) ): a = prime_implicants[i].count('''_''' ) for j in range(len(snake_case_ ) ): if is_for_table(prime_implicants[i], binary[j], snake_case_ ): a = 1 return chart def SCREAMING_SNAKE_CASE__ ( ) -> None: """simple docstring""" a = int(input('''Enter the no. of variables\n''' ) ) a = [ float(snake_case_ ) for x in input( '''Enter the decimal representation of Minterms \'Spaces Separated\'\n''' ).split() ] a = decimal_to_binary(snake_case_, snake_case_ ) a = check(snake_case_ ) print('''Prime Implicants are:''' ) print(snake_case_ ) a = prime_implicant_chart(snake_case_, snake_case_ ) a = selection(snake_case_, snake_case_ ) print('''Essential Prime Implicants are:''' ) print(snake_case_ ) if __name__ == "__main__": import doctest doctest.testmod() main()
330
1
import itertools import json import os import unittest from transformers import AddedToken, RobertaTokenizer, RobertaTokenizerFast from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowerCamelCase_ ( a_ , unittest.TestCase ): SCREAMING_SNAKE_CASE_ = RobertaTokenizer SCREAMING_SNAKE_CASE_ = RobertaTokenizerFast SCREAMING_SNAKE_CASE_ = True SCREAMING_SNAKE_CASE_ = {'cls_token': '<s>'} def SCREAMING_SNAKE_CASE_ ( self : int ): '''simple docstring''' super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt a = [ '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''\u0120''', '''\u0120l''', '''\u0120n''', '''\u0120lo''', '''\u0120low''', '''er''', '''\u0120lowest''', '''\u0120newer''', '''\u0120wider''', '''<unk>''', ] a = dict(zip(__lowerCamelCase ,range(len(__lowerCamelCase ) ) ) ) a = ['''#version: 0.2''', '''\u0120 l''', '''\u0120l o''', '''\u0120lo w''', '''e r''', ''''''] a = {'''unk_token''': '''<unk>'''} a = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES['''vocab_file'''] ) a = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file ,'''w''' ,encoding='''utf-8''' ) as fp: fp.write(json.dumps(__lowerCamelCase ) + '''\n''' ) with open(self.merges_file ,'''w''' ,encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(__lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ,**__lowerCamelCase : Union[str, Any] ): '''simple docstring''' kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname ,**__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ,**__lowerCamelCase : Union[str, Any] ): '''simple docstring''' kwargs.update(self.special_tokens_map ) return RobertaTokenizerFast.from_pretrained(self.tmpdirname ,**__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ,__lowerCamelCase : Any ): '''simple docstring''' a = '''lower newer''' a = '''lower newer''' return input_text, output_text def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ): '''simple docstring''' a = self.tokenizer_class(self.vocab_file ,self.merges_file ,**self.special_tokens_map ) a = '''lower newer''' a = ['''l''', '''o''', '''w''', '''er''', '''\u0120''', '''n''', '''e''', '''w''', '''er'''] a = tokenizer.tokenize(__lowerCamelCase ) # , add_prefix_space=True) self.assertListEqual(__lowerCamelCase ,__lowerCamelCase ) a = tokens + [tokenizer.unk_token] a = [0, 1, 2, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(__lowerCamelCase ) ,__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : int ): '''simple docstring''' a = self.get_tokenizer() self.assertListEqual(tokenizer.encode('''Hello world!''' ,add_special_tokens=__lowerCamelCase ) ,[0, 3_14_14, 2_32, 3_28, 2] ) self.assertListEqual( tokenizer.encode('''Hello world! cécé herlolip 418''' ,add_special_tokens=__lowerCamelCase ) ,[0, 3_14_14, 2_32, 3_28, 7_40, 11_40, 1_26_95, 69, 4_60_78, 15_88, 2] ,) @slow def SCREAMING_SNAKE_CASE_ ( self : List[str] ): '''simple docstring''' a = self.tokenizer_class.from_pretrained('''roberta-base''' ) a = tokenizer.encode('''sequence builders''' ,add_special_tokens=__lowerCamelCase ) a = tokenizer.encode('''multi-sequence build''' ,add_special_tokens=__lowerCamelCase ) a = tokenizer.encode( '''sequence builders''' ,add_special_tokens=__lowerCamelCase ,add_prefix_space=__lowerCamelCase ) a = tokenizer.encode( '''sequence builders''' ,'''multi-sequence build''' ,add_special_tokens=__lowerCamelCase ,add_prefix_space=__lowerCamelCase ) a = tokenizer.build_inputs_with_special_tokens(__lowerCamelCase ) a = tokenizer.build_inputs_with_special_tokens(__lowerCamelCase ,__lowerCamelCase ) assert encoded_sentence == encoded_text_from_decode assert encoded_pair == encoded_pair_from_decode def SCREAMING_SNAKE_CASE_ ( self : List[str] ): '''simple docstring''' a = self.get_tokenizer() a = '''Encode this sequence.''' a = tokenizer.byte_encoder[''' '''.encode('''utf-8''' )[0]] # Testing encoder arguments a = tokenizer.encode(__lowerCamelCase ,add_special_tokens=__lowerCamelCase ,add_prefix_space=__lowerCamelCase ) a = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertNotEqual(__lowerCamelCase ,__lowerCamelCase ) a = tokenizer.encode(__lowerCamelCase ,add_special_tokens=__lowerCamelCase ,add_prefix_space=__lowerCamelCase ) a = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertEqual(__lowerCamelCase ,__lowerCamelCase ) tokenizer.add_special_tokens({'''bos_token''': '''<s>'''} ) a = tokenizer.encode(__lowerCamelCase ,add_special_tokens=__lowerCamelCase ) a = tokenizer.convert_ids_to_tokens(encoded[1] )[0] self.assertNotEqual(__lowerCamelCase ,__lowerCamelCase ) # Testing spaces after special tokens a = '''<mask>''' tokenizer.add_special_tokens( {'''mask_token''': AddedToken(__lowerCamelCase ,lstrip=__lowerCamelCase ,rstrip=__lowerCamelCase )} ) # mask token has a left space a = tokenizer.convert_tokens_to_ids(__lowerCamelCase ) a = '''Encode <mask> sequence''' a = '''Encode <mask>sequence''' a = tokenizer.encode(__lowerCamelCase ) a = encoded.index(__lowerCamelCase ) a = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertEqual(__lowerCamelCase ,__lowerCamelCase ) a = tokenizer.encode(__lowerCamelCase ) a = encoded.index(__lowerCamelCase ) a = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertNotEqual(__lowerCamelCase ,__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ): '''simple docstring''' pass def SCREAMING_SNAKE_CASE_ ( self : List[str] ): '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): a = self.rust_tokenizer_class.from_pretrained(__lowerCamelCase ,**__lowerCamelCase ) a = self.tokenizer_class.from_pretrained(__lowerCamelCase ,**__lowerCamelCase ) a = '''A, <mask> AllenNLP sentence.''' a = tokenizer_r.encode_plus(__lowerCamelCase ,add_special_tokens=__lowerCamelCase ,return_token_type_ids=__lowerCamelCase ) a = tokenizer_p.encode_plus(__lowerCamelCase ,add_special_tokens=__lowerCamelCase ,return_token_type_ids=__lowerCamelCase ) # token_type_ids should put 0 everywhere self.assertEqual(sum(tokens_r['''token_type_ids'''] ) ,sum(tokens_p['''token_type_ids'''] ) ) # attention_mask should put 1 everywhere, so sum over length should be 1 self.assertEqual( sum(tokens_r['''attention_mask'''] ) / len(tokens_r['''attention_mask'''] ) ,sum(tokens_p['''attention_mask'''] ) / len(tokens_p['''attention_mask'''] ) ,) a = tokenizer_r.convert_ids_to_tokens(tokens_r['''input_ids'''] ) a = tokenizer_p.convert_ids_to_tokens(tokens_p['''input_ids'''] ) # Rust correctly handles the space before the mask while python doesnt self.assertSequenceEqual(tokens_p['''input_ids'''] ,[0, 2_50, 6, 5_02_64, 38_23, 4_87, 2_19_92, 36_45, 4, 2] ) self.assertSequenceEqual(tokens_r['''input_ids'''] ,[0, 2_50, 6, 5_02_64, 38_23, 4_87, 2_19_92, 36_45, 4, 2] ) self.assertSequenceEqual( __lowerCamelCase ,['''<s>''', '''A''', ''',''', '''<mask>''', '''ĠAllen''', '''N''', '''LP''', '''Ġsentence''', '''.''', '''</s>'''] ) self.assertSequenceEqual( __lowerCamelCase ,['''<s>''', '''A''', ''',''', '''<mask>''', '''ĠAllen''', '''N''', '''LP''', '''Ġsentence''', '''.''', '''</s>'''] ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ): '''simple docstring''' for trim_offsets, add_prefix_space in itertools.product([True, False] ,repeat=2 ): a = self.rust_tokenizer_class.from_pretrained( self.tmpdirname ,use_fast=__lowerCamelCase ,add_prefix_space=__lowerCamelCase ,trim_offsets=__lowerCamelCase ) a = json.loads(tokenizer_r.backend_tokenizer.pre_tokenizer.__getstate__() ) a = json.loads(tokenizer_r.backend_tokenizer.post_processor.__getstate__() ) self.assertEqual(pre_tokenizer_state['''add_prefix_space'''] ,__lowerCamelCase ) self.assertEqual(post_processor_state['''add_prefix_space'''] ,__lowerCamelCase ) self.assertEqual(post_processor_state['''trim_offsets'''] ,__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ): '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): a = '''hello''' # `hello` is a token in the vocabulary of `pretrained_name` a = F"""{text_of_1_token} {text_of_1_token}""" a = self.rust_tokenizer_class.from_pretrained( __lowerCamelCase ,use_fast=__lowerCamelCase ,add_prefix_space=__lowerCamelCase ,trim_offsets=__lowerCamelCase ) a = tokenizer_r(__lowerCamelCase ,return_offsets_mapping=__lowerCamelCase ,add_special_tokens=__lowerCamelCase ) self.assertEqual(encoding.offset_mapping[0] ,(0, len(__lowerCamelCase )) ) self.assertEqual( encoding.offset_mapping[1] ,(len(__lowerCamelCase ) + 1, len(__lowerCamelCase ) + 1 + len(__lowerCamelCase )) ,) a = self.rust_tokenizer_class.from_pretrained( __lowerCamelCase ,use_fast=__lowerCamelCase ,add_prefix_space=__lowerCamelCase ,trim_offsets=__lowerCamelCase ) a = tokenizer_r(__lowerCamelCase ,return_offsets_mapping=__lowerCamelCase ,add_special_tokens=__lowerCamelCase ) self.assertEqual(encoding.offset_mapping[0] ,(0, len(__lowerCamelCase )) ) self.assertEqual( encoding.offset_mapping[1] ,(len(__lowerCamelCase ) + 1, len(__lowerCamelCase ) + 1 + len(__lowerCamelCase )) ,) a = self.rust_tokenizer_class.from_pretrained( __lowerCamelCase ,use_fast=__lowerCamelCase ,add_prefix_space=__lowerCamelCase ,trim_offsets=__lowerCamelCase ) a = tokenizer_r(__lowerCamelCase ,return_offsets_mapping=__lowerCamelCase ,add_special_tokens=__lowerCamelCase ) self.assertEqual(encoding.offset_mapping[0] ,(0, len(__lowerCamelCase )) ) self.assertEqual( encoding.offset_mapping[1] ,(len(__lowerCamelCase ), len(__lowerCamelCase ) + 1 + len(__lowerCamelCase )) ,) a = self.rust_tokenizer_class.from_pretrained( __lowerCamelCase ,use_fast=__lowerCamelCase ,add_prefix_space=__lowerCamelCase ,trim_offsets=__lowerCamelCase ) a = tokenizer_r(__lowerCamelCase ,return_offsets_mapping=__lowerCamelCase ,add_special_tokens=__lowerCamelCase ) self.assertEqual(encoding.offset_mapping[0] ,(0, len(__lowerCamelCase )) ) self.assertEqual( encoding.offset_mapping[1] ,(len(__lowerCamelCase ), len(__lowerCamelCase ) + 1 + len(__lowerCamelCase )) ,) a = F""" {text}""" # tokenizer_r = self.rust_tokenizer_class.from_pretrained( # pretrained_name, use_fast=True, add_prefix_space=True, trim_offsets=True # ) # encoding = tokenizer_r(text, return_offsets_mapping=True, add_special_tokens=False) # self.assertEqual(encoding.offset_mapping[0], (1, 1 + len(text_of_1_token))) # self.assertEqual( # encoding.offset_mapping[1], # (1 + len(text_of_1_token) + 1, 1 + len(text_of_1_token) + 1 + len(text_of_1_token)), # ) a = self.rust_tokenizer_class.from_pretrained( __lowerCamelCase ,use_fast=__lowerCamelCase ,add_prefix_space=__lowerCamelCase ,trim_offsets=__lowerCamelCase ) a = tokenizer_r(__lowerCamelCase ,return_offsets_mapping=__lowerCamelCase ,add_special_tokens=__lowerCamelCase ) self.assertEqual(encoding.offset_mapping[0] ,(1, 1 + len(__lowerCamelCase )) ) self.assertEqual( encoding.offset_mapping[1] ,(1 + len(__lowerCamelCase ) + 1, 1 + len(__lowerCamelCase ) + 1 + len(__lowerCamelCase )) ,) a = self.rust_tokenizer_class.from_pretrained( __lowerCamelCase ,use_fast=__lowerCamelCase ,add_prefix_space=__lowerCamelCase ,trim_offsets=__lowerCamelCase ) a = tokenizer_r(__lowerCamelCase ,return_offsets_mapping=__lowerCamelCase ,add_special_tokens=__lowerCamelCase ) self.assertEqual(encoding.offset_mapping[0] ,(0, 1 + len(__lowerCamelCase )) ) self.assertEqual( encoding.offset_mapping[1] ,(1 + len(__lowerCamelCase ), 1 + len(__lowerCamelCase ) + 1 + len(__lowerCamelCase )) ,) a = self.rust_tokenizer_class.from_pretrained( __lowerCamelCase ,use_fast=__lowerCamelCase ,add_prefix_space=__lowerCamelCase ,trim_offsets=__lowerCamelCase ) a = tokenizer_r(__lowerCamelCase ,return_offsets_mapping=__lowerCamelCase ,add_special_tokens=__lowerCamelCase ) self.assertEqual(encoding.offset_mapping[0] ,(0, 1 + len(__lowerCamelCase )) ) self.assertEqual( encoding.offset_mapping[1] ,(1 + len(__lowerCamelCase ), 1 + len(__lowerCamelCase ) + 1 + len(__lowerCamelCase )) ,)
330
from typing import List, Union import numpy as np from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_DEPTH_ESTIMATION_MAPPING UpperCamelCase__ : List[str] = logging.get_logger(__name__) @add_end_docstrings(a_ ) class lowerCamelCase_ ( a_ ): def __init__( self : int ,*__lowerCamelCase : str ,**__lowerCamelCase : Optional[Any] ): '''simple docstring''' super().__init__(*__lowerCamelCase ,**__lowerCamelCase ) requires_backends(self ,'''vision''' ) self.check_model_type(__lowerCamelCase ) def __call__( self : int ,__lowerCamelCase : Union[str, List[str], "Image.Image", List["Image.Image"]] ,**__lowerCamelCase : str ): '''simple docstring''' return super().__call__(__lowerCamelCase ,**__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : Any ,**__lowerCamelCase : Dict ): '''simple docstring''' return {}, {}, {} def SCREAMING_SNAKE_CASE_ ( self : int ,__lowerCamelCase : Union[str, Any] ): '''simple docstring''' a = load_image(__lowerCamelCase ) a = image.size a = self.image_processor(images=__lowerCamelCase ,return_tensors=self.framework ) return model_inputs def SCREAMING_SNAKE_CASE_ ( self : str ,__lowerCamelCase : Union[str, Any] ): '''simple docstring''' a = self.model(**__lowerCamelCase ) return model_outputs def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ,__lowerCamelCase : Union[str, Any] ): '''simple docstring''' a = model_outputs.predicted_depth a = torch.nn.functional.interpolate( predicted_depth.unsqueeze(1 ) ,size=self.image_size[::-1] ,mode='''bicubic''' ,align_corners=__lowerCamelCase ) a = prediction.squeeze().cpu().numpy() a = (output * 2_55 / np.max(__lowerCamelCase )).astype('''uint8''' ) a = Image.fromarray(__lowerCamelCase ) a = {} a = predicted_depth a = depth return output_dict
330
1
import inspect import unittest from transformers import BitConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import BitBackbone, BitForImageClassification, BitImageProcessor, BitModel from transformers.models.bit.modeling_bit import BIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image class lowerCamelCase_ : def __init__( self : str ,__lowerCamelCase : str ,__lowerCamelCase : Optional[int]=3 ,__lowerCamelCase : List[str]=32 ,__lowerCamelCase : Tuple=3 ,__lowerCamelCase : List[Any]=10 ,__lowerCamelCase : Optional[int]=[8, 16, 32, 64] ,__lowerCamelCase : List[Any]=[1, 1, 2, 1] ,__lowerCamelCase : Any=True ,__lowerCamelCase : int=True ,__lowerCamelCase : int="relu" ,__lowerCamelCase : Tuple=3 ,__lowerCamelCase : Union[str, Any]=None ,__lowerCamelCase : Union[str, Any]=["stage2", "stage3", "stage4"] ,__lowerCamelCase : Any=[2, 3, 4] ,__lowerCamelCase : List[Any]=1 ,): '''simple docstring''' a = parent a = batch_size a = image_size a = num_channels a = embeddings_size a = hidden_sizes a = depths a = is_training a = use_labels a = hidden_act a = num_labels a = scope a = len(__lowerCamelCase ) a = out_features a = out_indices a = num_groups def SCREAMING_SNAKE_CASE_ ( self : Any ): '''simple docstring''' a = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) a = None if self.use_labels: a = ids_tensor([self.batch_size] ,self.num_labels ) a = self.get_config() return config, pixel_values, labels def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ): '''simple docstring''' return BitConfig( 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 ,out_features=self.out_features ,out_indices=self.out_indices ,num_groups=self.num_groups ,) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ,__lowerCamelCase : str ,__lowerCamelCase : Dict ,__lowerCamelCase : Optional[Any] ): '''simple docstring''' a = BitModel(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() a = model(__lowerCamelCase ) self.parent.assertEqual( result.last_hidden_state.shape ,(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) ,) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ,__lowerCamelCase : int ,__lowerCamelCase : List[str] ,__lowerCamelCase : Union[str, Any] ): '''simple docstring''' a = self.num_labels a = BitForImageClassification(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() a = model(__lowerCamelCase ,labels=__lowerCamelCase ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE_ ( self : Any ,__lowerCamelCase : int ,__lowerCamelCase : List[str] ,__lowerCamelCase : int ): '''simple docstring''' a = BitBackbone(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() a = model(__lowerCamelCase ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) ,len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) ,[self.batch_size, self.hidden_sizes[1], 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) ,len(config.out_features ) ) self.parent.assertListEqual(model.channels ,config.hidden_sizes[1:] ) # verify backbone works with out_features=None a = None a = BitBackbone(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() a = model(__lowerCamelCase ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) ,1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) ,[self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) ,1 ) self.parent.assertListEqual(model.channels ,[config.hidden_sizes[-1]] ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ): '''simple docstring''' a = self.prepare_config_and_inputs() a , a , a = config_and_inputs a = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class lowerCamelCase_ ( a_ , a_ , unittest.TestCase ): SCREAMING_SNAKE_CASE_ = (BitModel, BitForImageClassification, BitBackbone) if is_torch_available() else () SCREAMING_SNAKE_CASE_ = ( {'feature-extraction': BitModel, 'image-classification': BitForImageClassification} if is_torch_available() else {} ) SCREAMING_SNAKE_CASE_ = False SCREAMING_SNAKE_CASE_ = False SCREAMING_SNAKE_CASE_ = False SCREAMING_SNAKE_CASE_ = False SCREAMING_SNAKE_CASE_ = False def SCREAMING_SNAKE_CASE_ ( self : Any ): '''simple docstring''' a = BitModelTester(self ) a = ConfigTester(self ,config_class=__lowerCamelCase ,has_text_modality=__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ): '''simple docstring''' 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 SCREAMING_SNAKE_CASE_ ( self : Tuple ): '''simple docstring''' return @unittest.skip(reason='''Bit does not output attentions''' ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ): '''simple docstring''' pass @unittest.skip(reason='''Bit does not use inputs_embeds''' ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ): '''simple docstring''' pass @unittest.skip(reason='''Bit does not support input and output embeddings''' ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ): '''simple docstring''' pass def SCREAMING_SNAKE_CASE_ ( self : int ): '''simple docstring''' a , a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a = model_class(__lowerCamelCase ) a = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic a = [*signature.parameters.keys()] a = ['''pixel_values'''] self.assertListEqual(arg_names[:1] ,__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : Any ): '''simple docstring''' a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ): '''simple docstring''' a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ): '''simple docstring''' a , a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a = model_class(config=__lowerCamelCase ) for name, module in model.named_modules(): if isinstance(__lowerCamelCase ,(nn.BatchNormad, nn.GroupNorm) ): self.assertTrue( torch.all(module.weight == 1 ) ,msg=F"""Parameter {name} of model {model_class} seems not properly initialized""" ,) self.assertTrue( torch.all(module.bias == 0 ) ,msg=F"""Parameter {name} of model {model_class} seems not properly initialized""" ,) def SCREAMING_SNAKE_CASE_ ( self : Tuple ): '''simple docstring''' def check_hidden_states_output(__lowerCamelCase : str ,__lowerCamelCase : str ,__lowerCamelCase : Any ): a = model_class(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() with torch.no_grad(): a = model(**self._prepare_for_class(__lowerCamelCase ,__lowerCamelCase ) ) a = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states a = self.model_tester.num_stages self.assertEqual(len(__lowerCamelCase ) ,expected_num_stages + 1 ) # Bit'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] ,) a , a = self.model_tester.prepare_config_and_inputs_for_common() a = ['''preactivation''', '''bottleneck'''] for model_class in self.all_model_classes: for layer_type in layers_type: a = layer_type a = True check_hidden_states_output(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] a = True check_hidden_states_output(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ) @unittest.skip(reason='''Bit does not use feedforward chunking''' ) def SCREAMING_SNAKE_CASE_ ( self : Any ): '''simple docstring''' pass def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ): '''simple docstring''' a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ): '''simple docstring''' for model_name in BIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a = BitModel.from_pretrained(__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) def SCREAMING_SNAKE_CASE__ ( ) -> int: """simple docstring""" a = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class lowerCamelCase_ ( unittest.TestCase ): @cached_property def SCREAMING_SNAKE_CASE_ ( self : Dict ): '''simple docstring''' return ( BitImageProcessor.from_pretrained(BIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def SCREAMING_SNAKE_CASE_ ( self : str ): '''simple docstring''' a = BitForImageClassification.from_pretrained(BIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to(__lowerCamelCase ) a = self.default_image_processor a = prepare_img() a = image_processor(images=__lowerCamelCase ,return_tensors='''pt''' ).to(__lowerCamelCase ) # forward pass with torch.no_grad(): a = model(**__lowerCamelCase ) # verify the logits a = torch.Size((1, 10_00) ) self.assertEqual(outputs.logits.shape ,__lowerCamelCase ) a = torch.tensor([[-0.6_526, -0.5_263, -1.4_398]] ).to(__lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] ,__lowerCamelCase ,atol=1e-4 ) ) @require_torch class lowerCamelCase_ ( a_ , unittest.TestCase ): SCREAMING_SNAKE_CASE_ = (BitBackbone,) if is_torch_available() else () SCREAMING_SNAKE_CASE_ = BitConfig SCREAMING_SNAKE_CASE_ = False def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ): '''simple docstring''' a = BitModelTester(self )
330
from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Features, Value from .base import TaskTemplate @dataclass(frozen=a_ ) class lowerCamelCase_ ( a_ ): SCREAMING_SNAKE_CASE_ = field(default='language-modeling' , metadata={'include_in_asdict_even_if_is_default': True} ) SCREAMING_SNAKE_CASE_ = Features({'text': Value('string' )} ) SCREAMING_SNAKE_CASE_ = Features({} ) SCREAMING_SNAKE_CASE_ = "text" @property def SCREAMING_SNAKE_CASE_ ( self : int ): '''simple docstring''' return {self.text_column: "text"}
330
1
from math import ceil from typing import List, Optional, Union import numpy as np from ...audio_utils import mel_filter_bank, spectrogram, window_function from ...feature_extraction_sequence_utils import BatchFeature, SequenceFeatureExtractor from ...utils import TensorType, logging UpperCamelCase__ : Optional[Any] = logging.get_logger(__name__) class lowerCamelCase_ ( a_ ): SCREAMING_SNAKE_CASE_ = ['audio_values', 'audio_mask'] def __init__( self : Union[str, Any] ,__lowerCamelCase : str=20_48 ,__lowerCamelCase : List[str]=1 ,__lowerCamelCase : Dict=[16, 16] ,__lowerCamelCase : List[Any]=1_28 ,__lowerCamelCase : Optional[int]=4_41_00 ,__lowerCamelCase : Optional[Any]=86 ,__lowerCamelCase : Optional[Any]=20_48 ,__lowerCamelCase : Optional[int]=0.0 ,**__lowerCamelCase : Optional[int] ,): '''simple docstring''' super().__init__( feature_size=__lowerCamelCase ,sampling_rate=__lowerCamelCase ,padding_value=__lowerCamelCase ,**__lowerCamelCase ,) a = spectrogram_length a = num_channels a = patch_size a = feature_size // self.patch_size[1] a = n_fft a = sampling_rate // hop_length_to_sampling_rate a = sampling_rate a = padding_value a = mel_filter_bank( num_frequency_bins=1 + n_fft // 2 ,num_mel_filters=__lowerCamelCase ,min_frequency=0.0 ,max_frequency=22_050.0 ,sampling_rate=__lowerCamelCase ,norm='''slaney''' ,mel_scale='''slaney''' ,).T def SCREAMING_SNAKE_CASE_ ( self : str ,__lowerCamelCase : np.array ): '''simple docstring''' a = spectrogram( __lowerCamelCase ,window_function(self.n_fft ,'''hann''' ) ,frame_length=self.n_fft ,hop_length=self.hop_length ,power=2.0 ,mel_filters=self.mel_filters.T ,log_mel='''dB''' ,db_range=80.0 ,) a = log_spec[:, :-1] a = log_spec - 20.0 a = np.clip(log_spec / 40.0 ,-2.0 ,0.0 ) + 1.0 return log_spec def __call__( self : List[str] ,__lowerCamelCase : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] ,__lowerCamelCase : Optional[Union[str, TensorType]] = None ,__lowerCamelCase : Optional[bool] = True ,__lowerCamelCase : Optional[int] = None ,__lowerCamelCase : bool = False ,__lowerCamelCase : bool = False ,**__lowerCamelCase : Tuple ,): '''simple docstring''' if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( '''This feature extractor is set to support sampling rate''' F""" of {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled""" F""" with {self.sampling_rate} and not {sampling_rate}.""" ) else: logger.warning( '''It is strongly recommended to pass the `sampling_rate` argument to this function. ''' '''Failing to do so can result in silent errors that might be hard to debug.''' ) a = isinstance(__lowerCamelCase ,np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(F"""Only mono-channel audio is supported for input to {self}""" ) a = is_batched_numpy or ( isinstance(__lowerCamelCase ,(list, tuple) ) and (isinstance(raw_speech[0] ,(np.ndarray, tuple, list) )) ) if is_batched: a = [np.asarray([speech] ,dtype=np.floataa ).T for speech in raw_speech] elif not is_batched and not isinstance(__lowerCamelCase ,np.ndarray ): a = np.asarray(__lowerCamelCase ,dtype=np.floataa ) elif isinstance(__lowerCamelCase ,np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): a = raw_speech.astype(np.floataa ) # always return batch if not is_batched: a = [np.asarray([raw_speech] ).T] # Convert audio signals to log mel spectrograms, truncate by time axis a = [ self._np_extract_fbank_features(waveform.squeeze() ).T[: self.spectrogram_length] for waveform in raw_speech ] if isinstance(audio_features[0] ,__lowerCamelCase ): a = [np.asarray(__lowerCamelCase ,dtype=np.floataa ) for feature in audio_features] # Create audio attention mask a = max( [ceil(feature.shape[0] / self.patch_size[0] ) * self.freq_len for feature in audio_features] ) # The maximum number of audio patches in a batch if return_attention_mask: a = [ (ceil(feature.shape[0] / self.patch_size[0] ) * self.freq_len) * [1] + (max_patch_len - ceil(feature.shape[0] / self.patch_size[0] ) * self.freq_len) * [0] for feature in audio_features ] a = np.array(__lowerCamelCase ).astype(np.floataa ) # convert into correct format for padding a = max_patch_len // self.freq_len * self.patch_size[0] # The maximum audio size in a batch a = np.ones([len(__lowerCamelCase ), 1, max_time_len, self.feature_size] ).astype(np.floataa ) a = padded_audio_features * self.padding_value for i in range(len(__lowerCamelCase ) ): a = audio_features[i] a = feature # return as BatchFeature if return_attention_mask: a = {'''audio_values''': padded_audio_features, '''audio_mask''': audio_mask} else: a = {'''audio_values''': padded_audio_features} a = BatchFeature(data=__lowerCamelCase ,tensor_type=__lowerCamelCase ) return encoded_inputs
330
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCamelCase__ : Union[str, Any] = logging.get_logger(__name__) UpperCamelCase__ : Union[str, Any] = { """hustvl/yolos-small""": """https://huggingface.co/hustvl/yolos-small/resolve/main/config.json""", # See all YOLOS models at https://huggingface.co/models?filter=yolos } class lowerCamelCase_ ( a_ ): SCREAMING_SNAKE_CASE_ = 'yolos' def __init__( self : Union[str, Any] ,__lowerCamelCase : int=7_68 ,__lowerCamelCase : Dict=12 ,__lowerCamelCase : Union[str, Any]=12 ,__lowerCamelCase : List[Any]=30_72 ,__lowerCamelCase : int="gelu" ,__lowerCamelCase : int=0.0 ,__lowerCamelCase : str=0.0 ,__lowerCamelCase : Optional[Any]=0.02 ,__lowerCamelCase : int=1e-12 ,__lowerCamelCase : Any=[5_12, 8_64] ,__lowerCamelCase : Tuple=16 ,__lowerCamelCase : int=3 ,__lowerCamelCase : Tuple=True ,__lowerCamelCase : Optional[int]=1_00 ,__lowerCamelCase : List[Any]=True ,__lowerCamelCase : List[str]=False ,__lowerCamelCase : int=1 ,__lowerCamelCase : List[Any]=5 ,__lowerCamelCase : Optional[int]=2 ,__lowerCamelCase : int=5 ,__lowerCamelCase : str=2 ,__lowerCamelCase : Tuple=0.1 ,**__lowerCamelCase : List[Any] ,): '''simple docstring''' super().__init__(**__lowerCamelCase ) 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 a = num_detection_tokens a = use_mid_position_embeddings a = auxiliary_loss # Hungarian matcher a = class_cost a = bbox_cost a = giou_cost # Loss coefficients a = bbox_loss_coefficient a = giou_loss_coefficient a = eos_coefficient class lowerCamelCase_ ( a_ ): SCREAMING_SNAKE_CASE_ = version.parse('1.11' ) @property def SCREAMING_SNAKE_CASE_ ( self : str ): '''simple docstring''' return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) @property def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ): '''simple docstring''' return 1e-4 @property def SCREAMING_SNAKE_CASE_ ( self : str ): '''simple docstring''' return 12
330
1
import argparse import random import joblib import numpy as np import torch from igf.igf import ( SecondaryLearner, collect_objective_set, compute_perplexity, generate_datasets, load_gpta, recopy_gpta, set_seed, train_secondary_learner, ) from torch.utils.data import DataLoader, RandomSampler from transformers import GPTaLMHeadModel def SCREAMING_SNAKE_CASE__ ( snake_case_=3_2, snake_case_=1_0, snake_case_=1_0_0, snake_case_=1_0_2_6, snake_case_=True, snake_case_="data/tokenized_stories_train_wikitext103.jbl", snake_case_="igf_context_pairs.jbl", ) -> Dict: """simple docstring""" set_seed(3 ) # generate train_data and objective_set a , a = generate_datasets( snake_case_, snake_case_, number=snake_case_, min_len=1_0_2_6, trim=snake_case_ ) # keeps model same across runs set_seed(4 ) # model, lm_optimizer, lm_scheduler = recopy_gpt2(model, device, max_steps) # store original model weights # can we train on GPU? a = torch.device('''cuda:0''' if torch.cuda.is_available() else '''cpu''' ) # load pretrained model a = load_gpta('''gpt2''' ).to(snake_case_ ) print('''computing perplexity on objective set''' ) a = compute_perplexity(snake_case_, snake_case_, snake_case_ ).item() print('''perplexity on objective set:''', snake_case_ ) # collect igf pairs and save to file demo.jbl collect_objective_set(snake_case_, snake_case_, snake_case_, snake_case_, snake_case_, snake_case_, snake_case_, snake_case_ ) # clean up, delete model and data we don't need anymore del model, train_data, objective_set torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_=1_5, snake_case_=1_2_8, snake_case_=1_0_0, snake_case_="igf_model.pt", ) -> List[Any]: """simple docstring""" set_seed(4_2 ) # Load pre-trained model a = GPTaLMHeadModel.from_pretrained('''gpt2''' ) # Initialize secondary learner to use embedding weights of model a = SecondaryLearner(snake_case_ ) # Train secondary learner a = train_secondary_learner( snake_case_, snake_case_, max_epochs=snake_case_, batch_size=snake_case_, eval_freq=1_0_0, igf_model_path=snake_case_, ) del model, secondary_learner_train_data torch.cuda.empty_cache() return secondary_learner def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_, snake_case_=3_2, snake_case_=1_0_0_0, snake_case_=1_6, snake_case_=1.0, snake_case_=recopy_gpta, snake_case_=None, snake_case_=1_0, snake_case_="gpt2_finetuned.pt", ) -> Any: """simple docstring""" a = torch.device('''cuda:0''' if torch.cuda.is_available() else '''cpu''' ) a = RandomSampler(snake_case_ ) a = DataLoader(snake_case_, sampler=snake_case_ ) a = max_steps // (len(snake_case_ )) + 1 a = 0 a = torch.zeros((1, context_len), dtype=torch.long, device=snake_case_ ) a , a , a = recopy_model(snake_case_, snake_case_, snake_case_ ) model.train() if secondary_learner is not None: secondary_learner.to(snake_case_ ) secondary_learner.eval() a = [] a = 0 a = [] a = [] # Compute the performance of the transformer model at the beginning a = compute_perplexity(snake_case_, snake_case_, snake_case_ ) test_perps.append(snake_case_ ) print('''Test perplexity, step''', snake_case_, ''':''', snake_case_ ) for epoch in range(int(snake_case_ ) ): for step, example in enumerate(snake_case_ ): torch.cuda.empty_cache() a = random.randint(0, example.size(2 ) - context_len - 1 ) a = example[0, 0, start : start + context_len] lm_optimizer.zero_grad() a = model(snake_case_, labels=snake_case_ ) a = True if secondary_learner is not None: a = secondary_learner.forward( torch.tensor(snake_case_, dtype=torch.long, device=snake_case_ ).unsqueeze(0 ) )[0].item() observed_qs.append(float(snake_case_ ) ) # Here we implement the simple non-constant threshold for the predicted IG(X) value # We will decay the selectivity of our secondary learner filter from # 1 standard deviation above average to 1 below average after 10 batches. if global_step == 1_0: a = -1 if predicted_q < threshold: a = False # If we passed the filter, add the context to the batch! if do_backprop: contexts.append(np.array(context.cpu() ) ) a = outputs[0] lm_loss.backward() examples += 1 del outputs # Once the batch is filled with enough contexts, backprop on the batch. if examples == batch_size: torch.cuda.empty_cache() a = 0 # Do LM backprop torch.nn.utils.clip_grad_norm_(model.parameters(), 3.0 ) lm_optimizer.step() lm_scheduler.step() # Update learning rate schedule global_step += 1 # Compute the performance of the transformer model at this batch if global_step % eval_interval == 0: a = compute_perplexity(snake_case_, snake_case_, snake_case_ ) test_perps.append(snake_case_ ) print('''Test perplexity, step''', snake_case_, ''':''', snake_case_ ) # Break out of the loop after 60 batches if max_steps > 0 and global_step > 6_0: break if max_steps > 0 and global_step > 6_0: break # save finetuned transformer model torch.save(model.state_dict(), snake_case_ ) torch.cuda.empty_cache() # Do some cleaning up so we can reinitialize for the next run of this function del lm_optimizer del lm_scheduler return model def SCREAMING_SNAKE_CASE__ ( ) -> Tuple: """simple docstring""" a = argparse.ArgumentParser(description='''Fine-tune a transformer model with IGF on a language modeling task''' ) # Required parameters parser.add_argument( '''--data_dir''', default=snake_case_, type=snake_case_, required=snake_case_, help='''The input data dir. Should contain data files for WikiText.''', ) parser.add_argument( '''--model_name_or_path''', default=snake_case_, type=snake_case_, required=snake_case_, help='''Path to pretrained model or model identifier from huggingface.co/models''', ) parser.add_argument( '''--data_file''', type=snake_case_, default=snake_case_, help=( '''A jbl file containing tokenized data which can be split as objective dataset, ''' '''train_dataset and test_dataset.''' ), ) parser.add_argument( '''--igf_data_file''', type=snake_case_, default=snake_case_, help='''A jbl file containing the context and information gain pairs to train secondary learner.''', ) parser.add_argument( '''--output_dir''', default=snake_case_, type=snake_case_, required=snake_case_, help='''The output directory where the final fine-tuned model is stored.''', ) parser.add_argument( '''--tokenizer_name''', default=snake_case_, type=snake_case_, help='''Pretrained tokenizer name or path if not the same as model_name''', ) parser.add_argument('''--seed''', type=snake_case_, default=snake_case_, help='''A seed for reproducible training.''' ) parser.add_argument( '''--context_len''', default=3_2, type=snake_case_, help=( '''The maximum total input sequence length after tokenization. Sequences longer ''' '''than this will be truncated, sequences shorter will be padded.''' ), ) parser.add_argument( '''--size_objective_set''', default=1_0_0, type=snake_case_, help='''number of articles that are long enough to be used as our objective set''', ) parser.add_argument( '''--eval_freq''', default=1_0_0, type=snake_case_, help='''secondary model evaluation is triggered at eval_freq''' ) parser.add_argument('''--max_steps''', default=1_0_0_0, type=snake_case_, help='''To calculate training epochs''' ) parser.add_argument( '''--secondary_learner_batch_size''', default=1_2_8, type=snake_case_, help='''batch size of training data for secondary learner''', ) parser.add_argument( '''--batch_size''', default=1_6, type=snake_case_, help='''batch size of training data of language model(gpt2) ''' ) parser.add_argument( '''--eval_interval''', default=1_0, type=snake_case_, help=( '''decay the selectivity of our secondary learner filter from''' '''1 standard deviation above average to 1 below average after 10 batches''' ), ) parser.add_argument( '''--number''', default=1_0_0, type=snake_case_, help='''The number of examples split to be used as objective_set/test_data''' ) parser.add_argument( '''--min_len''', default=1_0_2_6, type=snake_case_, help='''The minimum length of the article to be used as objective set''' ) parser.add_argument( '''--secondary_learner_max_epochs''', default=1_5, type=snake_case_, help='''number of epochs to train secondary learner''' ) parser.add_argument('''--trim''', default=snake_case_, type=snake_case_, help='''truncate the example if it exceeds context length''' ) parser.add_argument( '''--threshold''', default=1.0, type=snake_case_, help=( '''The threshold value used by secondary learner to filter the train_data and allow only''' ''' informative data as input to the model''' ), ) parser.add_argument('''--finetuned_model_name''', default='''gpt2_finetuned.pt''', type=snake_case_, help='''finetuned_model_name''' ) parser.add_argument( '''--recopy_model''', default=snake_case_, type=snake_case_, help='''Reset the model to the original pretrained GPT-2 weights after each iteration''', ) # function calls # Collecting *n* pairs of context and information gain(X, IG(X)) for training the secondary learner generate_n_pairs( context_len=3_2, max_steps=1_0, size_objective_set=1_0_0, min_len=1_0_2_6, trim=snake_case_, data_file='''data/tokenized_stories_train_wikitext103.jbl''', igf_data_file='''igf_context_pairs.jbl''', ) # Load train data for secondary learner a = joblib.load('''data/IGF_values.jbl''' ) # Train secondary learner a = training_secondary_learner( snake_case_, secondary_learner_max_epochs=1_5, secondary_learner_batch_size=1_2_8, eval_freq=1_0_0, igf_model_path='''igf_model.pt''', ) # load pretrained gpt2 model a = GPTaLMHeadModel.from_pretrained('''gpt2''' ) set_seed(4_2 ) # Generate train and test data to train and evaluate gpt2 model a , a = generate_datasets( context_len=3_2, file='''data/tokenized_stories_train_wikitext103.jbl''', number=1_0_0, min_len=1_0_2_6, trim=snake_case_ ) # fine-tuning of the gpt2 model using igf (Information Gain Filtration) finetune( snake_case_, snake_case_, snake_case_, context_len=3_2, max_steps=1_0_0_0, batch_size=1_6, threshold=1.0, recopy_model=snake_case_, secondary_learner=snake_case_, eval_interval=1_0, finetuned_model_name='''gpt2_finetuned.pt''', ) if __name__ == "__main__": main()
330
def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> int: """simple docstring""" a = '''''' for i in table: res += inp[i - 1] return res def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> int: """simple docstring""" return data[1:] + data[0] def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> List[str]: """simple docstring""" a = '''''' for i in range(len(snake_case_ ) ): if a[i] == b[i]: res += "0" else: res += "1" return res def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> Dict: """simple docstring""" a = int('''0b''' + data[0] + data[-1], 2 ) a = int('''0b''' + data[1:3], 2 ) return bin(s[row][col] )[2:] def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_, snake_case_, snake_case_ ) -> Optional[int]: """simple docstring""" a = message[:4] a = message[4:] a = apply_table(snake_case_, snake_case_ ) a = xor(snake_case_, snake_case_ ) a = apply_sbox(snake_case_, temp[:4] ) # noqa: E741 a = apply_sbox(snake_case_, temp[4:] ) a = '''0''' * (2 - len(snake_case_ )) + l # noqa: E741 a = '''0''' * (2 - len(snake_case_ )) + r a = apply_table(l + r, snake_case_ ) a = xor(snake_case_, snake_case_ ) return temp + right if __name__ == "__main__": UpperCamelCase__ : int = input("""Enter 10 bit key: """) UpperCamelCase__ : Union[str, Any] = input("""Enter 8 bit message: """) UpperCamelCase__ : Dict = [6, 3, 7, 4, 8, 5, 10, 9] UpperCamelCase__ : Union[str, Any] = [3, 5, 2, 7, 4, 10, 1, 9, 8, 6] UpperCamelCase__ : Optional[int] = [2, 4, 3, 1] UpperCamelCase__ : List[Any] = [2, 6, 3, 1, 4, 8, 5, 7] UpperCamelCase__ : str = [4, 1, 3, 5, 7, 2, 8, 6] UpperCamelCase__ : List[Any] = [4, 1, 2, 3, 2, 3, 4, 1] UpperCamelCase__ : int = [[1, 0, 3, 2], [3, 2, 1, 0], [0, 2, 1, 3], [3, 1, 3, 2]] UpperCamelCase__ : Dict = [[0, 1, 2, 3], [2, 0, 1, 3], [3, 0, 1, 0], [2, 1, 0, 3]] # key generation UpperCamelCase__ : Optional[Any] = apply_table(key, paa_table) UpperCamelCase__ : str = temp[:5] UpperCamelCase__ : List[Any] = temp[5:] UpperCamelCase__ : Dict = left_shift(left) UpperCamelCase__ : Any = left_shift(right) UpperCamelCase__ : Optional[Any] = apply_table(left + right, pa_table) UpperCamelCase__ : List[str] = left_shift(left) UpperCamelCase__ : int = left_shift(right) UpperCamelCase__ : List[str] = left_shift(left) UpperCamelCase__ : Dict = left_shift(right) UpperCamelCase__ : List[str] = apply_table(left + right, pa_table) # encryption UpperCamelCase__ : Tuple = apply_table(message, IP) UpperCamelCase__ : Optional[Any] = function(expansion, sa, sa, keya, temp) UpperCamelCase__ : Optional[int] = temp[4:] + temp[:4] UpperCamelCase__ : Any = function(expansion, sa, sa, keya, temp) UpperCamelCase__ : Tuple = apply_table(temp, IP_inv) print("""Cipher text is:""", CT) # decryption UpperCamelCase__ : Union[str, Any] = apply_table(CT, IP) UpperCamelCase__ : List[str] = function(expansion, sa, sa, keya, temp) UpperCamelCase__ : Optional[Any] = temp[4:] + temp[:4] UpperCamelCase__ : Optional[int] = function(expansion, sa, sa, keya, temp) UpperCamelCase__ : Any = apply_table(temp, IP_inv) print("""Plain text after decypting is:""", PT)
330
1
def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> str: """simple docstring""" a = int(snake_case_ ) if decimal in (0, 1): # Exit cases for the recursion return str(snake_case_ ) a , a = divmod(snake_case_, 2 ) return binary_recursive(snake_case_ ) + str(snake_case_ ) def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> str: """simple docstring""" a = str(snake_case_ ).strip() if not number: raise ValueError('''No input value was provided''' ) a = '''-''' if number.startswith('''-''' ) else '''''' a = number.lstrip('''-''' ) if not number.isnumeric(): raise ValueError('''Input value is not an integer''' ) return f"""{negative}0b{binary_recursive(int(snake_case_ ) )}""" if __name__ == "__main__": from doctest import testmod testmod()
330
import unittest from transformers import AutoTokenizer, is_flax_available from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, slow if is_flax_available(): import jax.numpy as jnp from transformers import FlaxXLMRobertaModel @require_sentencepiece @require_tokenizers @require_flax class lowerCamelCase_ ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE_ ( self : Tuple ): '''simple docstring''' a = FlaxXLMRobertaModel.from_pretrained('''xlm-roberta-base''' ) a = AutoTokenizer.from_pretrained('''xlm-roberta-base''' ) a = '''The dog is cute and lives in the garden house''' a = jnp.array([tokenizer.encode(__lowerCamelCase )] ) a = (1, 12, 7_68) # batch_size, sequence_length, embedding_vector_dim a = jnp.array( [[-0.0_101, 0.1_218, -0.0_803, 0.0_801, 0.1_327, 0.0_776, -0.1_215, 0.2_383, 0.3_338, 0.3_106, 0.0_300, 0.0_252]] ) a = model(__lowerCamelCase )['''last_hidden_state'''] self.assertEqual(output.shape ,__lowerCamelCase ) # compare the actual values for a slice of last dim self.assertTrue(jnp.allclose(output[:, :, -1] ,__lowerCamelCase ,atol=1e-3 ) )
330
1
def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> bool: """simple docstring""" if not isinstance(snake_case_, snake_case_ ): a = f"""Input value of [number={number}] must be an integer""" raise TypeError(snake_case_ ) if number < 0: return False a = number * number while number > 0: if number % 1_0 != number_square % 1_0: return False number //= 1_0 number_square //= 1_0 return True if __name__ == "__main__": import doctest doctest.testmod()
330
import argparse import os # New Code # import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils import find_executable_batch_size ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to ensure out-of-memory errors never # interrupt training, and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## UpperCamelCase__ : Union[str, Any] = 16 UpperCamelCase__ : Dict = 32 def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ = 1_6 ) -> Tuple: """simple docstring""" a = AutoTokenizer.from_pretrained('''bert-base-cased''' ) a = load_dataset('''glue''', '''mrpc''' ) def tokenize_function(snake_case_ ): # max_length=None => use the model max length (it's actually the default) a = tokenizer(examples['''sentence1'''], examples['''sentence2'''], truncation=snake_case_, max_length=snake_case_ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): a = datasets.map( snake_case_, batched=snake_case_, remove_columns=['''idx''', '''sentence1''', '''sentence2'''], ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library a = tokenized_datasets.rename_column('''label''', '''labels''' ) def collate_fn(snake_case_ ): # On TPU it's best to pad everything to the same length or training will be very slow. a = 1_2_8 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": a = 1_6 elif accelerator.mixed_precision != "no": a = 8 else: a = None return tokenizer.pad( snake_case_, padding='''longest''', max_length=snake_case_, pad_to_multiple_of=snake_case_, return_tensors='''pt''', ) # Instantiate dataloaders. a = DataLoader( tokenized_datasets['''train'''], shuffle=snake_case_, collate_fn=snake_case_, batch_size=snake_case_ ) a = DataLoader( tokenized_datasets['''validation'''], shuffle=snake_case_, collate_fn=snake_case_, batch_size=snake_case_ ) return train_dataloader, eval_dataloader # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""", None) == "1": from accelerate.test_utils.training import mocked_dataloaders UpperCamelCase__ : int = mocked_dataloaders # noqa: F811 def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> List[Any]: """simple docstring""" if os.environ.get('''TESTING_MOCKED_DATALOADERS''', snake_case_ ) == "1": a = 2 # Initialize accelerator a = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs a = config['''lr'''] a = int(config['''num_epochs'''] ) a = int(config['''seed'''] ) a = int(config['''batch_size'''] ) a = evaluate.load('''glue''', '''mrpc''' ) # New Code # # We now can define an inner training loop function. It should take a batch size as the only parameter, # and build the dataloaders in there. # It also gets our decorator @find_executable_batch_size(starting_batch_size=snake_case_ ) def inner_training_loop(snake_case_ ): # And now just move everything below under this function # We need to bring in the Accelerator object from earlier nonlocal accelerator # And reset all of its attributes that could hold onto any memory: accelerator.free_memory() # Then we can declare the model, optimizer, and everything else: set_seed(snake_case_ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) a = AutoModelForSequenceClassification.from_pretrained('''bert-base-cased''', return_dict=snake_case_ ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). a = model.to(accelerator.device ) # Instantiate optimizer a = AdamW(params=model.parameters(), lr=snake_case_ ) a , a = get_dataloaders(snake_case_, snake_case_ ) # Instantiate scheduler a = get_linear_schedule_with_warmup( optimizer=snake_case_, num_warmup_steps=1_0_0, num_training_steps=(len(snake_case_ ) * num_epochs), ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. a , a , a , a , a = accelerator.prepare( snake_case_, snake_case_, snake_case_, snake_case_, snake_case_ ) # Now we train the model for epoch in range(snake_case_ ): model.train() for step, batch in enumerate(snake_case_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) a = model(**snake_case_ ) a = outputs.loss accelerator.backward(snake_case_ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(snake_case_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): a = model(**snake_case_ ) a = outputs.logits.argmax(dim=-1 ) a , a = accelerator.gather_for_metrics((predictions, batch['''labels''']) ) metric.add_batch( predictions=snake_case_, references=snake_case_, ) a = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f"""epoch {epoch}:""", snake_case_ ) # New Code # # And call it at the end with no arguments # Note: You could also refactor this outside of your training loop function inner_training_loop() def SCREAMING_SNAKE_CASE__ ( ) -> Tuple: """simple docstring""" a = argparse.ArgumentParser(description='''Simple example of training script.''' ) parser.add_argument( '''--mixed_precision''', type=snake_case_, default=snake_case_, choices=['''no''', '''fp16''', '''bf16''', '''fp8'''], help='''Whether to use mixed precision. Choose''' '''between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.''' '''and an Nvidia Ampere GPU.''', ) parser.add_argument('''--cpu''', action='''store_true''', help='''If passed, will train on the CPU.''' ) a = parser.parse_args() a = {'''lr''': 2e-5, '''num_epochs''': 3, '''seed''': 4_2, '''batch_size''': 1_6} training_function(snake_case_, snake_case_ ) if __name__ == "__main__": main()
330
1
import numpy as np UpperCamelCase__ : int = [ ["""a""", """b""", """c""", """d""", """e"""], ["""f""", """g""", """h""", """i""", """k"""], ["""l""", """m""", """n""", """o""", """p"""], ["""q""", """r""", """s""", """t""", """u"""], ["""v""", """w""", """x""", """y""", """z"""], ] class lowerCamelCase_ : def __init__( self : int ): '''simple docstring''' a = np.array(__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ,__lowerCamelCase : str ): '''simple docstring''' a , a = np.where(letter == self.SQUARE ) a = np.concatenate([indexa + 1, indexa + 1] ) return indexes def SCREAMING_SNAKE_CASE_ ( self : str ,__lowerCamelCase : int ,__lowerCamelCase : int ): '''simple docstring''' a = self.SQUARE[indexa - 1, indexa - 1] return letter def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ,__lowerCamelCase : str ): '''simple docstring''' a = message.lower() a = message.replace(''' ''' ,'''''' ) a = message.replace('''j''' ,'''i''' ) a = np.empty((2, len(__lowerCamelCase )) ) for letter_index in range(len(__lowerCamelCase ) ): a = self.letter_to_numbers(message[letter_index] ) a = numbers[0] a = numbers[1] a = first_step.reshape(2 * len(__lowerCamelCase ) ) a = '''''' for numbers_index in range(len(__lowerCamelCase ) ): a = int(second_step[numbers_index * 2] ) a = int(second_step[(numbers_index * 2) + 1] ) a = self.numbers_to_letter(__lowerCamelCase ,__lowerCamelCase ) a = encoded_message + letter return encoded_message def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ,__lowerCamelCase : str ): '''simple docstring''' a = message.lower() message.replace(''' ''' ,'''''' ) a = np.empty(2 * len(__lowerCamelCase ) ) for letter_index in range(len(__lowerCamelCase ) ): a = self.letter_to_numbers(message[letter_index] ) a = numbers[0] a = numbers[1] a = first_step.reshape((2, len(__lowerCamelCase )) ) a = '''''' for numbers_index in range(len(__lowerCamelCase ) ): a = int(second_step[0, numbers_index] ) a = int(second_step[1, numbers_index] ) a = self.numbers_to_letter(__lowerCamelCase ,__lowerCamelCase ) a = decoded_message + letter return decoded_message
330
import argparse import fairseq import torch from transformers import UniSpeechSatConfig, UniSpeechSatForCTC, UniSpeechSatForPreTraining, logging logging.set_verbosity_info() UpperCamelCase__ : Optional[int] = logging.get_logger(__name__) UpperCamelCase__ : str = { """post_extract_proj""": """feature_projection.projection""", """encoder.pos_conv.0""": """encoder.pos_conv_embed.conv""", """self_attn.k_proj""": """encoder.layers.*.attention.k_proj""", """self_attn.v_proj""": """encoder.layers.*.attention.v_proj""", """self_attn.q_proj""": """encoder.layers.*.attention.q_proj""", """self_attn.out_proj""": """encoder.layers.*.attention.out_proj""", """self_attn_layer_norm""": """encoder.layers.*.layer_norm""", """fc1""": """encoder.layers.*.feed_forward.intermediate_dense""", """fc2""": """encoder.layers.*.feed_forward.output_dense""", """final_layer_norm""": """encoder.layers.*.final_layer_norm""", """encoder.layer_norm""": """encoder.layer_norm""", """encoder.layer_norm_for_extract""": """layer_norm_for_extract""", """w2v_model.layer_norm""": """feature_projection.layer_norm""", """quantizer.weight_proj""": """quantizer.weight_proj""", """quantizer.vars""": """quantizer.codevectors""", """project_q""": """project_q""", """final_proj""": """project_hid""", """w2v_encoder.proj""": """lm_head""", """label_embs_concat""": """label_embeddings_concat""", """mask_emb""": """masked_spec_embed""", """spk_proj""": """speaker_proj""", } UpperCamelCase__ : Optional[Any] = [ """lm_head""", """quantizer.weight_proj""", """quantizer.codevectors""", """project_q""", """project_hid""", """label_embeddings_concat""", """speaker_proj""", """layer_norm_for_extract""", ] def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_, snake_case_, snake_case_ ) -> List[Any]: """simple docstring""" for attribute in key.split('''.''' ): a = getattr(snake_case_, snake_case_ ) if weight_type is not None: a = getattr(snake_case_, snake_case_ ).shape else: a = hf_pointer.shape if hf_shape != value.shape: raise ValueError( f"""Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be""" f""" {value.shape} for {full_name}""" ) if weight_type == "weight": a = value elif weight_type == "weight_g": a = value elif weight_type == "weight_v": a = value elif weight_type == "bias": a = value else: a = value logger.info(f"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" ) def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> Union[str, Any]: """simple docstring""" a = [] a = fairseq_model.state_dict() a = hf_model.unispeech_sat.feature_extractor for name, value in fairseq_dict.items(): a = False if "conv_layers" in name: load_conv_layer( snake_case_, snake_case_, snake_case_, snake_case_, hf_model.config.feat_extract_norm == '''group''', ) a = True else: for key, mapped_key in MAPPING.items(): a = '''unispeech_sat.''' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split('''w2v_model.''' )[-1] == name.split('''.''' )[0]: if "layer_norm_for_extract" in name and (".".join(name.split('''.''' )[:-1] ) != key): # special case since naming is very similar continue a = True if "*" in mapped_key: a = name.split(snake_case_ )[0].split('''.''' )[-2] a = mapped_key.replace('''*''', snake_case_ ) if "weight_g" in name: a = '''weight_g''' elif "weight_v" in name: a = '''weight_v''' elif "bias" in name: a = '''bias''' elif "weight" in name: # TODO: don't match quantizer.weight_proj a = '''weight''' else: a = None set_recursively(snake_case_, snake_case_, snake_case_, snake_case_, snake_case_ ) continue if not is_used: unused_weights.append(snake_case_ ) logger.warning(f"""Unused weights: {unused_weights}""" ) def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_, snake_case_, snake_case_ ) -> Union[str, Any]: """simple docstring""" a = full_name.split('''conv_layers.''' )[-1] a = name.split('''.''' ) a = int(items[0] ) a = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) a = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) a = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor[layer_id].layer_norm.bias.data.shape} was found.""" ) a = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.""" ) a = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(snake_case_ ) @torch.no_grad() def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_=None, snake_case_=None, snake_case_=True ) -> Union[str, Any]: """simple docstring""" if config_path is not None: a = UniSpeechSatConfig.from_pretrained(snake_case_ ) else: a = UniSpeechSatConfig() a = '''''' if is_finetuned: a = UniSpeechSatForCTC(snake_case_ ) else: a = UniSpeechSatForPreTraining(snake_case_ ) a , a , a = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path], arg_overrides={'''data''': '''/'''.join(dict_path.split('''/''' )[:-1] )} ) a = model[0].eval() recursively_load_weights(snake_case_, snake_case_ ) hf_wavavec.save_pretrained(snake_case_ ) if __name__ == "__main__": UpperCamelCase__ : Optional[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 fairseq checkpoint""") parser.add_argument("""--dict_path""", default=None, type=str, help="""Path to dict of fine-tuned model""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") parser.add_argument( """--not_finetuned""", action="""store_true""", help="""Whether the model to convert is a fine-tuned model or not""" ) UpperCamelCase__ : int = parser.parse_args() convert_unispeech_sat_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
330
1
from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( ImageTextPipelineOutput, UniDiffuserPipeline, ) else: from .modeling_text_decoder import UniDiffuserTextDecoder from .modeling_uvit import UniDiffuserModel, UTransformeraDModel from .pipeline_unidiffuser import ImageTextPipelineOutput, UniDiffuserPipeline
330
import pytest from datasets import inspect_metric, list_metrics, load_metric @pytest.fixture def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> List[str]: """simple docstring""" monkeypatch.setattr('''datasets.utils.deprecation_utils._emitted_deprecation_warnings''', set() ) @pytest.fixture def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> Optional[int]: """simple docstring""" class lowerCamelCase_ : def __init__( self : Dict ,__lowerCamelCase : List[str] ): '''simple docstring''' a = metric_id class lowerCamelCase_ : SCREAMING_SNAKE_CASE_ = [MetricMock(a_ ) for metric_id in ['accuracy', 'mse', 'precision', 'codeparrot/apps_metric']] def SCREAMING_SNAKE_CASE_ ( self : Dict ): '''simple docstring''' return self._metrics monkeypatch.setattr('''datasets.inspect.huggingface_hub''', HfhMock() ) @pytest.mark.parametrize( '''func, args''', [(load_metric, ('''metrics/mse''',)), (list_metrics, ()), (inspect_metric, ('''metrics/mse''', '''tmp_path'''))] ) def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_, snake_case_, snake_case_ ) -> Tuple: """simple docstring""" if "tmp_path" in args: a = tuple(arg if arg != '''tmp_path''' else tmp_path for arg in args ) with pytest.warns(snake_case_, match='''https://huggingface.co/docs/evaluate''' ): func(*snake_case_ )
330
1
from typing import List, Optional, Union import numpy as np from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import PaddingStrategy, TensorType, logging UpperCamelCase__ : Optional[Any] = logging.get_logger(__name__) class lowerCamelCase_ ( a_ ): SCREAMING_SNAKE_CASE_ = ['input_values', 'padding_mask'] def __init__( self : List[Any] ,__lowerCamelCase : int = 1 ,__lowerCamelCase : int = 2_40_00 ,__lowerCamelCase : float = 0.0 ,__lowerCamelCase : float = None ,__lowerCamelCase : float = None ,**__lowerCamelCase : Tuple ,): '''simple docstring''' super().__init__(feature_size=__lowerCamelCase ,sampling_rate=__lowerCamelCase ,padding_value=__lowerCamelCase ,**__lowerCamelCase ) a = chunk_length_s a = overlap @property def SCREAMING_SNAKE_CASE_ ( self : List[str] ): '''simple docstring''' if self.chunk_length_s is None: return None else: return int(self.chunk_length_s * self.sampling_rate ) @property def SCREAMING_SNAKE_CASE_ ( self : int ): '''simple docstring''' if self.chunk_length_s is None or self.overlap is None: return None else: return max(1 ,int((1.0 - self.overlap) * self.chunk_length ) ) def __call__( self : Optional[int] ,__lowerCamelCase : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] ,__lowerCamelCase : Optional[Union[bool, str, PaddingStrategy]] = None ,__lowerCamelCase : Optional[bool] = False ,__lowerCamelCase : Optional[int] = None ,__lowerCamelCase : Optional[Union[str, TensorType]] = None ,__lowerCamelCase : Optional[int] = None ,): '''simple docstring''' if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( F"""The model corresponding to this feature extractor: {self} was trained using a sampling rate of""" F""" {self.sampling_rate}. Please make sure that the provided audio input was sampled with""" F""" {self.sampling_rate} and not {sampling_rate}.""" ) else: logger.warning( '''It is strongly recommended to pass the `sampling_rate` argument to this function. ''' '''Failing to do so can result in silent errors that might be hard to debug.''' ) if padding and truncation: raise ValueError('''Both padding and truncation were set. Make sure you only set one.''' ) elif padding is None: # by default let's pad the inputs a = True a = bool( isinstance(__lowerCamelCase ,(list, tuple) ) and (isinstance(raw_audio[0] ,(np.ndarray, tuple, list) )) ) if is_batched: a = [np.asarray(__lowerCamelCase ,dtype=np.floataa ).T for audio in raw_audio] elif not is_batched and not isinstance(__lowerCamelCase ,np.ndarray ): a = np.asarray(__lowerCamelCase ,dtype=np.floataa ) elif isinstance(__lowerCamelCase ,np.ndarray ) and raw_audio.dtype is np.dtype(np.floataa ): a = raw_audio.astype(np.floataa ) # always return batch if not is_batched: a = [np.asarray(__lowerCamelCase ).T] # verify inputs are valid for idx, example in enumerate(__lowerCamelCase ): if example.ndim > 2: raise ValueError(F"""Expected input shape (channels, length) but got shape {example.shape}""" ) if self.feature_size == 1 and example.ndim != 1: raise ValueError(F"""Expected mono audio but example has {example.shape[-1]} channels""" ) if self.feature_size == 2 and example.shape[-1] != 2: raise ValueError(F"""Expected stereo audio but example has {example.shape[-1]} channels""" ) a = None a = BatchFeature({'''input_values''': raw_audio} ) if self.chunk_stride is not None and self.chunk_length is not None and max_length is None: if truncation: a = min(array.shape[0] for array in raw_audio ) a = int(np.floor(max_length / self.chunk_stride ) ) a = (nb_step - 1) * self.chunk_stride + self.chunk_length elif padding: a = max(array.shape[0] for array in raw_audio ) a = int(np.ceil(max_length / self.chunk_stride ) ) a = (nb_step - 1) * self.chunk_stride + self.chunk_length a = '''max_length''' else: a = input_values # normal padding on batch if padded_inputs is None: a = self.pad( __lowerCamelCase ,max_length=__lowerCamelCase ,truncation=__lowerCamelCase ,padding=__lowerCamelCase ,return_attention_mask=__lowerCamelCase ,) if padding: a = padded_inputs.pop('''attention_mask''' ) a = [] for example in padded_inputs.pop('''input_values''' ): if self.feature_size == 1: a = example[..., None] input_values.append(example.T ) a = input_values if return_tensors is not None: a = padded_inputs.convert_to_tensors(__lowerCamelCase ) return padded_inputs
330
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase__ : str = logging.get_logger(__name__) UpperCamelCase__ : Optional[int] = { """studio-ousia/luke-base""": """https://huggingface.co/studio-ousia/luke-base/resolve/main/config.json""", """studio-ousia/luke-large""": """https://huggingface.co/studio-ousia/luke-large/resolve/main/config.json""", } class lowerCamelCase_ ( a_ ): SCREAMING_SNAKE_CASE_ = 'luke' def __init__( self : Dict ,__lowerCamelCase : Optional[Any]=5_02_67 ,__lowerCamelCase : str=50_00_00 ,__lowerCamelCase : Any=7_68 ,__lowerCamelCase : int=2_56 ,__lowerCamelCase : Optional[int]=12 ,__lowerCamelCase : Tuple=12 ,__lowerCamelCase : Any=30_72 ,__lowerCamelCase : Any="gelu" ,__lowerCamelCase : Any=0.1 ,__lowerCamelCase : Tuple=0.1 ,__lowerCamelCase : Tuple=5_12 ,__lowerCamelCase : int=2 ,__lowerCamelCase : Optional[int]=0.02 ,__lowerCamelCase : List[Any]=1e-12 ,__lowerCamelCase : Dict=True ,__lowerCamelCase : Tuple=None ,__lowerCamelCase : Any=1 ,__lowerCamelCase : Dict=0 ,__lowerCamelCase : Any=2 ,**__lowerCamelCase : str ,): '''simple docstring''' super().__init__(pad_token_id=__lowerCamelCase ,bos_token_id=__lowerCamelCase ,eos_token_id=__lowerCamelCase ,**__lowerCamelCase ) a = vocab_size a = entity_vocab_size a = hidden_size a = entity_emb_size a = num_hidden_layers a = num_attention_heads a = hidden_act a = intermediate_size a = hidden_dropout_prob a = attention_probs_dropout_prob a = max_position_embeddings a = type_vocab_size a = initializer_range a = layer_norm_eps a = use_entity_aware_attention a = classifier_dropout
330
1
import argparse from typing import Dict import tensorflow as tf import torch from tqdm import tqdm from transformers import BigBirdPegasusConfig, BigBirdPegasusForConditionalGeneration UpperCamelCase__ : Any = [ # tf -> hf ("""/""", """."""), ("""layer_""", """layers."""), ("""kernel""", """weight"""), ("""beta""", """bias"""), ("""gamma""", """weight"""), ("""pegasus""", """model"""), ] UpperCamelCase__ : Optional[Any] = [ (""".output.dense""", """.fc2"""), ("""intermediate.LayerNorm""", """final_layer_norm"""), ("""intermediate.dense""", """fc1"""), ] UpperCamelCase__ : Optional[Any] = ( INIT_COMMON + [ ("""attention.self.LayerNorm""", """self_attn_layer_norm"""), ("""attention.output.dense""", """self_attn.out_proj"""), ("""attention.self""", """self_attn"""), ("""attention.encdec.LayerNorm""", """encoder_attn_layer_norm"""), ("""attention.encdec_output.dense""", """encoder_attn.out_proj"""), ("""attention.encdec""", """encoder_attn"""), ("""key""", """k_proj"""), ("""value""", """v_proj"""), ("""query""", """q_proj"""), ("""decoder.LayerNorm""", """decoder.layernorm_embedding"""), ] + END_COMMON ) UpperCamelCase__ : List[str] = ( INIT_COMMON + [ ("""embeddings.word_embeddings""", """shared.weight"""), ("""embeddings.position_embeddings""", """embed_positions.weight"""), ("""attention.self.LayerNorm""", """self_attn_layer_norm"""), ("""attention.output.dense""", """self_attn.output"""), ("""attention.self""", """self_attn.self"""), ("""encoder.LayerNorm""", """encoder.layernorm_embedding"""), ] + END_COMMON ) UpperCamelCase__ : Optional[int] = [ """encdec/key/bias""", """encdec/query/bias""", """encdec/value/bias""", """self/key/bias""", """self/query/bias""", """self/value/bias""", """encdec_output/dense/bias""", """attention/output/dense/bias""", ] def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> List[Any]: """simple docstring""" for tf_name, hf_name in patterns: a = k.replace(snake_case_, snake_case_ ) return k def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> BigBirdPegasusForConditionalGeneration: """simple docstring""" a = BigBirdPegasusConfig(**snake_case_ ) a = BigBirdPegasusForConditionalGeneration(snake_case_ ) a = torch_model.state_dict() a = {} # separating decoder weights a = {k: tf_weights[k] for k in tf_weights if k.startswith('''pegasus/decoder''' )} a = {k: tf_weights[k] for k in tf_weights if not k.startswith('''pegasus/decoder''' )} for k, v in tqdm(decoder_weights.items(), '''tf -> hf conversion''' ): a = [k.endswith(snake_case_ ) for ending in KEYS_TO_IGNORE] if any(snake_case_ ): continue a = DECODER_PATTERNS a = rename_state_dict_key(snake_case_, snake_case_ ) if new_k not in state_dict: raise ValueError(f"""could not find new key {new_k} in state dict. (converted from {k})""" ) if any(True if i in k else False for i in ['''dense''', '''query''', '''key''', '''value'''] ): a = v.T a = torch.from_numpy(snake_case_ ) assert v.shape == state_dict[new_k].shape, f"""{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}""" for k, v in tqdm(remaining_weights.items(), '''tf -> hf conversion''' ): a = [k.endswith(snake_case_ ) for ending in KEYS_TO_IGNORE] if any(snake_case_ ): continue a = REMAINING_PATTERNS a = rename_state_dict_key(snake_case_, snake_case_ ) if new_k not in state_dict and k != "pegasus/embeddings/position_embeddings": raise ValueError(f"""could not find new key {new_k} in state dict. (converted from {k})""" ) if any(True if i in k else False for i in ['''dense''', '''query''', '''key''', '''value'''] ): a = v.T a = torch.from_numpy(snake_case_ ) if k != "pegasus/embeddings/position_embeddings": assert v.shape == state_dict[new_k].shape, f"""{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}""" a = mapping['''model.embed_positions.weight'''] a = mapping.pop('''model.embed_positions.weight''' ) a , a = torch_model.load_state_dict(snake_case_, strict=snake_case_ ) a = [ k for k in missing if k not in [ '''final_logits_bias''', '''model.encoder.embed_tokens.weight''', '''model.decoder.embed_tokens.weight''', '''lm_head.weight''', ] ] assert unexpected_missing == [], f"""no matches found for the following torch keys {unexpected_missing}""" assert extra == [], f"""no matches found for the following tf keys {extra}""" return torch_model def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> Dict: """simple docstring""" a = tf.train.list_variables(snake_case_ ) a = {} a = ['''global_step'''] for name, shape in tqdm(snake_case_, desc='''converting tf checkpoint to dict''' ): a = any(pat in name for pat in ignore_name ) if skip_key: continue a = tf.train.load_variable(snake_case_, snake_case_ ) a = array return tf_weights def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_ ) -> int: """simple docstring""" a = get_tf_weights_as_numpy(snake_case_ ) a = convert_bigbird_pegasus(snake_case_, snake_case_ ) torch_model.save_pretrained(snake_case_ ) if __name__ == "__main__": UpperCamelCase__ : str = argparse.ArgumentParser() parser.add_argument("""--tf_ckpt_path""", type=str, help="""passed to tf.train.list_variables""") parser.add_argument("""--save_dir""", default=None, type=str, help="""Path to the output PyTorch model.""") UpperCamelCase__ : int = parser.parse_args() UpperCamelCase__ : Tuple = {} convert_bigbird_pegasus_ckpt_to_pytorch(args.tf_ckpt_path, args.save_dir, config_update=config_update)
330
import numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler from tensorflow.keras.layers import LSTM, Dense from tensorflow.keras.models import Sequential if __name__ == "__main__": UpperCamelCase__ : Optional[int] = pd.read_csv("""sample_data.csv""", header=None) UpperCamelCase__ : Tuple = df.shape[:1][0] # If you're using some other dataset input the target column UpperCamelCase__ : List[Any] = df.iloc[:, 1:2] UpperCamelCase__ : Union[str, Any] = actual_data.values.reshape(len_data, 1) UpperCamelCase__ : List[Any] = MinMaxScaler().fit_transform(actual_data) UpperCamelCase__ : Optional[Any] = 10 UpperCamelCase__ : int = 5 UpperCamelCase__ : List[str] = 20 UpperCamelCase__ : Optional[int] = len_data - periods * look_back UpperCamelCase__ : Union[str, Any] = actual_data[:division] UpperCamelCase__ : str = actual_data[division - look_back :] UpperCamelCase__ , UpperCamelCase__ : Union[str, Any] = [], [] UpperCamelCase__ , UpperCamelCase__ : str = [], [] for i in range(0, len(train_data) - forward_days - look_back + 1): train_x.append(train_data[i : i + look_back]) train_y.append(train_data[i + look_back : i + look_back + forward_days]) for i in range(0, len(test_data) - forward_days - look_back + 1): test_x.append(test_data[i : i + look_back]) test_y.append(test_data[i + look_back : i + look_back + forward_days]) UpperCamelCase__ : List[str] = np.array(train_x) UpperCamelCase__ : Optional[Any] = np.array(test_x) UpperCamelCase__ : Tuple = np.array([list(i.ravel()) for i in train_y]) UpperCamelCase__ : Optional[Any] = np.array([list(i.ravel()) for i in test_y]) UpperCamelCase__ : Union[str, Any] = Sequential() model.add(LSTM(128, input_shape=(look_back, 1), return_sequences=True)) model.add(LSTM(64, input_shape=(128, 1))) model.add(Dense(forward_days)) model.compile(loss="""mean_squared_error""", optimizer="""adam""") UpperCamelCase__ : Tuple = model.fit( x_train, y_train, epochs=150, verbose=1, shuffle=True, batch_size=4 ) UpperCamelCase__ : Tuple = model.predict(x_test)
330
1
from PIL import Image def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> Image: """simple docstring""" a = (2_5_9 * (level + 2_5_5)) / (2_5_5 * (2_5_9 - level)) def contrast(snake_case_ ) -> int: return int(1_2_8 + factor * (c - 1_2_8) ) return img.point(snake_case_ ) if __name__ == "__main__": # Load image with Image.open("""image_data/lena.jpg""") as img: # Change contrast to 170 UpperCamelCase__ : Union[str, Any] = change_contrast(img, 170) cont_img.save("""image_data/lena_high_contrast.png""", format="""png""")
330
import os import time import pytest from datasets.utils.filelock import FileLock, Timeout def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> Tuple: """simple docstring""" a = FileLock(str(tmpdir / '''foo.lock''' ) ) a = FileLock(str(tmpdir / '''foo.lock''' ) ) a = 0.01 with locka.acquire(): with pytest.raises(snake_case_ ): a = time.time() locka.acquire(snake_case_ ) assert time.time() - _start > timeout def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> Optional[int]: """simple docstring""" a = '''a''' * 1_0_0_0 + '''.lock''' a = FileLock(str(tmpdir / filename ) ) assert locka._lock_file.endswith('''.lock''' ) assert not locka._lock_file.endswith(snake_case_ ) assert len(os.path.basename(locka._lock_file ) ) <= 2_5_5 a = FileLock(tmpdir / filename ) with locka.acquire(): with pytest.raises(snake_case_ ): locka.acquire(0 )
330
1
import argparse import os import numpy as np import tensorflow as tf import torch from transformers import BertModel def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_ ) -> Optional[Any]: """simple docstring""" a = ('''dense.weight''', '''attention.self.query''', '''attention.self.key''', '''attention.self.value''') a = ( ('''layer.''', '''layer_'''), ('''word_embeddings.weight''', '''word_embeddings'''), ('''position_embeddings.weight''', '''position_embeddings'''), ('''token_type_embeddings.weight''', '''token_type_embeddings'''), ('''.''', '''/'''), ('''LayerNorm/weight''', '''LayerNorm/gamma'''), ('''LayerNorm/bias''', '''LayerNorm/beta'''), ('''weight''', '''kernel'''), ) if not os.path.isdir(snake_case_ ): os.makedirs(snake_case_ ) a = model.state_dict() def to_tf_var_name(snake_case_ ): for patt, repl in iter(snake_case_ ): a = name.replace(snake_case_, snake_case_ ) return f"""bert/{name}""" def create_tf_var(snake_case_, snake_case_, snake_case_ ): a = tf.dtypes.as_dtype(tensor.dtype ) a = tf.get_variable(dtype=snake_case_, shape=tensor.shape, name=snake_case_, initializer=tf.zeros_initializer() ) session.run(tf.variables_initializer([tf_var] ) ) session.run(snake_case_ ) return tf_var tf.reset_default_graph() with tf.Session() as session: for var_name in state_dict: a = to_tf_var_name(snake_case_ ) a = state_dict[var_name].numpy() if any(x in var_name for x in tensors_to_transpose ): a = torch_tensor.T a = create_tf_var(tensor=snake_case_, name=snake_case_, session=snake_case_ ) tf.keras.backend.set_value(snake_case_, snake_case_ ) a = session.run(snake_case_ ) print(f"""Successfully created {tf_name}: {np.allclose(snake_case_, snake_case_ )}""" ) a = tf.train.Saver(tf.trainable_variables() ) saver.save(snake_case_, os.path.join(snake_case_, model_name.replace('''-''', '''_''' ) + '''.ckpt''' ) ) def SCREAMING_SNAKE_CASE__ ( snake_case_=None ) -> Optional[int]: """simple docstring""" a = argparse.ArgumentParser() parser.add_argument('''--model_name''', type=snake_case_, required=snake_case_, help='''model name e.g. bert-base-uncased''' ) parser.add_argument( '''--cache_dir''', type=snake_case_, default=snake_case_, required=snake_case_, help='''Directory containing pytorch model''' ) parser.add_argument('''--pytorch_model_path''', type=snake_case_, required=snake_case_, help='''/path/to/<pytorch-model-name>.bin''' ) parser.add_argument('''--tf_cache_dir''', type=snake_case_, required=snake_case_, help='''Directory in which to save tensorflow model''' ) a = parser.parse_args(snake_case_ ) a = BertModel.from_pretrained( pretrained_model_name_or_path=args.model_name, state_dict=torch.load(args.pytorch_model_path ), cache_dir=args.cache_dir, ) convert_pytorch_checkpoint_to_tf(model=snake_case_, ckpt_dir=args.tf_cache_dir, model_name=args.model_name ) if __name__ == "__main__": main()
330
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase__ : Optional[int] = logging.get_logger(__name__) UpperCamelCase__ : Dict = { """facebook/vit-mae-base""": """https://huggingface.co/facebook/vit-mae-base/resolve/main/config.json""", # See all ViT MAE models at https://huggingface.co/models?filter=vit-mae } class lowerCamelCase_ ( a_ ): SCREAMING_SNAKE_CASE_ = 'vit_mae' def __init__( self : Dict ,__lowerCamelCase : Any=7_68 ,__lowerCamelCase : Optional[Any]=12 ,__lowerCamelCase : List[str]=12 ,__lowerCamelCase : Optional[int]=30_72 ,__lowerCamelCase : int="gelu" ,__lowerCamelCase : Union[str, Any]=0.0 ,__lowerCamelCase : Optional[int]=0.0 ,__lowerCamelCase : Dict=0.02 ,__lowerCamelCase : List[Any]=1e-12 ,__lowerCamelCase : Dict=2_24 ,__lowerCamelCase : str=16 ,__lowerCamelCase : Union[str, Any]=3 ,__lowerCamelCase : Optional[Any]=True ,__lowerCamelCase : Dict=16 ,__lowerCamelCase : List[str]=5_12 ,__lowerCamelCase : int=8 ,__lowerCamelCase : int=20_48 ,__lowerCamelCase : Optional[Any]=0.75 ,__lowerCamelCase : int=False ,**__lowerCamelCase : Any ,): '''simple docstring''' super().__init__(**__lowerCamelCase ) 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 a = decoder_num_attention_heads a = decoder_hidden_size a = decoder_num_hidden_layers a = decoder_intermediate_size a = mask_ratio a = norm_pix_loss
330
1
import importlib import math import os from dataclasses import dataclass from enum import Enum from typing import Any, Dict, Optional, Tuple, Union import flax import jax.numpy as jnp from ..utils import BaseOutput UpperCamelCase__ : int = """scheduler_config.json""" class lowerCamelCase_ ( a_ ): SCREAMING_SNAKE_CASE_ = 1 SCREAMING_SNAKE_CASE_ = 2 SCREAMING_SNAKE_CASE_ = 3 SCREAMING_SNAKE_CASE_ = 4 SCREAMING_SNAKE_CASE_ = 5 @dataclass class lowerCamelCase_ ( a_ ): SCREAMING_SNAKE_CASE_ = 42 class lowerCamelCase_ : SCREAMING_SNAKE_CASE_ = SCHEDULER_CONFIG_NAME SCREAMING_SNAKE_CASE_ = ['dtype'] SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = True @classmethod def SCREAMING_SNAKE_CASE_ ( cls : Union[str, Any] ,__lowerCamelCase : Dict[str, Any] = None ,__lowerCamelCase : Optional[str] = None ,__lowerCamelCase : str=False ,**__lowerCamelCase : Union[str, Any] ,): '''simple docstring''' a , a = cls.load_config( pretrained_model_name_or_path=__lowerCamelCase ,subfolder=__lowerCamelCase ,return_unused_kwargs=__lowerCamelCase ,**__lowerCamelCase ,) a , a = cls.from_config(__lowerCamelCase ,return_unused_kwargs=__lowerCamelCase ,**__lowerCamelCase ) if hasattr(__lowerCamelCase ,'''create_state''' ) and getattr(__lowerCamelCase ,'''has_state''' ,__lowerCamelCase ): a = scheduler.create_state() if return_unused_kwargs: return scheduler, state, unused_kwargs return scheduler, state def SCREAMING_SNAKE_CASE_ ( self : Dict ,__lowerCamelCase : Union[str, os.PathLike] ,__lowerCamelCase : bool = False ,**__lowerCamelCase : List[Any] ): '''simple docstring''' self.save_config(save_directory=__lowerCamelCase ,push_to_hub=__lowerCamelCase ,**__lowerCamelCase ) @property def SCREAMING_SNAKE_CASE_ ( self : List[Any] ): '''simple docstring''' return self._get_compatibles() @classmethod def SCREAMING_SNAKE_CASE_ ( cls : Optional[Any] ): '''simple docstring''' a = list(set([cls.__name__] + cls._compatibles ) ) a = importlib.import_module(__name__.split('''.''' )[0] ) a = [ getattr(__lowerCamelCase ,__lowerCamelCase ) for c in compatible_classes_str if hasattr(__lowerCamelCase ,__lowerCamelCase ) ] return compatible_classes def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> jnp.ndarray: """simple docstring""" assert len(snake_case_ ) >= x.ndim return jnp.broadcast_to(x.reshape(x.shape + (1,) * (len(snake_case_ ) - x.ndim) ), snake_case_ ) def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_=0.999, snake_case_=jnp.floataa ) -> jnp.ndarray: """simple docstring""" def alpha_bar(snake_case_ ): return math.cos((time_step + 0.008) / 1.008 * math.pi / 2 ) ** 2 a = [] for i in range(snake_case_ ): a = i / num_diffusion_timesteps a = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar(snake_case_ ) / alpha_bar(snake_case_ ), snake_case_ ) ) return jnp.array(snake_case_, dtype=snake_case_ ) @flax.struct.dataclass class lowerCamelCase_ : SCREAMING_SNAKE_CASE_ = 42 SCREAMING_SNAKE_CASE_ = 42 SCREAMING_SNAKE_CASE_ = 42 @classmethod def SCREAMING_SNAKE_CASE_ ( cls : Optional[Any] ,__lowerCamelCase : str ): '''simple docstring''' a = scheduler.config if config.trained_betas is not None: a = jnp.asarray(config.trained_betas ,dtype=scheduler.dtype ) elif config.beta_schedule == "linear": a = jnp.linspace(config.beta_start ,config.beta_end ,config.num_train_timesteps ,dtype=scheduler.dtype ) elif config.beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. a = ( jnp.linspace( config.beta_start**0.5 ,config.beta_end**0.5 ,config.num_train_timesteps ,dtype=scheduler.dtype ) ** 2 ) elif config.beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule a = betas_for_alpha_bar(config.num_train_timesteps ,dtype=scheduler.dtype ) else: raise NotImplementedError( F"""beta_schedule {config.beta_schedule} is not implemented for scheduler {scheduler.__class__.__name__}""" ) a = 1.0 - betas a = jnp.cumprod(__lowerCamelCase ,axis=0 ) return cls( alphas=__lowerCamelCase ,betas=__lowerCamelCase ,alphas_cumprod=__lowerCamelCase ,) def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_, snake_case_ ) -> Optional[Any]: """simple docstring""" a = state.alphas_cumprod a = alphas_cumprod[timesteps] ** 0.5 a = sqrt_alpha_prod.flatten() a = broadcast_to_shape_from_left(snake_case_, original_samples.shape ) a = (1 - alphas_cumprod[timesteps]) ** 0.5 a = sqrt_one_minus_alpha_prod.flatten() a = broadcast_to_shape_from_left(snake_case_, original_samples.shape ) return sqrt_alpha_prod, sqrt_one_minus_alpha_prod def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_, snake_case_ ) -> Tuple: """simple docstring""" a , a = get_sqrt_alpha_prod(snake_case_, snake_case_, snake_case_, snake_case_ ) a = sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise return noisy_samples def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_, snake_case_ ) -> Dict: """simple docstring""" a , a = get_sqrt_alpha_prod(snake_case_, snake_case_, snake_case_, snake_case_ ) a = sqrt_alpha_prod * noise - sqrt_one_minus_alpha_prod * sample return velocity
330
def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> Union[str, Any]: """simple docstring""" stooge(snake_case_, 0, len(snake_case_ ) - 1 ) return arr def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_ ) -> Optional[Any]: """simple docstring""" if i >= h: return # If first element is smaller than the last then swap them if arr[i] > arr[h]: a , a = arr[h], arr[i] # If there are more than 2 elements in the array if h - i + 1 > 2: a = (int)((h - i + 1) / 3 ) # Recursively sort first 2/3 elements stooge(snake_case_, snake_case_, (h - t) ) # Recursively sort last 2/3 elements stooge(snake_case_, i + t, (snake_case_) ) # Recursively sort first 2/3 elements stooge(snake_case_, snake_case_, (h - t) ) if __name__ == "__main__": UpperCamelCase__ : Dict = input("""Enter numbers separated by a comma:\n""").strip() UpperCamelCase__ : Optional[int] = [int(item) for item in user_input.split(""",""")] print(stooge_sort(unsorted))
330
1
from __future__ import annotations from functools import lru_cache from math import ceil UpperCamelCase__ : Tuple = 100 UpperCamelCase__ : str = set(range(3, NUM_PRIMES, 2)) primes.add(2) UpperCamelCase__ : int for prime in range(3, ceil(NUM_PRIMES**0.5), 2): if prime not in primes: continue primes.difference_update(set(range(prime * prime, NUM_PRIMES, prime))) @lru_cache(maxsize=1_0_0 ) def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> set[int]: """simple docstring""" if number_to_partition < 0: return set() elif number_to_partition == 0: return {1} a = set() a = 42 a = 42 for prime in primes: if prime > number_to_partition: continue for sub in partition(number_to_partition - prime ): ret.add(sub * prime ) return ret def SCREAMING_SNAKE_CASE__ ( snake_case_ = 5_0_0_0 ) -> int | None: """simple docstring""" for number_to_partition in range(1, snake_case_ ): if len(partition(snake_case_ ) ) > number_unique_partitions: return number_to_partition return None if __name__ == "__main__": print(F"{solution() = }")
330
import json import os import re import unicodedata from json.encoder import INFINITY from typing import Any, Dict, List, Optional, Tuple, Union import numpy as np import regex from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, is_flax_available, is_tf_available, is_torch_available, logging from ...utils.generic import _is_jax, _is_numpy UpperCamelCase__ : Any = logging.get_logger(__name__) UpperCamelCase__ : Optional[Any] = { """artists_file""": """artists.json""", """lyrics_file""": """lyrics.json""", """genres_file""": """genres.json""", } UpperCamelCase__ : Union[str, Any] = { """artists_file""": { """jukebox""": """https://huggingface.co/ArthurZ/jukebox/blob/main/artists.json""", }, """genres_file""": { """jukebox""": """https://huggingface.co/ArthurZ/jukebox/blob/main/genres.json""", }, """lyrics_file""": { """jukebox""": """https://huggingface.co/ArthurZ/jukebox/blob/main/lyrics.json""", }, } UpperCamelCase__ : str = { """jukebox""": 512, } class lowerCamelCase_ ( a_ ): SCREAMING_SNAKE_CASE_ = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE_ = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE_ = PRETRAINED_LYRIC_TOKENS_SIZES SCREAMING_SNAKE_CASE_ = ['input_ids', 'attention_mask'] def __init__( self : Optional[Any] ,__lowerCamelCase : Optional[Any] ,__lowerCamelCase : List[Any] ,__lowerCamelCase : Tuple ,__lowerCamelCase : Union[str, Any]=["v3", "v2", "v2"] ,__lowerCamelCase : List[Any]=5_12 ,__lowerCamelCase : Tuple=5 ,__lowerCamelCase : List[Any]="<|endoftext|>" ,**__lowerCamelCase : List[str] ,): '''simple docstring''' a = AddedToken(__lowerCamelCase ,lstrip=__lowerCamelCase ,rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase ,__lowerCamelCase ) else unk_token super().__init__( unk_token=__lowerCamelCase ,n_genres=__lowerCamelCase ,version=__lowerCamelCase ,max_n_lyric_tokens=__lowerCamelCase ,**__lowerCamelCase ,) a = version a = max_n_lyric_tokens a = n_genres with open(__lowerCamelCase ,encoding='''utf-8''' ) as vocab_handle: a = json.load(__lowerCamelCase ) with open(__lowerCamelCase ,encoding='''utf-8''' ) as vocab_handle: a = json.load(__lowerCamelCase ) with open(__lowerCamelCase ,encoding='''utf-8''' ) as vocab_handle: a = json.load(__lowerCamelCase ) a = r'''[^A-Za-z0-9.,:;!?\-\'\"()\[\] \t\n]+''' # In v2, we had a n_vocab=80 and in v3 we missed + and so n_vocab=79 of characters. if len(self.lyrics_encoder ) == 79: a = oov.replace(r'''\-\'''' ,r'''\-+\'''' ) a = regex.compile(__lowerCamelCase ) a = {v: k for k, v in self.artists_encoder.items()} a = {v: k for k, v in self.genres_encoder.items()} a = {v: k for k, v in self.lyrics_encoder.items()} @property def SCREAMING_SNAKE_CASE_ ( self : str ): '''simple docstring''' return len(self.artists_encoder ) + len(self.genres_encoder ) + len(self.lyrics_encoder ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ): '''simple docstring''' return dict(self.artists_encoder ,self.genres_encoder ,self.lyrics_encoder ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ,__lowerCamelCase : Optional[int] ,__lowerCamelCase : Optional[Any] ,__lowerCamelCase : List[Any] ): '''simple docstring''' a = [self.artists_encoder.get(__lowerCamelCase ,0 ) for artist in list_artists] for genres in range(len(__lowerCamelCase ) ): a = [self.genres_encoder.get(__lowerCamelCase ,0 ) for genre in list_genres[genres]] a = list_genres[genres] + [-1] * (self.n_genres - len(list_genres[genres] )) a = [[self.lyrics_encoder.get(__lowerCamelCase ,0 ) for character in list_lyrics[0]], [], []] return artists_id, list_genres, lyric_ids def SCREAMING_SNAKE_CASE_ ( self : Tuple ,__lowerCamelCase : List[str] ): '''simple docstring''' return list(__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ,__lowerCamelCase : List[Any] ,__lowerCamelCase : Any ,__lowerCamelCase : Optional[int] ,**__lowerCamelCase : Optional[Any] ): '''simple docstring''' a , a , a = self.prepare_for_tokenization(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ) a = self._tokenize(__lowerCamelCase ) return artist, genre, lyrics def SCREAMING_SNAKE_CASE_ ( self : int ,__lowerCamelCase : str ,__lowerCamelCase : str ,__lowerCamelCase : str ,__lowerCamelCase : bool = False ): '''simple docstring''' for idx in range(len(self.version ) ): if self.version[idx] == "v3": a = artists[idx].lower() a = [genres[idx].lower()] else: a = self._normalize(artists[idx] ) + '''.v2''' a = [ self._normalize(__lowerCamelCase ) + '''.v2''' for genre in genres[idx].split('''_''' ) ] # split is for the full dictionary with combined genres if self.version[0] == "v2": a = regex.compile(r'''[^A-Za-z0-9.,:;!?\-\'\"()\[\] \t\n]+''' ) a = '''ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,:;!?-+\'\"()[] \t\n''' a = {vocab[index]: index + 1 for index in range(len(__lowerCamelCase ) )} a = 0 a = len(__lowerCamelCase ) + 1 a = self.vocab a = {v: k for k, v in self.vocab.items()} a = '''''' else: a = regex.compile(r'''[^A-Za-z0-9.,:;!?\-+\'\"()\[\] \t\n]+''' ) a = self._run_strip_accents(__lowerCamelCase ) a = lyrics.replace('''\\''' ,'''\n''' ) a = self.out_of_vocab.sub('''''' ,__lowerCamelCase ), [], [] return artists, genres, lyrics def SCREAMING_SNAKE_CASE_ ( self : str ,__lowerCamelCase : int ): '''simple docstring''' a = unicodedata.normalize('''NFD''' ,__lowerCamelCase ) a = [] for char in text: a = unicodedata.category(__lowerCamelCase ) if cat == "Mn": continue output.append(__lowerCamelCase ) return "".join(__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ,__lowerCamelCase : str ): '''simple docstring''' a = ( [chr(__lowerCamelCase ) for i in range(ord('''a''' ) ,ord('''z''' ) + 1 )] + [chr(__lowerCamelCase ) for i in range(ord('''A''' ) ,ord('''Z''' ) + 1 )] + [chr(__lowerCamelCase ) for i in range(ord('''0''' ) ,ord('''9''' ) + 1 )] + ['''.'''] ) a = frozenset(__lowerCamelCase ) a = re.compile(r'''_+''' ) a = ''''''.join([c if c in accepted else '''_''' for c in text.lower()] ) a = pattern.sub('''_''' ,__lowerCamelCase ).strip('''_''' ) return text def SCREAMING_SNAKE_CASE_ ( self : List[str] ,__lowerCamelCase : List[str] ): '''simple docstring''' return " ".join(__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : Any ,__lowerCamelCase : str ,__lowerCamelCase : Optional[Union[str, TensorType]] = None ,__lowerCamelCase : bool = False ): '''simple docstring''' if not isinstance(__lowerCamelCase ,__lowerCamelCase ): a = TensorType(__lowerCamelCase ) # Get a function reference for the correct framework if tensor_type == TensorType.TENSORFLOW: if not is_tf_available(): raise ImportError( '''Unable to convert output to TensorFlow tensors format, TensorFlow is not installed.''' ) import tensorflow as tf a = tf.constant a = tf.is_tensor elif tensor_type == TensorType.PYTORCH: if not is_torch_available(): raise ImportError('''Unable to convert output to PyTorch tensors format, PyTorch is not installed.''' ) import torch a = torch.tensor a = torch.is_tensor elif tensor_type == TensorType.JAX: if not is_flax_available(): raise ImportError('''Unable to convert output to JAX tensors format, JAX is not installed.''' ) import jax.numpy as jnp # noqa: F811 a = jnp.array a = _is_jax else: a = np.asarray a = _is_numpy # Do the tensor conversion in batch try: if prepend_batch_axis: a = [inputs] if not is_tensor(__lowerCamelCase ): a = as_tensor(__lowerCamelCase ) except: # noqa E722 raise ValueError( '''Unable to create tensor, you should probably activate truncation and/or padding ''' '''with \'padding=True\' \'truncation=True\' to have batched tensors with the same length.''' ) return inputs def __call__( self : Tuple ,__lowerCamelCase : Tuple ,__lowerCamelCase : Optional[int] ,__lowerCamelCase : List[str]="" ,__lowerCamelCase : List[Any]="pt" ): '''simple docstring''' a = [0, 0, 0] a = [artist] * len(self.version ) a = [genres] * len(self.version ) a , a , a = self.tokenize(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ) a , a , a = self._convert_token_to_id(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ) a = [-INFINITY] * len(full_tokens[-1] ) a = [ self.convert_to_tensors( [input_ids + [artists_id[i]] + genres_ids[i] + full_tokens[i]] ,tensor_type=__lowerCamelCase ) for i in range(len(self.version ) ) ] return BatchEncoding({'''input_ids''': input_ids, '''attention_masks''': attention_masks} ) def SCREAMING_SNAKE_CASE_ ( self : int ,__lowerCamelCase : str ,__lowerCamelCase : Optional[str] = None ): '''simple docstring''' 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['''artists_file'''] ) with open(__lowerCamelCase ,'''w''' ,encoding='''utf-8''' ) as f: f.write(json.dumps(self.artists_encoder ,ensure_ascii=__lowerCamelCase ) ) a = os.path.join( __lowerCamelCase ,(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''genres_file'''] ) with open(__lowerCamelCase ,'''w''' ,encoding='''utf-8''' ) as f: f.write(json.dumps(self.genres_encoder ,ensure_ascii=__lowerCamelCase ) ) a = os.path.join( __lowerCamelCase ,(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''lyrics_file'''] ) with open(__lowerCamelCase ,'''w''' ,encoding='''utf-8''' ) as f: f.write(json.dumps(self.lyrics_encoder ,ensure_ascii=__lowerCamelCase ) ) return (artists_file, genres_file, lyrics_file) def SCREAMING_SNAKE_CASE_ ( self : Any ,__lowerCamelCase : Any ,__lowerCamelCase : Any ,__lowerCamelCase : str ): '''simple docstring''' a = self.artists_decoder.get(__lowerCamelCase ) a = [self.genres_decoder.get(__lowerCamelCase ) for genre in genres_index] a = [self.lyrics_decoder.get(__lowerCamelCase ) for character in lyric_index] return artist, genres, lyrics
330
1
from __future__ import annotations UpperCamelCase__ : List[Any] = [-10, -5, 0, 5, 5.1, 11, 13, 21, 3, 4, -21, -10, -5, -1, 0] UpperCamelCase__ : str = [-5, 0, 5, 5.1, 11, 13, 21, -1, 4, -1, -10, -5, -1, 0, -1] def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> list[float]: """simple docstring""" a = [] a = len(snake_case_ ) for i in range(snake_case_ ): a = -1 for j in range(i + 1, snake_case_ ): if arr[i] < arr[j]: a = arr[j] break result.append(snake_case_ ) return result def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> list[float]: """simple docstring""" a = [] for i, outer in enumerate(snake_case_ ): a = -1 for inner in arr[i + 1 :]: if outer < inner: a = inner break result.append(snake_case_ ) return result def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> list[float]: """simple docstring""" a = len(snake_case_ ) a = [] a = [-1] * arr_size for index in reversed(range(snake_case_ ) ): if stack: while stack[-1] <= arr[index]: stack.pop() if not stack: break if stack: a = stack[-1] stack.append(arr[index] ) return result if __name__ == "__main__": from doctest import testmod from timeit import timeit testmod() print(next_greatest_element_slow(arr)) print(next_greatest_element_fast(arr)) print(next_greatest_element(arr)) UpperCamelCase__ : List[str] = ( """from __main__ import arr, next_greatest_element_slow, """ """next_greatest_element_fast, next_greatest_element""" ) print( """next_greatest_element_slow():""", timeit("""next_greatest_element_slow(arr)""", setup=setup), ) print( """next_greatest_element_fast():""", timeit("""next_greatest_element_fast(arr)""", setup=setup), ) print( """ next_greatest_element():""", timeit("""next_greatest_element(arr)""", setup=setup), )
330
# This script creates a super tiny model that is useful inside tests, when we just want to test that # the machinery works, without needing to the check the quality of the outcomes. # # This version creates a tiny vocab first, and then a tiny model - so the outcome is truly tiny - # all files ~60KB. As compared to taking a full-size model, reducing to the minimum its layers and # emb dimensions, but keeping the full vocab + merges files, leading to ~3MB in total for all files. # The latter is done by `fsmt-make-super-tiny-model.py`. # # It will be used then as "stas/tiny-wmt19-en-ru" from pathlib import Path import json import tempfile from transformers import FSMTTokenizer, FSMTConfig, FSMTForConditionalGeneration from transformers.models.fsmt.tokenization_fsmt import VOCAB_FILES_NAMES UpperCamelCase__ : Optional[Any] = """tiny-wmt19-en-ru""" # Build # borrowed from a test UpperCamelCase__ : Any = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """w</w>""", """r</w>""", """t</w>""", """lo""", """low""", """er</w>""", """low</w>""", """lowest</w>""", """newer</w>""", """wider</w>""", """<unk>""", ] UpperCamelCase__ : List[Any] = dict(zip(vocab, range(len(vocab)))) UpperCamelCase__ : Any = ["""l o 123""", """lo w 1456""", """e r</w> 1789""", """"""] with tempfile.TemporaryDirectory() as tmpdirname: UpperCamelCase__ : Optional[Any] = Path(tmpdirname) UpperCamelCase__ : Tuple = build_dir / VOCAB_FILES_NAMES["""src_vocab_file"""] UpperCamelCase__ : int = build_dir / VOCAB_FILES_NAMES["""tgt_vocab_file"""] UpperCamelCase__ : Union[str, Any] = build_dir / VOCAB_FILES_NAMES["""merges_file"""] with open(src_vocab_file, """w""") as fp: fp.write(json.dumps(vocab_tokens)) with open(tgt_vocab_file, """w""") as fp: fp.write(json.dumps(vocab_tokens)) with open(merges_file, """w""") as fp: fp.write("""\n""".join(merges)) UpperCamelCase__ : Dict = FSMTTokenizer( langs=["""en""", """ru"""], src_vocab_size=len(vocab), tgt_vocab_size=len(vocab), src_vocab_file=src_vocab_file, tgt_vocab_file=tgt_vocab_file, merges_file=merges_file, ) UpperCamelCase__ : Union[str, Any] = FSMTConfig( langs=["""ru""", """en"""], src_vocab_size=1_000, tgt_vocab_size=1_000, d_model=4, encoder_layers=1, decoder_layers=1, encoder_ffn_dim=4, decoder_ffn_dim=4, encoder_attention_heads=1, decoder_attention_heads=1, ) UpperCamelCase__ : Union[str, Any] = FSMTForConditionalGeneration(config) print(F"num of params {tiny_model.num_parameters()}") # Test UpperCamelCase__ : List[str] = tokenizer(["""Making tiny model"""], return_tensors="""pt""") UpperCamelCase__ : Tuple = tiny_model(**batch) print("""test output:""", len(outputs.logits[0])) # Save tiny_model.half() # makes it smaller tiny_model.save_pretrained(mname_tiny) tokenizer.save_pretrained(mname_tiny) print(F"Generated {mname_tiny}") # Upload # transformers-cli upload tiny-wmt19-en-ru
330
1
from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Features, Value from .base import TaskTemplate @dataclass(frozen=a_ ) class lowerCamelCase_ ( a_ ): SCREAMING_SNAKE_CASE_ = field(default='language-modeling' , metadata={'include_in_asdict_even_if_is_default': True} ) SCREAMING_SNAKE_CASE_ = Features({'text': Value('string' )} ) SCREAMING_SNAKE_CASE_ = Features({} ) SCREAMING_SNAKE_CASE_ = "text" @property def SCREAMING_SNAKE_CASE_ ( self : int ): '''simple docstring''' return {self.text_column: "text"}
330
import inspect import os import torch from transformers import AutoModel from transformers.testing_utils import mockenv_context from transformers.trainer_utils import set_seed import accelerate from accelerate.accelerator import Accelerator from accelerate.state import AcceleratorState from accelerate.test_utils.testing import ( AccelerateTestCase, TempDirTestCase, execute_subprocess_async, require_cuda, require_fsdp, require_multi_gpu, slow, ) from accelerate.utils.constants import ( FSDP_AUTO_WRAP_POLICY, FSDP_BACKWARD_PREFETCH, FSDP_SHARDING_STRATEGY, FSDP_STATE_DICT_TYPE, ) from accelerate.utils.dataclasses import FullyShardedDataParallelPlugin from accelerate.utils.other import patch_environment set_seed(42) UpperCamelCase__ : Optional[Any] = """bert-base-cased""" UpperCamelCase__ : int = """fp16""" UpperCamelCase__ : str = """bf16""" UpperCamelCase__ : List[Any] = [FPaa, BFaa] @require_fsdp @require_cuda class lowerCamelCase_ ( a_ ): def SCREAMING_SNAKE_CASE_ ( self : int ): '''simple docstring''' super().setUp() a = dict( ACCELERATE_USE_FSDP='''true''' ,MASTER_ADDR='''localhost''' ,MASTER_PORT='''10999''' ,RANK='''0''' ,LOCAL_RANK='''0''' ,WORLD_SIZE='''1''' ,) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ): '''simple docstring''' from torch.distributed.fsdp.fully_sharded_data_parallel import ShardingStrategy for i, strategy in enumerate(__lowerCamelCase ): a = self.dist_env.copy() a = F"""{i + 1}""" a = strategy with mockenv_context(**__lowerCamelCase ): a = FullyShardedDataParallelPlugin() self.assertEqual(fsdp_plugin.sharding_strategy ,ShardingStrategy(i + 1 ) ) def SCREAMING_SNAKE_CASE_ ( self : Any ): '''simple docstring''' from torch.distributed.fsdp.fully_sharded_data_parallel import BackwardPrefetch for i, prefetch_policy in enumerate(__lowerCamelCase ): a = self.dist_env.copy() a = prefetch_policy with mockenv_context(**__lowerCamelCase ): a = FullyShardedDataParallelPlugin() if prefetch_policy == "NO_PREFETCH": self.assertIsNone(fsdp_plugin.backward_prefetch ) else: self.assertEqual(fsdp_plugin.backward_prefetch ,BackwardPrefetch(i + 1 ) ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ): '''simple docstring''' from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType for i, state_dict_type in enumerate(__lowerCamelCase ): a = self.dist_env.copy() a = state_dict_type with mockenv_context(**__lowerCamelCase ): a = FullyShardedDataParallelPlugin() self.assertEqual(fsdp_plugin.state_dict_type ,StateDictType(i + 1 ) ) if state_dict_type == "FULL_STATE_DICT": self.assertTrue(fsdp_plugin.state_dict_config.offload_to_cpu ) self.assertTrue(fsdp_plugin.state_dict_config.ranka_only ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ): '''simple docstring''' a = AutoModel.from_pretrained(__lowerCamelCase ) for policy in FSDP_AUTO_WRAP_POLICY: a = self.dist_env.copy() a = policy if policy == "TRANSFORMER_BASED_WRAP": a = '''BertLayer''' elif policy == "SIZE_BASED_WRAP": a = '''2000''' with mockenv_context(**__lowerCamelCase ): a = FullyShardedDataParallelPlugin() fsdp_plugin.set_auto_wrap_policy(__lowerCamelCase ) if policy == "NO_WRAP": self.assertIsNone(fsdp_plugin.auto_wrap_policy ) else: self.assertIsNotNone(fsdp_plugin.auto_wrap_policy ) a = self.dist_env.copy() a = '''TRANSFORMER_BASED_WRAP''' a = '''T5Layer''' with mockenv_context(**__lowerCamelCase ): a = FullyShardedDataParallelPlugin() with self.assertRaises(__lowerCamelCase ) as cm: fsdp_plugin.set_auto_wrap_policy(__lowerCamelCase ) self.assertTrue('''Could not find the transformer layer class to wrap in the model.''' in str(cm.exception ) ) a = self.dist_env.copy() a = '''SIZE_BASED_WRAP''' a = '''0''' with mockenv_context(**__lowerCamelCase ): a = FullyShardedDataParallelPlugin() fsdp_plugin.set_auto_wrap_policy(__lowerCamelCase ) self.assertIsNone(fsdp_plugin.auto_wrap_policy ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ): '''simple docstring''' from torch.distributed.fsdp.fully_sharded_data_parallel import MixedPrecision from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler for mp_dtype in dtypes: a = self.dist_env.copy() a = mp_dtype with mockenv_context(**__lowerCamelCase ): a = Accelerator() if mp_dtype == "fp16": a = torch.floataa elif mp_dtype == "bf16": a = torch.bfloataa a = MixedPrecision(param_dtype=__lowerCamelCase ,reduce_dtype=__lowerCamelCase ,buffer_dtype=__lowerCamelCase ) self.assertEqual(accelerator.state.fsdp_plugin.mixed_precision_policy ,__lowerCamelCase ) if mp_dtype == FPaa: self.assertTrue(isinstance(accelerator.scaler ,__lowerCamelCase ) ) elif mp_dtype == BFaa: self.assertIsNone(accelerator.scaler ) AcceleratorState._reset_state(__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ): '''simple docstring''' from torch.distributed.fsdp.fully_sharded_data_parallel import CPUOffload for flag in [True, False]: a = self.dist_env.copy() a = str(__lowerCamelCase ).lower() with mockenv_context(**__lowerCamelCase ): a = FullyShardedDataParallelPlugin() self.assertEqual(fsdp_plugin.cpu_offload ,CPUOffload(offload_params=__lowerCamelCase ) ) @require_fsdp @require_multi_gpu @slow class lowerCamelCase_ ( a_ ): def SCREAMING_SNAKE_CASE_ ( self : List[Any] ): '''simple docstring''' super().setUp() a = 0.82 a = [ '''fsdp_shard_grad_op_transformer_based_wrap''', '''fsdp_full_shard_transformer_based_wrap''', ] a = { '''multi_gpu_fp16''': 32_00, '''fsdp_shard_grad_op_transformer_based_wrap_fp16''': 20_00, '''fsdp_full_shard_transformer_based_wrap_fp16''': 19_00, # Disabling below test as it overwhelms the RAM memory usage # on CI self-hosted runner leading to tests getting killed. # "fsdp_full_shard_cpu_offload_transformer_based_wrap_fp32": 1500, # fp16 was leading to indefinite hang } a = 1_60 a = 1_60 a = inspect.getfile(accelerate.test_utils ) a = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''external_deps'''] ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ): '''simple docstring''' a = os.path.join(self.test_scripts_folder ,'''test_performance.py''' ) a = ['''accelerate''', '''launch''', '''--num_processes=2''', '''--num_machines=1''', '''--machine_rank=0''', '''--use_fsdp'''] for config in self.performance_configs: a = cmd.copy() for i, strategy in enumerate(__lowerCamelCase ): if strategy.lower() in config: cmd_config.append(F"""--fsdp_sharding_strategy={i+1}""" ) break if "fp32" in config: cmd_config.append('''--mixed_precision=no''' ) else: cmd_config.append('''--mixed_precision=fp16''' ) if "cpu_offload" in config: cmd_config.append('''--fsdp_offload_params=True''' ) for policy in FSDP_AUTO_WRAP_POLICY: if policy.lower() in config: cmd_config.append(F"""--fsdp_auto_wrap_policy={policy}""" ) break if policy == "TRANSFORMER_BASED_WRAP": cmd_config.append('''--fsdp_transformer_layer_cls_to_wrap=BertLayer''' ) elif policy == "SIZE_BASED_WRAP": cmd_config.append('''--fsdp_min_num_params=2000''' ) cmd_config.extend( [ self.test_file_path, F"""--output_dir={self.tmpdir}""", F"""--performance_lower_bound={self.performance_lower_bound}""", ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__lowerCamelCase ,env=os.environ.copy() ) def SCREAMING_SNAKE_CASE_ ( self : Any ): '''simple docstring''' a = os.path.join(self.test_scripts_folder ,'''test_checkpointing.py''' ) a = [ '''accelerate''', '''launch''', '''--num_processes=2''', '''--num_machines=1''', '''--machine_rank=0''', '''--use_fsdp''', '''--mixed_precision=fp16''', '''--fsdp_transformer_layer_cls_to_wrap=BertLayer''', ] for i, strategy in enumerate(__lowerCamelCase ): a = cmd.copy() cmd_config.append(F"""--fsdp_sharding_strategy={i+1}""" ) if strategy != "FULL_SHARD": continue a = len(__lowerCamelCase ) for state_dict_type in FSDP_STATE_DICT_TYPE: a = cmd_config[:state_dict_config_index] cmd_config.append(F"""--fsdp_state_dict_type={state_dict_type}""" ) cmd_config.extend( [ self.test_file_path, F"""--output_dir={self.tmpdir}""", '''--partial_train_epoch=1''', ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__lowerCamelCase ,env=os.environ.copy() ) a = cmd_config[:-1] a = os.path.join(self.tmpdir ,'''epoch_0''' ) cmd_config.extend( [ F"""--resume_from_checkpoint={resume_from_checkpoint}""", ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__lowerCamelCase ,env=os.environ.copy() ) def SCREAMING_SNAKE_CASE_ ( self : int ): '''simple docstring''' a = os.path.join(self.test_scripts_folder ,'''test_peak_memory_usage.py''' ) a = [ '''accelerate''', '''launch''', '''--num_processes=2''', '''--num_machines=1''', '''--machine_rank=0''', ] for spec, peak_mem_upper_bound in self.peak_memory_usage_upper_bound.items(): a = cmd.copy() if "fp16" in spec: cmd_config.extend(['''--mixed_precision=fp16'''] ) else: cmd_config.extend(['''--mixed_precision=no'''] ) if "multi_gpu" in spec: continue else: cmd_config.extend(['''--use_fsdp'''] ) for i, strategy in enumerate(__lowerCamelCase ): if strategy.lower() in spec: cmd_config.append(F"""--fsdp_sharding_strategy={i+1}""" ) break if "cpu_offload" in spec: cmd_config.append('''--fsdp_offload_params=True''' ) for policy in FSDP_AUTO_WRAP_POLICY: if policy.lower() in spec: cmd_config.append(F"""--fsdp_auto_wrap_policy={policy}""" ) break if policy == "TRANSFORMER_BASED_WRAP": cmd_config.append('''--fsdp_transformer_layer_cls_to_wrap=BertLayer''' ) elif policy == "SIZE_BASED_WRAP": cmd_config.append('''--fsdp_min_num_params=2000''' ) cmd_config.extend( [ self.test_file_path, F"""--output_dir={self.tmpdir}""", F"""--peak_memory_upper_bound={peak_mem_upper_bound}""", F"""--n_train={self.n_train}""", F"""--n_val={self.n_val}""", ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__lowerCamelCase ,env=os.environ.copy() )
330
1
import inspect import jax import jax.lax as lax import jax.numpy as jnp from ..utils import add_start_docstrings from ..utils.logging import get_logger UpperCamelCase__ : List[Any] = get_logger(__name__) UpperCamelCase__ : Union[str, Any] = R""" Args: input_ids (`jnp.ndarray` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`PreTrainedTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) scores (`jnp.ndarray` of shape `(batch_size, config.vocab_size)`): Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam search or log softmax for each vocabulary token when using beam search kwargs (`Dict[str, Any]`, *optional*): Additional logits processor specific kwargs. Return: `jnp.ndarray` of shape `(batch_size, config.vocab_size)`: The processed prediction scores. """ class lowerCamelCase_ : @add_start_docstrings(__lowerCamelCase ) def __call__( self : Optional[Any] ,__lowerCamelCase : jnp.ndarray ,__lowerCamelCase : jnp.ndarray ): '''simple docstring''' raise NotImplementedError( F"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""" ) class lowerCamelCase_ : @add_start_docstrings(__lowerCamelCase ) def __call__( self : str ,__lowerCamelCase : jnp.ndarray ,__lowerCamelCase : jnp.ndarray ): '''simple docstring''' raise NotImplementedError( F"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""" ) class lowerCamelCase_ ( a_ ): @add_start_docstrings(__lowerCamelCase ) def __call__( self : int ,__lowerCamelCase : jnp.ndarray ,__lowerCamelCase : jnp.ndarray ,__lowerCamelCase : int ,**__lowerCamelCase : List[str] ): '''simple docstring''' for processor in self: a = inspect.signature(processor.__call__ ).parameters if len(__lowerCamelCase ) > 3: if not all(arg in kwargs for arg in list(function_args.keys() )[2:] ): raise ValueError( F"""Make sure that all the required parameters: {list(function_args.keys() )} for """ F"""{processor.__class__} are passed to the logits processor.""" ) a = processor(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ,**__lowerCamelCase ) else: a = processor(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ) return scores class lowerCamelCase_ ( a_ ): def __init__( self : Optional[int] ,__lowerCamelCase : float ): '''simple docstring''' if not isinstance(__lowerCamelCase ,__lowerCamelCase ) or not (temperature > 0): raise ValueError(F"""`temperature` has to be a strictly positive float, but is {temperature}""" ) a = temperature def __call__( self : List[Any] ,__lowerCamelCase : jnp.ndarray ,__lowerCamelCase : jnp.ndarray ,__lowerCamelCase : int ): '''simple docstring''' a = scores / self.temperature return scores class lowerCamelCase_ ( a_ ): def __init__( self : Optional[int] ,__lowerCamelCase : float ,__lowerCamelCase : float = -float('''Inf''' ) ,__lowerCamelCase : int = 1 ): '''simple docstring''' if not isinstance(__lowerCamelCase ,__lowerCamelCase ) or (top_p < 0 or top_p > 1.0): raise ValueError(F"""`top_p` has to be a float > 0 and < 1, but is {top_p}""" ) if not isinstance(__lowerCamelCase ,__lowerCamelCase ) or (min_tokens_to_keep < 1): raise ValueError(F"""`min_tokens_to_keep` has to be a positive integer, but is {min_tokens_to_keep}""" ) a = top_p a = filter_value a = min_tokens_to_keep def __call__( self : Dict ,__lowerCamelCase : jnp.ndarray ,__lowerCamelCase : jnp.ndarray ,__lowerCamelCase : int ): '''simple docstring''' a , a = lax.top_k(__lowerCamelCase ,scores.shape[-1] ) a = jnp.full_like(__lowerCamelCase ,self.filter_value ) a = jax.nn.softmax(__lowerCamelCase ,axis=-1 ).cumsum(axis=-1 ) a = cumulative_probs < self.top_p # include the token that is higher than top_p as well a = jnp.roll(__lowerCamelCase ,1 ) score_mask |= score_mask.at[:, 0].set(__lowerCamelCase ) # min tokens to keep a = score_mask.at[:, : self.min_tokens_to_keep].set(__lowerCamelCase ) a = jnp.where(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ) a = jax.lax.sort_key_val(__lowerCamelCase ,__lowerCamelCase )[-1] return next_scores class lowerCamelCase_ ( a_ ): def __init__( self : Tuple ,__lowerCamelCase : int ,__lowerCamelCase : float = -float('''Inf''' ) ,__lowerCamelCase : int = 1 ): '''simple docstring''' if not isinstance(__lowerCamelCase ,__lowerCamelCase ) or top_k <= 0: raise ValueError(F"""`top_k` has to be a strictly positive integer, but is {top_k}""" ) a = max(__lowerCamelCase ,__lowerCamelCase ) a = filter_value def __call__( self : Dict ,__lowerCamelCase : jnp.ndarray ,__lowerCamelCase : jnp.ndarray ,__lowerCamelCase : int ): '''simple docstring''' a , a = scores.shape a = jnp.full(batch_size * vocab_size ,self.filter_value ) a = min(self.top_k ,scores.shape[-1] ) # Safety check a , a = lax.top_k(__lowerCamelCase ,__lowerCamelCase ) a = jnp.broadcast_to((jnp.arange(__lowerCamelCase ) * vocab_size)[:, None] ,(batch_size, topk) ).flatten() a = topk_scores.flatten() a = topk_indices.flatten() + shift a = next_scores_flat.at[topk_indices_flat].set(__lowerCamelCase ) a = next_scores_flat.reshape(__lowerCamelCase ,__lowerCamelCase ) return next_scores class lowerCamelCase_ ( a_ ): def __init__( self : str ,__lowerCamelCase : int ): '''simple docstring''' a = bos_token_id def __call__( self : Dict ,__lowerCamelCase : jnp.ndarray ,__lowerCamelCase : jnp.ndarray ,__lowerCamelCase : int ): '''simple docstring''' a = jnp.full(scores.shape ,-float('''inf''' ) ) a = 1 - jnp.bool_(cur_len - 1 ) a = jnp.where(__lowerCamelCase ,new_scores.at[:, self.bos_token_id].set(0 ) ,__lowerCamelCase ) return scores class lowerCamelCase_ ( a_ ): def __init__( self : Tuple ,__lowerCamelCase : int ,__lowerCamelCase : int ): '''simple docstring''' a = max_length a = eos_token_id def __call__( self : Tuple ,__lowerCamelCase : jnp.ndarray ,__lowerCamelCase : jnp.ndarray ,__lowerCamelCase : int ): '''simple docstring''' a = jnp.full(scores.shape ,-float('''inf''' ) ) a = 1 - jnp.bool_(cur_len - self.max_length + 1 ) a = jnp.where(__lowerCamelCase ,new_scores.at[:, self.eos_token_id].set(0 ) ,__lowerCamelCase ) return scores class lowerCamelCase_ ( a_ ): def __init__( self : str ,__lowerCamelCase : int ,__lowerCamelCase : int ): '''simple docstring''' if not isinstance(__lowerCamelCase ,__lowerCamelCase ) or min_length < 0: raise ValueError(F"""`min_length` has to be a positive integer, but is {min_length}""" ) if not isinstance(__lowerCamelCase ,__lowerCamelCase ) or eos_token_id < 0: raise ValueError(F"""`eos_token_id` has to be a positive integer, but is {eos_token_id}""" ) a = min_length a = eos_token_id def __call__( self : List[str] ,__lowerCamelCase : jnp.ndarray ,__lowerCamelCase : jnp.ndarray ,__lowerCamelCase : int ): '''simple docstring''' a = 1 - jnp.clip(cur_len - self.min_length ,0 ,1 ) a = jnp.where(__lowerCamelCase ,scores.at[:, self.eos_token_id].set(-float('''inf''' ) ) ,__lowerCamelCase ) return scores class lowerCamelCase_ ( a_ ): def __init__( self : Dict ,__lowerCamelCase : List[str] ,__lowerCamelCase : int ): '''simple docstring''' a = list(__lowerCamelCase ) a = begin_index def __call__( self : List[str] ,__lowerCamelCase : str ,__lowerCamelCase : str ,__lowerCamelCase : int ): '''simple docstring''' a = 1 - jnp.bool_(cur_len - self.begin_index ) a = jnp.where(__lowerCamelCase ,scores.at[:, self.begin_suppress_tokens].set(-float('''inf''' ) ) ,__lowerCamelCase ) return scores class lowerCamelCase_ ( a_ ): def __init__( self : str ,__lowerCamelCase : list ): '''simple docstring''' a = list(__lowerCamelCase ) def __call__( self : str ,__lowerCamelCase : jnp.ndarray ,__lowerCamelCase : jnp.ndarray ,__lowerCamelCase : int ): '''simple docstring''' a = scores.at[..., self.suppress_tokens].set(-float('''inf''' ) ) return scores class lowerCamelCase_ ( a_ ): def __init__( self : int ,__lowerCamelCase : Optional[int] ): '''simple docstring''' a = dict(__lowerCamelCase ) # Converts the dictionary of format {index: token} containing the tokens to be forced to an array, where the # index of the array corresponds to the index of the token to be forced, for XLA compatibility. # Indexes without forced tokens will have a negative value. a = jnp.ones((max(force_token_map.keys() ) + 1) ,dtype=jnp.intaa ) * -1 for index, token in force_token_map.items(): if token is not None: a = force_token_array.at[index].set(__lowerCamelCase ) a = jnp.intaa(__lowerCamelCase ) def __call__( self : int ,__lowerCamelCase : jnp.ndarray ,__lowerCamelCase : jnp.ndarray ,__lowerCamelCase : int ): '''simple docstring''' def _force_token(__lowerCamelCase : List[str] ): a = scores.shape[0] a = self.force_token_array[generation_idx] a = jnp.ones_like(__lowerCamelCase ,dtype=scores.dtype ) * -float('''inf''' ) a = jnp.zeros((batch_size, 1) ,dtype=scores.dtype ) a = lax.dynamic_update_slice(__lowerCamelCase ,__lowerCamelCase ,(0, current_token) ) return new_scores a = lax.cond( cur_len >= self.force_token_array.shape[0] ,lambda: scores ,lambda: lax.cond( self.force_token_array[cur_len] >= 0 ,lambda: _force_token(__lowerCamelCase ) ,lambda: scores ,) ,) return scores class lowerCamelCase_ ( a_ ): def __init__( self : Optional[Any] ,__lowerCamelCase : Union[str, Any] ,__lowerCamelCase : List[str] ,__lowerCamelCase : Optional[int] ): '''simple docstring''' a = generate_config.eos_token_id a = generate_config.no_timestamps_token_id a = generate_config.no_timestamps_token_id + 1 a = decoder_input_length + 1 if generate_config.is_multilingual: # room for language token and task token self.begin_index += 2 if hasattr(__lowerCamelCase ,'''max_initial_timestamp_index''' ): a = generate_config.max_initial_timestamp_index else: a = model_config.vocab_size if self.max_initial_timestamp_index is None: a = model_config.vocab_size def __call__( self : List[Any] ,__lowerCamelCase : int ,__lowerCamelCase : Optional[int] ,__lowerCamelCase : List[Any] ): '''simple docstring''' a = scores.at[:, self.no_timestamps_token_id].set(-float('''inf''' ) ) def handle_pairs(__lowerCamelCase : int ,__lowerCamelCase : Union[str, Any] ): a = jnp.where((cur_len - self.begin_index) >= 1 ,__lowerCamelCase ,__lowerCamelCase ) a = jnp.where( input_ids_k[cur_len - 1] >= self.timestamp_begin ,True and last_was_timestamp ,__lowerCamelCase ,) a = jnp.where((cur_len - self.begin_index) < 2 ,__lowerCamelCase ,__lowerCamelCase ) a = jnp.where( input_ids_k[cur_len - 2] >= self.timestamp_begin ,__lowerCamelCase ,__lowerCamelCase ,) return jnp.where( __lowerCamelCase ,jnp.where( penultimate_was_timestamp > 0 ,scores_k.at[self.timestamp_begin :].set(-float('''inf''' ) ) ,scores_k.at[: self.eos_token_id].set(-float('''inf''' ) ) ,) ,__lowerCamelCase ,) a = jax.vmap(__lowerCamelCase )(__lowerCamelCase ,__lowerCamelCase ) a = jnp.where(cur_len == self.begin_index ,__lowerCamelCase ,__lowerCamelCase ) a = jnp.where( self.max_initial_timestamp_index is not None ,True and apply_max_initial_timestamp ,__lowerCamelCase ,) a = self.timestamp_begin + self.max_initial_timestamp_index a = jnp.where( __lowerCamelCase ,scores.at[:, last_allowed + 1 :].set(-float('''inf''' ) ) ,__lowerCamelCase ,) # if sum of probability over timestamps is above any other token, sample timestamp a = jax.nn.log_softmax(__lowerCamelCase ,axis=-1 ) def handle_cumulative_probs(__lowerCamelCase : Any ,__lowerCamelCase : int ): a = jax.nn.logsumexp(logprobs_k[self.timestamp_begin :] ,axis=-1 ) a = jnp.max(logprobs_k[: self.timestamp_begin] ) return jnp.where( timestamp_logprob > max_text_token_logprob ,scores_k.at[: self.timestamp_begin].set(-float('''inf''' ) ) ,__lowerCamelCase ,) a = jax.vmap(__lowerCamelCase )(__lowerCamelCase ,__lowerCamelCase ) return scores
330
from __future__ import annotations import os from collections.abc import Mapping UpperCamelCase__ : Any = tuple[int, int] class lowerCamelCase_ : def __init__( self : Optional[Any] ,__lowerCamelCase : set[int] ,__lowerCamelCase : Mapping[EdgeT, int] ): '''simple docstring''' a = vertices a = { (min(__lowerCamelCase ), max(__lowerCamelCase )): weight for edge, weight in edges.items() } def SCREAMING_SNAKE_CASE_ ( self : str ,__lowerCamelCase : EdgeT ,__lowerCamelCase : int ): '''simple docstring''' self.vertices.add(edge[0] ) self.vertices.add(edge[1] ) a = weight def SCREAMING_SNAKE_CASE_ ( self : Dict ): '''simple docstring''' a = Graph({min(self.vertices )} ,{} ) a = 42 a = 42 a = 42 a = 42 while len(subgraph.vertices ) < len(self.vertices ): a = max(self.edges.values() ) + 1 for edge, weight in self.edges.items(): if (edge[0] in subgraph.vertices) ^ (edge[1] in subgraph.vertices): if weight < min_weight: a = edge a = weight subgraph.add_edge(__lowerCamelCase ,__lowerCamelCase ) return subgraph def SCREAMING_SNAKE_CASE__ ( snake_case_ = "p107_network.txt" ) -> int: """simple docstring""" a = os.path.abspath(os.path.dirname(snake_case_ ) ) a = os.path.join(snake_case_, snake_case_ ) a = {} a = 42 a = 42 a = 42 with open(snake_case_ ) as f: a = f.read().strip().split('''\n''' ) a = [line.split(''',''' ) for line in data] for edgea in range(1, len(snake_case_ ) ): for edgea in range(snake_case_ ): if adjaceny_matrix[edgea][edgea] != "-": a = int(adjaceny_matrix[edgea][edgea] ) a = Graph(set(range(len(snake_case_ ) ) ), snake_case_ ) a = graph.prims_algorithm() a = sum(graph.edges.values() ) a = sum(subgraph.edges.values() ) return initial_total - optimal_total if __name__ == "__main__": print(F"{solution() = }")
330
1
import qiskit def SCREAMING_SNAKE_CASE__ ( snake_case_ = 2 ) -> qiskit.result.counts.Counts: """simple docstring""" a = qubits # Using Aer's simulator a = qiskit.Aer.get_backend('''aer_simulator''' ) # Creating a Quantum Circuit acting on the q register a = qiskit.QuantumCircuit(snake_case_, snake_case_ ) # Adding a H gate on qubit 0 (now q0 in superposition) circuit.h(0 ) for i in range(1, snake_case_ ): # Adding CX (CNOT) gate circuit.cx(i - 1, snake_case_ ) # Mapping the quantum measurement to the classical bits circuit.measure(list(range(snake_case_ ) ), list(range(snake_case_ ) ) ) # Now measuring any one qubit would affect other qubits to collapse # their super position and have same state as the measured one. # Executing the circuit on the simulator a = qiskit.execute(snake_case_, snake_case_, shots=1_0_0_0 ) return job.result().get_counts(snake_case_ ) if __name__ == "__main__": print(F"Total count for various states are: {quantum_entanglement(3)}")
330
from typing import Optional, Tuple, Union import tensorflow as tf from ...activations_tf import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_tf_outputs import ( TFBaseModelOutputWithNoAttention, TFBaseModelOutputWithPoolingAndNoAttention, TFSequenceClassifierOutput, ) from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs from ...tf_utils import shape_list from ...utils import logging from .configuration_regnet import RegNetConfig UpperCamelCase__ : List[Any] = logging.get_logger(__name__) # General docstring UpperCamelCase__ : List[Any] = """RegNetConfig""" # Base docstring UpperCamelCase__ : Dict = """facebook/regnet-y-040""" UpperCamelCase__ : int = [1, 1_088, 7, 7] # Image classification docstring UpperCamelCase__ : Optional[Any] = """facebook/regnet-y-040""" UpperCamelCase__ : Dict = """tabby, tabby cat""" UpperCamelCase__ : Dict = [ """facebook/regnet-y-040""", # See all regnet models at https://huggingface.co/models?filter=regnet ] class lowerCamelCase_ ( tf.keras.layers.Layer ): def __init__( self : List[str] ,__lowerCamelCase : int ,__lowerCamelCase : int = 3 ,__lowerCamelCase : int = 1 ,__lowerCamelCase : int = 1 ,__lowerCamelCase : Optional[str] = "relu" ,**__lowerCamelCase : str ,): '''simple docstring''' super().__init__(**__lowerCamelCase ) # The padding and conv has been verified in # https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb a = tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2 ) a = tf.keras.layers.ConvaD( filters=__lowerCamelCase ,kernel_size=__lowerCamelCase ,strides=__lowerCamelCase ,padding='''VALID''' ,groups=__lowerCamelCase ,use_bias=__lowerCamelCase ,name='''convolution''' ,) a = tf.keras.layers.BatchNormalization(epsilon=1e-5 ,momentum=0.9 ,name='''normalization''' ) a = ACTaFN[activation] if activation is not None else tf.identity def SCREAMING_SNAKE_CASE_ ( self : str ,__lowerCamelCase : List[str] ): '''simple docstring''' a = self.convolution(self.padding(__lowerCamelCase ) ) a = self.normalization(__lowerCamelCase ) a = self.activation(__lowerCamelCase ) return hidden_state class lowerCamelCase_ ( tf.keras.layers.Layer ): def __init__( self : Any ,__lowerCamelCase : RegNetConfig ,**__lowerCamelCase : List[Any] ): '''simple docstring''' super().__init__(**__lowerCamelCase ) a = config.num_channels a = TFRegNetConvLayer( out_channels=config.embedding_size ,kernel_size=3 ,stride=2 ,activation=config.hidden_act ,name='''embedder''' ,) def SCREAMING_SNAKE_CASE_ ( self : Any ,__lowerCamelCase : Optional[Any] ): '''simple docstring''' a = shape_list(__lowerCamelCase )[1] if tf.executing_eagerly() and num_channels != self.num_channels: raise ValueError( '''Make sure that the channel dimension of the pixel values match with the one set in the configuration.''' ) # When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format. # So change the input format from `NCHW` to `NHWC`. # shape = (batch_size, in_height, in_width, in_channels=num_channels) a = tf.transpose(__lowerCamelCase ,perm=(0, 2, 3, 1) ) a = self.embedder(__lowerCamelCase ) return hidden_state class lowerCamelCase_ ( tf.keras.layers.Layer ): def __init__( self : str ,__lowerCamelCase : int ,__lowerCamelCase : int = 2 ,**__lowerCamelCase : Tuple ): '''simple docstring''' super().__init__(**__lowerCamelCase ) a = tf.keras.layers.ConvaD( filters=__lowerCamelCase ,kernel_size=1 ,strides=__lowerCamelCase ,use_bias=__lowerCamelCase ,name='''convolution''' ) a = tf.keras.layers.BatchNormalization(epsilon=1e-5 ,momentum=0.9 ,name='''normalization''' ) def SCREAMING_SNAKE_CASE_ ( self : Dict ,__lowerCamelCase : tf.Tensor ,__lowerCamelCase : bool = False ): '''simple docstring''' return self.normalization(self.convolution(__lowerCamelCase ) ,training=__lowerCamelCase ) class lowerCamelCase_ ( tf.keras.layers.Layer ): def __init__( self : List[Any] ,__lowerCamelCase : int ,__lowerCamelCase : int ,**__lowerCamelCase : str ): '''simple docstring''' super().__init__(**__lowerCamelCase ) a = tf.keras.layers.GlobalAveragePoolingaD(keepdims=__lowerCamelCase ,name='''pooler''' ) a = [ tf.keras.layers.ConvaD(filters=__lowerCamelCase ,kernel_size=1 ,activation='''relu''' ,name='''attention.0''' ), tf.keras.layers.ConvaD(filters=__lowerCamelCase ,kernel_size=1 ,activation='''sigmoid''' ,name='''attention.2''' ), ] def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ,__lowerCamelCase : Optional[Any] ): '''simple docstring''' a = self.pooler(__lowerCamelCase ) for layer_module in self.attention: a = layer_module(__lowerCamelCase ) a = hidden_state * pooled return hidden_state class lowerCamelCase_ ( tf.keras.layers.Layer ): def __init__( self : Union[str, Any] ,__lowerCamelCase : RegNetConfig ,__lowerCamelCase : int ,__lowerCamelCase : int ,__lowerCamelCase : int = 1 ,**__lowerCamelCase : Dict ): '''simple docstring''' super().__init__(**__lowerCamelCase ) a = in_channels != out_channels or stride != 1 a = max(1 ,out_channels // config.groups_width ) a = ( TFRegNetShortCut(__lowerCamelCase ,stride=__lowerCamelCase ,name='''shortcut''' ) if should_apply_shortcut else tf.keras.layers.Activation('''linear''' ,name='''shortcut''' ) ) # `self.layers` instead of `self.layer` because that is a reserved argument. a = [ TFRegNetConvLayer(__lowerCamelCase ,kernel_size=1 ,activation=config.hidden_act ,name='''layer.0''' ), TFRegNetConvLayer( __lowerCamelCase ,stride=__lowerCamelCase ,groups=__lowerCamelCase ,activation=config.hidden_act ,name='''layer.1''' ), TFRegNetConvLayer(__lowerCamelCase ,kernel_size=1 ,activation=__lowerCamelCase ,name='''layer.2''' ), ] a = ACTaFN[config.hidden_act] def SCREAMING_SNAKE_CASE_ ( self : List[str] ,__lowerCamelCase : Union[str, Any] ): '''simple docstring''' a = hidden_state for layer_module in self.layers: a = layer_module(__lowerCamelCase ) a = self.shortcut(__lowerCamelCase ) hidden_state += residual a = self.activation(__lowerCamelCase ) return hidden_state class lowerCamelCase_ ( tf.keras.layers.Layer ): def __init__( self : Dict ,__lowerCamelCase : RegNetConfig ,__lowerCamelCase : int ,__lowerCamelCase : int ,__lowerCamelCase : int = 1 ,**__lowerCamelCase : List[str] ): '''simple docstring''' super().__init__(**__lowerCamelCase ) a = in_channels != out_channels or stride != 1 a = max(1 ,out_channels // config.groups_width ) a = ( TFRegNetShortCut(__lowerCamelCase ,stride=__lowerCamelCase ,name='''shortcut''' ) if should_apply_shortcut else tf.keras.layers.Activation('''linear''' ,name='''shortcut''' ) ) a = [ TFRegNetConvLayer(__lowerCamelCase ,kernel_size=1 ,activation=config.hidden_act ,name='''layer.0''' ), TFRegNetConvLayer( __lowerCamelCase ,stride=__lowerCamelCase ,groups=__lowerCamelCase ,activation=config.hidden_act ,name='''layer.1''' ), TFRegNetSELayer(__lowerCamelCase ,reduced_channels=int(round(in_channels / 4 ) ) ,name='''layer.2''' ), TFRegNetConvLayer(__lowerCamelCase ,kernel_size=1 ,activation=__lowerCamelCase ,name='''layer.3''' ), ] a = ACTaFN[config.hidden_act] def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ,__lowerCamelCase : str ): '''simple docstring''' a = hidden_state for layer_module in self.layers: a = layer_module(__lowerCamelCase ) a = self.shortcut(__lowerCamelCase ) hidden_state += residual a = self.activation(__lowerCamelCase ) return hidden_state class lowerCamelCase_ ( tf.keras.layers.Layer ): def __init__( self : Optional[int] ,__lowerCamelCase : RegNetConfig ,__lowerCamelCase : int ,__lowerCamelCase : int ,__lowerCamelCase : int = 2 ,__lowerCamelCase : int = 2 ,**__lowerCamelCase : Optional[Any] ): '''simple docstring''' super().__init__(**__lowerCamelCase ) a = TFRegNetXLayer if config.layer_type == '''x''' else TFRegNetYLayer a = [ # downsampling is done in the first layer with stride of 2 layer(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ,stride=__lowerCamelCase ,name='''layers.0''' ), *[layer(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ,name=F"""layers.{i+1}""" ) for i in range(depth - 1 )], ] def SCREAMING_SNAKE_CASE_ ( self : Tuple ,__lowerCamelCase : int ): '''simple docstring''' for layer_module in self.layers: a = layer_module(__lowerCamelCase ) return hidden_state class lowerCamelCase_ ( tf.keras.layers.Layer ): def __init__( self : Union[str, Any] ,__lowerCamelCase : RegNetConfig ,**__lowerCamelCase : Optional[Any] ): '''simple docstring''' super().__init__(**__lowerCamelCase ) a = [] # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( TFRegNetStage( __lowerCamelCase ,config.embedding_size ,config.hidden_sizes[0] ,stride=2 if config.downsample_in_first_stage else 1 ,depth=config.depths[0] ,name='''stages.0''' ,) ) a = zip(config.hidden_sizes ,config.hidden_sizes[1:] ) for i, ((in_channels, out_channels), depth) in enumerate(zip(__lowerCamelCase ,config.depths[1:] ) ): self.stages.append(TFRegNetStage(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ,depth=__lowerCamelCase ,name=F"""stages.{i+1}""" ) ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ,__lowerCamelCase : tf.Tensor ,__lowerCamelCase : bool = False ,__lowerCamelCase : bool = True ): '''simple docstring''' a = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: a = hidden_states + (hidden_state,) a = stage_module(__lowerCamelCase ) if output_hidden_states: a = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return TFBaseModelOutputWithNoAttention(last_hidden_state=__lowerCamelCase ,hidden_states=__lowerCamelCase ) @keras_serializable class lowerCamelCase_ ( tf.keras.layers.Layer ): SCREAMING_SNAKE_CASE_ = RegNetConfig def __init__( self : Dict ,__lowerCamelCase : Optional[int] ,**__lowerCamelCase : Optional[Any] ): '''simple docstring''' super().__init__(**__lowerCamelCase ) a = config a = TFRegNetEmbeddings(__lowerCamelCase ,name='''embedder''' ) a = TFRegNetEncoder(__lowerCamelCase ,name='''encoder''' ) a = tf.keras.layers.GlobalAveragePoolingaD(keepdims=__lowerCamelCase ,name='''pooler''' ) @unpack_inputs def SCREAMING_SNAKE_CASE_ ( self : Tuple ,__lowerCamelCase : tf.Tensor ,__lowerCamelCase : Optional[bool] = None ,__lowerCamelCase : Optional[bool] = None ,__lowerCamelCase : bool = False ,): '''simple docstring''' a = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) a = return_dict if return_dict is not None else self.config.use_return_dict a = self.embedder(__lowerCamelCase ,training=__lowerCamelCase ) a = self.encoder( __lowerCamelCase ,output_hidden_states=__lowerCamelCase ,return_dict=__lowerCamelCase ,training=__lowerCamelCase ) a = encoder_outputs[0] a = self.pooler(__lowerCamelCase ) # Change to NCHW output format have uniformity in the modules a = tf.transpose(__lowerCamelCase ,perm=(0, 3, 1, 2) ) a = tf.transpose(__lowerCamelCase ,perm=(0, 3, 1, 2) ) # Change the other hidden state outputs to NCHW as well if output_hidden_states: a = tuple([tf.transpose(__lowerCamelCase ,perm=(0, 3, 1, 2) ) for h in encoder_outputs[1]] ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=__lowerCamelCase ,pooler_output=__lowerCamelCase ,hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states ,) class lowerCamelCase_ ( a_ ): SCREAMING_SNAKE_CASE_ = RegNetConfig SCREAMING_SNAKE_CASE_ = 'regnet' SCREAMING_SNAKE_CASE_ = 'pixel_values' @property def SCREAMING_SNAKE_CASE_ ( self : str ): '''simple docstring''' return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 2_24, 2_24) ,dtype=tf.floataa )} UpperCamelCase__ : Union[str, Any] = R""" Parameters: This model is a Tensorflow [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and behavior. config ([`RegNetConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights. """ UpperCamelCase__ : List[str] = R""" Args: pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`ConveNextImageProcessor.__call__`] for details. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. """ @add_start_docstrings( 'The bare RegNet model outputting raw features without any specific head on top.' , a_ , ) class lowerCamelCase_ ( a_ ): def __init__( self : Optional[int] ,__lowerCamelCase : RegNetConfig ,*__lowerCamelCase : int ,**__lowerCamelCase : Union[str, Any] ): '''simple docstring''' super().__init__(__lowerCamelCase ,*__lowerCamelCase ,**__lowerCamelCase ) a = TFRegNetMainLayer(__lowerCamelCase ,name='''regnet''' ) @unpack_inputs @add_start_docstrings_to_model_forward(__lowerCamelCase ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC ,output_type=__lowerCamelCase ,config_class=_CONFIG_FOR_DOC ,modality='''vision''' ,expected_output=_EXPECTED_OUTPUT_SHAPE ,) def SCREAMING_SNAKE_CASE_ ( self : Any ,__lowerCamelCase : tf.Tensor ,__lowerCamelCase : Optional[bool] = None ,__lowerCamelCase : Optional[bool] = None ,__lowerCamelCase : List[str]=False ,): '''simple docstring''' a = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) a = return_dict if return_dict is not None else self.config.use_return_dict a = self.regnet( pixel_values=__lowerCamelCase ,output_hidden_states=__lowerCamelCase ,return_dict=__lowerCamelCase ,training=__lowerCamelCase ,) if not return_dict: return (outputs[0],) + outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=outputs.last_hidden_state ,pooler_output=outputs.pooler_output ,hidden_states=outputs.hidden_states ,) @add_start_docstrings( '\n RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n ' , a_ , ) class lowerCamelCase_ ( a_ , a_ ): def __init__( self : Optional[int] ,__lowerCamelCase : RegNetConfig ,*__lowerCamelCase : str ,**__lowerCamelCase : Any ): '''simple docstring''' super().__init__(__lowerCamelCase ,*__lowerCamelCase ,**__lowerCamelCase ) a = config.num_labels a = TFRegNetMainLayer(__lowerCamelCase ,name='''regnet''' ) # classification head a = [ tf.keras.layers.Flatten(), tf.keras.layers.Dense(config.num_labels ,name='''classifier.1''' ) if config.num_labels > 0 else tf.identity, ] @unpack_inputs @add_start_docstrings_to_model_forward(__lowerCamelCase ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT ,output_type=__lowerCamelCase ,config_class=_CONFIG_FOR_DOC ,expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT ,) def SCREAMING_SNAKE_CASE_ ( self : Tuple ,__lowerCamelCase : tf.Tensor = None ,__lowerCamelCase : tf.Tensor = None ,__lowerCamelCase : bool = None ,__lowerCamelCase : bool = None ,__lowerCamelCase : Dict=False ,): '''simple docstring''' a = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) a = return_dict if return_dict is not None else self.config.use_return_dict a = self.regnet( __lowerCamelCase ,output_hidden_states=__lowerCamelCase ,return_dict=__lowerCamelCase ,training=__lowerCamelCase ) a = outputs.pooler_output if return_dict else outputs[1] a = self.classifier[0](__lowerCamelCase ) a = self.classifier[1](__lowerCamelCase ) a = None if labels is None else self.hf_compute_loss(labels=__lowerCamelCase ,logits=__lowerCamelCase ) if not return_dict: a = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return TFSequenceClassifierOutput(loss=__lowerCamelCase ,logits=__lowerCamelCase ,hidden_states=outputs.hidden_states )
330
1
import argparse import re import requests import torch # git clone https://github.com/salesforce/BLIP.git from models.blip import blip_decoder from models.blip_itm import blip_itm from models.blip_vqa import blip_vqa from PIL import Image from torchvision import transforms from torchvision.transforms.functional import InterpolationMode from transformers import ( BertTokenizer, BlipConfig, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, ) def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> Tuple: """simple docstring""" a = '''https://storage.googleapis.com/sfr-vision-language-research/BLIP/demo.jpg''' a = Image.open(requests.get(snake_case_, stream=snake_case_ ).raw ).convert('''RGB''' ) a = transforms.Compose( [ transforms.Resize((image_size, image_size), interpolation=InterpolationMode.BICUBIC ), transforms.ToTensor(), transforms.Normalize((0.4814_5466, 0.457_8275, 0.4082_1073), (0.2686_2954, 0.2613_0258, 0.2757_7711) ), ] ) a = transform(snake_case_ ).unsqueeze(0 ).to(snake_case_ ) return image def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> Optional[Any]: """simple docstring""" if "visual_encoder" in key: a = re.sub('''visual_encoder*''', '''vision_model.encoder''', snake_case_ ) if "blocks" in key: a = re.sub(r'''blocks''', '''layers''', snake_case_ ) if "attn" in key: a = re.sub(r'''attn''', '''self_attn''', snake_case_ ) if "norm1" in key: a = re.sub(r'''norm1''', '''layer_norm1''', snake_case_ ) if "norm2" in key: a = re.sub(r'''norm2''', '''layer_norm2''', snake_case_ ) if "encoder.norm" in key: a = re.sub(r'''encoder.norm''', '''post_layernorm''', snake_case_ ) if "encoder.patch_embed.proj" in key: a = re.sub(r'''encoder.patch_embed.proj''', '''embeddings.patch_embedding''', snake_case_ ) if "encoder.pos_embed" in key: a = re.sub(r'''encoder.pos_embed''', '''embeddings.position_embedding''', snake_case_ ) if "encoder.cls_token" in key: a = re.sub(r'''encoder.cls_token''', '''embeddings.class_embedding''', snake_case_ ) if "self_attn" in key: a = re.sub(r'''self_attn.proj''', '''self_attn.projection''', snake_case_ ) return key @torch.no_grad() def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_=None ) -> int: """simple docstring""" if config_path is not None: a = BlipConfig.from_pretrained(snake_case_ ) else: a = BlipConfig(projection_dim=5_1_2, text_config={}, vision_config={} ) a = BlipForConditionalGeneration(snake_case_ ).eval() a = '''https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_capfilt_large.pth''' a = blip_decoder(pretrained=snake_case_, image_size=3_8_4, vit='''base''' ) a = pt_model.eval() a = pt_model.state_dict() for key in modified_state_dict.copy(): a = modified_state_dict.pop(snake_case_ ) a = rename_key(snake_case_ ) a = value hf_model.load_state_dict(snake_case_ ) a = 3_8_4 a = load_demo_image(image_size=snake_case_, device='''cpu''' ) a = BertTokenizer.from_pretrained('''bert-base-uncased''' ) a = tokenizer(['''a picture of'''] ).input_ids a = hf_model.generate(snake_case_, snake_case_ ) assert out[0].tolist() == [3_0_5_2_2, 1_0_3_7, 3_8_6_1, 1_9_9_7, 1_0_3_7, 2_4_5_0, 3_5_6_4, 2_0_0_6, 1_9_9_6, 3_5_0_9, 2_0_0_7, 2_0_1_4, 3_8_9_9, 1_0_2] a = hf_model.generate(snake_case_ ) assert out[0].tolist() == [3_0_5_2_2, 1_0_3_7, 2_4_5_0, 3_5_6_4, 2_0_0_6, 1_9_9_6, 3_5_0_9, 2_0_0_7, 2_0_1_4, 3_8_9_9, 1_0_2] if pytorch_dump_folder_path is not None: hf_model.save_pretrained(snake_case_ ) # model_url = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_vqa.pth' a = ( '''https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_vqa_capfilt_large.pth''' ) a = blip_vqa(pretrained=snake_case_, image_size=snake_case_, vit='''base''' ) vqa_model.eval() a = vqa_model.state_dict() for key in modified_state_dict.copy(): a = modified_state_dict.pop(snake_case_ ) a = rename_key(snake_case_ ) a = value a = BlipForQuestionAnswering(snake_case_ ) hf_vqa_model.load_state_dict(snake_case_ ) a = ['''How many dogs are in this image?'''] a = tokenizer(snake_case_, return_tensors='''pt''' ).input_ids a = hf_vqa_model.generate(snake_case_, snake_case_ ) print(tokenizer.decode(answer[0] ) ) assert tokenizer.decode(answer[0] ) == "[UNK] 1 [SEP]" if pytorch_dump_folder_path is not None: hf_vqa_model.save_pretrained(pytorch_dump_folder_path + '''_vqa''' ) a = '''https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_retrieval_coco.pth''' a = blip_itm(pretrained=snake_case_, image_size=snake_case_, vit='''base''' ) itm_model.eval() a = itm_model.state_dict() for key in modified_state_dict.copy(): a = modified_state_dict.pop(snake_case_ ) a = rename_key(snake_case_ ) a = value a = BlipForImageTextRetrieval(snake_case_ ) a = ['''A picture of a woman with a dog sitting in a beach'''] a = tokenizer( snake_case_, return_tensors='''pt''', padding='''max_length''', truncation=snake_case_, max_length=3_5, ).input_ids hf_itm_model.load_state_dict(snake_case_ ) hf_itm_model.eval() a = hf_itm_model(snake_case_, snake_case_, use_itm_head=snake_case_ ) a = hf_itm_model(snake_case_, snake_case_, use_itm_head=snake_case_ ) assert out[0].item() == 0.2110_6874_9427_7954 assert torch.nn.functional.softmax(out_itm[0], dim=1 )[:, 1].item() == 0.4_5698_8453_8650_5127 if pytorch_dump_folder_path is not None: hf_itm_model.save_pretrained(pytorch_dump_folder_path + '''_itm''' ) if __name__ == "__main__": UpperCamelCase__ : Tuple = argparse.ArgumentParser() parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") UpperCamelCase__ : int = parser.parse_args() convert_blip_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
330
from typing import List from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase__ : Union[str, Any] = logging.get_logger(__name__) UpperCamelCase__ : List[str] = { """snap-research/efficientformer-l1-300""": ( """https://huggingface.co/snap-research/efficientformer-l1-300/resolve/main/config.json""" ), } class lowerCamelCase_ ( a_ ): SCREAMING_SNAKE_CASE_ = 'efficientformer' def __init__( self : Optional[int] ,__lowerCamelCase : List[int] = [3, 2, 6, 4] ,__lowerCamelCase : List[int] = [48, 96, 2_24, 4_48] ,__lowerCamelCase : List[bool] = [True, True, True, True] ,__lowerCamelCase : int = 4_48 ,__lowerCamelCase : int = 32 ,__lowerCamelCase : int = 4 ,__lowerCamelCase : int = 7 ,__lowerCamelCase : int = 5 ,__lowerCamelCase : int = 8 ,__lowerCamelCase : int = 4 ,__lowerCamelCase : float = 0.0 ,__lowerCamelCase : int = 16 ,__lowerCamelCase : int = 3 ,__lowerCamelCase : int = 3 ,__lowerCamelCase : int = 3 ,__lowerCamelCase : int = 2 ,__lowerCamelCase : int = 1 ,__lowerCamelCase : float = 0.0 ,__lowerCamelCase : int = 1 ,__lowerCamelCase : bool = True ,__lowerCamelCase : bool = True ,__lowerCamelCase : float = 1e-5 ,__lowerCamelCase : str = "gelu" ,__lowerCamelCase : float = 0.02 ,__lowerCamelCase : float = 1e-12 ,__lowerCamelCase : int = 2_24 ,__lowerCamelCase : float = 1e-05 ,**__lowerCamelCase : Dict ,): '''simple docstring''' super().__init__(**__lowerCamelCase ) a = hidden_act a = hidden_dropout_prob a = hidden_sizes a = num_hidden_layers a = num_attention_heads a = initializer_range a = layer_norm_eps a = patch_size a = num_channels a = depths a = mlp_expansion_ratio a = downsamples a = dim a = key_dim a = attention_ratio a = resolution a = pool_size a = downsample_patch_size a = downsample_stride a = downsample_pad a = drop_path_rate a = num_metaad_blocks a = distillation a = use_layer_scale a = layer_scale_init_value a = image_size a = batch_norm_eps
330
1
from copy import deepcopy import torch import torch.nn.functional as F from torch.optim import AdamW from torch.optim.lr_scheduler import LambdaLR from torch.utils.data import DataLoader from accelerate.accelerator import Accelerator from accelerate.state import GradientState from accelerate.test_utils import RegressionDataset, RegressionModel from accelerate.utils import DistributedType, is_torch_version, set_seed def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_, snake_case_ ) -> Union[str, Any]: """simple docstring""" for param, grad_param in zip(model_a.parameters(), model_b.parameters() ): if not param.requires_grad: continue if not did_step: # Grads should not be in sync assert ( torch.allclose(param.grad, grad_param.grad ) is False ), f"""Gradients in sync when they should not be at iteration {iteration}:\nmodel_a grad ({param.grad}) == model_b grad ({grad_param.grad})""" else: # Grads should be in sync assert ( torch.allclose(param.grad, grad_param.grad ) is True ), f"""Gradients not in sync when they should be at iteration {iteration}:\nmodel_a grad ({param.grad}) != model_b grad ({grad_param.grad})""" def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_, snake_case_, snake_case_=True ) -> str: """simple docstring""" model.train() a = model(snake_case_ ) a = F.mse_loss(snake_case_, target.to(output.device ) ) if not do_backward: loss /= accelerator.gradient_accumulation_steps loss.backward() else: accelerator.backward(snake_case_ ) def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_=False ) -> List[str]: """simple docstring""" set_seed(4_2 ) a = RegressionModel() a = deepcopy(snake_case_ ) a = RegressionDataset(length=8_0 ) a = DataLoader(snake_case_, batch_size=1_6 ) model.to(accelerator.device ) if sched: a = AdamW(params=model.parameters(), lr=1e-3 ) a = AdamW(params=ddp_model.parameters(), lr=1e-3 ) a = LambdaLR(snake_case_, lr_lambda=lambda snake_case_ : epoch**0.65 ) a = LambdaLR(snake_case_, lr_lambda=lambda snake_case_ : epoch**0.65 ) # Make a copy of `model` if sched: a , a , a , a = accelerator.prepare(snake_case_, snake_case_, snake_case_, snake_case_ ) else: a , a = accelerator.prepare(snake_case_, snake_case_ ) if sched: return (model, opt, sched, dataloader, ddp_model, ddp_opt, ddp_sched) return model, ddp_model, dataloader def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> Tuple: """simple docstring""" a , a , a = get_training_setup(snake_case_ ) # Use a single batch a , a = next(iter(snake_case_ ) ).values() for iteration in range(3 ): # Gather the distributed inputs and targs for the base model a , a = accelerator.gather((ddp_input, ddp_target) ) a , a = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" step_model(snake_case_, snake_case_, snake_case_, snake_case_ ) # Do "gradient accumulation" (noop) if iteration % 2 == 0: # Accumulate grads locally with accelerator.no_sync(snake_case_ ): step_model(snake_case_, snake_case_, snake_case_, snake_case_ ) else: # Sync grads step_model(snake_case_, snake_case_, snake_case_, snake_case_ ) # Since `no_sync` is a noop, `ddp_model` and `model` grads should always be in sync check_model_parameters(snake_case_, snake_case_, snake_case_, snake_case_ ) for param, ddp_param in zip(model.parameters(), ddp_model.parameters() ): if not param.requires_grad: continue assert torch.allclose( param.grad, ddp_param.grad ), f"""Gradients not in sync when they should be:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})""" # Shuffle ddp_input on each iteration torch.manual_seed(1_3_3_7 + iteration ) a = ddp_input[torch.randperm(len(snake_case_ ) )] def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> Tuple: """simple docstring""" a , a , a = get_training_setup(snake_case_ ) # Use a single batch a , a = next(iter(snake_case_ ) ).values() for iteration in range(3 ): # Gather the distributed inputs and targs for the base model a , a = accelerator.gather((ddp_input, ddp_target) ) a , a = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" step_model(snake_case_, snake_case_, snake_case_, snake_case_ ) # Do "gradient accumulation" (noop) if iteration % 2 == 0: # Accumulate grads locally with accelerator.no_sync(snake_case_ ): step_model(snake_case_, snake_case_, snake_case_, snake_case_ ) else: # Sync grads step_model(snake_case_, snake_case_, snake_case_, snake_case_ ) # DDP model and model should only be in sync when not (iteration % 2 == 0) for param, ddp_param in zip(model.parameters(), ddp_model.parameters() ): if not param.requires_grad: continue if iteration % 2 == 0: # Grads should not be in sync assert ( torch.allclose(param.grad, ddp_param.grad ) is False ), f"""Gradients in sync when they should not be:\nModel grad ({param.grad}) == DDP grad ({ddp_param.grad})""" else: # Grads should be in sync assert ( torch.allclose(param.grad, ddp_param.grad ) is True ), f"""Gradients not in sync when they should be:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})""" # Shuffle ddp_input on each iteration torch.manual_seed(1_3_3_7 + iteration ) a = ddp_input[torch.randperm(len(snake_case_ ) )] def SCREAMING_SNAKE_CASE__ ( snake_case_=False, snake_case_=False ) -> Tuple: """simple docstring""" a = Accelerator( split_batches=snake_case_, dispatch_batches=snake_case_, gradient_accumulation_steps=2 ) # Test that context manager behaves properly a , a , a = get_training_setup(snake_case_ ) for iteration, batch in enumerate(snake_case_ ): a , a = batch.values() # Gather the distributed inputs and targs for the base model a , a = accelerator.gather((ddp_input, ddp_target) ) a , a = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" step_model(snake_case_, snake_case_, snake_case_, snake_case_, snake_case_ ) # Do "gradient accumulation" (noop) with accelerator.accumulate(snake_case_ ): step_model(snake_case_, snake_case_, snake_case_, snake_case_ ) # DDP model and model should only be in sync when not (iteration % 2 == 0) for param, ddp_param in zip(model.parameters(), ddp_model.parameters() ): if not param.requires_grad: continue if ((iteration + 1) % 2 == 0) or (iteration == len(snake_case_ ) - 1): # Grads should be in sync assert ( torch.allclose(param.grad, ddp_param.grad ) is True ), f"""Gradients not in sync when they should be at iteration {iteration}:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})""" else: # Grads should not be in sync assert ( torch.allclose(param.grad, ddp_param.grad ) is False ), f"""Gradients in sync when they should not be at iteration {iteration}:\nModel grad ({param.grad}) == DDP grad ({ddp_param.grad})""" # Shuffle ddp_input on each iteration torch.manual_seed(1_3_3_7 + iteration ) a = ddp_input[torch.randperm(len(snake_case_ ) )] GradientState._reset_state() def SCREAMING_SNAKE_CASE__ ( snake_case_=False, snake_case_=False ) -> Optional[int]: """simple docstring""" a = Accelerator( split_batches=snake_case_, dispatch_batches=snake_case_, gradient_accumulation_steps=2 ) # Test that context manager behaves properly a , a , a , a , a , a , a = get_training_setup(snake_case_, snake_case_ ) for iteration, batch in enumerate(snake_case_ ): a , a = batch.values() # Gather the distributed inputs and targs for the base model a , a = accelerator.gather((ddp_input, ddp_target) ) a , a = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" model.train() ddp_model.train() step_model(snake_case_, snake_case_, snake_case_, snake_case_, snake_case_ ) opt.step() if ((iteration + 1) % 2 == 0) or ((iteration + 1) == len(snake_case_ )): if split_batches: sched.step() else: for _ in range(accelerator.num_processes ): sched.step() opt.zero_grad() # Perform gradient accumulation under wrapper with accelerator.accumulate(snake_case_ ): step_model(snake_case_, snake_case_, snake_case_, snake_case_ ) ddp_opt.step() ddp_sched.step() ddp_opt.zero_grad() # Learning rates should be the same assert ( opt.param_groups[0]["lr"] == ddp_opt.param_groups[0]["lr"] ), f"""Learning rates found in each optimizer did not align\nopt: {opt.param_groups[0]["lr"]}\nDDP opt: {ddp_opt.param_groups[0]["lr"]}\n""" a = (((iteration + 1) % 2) == 0) or ((iteration + 1) == len(snake_case_ )) if accelerator.num_processes > 1: check_model_parameters(snake_case_, snake_case_, snake_case_, snake_case_ ) # Shuffle ddp_input on each iteration torch.manual_seed(1_3_3_7 + iteration ) GradientState._reset_state() def SCREAMING_SNAKE_CASE__ ( ) -> Any: """simple docstring""" a = Accelerator() a = RegressionDataset(length=8_0 ) a = DataLoader(snake_case_, batch_size=1_6 ) a = RegressionDataset(length=9_6 ) a = DataLoader(snake_case_, batch_size=1_6 ) a , a = accelerator.prepare(snake_case_, snake_case_ ) assert accelerator.gradient_state.active_dataloader is None for iteration, _ in enumerate(snake_case_ ): assert id(accelerator.gradient_state.active_dataloader ) == id(snake_case_ ) if iteration < len(snake_case_ ) - 1: assert not accelerator.gradient_state.end_of_dataloader if iteration == 1: for batch_num, _ in enumerate(snake_case_ ): assert id(accelerator.gradient_state.active_dataloader ) == id(snake_case_ ) if batch_num < len(snake_case_ ) - 1: assert not accelerator.gradient_state.end_of_dataloader else: assert accelerator.gradient_state.end_of_dataloader else: assert accelerator.gradient_state.end_of_dataloader assert accelerator.gradient_state.active_dataloader is None def SCREAMING_SNAKE_CASE__ ( ) -> Tuple: """simple docstring""" a = Accelerator() a = accelerator.state if state.local_process_index == 0: print('''**Test `accumulate` gradient accumulation with dataloader break**''' ) test_dataloader_break() if state.distributed_type == DistributedType.NO: if state.local_process_index == 0: print('''**Test NOOP `no_sync` context manager**''' ) test_noop_sync(snake_case_ ) if state.distributed_type in (DistributedType.MULTI_GPU, DistributedType.MULTI_CPU): if state.local_process_index == 0: print('''**Test Distributed `no_sync` context manager**''' ) test_distributed_sync(snake_case_ ) if state.distributed_type == DistributedType.MULTI_GPU: for split_batch in [True, False]: for dispatch_batches in [True, False]: if state.local_process_index == 0: print( '''**Test `accumulate` gradient accumulation, ''', f"""`split_batches={split_batch}` and `dispatch_batches={dispatch_batches}`**""", ) test_gradient_accumulation(snake_case_, snake_case_ ) # Currently will break on torch 2.0 +, need to investigate why if is_torch_version('''<''', '''2.0''' ) or state.distributed_type == DistributedType.NO: if state.local_process_index == 0: print( '''**Test `accumulate` gradient accumulation with optimizer and scheduler, ''', '''`split_batches=False`, `dispatch_batches=False`**''', ) test_gradient_accumulation_with_opt_and_scheduler() if state.distributed_type == DistributedType.MULTI_GPU: for split_batch in [True, False]: for dispatch_batches in [True, False]: if not split_batch and not dispatch_batches: continue if state.local_process_index == 0: print( '''**Test `accumulate` gradient accumulation with optimizer and scheduler, ''', f"""`split_batches={split_batch}` and `dispatch_batches={dispatch_batches}`**""", ) test_gradient_accumulation_with_opt_and_scheduler(snake_case_, snake_case_ ) def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> Tuple: """simple docstring""" main() if __name__ == "__main__": main()
330
import argparse from typing import Dict import tensorflow as tf import torch from tqdm import tqdm from transformers import BigBirdPegasusConfig, BigBirdPegasusForConditionalGeneration UpperCamelCase__ : Any = [ # tf -> hf ("""/""", """."""), ("""layer_""", """layers."""), ("""kernel""", """weight"""), ("""beta""", """bias"""), ("""gamma""", """weight"""), ("""pegasus""", """model"""), ] UpperCamelCase__ : Optional[Any] = [ (""".output.dense""", """.fc2"""), ("""intermediate.LayerNorm""", """final_layer_norm"""), ("""intermediate.dense""", """fc1"""), ] UpperCamelCase__ : Optional[Any] = ( INIT_COMMON + [ ("""attention.self.LayerNorm""", """self_attn_layer_norm"""), ("""attention.output.dense""", """self_attn.out_proj"""), ("""attention.self""", """self_attn"""), ("""attention.encdec.LayerNorm""", """encoder_attn_layer_norm"""), ("""attention.encdec_output.dense""", """encoder_attn.out_proj"""), ("""attention.encdec""", """encoder_attn"""), ("""key""", """k_proj"""), ("""value""", """v_proj"""), ("""query""", """q_proj"""), ("""decoder.LayerNorm""", """decoder.layernorm_embedding"""), ] + END_COMMON ) UpperCamelCase__ : List[str] = ( INIT_COMMON + [ ("""embeddings.word_embeddings""", """shared.weight"""), ("""embeddings.position_embeddings""", """embed_positions.weight"""), ("""attention.self.LayerNorm""", """self_attn_layer_norm"""), ("""attention.output.dense""", """self_attn.output"""), ("""attention.self""", """self_attn.self"""), ("""encoder.LayerNorm""", """encoder.layernorm_embedding"""), ] + END_COMMON ) UpperCamelCase__ : Optional[int] = [ """encdec/key/bias""", """encdec/query/bias""", """encdec/value/bias""", """self/key/bias""", """self/query/bias""", """self/value/bias""", """encdec_output/dense/bias""", """attention/output/dense/bias""", ] def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> List[Any]: """simple docstring""" for tf_name, hf_name in patterns: a = k.replace(snake_case_, snake_case_ ) return k def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> BigBirdPegasusForConditionalGeneration: """simple docstring""" a = BigBirdPegasusConfig(**snake_case_ ) a = BigBirdPegasusForConditionalGeneration(snake_case_ ) a = torch_model.state_dict() a = {} # separating decoder weights a = {k: tf_weights[k] for k in tf_weights if k.startswith('''pegasus/decoder''' )} a = {k: tf_weights[k] for k in tf_weights if not k.startswith('''pegasus/decoder''' )} for k, v in tqdm(decoder_weights.items(), '''tf -> hf conversion''' ): a = [k.endswith(snake_case_ ) for ending in KEYS_TO_IGNORE] if any(snake_case_ ): continue a = DECODER_PATTERNS a = rename_state_dict_key(snake_case_, snake_case_ ) if new_k not in state_dict: raise ValueError(f"""could not find new key {new_k} in state dict. (converted from {k})""" ) if any(True if i in k else False for i in ['''dense''', '''query''', '''key''', '''value'''] ): a = v.T a = torch.from_numpy(snake_case_ ) assert v.shape == state_dict[new_k].shape, f"""{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}""" for k, v in tqdm(remaining_weights.items(), '''tf -> hf conversion''' ): a = [k.endswith(snake_case_ ) for ending in KEYS_TO_IGNORE] if any(snake_case_ ): continue a = REMAINING_PATTERNS a = rename_state_dict_key(snake_case_, snake_case_ ) if new_k not in state_dict and k != "pegasus/embeddings/position_embeddings": raise ValueError(f"""could not find new key {new_k} in state dict. (converted from {k})""" ) if any(True if i in k else False for i in ['''dense''', '''query''', '''key''', '''value'''] ): a = v.T a = torch.from_numpy(snake_case_ ) if k != "pegasus/embeddings/position_embeddings": assert v.shape == state_dict[new_k].shape, f"""{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}""" a = mapping['''model.embed_positions.weight'''] a = mapping.pop('''model.embed_positions.weight''' ) a , a = torch_model.load_state_dict(snake_case_, strict=snake_case_ ) a = [ k for k in missing if k not in [ '''final_logits_bias''', '''model.encoder.embed_tokens.weight''', '''model.decoder.embed_tokens.weight''', '''lm_head.weight''', ] ] assert unexpected_missing == [], f"""no matches found for the following torch keys {unexpected_missing}""" assert extra == [], f"""no matches found for the following tf keys {extra}""" return torch_model def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> Dict: """simple docstring""" a = tf.train.list_variables(snake_case_ ) a = {} a = ['''global_step'''] for name, shape in tqdm(snake_case_, desc='''converting tf checkpoint to dict''' ): a = any(pat in name for pat in ignore_name ) if skip_key: continue a = tf.train.load_variable(snake_case_, snake_case_ ) a = array return tf_weights def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_ ) -> int: """simple docstring""" a = get_tf_weights_as_numpy(snake_case_ ) a = convert_bigbird_pegasus(snake_case_, snake_case_ ) torch_model.save_pretrained(snake_case_ ) if __name__ == "__main__": UpperCamelCase__ : str = argparse.ArgumentParser() parser.add_argument("""--tf_ckpt_path""", type=str, help="""passed to tf.train.list_variables""") parser.add_argument("""--save_dir""", default=None, type=str, help="""Path to the output PyTorch model.""") UpperCamelCase__ : int = parser.parse_args() UpperCamelCase__ : Tuple = {} convert_bigbird_pegasus_ckpt_to_pytorch(args.tf_ckpt_path, args.save_dir, config_update=config_update)
330
1
from scipy.stats import pearsonr, spearmanr from sklearn.metrics import fa_score, matthews_corrcoef import datasets UpperCamelCase__ : Dict = """\ @inproceedings{wang2019glue, title={{GLUE}: A Multi-Task Benchmark and Analysis Platform for Natural Language Understanding}, author={Wang, Alex and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R.}, note={In the Proceedings of ICLR.}, year={2019} } """ UpperCamelCase__ : List[Any] = """\ GLUE, the General Language Understanding Evaluation benchmark (https://gluebenchmark.com/) is a collection of resources for training, evaluating, and analyzing natural language understanding systems. """ UpperCamelCase__ : Any = """ Compute GLUE evaluation metric associated to each GLUE dataset. Args: predictions: list of predictions to score. Each translation should be tokenized into a list of tokens. references: list of lists of references for each translation. Each reference should be tokenized into a list of tokens. Returns: depending on the GLUE subset, one or several of: \"accuracy\": Accuracy \"f1\": F1 score \"pearson\": Pearson Correlation \"spearmanr\": Spearman Correlation \"matthews_correlation\": Matthew Correlation Examples: >>> glue_metric = datasets.load_metric('glue', 'sst2') # 'sst2' or any of [\"mnli\", \"mnli_mismatched\", \"mnli_matched\", \"qnli\", \"rte\", \"wnli\", \"hans\"] >>> references = [0, 1] >>> predictions = [0, 1] >>> results = glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'accuracy': 1.0} >>> glue_metric = datasets.load_metric('glue', 'mrpc') # 'mrpc' or 'qqp' >>> references = [0, 1] >>> predictions = [0, 1] >>> results = glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'accuracy': 1.0, 'f1': 1.0} >>> glue_metric = datasets.load_metric('glue', 'stsb') >>> references = [0., 1., 2., 3., 4., 5.] >>> predictions = [0., 1., 2., 3., 4., 5.] >>> results = glue_metric.compute(predictions=predictions, references=references) >>> print({\"pearson\": round(results[\"pearson\"], 2), \"spearmanr\": round(results[\"spearmanr\"], 2)}) {'pearson': 1.0, 'spearmanr': 1.0} >>> glue_metric = datasets.load_metric('glue', 'cola') >>> references = [0, 1] >>> predictions = [0, 1] >>> results = glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'matthews_correlation': 1.0} """ def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> str: """simple docstring""" return float((preds == labels).mean() ) def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> Dict: """simple docstring""" a = simple_accuracy(snake_case_, snake_case_ ) a = float(fa_score(y_true=snake_case_, y_pred=snake_case_ ) ) return { "accuracy": acc, "f1": fa, } def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> int: """simple docstring""" a = float(pearsonr(snake_case_, snake_case_ )[0] ) a = float(spearmanr(snake_case_, snake_case_ )[0] ) return { "pearson": pearson_corr, "spearmanr": spearman_corr, } @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCamelCase_ ( datasets.Metric ): def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ): '''simple docstring''' if self.config_name not in [ "sst2", "mnli", "mnli_mismatched", "mnli_matched", "cola", "stsb", "mrpc", "qqp", "qnli", "rte", "wnli", "hans", ]: raise KeyError( '''You should supply a configuration name selected in ''' '''["sst2", "mnli", "mnli_mismatched", "mnli_matched", ''' '''"cola", "stsb", "mrpc", "qqp", "qnli", "rte", "wnli", "hans"]''' ) return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { '''predictions''': datasets.Value('''int64''' if self.config_name != '''stsb''' else '''float32''' ), '''references''': datasets.Value('''int64''' if self.config_name != '''stsb''' else '''float32''' ), } ) ,codebase_urls=[] ,reference_urls=[] ,format='''numpy''' ,) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ,__lowerCamelCase : Dict ,__lowerCamelCase : int ): '''simple docstring''' if self.config_name == "cola": return {"matthews_correlation": matthews_corrcoef(__lowerCamelCase ,__lowerCamelCase )} elif self.config_name == "stsb": return pearson_and_spearman(__lowerCamelCase ,__lowerCamelCase ) elif self.config_name in ["mrpc", "qqp"]: return acc_and_fa(__lowerCamelCase ,__lowerCamelCase ) elif self.config_name in ["sst2", "mnli", "mnli_mismatched", "mnli_matched", "qnli", "rte", "wnli", "hans"]: return {"accuracy": simple_accuracy(__lowerCamelCase ,__lowerCamelCase )} else: raise KeyError( '''You should supply a configuration name selected in ''' '''["sst2", "mnli", "mnli_mismatched", "mnli_matched", ''' '''"cola", "stsb", "mrpc", "qqp", "qnli", "rte", "wnli", "hans"]''' )
330
import re def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> str: """simple docstring""" if len(re.findall('''[ATCG]''', snake_case_ ) ) != len(snake_case_ ): raise ValueError('''Invalid Strand''' ) return dna.translate(dna.maketrans('''ATCG''', '''TAGC''' ) ) if __name__ == "__main__": import doctest doctest.testmod()
330
1
from math import factorial def SCREAMING_SNAKE_CASE__ ( snake_case_ = 2_0 ) -> int: """simple docstring""" a = 2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1, # 2, 3,... a = n // 2 return int(factorial(snake_case_ ) / (factorial(snake_case_ ) * factorial(n - k )) ) if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution(20)) else: try: UpperCamelCase__ : List[str] = int(sys.argv[1]) print(solution(n)) except ValueError: print("""Invalid entry - please enter a number.""")
330
from __future__ import annotations from collections.abc import Sequence from typing import Literal def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> str | Literal[False]: """simple docstring""" a = list(snake_case_ ) a = list(snake_case_ ) a = 0 for i in range(len(snake_case_ ) ): if lista[i] != lista[i]: count += 1 a = '''_''' if count > 1: return False else: return "".join(snake_case_ ) def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> list[str]: """simple docstring""" a = [] while True: a = ['''$'''] * len(snake_case_ ) a = [] for i in range(len(snake_case_ ) ): for j in range(i + 1, len(snake_case_ ) ): a = compare_string(binary[i], binary[j] ) if k is False: a = '''*''' a = '''*''' temp.append('''X''' ) for i in range(len(snake_case_ ) ): if checka[i] == "$": pi.append(binary[i] ) if len(snake_case_ ) == 0: return pi a = list(set(snake_case_ ) ) def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> list[str]: """simple docstring""" a = [] for minterm in minterms: a = '''''' for _ in range(snake_case_ ): a = str(minterm % 2 ) + string minterm //= 2 temp.append(snake_case_ ) return temp def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_ ) -> bool: """simple docstring""" a = list(snake_case_ ) a = list(snake_case_ ) a = 0 for i in range(len(snake_case_ ) ): if lista[i] != lista[i]: count_n += 1 return count_n == count def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> list[str]: """simple docstring""" a = [] a = [0] * len(snake_case_ ) for i in range(len(chart[0] ) ): a = 0 a = -1 for j in range(len(snake_case_ ) ): if chart[j][i] == 1: count += 1 a = j if count == 1: a = 1 for i in range(len(snake_case_ ) ): if select[i] == 1: for j in range(len(chart[0] ) ): if chart[i][j] == 1: for k in range(len(snake_case_ ) ): a = 0 temp.append(prime_implicants[i] ) while True: a = 0 a = -1 a = 0 for i in range(len(snake_case_ ) ): a = chart[i].count(1 ) if count_n > max_n: a = count_n a = i if max_n == 0: return temp temp.append(prime_implicants[rem] ) for i in range(len(chart[0] ) ): if chart[rem][i] == 1: for j in range(len(snake_case_ ) ): a = 0 def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> list[list[int]]: """simple docstring""" a = [[0 for x in range(len(snake_case_ ) )] for x in range(len(snake_case_ ) )] for i in range(len(snake_case_ ) ): a = prime_implicants[i].count('''_''' ) for j in range(len(snake_case_ ) ): if is_for_table(prime_implicants[i], binary[j], snake_case_ ): a = 1 return chart def SCREAMING_SNAKE_CASE__ ( ) -> None: """simple docstring""" a = int(input('''Enter the no. of variables\n''' ) ) a = [ float(snake_case_ ) for x in input( '''Enter the decimal representation of Minterms \'Spaces Separated\'\n''' ).split() ] a = decimal_to_binary(snake_case_, snake_case_ ) a = check(snake_case_ ) print('''Prime Implicants are:''' ) print(snake_case_ ) a = prime_implicant_chart(snake_case_, snake_case_ ) a = selection(snake_case_, snake_case_ ) print('''Essential Prime Implicants are:''' ) print(snake_case_ ) if __name__ == "__main__": import doctest doctest.testmod() main()
330
1
from __future__ import annotations from math import pow, sqrt def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_ ) -> dict[str, float]: """simple docstring""" if (resistance, reactance, impedance).count(0 ) != 1: raise ValueError('''One and only one argument must be 0''' ) if resistance == 0: return {"resistance": sqrt(pow(snake_case_, 2 ) - pow(snake_case_, 2 ) )} elif reactance == 0: return {"reactance": sqrt(pow(snake_case_, 2 ) - pow(snake_case_, 2 ) )} elif impedance == 0: return {"impedance": sqrt(pow(snake_case_, 2 ) + pow(snake_case_, 2 ) )} else: raise ValueError('''Exactly one argument must be 0''' ) if __name__ == "__main__": import doctest doctest.testmod()
330
from typing import List, Union import numpy as np from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_DEPTH_ESTIMATION_MAPPING UpperCamelCase__ : List[str] = logging.get_logger(__name__) @add_end_docstrings(a_ ) class lowerCamelCase_ ( a_ ): def __init__( self : int ,*__lowerCamelCase : str ,**__lowerCamelCase : Optional[Any] ): '''simple docstring''' super().__init__(*__lowerCamelCase ,**__lowerCamelCase ) requires_backends(self ,'''vision''' ) self.check_model_type(__lowerCamelCase ) def __call__( self : int ,__lowerCamelCase : Union[str, List[str], "Image.Image", List["Image.Image"]] ,**__lowerCamelCase : str ): '''simple docstring''' return super().__call__(__lowerCamelCase ,**__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : Any ,**__lowerCamelCase : Dict ): '''simple docstring''' return {}, {}, {} def SCREAMING_SNAKE_CASE_ ( self : int ,__lowerCamelCase : Union[str, Any] ): '''simple docstring''' a = load_image(__lowerCamelCase ) a = image.size a = self.image_processor(images=__lowerCamelCase ,return_tensors=self.framework ) return model_inputs def SCREAMING_SNAKE_CASE_ ( self : str ,__lowerCamelCase : Union[str, Any] ): '''simple docstring''' a = self.model(**__lowerCamelCase ) return model_outputs def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ,__lowerCamelCase : Union[str, Any] ): '''simple docstring''' a = model_outputs.predicted_depth a = torch.nn.functional.interpolate( predicted_depth.unsqueeze(1 ) ,size=self.image_size[::-1] ,mode='''bicubic''' ,align_corners=__lowerCamelCase ) a = prediction.squeeze().cpu().numpy() a = (output * 2_55 / np.max(__lowerCamelCase )).astype('''uint8''' ) a = Image.fromarray(__lowerCamelCase ) a = {} a = predicted_depth a = depth return output_dict
330
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCamelCase__ : List[str] = { """configuration_blip_2""": [ """BLIP_2_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Blip2Config""", """Blip2QFormerConfig""", """Blip2VisionConfig""", ], """processing_blip_2""": ["""Blip2Processor"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ : List[Any] = [ """BLIP_2_PRETRAINED_MODEL_ARCHIVE_LIST""", """Blip2Model""", """Blip2QFormerModel""", """Blip2PreTrainedModel""", """Blip2ForConditionalGeneration""", """Blip2VisionModel""", ] if TYPE_CHECKING: from .configuration_blip_a import ( BLIP_2_PRETRAINED_CONFIG_ARCHIVE_MAP, BlipaConfig, BlipaQFormerConfig, BlipaVisionConfig, ) from .processing_blip_a import BlipaProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blip_a import ( BLIP_2_PRETRAINED_MODEL_ARCHIVE_LIST, BlipaForConditionalGeneration, BlipaModel, BlipaPreTrainedModel, BlipaQFormerModel, BlipaVisionModel, ) else: import sys UpperCamelCase__ : Optional[int] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
330
from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Features, Value from .base import TaskTemplate @dataclass(frozen=a_ ) class lowerCamelCase_ ( a_ ): SCREAMING_SNAKE_CASE_ = field(default='language-modeling' , metadata={'include_in_asdict_even_if_is_default': True} ) SCREAMING_SNAKE_CASE_ = Features({'text': Value('string' )} ) SCREAMING_SNAKE_CASE_ = Features({} ) SCREAMING_SNAKE_CASE_ = "text" @property def SCREAMING_SNAKE_CASE_ ( self : int ): '''simple docstring''' return {self.text_column: "text"}
330
1
from __future__ import annotations import bisect def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_ = 0, snake_case_ = -1 ) -> int: """simple docstring""" if hi < 0: a = len(snake_case_ ) while lo < hi: a = lo + (hi - lo) // 2 if sorted_collection[mid] < item: a = mid + 1 else: a = mid return lo def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_ = 0, snake_case_ = -1 ) -> int: """simple docstring""" if hi < 0: a = len(snake_case_ ) while lo < hi: a = lo + (hi - lo) // 2 if sorted_collection[mid] <= item: a = mid + 1 else: a = mid return lo def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_ = 0, snake_case_ = -1 ) -> None: """simple docstring""" sorted_collection.insert(bisect_left(snake_case_, snake_case_, snake_case_, snake_case_ ), snake_case_ ) def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_ = 0, snake_case_ = -1 ) -> None: """simple docstring""" sorted_collection.insert(bisect_right(snake_case_, snake_case_, snake_case_, snake_case_ ), snake_case_ ) def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> int | None: """simple docstring""" a = 0 a = len(snake_case_ ) - 1 while left <= right: a = left + (right - left) // 2 a = sorted_collection[midpoint] if current_item == item: return midpoint elif item < current_item: a = midpoint - 1 else: a = midpoint + 1 return None def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> int | None: """simple docstring""" a = bisect.bisect_left(snake_case_, snake_case_ ) if index != len(snake_case_ ) and sorted_collection[index] == item: return index return None def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_, snake_case_ ) -> int | None: """simple docstring""" if right < left: return None a = left + (right - left) // 2 if sorted_collection[midpoint] == item: return midpoint elif sorted_collection[midpoint] > item: return binary_search_by_recursion(snake_case_, snake_case_, snake_case_, midpoint - 1 ) else: return binary_search_by_recursion(snake_case_, snake_case_, midpoint + 1, snake_case_ ) if __name__ == "__main__": UpperCamelCase__ : Optional[Any] = input("""Enter numbers separated by comma:\n""").strip() UpperCamelCase__ : Any = sorted(int(item) for item in user_input.split(""",""")) UpperCamelCase__ : int = int(input("""Enter a single number to be found in the list:\n""")) UpperCamelCase__ : Optional[int] = binary_search(collection, target) if result is None: print(F"{target} was not found in {collection}.") else: print(F"{target} was found at position {result} in {collection}.")
330
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCamelCase__ : Union[str, Any] = logging.get_logger(__name__) UpperCamelCase__ : Union[str, Any] = { """hustvl/yolos-small""": """https://huggingface.co/hustvl/yolos-small/resolve/main/config.json""", # See all YOLOS models at https://huggingface.co/models?filter=yolos } class lowerCamelCase_ ( a_ ): SCREAMING_SNAKE_CASE_ = 'yolos' def __init__( self : Union[str, Any] ,__lowerCamelCase : int=7_68 ,__lowerCamelCase : Dict=12 ,__lowerCamelCase : Union[str, Any]=12 ,__lowerCamelCase : List[Any]=30_72 ,__lowerCamelCase : int="gelu" ,__lowerCamelCase : int=0.0 ,__lowerCamelCase : str=0.0 ,__lowerCamelCase : Optional[Any]=0.02 ,__lowerCamelCase : int=1e-12 ,__lowerCamelCase : Any=[5_12, 8_64] ,__lowerCamelCase : Tuple=16 ,__lowerCamelCase : int=3 ,__lowerCamelCase : Tuple=True ,__lowerCamelCase : Optional[int]=1_00 ,__lowerCamelCase : List[Any]=True ,__lowerCamelCase : List[str]=False ,__lowerCamelCase : int=1 ,__lowerCamelCase : List[Any]=5 ,__lowerCamelCase : Optional[int]=2 ,__lowerCamelCase : int=5 ,__lowerCamelCase : str=2 ,__lowerCamelCase : Tuple=0.1 ,**__lowerCamelCase : List[Any] ,): '''simple docstring''' super().__init__(**__lowerCamelCase ) 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 a = num_detection_tokens a = use_mid_position_embeddings a = auxiliary_loss # Hungarian matcher a = class_cost a = bbox_cost a = giou_cost # Loss coefficients a = bbox_loss_coefficient a = giou_loss_coefficient a = eos_coefficient class lowerCamelCase_ ( a_ ): SCREAMING_SNAKE_CASE_ = version.parse('1.11' ) @property def SCREAMING_SNAKE_CASE_ ( self : str ): '''simple docstring''' return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) @property def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ): '''simple docstring''' return 1e-4 @property def SCREAMING_SNAKE_CASE_ ( self : str ): '''simple docstring''' return 12
330
1
import argparse import re from typing import Dict import torch from datasets import Audio, Dataset, load_dataset, load_metric from transformers import AutoFeatureExtractor, pipeline def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> Optional[int]: """simple docstring""" a = args.log_outputs a = '''_'''.join(args.dataset.split('''/''' ) + [args.config, args.split] ) # load metric a = load_metric('''wer''' ) a = load_metric('''cer''' ) # compute metrics a = wer.compute(references=result['''target'''], predictions=result['''prediction'''] ) a = cer.compute(references=result['''target'''], predictions=result['''prediction'''] ) # print & log results a = f"""WER: {wer_result}\nCER: {cer_result}""" print(snake_case_ ) with open(f"""{dataset_id}_eval_results.txt""", '''w''' ) as f: f.write(snake_case_ ) # log all results in text file. Possibly interesting for analysis if log_outputs is not None: a = f"""log_{dataset_id}_predictions.txt""" a = f"""log_{dataset_id}_targets.txt""" with open(snake_case_, '''w''' ) as p, open(snake_case_, '''w''' ) as t: # mapping function to write output def write_to_file(snake_case_, snake_case_ ): p.write(f"""{i}""" + '''\n''' ) p.write(batch['''prediction'''] + '''\n''' ) t.write(f"""{i}""" + '''\n''' ) t.write(batch['''target'''] + '''\n''' ) result.map(snake_case_, with_indices=snake_case_ ) def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> str: """simple docstring""" a = '''[,?.!\-\;\:"“%‘”�—’…–]''' # noqa: W605 IMPORTANT: this should correspond to the chars that were ignored during training a = re.sub(snake_case_, '''''', text.lower() ) # In addition, we can normalize the target text, e.g. removing new lines characters etc... # note that order is important here! a = ['''\n\n''', '''\n''', ''' ''', ''' '''] for t in token_sequences_to_ignore: a = ''' '''.join(text.split(snake_case_ ) ) return text def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> Optional[Any]: """simple docstring""" a = load_dataset(args.dataset, args.config, split=args.split, use_auth_token=snake_case_ ) # for testing: only process the first two examples as a test # dataset = dataset.select(range(10)) # load processor a = AutoFeatureExtractor.from_pretrained(args.model_id ) a = feature_extractor.sampling_rate # resample audio a = dataset.cast_column('''audio''', Audio(sampling_rate=snake_case_ ) ) # load eval pipeline if args.device is None: a = 0 if torch.cuda.is_available() else -1 a = pipeline('''automatic-speech-recognition''', model=args.model_id, device=args.device ) # map function to decode audio def map_to_pred(snake_case_ ): a = asr( batch['''audio''']['''array'''], chunk_length_s=args.chunk_length_s, stride_length_s=args.stride_length_s ) a = prediction['''text'''] a = normalize_text(batch['''sentence'''] ) return batch # run inference on all examples a = dataset.map(snake_case_, remove_columns=dataset.column_names ) # compute and log_results # do not change function below log_results(snake_case_, snake_case_ ) if __name__ == "__main__": UpperCamelCase__ : Any = argparse.ArgumentParser() parser.add_argument( """--model_id""", type=str, required=True, help="""Model identifier. Should be loadable with 🤗 Transformers""" ) parser.add_argument( """--dataset""", type=str, required=True, help="""Dataset name to evaluate the `model_id`. Should be loadable with 🤗 Datasets""", ) parser.add_argument( """--config""", type=str, required=True, help="""Config of the dataset. *E.g.* `'en'` for Common Voice""" ) parser.add_argument("""--split""", type=str, required=True, help="""Split of the dataset. *E.g.* `'test'`""") parser.add_argument( """--chunk_length_s""", type=float, default=None, help="""Chunk length in seconds. Defaults to 5 seconds.""" ) parser.add_argument( """--stride_length_s""", type=float, default=None, help="""Stride of the audio chunks. Defaults to 1 second.""" ) parser.add_argument( """--log_outputs""", action="""store_true""", help="""If defined, write outputs to log file for analysis.""" ) parser.add_argument( """--device""", type=int, default=None, help="""The device to run the pipeline on. -1 for CPU (default), 0 for the first GPU and so on.""", ) UpperCamelCase__ : Dict = parser.parse_args() main(args)
330
def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> int: """simple docstring""" a = '''''' for i in table: res += inp[i - 1] return res def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> int: """simple docstring""" return data[1:] + data[0] def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> List[str]: """simple docstring""" a = '''''' for i in range(len(snake_case_ ) ): if a[i] == b[i]: res += "0" else: res += "1" return res def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> Dict: """simple docstring""" a = int('''0b''' + data[0] + data[-1], 2 ) a = int('''0b''' + data[1:3], 2 ) return bin(s[row][col] )[2:] def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_, snake_case_, snake_case_ ) -> Optional[int]: """simple docstring""" a = message[:4] a = message[4:] a = apply_table(snake_case_, snake_case_ ) a = xor(snake_case_, snake_case_ ) a = apply_sbox(snake_case_, temp[:4] ) # noqa: E741 a = apply_sbox(snake_case_, temp[4:] ) a = '''0''' * (2 - len(snake_case_ )) + l # noqa: E741 a = '''0''' * (2 - len(snake_case_ )) + r a = apply_table(l + r, snake_case_ ) a = xor(snake_case_, snake_case_ ) return temp + right if __name__ == "__main__": UpperCamelCase__ : int = input("""Enter 10 bit key: """) UpperCamelCase__ : Union[str, Any] = input("""Enter 8 bit message: """) UpperCamelCase__ : Dict = [6, 3, 7, 4, 8, 5, 10, 9] UpperCamelCase__ : Union[str, Any] = [3, 5, 2, 7, 4, 10, 1, 9, 8, 6] UpperCamelCase__ : Optional[int] = [2, 4, 3, 1] UpperCamelCase__ : List[Any] = [2, 6, 3, 1, 4, 8, 5, 7] UpperCamelCase__ : str = [4, 1, 3, 5, 7, 2, 8, 6] UpperCamelCase__ : List[Any] = [4, 1, 2, 3, 2, 3, 4, 1] UpperCamelCase__ : int = [[1, 0, 3, 2], [3, 2, 1, 0], [0, 2, 1, 3], [3, 1, 3, 2]] UpperCamelCase__ : Dict = [[0, 1, 2, 3], [2, 0, 1, 3], [3, 0, 1, 0], [2, 1, 0, 3]] # key generation UpperCamelCase__ : Optional[Any] = apply_table(key, paa_table) UpperCamelCase__ : str = temp[:5] UpperCamelCase__ : List[Any] = temp[5:] UpperCamelCase__ : Dict = left_shift(left) UpperCamelCase__ : Any = left_shift(right) UpperCamelCase__ : Optional[Any] = apply_table(left + right, pa_table) UpperCamelCase__ : List[str] = left_shift(left) UpperCamelCase__ : int = left_shift(right) UpperCamelCase__ : List[str] = left_shift(left) UpperCamelCase__ : Dict = left_shift(right) UpperCamelCase__ : List[str] = apply_table(left + right, pa_table) # encryption UpperCamelCase__ : Tuple = apply_table(message, IP) UpperCamelCase__ : Optional[Any] = function(expansion, sa, sa, keya, temp) UpperCamelCase__ : Optional[int] = temp[4:] + temp[:4] UpperCamelCase__ : Any = function(expansion, sa, sa, keya, temp) UpperCamelCase__ : Tuple = apply_table(temp, IP_inv) print("""Cipher text is:""", CT) # decryption UpperCamelCase__ : Union[str, Any] = apply_table(CT, IP) UpperCamelCase__ : List[str] = function(expansion, sa, sa, keya, temp) UpperCamelCase__ : Optional[Any] = temp[4:] + temp[:4] UpperCamelCase__ : Optional[int] = function(expansion, sa, sa, keya, temp) UpperCamelCase__ : Any = apply_table(temp, IP_inv) print("""Plain text after decypting is:""", PT)
330
1
import unittest from transformers import BarthezTokenizer, BarthezTokenizerFast, BatchEncoding from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers @require_sentencepiece @slow # see https://github.com/huggingface/transformers/issues/11457 class lowerCamelCase_ ( a_ , unittest.TestCase ): SCREAMING_SNAKE_CASE_ = BarthezTokenizer SCREAMING_SNAKE_CASE_ = BarthezTokenizerFast SCREAMING_SNAKE_CASE_ = True SCREAMING_SNAKE_CASE_ = True def SCREAMING_SNAKE_CASE_ ( self : str ): '''simple docstring''' super().setUp() a = BarthezTokenizerFast.from_pretrained('''moussaKam/mbarthez''' ) tokenizer.save_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname ,legacy_format=__lowerCamelCase ) a = tokenizer def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ): '''simple docstring''' a = '''<pad>''' a = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__lowerCamelCase ) ,__lowerCamelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__lowerCamelCase ) ,__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : str ): '''simple docstring''' a = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] ,'''<s>''' ) self.assertEqual(vocab_keys[1] ,'''<pad>''' ) self.assertEqual(vocab_keys[-1] ,'''<mask>''' ) self.assertEqual(len(__lowerCamelCase ) ,10_11_22 ) def SCREAMING_SNAKE_CASE_ ( self : int ): '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size ,10_11_22 ) @require_torch def SCREAMING_SNAKE_CASE_ ( self : str ): '''simple docstring''' a = ['''A long paragraph for summarization.''', '''Another paragraph for summarization.'''] a = [0, 57, 30_18, 7_03_07, 91, 2] a = self.tokenizer( __lowerCamelCase ,max_length=len(__lowerCamelCase ) ,padding=__lowerCamelCase ,truncation=__lowerCamelCase ,return_tensors='''pt''' ) self.assertIsInstance(__lowerCamelCase ,__lowerCamelCase ) self.assertEqual((2, 6) ,batch.input_ids.shape ) self.assertEqual((2, 6) ,batch.attention_mask.shape ) a = batch.input_ids.tolist()[0] self.assertListEqual(__lowerCamelCase ,__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : int ): '''simple docstring''' if not self.test_rust_tokenizer: return a = self.get_tokenizer() a = self.get_rust_tokenizer() a = '''I was born in 92000, and this is falsé.''' a = tokenizer.tokenize(__lowerCamelCase ) a = rust_tokenizer.tokenize(__lowerCamelCase ) self.assertListEqual(__lowerCamelCase ,__lowerCamelCase ) a = tokenizer.encode(__lowerCamelCase ,add_special_tokens=__lowerCamelCase ) a = rust_tokenizer.encode(__lowerCamelCase ,add_special_tokens=__lowerCamelCase ) self.assertListEqual(__lowerCamelCase ,__lowerCamelCase ) a = self.get_rust_tokenizer() a = tokenizer.encode(__lowerCamelCase ) a = rust_tokenizer.encode(__lowerCamelCase ) self.assertListEqual(__lowerCamelCase ,__lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self : Any ): '''simple docstring''' a = {'''input_ids''': [[0, 4_90, 1_43_28, 45_07, 3_54, 47, 4_36_69, 95, 25, 7_81_17, 2_02_15, 1_97_79, 1_90, 22, 4_00, 4, 3_53_43, 8_03_10, 6_03, 86, 2_49_37, 1_05, 3_34_38, 9_47_62, 1_96, 3_96_42, 7, 15, 1_59_33, 1_73, 2, 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, 1_05_34, 87, 25, 66, 33_58, 1_96, 5_52_89, 8, 8_29_61, 81, 22_04, 7_52_03, 7, 15, 7_63, 1_29_56, 2_16, 1_78, 1_43_28, 95_95, 13_77, 6_96_93, 7, 4_48, 7_10_21, 1_96, 1_81_06, 14_37, 1_39_74, 1_08, 90_83, 4, 4_93_15, 7, 39, 86, 13_26, 27_93, 4_63_33, 4, 4_48, 1_96, 7_45_88, 7, 4_93_15, 7, 39, 21, 8_22, 3_84_70, 74, 21, 6_67_23, 6_24_80, 8, 2_20_50, 5, 2]], '''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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on # moussaKam/mbarthez is a french model. So we also use french texts. a = [ '''Le transformeur est un modèle d\'apprentissage profond introduit en 2017, ''' '''utilisé principalement dans le domaine du traitement automatique des langues (TAL).''', '''À l\'instar des réseaux de neurones récurrents (RNN), les transformeurs sont conçus ''' '''pour gérer des données séquentielles, telles que le langage naturel, pour des tâches ''' '''telles que la traduction et la synthèse de texte.''', ] self.tokenizer_integration_test_util( expected_encoding=__lowerCamelCase ,model_name='''moussaKam/mbarthez''' ,revision='''c2e4ecbca5e3cd2c37fe1ac285ca4fbdf1366fb6''' ,sequences=__lowerCamelCase ,)
330
import unittest from transformers import AutoTokenizer, is_flax_available from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, slow if is_flax_available(): import jax.numpy as jnp from transformers import FlaxXLMRobertaModel @require_sentencepiece @require_tokenizers @require_flax class lowerCamelCase_ ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE_ ( self : Tuple ): '''simple docstring''' a = FlaxXLMRobertaModel.from_pretrained('''xlm-roberta-base''' ) a = AutoTokenizer.from_pretrained('''xlm-roberta-base''' ) a = '''The dog is cute and lives in the garden house''' a = jnp.array([tokenizer.encode(__lowerCamelCase )] ) a = (1, 12, 7_68) # batch_size, sequence_length, embedding_vector_dim a = jnp.array( [[-0.0_101, 0.1_218, -0.0_803, 0.0_801, 0.1_327, 0.0_776, -0.1_215, 0.2_383, 0.3_338, 0.3_106, 0.0_300, 0.0_252]] ) a = model(__lowerCamelCase )['''last_hidden_state'''] self.assertEqual(output.shape ,__lowerCamelCase ) # compare the actual values for a slice of last dim self.assertTrue(jnp.allclose(output[:, :, -1] ,__lowerCamelCase ,atol=1e-3 ) )
330
1
import argparse import re import numpy as np import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( SamConfig, SamImageProcessor, SamModel, SamProcessor, SamVisionConfig, ) UpperCamelCase__ : Optional[Any] = { """iou_prediction_head.layers.0""": """iou_prediction_head.proj_in""", """iou_prediction_head.layers.1""": """iou_prediction_head.layers.0""", """iou_prediction_head.layers.2""": """iou_prediction_head.proj_out""", """mask_decoder.output_upscaling.0""": """mask_decoder.upscale_conv1""", """mask_decoder.output_upscaling.1""": """mask_decoder.upscale_layer_norm""", """mask_decoder.output_upscaling.3""": """mask_decoder.upscale_conv2""", """mask_downscaling.0""": """mask_embed.conv1""", """mask_downscaling.1""": """mask_embed.layer_norm1""", """mask_downscaling.3""": """mask_embed.conv2""", """mask_downscaling.4""": """mask_embed.layer_norm2""", """mask_downscaling.6""": """mask_embed.conv3""", """point_embeddings""": """point_embed""", """pe_layer.positional_encoding_gaussian_matrix""": """shared_embedding.positional_embedding""", """image_encoder""": """vision_encoder""", """neck.0""": """neck.conv1""", """neck.1""": """neck.layer_norm1""", """neck.2""": """neck.conv2""", """neck.3""": """neck.layer_norm2""", """patch_embed.proj""": """patch_embed.projection""", """.norm""": """.layer_norm""", """blocks""": """layers""", } def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> List[str]: """simple docstring""" a = {} state_dict.pop('''pixel_mean''', snake_case_ ) state_dict.pop('''pixel_std''', snake_case_ ) a = r'''.*.output_hypernetworks_mlps.(\d+).layers.(\d+).*''' for key, value in state_dict.items(): for key_to_modify, new_key in KEYS_TO_MODIFY_MAPPING.items(): if key_to_modify in key: a = key.replace(snake_case_, snake_case_ ) if re.match(snake_case_, snake_case_ ): a = int(re.match(snake_case_, snake_case_ ).group(2 ) ) if layer_nb == 0: a = key.replace('''layers.0''', '''proj_in''' ) elif layer_nb == 1: a = key.replace('''layers.1''', '''layers.0''' ) elif layer_nb == 2: a = key.replace('''layers.2''', '''proj_out''' ) a = value a = model_state_dict[ '''prompt_encoder.shared_embedding.positional_embedding''' ] return model_state_dict def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_, snake_case_="ybelkada/segment-anything" ) -> str: """simple docstring""" a = hf_hub_download(snake_case_, f"""checkpoints/{model_name}.pth""" ) if "sam_vit_b" in model_name: a = SamConfig() elif "sam_vit_l" in model_name: a = SamVisionConfig( hidden_size=1_0_2_4, num_hidden_layers=2_4, num_attention_heads=1_6, global_attn_indexes=[5, 1_1, 1_7, 2_3], ) a = SamConfig( vision_config=snake_case_, ) elif "sam_vit_h" in model_name: a = SamVisionConfig( hidden_size=1_2_8_0, num_hidden_layers=3_2, num_attention_heads=1_6, global_attn_indexes=[7, 1_5, 2_3, 3_1], ) a = SamConfig( vision_config=snake_case_, ) a = torch.load(snake_case_, map_location='''cpu''' ) a = replace_keys(snake_case_ ) a = SamImageProcessor() a = SamProcessor(image_processor=snake_case_ ) a = SamModel(snake_case_ ) hf_model.load_state_dict(snake_case_ ) a = hf_model.to('''cuda''' ) a = '''https://huggingface.co/ybelkada/segment-anything/resolve/main/assets/car.png''' a = Image.open(requests.get(snake_case_, stream=snake_case_ ).raw ).convert('''RGB''' ) a = [[[4_0_0, 6_5_0]]] a = [[1]] a = processor(images=np.array(snake_case_ ), return_tensors='''pt''' ).to('''cuda''' ) with torch.no_grad(): a = hf_model(**snake_case_ ) a = output.iou_scores.squeeze() if model_name == "sam_vit_h_4b8939": assert scores[-1].item() == 0.579_8902_5115_9668 a = processor( images=np.array(snake_case_ ), input_points=snake_case_, input_labels=snake_case_, return_tensors='''pt''' ).to('''cuda''' ) with torch.no_grad(): a = hf_model(**snake_case_ ) a = output.iou_scores.squeeze() assert scores[-1].item() == 0.9712_6030_9219_3604 a = ((7_5, 2_7_5, 1_7_2_5, 8_5_0),) a = processor(images=np.array(snake_case_ ), input_boxes=snake_case_, return_tensors='''pt''' ).to('''cuda''' ) with torch.no_grad(): a = hf_model(**snake_case_ ) a = output.iou_scores.squeeze() assert scores[-1].item() == 0.8686_0156_0592_6514 # Test with 2 points and 1 image. a = [[[4_0_0, 6_5_0], [8_0_0, 6_5_0]]] a = [[1, 1]] a = processor( images=np.array(snake_case_ ), input_points=snake_case_, input_labels=snake_case_, return_tensors='''pt''' ).to('''cuda''' ) with torch.no_grad(): a = hf_model(**snake_case_ ) a = output.iou_scores.squeeze() assert scores[-1].item() == 0.9936_0477_9243_4692 if __name__ == "__main__": UpperCamelCase__ : Optional[int] = argparse.ArgumentParser() UpperCamelCase__ : List[Any] = ["""sam_vit_b_01ec64""", """sam_vit_h_4b8939""", """sam_vit_l_0b3195"""] parser.add_argument( """--model_name""", default="""sam_vit_h_4b8939""", choices=choices, type=str, help="""Path to hf config.json of model to convert""", ) parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument( """--push_to_hub""", action="""store_true""", help="""Whether to push the model and processor to the hub after converting""", ) parser.add_argument( """--model_hub_id""", default="""ybelkada/segment-anything""", choices=choices, type=str, help="""Path to hf config.json of model to convert""", ) UpperCamelCase__ : Any = parser.parse_args() convert_sam_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub, args.model_hub_id)
330
import argparse import os # New Code # import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils import find_executable_batch_size ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to ensure out-of-memory errors never # interrupt training, and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## UpperCamelCase__ : Union[str, Any] = 16 UpperCamelCase__ : Dict = 32 def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ = 1_6 ) -> Tuple: """simple docstring""" a = AutoTokenizer.from_pretrained('''bert-base-cased''' ) a = load_dataset('''glue''', '''mrpc''' ) def tokenize_function(snake_case_ ): # max_length=None => use the model max length (it's actually the default) a = tokenizer(examples['''sentence1'''], examples['''sentence2'''], truncation=snake_case_, max_length=snake_case_ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): a = datasets.map( snake_case_, batched=snake_case_, remove_columns=['''idx''', '''sentence1''', '''sentence2'''], ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library a = tokenized_datasets.rename_column('''label''', '''labels''' ) def collate_fn(snake_case_ ): # On TPU it's best to pad everything to the same length or training will be very slow. a = 1_2_8 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": a = 1_6 elif accelerator.mixed_precision != "no": a = 8 else: a = None return tokenizer.pad( snake_case_, padding='''longest''', max_length=snake_case_, pad_to_multiple_of=snake_case_, return_tensors='''pt''', ) # Instantiate dataloaders. a = DataLoader( tokenized_datasets['''train'''], shuffle=snake_case_, collate_fn=snake_case_, batch_size=snake_case_ ) a = DataLoader( tokenized_datasets['''validation'''], shuffle=snake_case_, collate_fn=snake_case_, batch_size=snake_case_ ) return train_dataloader, eval_dataloader # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""", None) == "1": from accelerate.test_utils.training import mocked_dataloaders UpperCamelCase__ : int = mocked_dataloaders # noqa: F811 def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> List[Any]: """simple docstring""" if os.environ.get('''TESTING_MOCKED_DATALOADERS''', snake_case_ ) == "1": a = 2 # Initialize accelerator a = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs a = config['''lr'''] a = int(config['''num_epochs'''] ) a = int(config['''seed'''] ) a = int(config['''batch_size'''] ) a = evaluate.load('''glue''', '''mrpc''' ) # New Code # # We now can define an inner training loop function. It should take a batch size as the only parameter, # and build the dataloaders in there. # It also gets our decorator @find_executable_batch_size(starting_batch_size=snake_case_ ) def inner_training_loop(snake_case_ ): # And now just move everything below under this function # We need to bring in the Accelerator object from earlier nonlocal accelerator # And reset all of its attributes that could hold onto any memory: accelerator.free_memory() # Then we can declare the model, optimizer, and everything else: set_seed(snake_case_ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) a = AutoModelForSequenceClassification.from_pretrained('''bert-base-cased''', return_dict=snake_case_ ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). a = model.to(accelerator.device ) # Instantiate optimizer a = AdamW(params=model.parameters(), lr=snake_case_ ) a , a = get_dataloaders(snake_case_, snake_case_ ) # Instantiate scheduler a = get_linear_schedule_with_warmup( optimizer=snake_case_, num_warmup_steps=1_0_0, num_training_steps=(len(snake_case_ ) * num_epochs), ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. a , a , a , a , a = accelerator.prepare( snake_case_, snake_case_, snake_case_, snake_case_, snake_case_ ) # Now we train the model for epoch in range(snake_case_ ): model.train() for step, batch in enumerate(snake_case_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) a = model(**snake_case_ ) a = outputs.loss accelerator.backward(snake_case_ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(snake_case_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): a = model(**snake_case_ ) a = outputs.logits.argmax(dim=-1 ) a , a = accelerator.gather_for_metrics((predictions, batch['''labels''']) ) metric.add_batch( predictions=snake_case_, references=snake_case_, ) a = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f"""epoch {epoch}:""", snake_case_ ) # New Code # # And call it at the end with no arguments # Note: You could also refactor this outside of your training loop function inner_training_loop() def SCREAMING_SNAKE_CASE__ ( ) -> Tuple: """simple docstring""" a = argparse.ArgumentParser(description='''Simple example of training script.''' ) parser.add_argument( '''--mixed_precision''', type=snake_case_, default=snake_case_, choices=['''no''', '''fp16''', '''bf16''', '''fp8'''], help='''Whether to use mixed precision. Choose''' '''between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.''' '''and an Nvidia Ampere GPU.''', ) parser.add_argument('''--cpu''', action='''store_true''', help='''If passed, will train on the CPU.''' ) a = parser.parse_args() a = {'''lr''': 2e-5, '''num_epochs''': 3, '''seed''': 4_2, '''batch_size''': 1_6} training_function(snake_case_, snake_case_ ) if __name__ == "__main__": main()
330
1
import argparse import fairseq import torch from transformers import UniSpeechSatConfig, UniSpeechSatForCTC, UniSpeechSatForPreTraining, logging logging.set_verbosity_info() UpperCamelCase__ : Optional[int] = logging.get_logger(__name__) UpperCamelCase__ : str = { """post_extract_proj""": """feature_projection.projection""", """encoder.pos_conv.0""": """encoder.pos_conv_embed.conv""", """self_attn.k_proj""": """encoder.layers.*.attention.k_proj""", """self_attn.v_proj""": """encoder.layers.*.attention.v_proj""", """self_attn.q_proj""": """encoder.layers.*.attention.q_proj""", """self_attn.out_proj""": """encoder.layers.*.attention.out_proj""", """self_attn_layer_norm""": """encoder.layers.*.layer_norm""", """fc1""": """encoder.layers.*.feed_forward.intermediate_dense""", """fc2""": """encoder.layers.*.feed_forward.output_dense""", """final_layer_norm""": """encoder.layers.*.final_layer_norm""", """encoder.layer_norm""": """encoder.layer_norm""", """encoder.layer_norm_for_extract""": """layer_norm_for_extract""", """w2v_model.layer_norm""": """feature_projection.layer_norm""", """quantizer.weight_proj""": """quantizer.weight_proj""", """quantizer.vars""": """quantizer.codevectors""", """project_q""": """project_q""", """final_proj""": """project_hid""", """w2v_encoder.proj""": """lm_head""", """label_embs_concat""": """label_embeddings_concat""", """mask_emb""": """masked_spec_embed""", """spk_proj""": """speaker_proj""", } UpperCamelCase__ : Optional[Any] = [ """lm_head""", """quantizer.weight_proj""", """quantizer.codevectors""", """project_q""", """project_hid""", """label_embeddings_concat""", """speaker_proj""", """layer_norm_for_extract""", ] def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_, snake_case_, snake_case_ ) -> List[Any]: """simple docstring""" for attribute in key.split('''.''' ): a = getattr(snake_case_, snake_case_ ) if weight_type is not None: a = getattr(snake_case_, snake_case_ ).shape else: a = hf_pointer.shape if hf_shape != value.shape: raise ValueError( f"""Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be""" f""" {value.shape} for {full_name}""" ) if weight_type == "weight": a = value elif weight_type == "weight_g": a = value elif weight_type == "weight_v": a = value elif weight_type == "bias": a = value else: a = value logger.info(f"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" ) def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> Union[str, Any]: """simple docstring""" a = [] a = fairseq_model.state_dict() a = hf_model.unispeech_sat.feature_extractor for name, value in fairseq_dict.items(): a = False if "conv_layers" in name: load_conv_layer( snake_case_, snake_case_, snake_case_, snake_case_, hf_model.config.feat_extract_norm == '''group''', ) a = True else: for key, mapped_key in MAPPING.items(): a = '''unispeech_sat.''' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split('''w2v_model.''' )[-1] == name.split('''.''' )[0]: if "layer_norm_for_extract" in name and (".".join(name.split('''.''' )[:-1] ) != key): # special case since naming is very similar continue a = True if "*" in mapped_key: a = name.split(snake_case_ )[0].split('''.''' )[-2] a = mapped_key.replace('''*''', snake_case_ ) if "weight_g" in name: a = '''weight_g''' elif "weight_v" in name: a = '''weight_v''' elif "bias" in name: a = '''bias''' elif "weight" in name: # TODO: don't match quantizer.weight_proj a = '''weight''' else: a = None set_recursively(snake_case_, snake_case_, snake_case_, snake_case_, snake_case_ ) continue if not is_used: unused_weights.append(snake_case_ ) logger.warning(f"""Unused weights: {unused_weights}""" ) def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_, snake_case_, snake_case_ ) -> Union[str, Any]: """simple docstring""" a = full_name.split('''conv_layers.''' )[-1] a = name.split('''.''' ) a = int(items[0] ) a = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) a = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) a = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor[layer_id].layer_norm.bias.data.shape} was found.""" ) a = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.""" ) a = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(snake_case_ ) @torch.no_grad() def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_=None, snake_case_=None, snake_case_=True ) -> Union[str, Any]: """simple docstring""" if config_path is not None: a = UniSpeechSatConfig.from_pretrained(snake_case_ ) else: a = UniSpeechSatConfig() a = '''''' if is_finetuned: a = UniSpeechSatForCTC(snake_case_ ) else: a = UniSpeechSatForPreTraining(snake_case_ ) a , a , a = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path], arg_overrides={'''data''': '''/'''.join(dict_path.split('''/''' )[:-1] )} ) a = model[0].eval() recursively_load_weights(snake_case_, snake_case_ ) hf_wavavec.save_pretrained(snake_case_ ) if __name__ == "__main__": UpperCamelCase__ : Optional[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 fairseq checkpoint""") parser.add_argument("""--dict_path""", default=None, type=str, help="""Path to dict of fine-tuned model""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") parser.add_argument( """--not_finetuned""", action="""store_true""", help="""Whether the model to convert is a fine-tuned model or not""" ) UpperCamelCase__ : int = parser.parse_args() convert_unispeech_sat_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
330
import argparse import fairseq import torch from transformers import UniSpeechSatConfig, UniSpeechSatForCTC, UniSpeechSatForPreTraining, logging logging.set_verbosity_info() UpperCamelCase__ : Optional[int] = logging.get_logger(__name__) UpperCamelCase__ : str = { """post_extract_proj""": """feature_projection.projection""", """encoder.pos_conv.0""": """encoder.pos_conv_embed.conv""", """self_attn.k_proj""": """encoder.layers.*.attention.k_proj""", """self_attn.v_proj""": """encoder.layers.*.attention.v_proj""", """self_attn.q_proj""": """encoder.layers.*.attention.q_proj""", """self_attn.out_proj""": """encoder.layers.*.attention.out_proj""", """self_attn_layer_norm""": """encoder.layers.*.layer_norm""", """fc1""": """encoder.layers.*.feed_forward.intermediate_dense""", """fc2""": """encoder.layers.*.feed_forward.output_dense""", """final_layer_norm""": """encoder.layers.*.final_layer_norm""", """encoder.layer_norm""": """encoder.layer_norm""", """encoder.layer_norm_for_extract""": """layer_norm_for_extract""", """w2v_model.layer_norm""": """feature_projection.layer_norm""", """quantizer.weight_proj""": """quantizer.weight_proj""", """quantizer.vars""": """quantizer.codevectors""", """project_q""": """project_q""", """final_proj""": """project_hid""", """w2v_encoder.proj""": """lm_head""", """label_embs_concat""": """label_embeddings_concat""", """mask_emb""": """masked_spec_embed""", """spk_proj""": """speaker_proj""", } UpperCamelCase__ : Optional[Any] = [ """lm_head""", """quantizer.weight_proj""", """quantizer.codevectors""", """project_q""", """project_hid""", """label_embeddings_concat""", """speaker_proj""", """layer_norm_for_extract""", ] def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_, snake_case_, snake_case_ ) -> List[Any]: """simple docstring""" for attribute in key.split('''.''' ): a = getattr(snake_case_, snake_case_ ) if weight_type is not None: a = getattr(snake_case_, snake_case_ ).shape else: a = hf_pointer.shape if hf_shape != value.shape: raise ValueError( f"""Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be""" f""" {value.shape} for {full_name}""" ) if weight_type == "weight": a = value elif weight_type == "weight_g": a = value elif weight_type == "weight_v": a = value elif weight_type == "bias": a = value else: a = value logger.info(f"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" ) def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> Union[str, Any]: """simple docstring""" a = [] a = fairseq_model.state_dict() a = hf_model.unispeech_sat.feature_extractor for name, value in fairseq_dict.items(): a = False if "conv_layers" in name: load_conv_layer( snake_case_, snake_case_, snake_case_, snake_case_, hf_model.config.feat_extract_norm == '''group''', ) a = True else: for key, mapped_key in MAPPING.items(): a = '''unispeech_sat.''' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split('''w2v_model.''' )[-1] == name.split('''.''' )[0]: if "layer_norm_for_extract" in name and (".".join(name.split('''.''' )[:-1] ) != key): # special case since naming is very similar continue a = True if "*" in mapped_key: a = name.split(snake_case_ )[0].split('''.''' )[-2] a = mapped_key.replace('''*''', snake_case_ ) if "weight_g" in name: a = '''weight_g''' elif "weight_v" in name: a = '''weight_v''' elif "bias" in name: a = '''bias''' elif "weight" in name: # TODO: don't match quantizer.weight_proj a = '''weight''' else: a = None set_recursively(snake_case_, snake_case_, snake_case_, snake_case_, snake_case_ ) continue if not is_used: unused_weights.append(snake_case_ ) logger.warning(f"""Unused weights: {unused_weights}""" ) def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_, snake_case_, snake_case_ ) -> Union[str, Any]: """simple docstring""" a = full_name.split('''conv_layers.''' )[-1] a = name.split('''.''' ) a = int(items[0] ) a = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) a = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) a = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor[layer_id].layer_norm.bias.data.shape} was found.""" ) a = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.""" ) a = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(snake_case_ ) @torch.no_grad() def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_=None, snake_case_=None, snake_case_=True ) -> Union[str, Any]: """simple docstring""" if config_path is not None: a = UniSpeechSatConfig.from_pretrained(snake_case_ ) else: a = UniSpeechSatConfig() a = '''''' if is_finetuned: a = UniSpeechSatForCTC(snake_case_ ) else: a = UniSpeechSatForPreTraining(snake_case_ ) a , a , a = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path], arg_overrides={'''data''': '''/'''.join(dict_path.split('''/''' )[:-1] )} ) a = model[0].eval() recursively_load_weights(snake_case_, snake_case_ ) hf_wavavec.save_pretrained(snake_case_ ) if __name__ == "__main__": UpperCamelCase__ : Optional[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 fairseq checkpoint""") parser.add_argument("""--dict_path""", default=None, type=str, help="""Path to dict of fine-tuned model""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") parser.add_argument( """--not_finetuned""", action="""store_true""", help="""Whether the model to convert is a fine-tuned model or not""" ) UpperCamelCase__ : int = parser.parse_args() convert_unispeech_sat_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
330
1
UpperCamelCase__ : Tuple = { """Pillow""": """Pillow<10.0.0""", """accelerate""": """accelerate>=0.20.3""", """av""": """av==9.2.0""", """beautifulsoup4""": """beautifulsoup4""", """black""": """black~=23.1""", """codecarbon""": """codecarbon==1.2.0""", """cookiecutter""": """cookiecutter==1.7.3""", """dataclasses""": """dataclasses""", """datasets""": """datasets!=2.5.0""", """decord""": """decord==0.6.0""", """deepspeed""": """deepspeed>=0.9.3""", """diffusers""": """diffusers""", """dill""": """dill<0.3.5""", """evaluate""": """evaluate>=0.2.0""", """fairscale""": """fairscale>0.3""", """faiss-cpu""": """faiss-cpu""", """fastapi""": """fastapi""", """filelock""": """filelock""", """flax""": """flax>=0.4.1,<=0.7.0""", """ftfy""": """ftfy""", """fugashi""": """fugashi>=1.0""", """GitPython""": """GitPython<3.1.19""", """hf-doc-builder""": """hf-doc-builder>=0.3.0""", """huggingface-hub""": """huggingface-hub>=0.14.1,<1.0""", """importlib_metadata""": """importlib_metadata""", """ipadic""": """ipadic>=1.0.0,<2.0""", """isort""": """isort>=5.5.4""", """jax""": """jax>=0.2.8,!=0.3.2,<=0.4.13""", """jaxlib""": """jaxlib>=0.1.65,<=0.4.13""", """jieba""": """jieba""", """kenlm""": """kenlm""", """keras-nlp""": """keras-nlp>=0.3.1""", """librosa""": """librosa""", """nltk""": """nltk""", """natten""": """natten>=0.14.6""", """numpy""": """numpy>=1.17""", """onnxconverter-common""": """onnxconverter-common""", """onnxruntime-tools""": """onnxruntime-tools>=1.4.2""", """onnxruntime""": """onnxruntime>=1.4.0""", """opencv-python""": """opencv-python""", """optuna""": """optuna""", """optax""": """optax>=0.0.8,<=0.1.4""", """packaging""": """packaging>=20.0""", """parameterized""": """parameterized""", """phonemizer""": """phonemizer""", """protobuf""": """protobuf""", """psutil""": """psutil""", """pyyaml""": """pyyaml>=5.1""", """pydantic""": """pydantic<2""", """pytest""": """pytest>=7.2.0""", """pytest-timeout""": """pytest-timeout""", """pytest-xdist""": """pytest-xdist""", """python""": """python>=3.8.0""", """ray[tune]""": """ray[tune]""", """regex""": """regex!=2019.12.17""", """requests""": """requests""", """rhoknp""": """rhoknp>=1.1.0,<1.3.1""", """rjieba""": """rjieba""", """rouge-score""": """rouge-score!=0.0.7,!=0.0.8,!=0.1,!=0.1.1""", """ruff""": """ruff>=0.0.241,<=0.0.259""", """sacrebleu""": """sacrebleu>=1.4.12,<2.0.0""", """sacremoses""": """sacremoses""", """safetensors""": """safetensors>=0.3.1""", """sagemaker""": """sagemaker>=2.31.0""", """scikit-learn""": """scikit-learn""", """sentencepiece""": """sentencepiece>=0.1.91,!=0.1.92""", """sigopt""": """sigopt""", """starlette""": """starlette""", """sudachipy""": """sudachipy>=0.6.6""", """sudachidict_core""": """sudachidict_core>=20220729""", """tensorflow-cpu""": """tensorflow-cpu>=2.6,<2.14""", """tensorflow""": """tensorflow>=2.6,<2.14""", """tensorflow-text""": """tensorflow-text<2.14""", """tf2onnx""": """tf2onnx""", """timeout-decorator""": """timeout-decorator""", """timm""": """timm""", """tokenizers""": """tokenizers>=0.11.1,!=0.11.3,<0.14""", """torch""": """torch>=1.9,!=1.12.0""", """torchaudio""": """torchaudio""", """torchvision""": """torchvision""", """pyctcdecode""": """pyctcdecode>=0.4.0""", """tqdm""": """tqdm>=4.27""", """unidic""": """unidic>=1.0.2""", """unidic_lite""": """unidic_lite>=1.0.7""", """urllib3""": """urllib3<2.0.0""", """uvicorn""": """uvicorn""", }
330
import pytest from datasets import inspect_metric, list_metrics, load_metric @pytest.fixture def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> List[str]: """simple docstring""" monkeypatch.setattr('''datasets.utils.deprecation_utils._emitted_deprecation_warnings''', set() ) @pytest.fixture def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> Optional[int]: """simple docstring""" class lowerCamelCase_ : def __init__( self : Dict ,__lowerCamelCase : List[str] ): '''simple docstring''' a = metric_id class lowerCamelCase_ : SCREAMING_SNAKE_CASE_ = [MetricMock(a_ ) for metric_id in ['accuracy', 'mse', 'precision', 'codeparrot/apps_metric']] def SCREAMING_SNAKE_CASE_ ( self : Dict ): '''simple docstring''' return self._metrics monkeypatch.setattr('''datasets.inspect.huggingface_hub''', HfhMock() ) @pytest.mark.parametrize( '''func, args''', [(load_metric, ('''metrics/mse''',)), (list_metrics, ()), (inspect_metric, ('''metrics/mse''', '''tmp_path'''))] ) def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_, snake_case_, snake_case_ ) -> Tuple: """simple docstring""" if "tmp_path" in args: a = tuple(arg if arg != '''tmp_path''' else tmp_path for arg in args ) with pytest.warns(snake_case_, match='''https://huggingface.co/docs/evaluate''' ): func(*snake_case_ )
330
1
import json import os from functools import lru_cache from typing import List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging UpperCamelCase__ : str = logging.get_logger(__name__) UpperCamelCase__ : Optional[Any] = {"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt"""} UpperCamelCase__ : List[Any] = { """vocab_file""": { """allenai/longformer-base-4096""": """https://huggingface.co/allenai/longformer-base-4096/resolve/main/vocab.json""", """allenai/longformer-large-4096""": ( """https://huggingface.co/allenai/longformer-large-4096/resolve/main/vocab.json""" ), """allenai/longformer-large-4096-finetuned-triviaqa""": ( """https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/vocab.json""" ), """allenai/longformer-base-4096-extra.pos.embd.only""": ( """https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/vocab.json""" ), """allenai/longformer-large-4096-extra.pos.embd.only""": ( """https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/vocab.json""" ), }, """merges_file""": { """allenai/longformer-base-4096""": """https://huggingface.co/allenai/longformer-base-4096/resolve/main/merges.txt""", """allenai/longformer-large-4096""": ( """https://huggingface.co/allenai/longformer-large-4096/resolve/main/merges.txt""" ), """allenai/longformer-large-4096-finetuned-triviaqa""": ( """https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/merges.txt""" ), """allenai/longformer-base-4096-extra.pos.embd.only""": ( """https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/merges.txt""" ), """allenai/longformer-large-4096-extra.pos.embd.only""": ( """https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/merges.txt""" ), }, } UpperCamelCase__ : Optional[Any] = { """allenai/longformer-base-4096""": 4_096, """allenai/longformer-large-4096""": 4_096, """allenai/longformer-large-4096-finetuned-triviaqa""": 4_096, """allenai/longformer-base-4096-extra.pos.embd.only""": 4_096, """allenai/longformer-large-4096-extra.pos.embd.only""": 4_096, } @lru_cache() # Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode def SCREAMING_SNAKE_CASE__ ( ) -> int: """simple docstring""" a = ( list(range(ord('''!''' ), ord('''~''' ) + 1 ) ) + list(range(ord('''¡''' ), ord('''¬''' ) + 1 ) ) + list(range(ord('''®''' ), ord('''ÿ''' ) + 1 ) ) ) a = bs[:] a = 0 for b in range(2**8 ): if b not in bs: bs.append(snake_case_ ) cs.append(2**8 + n ) n += 1 a = [chr(snake_case_ ) for n in cs] return dict(zip(snake_case_, snake_case_ ) ) def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> Any: """simple docstring""" a = set() a = word[0] for char in word[1:]: pairs.add((prev_char, char) ) a = char return pairs class lowerCamelCase_ ( a_ ): SCREAMING_SNAKE_CASE_ = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE_ = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES SCREAMING_SNAKE_CASE_ = ['input_ids', 'attention_mask'] def __init__( self : Tuple ,__lowerCamelCase : int ,__lowerCamelCase : Tuple ,__lowerCamelCase : int="replace" ,__lowerCamelCase : Dict="<s>" ,__lowerCamelCase : str="</s>" ,__lowerCamelCase : Any="</s>" ,__lowerCamelCase : Dict="<s>" ,__lowerCamelCase : Tuple="<unk>" ,__lowerCamelCase : List[str]="<pad>" ,__lowerCamelCase : str="<mask>" ,__lowerCamelCase : int=False ,**__lowerCamelCase : Optional[int] ,): '''simple docstring''' a = AddedToken(__lowerCamelCase ,lstrip=__lowerCamelCase ,rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase ,__lowerCamelCase ) else bos_token a = AddedToken(__lowerCamelCase ,lstrip=__lowerCamelCase ,rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase ,__lowerCamelCase ) else eos_token a = AddedToken(__lowerCamelCase ,lstrip=__lowerCamelCase ,rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase ,__lowerCamelCase ) else sep_token a = AddedToken(__lowerCamelCase ,lstrip=__lowerCamelCase ,rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase ,__lowerCamelCase ) else cls_token a = AddedToken(__lowerCamelCase ,lstrip=__lowerCamelCase ,rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase ,__lowerCamelCase ) else unk_token a = AddedToken(__lowerCamelCase ,lstrip=__lowerCamelCase ,rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase ,__lowerCamelCase ) else pad_token # Mask token behave like a normal word, i.e. include the space before it a = AddedToken(__lowerCamelCase ,lstrip=__lowerCamelCase ,rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase ,__lowerCamelCase ) else mask_token super().__init__( errors=__lowerCamelCase ,bos_token=__lowerCamelCase ,eos_token=__lowerCamelCase ,unk_token=__lowerCamelCase ,sep_token=__lowerCamelCase ,cls_token=__lowerCamelCase ,pad_token=__lowerCamelCase ,mask_token=__lowerCamelCase ,add_prefix_space=__lowerCamelCase ,**__lowerCamelCase ,) with open(__lowerCamelCase ,encoding='''utf-8''' ) as vocab_handle: a = json.load(__lowerCamelCase ) a = {v: k for k, v in self.encoder.items()} a = errors # how to handle errors in decoding a = bytes_to_unicode() a = {v: k for k, v in self.byte_encoder.items()} with open(__lowerCamelCase ,encoding='''utf-8''' ) as merges_handle: a = merges_handle.read().split('''\n''' )[1:-1] a = [tuple(merge.split() ) for merge in bpe_merges] a = dict(zip(__lowerCamelCase ,range(len(__lowerCamelCase ) ) ) ) a = {} a = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions a = re.compile(r'''\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+''' ) @property def SCREAMING_SNAKE_CASE_ ( self : Any ): '''simple docstring''' return len(self.encoder ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ): '''simple docstring''' return dict(self.encoder ,**self.added_tokens_encoder ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ,__lowerCamelCase : List[Any] ): '''simple docstring''' if token in self.cache: return self.cache[token] a = tuple(__lowerCamelCase ) a = get_pairs(__lowerCamelCase ) if not pairs: return token while True: a = min(__lowerCamelCase ,key=lambda __lowerCamelCase : self.bpe_ranks.get(__lowerCamelCase ,float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break a , a = bigram a = [] a = 0 while i < len(__lowerCamelCase ): try: a = word.index(__lowerCamelCase ,__lowerCamelCase ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) a = j if word[i] == first and i < len(__lowerCamelCase ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 a = tuple(__lowerCamelCase ) a = new_word if len(__lowerCamelCase ) == 1: break else: a = get_pairs(__lowerCamelCase ) a = ''' '''.join(__lowerCamelCase ) a = word return word def SCREAMING_SNAKE_CASE_ ( self : Tuple ,__lowerCamelCase : Optional[Any] ): '''simple docstring''' a = [] for token in re.findall(self.pat ,__lowerCamelCase ): a = ''''''.join( self.byte_encoder[b] for b in token.encode('''utf-8''' ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(__lowerCamelCase ).split(''' ''' ) ) return bpe_tokens def SCREAMING_SNAKE_CASE_ ( self : Dict ,__lowerCamelCase : Tuple ): '''simple docstring''' return self.encoder.get(__lowerCamelCase ,self.encoder.get(self.unk_token ) ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ,__lowerCamelCase : List[str] ): '''simple docstring''' return self.decoder.get(__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : Dict ,__lowerCamelCase : int ): '''simple docstring''' a = ''''''.join(__lowerCamelCase ) a = bytearray([self.byte_decoder[c] for c in text] ).decode('''utf-8''' ,errors=self.errors ) return text def SCREAMING_SNAKE_CASE_ ( self : str ,__lowerCamelCase : str ,__lowerCamelCase : Optional[str] = None ): '''simple docstring''' 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'''] ) a = os.path.join( __lowerCamelCase ,(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] ) with open(__lowerCamelCase ,'''w''' ,encoding='''utf-8''' ) as f: f.write(json.dumps(self.encoder ,indent=2 ,sort_keys=__lowerCamelCase ,ensure_ascii=__lowerCamelCase ) + '''\n''' ) a = 0 with open(__lowerCamelCase ,'''w''' ,encoding='''utf-8''' ) as writer: writer.write('''#version: 0.2\n''' ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() ,key=lambda __lowerCamelCase : kv[1] ): if index != token_index: logger.warning( F"""Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.""" ''' Please check that the tokenizer is not corrupted!''' ) a = token_index writer.write(''' '''.join(__lowerCamelCase ) + '''\n''' ) index += 1 return vocab_file, merge_file def SCREAMING_SNAKE_CASE_ ( self : int ,__lowerCamelCase : List[int] ,__lowerCamelCase : Optional[List[int]] = None ): '''simple docstring''' if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] a = [self.cls_token_id] a = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE_ ( self : Dict ,__lowerCamelCase : List[int] ,__lowerCamelCase : Optional[List[int]] = None ,__lowerCamelCase : bool = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__lowerCamelCase ,token_ids_a=__lowerCamelCase ,already_has_special_tokens=__lowerCamelCase ) if token_ids_a is None: return [1] + ([0] * len(__lowerCamelCase )) + [1] return [1] + ([0] * len(__lowerCamelCase )) + [1, 1] + ([0] * len(__lowerCamelCase )) + [1] def SCREAMING_SNAKE_CASE_ ( self : Any ,__lowerCamelCase : List[int] ,__lowerCamelCase : Optional[List[int]] = None ): '''simple docstring''' 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 + sep + token_ids_a + sep ) * [0] def SCREAMING_SNAKE_CASE_ ( self : Tuple ,__lowerCamelCase : List[Any] ,__lowerCamelCase : List[str]=False ,**__lowerCamelCase : Optional[Any] ): '''simple docstring''' a = kwargs.pop('''add_prefix_space''' ,self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(__lowerCamelCase ) > 0 and not text[0].isspace()): a = ''' ''' + text return (text, kwargs)
330
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase__ : str = logging.get_logger(__name__) UpperCamelCase__ : Optional[int] = { """studio-ousia/luke-base""": """https://huggingface.co/studio-ousia/luke-base/resolve/main/config.json""", """studio-ousia/luke-large""": """https://huggingface.co/studio-ousia/luke-large/resolve/main/config.json""", } class lowerCamelCase_ ( a_ ): SCREAMING_SNAKE_CASE_ = 'luke' def __init__( self : Dict ,__lowerCamelCase : Optional[Any]=5_02_67 ,__lowerCamelCase : str=50_00_00 ,__lowerCamelCase : Any=7_68 ,__lowerCamelCase : int=2_56 ,__lowerCamelCase : Optional[int]=12 ,__lowerCamelCase : Tuple=12 ,__lowerCamelCase : Any=30_72 ,__lowerCamelCase : Any="gelu" ,__lowerCamelCase : Any=0.1 ,__lowerCamelCase : Tuple=0.1 ,__lowerCamelCase : Tuple=5_12 ,__lowerCamelCase : int=2 ,__lowerCamelCase : Optional[int]=0.02 ,__lowerCamelCase : List[Any]=1e-12 ,__lowerCamelCase : Dict=True ,__lowerCamelCase : Tuple=None ,__lowerCamelCase : Any=1 ,__lowerCamelCase : Dict=0 ,__lowerCamelCase : Any=2 ,**__lowerCamelCase : str ,): '''simple docstring''' super().__init__(pad_token_id=__lowerCamelCase ,bos_token_id=__lowerCamelCase ,eos_token_id=__lowerCamelCase ,**__lowerCamelCase ) a = vocab_size a = entity_vocab_size a = hidden_size a = entity_emb_size a = num_hidden_layers a = num_attention_heads a = hidden_act a = intermediate_size a = hidden_dropout_prob a = attention_probs_dropout_prob a = max_position_embeddings a = type_vocab_size a = initializer_range a = layer_norm_eps a = use_entity_aware_attention a = classifier_dropout
330
1
import argparse import json import math import os import time import traceback import zipfile from collections import Counter import requests def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_=None ) -> List[str]: """simple docstring""" a = None if token is not None: a = {'''Accept''': '''application/vnd.github+json''', '''Authorization''': f"""Bearer {token}"""} a = f"""https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100""" a = requests.get(snake_case_, headers=snake_case_ ).json() a = {} try: job_links.update({job['''name''']: job['''html_url'''] for job in result['''jobs''']} ) a = math.ceil((result['''total_count'''] - 1_0_0) / 1_0_0 ) for i in range(snake_case_ ): a = requests.get(url + f"""&page={i + 2}""", headers=snake_case_ ).json() job_links.update({job['''name''']: job['''html_url'''] for job in result['''jobs''']} ) return job_links except Exception: print(f"""Unknown error, could not fetch links:\n{traceback.format_exc()}""" ) return {} def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_=None ) -> Union[str, Any]: """simple docstring""" a = None if token is not None: a = {'''Accept''': '''application/vnd.github+json''', '''Authorization''': f"""Bearer {token}"""} a = f"""https://api.github.com/repos/huggingface/transformers/actions/runs/{worflow_run_id}/artifacts?per_page=100""" a = requests.get(snake_case_, headers=snake_case_ ).json() a = {} try: artifacts.update({artifact['''name''']: artifact['''archive_download_url'''] for artifact in result['''artifacts''']} ) a = math.ceil((result['''total_count'''] - 1_0_0) / 1_0_0 ) for i in range(snake_case_ ): a = requests.get(url + f"""&page={i + 2}""", headers=snake_case_ ).json() artifacts.update({artifact['''name''']: artifact['''archive_download_url'''] for artifact in result['''artifacts''']} ) return artifacts except Exception: print(f"""Unknown error, could not fetch links:\n{traceback.format_exc()}""" ) return {} def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_, snake_case_ ) -> List[str]: """simple docstring""" a = None if token is not None: a = {'''Accept''': '''application/vnd.github+json''', '''Authorization''': f"""Bearer {token}"""} a = requests.get(snake_case_, headers=snake_case_, allow_redirects=snake_case_ ) a = result.headers['''Location'''] a = requests.get(snake_case_, allow_redirects=snake_case_ ) a = os.path.join(snake_case_, f"""{artifact_name}.zip""" ) with open(snake_case_, '''wb''' ) as fp: fp.write(response.content ) def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_=None ) -> int: """simple docstring""" a = [] a = [] a = None with zipfile.ZipFile(snake_case_ ) as z: for filename in z.namelist(): if not os.path.isdir(snake_case_ ): # read the file if filename in ["failures_line.txt", "summary_short.txt", "job_name.txt"]: with z.open(snake_case_ ) as f: for line in f: a = line.decode('''UTF-8''' ).strip() if filename == "failures_line.txt": try: # `error_line` is the place where `error` occurs a = line[: line.index(''': ''' )] a = line[line.index(''': ''' ) + len(''': ''' ) :] errors.append([error_line, error] ) except Exception: # skip un-related lines pass elif filename == "summary_short.txt" and line.startswith('''FAILED ''' ): # `test` is the test method that failed a = line[len('''FAILED ''' ) :] failed_tests.append(snake_case_ ) elif filename == "job_name.txt": a = line if len(snake_case_ ) != len(snake_case_ ): raise ValueError( f"""`errors` and `failed_tests` should have the same number of elements. Got {len(snake_case_ )} for `errors` """ f"""and {len(snake_case_ )} for `failed_tests` instead. The test reports in {artifact_zip_path} have some""" ''' problem.''' ) a = None if job_name and job_links: a = job_links.get(snake_case_, snake_case_ ) # A list with elements of the form (line of error, error, failed test) a = [x + [y] + [job_link] for x, y in zip(snake_case_, snake_case_ )] return result def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_=None ) -> Optional[int]: """simple docstring""" a = [] a = [os.path.join(snake_case_, snake_case_ ) for p in os.listdir(snake_case_ ) if p.endswith('''.zip''' )] for p in paths: errors.extend(get_errors_from_single_artifact(snake_case_, job_links=snake_case_ ) ) return errors def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_=None ) -> str: """simple docstring""" a = Counter() counter.update([x[1] for x in logs] ) a = counter.most_common() a = {} for error, count in counts: if error_filter is None or error not in error_filter: a = {'''count''': count, '''failed_tests''': [(x[2], x[0]) for x in logs if x[1] == error]} a = dict(sorted(r.items(), key=lambda snake_case_ : item[1]["count"], reverse=snake_case_ ) ) return r def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> Optional[int]: """simple docstring""" a = test.split('''::''' )[0] if test.startswith('''tests/models/''' ): a = test.split('''/''' )[2] else: a = None return test def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_=None ) -> Any: """simple docstring""" a = [(x[0], x[1], get_model(x[2] )) for x in logs] a = [x for x in logs if x[2] is not None] a = {x[2] for x in logs} a = {} for test in tests: a = Counter() # count by errors in `test` counter.update([x[1] for x in logs if x[2] == test] ) a = counter.most_common() a = {error: count for error, count in counts if (error_filter is None or error not in error_filter)} a = sum(error_counts.values() ) if n_errors > 0: a = {'''count''': n_errors, '''errors''': error_counts} a = dict(sorted(r.items(), key=lambda snake_case_ : item[1]["count"], reverse=snake_case_ ) ) return r def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> int: """simple docstring""" a = '''| no. | error | status |''' a = '''|-:|:-|:-|''' a = [header, sep] for error in reduced_by_error: a = reduced_by_error[error]['''count'''] a = f"""| {count} | {error[:1_0_0]} | |""" lines.append(snake_case_ ) return "\n".join(snake_case_ ) def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> Dict: """simple docstring""" a = '''| model | no. of errors | major error | count |''' a = '''|-:|-:|-:|-:|''' a = [header, sep] for model in reduced_by_model: a = reduced_by_model[model]['''count'''] a , a = list(reduced_by_model[model]['''errors'''].items() )[0] a = f"""| {model} | {count} | {error[:6_0]} | {_count} |""" lines.append(snake_case_ ) return "\n".join(snake_case_ ) if __name__ == "__main__": UpperCamelCase__ : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument("""--workflow_run_id""", type=str, required=True, help="""A GitHub Actions workflow run id.""") parser.add_argument( """--output_dir""", type=str, required=True, help="""Where to store the downloaded artifacts and other result files.""", ) parser.add_argument("""--token""", default=None, type=str, help="""A token that has actions:read permission.""") UpperCamelCase__ : int = parser.parse_args() os.makedirs(args.output_dir, exist_ok=True) UpperCamelCase__ : Union[str, Any] = get_job_links(args.workflow_run_id, token=args.token) UpperCamelCase__ : str = {} # To deal with `workflow_call` event, where a job name is the combination of the job names in the caller and callee. # For example, `PyTorch 1.11 / Model tests (models/albert, single-gpu)`. if _job_links: for k, v in _job_links.items(): # This is how GitHub actions combine job names. if " / " in k: UpperCamelCase__ : Tuple = k.find(""" / """) UpperCamelCase__ : Tuple = k[index + len(""" / """) :] UpperCamelCase__ : Dict = v with open(os.path.join(args.output_dir, """job_links.json"""), """w""", encoding="""UTF-8""") as fp: json.dump(job_links, fp, ensure_ascii=False, indent=4) UpperCamelCase__ : str = get_artifacts_links(args.workflow_run_id, token=args.token) with open(os.path.join(args.output_dir, """artifacts.json"""), """w""", encoding="""UTF-8""") as fp: json.dump(artifacts, fp, ensure_ascii=False, indent=4) for idx, (name, url) in enumerate(artifacts.items()): download_artifact(name, url, args.output_dir, args.token) # Be gentle to GitHub time.sleep(1) UpperCamelCase__ : List[str] = get_all_errors(args.output_dir, job_links=job_links) # `e[1]` is the error UpperCamelCase__ : List[Any] = Counter() counter.update([e[1] for e in errors]) # print the top 30 most common test errors UpperCamelCase__ : Tuple = counter.most_common(30) for item in most_common: print(item) with open(os.path.join(args.output_dir, """errors.json"""), """w""", encoding="""UTF-8""") as fp: json.dump(errors, fp, ensure_ascii=False, indent=4) UpperCamelCase__ : Union[str, Any] = reduce_by_error(errors) UpperCamelCase__ : Any = reduce_by_model(errors) UpperCamelCase__ : Dict = make_github_table(reduced_by_error) UpperCamelCase__ : Any = make_github_table_per_model(reduced_by_model) with open(os.path.join(args.output_dir, """reduced_by_error.txt"""), """w""", encoding="""UTF-8""") as fp: fp.write(sa) with open(os.path.join(args.output_dir, """reduced_by_model.txt"""), """w""", encoding="""UTF-8""") as fp: fp.write(sa)
330
import numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler from tensorflow.keras.layers import LSTM, Dense from tensorflow.keras.models import Sequential if __name__ == "__main__": UpperCamelCase__ : Optional[int] = pd.read_csv("""sample_data.csv""", header=None) UpperCamelCase__ : Tuple = df.shape[:1][0] # If you're using some other dataset input the target column UpperCamelCase__ : List[Any] = df.iloc[:, 1:2] UpperCamelCase__ : Union[str, Any] = actual_data.values.reshape(len_data, 1) UpperCamelCase__ : List[Any] = MinMaxScaler().fit_transform(actual_data) UpperCamelCase__ : Optional[Any] = 10 UpperCamelCase__ : int = 5 UpperCamelCase__ : List[str] = 20 UpperCamelCase__ : Optional[int] = len_data - periods * look_back UpperCamelCase__ : Union[str, Any] = actual_data[:division] UpperCamelCase__ : str = actual_data[division - look_back :] UpperCamelCase__ , UpperCamelCase__ : Union[str, Any] = [], [] UpperCamelCase__ , UpperCamelCase__ : str = [], [] for i in range(0, len(train_data) - forward_days - look_back + 1): train_x.append(train_data[i : i + look_back]) train_y.append(train_data[i + look_back : i + look_back + forward_days]) for i in range(0, len(test_data) - forward_days - look_back + 1): test_x.append(test_data[i : i + look_back]) test_y.append(test_data[i + look_back : i + look_back + forward_days]) UpperCamelCase__ : List[str] = np.array(train_x) UpperCamelCase__ : Optional[Any] = np.array(test_x) UpperCamelCase__ : Tuple = np.array([list(i.ravel()) for i in train_y]) UpperCamelCase__ : Optional[Any] = np.array([list(i.ravel()) for i in test_y]) UpperCamelCase__ : Union[str, Any] = Sequential() model.add(LSTM(128, input_shape=(look_back, 1), return_sequences=True)) model.add(LSTM(64, input_shape=(128, 1))) model.add(Dense(forward_days)) model.compile(loss="""mean_squared_error""", optimizer="""adam""") UpperCamelCase__ : Tuple = model.fit( x_train, y_train, epochs=150, verbose=1, shuffle=True, batch_size=4 ) UpperCamelCase__ : Tuple = model.predict(x_test)
330
1
import shutil import tempfile import unittest import numpy as np import pytest from transformers.testing_utils import require_vision from transformers.utils import is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, BlipaProcessor, BlipImageProcessor, GPTaTokenizer, PreTrainedTokenizerFast @require_vision class lowerCamelCase_ ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self : Dict ): '''simple docstring''' a = tempfile.mkdtemp() a = BlipImageProcessor() a = GPTaTokenizer.from_pretrained('''hf-internal-testing/tiny-random-GPT2Model''' ) a = BlipaProcessor(__lowerCamelCase ,__lowerCamelCase ) processor.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ,**__lowerCamelCase : Optional[Any] ): '''simple docstring''' return AutoProcessor.from_pretrained(self.tmpdirname ,**__lowerCamelCase ).tokenizer def SCREAMING_SNAKE_CASE_ ( self : Dict ,**__lowerCamelCase : Tuple ): '''simple docstring''' return AutoProcessor.from_pretrained(self.tmpdirname ,**__lowerCamelCase ).image_processor def SCREAMING_SNAKE_CASE_ ( self : str ): '''simple docstring''' shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : Dict ): '''simple docstring''' a = [np.random.randint(2_55 ,size=(3, 30, 4_00) ,dtype=np.uinta )] a = [Image.fromarray(np.moveaxis(__lowerCamelCase ,0 ,-1 ) ) for x in image_inputs] return image_inputs def SCREAMING_SNAKE_CASE_ ( self : str ): '''simple docstring''' a = BlipaProcessor(tokenizer=self.get_tokenizer() ,image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) a = self.get_tokenizer(bos_token='''(BOS)''' ,eos_token='''(EOS)''' ) a = self.get_image_processor(do_normalize=__lowerCamelCase ,padding_value=1.0 ) a = BlipaProcessor.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.image_processor.to_json_string() ,image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor ,__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ): '''simple docstring''' a = self.get_image_processor() a = self.get_tokenizer() a = BlipaProcessor(tokenizer=__lowerCamelCase ,image_processor=__lowerCamelCase ) a = self.prepare_image_inputs() a = image_processor(__lowerCamelCase ,return_tensors='''np''' ) a = processor(images=__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 SCREAMING_SNAKE_CASE_ ( self : List[str] ): '''simple docstring''' a = self.get_image_processor() a = self.get_tokenizer() a = BlipaProcessor(tokenizer=__lowerCamelCase ,image_processor=__lowerCamelCase ) a = '''lower newer''' a = processor(text=__lowerCamelCase ) a = tokenizer(__lowerCamelCase ,return_token_type_ids=__lowerCamelCase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] ,encoded_processor[key] ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ): '''simple docstring''' a = self.get_image_processor() a = self.get_tokenizer() a = BlipaProcessor(tokenizer=__lowerCamelCase ,image_processor=__lowerCamelCase ) a = '''lower newer''' a = self.prepare_image_inputs() a = processor(text=__lowerCamelCase ,images=__lowerCamelCase ) self.assertListEqual(list(inputs.keys() ) ,['''pixel_values''', '''input_ids''', '''attention_mask'''] ) # test if it raises when no input is passed with pytest.raises(__lowerCamelCase ): processor() def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ): '''simple docstring''' a = self.get_image_processor() a = self.get_tokenizer() a = BlipaProcessor(tokenizer=__lowerCamelCase ,image_processor=__lowerCamelCase ) a = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] a = processor.batch_decode(__lowerCamelCase ) a = tokenizer.batch_decode(__lowerCamelCase ) self.assertListEqual(__lowerCamelCase ,__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ): '''simple docstring''' a = self.get_image_processor() a = self.get_tokenizer() a = BlipaProcessor(tokenizer=__lowerCamelCase ,image_processor=__lowerCamelCase ) a = '''lower newer''' a = self.prepare_image_inputs() a = processor(text=__lowerCamelCase ,images=__lowerCamelCase ) # For now the processor supports only ['pixel_values', 'input_ids', 'attention_mask'] self.assertListEqual(list(inputs.keys() ) ,['''pixel_values''', '''input_ids''', '''attention_mask'''] )
330
import os import time import pytest from datasets.utils.filelock import FileLock, Timeout def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> Tuple: """simple docstring""" a = FileLock(str(tmpdir / '''foo.lock''' ) ) a = FileLock(str(tmpdir / '''foo.lock''' ) ) a = 0.01 with locka.acquire(): with pytest.raises(snake_case_ ): a = time.time() locka.acquire(snake_case_ ) assert time.time() - _start > timeout def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> Optional[int]: """simple docstring""" a = '''a''' * 1_0_0_0 + '''.lock''' a = FileLock(str(tmpdir / filename ) ) assert locka._lock_file.endswith('''.lock''' ) assert not locka._lock_file.endswith(snake_case_ ) assert len(os.path.basename(locka._lock_file ) ) <= 2_5_5 a = FileLock(tmpdir / filename ) with locka.acquire(): with pytest.raises(snake_case_ ): locka.acquire(0 )
330
1
from typing import Callable, List, Optional, Tuple, Union import torch from transformers import CLIPTextModel, CLIPTokenizer from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin, TransformeraDModel, VQModel from ...schedulers import VQDiffusionScheduler from ...utils import logging from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput UpperCamelCase__ : Dict = logging.get_logger(__name__) # pylint: disable=invalid-name class lowerCamelCase_ ( a_ , a_ ): @register_to_config def __init__( self : Optional[int] ,__lowerCamelCase : bool ,__lowerCamelCase : Optional[int] = None ,__lowerCamelCase : Optional[int] = None ): '''simple docstring''' super().__init__() a = learnable if self.learnable: assert hidden_size is not None, "learnable=True requires `hidden_size` to be set" assert length is not None, "learnable=True requires `length` to be set" a = torch.zeros(__lowerCamelCase ,__lowerCamelCase ) else: a = None a = torch.nn.Parameter(__lowerCamelCase ) class lowerCamelCase_ ( a_ ): SCREAMING_SNAKE_CASE_ = 42 SCREAMING_SNAKE_CASE_ = 42 SCREAMING_SNAKE_CASE_ = 42 SCREAMING_SNAKE_CASE_ = 42 SCREAMING_SNAKE_CASE_ = 42 SCREAMING_SNAKE_CASE_ = 42 def __init__( self : Any ,__lowerCamelCase : VQModel ,__lowerCamelCase : CLIPTextModel ,__lowerCamelCase : CLIPTokenizer ,__lowerCamelCase : TransformeraDModel ,__lowerCamelCase : VQDiffusionScheduler ,__lowerCamelCase : LearnedClassifierFreeSamplingEmbeddings ,): '''simple docstring''' super().__init__() self.register_modules( vqvae=__lowerCamelCase ,transformer=__lowerCamelCase ,text_encoder=__lowerCamelCase ,tokenizer=__lowerCamelCase ,scheduler=__lowerCamelCase ,learned_classifier_free_sampling_embeddings=__lowerCamelCase ,) def SCREAMING_SNAKE_CASE_ ( self : Any ,__lowerCamelCase : Tuple ,__lowerCamelCase : Optional[int] ,__lowerCamelCase : Union[str, Any] ): '''simple docstring''' a = len(__lowerCamelCase ) if isinstance(__lowerCamelCase ,__lowerCamelCase ) else 1 # get prompt text embeddings a = self.tokenizer( __lowerCamelCase ,padding='''max_length''' ,max_length=self.tokenizer.model_max_length ,return_tensors='''pt''' ,) a = text_inputs.input_ids if text_input_ids.shape[-1] > self.tokenizer.model_max_length: a = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :] ) logger.warning( '''The following part of your input was truncated because CLIP can only handle sequences up to''' F""" {self.tokenizer.model_max_length} tokens: {removed_text}""" ) a = text_input_ids[:, : self.tokenizer.model_max_length] a = self.text_encoder(text_input_ids.to(self.device ) )[0] # NOTE: This additional step of normalizing the text embeddings is from VQ-Diffusion. # While CLIP does normalize the pooled output of the text transformer when combining # the image and text embeddings, CLIP does not directly normalize the last hidden state. # # CLIP normalizing the pooled output. # https://github.com/huggingface/transformers/blob/d92e22d1f28324f513f3080e5c47c071a3916721/src/transformers/models/clip/modeling_clip.py#L1052-L1053 a = prompt_embeds / prompt_embeds.norm(dim=-1 ,keepdim=__lowerCamelCase ) # duplicate text embeddings for each generation per prompt a = prompt_embeds.repeat_interleave(__lowerCamelCase ,dim=0 ) if do_classifier_free_guidance: if self.learned_classifier_free_sampling_embeddings.learnable: a = self.learned_classifier_free_sampling_embeddings.embeddings a = negative_prompt_embeds.unsqueeze(0 ).repeat(__lowerCamelCase ,1 ,1 ) else: a = [''''''] * batch_size a = text_input_ids.shape[-1] a = self.tokenizer( __lowerCamelCase ,padding='''max_length''' ,max_length=__lowerCamelCase ,truncation=__lowerCamelCase ,return_tensors='''pt''' ,) a = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # See comment for normalizing text embeddings a = negative_prompt_embeds / negative_prompt_embeds.norm(dim=-1 ,keepdim=__lowerCamelCase ) # duplicate unconditional embeddings for each generation per prompt, using mps friendly method a = negative_prompt_embeds.shape[1] a = negative_prompt_embeds.repeat(1 ,__lowerCamelCase ,1 ) a = negative_prompt_embeds.view(batch_size * num_images_per_prompt ,__lowerCamelCase ,-1 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes a = torch.cat([negative_prompt_embeds, prompt_embeds] ) return prompt_embeds @torch.no_grad() def __call__( self : int ,__lowerCamelCase : Union[str, List[str]] ,__lowerCamelCase : int = 1_00 ,__lowerCamelCase : float = 5.0 ,__lowerCamelCase : float = 1.0 ,__lowerCamelCase : int = 1 ,__lowerCamelCase : Optional[Union[torch.Generator, List[torch.Generator]]] = None ,__lowerCamelCase : Optional[torch.FloatTensor] = None ,__lowerCamelCase : Optional[str] = "pil" ,__lowerCamelCase : bool = True ,__lowerCamelCase : Optional[Callable[[int, int, torch.FloatTensor], None]] = None ,__lowerCamelCase : int = 1 ,): '''simple docstring''' if isinstance(__lowerCamelCase ,__lowerCamelCase ): a = 1 elif isinstance(__lowerCamelCase ,__lowerCamelCase ): a = len(__lowerCamelCase ) else: raise ValueError(F"""`prompt` has to be of type `str` or `list` but is {type(__lowerCamelCase )}""" ) a = batch_size * num_images_per_prompt a = guidance_scale > 1.0 a = self._encode_prompt(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ) if (callback_steps is None) or ( callback_steps is not None and (not isinstance(__lowerCamelCase ,__lowerCamelCase ) or callback_steps <= 0) ): raise ValueError( F"""`callback_steps` has to be a positive integer but is {callback_steps} of type""" F""" {type(__lowerCamelCase )}.""" ) # get the initial completely masked latents unless the user supplied it a = (batch_size, self.transformer.num_latent_pixels) if latents is None: a = self.transformer.num_vector_embeds - 1 a = torch.full(__lowerCamelCase ,__lowerCamelCase ).to(self.device ) else: if latents.shape != latents_shape: raise ValueError(F"""Unexpected latents shape, got {latents.shape}, expected {latents_shape}""" ) if (latents < 0).any() or (latents >= self.transformer.num_vector_embeds).any(): raise ValueError( '''Unexpected latents value(s). All latents be valid embedding indices i.e. in the range 0,''' F""" {self.transformer.num_vector_embeds - 1} (inclusive).""" ) a = latents.to(self.device ) # set timesteps self.scheduler.set_timesteps(__lowerCamelCase ,device=self.device ) a = self.scheduler.timesteps.to(self.device ) a = latents for i, t in enumerate(self.progress_bar(__lowerCamelCase ) ): # expand the sample if we are doing classifier free guidance a = torch.cat([sample] * 2 ) if do_classifier_free_guidance else sample # predict the un-noised image # model_output == `log_p_x_0` a = self.transformer(__lowerCamelCase ,encoder_hidden_states=__lowerCamelCase ,timestep=__lowerCamelCase ).sample if do_classifier_free_guidance: a , a = model_output.chunk(2 ) a = model_output_uncond + guidance_scale * (model_output_text - model_output_uncond) model_output -= torch.logsumexp(__lowerCamelCase ,dim=1 ,keepdim=__lowerCamelCase ) a = self.truncate(__lowerCamelCase ,__lowerCamelCase ) # remove `log(0)`'s (`-inf`s) a = model_output.clamp(-70 ) # compute the previous noisy sample x_t -> x_t-1 a = self.scheduler.step(__lowerCamelCase ,timestep=__lowerCamelCase ,sample=__lowerCamelCase ,generator=__lowerCamelCase ).prev_sample # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ) a = self.vqvae.config.vq_embed_dim a = (batch_size, self.transformer.height, self.transformer.width, embedding_channels) a = self.vqvae.quantize.get_codebook_entry(__lowerCamelCase ,shape=__lowerCamelCase ) a = self.vqvae.decode(__lowerCamelCase ,force_not_quantize=__lowerCamelCase ).sample a = (image / 2 + 0.5).clamp(0 ,1 ) a = image.cpu().permute(0 ,2 ,3 ,1 ).numpy() if output_type == "pil": a = self.numpy_to_pil(__lowerCamelCase ) if not return_dict: return (image,) return ImagePipelineOutput(images=__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ,__lowerCamelCase : torch.FloatTensor ,__lowerCamelCase : float ): '''simple docstring''' a , a = torch.sort(__lowerCamelCase ,1 ,descending=__lowerCamelCase ) a = torch.exp(__lowerCamelCase ) a = sorted_p_x_0.cumsum(dim=1 ) < truncation_rate # Ensure that at least the largest probability is not zeroed out a = torch.full_like(keep_mask[:, 0:1, :] ,__lowerCamelCase ) a = torch.cat((all_true, keep_mask) ,dim=1 ) a = keep_mask[:, :-1, :] a = keep_mask.gather(1 ,indices.argsort(1 ) ) a = log_p_x_0.clone() a = -torch.inf # -inf = log(0) return rv
330
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase__ : Optional[int] = logging.get_logger(__name__) UpperCamelCase__ : Dict = { """facebook/vit-mae-base""": """https://huggingface.co/facebook/vit-mae-base/resolve/main/config.json""", # See all ViT MAE models at https://huggingface.co/models?filter=vit-mae } class lowerCamelCase_ ( a_ ): SCREAMING_SNAKE_CASE_ = 'vit_mae' def __init__( self : Dict ,__lowerCamelCase : Any=7_68 ,__lowerCamelCase : Optional[Any]=12 ,__lowerCamelCase : List[str]=12 ,__lowerCamelCase : Optional[int]=30_72 ,__lowerCamelCase : int="gelu" ,__lowerCamelCase : Union[str, Any]=0.0 ,__lowerCamelCase : Optional[int]=0.0 ,__lowerCamelCase : Dict=0.02 ,__lowerCamelCase : List[Any]=1e-12 ,__lowerCamelCase : Dict=2_24 ,__lowerCamelCase : str=16 ,__lowerCamelCase : Union[str, Any]=3 ,__lowerCamelCase : Optional[Any]=True ,__lowerCamelCase : Dict=16 ,__lowerCamelCase : List[str]=5_12 ,__lowerCamelCase : int=8 ,__lowerCamelCase : int=20_48 ,__lowerCamelCase : Optional[Any]=0.75 ,__lowerCamelCase : int=False ,**__lowerCamelCase : Any ,): '''simple docstring''' super().__init__(**__lowerCamelCase ) 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 a = decoder_num_attention_heads a = decoder_hidden_size a = decoder_num_hidden_layers a = decoder_intermediate_size a = mask_ratio a = norm_pix_loss
330
1
import copy import inspect import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers import TimesformerConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, TimesformerForVideoClassification, TimesformerModel, ) from transformers.models.timesformer.modeling_timesformer import TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from transformers import VideoMAEImageProcessor class lowerCamelCase_ : def __init__( self : Optional[Any] ,__lowerCamelCase : Any ,__lowerCamelCase : Optional[int]=13 ,__lowerCamelCase : Union[str, Any]=10 ,__lowerCamelCase : List[str]=3 ,__lowerCamelCase : int=2 ,__lowerCamelCase : List[Any]=2 ,__lowerCamelCase : List[Any]=True ,__lowerCamelCase : Dict=True ,__lowerCamelCase : List[str]=32 ,__lowerCamelCase : List[str]=5 ,__lowerCamelCase : Union[str, Any]=4 ,__lowerCamelCase : List[str]=37 ,__lowerCamelCase : Optional[Any]="gelu" ,__lowerCamelCase : Optional[Any]=0.1 ,__lowerCamelCase : str=0.1 ,__lowerCamelCase : List[str]=10 ,__lowerCamelCase : Optional[int]=0.02 ,__lowerCamelCase : Union[str, Any]="divided_space_time" ,__lowerCamelCase : Optional[int]=None ,): '''simple docstring''' a = parent a = batch_size a = image_size a = num_channels a = patch_size a = num_frames a = is_training a = use_labels 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 = attention_type a = initializer_range a = scope a = num_labels # in TimeSformer, the number of spatial tokens equals num_frames * num_patches per frame + 1 CLS token a = (image_size // patch_size) ** 2 a = (num_frames) * self.num_patches_per_frame + 1 def SCREAMING_SNAKE_CASE_ ( self : Dict ): '''simple docstring''' a = floats_tensor( [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size] ) a = None if self.use_labels: a = ids_tensor([self.batch_size] ,self.num_labels ) a = self.get_config() return config, pixel_values, labels def SCREAMING_SNAKE_CASE_ ( self : List[str] ): '''simple docstring''' a = TimesformerConfig( image_size=self.image_size ,patch_size=self.patch_size ,num_channels=self.num_channels ,num_frames=self.num_frames ,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 ,initializer_range=self.initializer_range ,attention_type=self.attention_type ,) a = self.num_labels return config def SCREAMING_SNAKE_CASE_ ( self : List[Any] ,__lowerCamelCase : Dict ,__lowerCamelCase : List[Any] ,__lowerCamelCase : Any ): '''simple docstring''' a = TimesformerModel(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() a = model(__lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ,__lowerCamelCase : Union[str, Any] ,__lowerCamelCase : Any ,__lowerCamelCase : int ): '''simple docstring''' a = TimesformerForVideoClassification(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() a = model(__lowerCamelCase ) # verify the logits shape a = torch.Size((self.batch_size, self.num_labels) ) self.parent.assertEqual(result.logits.shape ,__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : Any ): '''simple docstring''' a = self.prepare_config_and_inputs() a , a , a = config_and_inputs a = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class lowerCamelCase_ ( a_ , a_ , unittest.TestCase ): SCREAMING_SNAKE_CASE_ = (TimesformerModel, TimesformerForVideoClassification) if is_torch_available() else () SCREAMING_SNAKE_CASE_ = ( {'feature-extraction': TimesformerModel, 'video-classification': TimesformerForVideoClassification} if is_torch_available() else {} ) SCREAMING_SNAKE_CASE_ = False SCREAMING_SNAKE_CASE_ = False SCREAMING_SNAKE_CASE_ = False SCREAMING_SNAKE_CASE_ = False def SCREAMING_SNAKE_CASE_ ( self : int ): '''simple docstring''' a = TimesformerModelTester(self ) a = ConfigTester( self ,config_class=__lowerCamelCase ,has_text_modality=__lowerCamelCase ,hidden_size=37 ) def SCREAMING_SNAKE_CASE_ ( self : str ,__lowerCamelCase : int ,__lowerCamelCase : List[str] ,__lowerCamelCase : str=False ): '''simple docstring''' a = copy.deepcopy(__lowerCamelCase ) if return_labels: if model_class in get_values(__lowerCamelCase ): a = torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=__lowerCamelCase ) return inputs_dict def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ): '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason='''TimeSformer does not use inputs_embeds''' ) def SCREAMING_SNAKE_CASE_ ( self : int ): '''simple docstring''' pass def SCREAMING_SNAKE_CASE_ ( self : int ): '''simple docstring''' a , a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a = model_class(__lowerCamelCase ) self.assertIsInstance(model.get_input_embeddings() ,(nn.Module) ) a = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__lowerCamelCase ,nn.Linear ) ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ): '''simple docstring''' a , a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a = model_class(__lowerCamelCase ) a = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic a = [*signature.parameters.keys()] a = ['''pixel_values'''] self.assertListEqual(arg_names[:1] ,__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ): '''simple docstring''' a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ): '''simple docstring''' a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_video_classification(*__lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self : List[Any] ): '''simple docstring''' for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a = TimesformerModel.from_pretrained(__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : int ): '''simple docstring''' if not self.has_attentions: pass else: a , a = self.model_tester.prepare_config_and_inputs_for_common() a = True for model_class in self.all_model_classes: a = self.model_tester.seq_length a = self.model_tester.num_frames a = True a = False a = True a = model_class(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() with torch.no_grad(): a = model(**self._prepare_for_class(__lowerCamelCase ,__lowerCamelCase ) ) a = outputs.attentions self.assertEqual(len(__lowerCamelCase ) ,self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] a = True a = model_class(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() with torch.no_grad(): a = model(**self._prepare_for_class(__lowerCamelCase ,__lowerCamelCase ) ) a = outputs.attentions self.assertEqual(len(__lowerCamelCase ) ,self.model_tester.num_hidden_layers ) # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1) self.assertListEqual( list(attentions[0].shape[-3:] ) ,[self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] ,) a = len(__lowerCamelCase ) # Check attention is always last and order is fine a = True a = True a = model_class(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() with torch.no_grad(): a = model(**self._prepare_for_class(__lowerCamelCase ,__lowerCamelCase ) ) self.assertEqual(out_len + 1 ,len(__lowerCamelCase ) ) a = outputs.attentions self.assertEqual(len(__lowerCamelCase ) ,self.model_tester.num_hidden_layers ) # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1) self.assertListEqual( list(self_attentions[0].shape[-3:] ) ,[self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] ,) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ): '''simple docstring''' def check_hidden_states_output(__lowerCamelCase : Any ,__lowerCamelCase : List[Any] ,__lowerCamelCase : Optional[int] ): a = model_class(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() with torch.no_grad(): a = model(**self._prepare_for_class(__lowerCamelCase ,__lowerCamelCase ) ) a = outputs.hidden_states a = self.model_tester.num_hidden_layers + 1 self.assertEqual(len(__lowerCamelCase ) ,__lowerCamelCase ) a = self.model_tester.seq_length self.assertListEqual( list(hidden_states[0].shape[-2:] ) ,[seq_length, self.model_tester.hidden_size] ,) a , a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a = True check_hidden_states_output(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] a = True check_hidden_states_output(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ) def SCREAMING_SNAKE_CASE__ ( ) -> Tuple: """simple docstring""" a = hf_hub_download( repo_id='''hf-internal-testing/spaghetti-video''', filename='''eating_spaghetti.npy''', repo_type='''dataset''' ) a = np.load(snake_case_ ) return list(snake_case_ ) @require_torch @require_vision class lowerCamelCase_ ( unittest.TestCase ): @cached_property def SCREAMING_SNAKE_CASE_ ( self : List[Any] ): '''simple docstring''' return ( VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5] ,image_std=[0.5, 0.5, 0.5] ) if is_vision_available() else None ) @slow def SCREAMING_SNAKE_CASE_ ( self : List[str] ): '''simple docstring''' a = TimesformerForVideoClassification.from_pretrained('''facebook/timesformer-base-finetuned-k400''' ).to( __lowerCamelCase ) a = self.default_image_processor a = prepare_video() a = image_processor(video[:8] ,return_tensors='''pt''' ).to(__lowerCamelCase ) # forward pass with torch.no_grad(): a = model(**__lowerCamelCase ) # verify the logits a = torch.Size((1, 4_00) ) self.assertEqual(outputs.logits.shape ,__lowerCamelCase ) a = torch.tensor([-0.3_016, -0.7_713, -0.4_205] ).to(__lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] ,__lowerCamelCase ,atol=1e-4 ) )
330
def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> Union[str, Any]: """simple docstring""" stooge(snake_case_, 0, len(snake_case_ ) - 1 ) return arr def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_ ) -> Optional[Any]: """simple docstring""" if i >= h: return # If first element is smaller than the last then swap them if arr[i] > arr[h]: a , a = arr[h], arr[i] # If there are more than 2 elements in the array if h - i + 1 > 2: a = (int)((h - i + 1) / 3 ) # Recursively sort first 2/3 elements stooge(snake_case_, snake_case_, (h - t) ) # Recursively sort last 2/3 elements stooge(snake_case_, i + t, (snake_case_) ) # Recursively sort first 2/3 elements stooge(snake_case_, snake_case_, (h - t) ) if __name__ == "__main__": UpperCamelCase__ : Dict = input("""Enter numbers separated by a comma:\n""").strip() UpperCamelCase__ : Optional[int] = [int(item) for item in user_input.split(""",""")] print(stooge_sort(unsorted))
330
1
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConformerConfig, WavaVecaConformerForCTC, WavaVecaConformerForPreTraining, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_verbosity_info() UpperCamelCase__ : List[str] = logging.get_logger(__name__) UpperCamelCase__ : Optional[Any] = { """post_extract_proj""": """feature_projection.projection""", """encoder.pos_conv.0""": """encoder.pos_conv_embed.conv""", """self_attn.linear_k""": """encoder.layers.*.self_attn.linear_k""", """self_attn.linear_v""": """encoder.layers.*.self_attn.linear_v""", """self_attn.linear_q""": """encoder.layers.*.self_attn.linear_q""", """self_attn.pos_bias_u""": """encoder.layers.*.self_attn.pos_bias_u""", """self_attn.pos_bias_v""": """encoder.layers.*.self_attn.pos_bias_v""", """self_attn.linear_out""": """encoder.layers.*.self_attn.linear_out""", """self_attn.linear_pos""": """encoder.layers.*.self_attn.linear_pos""", """self_attn.rotary_emb""": """encoder.embed_positions""", """self_attn_layer_norm""": """encoder.layers.*.self_attn_layer_norm""", """conv_module.pointwise_conv1""": """encoder.layers.*.conv_module.pointwise_conv1""", """conv_module.pointwise_conv2""": """encoder.layers.*.conv_module.pointwise_conv2""", """conv_module.depthwise_conv""": """encoder.layers.*.conv_module.depthwise_conv""", """conv_module.batch_norm""": """encoder.layers.*.conv_module.batch_norm""", """conv_module.layer_norm""": """encoder.layers.*.conv_module.layer_norm""", """ffn1.w_1""": """encoder.layers.*.ffn1.intermediate_dense""", """ffn1.w_2""": """encoder.layers.*.ffn1.output_dense""", """ffn1.layer_norm""": """encoder.layers.*.ffn1_layer_norm""", """ffn2.w_1""": """encoder.layers.*.ffn2.intermediate_dense""", """ffn2.w_2""": """encoder.layers.*.ffn2.output_dense""", """ffn2.layer_norm""": """encoder.layers.*.ffn2_layer_norm""", """final_layer_norm""": """encoder.layers.*.final_layer_norm""", """encoder.layer_norm""": """encoder.layer_norm""", """w2v_model.layer_norm""": """feature_projection.layer_norm""", """quantizer.weight_proj""": """quantizer.weight_proj""", """quantizer.vars""": """quantizer.codevectors""", """project_q""": """project_q""", """final_proj""": """project_hid""", """w2v_encoder.proj""": """lm_head""", """mask_emb""": """masked_spec_embed""", } UpperCamelCase__ : Optional[int] = [ """lm_head""", """quantizer.weight_proj""", """quantizer.codevectors""", """project_q""", """project_hid""", ] def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_, snake_case_, snake_case_ ) -> str: """simple docstring""" for attribute in key.split('''.''' ): a = getattr(snake_case_, snake_case_ ) if weight_type is not None: a = getattr(snake_case_, snake_case_ ).shape else: a = hf_pointer.shape if hf_shape != value.shape: raise ValueError( f"""Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be""" f""" {value.shape} for {full_name}""" ) if weight_type == "weight": a = value elif weight_type == "weight_g": a = value elif weight_type == "weight_v": a = value elif weight_type == "bias": a = value elif weight_type == "running_mean": a = value elif weight_type == "running_var": a = value elif weight_type == "num_batches_tracked": a = value elif weight_type == "inv_freq": a = value else: a = value logger.info(f"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" ) def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_ ) -> Dict: """simple docstring""" a = [] a = fairseq_model.state_dict() a = hf_model.wavaveca_conformer.feature_extractor for name, value in fairseq_dict.items(): a = False if "conv_layers" in name: load_conv_layer( snake_case_, snake_case_, snake_case_, snake_case_, hf_model.config.feat_extract_norm == '''group''', ) a = True else: for key, mapped_key in MAPPING.items(): a = '''wav2vec2_conformer.''' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split('''w2v_model.''' )[-1] == name.split('''.''' )[0]: a = True if "*" in mapped_key: a = name.split(snake_case_ )[0].split('''.''' )[-2] a = mapped_key.replace('''*''', snake_case_ ) if "pos_bias_u" in name: a = None elif "pos_bias_v" in name: a = None elif "weight_g" in name: a = '''weight_g''' elif "weight_v" in name: a = '''weight_v''' elif "bias" in name: a = '''bias''' elif "weight" in name: # TODO: don't match quantizer.weight_proj a = '''weight''' elif "running_mean" in name: a = '''running_mean''' elif "inv_freq" in name: a = '''inv_freq''' elif "running_var" in name: a = '''running_var''' elif "num_batches_tracked" in name: a = '''num_batches_tracked''' else: a = None set_recursively(snake_case_, snake_case_, snake_case_, snake_case_, snake_case_ ) continue if not is_used: unused_weights.append(snake_case_ ) logger.warning(f"""Unused weights: {unused_weights}""" ) def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_, snake_case_, snake_case_ ) -> List[str]: """simple docstring""" a = full_name.split('''conv_layers.''' )[-1] a = name.split('''.''' ) a = int(items[0] ) a = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) a = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) a = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.""" ) a = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.""" ) a = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(snake_case_ ) @torch.no_grad() def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_=None, snake_case_=None, snake_case_=True ) -> Dict: """simple docstring""" if config_path is not None: a = WavaVecaConformerConfig.from_pretrained(snake_case_, hidden_act='''swish''' ) else: a = WavaVecaConformerConfig() if "rope" in checkpoint_path: a = '''rotary''' if is_finetuned: if dict_path: a = Dictionary.load(snake_case_ ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq a = target_dict.pad_index a = target_dict.bos_index a = target_dict.eos_index a = len(target_dict.symbols ) a = os.path.join(snake_case_, '''vocab.json''' ) if not os.path.isdir(snake_case_ ): logger.error('''--pytorch_dump_folder_path ({}) should be a directory'''.format(snake_case_ ) ) return os.makedirs(snake_case_, exist_ok=snake_case_ ) a = target_dict.indices # fairseq has the <pad> and <s> switched a = 0 a = 1 with open(snake_case_, '''w''', encoding='''utf-8''' ) as vocab_handle: json.dump(snake_case_, snake_case_ ) a = WavaVecaCTCTokenizer( snake_case_, unk_token=target_dict.unk_word, pad_token=target_dict.pad_word, bos_token=target_dict.bos_word, eos_token=target_dict.eos_word, word_delimiter_token='''|''', do_lower_case=snake_case_, ) a = True if config.feat_extract_norm == '''layer''' else False a = WavaVecaFeatureExtractor( feature_size=1, sampling_rate=1_6_0_0_0, padding_value=0, do_normalize=snake_case_, return_attention_mask=snake_case_, ) a = WavaVecaProcessor(feature_extractor=snake_case_, tokenizer=snake_case_ ) processor.save_pretrained(snake_case_ ) a = WavaVecaConformerForCTC(snake_case_ ) else: a = WavaVecaConformerForPreTraining(snake_case_ ) if is_finetuned: a , a , a = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path], arg_overrides={'''data''': '''/'''.join(dict_path.split('''/''' )[:-1] )} ) else: a = argparse.Namespace(task='''audio_pretraining''' ) a = fairseq.tasks.setup_task(snake_case_ ) a , a , a = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path], task=snake_case_ ) a = model[0].eval() recursively_load_weights(snake_case_, snake_case_, not is_finetuned ) hf_wavavec.save_pretrained(snake_case_ ) if __name__ == "__main__": UpperCamelCase__ : Any = argparse.ArgumentParser() parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to fairseq checkpoint""") parser.add_argument("""--dict_path""", default=None, type=str, help="""Path to dict of fine-tuned model""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") parser.add_argument( """--not_finetuned""", action="""store_true""", help="""Whether the model to convert is a fine-tuned model or not""" ) UpperCamelCase__ : Tuple = parser.parse_args() convert_wavaveca_conformer_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
330
import json import os import re import unicodedata from json.encoder import INFINITY from typing import Any, Dict, List, Optional, Tuple, Union import numpy as np import regex from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, is_flax_available, is_tf_available, is_torch_available, logging from ...utils.generic import _is_jax, _is_numpy UpperCamelCase__ : Any = logging.get_logger(__name__) UpperCamelCase__ : Optional[Any] = { """artists_file""": """artists.json""", """lyrics_file""": """lyrics.json""", """genres_file""": """genres.json""", } UpperCamelCase__ : Union[str, Any] = { """artists_file""": { """jukebox""": """https://huggingface.co/ArthurZ/jukebox/blob/main/artists.json""", }, """genres_file""": { """jukebox""": """https://huggingface.co/ArthurZ/jukebox/blob/main/genres.json""", }, """lyrics_file""": { """jukebox""": """https://huggingface.co/ArthurZ/jukebox/blob/main/lyrics.json""", }, } UpperCamelCase__ : str = { """jukebox""": 512, } class lowerCamelCase_ ( a_ ): SCREAMING_SNAKE_CASE_ = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE_ = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE_ = PRETRAINED_LYRIC_TOKENS_SIZES SCREAMING_SNAKE_CASE_ = ['input_ids', 'attention_mask'] def __init__( self : Optional[Any] ,__lowerCamelCase : Optional[Any] ,__lowerCamelCase : List[Any] ,__lowerCamelCase : Tuple ,__lowerCamelCase : Union[str, Any]=["v3", "v2", "v2"] ,__lowerCamelCase : List[Any]=5_12 ,__lowerCamelCase : Tuple=5 ,__lowerCamelCase : List[Any]="<|endoftext|>" ,**__lowerCamelCase : List[str] ,): '''simple docstring''' a = AddedToken(__lowerCamelCase ,lstrip=__lowerCamelCase ,rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase ,__lowerCamelCase ) else unk_token super().__init__( unk_token=__lowerCamelCase ,n_genres=__lowerCamelCase ,version=__lowerCamelCase ,max_n_lyric_tokens=__lowerCamelCase ,**__lowerCamelCase ,) a = version a = max_n_lyric_tokens a = n_genres with open(__lowerCamelCase ,encoding='''utf-8''' ) as vocab_handle: a = json.load(__lowerCamelCase ) with open(__lowerCamelCase ,encoding='''utf-8''' ) as vocab_handle: a = json.load(__lowerCamelCase ) with open(__lowerCamelCase ,encoding='''utf-8''' ) as vocab_handle: a = json.load(__lowerCamelCase ) a = r'''[^A-Za-z0-9.,:;!?\-\'\"()\[\] \t\n]+''' # In v2, we had a n_vocab=80 and in v3 we missed + and so n_vocab=79 of characters. if len(self.lyrics_encoder ) == 79: a = oov.replace(r'''\-\'''' ,r'''\-+\'''' ) a = regex.compile(__lowerCamelCase ) a = {v: k for k, v in self.artists_encoder.items()} a = {v: k for k, v in self.genres_encoder.items()} a = {v: k for k, v in self.lyrics_encoder.items()} @property def SCREAMING_SNAKE_CASE_ ( self : str ): '''simple docstring''' return len(self.artists_encoder ) + len(self.genres_encoder ) + len(self.lyrics_encoder ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ): '''simple docstring''' return dict(self.artists_encoder ,self.genres_encoder ,self.lyrics_encoder ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ,__lowerCamelCase : Optional[int] ,__lowerCamelCase : Optional[Any] ,__lowerCamelCase : List[Any] ): '''simple docstring''' a = [self.artists_encoder.get(__lowerCamelCase ,0 ) for artist in list_artists] for genres in range(len(__lowerCamelCase ) ): a = [self.genres_encoder.get(__lowerCamelCase ,0 ) for genre in list_genres[genres]] a = list_genres[genres] + [-1] * (self.n_genres - len(list_genres[genres] )) a = [[self.lyrics_encoder.get(__lowerCamelCase ,0 ) for character in list_lyrics[0]], [], []] return artists_id, list_genres, lyric_ids def SCREAMING_SNAKE_CASE_ ( self : Tuple ,__lowerCamelCase : List[str] ): '''simple docstring''' return list(__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ,__lowerCamelCase : List[Any] ,__lowerCamelCase : Any ,__lowerCamelCase : Optional[int] ,**__lowerCamelCase : Optional[Any] ): '''simple docstring''' a , a , a = self.prepare_for_tokenization(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ) a = self._tokenize(__lowerCamelCase ) return artist, genre, lyrics def SCREAMING_SNAKE_CASE_ ( self : int ,__lowerCamelCase : str ,__lowerCamelCase : str ,__lowerCamelCase : str ,__lowerCamelCase : bool = False ): '''simple docstring''' for idx in range(len(self.version ) ): if self.version[idx] == "v3": a = artists[idx].lower() a = [genres[idx].lower()] else: a = self._normalize(artists[idx] ) + '''.v2''' a = [ self._normalize(__lowerCamelCase ) + '''.v2''' for genre in genres[idx].split('''_''' ) ] # split is for the full dictionary with combined genres if self.version[0] == "v2": a = regex.compile(r'''[^A-Za-z0-9.,:;!?\-\'\"()\[\] \t\n]+''' ) a = '''ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,:;!?-+\'\"()[] \t\n''' a = {vocab[index]: index + 1 for index in range(len(__lowerCamelCase ) )} a = 0 a = len(__lowerCamelCase ) + 1 a = self.vocab a = {v: k for k, v in self.vocab.items()} a = '''''' else: a = regex.compile(r'''[^A-Za-z0-9.,:;!?\-+\'\"()\[\] \t\n]+''' ) a = self._run_strip_accents(__lowerCamelCase ) a = lyrics.replace('''\\''' ,'''\n''' ) a = self.out_of_vocab.sub('''''' ,__lowerCamelCase ), [], [] return artists, genres, lyrics def SCREAMING_SNAKE_CASE_ ( self : str ,__lowerCamelCase : int ): '''simple docstring''' a = unicodedata.normalize('''NFD''' ,__lowerCamelCase ) a = [] for char in text: a = unicodedata.category(__lowerCamelCase ) if cat == "Mn": continue output.append(__lowerCamelCase ) return "".join(__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ,__lowerCamelCase : str ): '''simple docstring''' a = ( [chr(__lowerCamelCase ) for i in range(ord('''a''' ) ,ord('''z''' ) + 1 )] + [chr(__lowerCamelCase ) for i in range(ord('''A''' ) ,ord('''Z''' ) + 1 )] + [chr(__lowerCamelCase ) for i in range(ord('''0''' ) ,ord('''9''' ) + 1 )] + ['''.'''] ) a = frozenset(__lowerCamelCase ) a = re.compile(r'''_+''' ) a = ''''''.join([c if c in accepted else '''_''' for c in text.lower()] ) a = pattern.sub('''_''' ,__lowerCamelCase ).strip('''_''' ) return text def SCREAMING_SNAKE_CASE_ ( self : List[str] ,__lowerCamelCase : List[str] ): '''simple docstring''' return " ".join(__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : Any ,__lowerCamelCase : str ,__lowerCamelCase : Optional[Union[str, TensorType]] = None ,__lowerCamelCase : bool = False ): '''simple docstring''' if not isinstance(__lowerCamelCase ,__lowerCamelCase ): a = TensorType(__lowerCamelCase ) # Get a function reference for the correct framework if tensor_type == TensorType.TENSORFLOW: if not is_tf_available(): raise ImportError( '''Unable to convert output to TensorFlow tensors format, TensorFlow is not installed.''' ) import tensorflow as tf a = tf.constant a = tf.is_tensor elif tensor_type == TensorType.PYTORCH: if not is_torch_available(): raise ImportError('''Unable to convert output to PyTorch tensors format, PyTorch is not installed.''' ) import torch a = torch.tensor a = torch.is_tensor elif tensor_type == TensorType.JAX: if not is_flax_available(): raise ImportError('''Unable to convert output to JAX tensors format, JAX is not installed.''' ) import jax.numpy as jnp # noqa: F811 a = jnp.array a = _is_jax else: a = np.asarray a = _is_numpy # Do the tensor conversion in batch try: if prepend_batch_axis: a = [inputs] if not is_tensor(__lowerCamelCase ): a = as_tensor(__lowerCamelCase ) except: # noqa E722 raise ValueError( '''Unable to create tensor, you should probably activate truncation and/or padding ''' '''with \'padding=True\' \'truncation=True\' to have batched tensors with the same length.''' ) return inputs def __call__( self : Tuple ,__lowerCamelCase : Tuple ,__lowerCamelCase : Optional[int] ,__lowerCamelCase : List[str]="" ,__lowerCamelCase : List[Any]="pt" ): '''simple docstring''' a = [0, 0, 0] a = [artist] * len(self.version ) a = [genres] * len(self.version ) a , a , a = self.tokenize(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ) a , a , a = self._convert_token_to_id(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ) a = [-INFINITY] * len(full_tokens[-1] ) a = [ self.convert_to_tensors( [input_ids + [artists_id[i]] + genres_ids[i] + full_tokens[i]] ,tensor_type=__lowerCamelCase ) for i in range(len(self.version ) ) ] return BatchEncoding({'''input_ids''': input_ids, '''attention_masks''': attention_masks} ) def SCREAMING_SNAKE_CASE_ ( self : int ,__lowerCamelCase : str ,__lowerCamelCase : Optional[str] = None ): '''simple docstring''' 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['''artists_file'''] ) with open(__lowerCamelCase ,'''w''' ,encoding='''utf-8''' ) as f: f.write(json.dumps(self.artists_encoder ,ensure_ascii=__lowerCamelCase ) ) a = os.path.join( __lowerCamelCase ,(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''genres_file'''] ) with open(__lowerCamelCase ,'''w''' ,encoding='''utf-8''' ) as f: f.write(json.dumps(self.genres_encoder ,ensure_ascii=__lowerCamelCase ) ) a = os.path.join( __lowerCamelCase ,(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''lyrics_file'''] ) with open(__lowerCamelCase ,'''w''' ,encoding='''utf-8''' ) as f: f.write(json.dumps(self.lyrics_encoder ,ensure_ascii=__lowerCamelCase ) ) return (artists_file, genres_file, lyrics_file) def SCREAMING_SNAKE_CASE_ ( self : Any ,__lowerCamelCase : Any ,__lowerCamelCase : Any ,__lowerCamelCase : str ): '''simple docstring''' a = self.artists_decoder.get(__lowerCamelCase ) a = [self.genres_decoder.get(__lowerCamelCase ) for genre in genres_index] a = [self.lyrics_decoder.get(__lowerCamelCase ) for character in lyric_index] return artist, genres, lyrics
330
1
import numpy # List of input, output pairs UpperCamelCase__ : int = ( ((5, 2, 3), 15), ((6, 5, 9), 25), ((11, 12, 13), 41), ((1, 1, 1), 8), ((11, 12, 13), 41), ) UpperCamelCase__ : Optional[int] = (((515, 22, 13), 555), ((61, 35, 49), 150)) UpperCamelCase__ : str = [2, 4, 1, 5] UpperCamelCase__ : Union[str, Any] = len(train_data) UpperCamelCase__ : List[Any] = 0.0_0_9 def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_="train" ) -> List[str]: """simple docstring""" return calculate_hypothesis_value(snake_case_, snake_case_ ) - output( snake_case_, snake_case_ ) def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> Union[str, Any]: """simple docstring""" a = 0 for i in range(len(snake_case_ ) - 1 ): hyp_val += data_input_tuple[i] * parameter_vector[i + 1] hyp_val += parameter_vector[0] return hyp_val def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> List[Any]: """simple docstring""" if data_set == "train": return train_data[example_no][1] elif data_set == "test": return test_data[example_no][1] return None def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> Optional[Any]: """simple docstring""" if data_set == "train": return _hypothesis_value(train_data[example_no][0] ) elif data_set == "test": return _hypothesis_value(test_data[example_no][0] ) return None def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_=m ) -> Any: """simple docstring""" a = 0 for i in range(snake_case_ ): if index == -1: summation_value += _error(snake_case_ ) else: summation_value += _error(snake_case_ ) * train_data[i][0][index] return summation_value def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> int: """simple docstring""" a = summation_of_cost_derivative(snake_case_, snake_case_ ) / m return cost_derivative_value def SCREAMING_SNAKE_CASE__ ( ) -> Any: """simple docstring""" global parameter_vector # Tune these values to set a tolerance value for predicted output a = 0.00_0002 a = 0 a = 0 while True: j += 1 a = [0, 0, 0, 0] for i in range(0, len(snake_case_ ) ): a = get_cost_derivative(i - 1 ) a = ( parameter_vector[i] - LEARNING_RATE * cost_derivative ) if numpy.allclose( snake_case_, snake_case_, atol=snake_case_, rtol=snake_case_, ): break a = temp_parameter_vector print(('''Number of iterations:''', j) ) def SCREAMING_SNAKE_CASE__ ( ) -> Any: """simple docstring""" for i in range(len(snake_case_ ) ): print(('''Actual output value:''', output(snake_case_, '''test''' )) ) print(('''Hypothesis output:''', calculate_hypothesis_value(snake_case_, '''test''' )) ) if __name__ == "__main__": run_gradient_descent() print("""\nTesting gradient descent for a linear hypothesis function.\n""") test_gradient_descent()
330
# This script creates a super tiny model that is useful inside tests, when we just want to test that # the machinery works, without needing to the check the quality of the outcomes. # # This version creates a tiny vocab first, and then a tiny model - so the outcome is truly tiny - # all files ~60KB. As compared to taking a full-size model, reducing to the minimum its layers and # emb dimensions, but keeping the full vocab + merges files, leading to ~3MB in total for all files. # The latter is done by `fsmt-make-super-tiny-model.py`. # # It will be used then as "stas/tiny-wmt19-en-ru" from pathlib import Path import json import tempfile from transformers import FSMTTokenizer, FSMTConfig, FSMTForConditionalGeneration from transformers.models.fsmt.tokenization_fsmt import VOCAB_FILES_NAMES UpperCamelCase__ : Optional[Any] = """tiny-wmt19-en-ru""" # Build # borrowed from a test UpperCamelCase__ : Any = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """w</w>""", """r</w>""", """t</w>""", """lo""", """low""", """er</w>""", """low</w>""", """lowest</w>""", """newer</w>""", """wider</w>""", """<unk>""", ] UpperCamelCase__ : List[Any] = dict(zip(vocab, range(len(vocab)))) UpperCamelCase__ : Any = ["""l o 123""", """lo w 1456""", """e r</w> 1789""", """"""] with tempfile.TemporaryDirectory() as tmpdirname: UpperCamelCase__ : Optional[Any] = Path(tmpdirname) UpperCamelCase__ : Tuple = build_dir / VOCAB_FILES_NAMES["""src_vocab_file"""] UpperCamelCase__ : int = build_dir / VOCAB_FILES_NAMES["""tgt_vocab_file"""] UpperCamelCase__ : Union[str, Any] = build_dir / VOCAB_FILES_NAMES["""merges_file"""] with open(src_vocab_file, """w""") as fp: fp.write(json.dumps(vocab_tokens)) with open(tgt_vocab_file, """w""") as fp: fp.write(json.dumps(vocab_tokens)) with open(merges_file, """w""") as fp: fp.write("""\n""".join(merges)) UpperCamelCase__ : Dict = FSMTTokenizer( langs=["""en""", """ru"""], src_vocab_size=len(vocab), tgt_vocab_size=len(vocab), src_vocab_file=src_vocab_file, tgt_vocab_file=tgt_vocab_file, merges_file=merges_file, ) UpperCamelCase__ : Union[str, Any] = FSMTConfig( langs=["""ru""", """en"""], src_vocab_size=1_000, tgt_vocab_size=1_000, d_model=4, encoder_layers=1, decoder_layers=1, encoder_ffn_dim=4, decoder_ffn_dim=4, encoder_attention_heads=1, decoder_attention_heads=1, ) UpperCamelCase__ : Union[str, Any] = FSMTForConditionalGeneration(config) print(F"num of params {tiny_model.num_parameters()}") # Test UpperCamelCase__ : List[str] = tokenizer(["""Making tiny model"""], return_tensors="""pt""") UpperCamelCase__ : Tuple = tiny_model(**batch) print("""test output:""", len(outputs.logits[0])) # Save tiny_model.half() # makes it smaller tiny_model.save_pretrained(mname_tiny) tokenizer.save_pretrained(mname_tiny) print(F"Generated {mname_tiny}") # Upload # transformers-cli upload tiny-wmt19-en-ru
330
1
from abc import ABC, abstractmethod from typing import List, Optional class lowerCamelCase_ ( a_ ): def __init__( self : List[Any] ): '''simple docstring''' self.test() def SCREAMING_SNAKE_CASE_ ( self : Tuple ): '''simple docstring''' a = 0 a = False while not completed: if counter == 1: self.reset() a = self.advance() if not self.does_advance(__lowerCamelCase ): raise Exception( '''Custom Constraint is not defined correctly. self.does_advance(self.advance()) must be true.''' ) a , a , a = self.update(__lowerCamelCase ) counter += 1 if counter > 1_00_00: raise Exception('''update() does not fulfill the constraint.''' ) if self.remaining() != 0: raise Exception('''Custom Constraint is not defined correctly.''' ) @abstractmethod def SCREAMING_SNAKE_CASE_ ( self : int ): '''simple docstring''' raise NotImplementedError( F"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""" ) @abstractmethod def SCREAMING_SNAKE_CASE_ ( self : Any ,__lowerCamelCase : int ): '''simple docstring''' raise NotImplementedError( F"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""" ) @abstractmethod def SCREAMING_SNAKE_CASE_ ( self : str ,__lowerCamelCase : int ): '''simple docstring''' raise NotImplementedError( F"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""" ) @abstractmethod def SCREAMING_SNAKE_CASE_ ( self : str ): '''simple docstring''' raise NotImplementedError( F"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""" ) @abstractmethod def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ): '''simple docstring''' raise NotImplementedError( F"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""" ) @abstractmethod def SCREAMING_SNAKE_CASE_ ( self : Tuple ,__lowerCamelCase : int=False ): '''simple docstring''' raise NotImplementedError( F"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""" ) class lowerCamelCase_ ( a_ ): def __init__( self : List[str] ,__lowerCamelCase : List[int] ): '''simple docstring''' super(__lowerCamelCase ,self ).__init__() if not isinstance(__lowerCamelCase ,__lowerCamelCase ) or len(__lowerCamelCase ) == 0: raise ValueError(F"""`token_ids` has to be a non-empty list, but is {token_ids}.""" ) if any((not isinstance(__lowerCamelCase ,__lowerCamelCase ) or token_id < 0) for token_id in token_ids ): raise ValueError(F"""Each list in `token_ids` has to be a list of positive integers, but is {token_ids}.""" ) a = token_ids a = len(self.token_ids ) a = -1 # the index of the currently fulfilled step a = False def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ): '''simple docstring''' if self.completed: return None return self.token_ids[self.fulfilled_idx + 1] def SCREAMING_SNAKE_CASE_ ( self : Dict ,__lowerCamelCase : int ): '''simple docstring''' if not isinstance(__lowerCamelCase ,__lowerCamelCase ): raise ValueError(F"""`token_id` has to be an `int`, but is {token_id} of type {type(__lowerCamelCase )}""" ) if self.completed: return False return token_id == self.token_ids[self.fulfilled_idx + 1] def SCREAMING_SNAKE_CASE_ ( self : str ,__lowerCamelCase : int ): '''simple docstring''' if not isinstance(__lowerCamelCase ,__lowerCamelCase ): raise ValueError(F"""`token_id` has to be an `int`, but is {token_id} of type {type(__lowerCamelCase )}""" ) a = False a = False a = False if self.does_advance(__lowerCamelCase ): self.fulfilled_idx += 1 a = True if self.fulfilled_idx == (self.seqlen - 1): a = True a = completed else: # failed to make progress. a = True self.reset() return stepped, completed, reset def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ): '''simple docstring''' a = False a = 0 def SCREAMING_SNAKE_CASE_ ( self : Dict ): '''simple docstring''' return self.seqlen - (self.fulfilled_idx + 1) def SCREAMING_SNAKE_CASE_ ( self : Dict ,__lowerCamelCase : Dict=False ): '''simple docstring''' a = PhrasalConstraint(self.token_ids ) if stateful: a = self.seqlen a = self.fulfilled_idx a = self.completed return new_constraint class lowerCamelCase_ : def __init__( self : Dict ,__lowerCamelCase : List[List[int]] ,__lowerCamelCase : Union[str, Any]=True ): '''simple docstring''' a = max([len(__lowerCamelCase ) for one in nested_token_ids] ) a = {} for token_ids in nested_token_ids: a = root for tidx, token_id in enumerate(__lowerCamelCase ): if token_id not in level: a = {} a = level[token_id] if no_subsets and self.has_subsets(__lowerCamelCase ,__lowerCamelCase ): raise ValueError( '''Each list in `nested_token_ids` can\'t be a complete subset of another list, but is''' F""" {nested_token_ids}.""" ) a = root def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ,__lowerCamelCase : str ): '''simple docstring''' a = self.trie for current_token in current_seq: a = start[current_token] a = list(start.keys() ) return next_tokens def SCREAMING_SNAKE_CASE_ ( self : List[str] ,__lowerCamelCase : Union[str, Any] ): '''simple docstring''' a = self.next_tokens(__lowerCamelCase ) return len(__lowerCamelCase ) == 0 def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ,__lowerCamelCase : Optional[int] ): '''simple docstring''' a = list(root.values() ) if len(__lowerCamelCase ) == 0: return 1 else: return sum([self.count_leaves(__lowerCamelCase ) for nn in next_nodes] ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ,__lowerCamelCase : Any ,__lowerCamelCase : Optional[Any] ): '''simple docstring''' a = self.count_leaves(__lowerCamelCase ) return len(__lowerCamelCase ) != leaf_count class lowerCamelCase_ ( a_ ): def __init__( self : List[Any] ,__lowerCamelCase : List[List[int]] ): '''simple docstring''' super(__lowerCamelCase ,self ).__init__() if not isinstance(__lowerCamelCase ,__lowerCamelCase ) or len(__lowerCamelCase ) == 0: raise ValueError(F"""`nested_token_ids` has to be a non-empty list, but is {nested_token_ids}.""" ) if any(not isinstance(__lowerCamelCase ,__lowerCamelCase ) for token_ids in nested_token_ids ): raise ValueError(F"""`nested_token_ids` has to be a list of lists, but is {nested_token_ids}.""" ) if any( any((not isinstance(__lowerCamelCase ,__lowerCamelCase ) or token_id < 0) for token_id in token_ids ) for token_ids in nested_token_ids ): raise ValueError( F"""Each list in `nested_token_ids` has to be a list of positive integers, but is {nested_token_ids}.""" ) a = DisjunctiveTrie(__lowerCamelCase ) a = nested_token_ids a = self.trie.max_height a = [] a = False def SCREAMING_SNAKE_CASE_ ( self : List[Any] ): '''simple docstring''' a = self.trie.next_tokens(self.current_seq ) if len(__lowerCamelCase ) == 0: return None else: return token_list def SCREAMING_SNAKE_CASE_ ( self : Any ,__lowerCamelCase : int ): '''simple docstring''' if not isinstance(__lowerCamelCase ,__lowerCamelCase ): raise ValueError(F"""`token_id` is supposed to be type `int`, but is {token_id} of type {type(__lowerCamelCase )}""" ) a = self.trie.next_tokens(self.current_seq ) return token_id in next_tokens def SCREAMING_SNAKE_CASE_ ( self : Dict ,__lowerCamelCase : int ): '''simple docstring''' if not isinstance(__lowerCamelCase ,__lowerCamelCase ): raise ValueError(F"""`token_id` is supposed to be type `int`, but is {token_id} of type {type(__lowerCamelCase )}""" ) a = False a = False a = False if self.does_advance(__lowerCamelCase ): self.current_seq.append(__lowerCamelCase ) a = True else: a = True self.reset() a = self.trie.reached_leaf(self.current_seq ) a = completed return stepped, completed, reset def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ): '''simple docstring''' a = False a = [] def SCREAMING_SNAKE_CASE_ ( self : List[str] ): '''simple docstring''' if self.completed: # since this can be completed without reaching max height return 0 else: return self.seqlen - len(self.current_seq ) def SCREAMING_SNAKE_CASE_ ( self : Any ,__lowerCamelCase : Any=False ): '''simple docstring''' a = DisjunctiveConstraint(self.token_ids ) if stateful: a = self.seqlen a = self.current_seq a = self.completed return new_constraint class lowerCamelCase_ : def __init__( self : List[Any] ,__lowerCamelCase : List[Constraint] ): '''simple docstring''' a = constraints # max # of steps required to fulfill a given constraint a = max([c.seqlen for c in constraints] ) a = len(__lowerCamelCase ) a = False self.init_state() def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ): '''simple docstring''' a = [] a = None a = [constraint.copy(stateful=__lowerCamelCase ) for constraint in self.constraints] def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ): '''simple docstring''' a = 0 if self.inprogress_constraint: # extra points for having a constraint mid-fulfilled add += self.max_seqlen - self.inprogress_constraint.remaining() return (len(self.complete_constraints ) * self.max_seqlen) + add def SCREAMING_SNAKE_CASE_ ( self : str ): '''simple docstring''' a = [] if self.inprogress_constraint is None: for constraint in self.pending_constraints: # "pending" == "unfulfilled yet" a = constraint.advance() if isinstance(__lowerCamelCase ,__lowerCamelCase ): token_list.append(__lowerCamelCase ) elif isinstance(__lowerCamelCase ,__lowerCamelCase ): token_list.extend(__lowerCamelCase ) else: a = self.inprogress_constraint.advance() if isinstance(__lowerCamelCase ,__lowerCamelCase ): token_list.append(__lowerCamelCase ) elif isinstance(__lowerCamelCase ,__lowerCamelCase ): token_list.extend(__lowerCamelCase ) if len(__lowerCamelCase ) == 0: return None else: return token_list def SCREAMING_SNAKE_CASE_ ( self : int ,__lowerCamelCase : Optional[List[int]] ): '''simple docstring''' self.init_state() if token_ids is not None: for token in token_ids: # completes or steps **one** constraint a , a = self.add(__lowerCamelCase ) # the entire list of constraints are fulfilled if self.completed: break def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ,__lowerCamelCase : int ): '''simple docstring''' if not isinstance(__lowerCamelCase ,__lowerCamelCase ): raise ValueError(F"""`token_id` should be an `int`, but is `{token_id}`.""" ) a , a = False, False if self.completed: a = True a = False return complete, stepped if self.inprogress_constraint is not None: # In the middle of fulfilling a constraint. If the `token_id` *does* makes an incremental progress to current # job, simply update the state a , a , a = self.inprogress_constraint.update(__lowerCamelCase ) if reset: # 1. If the next token breaks the progress, then we must restart. # e.g. constraint = "I love pies" and sequence so far is "I love" but `token_id` == "books". # But that doesn't mean we self.init_state(), since we only reset the state for this particular # constraint, not the full list of constraints. self.pending_constraints.append(self.inprogress_constraint.copy(stateful=__lowerCamelCase ) ) a = None if complete: # 2. If the next token completes the constraint, move it to completed list, set # inprogress to None. If there are no pending constraints either, then this full list of constraints # is complete. self.complete_constraints.append(self.inprogress_constraint ) a = None if len(self.pending_constraints ) == 0: # we're done! a = True else: # Not in the middle of fulfilling a constraint. So does this `token_id` helps us step towards any of our list # of constraints? for cidx, pending_constraint in enumerate(self.pending_constraints ): if pending_constraint.does_advance(__lowerCamelCase ): a , a , a = pending_constraint.update(__lowerCamelCase ) if not stepped: raise Exception( '''`constraint.update(token_id)` is not yielding incremental progress, ''' '''even though `constraint.does_advance(token_id)` is true.''' ) if complete: self.complete_constraints.append(__lowerCamelCase ) a = None if not complete and stepped: a = pending_constraint if complete or stepped: # If we made any progress at all, then it's at least not a "pending constraint". a = ( self.pending_constraints[:cidx] + self.pending_constraints[cidx + 1 :] ) if len(self.pending_constraints ) == 0 and self.inprogress_constraint is None: # If there's no longer any pending after this and no inprogress either, then we must be # complete. a = True break # prevent accidentally stepping through multiple constraints with just one token. return complete, stepped def SCREAMING_SNAKE_CASE_ ( self : List[str] ,__lowerCamelCase : Tuple=True ): '''simple docstring''' a = ConstraintListState(self.constraints ) # we actually never though self.constraints objects # throughout this process. So it's at initialization state. if stateful: a = [ constraint.copy(stateful=__lowerCamelCase ) for constraint in self.complete_constraints ] if self.inprogress_constraint is not None: a = self.inprogress_constraint.copy(stateful=__lowerCamelCase ) a = [constraint.copy() for constraint in self.pending_constraints] return new_state
330
import inspect import os import torch from transformers import AutoModel from transformers.testing_utils import mockenv_context from transformers.trainer_utils import set_seed import accelerate from accelerate.accelerator import Accelerator from accelerate.state import AcceleratorState from accelerate.test_utils.testing import ( AccelerateTestCase, TempDirTestCase, execute_subprocess_async, require_cuda, require_fsdp, require_multi_gpu, slow, ) from accelerate.utils.constants import ( FSDP_AUTO_WRAP_POLICY, FSDP_BACKWARD_PREFETCH, FSDP_SHARDING_STRATEGY, FSDP_STATE_DICT_TYPE, ) from accelerate.utils.dataclasses import FullyShardedDataParallelPlugin from accelerate.utils.other import patch_environment set_seed(42) UpperCamelCase__ : Optional[Any] = """bert-base-cased""" UpperCamelCase__ : int = """fp16""" UpperCamelCase__ : str = """bf16""" UpperCamelCase__ : List[Any] = [FPaa, BFaa] @require_fsdp @require_cuda class lowerCamelCase_ ( a_ ): def SCREAMING_SNAKE_CASE_ ( self : int ): '''simple docstring''' super().setUp() a = dict( ACCELERATE_USE_FSDP='''true''' ,MASTER_ADDR='''localhost''' ,MASTER_PORT='''10999''' ,RANK='''0''' ,LOCAL_RANK='''0''' ,WORLD_SIZE='''1''' ,) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ): '''simple docstring''' from torch.distributed.fsdp.fully_sharded_data_parallel import ShardingStrategy for i, strategy in enumerate(__lowerCamelCase ): a = self.dist_env.copy() a = F"""{i + 1}""" a = strategy with mockenv_context(**__lowerCamelCase ): a = FullyShardedDataParallelPlugin() self.assertEqual(fsdp_plugin.sharding_strategy ,ShardingStrategy(i + 1 ) ) def SCREAMING_SNAKE_CASE_ ( self : Any ): '''simple docstring''' from torch.distributed.fsdp.fully_sharded_data_parallel import BackwardPrefetch for i, prefetch_policy in enumerate(__lowerCamelCase ): a = self.dist_env.copy() a = prefetch_policy with mockenv_context(**__lowerCamelCase ): a = FullyShardedDataParallelPlugin() if prefetch_policy == "NO_PREFETCH": self.assertIsNone(fsdp_plugin.backward_prefetch ) else: self.assertEqual(fsdp_plugin.backward_prefetch ,BackwardPrefetch(i + 1 ) ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ): '''simple docstring''' from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType for i, state_dict_type in enumerate(__lowerCamelCase ): a = self.dist_env.copy() a = state_dict_type with mockenv_context(**__lowerCamelCase ): a = FullyShardedDataParallelPlugin() self.assertEqual(fsdp_plugin.state_dict_type ,StateDictType(i + 1 ) ) if state_dict_type == "FULL_STATE_DICT": self.assertTrue(fsdp_plugin.state_dict_config.offload_to_cpu ) self.assertTrue(fsdp_plugin.state_dict_config.ranka_only ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ): '''simple docstring''' a = AutoModel.from_pretrained(__lowerCamelCase ) for policy in FSDP_AUTO_WRAP_POLICY: a = self.dist_env.copy() a = policy if policy == "TRANSFORMER_BASED_WRAP": a = '''BertLayer''' elif policy == "SIZE_BASED_WRAP": a = '''2000''' with mockenv_context(**__lowerCamelCase ): a = FullyShardedDataParallelPlugin() fsdp_plugin.set_auto_wrap_policy(__lowerCamelCase ) if policy == "NO_WRAP": self.assertIsNone(fsdp_plugin.auto_wrap_policy ) else: self.assertIsNotNone(fsdp_plugin.auto_wrap_policy ) a = self.dist_env.copy() a = '''TRANSFORMER_BASED_WRAP''' a = '''T5Layer''' with mockenv_context(**__lowerCamelCase ): a = FullyShardedDataParallelPlugin() with self.assertRaises(__lowerCamelCase ) as cm: fsdp_plugin.set_auto_wrap_policy(__lowerCamelCase ) self.assertTrue('''Could not find the transformer layer class to wrap in the model.''' in str(cm.exception ) ) a = self.dist_env.copy() a = '''SIZE_BASED_WRAP''' a = '''0''' with mockenv_context(**__lowerCamelCase ): a = FullyShardedDataParallelPlugin() fsdp_plugin.set_auto_wrap_policy(__lowerCamelCase ) self.assertIsNone(fsdp_plugin.auto_wrap_policy ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ): '''simple docstring''' from torch.distributed.fsdp.fully_sharded_data_parallel import MixedPrecision from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler for mp_dtype in dtypes: a = self.dist_env.copy() a = mp_dtype with mockenv_context(**__lowerCamelCase ): a = Accelerator() if mp_dtype == "fp16": a = torch.floataa elif mp_dtype == "bf16": a = torch.bfloataa a = MixedPrecision(param_dtype=__lowerCamelCase ,reduce_dtype=__lowerCamelCase ,buffer_dtype=__lowerCamelCase ) self.assertEqual(accelerator.state.fsdp_plugin.mixed_precision_policy ,__lowerCamelCase ) if mp_dtype == FPaa: self.assertTrue(isinstance(accelerator.scaler ,__lowerCamelCase ) ) elif mp_dtype == BFaa: self.assertIsNone(accelerator.scaler ) AcceleratorState._reset_state(__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ): '''simple docstring''' from torch.distributed.fsdp.fully_sharded_data_parallel import CPUOffload for flag in [True, False]: a = self.dist_env.copy() a = str(__lowerCamelCase ).lower() with mockenv_context(**__lowerCamelCase ): a = FullyShardedDataParallelPlugin() self.assertEqual(fsdp_plugin.cpu_offload ,CPUOffload(offload_params=__lowerCamelCase ) ) @require_fsdp @require_multi_gpu @slow class lowerCamelCase_ ( a_ ): def SCREAMING_SNAKE_CASE_ ( self : List[Any] ): '''simple docstring''' super().setUp() a = 0.82 a = [ '''fsdp_shard_grad_op_transformer_based_wrap''', '''fsdp_full_shard_transformer_based_wrap''', ] a = { '''multi_gpu_fp16''': 32_00, '''fsdp_shard_grad_op_transformer_based_wrap_fp16''': 20_00, '''fsdp_full_shard_transformer_based_wrap_fp16''': 19_00, # Disabling below test as it overwhelms the RAM memory usage # on CI self-hosted runner leading to tests getting killed. # "fsdp_full_shard_cpu_offload_transformer_based_wrap_fp32": 1500, # fp16 was leading to indefinite hang } a = 1_60 a = 1_60 a = inspect.getfile(accelerate.test_utils ) a = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''external_deps'''] ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ): '''simple docstring''' a = os.path.join(self.test_scripts_folder ,'''test_performance.py''' ) a = ['''accelerate''', '''launch''', '''--num_processes=2''', '''--num_machines=1''', '''--machine_rank=0''', '''--use_fsdp'''] for config in self.performance_configs: a = cmd.copy() for i, strategy in enumerate(__lowerCamelCase ): if strategy.lower() in config: cmd_config.append(F"""--fsdp_sharding_strategy={i+1}""" ) break if "fp32" in config: cmd_config.append('''--mixed_precision=no''' ) else: cmd_config.append('''--mixed_precision=fp16''' ) if "cpu_offload" in config: cmd_config.append('''--fsdp_offload_params=True''' ) for policy in FSDP_AUTO_WRAP_POLICY: if policy.lower() in config: cmd_config.append(F"""--fsdp_auto_wrap_policy={policy}""" ) break if policy == "TRANSFORMER_BASED_WRAP": cmd_config.append('''--fsdp_transformer_layer_cls_to_wrap=BertLayer''' ) elif policy == "SIZE_BASED_WRAP": cmd_config.append('''--fsdp_min_num_params=2000''' ) cmd_config.extend( [ self.test_file_path, F"""--output_dir={self.tmpdir}""", F"""--performance_lower_bound={self.performance_lower_bound}""", ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__lowerCamelCase ,env=os.environ.copy() ) def SCREAMING_SNAKE_CASE_ ( self : Any ): '''simple docstring''' a = os.path.join(self.test_scripts_folder ,'''test_checkpointing.py''' ) a = [ '''accelerate''', '''launch''', '''--num_processes=2''', '''--num_machines=1''', '''--machine_rank=0''', '''--use_fsdp''', '''--mixed_precision=fp16''', '''--fsdp_transformer_layer_cls_to_wrap=BertLayer''', ] for i, strategy in enumerate(__lowerCamelCase ): a = cmd.copy() cmd_config.append(F"""--fsdp_sharding_strategy={i+1}""" ) if strategy != "FULL_SHARD": continue a = len(__lowerCamelCase ) for state_dict_type in FSDP_STATE_DICT_TYPE: a = cmd_config[:state_dict_config_index] cmd_config.append(F"""--fsdp_state_dict_type={state_dict_type}""" ) cmd_config.extend( [ self.test_file_path, F"""--output_dir={self.tmpdir}""", '''--partial_train_epoch=1''', ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__lowerCamelCase ,env=os.environ.copy() ) a = cmd_config[:-1] a = os.path.join(self.tmpdir ,'''epoch_0''' ) cmd_config.extend( [ F"""--resume_from_checkpoint={resume_from_checkpoint}""", ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__lowerCamelCase ,env=os.environ.copy() ) def SCREAMING_SNAKE_CASE_ ( self : int ): '''simple docstring''' a = os.path.join(self.test_scripts_folder ,'''test_peak_memory_usage.py''' ) a = [ '''accelerate''', '''launch''', '''--num_processes=2''', '''--num_machines=1''', '''--machine_rank=0''', ] for spec, peak_mem_upper_bound in self.peak_memory_usage_upper_bound.items(): a = cmd.copy() if "fp16" in spec: cmd_config.extend(['''--mixed_precision=fp16'''] ) else: cmd_config.extend(['''--mixed_precision=no'''] ) if "multi_gpu" in spec: continue else: cmd_config.extend(['''--use_fsdp'''] ) for i, strategy in enumerate(__lowerCamelCase ): if strategy.lower() in spec: cmd_config.append(F"""--fsdp_sharding_strategy={i+1}""" ) break if "cpu_offload" in spec: cmd_config.append('''--fsdp_offload_params=True''' ) for policy in FSDP_AUTO_WRAP_POLICY: if policy.lower() in spec: cmd_config.append(F"""--fsdp_auto_wrap_policy={policy}""" ) break if policy == "TRANSFORMER_BASED_WRAP": cmd_config.append('''--fsdp_transformer_layer_cls_to_wrap=BertLayer''' ) elif policy == "SIZE_BASED_WRAP": cmd_config.append('''--fsdp_min_num_params=2000''' ) cmd_config.extend( [ self.test_file_path, F"""--output_dir={self.tmpdir}""", F"""--peak_memory_upper_bound={peak_mem_upper_bound}""", F"""--n_train={self.n_train}""", F"""--n_val={self.n_val}""", ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__lowerCamelCase ,env=os.environ.copy() )
330
1
import re def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> str: """simple docstring""" if len(re.findall('''[ATCG]''', snake_case_ ) ) != len(snake_case_ ): raise ValueError('''Invalid Strand''' ) return dna.translate(dna.maketrans('''ATCG''', '''TAGC''' ) ) if __name__ == "__main__": import doctest doctest.testmod()
330
from __future__ import annotations import os from collections.abc import Mapping UpperCamelCase__ : Any = tuple[int, int] class lowerCamelCase_ : def __init__( self : Optional[Any] ,__lowerCamelCase : set[int] ,__lowerCamelCase : Mapping[EdgeT, int] ): '''simple docstring''' a = vertices a = { (min(__lowerCamelCase ), max(__lowerCamelCase )): weight for edge, weight in edges.items() } def SCREAMING_SNAKE_CASE_ ( self : str ,__lowerCamelCase : EdgeT ,__lowerCamelCase : int ): '''simple docstring''' self.vertices.add(edge[0] ) self.vertices.add(edge[1] ) a = weight def SCREAMING_SNAKE_CASE_ ( self : Dict ): '''simple docstring''' a = Graph({min(self.vertices )} ,{} ) a = 42 a = 42 a = 42 a = 42 while len(subgraph.vertices ) < len(self.vertices ): a = max(self.edges.values() ) + 1 for edge, weight in self.edges.items(): if (edge[0] in subgraph.vertices) ^ (edge[1] in subgraph.vertices): if weight < min_weight: a = edge a = weight subgraph.add_edge(__lowerCamelCase ,__lowerCamelCase ) return subgraph def SCREAMING_SNAKE_CASE__ ( snake_case_ = "p107_network.txt" ) -> int: """simple docstring""" a = os.path.abspath(os.path.dirname(snake_case_ ) ) a = os.path.join(snake_case_, snake_case_ ) a = {} a = 42 a = 42 a = 42 with open(snake_case_ ) as f: a = f.read().strip().split('''\n''' ) a = [line.split(''',''' ) for line in data] for edgea in range(1, len(snake_case_ ) ): for edgea in range(snake_case_ ): if adjaceny_matrix[edgea][edgea] != "-": a = int(adjaceny_matrix[edgea][edgea] ) a = Graph(set(range(len(snake_case_ ) ) ), snake_case_ ) a = graph.prims_algorithm() a = sum(graph.edges.values() ) a = sum(subgraph.edges.values() ) return initial_total - optimal_total if __name__ == "__main__": print(F"{solution() = }")
330
1
def SCREAMING_SNAKE_CASE__ ( ) -> int: """simple docstring""" for n in range(1, 1_0_0_0_0_0_0 ): yield n * (n + 1) // 2 def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> Dict: """simple docstring""" a = 1 a = 2 while i * i <= n: a = 0 while n % i == 0: n //= i multiplicity += 1 divisors_count *= multiplicity + 1 i += 1 if n > 1: divisors_count *= 2 return divisors_count def SCREAMING_SNAKE_CASE__ ( ) -> List[str]: """simple docstring""" return next(i for i in triangle_number_generator() if count_divisors(snake_case_ ) > 5_0_0 ) if __name__ == "__main__": print(solution())
330
from typing import Optional, Tuple, Union import tensorflow as tf from ...activations_tf import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_tf_outputs import ( TFBaseModelOutputWithNoAttention, TFBaseModelOutputWithPoolingAndNoAttention, TFSequenceClassifierOutput, ) from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs from ...tf_utils import shape_list from ...utils import logging from .configuration_regnet import RegNetConfig UpperCamelCase__ : List[Any] = logging.get_logger(__name__) # General docstring UpperCamelCase__ : List[Any] = """RegNetConfig""" # Base docstring UpperCamelCase__ : Dict = """facebook/regnet-y-040""" UpperCamelCase__ : int = [1, 1_088, 7, 7] # Image classification docstring UpperCamelCase__ : Optional[Any] = """facebook/regnet-y-040""" UpperCamelCase__ : Dict = """tabby, tabby cat""" UpperCamelCase__ : Dict = [ """facebook/regnet-y-040""", # See all regnet models at https://huggingface.co/models?filter=regnet ] class lowerCamelCase_ ( tf.keras.layers.Layer ): def __init__( self : List[str] ,__lowerCamelCase : int ,__lowerCamelCase : int = 3 ,__lowerCamelCase : int = 1 ,__lowerCamelCase : int = 1 ,__lowerCamelCase : Optional[str] = "relu" ,**__lowerCamelCase : str ,): '''simple docstring''' super().__init__(**__lowerCamelCase ) # The padding and conv has been verified in # https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb a = tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2 ) a = tf.keras.layers.ConvaD( filters=__lowerCamelCase ,kernel_size=__lowerCamelCase ,strides=__lowerCamelCase ,padding='''VALID''' ,groups=__lowerCamelCase ,use_bias=__lowerCamelCase ,name='''convolution''' ,) a = tf.keras.layers.BatchNormalization(epsilon=1e-5 ,momentum=0.9 ,name='''normalization''' ) a = ACTaFN[activation] if activation is not None else tf.identity def SCREAMING_SNAKE_CASE_ ( self : str ,__lowerCamelCase : List[str] ): '''simple docstring''' a = self.convolution(self.padding(__lowerCamelCase ) ) a = self.normalization(__lowerCamelCase ) a = self.activation(__lowerCamelCase ) return hidden_state class lowerCamelCase_ ( tf.keras.layers.Layer ): def __init__( self : Any ,__lowerCamelCase : RegNetConfig ,**__lowerCamelCase : List[Any] ): '''simple docstring''' super().__init__(**__lowerCamelCase ) a = config.num_channels a = TFRegNetConvLayer( out_channels=config.embedding_size ,kernel_size=3 ,stride=2 ,activation=config.hidden_act ,name='''embedder''' ,) def SCREAMING_SNAKE_CASE_ ( self : Any ,__lowerCamelCase : Optional[Any] ): '''simple docstring''' a = shape_list(__lowerCamelCase )[1] if tf.executing_eagerly() and num_channels != self.num_channels: raise ValueError( '''Make sure that the channel dimension of the pixel values match with the one set in the configuration.''' ) # When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format. # So change the input format from `NCHW` to `NHWC`. # shape = (batch_size, in_height, in_width, in_channels=num_channels) a = tf.transpose(__lowerCamelCase ,perm=(0, 2, 3, 1) ) a = self.embedder(__lowerCamelCase ) return hidden_state class lowerCamelCase_ ( tf.keras.layers.Layer ): def __init__( self : str ,__lowerCamelCase : int ,__lowerCamelCase : int = 2 ,**__lowerCamelCase : Tuple ): '''simple docstring''' super().__init__(**__lowerCamelCase ) a = tf.keras.layers.ConvaD( filters=__lowerCamelCase ,kernel_size=1 ,strides=__lowerCamelCase ,use_bias=__lowerCamelCase ,name='''convolution''' ) a = tf.keras.layers.BatchNormalization(epsilon=1e-5 ,momentum=0.9 ,name='''normalization''' ) def SCREAMING_SNAKE_CASE_ ( self : Dict ,__lowerCamelCase : tf.Tensor ,__lowerCamelCase : bool = False ): '''simple docstring''' return self.normalization(self.convolution(__lowerCamelCase ) ,training=__lowerCamelCase ) class lowerCamelCase_ ( tf.keras.layers.Layer ): def __init__( self : List[Any] ,__lowerCamelCase : int ,__lowerCamelCase : int ,**__lowerCamelCase : str ): '''simple docstring''' super().__init__(**__lowerCamelCase ) a = tf.keras.layers.GlobalAveragePoolingaD(keepdims=__lowerCamelCase ,name='''pooler''' ) a = [ tf.keras.layers.ConvaD(filters=__lowerCamelCase ,kernel_size=1 ,activation='''relu''' ,name='''attention.0''' ), tf.keras.layers.ConvaD(filters=__lowerCamelCase ,kernel_size=1 ,activation='''sigmoid''' ,name='''attention.2''' ), ] def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ,__lowerCamelCase : Optional[Any] ): '''simple docstring''' a = self.pooler(__lowerCamelCase ) for layer_module in self.attention: a = layer_module(__lowerCamelCase ) a = hidden_state * pooled return hidden_state class lowerCamelCase_ ( tf.keras.layers.Layer ): def __init__( self : Union[str, Any] ,__lowerCamelCase : RegNetConfig ,__lowerCamelCase : int ,__lowerCamelCase : int ,__lowerCamelCase : int = 1 ,**__lowerCamelCase : Dict ): '''simple docstring''' super().__init__(**__lowerCamelCase ) a = in_channels != out_channels or stride != 1 a = max(1 ,out_channels // config.groups_width ) a = ( TFRegNetShortCut(__lowerCamelCase ,stride=__lowerCamelCase ,name='''shortcut''' ) if should_apply_shortcut else tf.keras.layers.Activation('''linear''' ,name='''shortcut''' ) ) # `self.layers` instead of `self.layer` because that is a reserved argument. a = [ TFRegNetConvLayer(__lowerCamelCase ,kernel_size=1 ,activation=config.hidden_act ,name='''layer.0''' ), TFRegNetConvLayer( __lowerCamelCase ,stride=__lowerCamelCase ,groups=__lowerCamelCase ,activation=config.hidden_act ,name='''layer.1''' ), TFRegNetConvLayer(__lowerCamelCase ,kernel_size=1 ,activation=__lowerCamelCase ,name='''layer.2''' ), ] a = ACTaFN[config.hidden_act] def SCREAMING_SNAKE_CASE_ ( self : List[str] ,__lowerCamelCase : Union[str, Any] ): '''simple docstring''' a = hidden_state for layer_module in self.layers: a = layer_module(__lowerCamelCase ) a = self.shortcut(__lowerCamelCase ) hidden_state += residual a = self.activation(__lowerCamelCase ) return hidden_state class lowerCamelCase_ ( tf.keras.layers.Layer ): def __init__( self : Dict ,__lowerCamelCase : RegNetConfig ,__lowerCamelCase : int ,__lowerCamelCase : int ,__lowerCamelCase : int = 1 ,**__lowerCamelCase : List[str] ): '''simple docstring''' super().__init__(**__lowerCamelCase ) a = in_channels != out_channels or stride != 1 a = max(1 ,out_channels // config.groups_width ) a = ( TFRegNetShortCut(__lowerCamelCase ,stride=__lowerCamelCase ,name='''shortcut''' ) if should_apply_shortcut else tf.keras.layers.Activation('''linear''' ,name='''shortcut''' ) ) a = [ TFRegNetConvLayer(__lowerCamelCase ,kernel_size=1 ,activation=config.hidden_act ,name='''layer.0''' ), TFRegNetConvLayer( __lowerCamelCase ,stride=__lowerCamelCase ,groups=__lowerCamelCase ,activation=config.hidden_act ,name='''layer.1''' ), TFRegNetSELayer(__lowerCamelCase ,reduced_channels=int(round(in_channels / 4 ) ) ,name='''layer.2''' ), TFRegNetConvLayer(__lowerCamelCase ,kernel_size=1 ,activation=__lowerCamelCase ,name='''layer.3''' ), ] a = ACTaFN[config.hidden_act] def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ,__lowerCamelCase : str ): '''simple docstring''' a = hidden_state for layer_module in self.layers: a = layer_module(__lowerCamelCase ) a = self.shortcut(__lowerCamelCase ) hidden_state += residual a = self.activation(__lowerCamelCase ) return hidden_state class lowerCamelCase_ ( tf.keras.layers.Layer ): def __init__( self : Optional[int] ,__lowerCamelCase : RegNetConfig ,__lowerCamelCase : int ,__lowerCamelCase : int ,__lowerCamelCase : int = 2 ,__lowerCamelCase : int = 2 ,**__lowerCamelCase : Optional[Any] ): '''simple docstring''' super().__init__(**__lowerCamelCase ) a = TFRegNetXLayer if config.layer_type == '''x''' else TFRegNetYLayer a = [ # downsampling is done in the first layer with stride of 2 layer(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ,stride=__lowerCamelCase ,name='''layers.0''' ), *[layer(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ,name=F"""layers.{i+1}""" ) for i in range(depth - 1 )], ] def SCREAMING_SNAKE_CASE_ ( self : Tuple ,__lowerCamelCase : int ): '''simple docstring''' for layer_module in self.layers: a = layer_module(__lowerCamelCase ) return hidden_state class lowerCamelCase_ ( tf.keras.layers.Layer ): def __init__( self : Union[str, Any] ,__lowerCamelCase : RegNetConfig ,**__lowerCamelCase : Optional[Any] ): '''simple docstring''' super().__init__(**__lowerCamelCase ) a = [] # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( TFRegNetStage( __lowerCamelCase ,config.embedding_size ,config.hidden_sizes[0] ,stride=2 if config.downsample_in_first_stage else 1 ,depth=config.depths[0] ,name='''stages.0''' ,) ) a = zip(config.hidden_sizes ,config.hidden_sizes[1:] ) for i, ((in_channels, out_channels), depth) in enumerate(zip(__lowerCamelCase ,config.depths[1:] ) ): self.stages.append(TFRegNetStage(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ,depth=__lowerCamelCase ,name=F"""stages.{i+1}""" ) ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ,__lowerCamelCase : tf.Tensor ,__lowerCamelCase : bool = False ,__lowerCamelCase : bool = True ): '''simple docstring''' a = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: a = hidden_states + (hidden_state,) a = stage_module(__lowerCamelCase ) if output_hidden_states: a = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return TFBaseModelOutputWithNoAttention(last_hidden_state=__lowerCamelCase ,hidden_states=__lowerCamelCase ) @keras_serializable class lowerCamelCase_ ( tf.keras.layers.Layer ): SCREAMING_SNAKE_CASE_ = RegNetConfig def __init__( self : Dict ,__lowerCamelCase : Optional[int] ,**__lowerCamelCase : Optional[Any] ): '''simple docstring''' super().__init__(**__lowerCamelCase ) a = config a = TFRegNetEmbeddings(__lowerCamelCase ,name='''embedder''' ) a = TFRegNetEncoder(__lowerCamelCase ,name='''encoder''' ) a = tf.keras.layers.GlobalAveragePoolingaD(keepdims=__lowerCamelCase ,name='''pooler''' ) @unpack_inputs def SCREAMING_SNAKE_CASE_ ( self : Tuple ,__lowerCamelCase : tf.Tensor ,__lowerCamelCase : Optional[bool] = None ,__lowerCamelCase : Optional[bool] = None ,__lowerCamelCase : bool = False ,): '''simple docstring''' a = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) a = return_dict if return_dict is not None else self.config.use_return_dict a = self.embedder(__lowerCamelCase ,training=__lowerCamelCase ) a = self.encoder( __lowerCamelCase ,output_hidden_states=__lowerCamelCase ,return_dict=__lowerCamelCase ,training=__lowerCamelCase ) a = encoder_outputs[0] a = self.pooler(__lowerCamelCase ) # Change to NCHW output format have uniformity in the modules a = tf.transpose(__lowerCamelCase ,perm=(0, 3, 1, 2) ) a = tf.transpose(__lowerCamelCase ,perm=(0, 3, 1, 2) ) # Change the other hidden state outputs to NCHW as well if output_hidden_states: a = tuple([tf.transpose(__lowerCamelCase ,perm=(0, 3, 1, 2) ) for h in encoder_outputs[1]] ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=__lowerCamelCase ,pooler_output=__lowerCamelCase ,hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states ,) class lowerCamelCase_ ( a_ ): SCREAMING_SNAKE_CASE_ = RegNetConfig SCREAMING_SNAKE_CASE_ = 'regnet' SCREAMING_SNAKE_CASE_ = 'pixel_values' @property def SCREAMING_SNAKE_CASE_ ( self : str ): '''simple docstring''' return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 2_24, 2_24) ,dtype=tf.floataa )} UpperCamelCase__ : Union[str, Any] = R""" Parameters: This model is a Tensorflow [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and behavior. config ([`RegNetConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights. """ UpperCamelCase__ : List[str] = R""" Args: pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`ConveNextImageProcessor.__call__`] for details. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. """ @add_start_docstrings( 'The bare RegNet model outputting raw features without any specific head on top.' , a_ , ) class lowerCamelCase_ ( a_ ): def __init__( self : Optional[int] ,__lowerCamelCase : RegNetConfig ,*__lowerCamelCase : int ,**__lowerCamelCase : Union[str, Any] ): '''simple docstring''' super().__init__(__lowerCamelCase ,*__lowerCamelCase ,**__lowerCamelCase ) a = TFRegNetMainLayer(__lowerCamelCase ,name='''regnet''' ) @unpack_inputs @add_start_docstrings_to_model_forward(__lowerCamelCase ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC ,output_type=__lowerCamelCase ,config_class=_CONFIG_FOR_DOC ,modality='''vision''' ,expected_output=_EXPECTED_OUTPUT_SHAPE ,) def SCREAMING_SNAKE_CASE_ ( self : Any ,__lowerCamelCase : tf.Tensor ,__lowerCamelCase : Optional[bool] = None ,__lowerCamelCase : Optional[bool] = None ,__lowerCamelCase : List[str]=False ,): '''simple docstring''' a = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) a = return_dict if return_dict is not None else self.config.use_return_dict a = self.regnet( pixel_values=__lowerCamelCase ,output_hidden_states=__lowerCamelCase ,return_dict=__lowerCamelCase ,training=__lowerCamelCase ,) if not return_dict: return (outputs[0],) + outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=outputs.last_hidden_state ,pooler_output=outputs.pooler_output ,hidden_states=outputs.hidden_states ,) @add_start_docstrings( '\n RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n ' , a_ , ) class lowerCamelCase_ ( a_ , a_ ): def __init__( self : Optional[int] ,__lowerCamelCase : RegNetConfig ,*__lowerCamelCase : str ,**__lowerCamelCase : Any ): '''simple docstring''' super().__init__(__lowerCamelCase ,*__lowerCamelCase ,**__lowerCamelCase ) a = config.num_labels a = TFRegNetMainLayer(__lowerCamelCase ,name='''regnet''' ) # classification head a = [ tf.keras.layers.Flatten(), tf.keras.layers.Dense(config.num_labels ,name='''classifier.1''' ) if config.num_labels > 0 else tf.identity, ] @unpack_inputs @add_start_docstrings_to_model_forward(__lowerCamelCase ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT ,output_type=__lowerCamelCase ,config_class=_CONFIG_FOR_DOC ,expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT ,) def SCREAMING_SNAKE_CASE_ ( self : Tuple ,__lowerCamelCase : tf.Tensor = None ,__lowerCamelCase : tf.Tensor = None ,__lowerCamelCase : bool = None ,__lowerCamelCase : bool = None ,__lowerCamelCase : Dict=False ,): '''simple docstring''' a = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) a = return_dict if return_dict is not None else self.config.use_return_dict a = self.regnet( __lowerCamelCase ,output_hidden_states=__lowerCamelCase ,return_dict=__lowerCamelCase ,training=__lowerCamelCase ) a = outputs.pooler_output if return_dict else outputs[1] a = self.classifier[0](__lowerCamelCase ) a = self.classifier[1](__lowerCamelCase ) a = None if labels is None else self.hf_compute_loss(labels=__lowerCamelCase ,logits=__lowerCamelCase ) if not return_dict: a = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return TFSequenceClassifierOutput(loss=__lowerCamelCase ,logits=__lowerCamelCase ,hidden_states=outputs.hidden_states )
330
1
import random import unittest from torch.utils.data import BatchSampler, DataLoader, IterableDataset from accelerate import Accelerator from accelerate.data_loader import ( BatchSamplerShard, DataLoaderDispatcher, DataLoaderShard, IterableDatasetShard, SkipBatchSampler, SkipDataLoader, skip_first_batches, ) class lowerCamelCase_ ( a_ ): def __init__( self : Any ,__lowerCamelCase : Tuple=0.01 ,__lowerCamelCase : str=10_00 ): '''simple docstring''' a = p_stop a = max_length def __iter__( self : Any ): '''simple docstring''' a = 0 a = False while not stop and count < self.max_length: yield count count += 1 a = random.random() < self.p_stop class lowerCamelCase_ ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self : str ,__lowerCamelCase : List[str] ,__lowerCamelCase : int ,__lowerCamelCase : Optional[int]=False ,__lowerCamelCase : int=True ): '''simple docstring''' a = [ BatchSamplerShard(__lowerCamelCase ,2 ,__lowerCamelCase ,split_batches=__lowerCamelCase ,even_batches=__lowerCamelCase ) for i in range(2 ) ] a = [list(__lowerCamelCase ) for batch_sampler_shard in batch_sampler_shards] if not split_batches: self.assertListEqual([len(__lowerCamelCase ) for shard in batch_sampler_shards] ,[len(__lowerCamelCase ) for e in expected] ) self.assertListEqual(__lowerCamelCase ,__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : int ): '''simple docstring''' a = BatchSampler(range(24 ) ,batch_size=3 ,drop_last=__lowerCamelCase ) a = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [21, 22, 23]], ] self.check_batch_sampler_shards(__lowerCamelCase ,__lowerCamelCase ) a = BatchSampler(range(24 ) ,batch_size=3 ,drop_last=__lowerCamelCase ) # Expected shouldn't change self.check_batch_sampler_shards(__lowerCamelCase ,__lowerCamelCase ) # Check the shards when the dataset is a round multiple of batch size but not total batch size. a = BatchSampler(range(21 ) ,batch_size=3 ,drop_last=__lowerCamelCase ) a = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [0, 1, 2]], ] self.check_batch_sampler_shards(__lowerCamelCase ,__lowerCamelCase ) a = BatchSampler(range(21 ) ,batch_size=3 ,drop_last=__lowerCamelCase ) a = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(__lowerCamelCase ,__lowerCamelCase ) # Check the shards when the dataset is not a round multiple of batch size but has a multiple of # num_processes batch. a = BatchSampler(range(22 ) ,batch_size=3 ,drop_last=__lowerCamelCase ) a = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [21, 0, 1]], ] self.check_batch_sampler_shards(__lowerCamelCase ,__lowerCamelCase ) a = BatchSampler(range(22 ) ,batch_size=3 ,drop_last=__lowerCamelCase ) a = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(__lowerCamelCase ,__lowerCamelCase ) # Check the shards when the dataset is not a round multiple of batch size but and has not a multiple of # num_processes batch. a = BatchSampler(range(20 ) ,batch_size=3 ,drop_last=__lowerCamelCase ) a = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 0]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [1, 2, 3]], ] self.check_batch_sampler_shards(__lowerCamelCase ,__lowerCamelCase ) a = BatchSampler(range(20 ) ,batch_size=3 ,drop_last=__lowerCamelCase ) a = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(__lowerCamelCase ,__lowerCamelCase ) # Check the shards when the dataset is very small. a = BatchSampler(range(2 ) ,batch_size=3 ,drop_last=__lowerCamelCase ) a = [[[0, 1, 0]], [[1, 0, 1]]] self.check_batch_sampler_shards(__lowerCamelCase ,__lowerCamelCase ) a = BatchSampler(range(2 ) ,batch_size=3 ,drop_last=__lowerCamelCase ) a = [[], []] self.check_batch_sampler_shards(__lowerCamelCase ,__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ): '''simple docstring''' a = BatchSampler(range(24 ) ,batch_size=4 ,drop_last=__lowerCamelCase ) a = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [22, 23]], ] self.check_batch_sampler_shards(__lowerCamelCase ,__lowerCamelCase ,split_batches=__lowerCamelCase ) a = BatchSampler(range(24 ) ,batch_size=4 ,drop_last=__lowerCamelCase ) # Expected shouldn't change self.check_batch_sampler_shards(__lowerCamelCase ,__lowerCamelCase ,split_batches=__lowerCamelCase ) # Check the shards when the dataset is not a round multiple of batch size. a = BatchSampler(range(22 ) ,batch_size=4 ,drop_last=__lowerCamelCase ) a = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [0, 1]], ] self.check_batch_sampler_shards(__lowerCamelCase ,__lowerCamelCase ,split_batches=__lowerCamelCase ) a = BatchSampler(range(22 ) ,batch_size=4 ,drop_last=__lowerCamelCase ) a = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(__lowerCamelCase ,__lowerCamelCase ,split_batches=__lowerCamelCase ) # Check the shards when the dataset is not a round multiple of batch size or num_processes. a = BatchSampler(range(21 ) ,batch_size=4 ,drop_last=__lowerCamelCase ) a = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 0]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [1, 2]], ] self.check_batch_sampler_shards(__lowerCamelCase ,__lowerCamelCase ,split_batches=__lowerCamelCase ) a = BatchSampler(range(21 ) ,batch_size=4 ,drop_last=__lowerCamelCase ) a = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(__lowerCamelCase ,__lowerCamelCase ,split_batches=__lowerCamelCase ) # Check the shards when the dataset is very small. a = BatchSampler(range(2 ) ,batch_size=4 ,drop_last=__lowerCamelCase ) a = [[[0, 1]], [[0, 1]]] self.check_batch_sampler_shards(__lowerCamelCase ,__lowerCamelCase ,split_batches=__lowerCamelCase ) a = BatchSampler(range(2 ) ,batch_size=4 ,drop_last=__lowerCamelCase ) a = [[], []] self.check_batch_sampler_shards(__lowerCamelCase ,__lowerCamelCase ,split_batches=__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ): '''simple docstring''' a = BatchSampler(range(24 ) ,batch_size=3 ,drop_last=__lowerCamelCase ) a = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [21, 22, 23]], ] self.check_batch_sampler_shards(__lowerCamelCase ,__lowerCamelCase ,even_batches=__lowerCamelCase ) a = BatchSampler(range(24 ) ,batch_size=3 ,drop_last=__lowerCamelCase ) # Expected shouldn't change self.check_batch_sampler_shards(__lowerCamelCase ,__lowerCamelCase ,even_batches=__lowerCamelCase ) # Check the shards when the dataset is a round multiple of batch size but not total batch size. a = BatchSampler(range(21 ) ,batch_size=3 ,drop_last=__lowerCamelCase ) a = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(__lowerCamelCase ,__lowerCamelCase ,even_batches=__lowerCamelCase ) a = BatchSampler(range(21 ) ,batch_size=3 ,drop_last=__lowerCamelCase ) a = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(__lowerCamelCase ,__lowerCamelCase ,even_batches=__lowerCamelCase ) # Check the shards when the dataset is not a round multiple of batch size but has a multiple of # num_processes batch. a = BatchSampler(range(22 ) ,batch_size=3 ,drop_last=__lowerCamelCase ) a = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [21]], ] self.check_batch_sampler_shards(__lowerCamelCase ,__lowerCamelCase ,even_batches=__lowerCamelCase ) a = BatchSampler(range(22 ) ,batch_size=3 ,drop_last=__lowerCamelCase ) a = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(__lowerCamelCase ,__lowerCamelCase ,even_batches=__lowerCamelCase ) # Check the shards when the dataset is not a round multiple of batch size but and has not a multiple of # num_processes batch. a = BatchSampler(range(20 ) ,batch_size=3 ,drop_last=__lowerCamelCase ) a = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(__lowerCamelCase ,__lowerCamelCase ,even_batches=__lowerCamelCase ) a = BatchSampler(range(20 ) ,batch_size=3 ,drop_last=__lowerCamelCase ) a = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(__lowerCamelCase ,__lowerCamelCase ,even_batches=__lowerCamelCase ) # Check the shards when the dataset is very small. a = BatchSampler(range(2 ) ,batch_size=3 ,drop_last=__lowerCamelCase ) a = [[[0, 1]], []] self.check_batch_sampler_shards(__lowerCamelCase ,__lowerCamelCase ,even_batches=__lowerCamelCase ) a = BatchSampler(range(2 ) ,batch_size=3 ,drop_last=__lowerCamelCase ) a = [[], []] self.check_batch_sampler_shards(__lowerCamelCase ,__lowerCamelCase ,even_batches=__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ): '''simple docstring''' a = BatchSampler(range(24 ) ,batch_size=4 ,drop_last=__lowerCamelCase ) a = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [22, 23]], ] self.check_batch_sampler_shards(__lowerCamelCase ,__lowerCamelCase ,split_batches=__lowerCamelCase ,even_batches=__lowerCamelCase ) a = BatchSampler(range(24 ) ,batch_size=4 ,drop_last=__lowerCamelCase ) # Expected shouldn't change self.check_batch_sampler_shards(__lowerCamelCase ,__lowerCamelCase ,split_batches=__lowerCamelCase ,even_batches=__lowerCamelCase ) # Check the shards when the dataset is not a round multiple of batch size. a = BatchSampler(range(22 ) ,batch_size=4 ,drop_last=__lowerCamelCase ) a = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(__lowerCamelCase ,__lowerCamelCase ,split_batches=__lowerCamelCase ,even_batches=__lowerCamelCase ) a = BatchSampler(range(22 ) ,batch_size=4 ,drop_last=__lowerCamelCase ) a = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(__lowerCamelCase ,__lowerCamelCase ,split_batches=__lowerCamelCase ,even_batches=__lowerCamelCase ) # Check the shards when the dataset is not a round multiple of batch size or num_processes. a = BatchSampler(range(21 ) ,batch_size=4 ,drop_last=__lowerCamelCase ) a = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(__lowerCamelCase ,__lowerCamelCase ,split_batches=__lowerCamelCase ,even_batches=__lowerCamelCase ) a = BatchSampler(range(21 ) ,batch_size=4 ,drop_last=__lowerCamelCase ) a = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(__lowerCamelCase ,__lowerCamelCase ,split_batches=__lowerCamelCase ,even_batches=__lowerCamelCase ) # Check the shards when the dataset is very small. a = BatchSampler(range(2 ) ,batch_size=4 ,drop_last=__lowerCamelCase ) a = [[[0, 1]], []] self.check_batch_sampler_shards(__lowerCamelCase ,__lowerCamelCase ,split_batches=__lowerCamelCase ,even_batches=__lowerCamelCase ) a = BatchSampler(range(2 ) ,batch_size=4 ,drop_last=__lowerCamelCase ) a = [[], []] self.check_batch_sampler_shards(__lowerCamelCase ,__lowerCamelCase ,split_batches=__lowerCamelCase ,even_batches=__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : int ): '''simple docstring''' a = [[0, 1, 2], [3, 4], [5, 6, 7, 8], [9, 10, 11], [12, 13]] a = [BatchSamplerShard(__lowerCamelCase ,2 ,__lowerCamelCase ,even_batches=__lowerCamelCase ) for i in range(2 )] self.assertEqual(len(batch_sampler_shards[0] ) ,3 ) self.assertEqual(len(batch_sampler_shards[1] ) ,2 ) self.assertListEqual(list(batch_sampler_shards[0] ) ,[[0, 1, 2], [5, 6, 7, 8], [12, 13]] ) self.assertListEqual(list(batch_sampler_shards[1] ) ,[[3, 4], [9, 10, 11]] ) def SCREAMING_SNAKE_CASE_ ( self : Dict ,__lowerCamelCase : Any ,__lowerCamelCase : Tuple ,__lowerCamelCase : Union[str, Any] ,__lowerCamelCase : List[Any]=False ,__lowerCamelCase : Any=2 ,__lowerCamelCase : str=False ): '''simple docstring''' random.seed(__lowerCamelCase ) a = list(__lowerCamelCase ) a = [ IterableDatasetShard( __lowerCamelCase ,batch_size=__lowerCamelCase ,drop_last=__lowerCamelCase ,num_processes=__lowerCamelCase ,process_index=__lowerCamelCase ,split_batches=__lowerCamelCase ,) for i in range(__lowerCamelCase ) ] a = [] for iterable_dataset_shard in iterable_dataset_shards: # Since our random iterable dataset will be... random... we need to use a seed to get reproducible results. random.seed(__lowerCamelCase ) iterable_dataset_lists.append(list(__lowerCamelCase ) ) a = batch_size // num_processes if split_batches else batch_size # All iterable dataset shard should have the same length, a round multiple of shard_batch_size a = iterable_dataset_lists[0] for l in iterable_dataset_lists[1:]: self.assertEqual(len(__lowerCamelCase ) ,len(__lowerCamelCase ) ) self.assertTrue(len(__lowerCamelCase ) % shard_batch_size == 0 ) a = [] for idx in range(0 ,len(__lowerCamelCase ) ,__lowerCamelCase ): for l in iterable_dataset_lists: observed += l[idx : idx + shard_batch_size] if not drop_last: while len(__lowerCamelCase ) < len(__lowerCamelCase ): reference += reference self.assertListEqual(__lowerCamelCase ,reference[: len(__lowerCamelCase )] ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ): '''simple docstring''' a = 42 a = RandomIterableDataset() self.check_iterable_dataset_shards(__lowerCamelCase ,__lowerCamelCase ,batch_size=4 ,drop_last=__lowerCamelCase ,split_batches=__lowerCamelCase ) self.check_iterable_dataset_shards(__lowerCamelCase ,__lowerCamelCase ,batch_size=4 ,drop_last=__lowerCamelCase ,split_batches=__lowerCamelCase ) self.check_iterable_dataset_shards(__lowerCamelCase ,__lowerCamelCase ,batch_size=4 ,drop_last=__lowerCamelCase ,split_batches=__lowerCamelCase ) self.check_iterable_dataset_shards(__lowerCamelCase ,__lowerCamelCase ,batch_size=4 ,drop_last=__lowerCamelCase ,split_batches=__lowerCamelCase ) # Edge case with a very small dataset a = RandomIterableDataset(max_length=2 ) self.check_iterable_dataset_shards(__lowerCamelCase ,__lowerCamelCase ,batch_size=4 ,drop_last=__lowerCamelCase ,split_batches=__lowerCamelCase ) self.check_iterable_dataset_shards(__lowerCamelCase ,__lowerCamelCase ,batch_size=4 ,drop_last=__lowerCamelCase ,split_batches=__lowerCamelCase ) self.check_iterable_dataset_shards(__lowerCamelCase ,__lowerCamelCase ,batch_size=4 ,drop_last=__lowerCamelCase ,split_batches=__lowerCamelCase ) self.check_iterable_dataset_shards(__lowerCamelCase ,__lowerCamelCase ,batch_size=4 ,drop_last=__lowerCamelCase ,split_batches=__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ): '''simple docstring''' a = BatchSampler(range(16 ) ,batch_size=4 ,drop_last=__lowerCamelCase ) a = SkipBatchSampler(__lowerCamelCase ,2 ) self.assertListEqual(list(__lowerCamelCase ) ,[[8, 9, 10, 11], [12, 13, 14, 15]] ) def SCREAMING_SNAKE_CASE_ ( self : Any ): '''simple docstring''' a = SkipDataLoader(list(range(16 ) ) ,batch_size=4 ,skip_batches=2 ) self.assertListEqual([t.tolist() for t in dataloader] ,[[8, 9, 10, 11], [12, 13, 14, 15]] ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ): '''simple docstring''' a = DataLoader(list(range(16 ) ) ,batch_size=4 ) a = skip_first_batches(__lowerCamelCase ,num_batches=2 ) self.assertListEqual([t.tolist() for t in new_dataloader] ,[[8, 9, 10, 11], [12, 13, 14, 15]] ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ): '''simple docstring''' a = DataLoaderShard(list(range(16 ) ) ,batch_size=4 ) for idx, _ in enumerate(__lowerCamelCase ): self.assertEqual(dataloader.end_of_dataloader ,idx == 3 ) # Test it also works on the second iteration for idx, _ in enumerate(__lowerCamelCase ): self.assertEqual(dataloader.end_of_dataloader ,idx == 3 ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ): '''simple docstring''' Accelerator() a = DataLoaderDispatcher(range(16 ) ,batch_size=4 ) for idx, _ in enumerate(__lowerCamelCase ): self.assertEqual(dataloader.end_of_dataloader ,idx == 3 ) # Test it also works on the second iteration for idx, _ in enumerate(__lowerCamelCase ): self.assertEqual(dataloader.end_of_dataloader ,idx == 3 )
330
from typing import List from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase__ : Union[str, Any] = logging.get_logger(__name__) UpperCamelCase__ : List[str] = { """snap-research/efficientformer-l1-300""": ( """https://huggingface.co/snap-research/efficientformer-l1-300/resolve/main/config.json""" ), } class lowerCamelCase_ ( a_ ): SCREAMING_SNAKE_CASE_ = 'efficientformer' def __init__( self : Optional[int] ,__lowerCamelCase : List[int] = [3, 2, 6, 4] ,__lowerCamelCase : List[int] = [48, 96, 2_24, 4_48] ,__lowerCamelCase : List[bool] = [True, True, True, True] ,__lowerCamelCase : int = 4_48 ,__lowerCamelCase : int = 32 ,__lowerCamelCase : int = 4 ,__lowerCamelCase : int = 7 ,__lowerCamelCase : int = 5 ,__lowerCamelCase : int = 8 ,__lowerCamelCase : int = 4 ,__lowerCamelCase : float = 0.0 ,__lowerCamelCase : int = 16 ,__lowerCamelCase : int = 3 ,__lowerCamelCase : int = 3 ,__lowerCamelCase : int = 3 ,__lowerCamelCase : int = 2 ,__lowerCamelCase : int = 1 ,__lowerCamelCase : float = 0.0 ,__lowerCamelCase : int = 1 ,__lowerCamelCase : bool = True ,__lowerCamelCase : bool = True ,__lowerCamelCase : float = 1e-5 ,__lowerCamelCase : str = "gelu" ,__lowerCamelCase : float = 0.02 ,__lowerCamelCase : float = 1e-12 ,__lowerCamelCase : int = 2_24 ,__lowerCamelCase : float = 1e-05 ,**__lowerCamelCase : Dict ,): '''simple docstring''' super().__init__(**__lowerCamelCase ) a = hidden_act a = hidden_dropout_prob a = hidden_sizes a = num_hidden_layers a = num_attention_heads a = initializer_range a = layer_norm_eps a = patch_size a = num_channels a = depths a = mlp_expansion_ratio a = downsamples a = dim a = key_dim a = attention_ratio a = resolution a = pool_size a = downsample_patch_size a = downsample_stride a = downsample_pad a = drop_path_rate a = num_metaad_blocks a = distillation a = use_layer_scale a = layer_scale_init_value a = image_size a = batch_norm_eps
330
1
import logging import os import threading import time try: import warnings except ImportError: UpperCamelCase__ : List[Any] = None try: import msvcrt except ImportError: UpperCamelCase__ : Optional[Any] = None try: import fcntl except ImportError: UpperCamelCase__ : Optional[Any] = None # Backward compatibility # ------------------------------------------------ try: TimeoutError except NameError: UpperCamelCase__ : List[str] = OSError # Data # ------------------------------------------------ UpperCamelCase__ : str = [ """Timeout""", """BaseFileLock""", """WindowsFileLock""", """UnixFileLock""", """SoftFileLock""", """FileLock""", ] UpperCamelCase__ : str = """3.0.12""" UpperCamelCase__ : Optional[Any] = None def SCREAMING_SNAKE_CASE__ ( ) -> int: """simple docstring""" global _logger a = _logger or logging.getLogger(__name__ ) return _logger class lowerCamelCase_ ( a_ ): def __init__( self : Optional[Any] ,__lowerCamelCase : Union[str, Any] ): '''simple docstring''' a = lock_file return None def __str__( self : List[Any] ): '''simple docstring''' a = F"""The file lock '{self.lock_file}' could not be acquired.""" return temp class lowerCamelCase_ : def __init__( self : Dict ,__lowerCamelCase : Tuple ): '''simple docstring''' a = lock return None def __enter__( self : int ): '''simple docstring''' return self.lock def __exit__( self : Dict ,__lowerCamelCase : Union[str, Any] ,__lowerCamelCase : Optional[int] ,__lowerCamelCase : List[Any] ): '''simple docstring''' self.lock.release() return None class lowerCamelCase_ : def __init__( self : str ,__lowerCamelCase : List[str] ,__lowerCamelCase : Union[str, Any]=-1 ,__lowerCamelCase : Optional[int]=None ): '''simple docstring''' a = max_filename_length if max_filename_length is not None else 2_55 # Hash the filename if it's too long a = self.hash_filename_if_too_long(__lowerCamelCase ,__lowerCamelCase ) # The path to the lock file. a = lock_file # The file descriptor for the *_lock_file* as it is returned by the # os.open() function. # This file lock is only NOT None, if the object currently holds the # lock. a = None # The default timeout value. a = timeout # We use this lock primarily for the lock counter. a = threading.Lock() # The lock counter is used for implementing the nested locking # mechanism. Whenever the lock is acquired, the counter is increased and # the lock is only released, when this value is 0 again. a = 0 return None @property def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ): '''simple docstring''' return self._lock_file @property def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ): '''simple docstring''' return self._timeout @timeout.setter def SCREAMING_SNAKE_CASE_ ( self : int ,__lowerCamelCase : Optional[Any] ): '''simple docstring''' a = float(__lowerCamelCase ) return None def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ): '''simple docstring''' raise NotImplementedError() def SCREAMING_SNAKE_CASE_ ( self : Tuple ): '''simple docstring''' raise NotImplementedError() @property def SCREAMING_SNAKE_CASE_ ( self : Tuple ): '''simple docstring''' return self._lock_file_fd is not None def SCREAMING_SNAKE_CASE_ ( self : Tuple ,__lowerCamelCase : Dict=None ,__lowerCamelCase : str=0.05 ): '''simple docstring''' if timeout is None: a = self.timeout # Increment the number right at the beginning. # We can still undo it, if something fails. with self._thread_lock: self._lock_counter += 1 a = id(self ) a = self._lock_file a = time.time() try: while True: with self._thread_lock: if not self.is_locked: logger().debug(F"""Attempting to acquire lock {lock_id} on {lock_filename}""" ) self._acquire() if self.is_locked: logger().debug(F"""Lock {lock_id} acquired on {lock_filename}""" ) break elif timeout >= 0 and time.time() - start_time > timeout: logger().debug(F"""Timeout on acquiring lock {lock_id} on {lock_filename}""" ) raise Timeout(self._lock_file ) else: logger().debug( F"""Lock {lock_id} not acquired on {lock_filename}, waiting {poll_intervall} seconds ...""" ) time.sleep(__lowerCamelCase ) except: # noqa # Something did go wrong, so decrement the counter. with self._thread_lock: a = max(0 ,self._lock_counter - 1 ) raise return _Acquire_ReturnProxy(lock=self ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ,__lowerCamelCase : int=False ): '''simple docstring''' with self._thread_lock: if self.is_locked: self._lock_counter -= 1 if self._lock_counter == 0 or force: a = id(self ) a = self._lock_file logger().debug(F"""Attempting to release lock {lock_id} on {lock_filename}""" ) self._release() a = 0 logger().debug(F"""Lock {lock_id} released on {lock_filename}""" ) return None def __enter__( self : Union[str, Any] ): '''simple docstring''' self.acquire() return self def __exit__( self : Optional[int] ,__lowerCamelCase : Union[str, Any] ,__lowerCamelCase : Union[str, Any] ,__lowerCamelCase : Union[str, Any] ): '''simple docstring''' self.release() return None def __del__( self : Dict ): '''simple docstring''' self.release(force=__lowerCamelCase ) return None def SCREAMING_SNAKE_CASE_ ( self : List[Any] ,__lowerCamelCase : str ,__lowerCamelCase : int ): '''simple docstring''' a = os.path.basename(__lowerCamelCase ) if len(__lowerCamelCase ) > max_length and max_length > 0: a = os.path.dirname(__lowerCamelCase ) a = str(hash(__lowerCamelCase ) ) a = filename[: max_length - len(__lowerCamelCase ) - 8] + '''...''' + hashed_filename + '''.lock''' return os.path.join(__lowerCamelCase ,__lowerCamelCase ) else: return path class lowerCamelCase_ ( a_ ): def __init__( self : Dict ,__lowerCamelCase : str ,__lowerCamelCase : Any=-1 ,__lowerCamelCase : Tuple=None ): '''simple docstring''' from .file_utils import relative_to_absolute_path super().__init__(__lowerCamelCase ,timeout=__lowerCamelCase ,max_filename_length=__lowerCamelCase ) a = '''\\\\?\\''' + relative_to_absolute_path(self.lock_file ) def SCREAMING_SNAKE_CASE_ ( self : str ): '''simple docstring''' a = os.O_RDWR | os.O_CREAT | os.O_TRUNC try: a = os.open(self._lock_file ,__lowerCamelCase ) except OSError: pass else: try: msvcrt.locking(__lowerCamelCase ,msvcrt.LK_NBLCK ,1 ) except OSError: os.close(__lowerCamelCase ) else: a = fd return None def SCREAMING_SNAKE_CASE_ ( self : List[str] ): '''simple docstring''' a = self._lock_file_fd a = None msvcrt.locking(__lowerCamelCase ,msvcrt.LK_UNLCK ,1 ) os.close(__lowerCamelCase ) try: os.remove(self._lock_file ) # Probably another instance of the application # that acquired the file lock. except OSError: pass return None class lowerCamelCase_ ( a_ ): def __init__( self : Dict ,__lowerCamelCase : str ,__lowerCamelCase : Tuple=-1 ,__lowerCamelCase : Tuple=None ): '''simple docstring''' a = os.statvfs(os.path.dirname(__lowerCamelCase ) ).f_namemax super().__init__(__lowerCamelCase ,timeout=__lowerCamelCase ,max_filename_length=__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ): '''simple docstring''' a = os.O_RDWR | os.O_CREAT | os.O_TRUNC a = os.open(self._lock_file ,__lowerCamelCase ) try: fcntl.flock(__lowerCamelCase ,fcntl.LOCK_EX | fcntl.LOCK_NB ) except OSError: os.close(__lowerCamelCase ) else: a = fd return None def SCREAMING_SNAKE_CASE_ ( self : str ): '''simple docstring''' a = self._lock_file_fd a = None fcntl.flock(__lowerCamelCase ,fcntl.LOCK_UN ) os.close(__lowerCamelCase ) return None class lowerCamelCase_ ( a_ ): def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ): '''simple docstring''' a = os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC try: a = os.open(self._lock_file ,__lowerCamelCase ) except OSError: pass else: a = fd return None def SCREAMING_SNAKE_CASE_ ( self : List[str] ): '''simple docstring''' os.close(self._lock_file_fd ) a = None try: os.remove(self._lock_file ) # The file is already deleted and that's what we want. except OSError: pass return None UpperCamelCase__ : Any = None if msvcrt: UpperCamelCase__ : Tuple = WindowsFileLock elif fcntl: UpperCamelCase__ : Any = UnixFileLock else: UpperCamelCase__ : Union[str, Any] = SoftFileLock if warnings is not None: warnings.warn("""only soft file lock is available""")
330
import argparse from typing import Dict import tensorflow as tf import torch from tqdm import tqdm from transformers import BigBirdPegasusConfig, BigBirdPegasusForConditionalGeneration UpperCamelCase__ : Any = [ # tf -> hf ("""/""", """."""), ("""layer_""", """layers."""), ("""kernel""", """weight"""), ("""beta""", """bias"""), ("""gamma""", """weight"""), ("""pegasus""", """model"""), ] UpperCamelCase__ : Optional[Any] = [ (""".output.dense""", """.fc2"""), ("""intermediate.LayerNorm""", """final_layer_norm"""), ("""intermediate.dense""", """fc1"""), ] UpperCamelCase__ : Optional[Any] = ( INIT_COMMON + [ ("""attention.self.LayerNorm""", """self_attn_layer_norm"""), ("""attention.output.dense""", """self_attn.out_proj"""), ("""attention.self""", """self_attn"""), ("""attention.encdec.LayerNorm""", """encoder_attn_layer_norm"""), ("""attention.encdec_output.dense""", """encoder_attn.out_proj"""), ("""attention.encdec""", """encoder_attn"""), ("""key""", """k_proj"""), ("""value""", """v_proj"""), ("""query""", """q_proj"""), ("""decoder.LayerNorm""", """decoder.layernorm_embedding"""), ] + END_COMMON ) UpperCamelCase__ : List[str] = ( INIT_COMMON + [ ("""embeddings.word_embeddings""", """shared.weight"""), ("""embeddings.position_embeddings""", """embed_positions.weight"""), ("""attention.self.LayerNorm""", """self_attn_layer_norm"""), ("""attention.output.dense""", """self_attn.output"""), ("""attention.self""", """self_attn.self"""), ("""encoder.LayerNorm""", """encoder.layernorm_embedding"""), ] + END_COMMON ) UpperCamelCase__ : Optional[int] = [ """encdec/key/bias""", """encdec/query/bias""", """encdec/value/bias""", """self/key/bias""", """self/query/bias""", """self/value/bias""", """encdec_output/dense/bias""", """attention/output/dense/bias""", ] def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> List[Any]: """simple docstring""" for tf_name, hf_name in patterns: a = k.replace(snake_case_, snake_case_ ) return k def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> BigBirdPegasusForConditionalGeneration: """simple docstring""" a = BigBirdPegasusConfig(**snake_case_ ) a = BigBirdPegasusForConditionalGeneration(snake_case_ ) a = torch_model.state_dict() a = {} # separating decoder weights a = {k: tf_weights[k] for k in tf_weights if k.startswith('''pegasus/decoder''' )} a = {k: tf_weights[k] for k in tf_weights if not k.startswith('''pegasus/decoder''' )} for k, v in tqdm(decoder_weights.items(), '''tf -> hf conversion''' ): a = [k.endswith(snake_case_ ) for ending in KEYS_TO_IGNORE] if any(snake_case_ ): continue a = DECODER_PATTERNS a = rename_state_dict_key(snake_case_, snake_case_ ) if new_k not in state_dict: raise ValueError(f"""could not find new key {new_k} in state dict. (converted from {k})""" ) if any(True if i in k else False for i in ['''dense''', '''query''', '''key''', '''value'''] ): a = v.T a = torch.from_numpy(snake_case_ ) assert v.shape == state_dict[new_k].shape, f"""{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}""" for k, v in tqdm(remaining_weights.items(), '''tf -> hf conversion''' ): a = [k.endswith(snake_case_ ) for ending in KEYS_TO_IGNORE] if any(snake_case_ ): continue a = REMAINING_PATTERNS a = rename_state_dict_key(snake_case_, snake_case_ ) if new_k not in state_dict and k != "pegasus/embeddings/position_embeddings": raise ValueError(f"""could not find new key {new_k} in state dict. (converted from {k})""" ) if any(True if i in k else False for i in ['''dense''', '''query''', '''key''', '''value'''] ): a = v.T a = torch.from_numpy(snake_case_ ) if k != "pegasus/embeddings/position_embeddings": assert v.shape == state_dict[new_k].shape, f"""{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}""" a = mapping['''model.embed_positions.weight'''] a = mapping.pop('''model.embed_positions.weight''' ) a , a = torch_model.load_state_dict(snake_case_, strict=snake_case_ ) a = [ k for k in missing if k not in [ '''final_logits_bias''', '''model.encoder.embed_tokens.weight''', '''model.decoder.embed_tokens.weight''', '''lm_head.weight''', ] ] assert unexpected_missing == [], f"""no matches found for the following torch keys {unexpected_missing}""" assert extra == [], f"""no matches found for the following tf keys {extra}""" return torch_model def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> Dict: """simple docstring""" a = tf.train.list_variables(snake_case_ ) a = {} a = ['''global_step'''] for name, shape in tqdm(snake_case_, desc='''converting tf checkpoint to dict''' ): a = any(pat in name for pat in ignore_name ) if skip_key: continue a = tf.train.load_variable(snake_case_, snake_case_ ) a = array return tf_weights def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_ ) -> int: """simple docstring""" a = get_tf_weights_as_numpy(snake_case_ ) a = convert_bigbird_pegasus(snake_case_, snake_case_ ) torch_model.save_pretrained(snake_case_ ) if __name__ == "__main__": UpperCamelCase__ : str = argparse.ArgumentParser() parser.add_argument("""--tf_ckpt_path""", type=str, help="""passed to tf.train.list_variables""") parser.add_argument("""--save_dir""", default=None, type=str, help="""Path to the output PyTorch model.""") UpperCamelCase__ : int = parser.parse_args() UpperCamelCase__ : Tuple = {} convert_bigbird_pegasus_ckpt_to_pytorch(args.tf_ckpt_path, args.save_dir, config_update=config_update)
330
1
from __future__ import annotations from typing import Generic, TypeVar UpperCamelCase__ : Dict = TypeVar("""T""") class lowerCamelCase_ ( Generic[T] ): def __init__( self : Dict ,__lowerCamelCase : T ): '''simple docstring''' a = data a = self a = 0 class lowerCamelCase_ ( Generic[T] ): def __init__( self : List[str] ): '''simple docstring''' a = {} def SCREAMING_SNAKE_CASE_ ( self : str ,__lowerCamelCase : T ): '''simple docstring''' a = DisjointSetTreeNode(__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ,__lowerCamelCase : T ): '''simple docstring''' a = self.map[data] if elem_ref != elem_ref.parent: a = self.find_set(elem_ref.parent.data ) return elem_ref.parent def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ,__lowerCamelCase : DisjointSetTreeNode[T] ,__lowerCamelCase : DisjointSetTreeNode[T] ): '''simple docstring''' if nodea.rank > nodea.rank: a = nodea else: a = nodea if nodea.rank == nodea.rank: nodea.rank += 1 def SCREAMING_SNAKE_CASE_ ( self : List[str] ,__lowerCamelCase : T ,__lowerCamelCase : T ): '''simple docstring''' self.link(self.find_set(__lowerCamelCase ) ,self.find_set(__lowerCamelCase ) ) class lowerCamelCase_ ( Generic[T] ): def __init__( self : Optional[int] ): '''simple docstring''' a = {} def SCREAMING_SNAKE_CASE_ ( self : Dict ,__lowerCamelCase : T ): '''simple docstring''' if node not in self.connections: a = {} def SCREAMING_SNAKE_CASE_ ( self : List[str] ,__lowerCamelCase : T ,__lowerCamelCase : T ,__lowerCamelCase : int ): '''simple docstring''' self.add_node(__lowerCamelCase ) self.add_node(__lowerCamelCase ) a = weight a = weight def SCREAMING_SNAKE_CASE_ ( self : int ): '''simple docstring''' a = [] a = set() for start in self.connections: for end in self.connections[start]: if (start, end) not in seen: seen.add((end, start) ) edges.append((start, end, self.connections[start][end]) ) edges.sort(key=lambda __lowerCamelCase : x[2] ) # creating the disjoint set a = DisjointSetTree[T]() for node in self.connections: disjoint_set.make_set(__lowerCamelCase ) # MST generation a = 0 a = 0 a = GraphUndirectedWeighted[T]() while num_edges < len(self.connections ) - 1: a , a , a = edges[index] index += 1 a = disjoint_set.find_set(__lowerCamelCase ) a = disjoint_set.find_set(__lowerCamelCase ) if parent_u != parent_v: num_edges += 1 graph.add_edge(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ) disjoint_set.union(__lowerCamelCase ,__lowerCamelCase ) return graph
330
import re def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> str: """simple docstring""" if len(re.findall('''[ATCG]''', snake_case_ ) ) != len(snake_case_ ): raise ValueError('''Invalid Strand''' ) return dna.translate(dna.maketrans('''ATCG''', '''TAGC''' ) ) if __name__ == "__main__": import doctest doctest.testmod()
330
1
import gc import unittest import numpy as np import torch import torch.nn.functional as F from transformers import ( ClapTextConfig, ClapTextModelWithProjection, RobertaTokenizer, SpeechTaHifiGan, SpeechTaHifiGanConfig, ) from diffusers import ( AudioLDMPipeline, AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.utils import is_xformers_available, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism from ..pipeline_params import TEXT_TO_AUDIO_BATCH_PARAMS, TEXT_TO_AUDIO_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class lowerCamelCase_ ( a_ , unittest.TestCase ): SCREAMING_SNAKE_CASE_ = AudioLDMPipeline SCREAMING_SNAKE_CASE_ = TEXT_TO_AUDIO_PARAMS SCREAMING_SNAKE_CASE_ = TEXT_TO_AUDIO_BATCH_PARAMS SCREAMING_SNAKE_CASE_ = frozenset( [ 'num_inference_steps', 'num_waveforms_per_prompt', 'generator', 'latents', 'output_type', 'return_dict', 'callback', 'callback_steps', ] ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ): '''simple docstring''' torch.manual_seed(0 ) a = UNetaDConditionModel( block_out_channels=(32, 64) ,layers_per_block=2 ,sample_size=32 ,in_channels=4 ,out_channels=4 ,down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') ,up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''') ,cross_attention_dim=(32, 64) ,class_embed_type='''simple_projection''' ,projection_class_embeddings_input_dim=32 ,class_embeddings_concat=__lowerCamelCase ,) a = DDIMScheduler( beta_start=0.00_085 ,beta_end=0.012 ,beta_schedule='''scaled_linear''' ,clip_sample=__lowerCamelCase ,set_alpha_to_one=__lowerCamelCase ,) torch.manual_seed(0 ) a = AutoencoderKL( block_out_channels=[32, 64] ,in_channels=1 ,out_channels=1 ,down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] ,up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] ,latent_channels=4 ,) torch.manual_seed(0 ) a = ClapTextConfig( 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 ,projection_dim=32 ,) a = ClapTextModelWithProjection(__lowerCamelCase ) a = RobertaTokenizer.from_pretrained('''hf-internal-testing/tiny-random-roberta''' ,model_max_length=77 ) a = SpeechTaHifiGanConfig( model_in_dim=8 ,sampling_rate=1_60_00 ,upsample_initial_channel=16 ,upsample_rates=[2, 2] ,upsample_kernel_sizes=[4, 4] ,resblock_kernel_sizes=[3, 7] ,resblock_dilation_sizes=[[1, 3, 5], [1, 3, 5]] ,normalize_before=__lowerCamelCase ,) a = SpeechTaHifiGan(__lowerCamelCase ) a = { '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''vocoder''': vocoder, } return components def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ,__lowerCamelCase : int ,__lowerCamelCase : Tuple=0 ): '''simple docstring''' if str(__lowerCamelCase ).startswith('''mps''' ): a = torch.manual_seed(__lowerCamelCase ) else: a = torch.Generator(device=__lowerCamelCase ).manual_seed(__lowerCamelCase ) a = { '''prompt''': '''A hammer hitting a wooden surface''', '''generator''': generator, '''num_inference_steps''': 2, '''guidance_scale''': 6.0, } return inputs def SCREAMING_SNAKE_CASE_ ( self : List[str] ): '''simple docstring''' a = '''cpu''' # ensure determinism for the device-dependent torch.Generator a = self.get_dummy_components() a = AudioLDMPipeline(**__lowerCamelCase ) a = audioldm_pipe.to(__lowerCamelCase ) audioldm_pipe.set_progress_bar_config(disable=__lowerCamelCase ) a = self.get_dummy_inputs(__lowerCamelCase ) a = audioldm_pipe(**__lowerCamelCase ) a = output.audios[0] assert audio.ndim == 1 assert len(__lowerCamelCase ) == 2_56 a = audio[:10] a = np.array( [-0.0_050, 0.0_050, -0.0_060, 0.0_033, -0.0_026, 0.0_033, -0.0_027, 0.0_033, -0.0_028, 0.0_033] ) assert np.abs(audio_slice - expected_slice ).max() < 1e-2 def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ): '''simple docstring''' a = self.get_dummy_components() a = AudioLDMPipeline(**__lowerCamelCase ) a = audioldm_pipe.to(__lowerCamelCase ) a = audioldm_pipe.to(__lowerCamelCase ) audioldm_pipe.set_progress_bar_config(disable=__lowerCamelCase ) a = self.get_dummy_inputs(__lowerCamelCase ) a = 3 * [inputs['''prompt''']] # forward a = audioldm_pipe(**__lowerCamelCase ) a = output.audios[0] a = self.get_dummy_inputs(__lowerCamelCase ) a = 3 * [inputs.pop('''prompt''' )] a = audioldm_pipe.tokenizer( __lowerCamelCase ,padding='''max_length''' ,max_length=audioldm_pipe.tokenizer.model_max_length ,truncation=__lowerCamelCase ,return_tensors='''pt''' ,) a = text_inputs['''input_ids'''].to(__lowerCamelCase ) a = audioldm_pipe.text_encoder( __lowerCamelCase ,) a = prompt_embeds.text_embeds # additional L_2 normalization over each hidden-state a = F.normalize(__lowerCamelCase ,dim=-1 ) a = prompt_embeds # forward a = audioldm_pipe(**__lowerCamelCase ) a = output.audios[0] assert np.abs(audio_a - audio_a ).max() < 1e-2 def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ): '''simple docstring''' a = self.get_dummy_components() a = AudioLDMPipeline(**__lowerCamelCase ) a = audioldm_pipe.to(__lowerCamelCase ) a = audioldm_pipe.to(__lowerCamelCase ) audioldm_pipe.set_progress_bar_config(disable=__lowerCamelCase ) a = self.get_dummy_inputs(__lowerCamelCase ) a = 3 * ['''this is a negative prompt'''] a = negative_prompt a = 3 * [inputs['''prompt''']] # forward a = audioldm_pipe(**__lowerCamelCase ) a = output.audios[0] a = self.get_dummy_inputs(__lowerCamelCase ) a = 3 * [inputs.pop('''prompt''' )] a = [] for p in [prompt, negative_prompt]: a = audioldm_pipe.tokenizer( __lowerCamelCase ,padding='''max_length''' ,max_length=audioldm_pipe.tokenizer.model_max_length ,truncation=__lowerCamelCase ,return_tensors='''pt''' ,) a = text_inputs['''input_ids'''].to(__lowerCamelCase ) a = audioldm_pipe.text_encoder( __lowerCamelCase ,) a = text_embeds.text_embeds # additional L_2 normalization over each hidden-state a = F.normalize(__lowerCamelCase ,dim=-1 ) embeds.append(__lowerCamelCase ) a , a = embeds # forward a = audioldm_pipe(**__lowerCamelCase ) a = output.audios[0] assert np.abs(audio_a - audio_a ).max() < 1e-2 def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ): '''simple docstring''' a = '''cpu''' # ensure determinism for the device-dependent torch.Generator a = self.get_dummy_components() a = PNDMScheduler(skip_prk_steps=__lowerCamelCase ) a = AudioLDMPipeline(**__lowerCamelCase ) a = audioldm_pipe.to(__lowerCamelCase ) audioldm_pipe.set_progress_bar_config(disable=__lowerCamelCase ) a = self.get_dummy_inputs(__lowerCamelCase ) a = '''egg cracking''' a = audioldm_pipe(**__lowerCamelCase ,negative_prompt=__lowerCamelCase ) a = output.audios[0] assert audio.ndim == 1 assert len(__lowerCamelCase ) == 2_56 a = audio[:10] a = np.array( [-0.0_051, 0.0_050, -0.0_060, 0.0_034, -0.0_026, 0.0_033, -0.0_027, 0.0_033, -0.0_028, 0.0_032] ) assert np.abs(audio_slice - expected_slice ).max() < 1e-2 def SCREAMING_SNAKE_CASE_ ( self : List[Any] ): '''simple docstring''' a = '''cpu''' # ensure determinism for the device-dependent torch.Generator a = self.get_dummy_components() a = PNDMScheduler(skip_prk_steps=__lowerCamelCase ) a = AudioLDMPipeline(**__lowerCamelCase ) a = audioldm_pipe.to(__lowerCamelCase ) audioldm_pipe.set_progress_bar_config(disable=__lowerCamelCase ) a = '''A hammer hitting a wooden surface''' # test num_waveforms_per_prompt=1 (default) a = audioldm_pipe(__lowerCamelCase ,num_inference_steps=2 ).audios assert audios.shape == (1, 2_56) # test num_waveforms_per_prompt=1 (default) for batch of prompts a = 2 a = audioldm_pipe([prompt] * batch_size ,num_inference_steps=2 ).audios assert audios.shape == (batch_size, 2_56) # test num_waveforms_per_prompt for single prompt a = 2 a = audioldm_pipe(__lowerCamelCase ,num_inference_steps=2 ,num_waveforms_per_prompt=__lowerCamelCase ).audios assert audios.shape == (num_waveforms_per_prompt, 2_56) # test num_waveforms_per_prompt for batch of prompts a = 2 a = audioldm_pipe( [prompt] * batch_size ,num_inference_steps=2 ,num_waveforms_per_prompt=__lowerCamelCase ).audios assert audios.shape == (batch_size * num_waveforms_per_prompt, 2_56) def SCREAMING_SNAKE_CASE_ ( self : Dict ): '''simple docstring''' a = '''cpu''' # ensure determinism for the device-dependent torch.Generator a = self.get_dummy_components() a = AudioLDMPipeline(**__lowerCamelCase ) a = audioldm_pipe.to(__lowerCamelCase ) audioldm_pipe.set_progress_bar_config(disable=__lowerCamelCase ) a = audioldm_pipe.vocoder.config.sampling_rate a = self.get_dummy_inputs(__lowerCamelCase ) a = audioldm_pipe(audio_length_in_s=0.016 ,**__lowerCamelCase ) a = output.audios[0] assert audio.ndim == 1 assert len(__lowerCamelCase ) / vocoder_sampling_rate == 0.016 a = audioldm_pipe(audio_length_in_s=0.032 ,**__lowerCamelCase ) a = output.audios[0] assert audio.ndim == 1 assert len(__lowerCamelCase ) / vocoder_sampling_rate == 0.032 def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ): '''simple docstring''' a = self.get_dummy_components() a = AudioLDMPipeline(**__lowerCamelCase ) a = audioldm_pipe.to(__lowerCamelCase ) audioldm_pipe.set_progress_bar_config(disable=__lowerCamelCase ) a = ['''hey'''] a = audioldm_pipe(__lowerCamelCase ,num_inference_steps=1 ) a = output.audios.shape assert audio_shape == (1, 2_56) a = audioldm_pipe.vocoder.config config.model_in_dim *= 2 a = SpeechTaHifiGan(__lowerCamelCase ).to(__lowerCamelCase ) a = audioldm_pipe(__lowerCamelCase ,num_inference_steps=1 ) a = output.audios.shape # waveform shape is unchanged, we just have 2x the number of mel channels in the spectrogram assert audio_shape == (1, 2_56) def SCREAMING_SNAKE_CASE_ ( self : Tuple ): '''simple docstring''' self._test_attention_slicing_forward_pass(test_mean_pixel_difference=__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : int ): '''simple docstring''' self._test_inference_batch_single_identical(test_mean_pixel_difference=__lowerCamelCase ) @unittest.skipIf( torch_device != '''cuda''' or not is_xformers_available() ,reason='''XFormers attention is only available with CUDA and `xformers` installed''' ,) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ): '''simple docstring''' self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=__lowerCamelCase ) @slow class lowerCamelCase_ ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self : int ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE_ ( self : Tuple ,__lowerCamelCase : Optional[Any] ,__lowerCamelCase : Union[str, Any]="cpu" ,__lowerCamelCase : Optional[Any]=torch.floataa ,__lowerCamelCase : Union[str, Any]=0 ): '''simple docstring''' a = torch.Generator(device=__lowerCamelCase ).manual_seed(__lowerCamelCase ) a = np.random.RandomState(__lowerCamelCase ).standard_normal((1, 8, 1_28, 16) ) a = torch.from_numpy(__lowerCamelCase ).to(device=__lowerCamelCase ,dtype=__lowerCamelCase ) a = { '''prompt''': '''A hammer hitting a wooden surface''', '''latents''': latents, '''generator''': generator, '''num_inference_steps''': 3, '''guidance_scale''': 2.5, } return inputs def SCREAMING_SNAKE_CASE_ ( self : Tuple ): '''simple docstring''' a = AudioLDMPipeline.from_pretrained('''cvssp/audioldm''' ) a = audioldm_pipe.to(__lowerCamelCase ) audioldm_pipe.set_progress_bar_config(disable=__lowerCamelCase ) a = self.get_inputs(__lowerCamelCase ) a = 25 a = audioldm_pipe(**__lowerCamelCase ).audios[0] assert audio.ndim == 1 assert len(__lowerCamelCase ) == 8_19_20 a = audio[7_72_30:7_72_40] a = np.array( [-0.4_884, -0.4_607, 0.0_023, 0.5_007, 0.5_896, 0.5_151, 0.3_813, -0.0_208, -0.3_687, -0.4_315] ) a = np.abs(expected_slice - audio_slice ).max() assert max_diff < 1e-2 def SCREAMING_SNAKE_CASE_ ( self : List[Any] ): '''simple docstring''' a = AudioLDMPipeline.from_pretrained('''cvssp/audioldm''' ) a = LMSDiscreteScheduler.from_config(audioldm_pipe.scheduler.config ) a = audioldm_pipe.to(__lowerCamelCase ) audioldm_pipe.set_progress_bar_config(disable=__lowerCamelCase ) a = self.get_inputs(__lowerCamelCase ) a = audioldm_pipe(**__lowerCamelCase ).audios[0] assert audio.ndim == 1 assert len(__lowerCamelCase ) == 8_19_20 a = audio[2_77_80:2_77_90] a = np.array([-0.2_131, -0.0_873, -0.0_124, -0.0_189, 0.0_569, 0.1_373, 0.1_883, 0.2_886, 0.3_297, 0.2_212] ) a = np.abs(expected_slice - audio_slice ).max() assert max_diff < 3e-2
330
from __future__ import annotations from collections.abc import Sequence from typing import Literal def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> str | Literal[False]: """simple docstring""" a = list(snake_case_ ) a = list(snake_case_ ) a = 0 for i in range(len(snake_case_ ) ): if lista[i] != lista[i]: count += 1 a = '''_''' if count > 1: return False else: return "".join(snake_case_ ) def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> list[str]: """simple docstring""" a = [] while True: a = ['''$'''] * len(snake_case_ ) a = [] for i in range(len(snake_case_ ) ): for j in range(i + 1, len(snake_case_ ) ): a = compare_string(binary[i], binary[j] ) if k is False: a = '''*''' a = '''*''' temp.append('''X''' ) for i in range(len(snake_case_ ) ): if checka[i] == "$": pi.append(binary[i] ) if len(snake_case_ ) == 0: return pi a = list(set(snake_case_ ) ) def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> list[str]: """simple docstring""" a = [] for minterm in minterms: a = '''''' for _ in range(snake_case_ ): a = str(minterm % 2 ) + string minterm //= 2 temp.append(snake_case_ ) return temp def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_ ) -> bool: """simple docstring""" a = list(snake_case_ ) a = list(snake_case_ ) a = 0 for i in range(len(snake_case_ ) ): if lista[i] != lista[i]: count_n += 1 return count_n == count def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> list[str]: """simple docstring""" a = [] a = [0] * len(snake_case_ ) for i in range(len(chart[0] ) ): a = 0 a = -1 for j in range(len(snake_case_ ) ): if chart[j][i] == 1: count += 1 a = j if count == 1: a = 1 for i in range(len(snake_case_ ) ): if select[i] == 1: for j in range(len(chart[0] ) ): if chart[i][j] == 1: for k in range(len(snake_case_ ) ): a = 0 temp.append(prime_implicants[i] ) while True: a = 0 a = -1 a = 0 for i in range(len(snake_case_ ) ): a = chart[i].count(1 ) if count_n > max_n: a = count_n a = i if max_n == 0: return temp temp.append(prime_implicants[rem] ) for i in range(len(chart[0] ) ): if chart[rem][i] == 1: for j in range(len(snake_case_ ) ): a = 0 def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> list[list[int]]: """simple docstring""" a = [[0 for x in range(len(snake_case_ ) )] for x in range(len(snake_case_ ) )] for i in range(len(snake_case_ ) ): a = prime_implicants[i].count('''_''' ) for j in range(len(snake_case_ ) ): if is_for_table(prime_implicants[i], binary[j], snake_case_ ): a = 1 return chart def SCREAMING_SNAKE_CASE__ ( ) -> None: """simple docstring""" a = int(input('''Enter the no. of variables\n''' ) ) a = [ float(snake_case_ ) for x in input( '''Enter the decimal representation of Minterms \'Spaces Separated\'\n''' ).split() ] a = decimal_to_binary(snake_case_, snake_case_ ) a = check(snake_case_ ) print('''Prime Implicants are:''' ) print(snake_case_ ) a = prime_implicant_chart(snake_case_, snake_case_ ) a = selection(snake_case_, snake_case_ ) print('''Essential Prime Implicants are:''' ) print(snake_case_ ) if __name__ == "__main__": import doctest doctest.testmod() main()
330
1
import unittest from datasets import load_dataset from transformers import BloomTokenizerFast from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowerCamelCase_ ( a_ , unittest.TestCase ): SCREAMING_SNAKE_CASE_ = None SCREAMING_SNAKE_CASE_ = BloomTokenizerFast SCREAMING_SNAKE_CASE_ = BloomTokenizerFast SCREAMING_SNAKE_CASE_ = True SCREAMING_SNAKE_CASE_ = False SCREAMING_SNAKE_CASE_ = 'tokenizer_file' SCREAMING_SNAKE_CASE_ = {'bos_token': '<s>', 'eos_token': '</s>', 'unk_token': '<unk>', 'pad_token': '<pad>'} def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ): '''simple docstring''' super().setUp() a = BloomTokenizerFast.from_pretrained('''bigscience/tokenizer''' ) tokenizer.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ,**__lowerCamelCase : Optional[int] ): '''simple docstring''' kwargs.update(self.special_tokens_map ) return BloomTokenizerFast.from_pretrained(self.tmpdirname ,**__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : Dict ): '''simple docstring''' a = self.get_rust_tokenizer() a = ['''The quick brown fox</s>''', '''jumps over the lazy dog</s>'''] a = [[21_75, 2_37_14, 7_31_73, 14_42_52, 2], [77, 13_26_19, 34_78, 3_68, 10_95_86, 3_54_33, 2]] a = tokenizer.batch_encode_plus(__lowerCamelCase )['''input_ids'''] self.assertListEqual(__lowerCamelCase ,__lowerCamelCase ) a = tokenizer.batch_decode(__lowerCamelCase ) self.assertListEqual(__lowerCamelCase ,__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ,__lowerCamelCase : Optional[Any]=6 ): '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): a = self.rust_tokenizer_class.from_pretrained(__lowerCamelCase ,**__lowerCamelCase ) # tokenizer_r.pad_token = None # Hotfixing padding = None # Simple input a = '''This is a simple input''' a = ['''This is a simple input 1''', '''This is a simple input 2'''] a = ('''This is a simple input''', '''This is a pair''') a = [ ('''This is a simple input 1''', '''This is a simple input 2'''), ('''This is a simple pair 1''', '''This is a simple pair 2'''), ] # Simple input tests try: tokenizer_r.encode(__lowerCamelCase ,max_length=__lowerCamelCase ) tokenizer_r.encode_plus(__lowerCamelCase ,max_length=__lowerCamelCase ) tokenizer_r.batch_encode_plus(__lowerCamelCase ,max_length=__lowerCamelCase ) tokenizer_r.encode(__lowerCamelCase ,max_length=__lowerCamelCase ) tokenizer_r.batch_encode_plus(__lowerCamelCase ,max_length=__lowerCamelCase ) except ValueError: self.fail('''Bloom Tokenizer should be able to deal with padding''' ) a = None # Hotfixing padding = None self.assertRaises(__lowerCamelCase ,tokenizer_r.encode ,__lowerCamelCase ,max_length=__lowerCamelCase ,padding='''max_length''' ) # Simple input self.assertRaises(__lowerCamelCase ,tokenizer_r.encode_plus ,__lowerCamelCase ,max_length=__lowerCamelCase ,padding='''max_length''' ) # Simple input self.assertRaises( __lowerCamelCase ,tokenizer_r.batch_encode_plus ,__lowerCamelCase ,max_length=__lowerCamelCase ,padding='''max_length''' ,) # Pair input self.assertRaises(__lowerCamelCase ,tokenizer_r.encode ,__lowerCamelCase ,max_length=__lowerCamelCase ,padding='''max_length''' ) # Pair input self.assertRaises(__lowerCamelCase ,tokenizer_r.encode_plus ,__lowerCamelCase ,max_length=__lowerCamelCase ,padding='''max_length''' ) # Pair input self.assertRaises( __lowerCamelCase ,tokenizer_r.batch_encode_plus ,__lowerCamelCase ,max_length=__lowerCamelCase ,padding='''max_length''' ,) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ): '''simple docstring''' a = self.get_rust_tokenizer() a = load_dataset('''xnli''' ,'''all_languages''' ,split='''test''' ,streaming=__lowerCamelCase ) a = next(iter(__lowerCamelCase ) )['''premise'''] # pick up one data a = list(sample_data.values() ) a = list(map(tokenizer.encode ,__lowerCamelCase ) ) a = [tokenizer.decode(__lowerCamelCase ,clean_up_tokenization_spaces=__lowerCamelCase ) for x in output_tokens] self.assertListEqual(__lowerCamelCase ,__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : str ): '''simple docstring''' self.assertGreaterEqual(len(self.tokenizer_class.pretrained_vocab_files_map ) ,1 ) self.assertGreaterEqual(len(list(self.tokenizer_class.pretrained_vocab_files_map.values() )[0] ) ,1 )
330
from typing import List, Union import numpy as np from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_DEPTH_ESTIMATION_MAPPING UpperCamelCase__ : List[str] = logging.get_logger(__name__) @add_end_docstrings(a_ ) class lowerCamelCase_ ( a_ ): def __init__( self : int ,*__lowerCamelCase : str ,**__lowerCamelCase : Optional[Any] ): '''simple docstring''' super().__init__(*__lowerCamelCase ,**__lowerCamelCase ) requires_backends(self ,'''vision''' ) self.check_model_type(__lowerCamelCase ) def __call__( self : int ,__lowerCamelCase : Union[str, List[str], "Image.Image", List["Image.Image"]] ,**__lowerCamelCase : str ): '''simple docstring''' return super().__call__(__lowerCamelCase ,**__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : Any ,**__lowerCamelCase : Dict ): '''simple docstring''' return {}, {}, {} def SCREAMING_SNAKE_CASE_ ( self : int ,__lowerCamelCase : Union[str, Any] ): '''simple docstring''' a = load_image(__lowerCamelCase ) a = image.size a = self.image_processor(images=__lowerCamelCase ,return_tensors=self.framework ) return model_inputs def SCREAMING_SNAKE_CASE_ ( self : str ,__lowerCamelCase : Union[str, Any] ): '''simple docstring''' a = self.model(**__lowerCamelCase ) return model_outputs def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ,__lowerCamelCase : Union[str, Any] ): '''simple docstring''' a = model_outputs.predicted_depth a = torch.nn.functional.interpolate( predicted_depth.unsqueeze(1 ) ,size=self.image_size[::-1] ,mode='''bicubic''' ,align_corners=__lowerCamelCase ) a = prediction.squeeze().cpu().numpy() a = (output * 2_55 / np.max(__lowerCamelCase )).astype('''uint8''' ) a = Image.fromarray(__lowerCamelCase ) a = {} a = predicted_depth a = depth return output_dict
330
1
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 lowerCamelCase_ ( unittest.TestCase ): def __init__( self : List[Any] ,__lowerCamelCase : Optional[Any] ,__lowerCamelCase : Union[str, Any]=3 ,__lowerCamelCase : List[str]=32 ,__lowerCamelCase : Any=3 ,__lowerCamelCase : Dict=10 ,__lowerCamelCase : Union[str, Any]=[10, 20, 30, 40] ,__lowerCamelCase : List[str]=[1, 1, 2, 1] ,__lowerCamelCase : List[Any]=True ,__lowerCamelCase : Tuple=True ,__lowerCamelCase : Any="relu" ,__lowerCamelCase : Optional[int]=3 ,__lowerCamelCase : Optional[int]=None ,): '''simple docstring''' a = parent a = batch_size a = image_size a = num_channels a = embeddings_size a = hidden_sizes a = depths a = is_training a = use_labels a = hidden_act a = num_labels a = scope a = len(__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ): '''simple docstring''' a = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) a = self.get_config() return config, pixel_values def SCREAMING_SNAKE_CASE_ ( self : Any ): '''simple docstring''' 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 SCREAMING_SNAKE_CASE_ ( self : Any ,__lowerCamelCase : Optional[Any] ,__lowerCamelCase : Optional[Any] ): '''simple docstring''' a = FlaxRegNetModel(config=__lowerCamelCase ) a = 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 SCREAMING_SNAKE_CASE_ ( self : Dict ,__lowerCamelCase : Optional[int] ,__lowerCamelCase : Any ): '''simple docstring''' a = self.num_labels a = FlaxRegNetForImageClassification(config=__lowerCamelCase ) a = model(__lowerCamelCase ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ): '''simple docstring''' a = self.prepare_config_and_inputs() a , a = config_and_inputs a = {'''pixel_values''': pixel_values} return config, inputs_dict @require_flax class lowerCamelCase_ ( a_ , unittest.TestCase ): SCREAMING_SNAKE_CASE_ = (FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else () SCREAMING_SNAKE_CASE_ = False SCREAMING_SNAKE_CASE_ = False SCREAMING_SNAKE_CASE_ = False def SCREAMING_SNAKE_CASE_ ( self : Dict ): '''simple docstring''' a = FlaxRegNetModelTester(self ) a = ConfigTester(self ,config_class=__lowerCamelCase ,has_text_modality=__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : int ): '''simple docstring''' 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 SCREAMING_SNAKE_CASE_ ( self : List[Any] ): '''simple docstring''' return def SCREAMING_SNAKE_CASE_ ( self : str ): '''simple docstring''' a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ): '''simple docstring''' a = 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 SCREAMING_SNAKE_CASE_ ( self : Any ): '''simple docstring''' pass @unittest.skip(reason='''RegNet does not support input and output embeddings''' ) def SCREAMING_SNAKE_CASE_ ( self : str ): '''simple docstring''' pass def SCREAMING_SNAKE_CASE_ ( self : List[Any] ): '''simple docstring''' a , a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a = model_class(__lowerCamelCase ) a = inspect.signature(model.__call__ ) # signature.parameters is an OrderedDict => so arg_names order is deterministic a = [*signature.parameters.keys()] a = ['''pixel_values'''] self.assertListEqual(arg_names[:1] ,__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : str ): '''simple docstring''' def check_hidden_states_output(__lowerCamelCase : int ,__lowerCamelCase : List[str] ,__lowerCamelCase : str ): a = model_class(__lowerCamelCase ) a = model(**self._prepare_for_class(__lowerCamelCase ,__lowerCamelCase ) ) a = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states a = self.model_tester.num_stages self.assertEqual(len(__lowerCamelCase ) ,expected_num_stages + 1 ) a , a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a = True check_hidden_states_output(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] a = True check_hidden_states_output(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self : Any ): '''simple docstring''' a , a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): a = self._prepare_for_class(__lowerCamelCase ,__lowerCamelCase ) a = model_class(__lowerCamelCase ) @jax.jit def model_jitted(__lowerCamelCase : Optional[Any] ,**__lowerCamelCase : int ): return model(pixel_values=__lowerCamelCase ,**__lowerCamelCase ) with self.subTest('''JIT Enabled''' ): a = model_jitted(**__lowerCamelCase ).to_tuple() with self.subTest('''JIT Disabled''' ): with jax.disable_jit(): a = 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 SCREAMING_SNAKE_CASE__ ( ) -> List[Any]: """simple docstring""" a = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_flax class lowerCamelCase_ ( unittest.TestCase ): @cached_property def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ): '''simple docstring''' return AutoImageProcessor.from_pretrained('''facebook/regnet-y-040''' ) if is_vision_available() else None @slow def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ): '''simple docstring''' a = FlaxRegNetForImageClassification.from_pretrained('''facebook/regnet-y-040''' ) a = self.default_image_processor a = prepare_img() a = image_processor(images=__lowerCamelCase ,return_tensors='''np''' ) a = model(**__lowerCamelCase ) # verify the logits a = (1, 10_00) self.assertEqual(outputs.logits.shape ,__lowerCamelCase ) a = jnp.array([-0.4_180, -1.5_051, -3.4_836] ) self.assertTrue(jnp.allclose(outputs.logits[0, :3] ,__lowerCamelCase ,atol=1e-4 ) )
330
from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Features, Value from .base import TaskTemplate @dataclass(frozen=a_ ) class lowerCamelCase_ ( a_ ): SCREAMING_SNAKE_CASE_ = field(default='language-modeling' , metadata={'include_in_asdict_even_if_is_default': True} ) SCREAMING_SNAKE_CASE_ = Features({'text': Value('string' )} ) SCREAMING_SNAKE_CASE_ = Features({} ) SCREAMING_SNAKE_CASE_ = "text" @property def SCREAMING_SNAKE_CASE_ ( self : int ): '''simple docstring''' return {self.text_column: "text"}
330
1