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
"""simple docstring""" import tempfile import unittest from transformers import SPIECE_UNDERLINE, BatchEncoding, PLBartTokenizer, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...test_tokenization_common import TokenizerTesterMixin __lowercase = get_tests_dir("""fixtures/test_sentencepiece.model""") if is_torch_available(): from transformers.models.plbart.modeling_plbart import shift_tokens_right __lowercase = 50003 __lowercase = 50002 @require_sentencepiece @require_tokenizers class _A ( _a ,unittest.TestCase ): """simple docstring""" UpperCAmelCase : int = PLBartTokenizer UpperCAmelCase : List[Any] = None UpperCAmelCase : str = False def __snake_case ( self : int): super().setUp() # We have a SentencePiece fixture for testing a : List[str] = PLBartTokenizer(__UpperCAmelCase , language_codes="base" , keep_accents=__UpperCAmelCase) tokenizer.save_pretrained(self.tmpdirname) def __snake_case ( self : List[str]): a : List[Any] = PLBartTokenizer(__UpperCAmelCase , language_codes="base" , keep_accents=__UpperCAmelCase) a : Tuple = tokenizer.tokenize("This is a test") self.assertListEqual(__UpperCAmelCase , ["▁This", "▁is", "▁a", "▁t", "est"]) self.assertListEqual( tokenizer.convert_tokens_to_ids(__UpperCAmelCase) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) a : Union[str, Any] = tokenizer.tokenize("I was born in 92000, and this is falsé.") self.assertListEqual( __UpperCAmelCase , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "é", ".", ] , ) a : Tuple = tokenizer.convert_tokens_to_ids(__UpperCAmelCase) self.assertListEqual( __UpperCAmelCase , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) a : Union[str, Any] = tokenizer.convert_ids_to_tokens(__UpperCAmelCase) self.assertListEqual( __UpperCAmelCase , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "<unk>", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "<unk>", ".", ] , ) a : List[str] = tokenizer.vocab_size a : Union[str, Any] = [tokenizer.convert_ids_to_tokens(__UpperCAmelCase) for x in range(end - 4 , __UpperCAmelCase)] self.assertListEqual(__UpperCAmelCase , ["__java__", "__python__", "__en_XX__", "<mask>"]) a : Union[str, Any] = "java.lang.Exception, python.lang.Exception, javascript, php, ruby, go" a : Tuple = tokenizer(__UpperCAmelCase).input_ids self.assertEqual( tokenizer.decode(__UpperCAmelCase , skip_special_tokens=__UpperCAmelCase , clean_up_tokenization_spaces=__UpperCAmelCase) , __UpperCAmelCase , ) def __snake_case ( self : int): a : Any = PLBartTokenizer(__UpperCAmelCase , language_codes="multi" , keep_accents=__UpperCAmelCase) a : Optional[int] = tokenizer.tokenize("This is a test") self.assertListEqual(__UpperCAmelCase , ["▁This", "▁is", "▁a", "▁t", "est"]) self.assertListEqual( tokenizer.convert_tokens_to_ids(__UpperCAmelCase) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) a : List[str] = tokenizer.tokenize("I was born in 92000, and this is falsé.") self.assertListEqual( __UpperCAmelCase , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "é", ".", ] , ) a : Optional[int] = tokenizer.convert_tokens_to_ids(__UpperCAmelCase) self.assertListEqual( __UpperCAmelCase , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) a : Dict = tokenizer.convert_ids_to_tokens(__UpperCAmelCase) self.assertListEqual( __UpperCAmelCase , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "<unk>", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "<unk>", ".", ] , ) a : Any = tokenizer.vocab_size a : Tuple = [tokenizer.convert_ids_to_tokens(__UpperCAmelCase) for x in range(end - 7 , __UpperCAmelCase)] self.assertListEqual( __UpperCAmelCase , ["__java__", "__python__", "__en_XX__", "__javascript__", "__php__", "__ruby__", "__go__"]) a : Dict = "java.lang.Exception, python.lang.Exception, javascript, php, ruby, go" a : Optional[Any] = tokenizer(__UpperCAmelCase).input_ids self.assertEqual( tokenizer.decode(__UpperCAmelCase , skip_special_tokens=__UpperCAmelCase , clean_up_tokenization_spaces=__UpperCAmelCase) , __UpperCAmelCase , ) @require_torch @require_sentencepiece @require_tokenizers class _A ( unittest.TestCase ): """simple docstring""" UpperCAmelCase : int = """uclanlp/plbart-python-en_XX""" UpperCAmelCase : Dict = [ """def maximum(a,b,c):NEW_LINE_INDENTreturn max([a,b,c])""", """def sum(a,b,c):NEW_LINE_INDENTreturn sum([a,b,c])""", ] UpperCAmelCase : Optional[Any] = [ """Returns the maximum value of a b c.""", """Sums the values of a b c.""", ] UpperCAmelCase : Dict = [ 1_3_4, 5_4_5_2, 3_3_4_6_0, 3_3_4_4_1, 3_3_4_6_3, 3_3_4_6_5, 3_3_4_6_3, 3_3_4_4_9, 9_8_8, 2_0, 3_3_4_5_6, 1_9, 3_3_4_5_6, 7_7_1, 3_9, 4_2_5_8, 8_8_9, 3_3_1_8, 3_3_4_4_1, 3_3_4_6_3, 3_3_4_6_5, 3_3_4_6_3, 3_3_4_4_9, 2_4_7_1, 2, PYTHON_CODE, ] @classmethod def __snake_case ( cls : Optional[Any]): a : PLBartTokenizer = PLBartTokenizer.from_pretrained( cls.checkpoint_name , language_codes="base" , src_lang="python" , tgt_lang="en_XX") a : Union[str, Any] = 1 return cls def __snake_case ( self : Any): self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["__java__"] , 50001) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["__python__"] , 50002) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["__en_XX__"] , 50003) def __snake_case ( self : List[Any]): a : Any = self.tokenizer.batch_encode_plus(self.src_text).input_ids[0] self.assertListEqual(self.expected_src_tokens , __UpperCAmelCase) def __snake_case ( self : Tuple): self.assertIn(__UpperCAmelCase , self.tokenizer.all_special_ids) a : Tuple = [EN_CODE, 9037, 33442, 57, 752, 153, 14, 56, 18, 9, 2] a : str = self.tokenizer.decode(__UpperCAmelCase , skip_special_tokens=__UpperCAmelCase) a : List[Any] = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=__UpperCAmelCase) self.assertEqual(__UpperCAmelCase , __UpperCAmelCase) self.assertNotIn(self.tokenizer.eos_token , __UpperCAmelCase) def __snake_case ( self : Any): a : Dict = ["def sum(a,b,c):NEW_LINE_INDENTreturn sum([a,b,c])" * 20] self.assertIsInstance(src_text[0] , __UpperCAmelCase) a : List[str] = 10 a : Union[str, Any] = self.tokenizer(__UpperCAmelCase , max_length=__UpperCAmelCase , truncation=__UpperCAmelCase).input_ids[0] self.assertEqual(ids[-2] , 2) self.assertEqual(ids[-1] , __UpperCAmelCase) self.assertEqual(len(__UpperCAmelCase) , __UpperCAmelCase) def __snake_case ( self : int): self.assertListEqual(self.tokenizer.convert_tokens_to_ids(["<mask>", "__java__"]) , [50004, 50001]) def __snake_case ( self : Optional[int]): a : Union[str, Any] = tempfile.mkdtemp() a : Dict = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(__UpperCAmelCase) a : Optional[int] = PLBartTokenizer.from_pretrained(__UpperCAmelCase) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , __UpperCAmelCase) @require_torch def __snake_case ( self : Tuple): a : Optional[int] = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=__UpperCAmelCase , return_tensors="pt") a : Optional[int] = shift_tokens_right(batch["labels"] , self.tokenizer.pad_token_id) # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 self.assertEqual(batch.input_ids[1][-2:].tolist() , [2, PYTHON_CODE]) self.assertEqual(batch.decoder_input_ids[1][0] , __UpperCAmelCase) self.assertEqual(batch.decoder_input_ids[1][-1] , 2) self.assertEqual(batch.labels[1][-2:].tolist() , [2, EN_CODE]) @require_torch def __snake_case ( self : Optional[Any]): a : Union[str, Any] = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=__UpperCAmelCase , truncation=__UpperCAmelCase , max_length=len(self.expected_src_tokens) , return_tensors="pt" , ) a : Tuple = shift_tokens_right(batch["labels"] , self.tokenizer.pad_token_id) self.assertIsInstance(__UpperCAmelCase , __UpperCAmelCase) self.assertEqual((2, 26) , batch.input_ids.shape) self.assertEqual((2, 26) , batch.attention_mask.shape) a : List[str] = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , __UpperCAmelCase) self.assertEqual(2 , batch.decoder_input_ids[0, -1]) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , []) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id, PYTHON_CODE]) def __snake_case ( self : str): a : Tuple = self.tokenizer(self.src_text , padding=__UpperCAmelCase , truncation=__UpperCAmelCase , max_length=3 , return_tensors="pt") a : Optional[Any] = self.tokenizer( text_target=self.tgt_text , padding=__UpperCAmelCase , truncation=__UpperCAmelCase , max_length=10 , return_tensors="pt") a : Dict = targets["input_ids"] a : str = shift_tokens_right(__UpperCAmelCase , self.tokenizer.pad_token_id) self.assertEqual(batch.input_ids.shape[1] , 3) self.assertEqual(batch.decoder_input_ids.shape[1] , 10) @require_torch def __snake_case ( self : Dict): a : Optional[int] = self.tokenizer._build_translation_inputs( "A test" , return_tensors="pt" , src_lang="en_XX" , tgt_lang="java") self.assertEqual( nested_simplify(__UpperCAmelCase) , { # A, test, EOS, en_XX "input_ids": [[150, 242, 2, 50003]], "attention_mask": [[1, 1, 1, 1]], # java "forced_bos_token_id": 50001, } , )
40
"""simple docstring""" import itertools from dataclasses import dataclass from typing import List, Optional import pyarrow as pa import pyarrow.parquet as pq import datasets from datasets.table import table_cast __lowercase = datasets.utils.logging.get_logger(__name__) @dataclass class _A ( datasets.BuilderConfig ): """simple docstring""" UpperCAmelCase : int = 1_0_0_0_0 UpperCAmelCase : Optional[List[str]] = None UpperCAmelCase : Optional[datasets.Features] = None class _A ( datasets.ArrowBasedBuilder ): """simple docstring""" UpperCAmelCase : str = ParquetConfig def __snake_case ( self : Tuple): return datasets.DatasetInfo(features=self.config.features) def __snake_case ( self : List[Any] , __UpperCAmelCase : str): if not self.config.data_files: raise ValueError(f'''At least one data file must be specified, but got data_files={self.config.data_files}''') a : str = dl_manager.download_and_extract(self.config.data_files) if isinstance(__UpperCAmelCase , (str, list, tuple)): a : Dict = data_files if isinstance(__UpperCAmelCase , __UpperCAmelCase): a : str = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive a : List[Any] = [dl_manager.iter_files(__UpperCAmelCase) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"files": files})] a : Dict = [] for split_name, files in data_files.items(): if isinstance(__UpperCAmelCase , __UpperCAmelCase): a : Optional[int] = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive a : Tuple = [dl_manager.iter_files(__UpperCAmelCase) for file in files] # Infer features is they are stoed in the arrow schema if self.info.features is None: for file in itertools.chain.from_iterable(__UpperCAmelCase): with open(__UpperCAmelCase , "rb") as f: a : Tuple = datasets.Features.from_arrow_schema(pq.read_schema(__UpperCAmelCase)) break splits.append(datasets.SplitGenerator(name=__UpperCAmelCase , gen_kwargs={"files": files})) return splits def __snake_case ( self : List[str] , __UpperCAmelCase : pa.Table): if self.info.features is not None: # more expensive cast to support nested features with keys in a different order # allows str <-> int/float or str to Audio for example a : Optional[int] = table_cast(__UpperCAmelCase , self.info.features.arrow_schema) return pa_table def __snake_case ( self : Union[str, Any] , __UpperCAmelCase : int): a : Tuple = self.info.features.arrow_schema if self.info.features is not None else None if self.info.features is not None and self.config.columns is not None: if sorted(field.name for field in schema) != sorted(self.config.columns): raise ValueError( f'''Tried to load parquet data with columns \'{self.config.columns}\' with mismatching features \'{self.info.features}\'''') for file_idx, file in enumerate(itertools.chain.from_iterable(__UpperCAmelCase)): with open(__UpperCAmelCase , "rb") as f: a : Tuple = pq.ParquetFile(__UpperCAmelCase) try: for batch_idx, record_batch in enumerate( parquet_file.iter_batches(batch_size=self.config.batch_size , columns=self.config.columns)): a : Optional[Any] = pa.Table.from_batches([record_batch]) # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield f'''{file_idx}_{batch_idx}''', self._cast_table(__UpperCAmelCase) except ValueError as e: logger.error(f'''Failed to read file \'{file}\' with error {type(__UpperCAmelCase)}: {e}''') raise
40
1
'''simple docstring''' from __future__ import annotations __lowercase: int = list[list[int]] # assigning initial values to the grid __lowercase: Matrix = [ [3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] # a grid with no solution __lowercase: Matrix = [ [5, 0, 6, 5, 0, 8, 4, 0, 3], [5, 2, 0, 0, 0, 0, 0, 0, 2], [1, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] def SCREAMING_SNAKE_CASE__( _UpperCamelCase : Matrix , _UpperCamelCase : int , _UpperCamelCase : int , _UpperCamelCase : int ) -> bool: '''simple docstring''' for i in range(9 ): if grid[row][i] == n or grid[i][column] == n: return False for i in range(3 ): for j in range(3 ): if grid[(row - row % 3) + i][(column - column % 3) + j] == n: return False return True def SCREAMING_SNAKE_CASE__( _UpperCamelCase : Matrix ) -> tuple[int, int] | None: '''simple docstring''' for i in range(9 ): for j in range(9 ): if grid[i][j] == 0: return i, j return None def SCREAMING_SNAKE_CASE__( _UpperCamelCase : Matrix ) -> Matrix | None: '''simple docstring''' if location := find_empty_location(_UpperCamelCase ): UpperCamelCase__ , UpperCamelCase__ = location else: # If the location is ``None``, then the grid is solved. return grid for digit in range(1 , 10 ): if is_safe(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): UpperCamelCase__ = digit if sudoku(_UpperCamelCase ) is not None: return grid UpperCamelCase__ = 0 return None def SCREAMING_SNAKE_CASE__( _UpperCamelCase : Matrix ) -> None: '''simple docstring''' for row in grid: for cell in row: print(_UpperCamelCase , end=" " ) print() if __name__ == "__main__": # make a copy of grid so that you can compare with the unmodified grid for example_grid in (initial_grid, no_solution): print("\nExample grid:\n" + "=" * 20) print_solution(example_grid) print("\nExample grid solution:") __lowercase: List[str] = sudoku(example_grid) if solution is not None: print_solution(solution) else: print("Cannot find a solution.")
31
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __lowercase: Dict = { "configuration_time_series_transformer": [ "TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "TimeSeriesTransformerConfig", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase: Optional[int] = [ "TIME_SERIES_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TimeSeriesTransformerForPrediction", "TimeSeriesTransformerModel", "TimeSeriesTransformerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_time_series_transformer import ( TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TimeSeriesTransformerConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_time_series_transformer import ( TIME_SERIES_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TimeSeriesTransformerForPrediction, TimeSeriesTransformerModel, TimeSeriesTransformerPreTrainedModel, ) else: import sys __lowercase: Any = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
31
1
'''simple docstring''' import os import tempfile import unittest from transformers.models.marian.convert_marian_tatoeba_to_pytorch import DEFAULT_REPO, TatoebaConverter from transformers.testing_utils import slow from transformers.utils import cached_property @unittest.skipUnless(os.path.exists(_lowerCamelCase ) , """Tatoeba directory does not exist.""" ) class __UpperCAmelCase ( unittest.TestCase ): @cached_property def lowerCamelCase ( self ): """simple docstring""" _snake_case = tempfile.mkdtemp() return TatoebaConverter(save_dir=lowerCAmelCase_ ) @slow def lowerCamelCase ( self ): """simple docstring""" self.resolver.convert_models(['heb-eng'] ) @slow def lowerCamelCase ( self ): """simple docstring""" _snake_case , _snake_case = self.resolver.write_model_card('opus-mt-he-en' , dry_run=lowerCAmelCase_ ) assert mmeta["long_pair"] == "heb-eng"
42
"""simple docstring""" from __future__ import annotations from collections import namedtuple from dataclasses import dataclass @dataclass class SCREAMING_SNAKE_CASE__ : """simple docstring""" a : int a : TreeNode | None =None a : TreeNode | None =None lowerCAmelCase__ = namedtuple('''CoinsDistribResult''', '''moves excess''') def a__ ( SCREAMING_SNAKE_CASE : TreeNode | None ): '''simple docstring''' if root is None: return 0 # Validation def count_nodes(SCREAMING_SNAKE_CASE : TreeNode | None ) -> int: if node is None: return 0 return count_nodes(node.left ) + count_nodes(node.right ) + 1 def count_coins(SCREAMING_SNAKE_CASE : TreeNode | None ) -> int: if node is None: return 0 return count_coins(node.left ) + count_coins(node.right ) + node.data if count_nodes(SCREAMING_SNAKE_CASE ) != count_coins(SCREAMING_SNAKE_CASE ): raise ValueError("The nodes number should be same as the number of coins" ) # Main calculation def get_distrib(SCREAMING_SNAKE_CASE : TreeNode | None ) -> CoinsDistribResult: if node is None: return CoinsDistribResult(0 , 1 ) lowerCAmelCase , lowerCAmelCase : List[str] = get_distrib(node.left ) lowerCAmelCase , lowerCAmelCase : List[str] = get_distrib(node.right ) lowerCAmelCase : Union[str, Any] = 1 - left_distrib_excess lowerCAmelCase : List[Any] = 1 - right_distrib_excess lowerCAmelCase : int = ( left_distrib_moves + right_distrib_moves + abs(SCREAMING_SNAKE_CASE ) + abs(SCREAMING_SNAKE_CASE ) ) lowerCAmelCase : int = node.data - coins_to_left - coins_to_right return CoinsDistribResult(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) return get_distrib(SCREAMING_SNAKE_CASE )[0] if __name__ == "__main__": import doctest doctest.testmod()
108
0
import argparse import requests import torch from PIL import Image from transformers import ViTMAEConfig, ViTMAEForPreTraining, ViTMAEImageProcessor def lowerCamelCase ( a_ ) -> Tuple: if "cls_token" in name: lowerCAmelCase_ = name.replace('cls_token' , 'vit.embeddings.cls_token' ) if "mask_token" in name: lowerCAmelCase_ = name.replace('mask_token' , 'decoder.mask_token' ) if "decoder_pos_embed" in name: lowerCAmelCase_ = name.replace('decoder_pos_embed' , 'decoder.decoder_pos_embed' ) if "pos_embed" in name and "decoder" not in name: lowerCAmelCase_ = name.replace('pos_embed' , 'vit.embeddings.position_embeddings' ) if "patch_embed.proj" in name: lowerCAmelCase_ = name.replace('patch_embed.proj' , 'vit.embeddings.patch_embeddings.projection' ) if "patch_embed.norm" in name: lowerCAmelCase_ = name.replace('patch_embed.norm' , 'vit.embeddings.norm' ) if "decoder_blocks" in name: lowerCAmelCase_ = name.replace('decoder_blocks' , 'decoder.decoder_layers' ) if "blocks" in name: lowerCAmelCase_ = name.replace('blocks' , 'vit.encoder.layer' ) if "attn.proj" in name: lowerCAmelCase_ = name.replace('attn.proj' , 'attention.output.dense' ) if "attn" in name: lowerCAmelCase_ = name.replace('attn' , 'attention.self' ) if "norm1" in name: lowerCAmelCase_ = name.replace('norm1' , 'layernorm_before' ) if "norm2" in name: lowerCAmelCase_ = name.replace('norm2' , 'layernorm_after' ) if "mlp.fc1" in name: lowerCAmelCase_ = name.replace('mlp.fc1' , 'intermediate.dense' ) if "mlp.fc2" in name: lowerCAmelCase_ = name.replace('mlp.fc2' , 'output.dense' ) if "decoder_embed" in name: lowerCAmelCase_ = name.replace('decoder_embed' , 'decoder.decoder_embed' ) if "decoder_norm" in name: lowerCAmelCase_ = name.replace('decoder_norm' , 'decoder.decoder_norm' ) if "decoder_pred" in name: lowerCAmelCase_ = name.replace('decoder_pred' , 'decoder.decoder_pred' ) if "norm.weight" in name and "decoder" not in name: lowerCAmelCase_ = name.replace('norm.weight' , 'vit.layernorm.weight' ) if "norm.bias" in name and "decoder" not in name: lowerCAmelCase_ = name.replace('norm.bias' , 'vit.layernorm.bias' ) return name def lowerCamelCase ( a_ , a_ ) -> Dict: for key in orig_state_dict.copy().keys(): lowerCAmelCase_ = orig_state_dict.pop(_UpperCAmelCase ) if "qkv" in key: lowerCAmelCase_ = key.split('.' ) lowerCAmelCase_ = int(key_split[1] ) if "decoder_blocks" in key: lowerCAmelCase_ = config.decoder_hidden_size lowerCAmelCase_ = "decoder.decoder_layers." if "weight" in key: lowerCAmelCase_ = val[:dim, :] lowerCAmelCase_ = val[dim : dim * 2, :] lowerCAmelCase_ = val[-dim:, :] elif "bias" in key: lowerCAmelCase_ = val[:dim] lowerCAmelCase_ = val[dim : dim * 2] lowerCAmelCase_ = val[-dim:] else: lowerCAmelCase_ = config.hidden_size lowerCAmelCase_ = "vit.encoder.layer." if "weight" in key: lowerCAmelCase_ = val[:dim, :] lowerCAmelCase_ = val[dim : dim * 2, :] lowerCAmelCase_ = val[-dim:, :] elif "bias" in key: lowerCAmelCase_ = val[:dim] lowerCAmelCase_ = val[dim : dim * 2] lowerCAmelCase_ = val[-dim:] else: lowerCAmelCase_ = val return orig_state_dict def lowerCamelCase ( a_ , a_ ) -> List[str]: lowerCAmelCase_ = ViTMAEConfig() if "large" in checkpoint_url: lowerCAmelCase_ = 1_024 lowerCAmelCase_ = 4_096 lowerCAmelCase_ = 24 lowerCAmelCase_ = 16 elif "huge" in checkpoint_url: lowerCAmelCase_ = 14 lowerCAmelCase_ = 1_280 lowerCAmelCase_ = 5_120 lowerCAmelCase_ = 32 lowerCAmelCase_ = 16 lowerCAmelCase_ = ViTMAEForPreTraining(_UpperCAmelCase ) lowerCAmelCase_ = torch.hub.load_state_dict_from_url(_UpperCAmelCase , map_location='cpu' )["model"] lowerCAmelCase_ = ViTMAEImageProcessor(size=config.image_size ) lowerCAmelCase_ = convert_state_dict(_UpperCAmelCase , _UpperCAmelCase ) model.load_state_dict(_UpperCAmelCase ) model.eval() lowerCAmelCase_ = "https://user-images.githubusercontent.com/11435359/147738734-196fd92f-9260-48d5-ba7e-bf103d29364d.jpg" lowerCAmelCase_ = Image.open(requests.get(_UpperCAmelCase , stream=_UpperCAmelCase ).raw ) lowerCAmelCase_ = ViTMAEImageProcessor(size=config.image_size ) lowerCAmelCase_ = image_processor(images=_UpperCAmelCase , return_tensors='pt' ) # forward pass torch.manual_seed(2 ) lowerCAmelCase_ = model(**_UpperCAmelCase ) lowerCAmelCase_ = outputs.logits if "large" in checkpoint_url: lowerCAmelCase_ = torch.tensor( [[-0.7_309, -0.7_128, -1.0_169], [-1.0_161, -0.9_058, -1.1_878], [-1.0_478, -0.9_411, -1.1_911]] ) elif "huge" in checkpoint_url: lowerCAmelCase_ = torch.tensor( [[-1.1_599, -0.9_199, -1.2_221], [-1.1_952, -0.9_269, -1.2_307], [-1.2_143, -0.9_337, -1.2_262]] ) else: lowerCAmelCase_ = torch.tensor( [[-0.9_192, -0.8_481, -1.1_259], [-1.1_349, -1.0_034, -1.2_599], [-1.1_757, -1.0_429, -1.2_726]] ) # verify logits assert torch.allclose(logits[0, :3, :3] , _UpperCAmelCase , atol=1e-4 ) print(F'''Saving model to {pytorch_dump_folder_path}''' ) model.save_pretrained(_UpperCAmelCase ) print(F'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(_UpperCAmelCase ) if __name__ == "__main__": lowerCamelCase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( """--checkpoint_url""", default="""https://dl.fbaipublicfiles.com/mae/visualize/mae_visualize_vit_base.pth""", type=str, help="""URL of the checkpoint you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) lowerCamelCase_ = parser.parse_args() convert_vit_mae_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
364
import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class a_ ( a_ , a_ , a_ , unittest.TestCase ): '''simple docstring''' __a: int = StableDiffusionInpaintPipeline __a: int = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS __a: Tuple = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS __a: int = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess __a: List[str] = frozenset([] ) def _lowercase ( self ) -> Dict: '''simple docstring''' torch.manual_seed(0 ) lowerCAmelCase_ = UNetaDConditionModel( block_out_channels=(3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=9 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=3_2 , attention_head_dim=(2, 4) , use_linear_projection=lowercase_ , ) lowerCAmelCase_ = PNDMScheduler(skip_prk_steps=lowercase_ ) torch.manual_seed(0 ) lowerCAmelCase_ = AutoencoderKL( block_out_channels=[3_2, 6_4] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , sample_size=1_2_8 , ) torch.manual_seed(0 ) lowerCAmelCase_ = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=3_2 , intermediate_size=3_7 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , hidden_act='gelu' , projection_dim=5_1_2 , ) lowerCAmelCase_ = CLIPTextModel(lowercase_ ) lowerCAmelCase_ = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) lowerCAmelCase_ = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def _lowercase ( self , lowercase_ , lowercase_=0 ) -> int: '''simple docstring''' lowerCAmelCase_ = floats_tensor((1, 3, 3_2, 3_2) , rng=random.Random(lowercase_ ) ).to(lowercase_ ) lowerCAmelCase_ = image.cpu().permute(0 , 2 , 3 , 1 )[0] lowerCAmelCase_ = Image.fromarray(np.uinta(lowercase_ ) ).convert('RGB' ).resize((6_4, 6_4) ) lowerCAmelCase_ = Image.fromarray(np.uinta(image + 4 ) ).convert('RGB' ).resize((6_4, 6_4) ) if str(lowercase_ ).startswith('mps' ): lowerCAmelCase_ = torch.manual_seed(lowercase_ ) else: lowerCAmelCase_ = torch.Generator(device=lowercase_ ).manual_seed(lowercase_ ) lowerCAmelCase_ = { 'prompt': 'A painting of a squirrel eating a burger', 'image': init_image, 'mask_image': mask_image, 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 6.0, 'output_type': 'numpy', } return inputs def _lowercase ( self ) -> str: '''simple docstring''' lowerCAmelCase_ = 'cpu' # ensure determinism for the device-dependent torch.Generator lowerCAmelCase_ = self.get_dummy_components() lowerCAmelCase_ = StableDiffusionInpaintPipeline(**lowercase_ ) lowerCAmelCase_ = sd_pipe.to(lowercase_ ) sd_pipe.set_progress_bar_config(disable=lowercase_ ) lowerCAmelCase_ = self.get_dummy_inputs(lowercase_ ) lowerCAmelCase_ = sd_pipe(**lowercase_ ).images lowerCAmelCase_ = image[0, -3:, -3:, -1] assert image.shape == (1, 6_4, 6_4, 3) lowerCAmelCase_ = np.array([0.47_27, 0.57_35, 0.39_41, 0.54_46, 0.59_26, 0.43_94, 0.50_62, 0.46_54, 0.44_76] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def _lowercase ( self ) -> Any: '''simple docstring''' super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class a_ ( unittest.TestCase ): '''simple docstring''' def _lowercase ( self ) -> Tuple: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def _lowercase ( self ) -> Optional[Any]: '''simple docstring''' lowerCAmelCase_ = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/sd2-inpaint/init_image.png' ) lowerCAmelCase_ = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png' ) lowerCAmelCase_ = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint' '/yellow_cat_sitting_on_a_park_bench.npy' ) lowerCAmelCase_ = 'stabilityai/stable-diffusion-2-inpainting' lowerCAmelCase_ = StableDiffusionInpaintPipeline.from_pretrained(lowercase_ , safety_checker=lowercase_ ) pipe.to(lowercase_ ) pipe.set_progress_bar_config(disable=lowercase_ ) pipe.enable_attention_slicing() lowerCAmelCase_ = 'Face of a yellow cat, high resolution, sitting on a park bench' lowerCAmelCase_ = torch.manual_seed(0 ) lowerCAmelCase_ = pipe( prompt=lowercase_ , image=lowercase_ , mask_image=lowercase_ , generator=lowercase_ , output_type='np' , ) lowerCAmelCase_ = output.images[0] assert image.shape == (5_1_2, 5_1_2, 3) assert np.abs(expected_image - image ).max() < 9e-3 def _lowercase ( self ) -> Union[str, Any]: '''simple docstring''' lowerCAmelCase_ = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/sd2-inpaint/init_image.png' ) lowerCAmelCase_ = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png' ) lowerCAmelCase_ = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint' '/yellow_cat_sitting_on_a_park_bench_fp16.npy' ) lowerCAmelCase_ = 'stabilityai/stable-diffusion-2-inpainting' lowerCAmelCase_ = StableDiffusionInpaintPipeline.from_pretrained( lowercase_ , torch_dtype=torch.floataa , safety_checker=lowercase_ , ) pipe.to(lowercase_ ) pipe.set_progress_bar_config(disable=lowercase_ ) pipe.enable_attention_slicing() lowerCAmelCase_ = 'Face of a yellow cat, high resolution, sitting on a park bench' lowerCAmelCase_ = torch.manual_seed(0 ) lowerCAmelCase_ = pipe( prompt=lowercase_ , image=lowercase_ , mask_image=lowercase_ , generator=lowercase_ , output_type='np' , ) lowerCAmelCase_ = output.images[0] assert image.shape == (5_1_2, 5_1_2, 3) assert np.abs(expected_image - image ).max() < 5e-1 def _lowercase ( self ) -> List[str]: '''simple docstring''' torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() lowerCAmelCase_ = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/sd2-inpaint/init_image.png' ) lowerCAmelCase_ = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png' ) lowerCAmelCase_ = 'stabilityai/stable-diffusion-2-inpainting' lowerCAmelCase_ = PNDMScheduler.from_pretrained(lowercase_ , subfolder='scheduler' ) lowerCAmelCase_ = StableDiffusionInpaintPipeline.from_pretrained( lowercase_ , safety_checker=lowercase_ , scheduler=lowercase_ , torch_dtype=torch.floataa , ) pipe.to(lowercase_ ) pipe.set_progress_bar_config(disable=lowercase_ ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() lowerCAmelCase_ = 'Face of a yellow cat, high resolution, sitting on a park bench' lowerCAmelCase_ = torch.manual_seed(0 ) lowerCAmelCase_ = pipe( prompt=lowercase_ , image=lowercase_ , mask_image=lowercase_ , generator=lowercase_ , num_inference_steps=2 , output_type='np' , ) lowerCAmelCase_ = torch.cuda.max_memory_allocated() # make sure that less than 2.65 GB is allocated assert mem_bytes < 2.65 * 1_0**9
14
0
def SCREAMING_SNAKE_CASE_ ( __A : int ) -> int: """simple docstring""" if not isinstance(__A , __A ): raise TypeError('only integers accepted as input' ) else: a_ : Union[str, Any] = str(abs(__A ) ) a_ : Optional[int] = [list(__A ) for char in range(len(__A ) )] for index in range(len(__A ) ): num_transpositions[index].pop(__A ) return max( int(''.join(list(__A ) ) ) for transposition in num_transpositions ) if __name__ == "__main__": __import__('doctest').testmod()
32
import unittest from transformers import LiltConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, ) from transformers.models.lilt.modeling_lilt import LILT_PRETRAINED_MODEL_ARCHIVE_LIST class SCREAMING_SNAKE_CASE__ : def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : str=1_3 , SCREAMING_SNAKE_CASE__ : Optional[int]=7 , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : int=True , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : str=9_9 , SCREAMING_SNAKE_CASE__ : str=2_4 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=2 , SCREAMING_SNAKE_CASE__ : Optional[Any]=6 , SCREAMING_SNAKE_CASE__ : Optional[int]=3_7 , SCREAMING_SNAKE_CASE__ : List[Any]="gelu" , SCREAMING_SNAKE_CASE__ : str=0.1 , SCREAMING_SNAKE_CASE__ : List[Any]=0.1 , SCREAMING_SNAKE_CASE__ : List[str]=5_1_2 , SCREAMING_SNAKE_CASE__ : List[str]=1_6 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=2 , SCREAMING_SNAKE_CASE__ : int=0.02 , SCREAMING_SNAKE_CASE__ : Optional[Any]=3 , SCREAMING_SNAKE_CASE__ : Optional[int]=None , SCREAMING_SNAKE_CASE__ : Tuple=1_0_0_0 , ) -> str: a_ : Optional[Any] = parent a_ : List[str] = batch_size a_ : List[str] = seq_length a_ : str = is_training a_ : str = use_input_mask a_ : int = use_token_type_ids a_ : List[str] = use_labels a_ : Optional[int] = vocab_size a_ : Any = hidden_size a_ : int = num_hidden_layers a_ : List[str] = num_attention_heads a_ : str = intermediate_size a_ : Union[str, Any] = hidden_act a_ : List[str] = hidden_dropout_prob a_ : int = attention_probs_dropout_prob a_ : int = max_position_embeddings a_ : Tuple = type_vocab_size a_ : Optional[Any] = type_sequence_label_size a_ : Tuple = initializer_range a_ : Dict = num_labels a_ : str = scope a_ : Optional[int] = range_bbox def SCREAMING_SNAKE_CASE ( self : List[str] ) -> int: a_ : Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a_ : Any = ids_tensor([self.batch_size, self.seq_length, 4] , self.range_bbox ) # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: a_ : int = bbox[i, j, 3] a_ : str = bbox[i, j, 1] a_ : List[str] = t if bbox[i, j, 2] < bbox[i, j, 0]: a_ : Tuple = bbox[i, j, 2] a_ : List[str] = bbox[i, j, 0] a_ : Union[str, Any] = t a_ : List[Any] = None if self.use_input_mask: a_ : Dict = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) a_ : List[Any] = None if self.use_token_type_ids: a_ : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) a_ : int = None a_ : Tuple = None if self.use_labels: a_ : List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a_ : int = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) a_ : Optional[int] = self.get_config() return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels def SCREAMING_SNAKE_CASE ( self : Dict ) -> int: return LiltConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) def SCREAMING_SNAKE_CASE ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , ) -> str: a_ : Any = LiltModel(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() a_ : Any = model(SCREAMING_SNAKE_CASE__ , bbox=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ ) a_ : Optional[int] = model(SCREAMING_SNAKE_CASE__ , bbox=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ ) a_ : List[Any] = model(SCREAMING_SNAKE_CASE__ , bbox=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def SCREAMING_SNAKE_CASE ( self : Tuple , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Optional[Any] , ) -> int: a_ : Any = self.num_labels a_ : str = LiltForTokenClassification(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() a_ : str = model( SCREAMING_SNAKE_CASE__ , bbox=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def SCREAMING_SNAKE_CASE ( self : Any , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any] , ) -> str: a_ : Union[str, Any] = LiltForQuestionAnswering(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() a_ : List[str] = model( SCREAMING_SNAKE_CASE__ , bbox=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , start_positions=SCREAMING_SNAKE_CASE__ , end_positions=SCREAMING_SNAKE_CASE__ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def SCREAMING_SNAKE_CASE ( self : int ) -> List[str]: a_ : int = self.prepare_config_and_inputs() ( ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ) : List[Any] = config_and_inputs a_ : Optional[int] = { 'input_ids': input_ids, 'bbox': bbox, 'token_type_ids': token_type_ids, 'attention_mask': input_mask, } return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE__ ( lowercase__ , lowercase__ , lowercase__ , unittest.TestCase ): snake_case__ : Union[str, Any] = ( ( LiltModel, LiltForSequenceClassification, LiltForTokenClassification, LiltForQuestionAnswering, ) if is_torch_available() else () ) snake_case__ : str = ( { '''feature-extraction''': LiltModel, '''question-answering''': LiltForQuestionAnswering, '''text-classification''': LiltForSequenceClassification, '''token-classification''': LiltForTokenClassification, '''zero-shot''': LiltForSequenceClassification, } if is_torch_available() else {} ) snake_case__ : List[str] = False snake_case__ : str = False def SCREAMING_SNAKE_CASE ( self : Dict , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : int ) -> int: return True def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple: a_ : str = LiltModelTester(self ) a_ : List[Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE__ , hidden_size=3_7 ) def SCREAMING_SNAKE_CASE ( self : Dict ) -> List[Any]: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> str: a_ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[int]: a_ : Tuple = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: a_ : List[str] = type self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : int ) -> Optional[Any]: a_ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[str]: a_ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*SCREAMING_SNAKE_CASE__ ) @slow def SCREAMING_SNAKE_CASE ( self : str ) -> Union[str, Any]: for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a_ : List[Any] = LiltModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) @require_torch @slow class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Union[str, Any]: a_ : List[str] = LiltModel.from_pretrained('SCUT-DLVCLab/lilt-roberta-en-base' ).to(SCREAMING_SNAKE_CASE__ ) a_ : str = torch.tensor([[1, 2]] , device=SCREAMING_SNAKE_CASE__ ) a_ : List[Any] = torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]] , device=SCREAMING_SNAKE_CASE__ ) # forward pass with torch.no_grad(): a_ : str = model(input_ids=SCREAMING_SNAKE_CASE__ , bbox=SCREAMING_SNAKE_CASE__ ) a_ : Optional[int] = torch.Size([1, 2, 7_6_8] ) a_ : int = torch.tensor( [[-0.0653, 0.0950, -0.0061], [-0.0545, 0.0926, -0.0324]] , device=SCREAMING_SNAKE_CASE__ , ) self.assertTrue(outputs.last_hidden_state.shape , SCREAMING_SNAKE_CASE__ ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :, :3] , SCREAMING_SNAKE_CASE__ , atol=1E-3 ) )
32
1
"""simple docstring""" from math import cos, sin, sqrt, tau from audio_filters.iir_filter import IIRFilter def __a ( __lowerCamelCase, __lowerCamelCase, __lowerCamelCase = 1 / sqrt(2 ) ): UpperCAmelCase_ : Any = tau * frequency / samplerate UpperCAmelCase_ : List[str] = sin(__lowerCamelCase ) UpperCAmelCase_ : Any = cos(__lowerCamelCase ) UpperCAmelCase_ : Dict = _sin / (2 * q_factor) UpperCAmelCase_ : List[str] = (1 - _cos) / 2 UpperCAmelCase_ : Optional[Any] = 1 - _cos UpperCAmelCase_ : Tuple = 1 + alpha UpperCAmelCase_ : List[str] = -2 * _cos UpperCAmelCase_ : Tuple = 1 - alpha UpperCAmelCase_ : Any = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa], [ba, ba, ba] ) return filt def __a ( __lowerCamelCase, __lowerCamelCase, __lowerCamelCase = 1 / sqrt(2 ) ): UpperCAmelCase_ : Optional[Any] = tau * frequency / samplerate UpperCAmelCase_ : List[Any] = sin(__lowerCamelCase ) UpperCAmelCase_ : Tuple = cos(__lowerCamelCase ) UpperCAmelCase_ : Union[str, Any] = _sin / (2 * q_factor) UpperCAmelCase_ : Tuple = (1 + _cos) / 2 UpperCAmelCase_ : Optional[Any] = -1 - _cos UpperCAmelCase_ : Dict = 1 + alpha UpperCAmelCase_ : Tuple = -2 * _cos UpperCAmelCase_ : Union[str, Any] = 1 - alpha UpperCAmelCase_ : Optional[int] = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa], [ba, ba, ba] ) return filt def __a ( __lowerCamelCase, __lowerCamelCase, __lowerCamelCase = 1 / sqrt(2 ) ): UpperCAmelCase_ : Union[str, Any] = tau * frequency / samplerate UpperCAmelCase_ : List[str] = sin(__lowerCamelCase ) UpperCAmelCase_ : str = cos(__lowerCamelCase ) UpperCAmelCase_ : Dict = _sin / (2 * q_factor) UpperCAmelCase_ : str = _sin / 2 UpperCAmelCase_ : Any = 0 UpperCAmelCase_ : int = -ba UpperCAmelCase_ : int = 1 + alpha UpperCAmelCase_ : Tuple = -2 * _cos UpperCAmelCase_ : str = 1 - alpha UpperCAmelCase_ : Optional[Any] = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa], [ba, ba, ba] ) return filt def __a ( __lowerCamelCase, __lowerCamelCase, __lowerCamelCase = 1 / sqrt(2 ) ): UpperCAmelCase_ : Union[str, Any] = tau * frequency / samplerate UpperCAmelCase_ : Any = sin(__lowerCamelCase ) UpperCAmelCase_ : int = cos(__lowerCamelCase ) UpperCAmelCase_ : Any = _sin / (2 * q_factor) UpperCAmelCase_ : Any = 1 - alpha UpperCAmelCase_ : Union[str, Any] = -2 * _cos UpperCAmelCase_ : Dict = 1 + alpha UpperCAmelCase_ : int = IIRFilter(2 ) filt.set_coefficients([ba, ba, ba], [ba, ba, ba] ) return filt def __a ( __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase = 1 / sqrt(2 ), ): UpperCAmelCase_ : Any = tau * frequency / samplerate UpperCAmelCase_ : Optional[Any] = sin(__lowerCamelCase ) UpperCAmelCase_ : Any = cos(__lowerCamelCase ) UpperCAmelCase_ : Optional[int] = _sin / (2 * q_factor) UpperCAmelCase_ : Optional[Any] = 10 ** (gain_db / 40) UpperCAmelCase_ : str = 1 + alpha * big_a UpperCAmelCase_ : Dict = -2 * _cos UpperCAmelCase_ : Optional[Any] = 1 - alpha * big_a UpperCAmelCase_ : List[str] = 1 + alpha / big_a UpperCAmelCase_ : List[Any] = -2 * _cos UpperCAmelCase_ : Optional[int] = 1 - alpha / big_a UpperCAmelCase_ : Tuple = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa], [ba, ba, ba] ) return filt def __a ( __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase = 1 / sqrt(2 ), ): UpperCAmelCase_ : Optional[Any] = tau * frequency / samplerate UpperCAmelCase_ : Optional[int] = sin(__lowerCamelCase ) UpperCAmelCase_ : Any = cos(__lowerCamelCase ) UpperCAmelCase_ : List[Any] = _sin / (2 * q_factor) UpperCAmelCase_ : Optional[Any] = 10 ** (gain_db / 40) UpperCAmelCase_ : Optional[int] = (big_a + 1) - (big_a - 1) * _cos UpperCAmelCase_ : Tuple = (big_a + 1) + (big_a - 1) * _cos UpperCAmelCase_ : int = (big_a - 1) - (big_a + 1) * _cos UpperCAmelCase_ : str = (big_a - 1) + (big_a + 1) * _cos UpperCAmelCase_ : Dict = 2 * sqrt(__lowerCamelCase ) * alpha UpperCAmelCase_ : List[str] = big_a * (pmc + aaa) UpperCAmelCase_ : Any = 2 * big_a * mpc UpperCAmelCase_ : List[str] = big_a * (pmc - aaa) UpperCAmelCase_ : Dict = ppmc + aaa UpperCAmelCase_ : Optional[Any] = -2 * pmpc UpperCAmelCase_ : Union[str, Any] = ppmc - aaa UpperCAmelCase_ : List[Any] = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa], [ba, ba, ba] ) return filt def __a ( __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase = 1 / sqrt(2 ), ): UpperCAmelCase_ : Optional[int] = tau * frequency / samplerate UpperCAmelCase_ : List[Any] = sin(__lowerCamelCase ) UpperCAmelCase_ : List[Any] = cos(__lowerCamelCase ) UpperCAmelCase_ : str = _sin / (2 * q_factor) UpperCAmelCase_ : Optional[Any] = 10 ** (gain_db / 40) UpperCAmelCase_ : Any = (big_a + 1) - (big_a - 1) * _cos UpperCAmelCase_ : Optional[int] = (big_a + 1) + (big_a - 1) * _cos UpperCAmelCase_ : Optional[Any] = (big_a - 1) - (big_a + 1) * _cos UpperCAmelCase_ : Any = (big_a - 1) + (big_a + 1) * _cos UpperCAmelCase_ : int = 2 * sqrt(__lowerCamelCase ) * alpha UpperCAmelCase_ : Dict = big_a * (ppmc + aaa) UpperCAmelCase_ : Optional[int] = -2 * big_a * pmpc UpperCAmelCase_ : Union[str, Any] = big_a * (ppmc - aaa) UpperCAmelCase_ : Optional[Any] = pmc + aaa UpperCAmelCase_ : Any = 2 * mpc UpperCAmelCase_ : List[str] = pmc - aaa UpperCAmelCase_ : Tuple = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa], [ba, ba, ba] ) return filt
23
"""simple docstring""" import copy from collections import OrderedDict from typing import Dict, Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING _a = logging.get_logger(__name__) _a = { 'facebook/detr-resnet-50': 'https://huggingface.co/facebook/detr-resnet-50/resolve/main/config.json', # See all DETR models at https://huggingface.co/models?filter=detr } class A_ (lowercase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = """detr""" SCREAMING_SNAKE_CASE__ : str = ["""past_key_values"""] SCREAMING_SNAKE_CASE__ : Union[str, Any] = { """hidden_size""": """d_model""", """num_attention_heads""": """encoder_attention_heads""", } def __init__( self , lowercase_=True , lowercase_=None , lowercase_=3 , lowercase_=100 , lowercase_=6 , lowercase_=2048 , lowercase_=8 , lowercase_=6 , lowercase_=2048 , lowercase_=8 , lowercase_=0.0 , lowercase_=0.0 , lowercase_=True , lowercase_="relu" , lowercase_=256 , lowercase_=0.1 , lowercase_=0.0 , lowercase_=0.0 , lowercase_=0.02 , lowercase_=1.0 , lowercase_=False , lowercase_="sine" , lowercase_="resnet50" , lowercase_=True , lowercase_=False , lowercase_=1 , lowercase_=5 , lowercase_=2 , lowercase_=1 , lowercase_=1 , lowercase_=5 , lowercase_=2 , lowercase_=0.1 , **lowercase_ , ): """simple docstring""" if backbone_config is not None and use_timm_backbone: raise ValueError("You can't specify both `backbone_config` and `use_timm_backbone`." ) if not use_timm_backbone: if backbone_config is None: logger.info("`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone." ) UpperCAmelCase_ : Union[str, Any] = CONFIG_MAPPING["resnet"](out_features=["stage4"] ) elif isinstance(lowercase_ , lowercase_ ): UpperCAmelCase_ : int = backbone_config.get("model_type" ) UpperCAmelCase_ : int = CONFIG_MAPPING[backbone_model_type] UpperCAmelCase_ : Any = config_class.from_dict(lowercase_ ) # set timm attributes to None UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : Optional[Any] = None, None, None UpperCAmelCase_ : int = use_timm_backbone UpperCAmelCase_ : int = backbone_config UpperCAmelCase_ : List[Any] = num_channels UpperCAmelCase_ : int = num_queries UpperCAmelCase_ : Union[str, Any] = d_model UpperCAmelCase_ : str = encoder_ffn_dim UpperCAmelCase_ : Tuple = encoder_layers UpperCAmelCase_ : List[Any] = encoder_attention_heads UpperCAmelCase_ : Union[str, Any] = decoder_ffn_dim UpperCAmelCase_ : Optional[Any] = decoder_layers UpperCAmelCase_ : Union[str, Any] = decoder_attention_heads UpperCAmelCase_ : Optional[int] = dropout UpperCAmelCase_ : List[str] = attention_dropout UpperCAmelCase_ : Any = activation_dropout UpperCAmelCase_ : str = activation_function UpperCAmelCase_ : Tuple = init_std UpperCAmelCase_ : Optional[Any] = init_xavier_std UpperCAmelCase_ : Optional[Any] = encoder_layerdrop UpperCAmelCase_ : Optional[int] = decoder_layerdrop UpperCAmelCase_ : Tuple = encoder_layers UpperCAmelCase_ : int = auxiliary_loss UpperCAmelCase_ : Optional[Any] = position_embedding_type UpperCAmelCase_ : Tuple = backbone UpperCAmelCase_ : Optional[int] = use_pretrained_backbone UpperCAmelCase_ : Dict = dilation # Hungarian matcher UpperCAmelCase_ : Union[str, Any] = class_cost UpperCAmelCase_ : Any = bbox_cost UpperCAmelCase_ : int = giou_cost # Loss coefficients UpperCAmelCase_ : str = mask_loss_coefficient UpperCAmelCase_ : Any = dice_loss_coefficient UpperCAmelCase_ : Optional[Any] = bbox_loss_coefficient UpperCAmelCase_ : List[str] = giou_loss_coefficient UpperCAmelCase_ : List[Any] = eos_coefficient super().__init__(is_encoder_decoder=lowercase_ , **lowercase_ ) @property def UpperCamelCase__ ( self ): """simple docstring""" return self.encoder_attention_heads @property def UpperCamelCase__ ( self ): """simple docstring""" return self.d_model @classmethod def UpperCamelCase__ ( cls , lowercase_ , **lowercase_ ): """simple docstring""" return cls(backbone_config=lowercase_ , **lowercase_ ) def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : List[Any] = copy.deepcopy(self.__dict__ ) if output["backbone_config"] is not None: UpperCAmelCase_ : Union[str, Any] = self.backbone_config.to_dict() UpperCAmelCase_ : str = self.__class__.model_type return output class A_ (lowercase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = version.parse("""1.11""" ) @property def UpperCamelCase__ ( self ): """simple docstring""" return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ("pixel_mask", {0: "batch"}), ] ) @property def UpperCamelCase__ ( self ): """simple docstring""" return 1E-5 @property def UpperCamelCase__ ( self ): """simple docstring""" return 12
23
1
"""simple docstring""" import importlib.util import json import os import warnings from dataclasses import dataclass, field import torch from ..training_args import TrainingArguments from ..utils import cached_property, is_sagemaker_dp_enabled, logging UpperCAmelCase__ : List[str] = logging.get_logger(__name__) def lowercase_ ( ): # Get the sagemaker specific mp parameters from smp_options variable. SCREAMING_SNAKE_CASE__ : Dict = os.getenv("""SM_HP_MP_PARAMETERS""" ,"""{}""" ) try: # Parse it and check the field "partitions" is included, it is required for model parallel. SCREAMING_SNAKE_CASE__ : List[str] = json.loads(_snake_case ) if "partitions" not in smp_options: return False except json.JSONDecodeError: return False # Get the sagemaker specific framework parameters from mpi_options variable. SCREAMING_SNAKE_CASE__ : int = os.getenv("""SM_FRAMEWORK_PARAMS""" ,"""{}""" ) try: # Parse it and check the field "sagemaker_distributed_dataparallel_enabled". SCREAMING_SNAKE_CASE__ : Union[str, Any] = json.loads(_snake_case ) if not mpi_options.get("""sagemaker_mpi_enabled""" ,_snake_case ): return False except json.JSONDecodeError: return False # Lastly, check if the `smdistributed` module is present. return importlib.util.find_spec("""smdistributed""" ) is not None if is_sagemaker_model_parallel_available(): import smdistributed.modelparallel.torch as smp smp.init() @dataclass class lowerCAmelCase_ (a__ ): """simple docstring""" __UpperCamelCase : str = field( default='''''' , metadata={'''help''': '''Used by the SageMaker launcher to send mp-specific args. Ignored in SageMakerTrainer'''} , ) def __magic_name__ (self ) -> Optional[int]: """simple docstring""" super().__post_init__() warnings.warn( """`SageMakerTrainingArguments` is deprecated and will be removed in v5 of Transformers. You can use """ """`TrainingArguments` instead.""" , SCREAMING_SNAKE_CASE__ , ) @cached_property def __magic_name__ (self ) -> "torch.device": """simple docstring""" logger.info("""PyTorch: setting up devices""" ) if torch.distributed.is_available() and torch.distributed.is_initialized() and self.local_rank == -1: logger.warning( """torch.distributed process group is initialized, but local_rank == -1. """ """In order to use Torch DDP, launch your script with `python -m torch.distributed.launch""" ) if self.no_cuda: SCREAMING_SNAKE_CASE__ : Optional[int] = torch.device("""cpu""" ) SCREAMING_SNAKE_CASE__ : int = 0 elif is_sagemaker_model_parallel_available(): SCREAMING_SNAKE_CASE__ : Optional[int] = smp.local_rank() SCREAMING_SNAKE_CASE__ : Any = torch.device("""cuda""" , SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : List[Any] = 1 elif is_sagemaker_dp_enabled(): import smdistributed.dataparallel.torch.torch_smddp # noqa: F401 torch.distributed.init_process_group(backend="""smddp""" , timeout=self.ddp_timeout_delta ) SCREAMING_SNAKE_CASE__ : str = int(os.getenv("""SMDATAPARALLEL_LOCAL_RANK""" ) ) SCREAMING_SNAKE_CASE__ : Dict = torch.device("""cuda""" , self.local_rank ) SCREAMING_SNAKE_CASE__ : Optional[int] = 1 elif self.local_rank == -1: # if n_gpu is > 1 we'll use nn.DataParallel. # If you only want to use a specific subset of GPUs use `CUDA_VISIBLE_DEVICES=0` # Explicitly set CUDA to the first (index 0) CUDA device, otherwise `set_device` will # trigger an error that a device index is missing. Index 0 takes into account the # GPUs available in the environment, so `CUDA_VISIBLE_DEVICES=1,2` with `cuda:0` # will use the first GPU in that env, i.e. GPU#1 SCREAMING_SNAKE_CASE__ : List[str] = torch.device("""cuda:0""" if torch.cuda.is_available() else """cpu""" ) # Sometimes the line in the postinit has not been run before we end up here, so just checking we're not at # the default value. SCREAMING_SNAKE_CASE__ : List[str] = torch.cuda.device_count() else: # Here, we'll use torch.distributed. # Initializes the distributed backend which will take care of synchronizing nodes/GPUs if not torch.distributed.is_initialized(): torch.distributed.init_process_group(backend="""nccl""" , timeout=self.ddp_timeout_delta ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.device("""cuda""" , self.local_rank ) SCREAMING_SNAKE_CASE__ : str = 1 if device.type == "cuda": torch.cuda.set_device(SCREAMING_SNAKE_CASE__ ) return device @property def __magic_name__ (self ) -> str: """simple docstring""" if is_sagemaker_model_parallel_available(): return smp.dp_size() return super().world_size @property def __magic_name__ (self ) -> Union[str, Any]: """simple docstring""" return not is_sagemaker_model_parallel_available() @property def __magic_name__ (self ) -> Tuple: """simple docstring""" return False
25
"""simple docstring""" import argparse import os import torch from transformers import FlavaConfig, FlavaForPreTraining from transformers.models.flava.convert_dalle_to_flava_codebook import convert_dalle_checkpoint def lowercase_ ( _snake_case ): # encoder.embeddings are double copied in original FLAVA return sum(param.float().sum() if """encoder.embeddings""" not in key else 0 for key, param in state_dict.items() ) def lowercase_ ( _snake_case ,_snake_case ): SCREAMING_SNAKE_CASE__ : Any = {} for key, value in state_dict.items(): if "text_encoder.embeddings" in key or "image_encoder.embeddings" in key: continue SCREAMING_SNAKE_CASE__ : Optional[int] = key.replace("""heads.cmd.mim_head.cls.predictions""" ,"""mmm_image_head""" ) SCREAMING_SNAKE_CASE__ : Dict = key.replace("""heads.cmd.mlm_head.cls.predictions""" ,"""mmm_text_head""" ) SCREAMING_SNAKE_CASE__ : List[Any] = key.replace("""heads.cmd.itm_head.cls""" ,"""itm_head""" ) SCREAMING_SNAKE_CASE__ : Tuple = key.replace("""heads.cmd.itm_head.pooler""" ,"""itm_head.pooler""" ) SCREAMING_SNAKE_CASE__ : int = key.replace("""heads.cmd.clip_head.logit_scale""" ,"""flava.logit_scale""" ) SCREAMING_SNAKE_CASE__ : Tuple = key.replace("""heads.fairseq_mlm.cls.predictions""" ,"""mlm_head""" ) SCREAMING_SNAKE_CASE__ : str = key.replace("""heads.imagenet.mim_head.cls.predictions""" ,"""mim_head""" ) SCREAMING_SNAKE_CASE__ : List[str] = key.replace("""mm_text_projection""" ,"""flava.text_to_mm_projection""" ) SCREAMING_SNAKE_CASE__ : Dict = key.replace("""mm_image_projection""" ,"""flava.image_to_mm_projection""" ) SCREAMING_SNAKE_CASE__ : str = key.replace("""image_encoder.module""" ,"""flava.image_model""" ) SCREAMING_SNAKE_CASE__ : Tuple = key.replace("""text_encoder.module""" ,"""flava.text_model""" ) SCREAMING_SNAKE_CASE__ : int = key.replace("""mm_encoder.module.encoder.cls_token""" ,"""flava.multimodal_model.cls_token""" ) SCREAMING_SNAKE_CASE__ : Dict = key.replace("""mm_encoder.module""" ,"""flava.multimodal_model""" ) SCREAMING_SNAKE_CASE__ : Any = key.replace("""text_projection""" ,"""flava.text_projection""" ) SCREAMING_SNAKE_CASE__ : List[Any] = key.replace("""image_projection""" ,"""flava.image_projection""" ) SCREAMING_SNAKE_CASE__ : Tuple = value.float() for key, value in codebook_state_dict.items(): SCREAMING_SNAKE_CASE__ : Optional[Any] = value return upgrade @torch.no_grad() def lowercase_ ( _snake_case ,_snake_case ,_snake_case ,_snake_case=None ): if config_path is not None: SCREAMING_SNAKE_CASE__ : Optional[Any] = FlavaConfig.from_pretrained(_snake_case ) else: SCREAMING_SNAKE_CASE__ : List[str] = FlavaConfig() SCREAMING_SNAKE_CASE__ : Optional[int] = FlavaForPreTraining(_snake_case ).eval() SCREAMING_SNAKE_CASE__ : List[Any] = convert_dalle_checkpoint(_snake_case ,_snake_case ,save_checkpoint=_snake_case ) if os.path.exists(_snake_case ): SCREAMING_SNAKE_CASE__ : List[str] = torch.load(_snake_case ,map_location="""cpu""" ) else: SCREAMING_SNAKE_CASE__ : Tuple = torch.hub.load_state_dict_from_url(_snake_case ,map_location="""cpu""" ) SCREAMING_SNAKE_CASE__ : Dict = upgrade_state_dict(_snake_case ,_snake_case ) hf_model.load_state_dict(_snake_case ) SCREAMING_SNAKE_CASE__ : Any = hf_model.state_dict() SCREAMING_SNAKE_CASE__ : Any = count_parameters(_snake_case ) SCREAMING_SNAKE_CASE__ : str = count_parameters(_snake_case ) + count_parameters(_snake_case ) assert torch.allclose(_snake_case ,_snake_case ,atol=1E-3 ) hf_model.save_pretrained(_snake_case ) if __name__ == "__main__": UpperCAmelCase__ : List[Any] = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to flava checkpoint') parser.add_argument('--codebook_path', default=None, type=str, help='Path to flava codebook checkpoint') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') UpperCAmelCase__ : Optional[int] = parser.parse_args() convert_flava_checkpoint(args.checkpoint_path, args.codebook_path, args.pytorch_dump_folder_path, args.config_path)
25
1
import itertools import json import os import unittest from transformers import AddedToken, LongformerTokenizer, LongformerTokenizerFast from transformers.models.longformer.tokenization_longformer import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class _snake_case ( __snake_case , unittest.TestCase ): A__ : int = LongformerTokenizer A__ : Tuple = True A__ : Tuple = LongformerTokenizerFast A__ : List[Any] = True def A__ ( self: Optional[Any] ) -> Union[str, Any]: super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt UpperCAmelCase_ : List[str] = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """\u0120""", """\u0120l""", """\u0120n""", """\u0120lo""", """\u0120low""", """er""", """\u0120lowest""", """\u0120newer""", """\u0120wider""", """<unk>""", ] UpperCAmelCase_ : List[Any] = dict(zip(lowerCamelCase_ ,range(len(lowerCamelCase_ ) ) ) ) UpperCAmelCase_ : List[str] = ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""] UpperCAmelCase_ : List[str] = {"""unk_token""": """<unk>"""} UpperCAmelCase_ : Any = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES["""vocab_file"""] ) UpperCAmelCase_ : List[Any] = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file ,"""w""" ,encoding="""utf-8""" ) as fp: fp.write(json.dumps(lowerCamelCase_ ) + """\n""" ) with open(self.merges_file ,"""w""" ,encoding="""utf-8""" ) as fp: fp.write("""\n""".join(lowerCamelCase_ ) ) def A__ ( self: Tuple ,**lowerCamelCase_: Any ) -> Dict: kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname ,**lowerCamelCase_ ) def A__ ( self: Tuple ,**lowerCamelCase_: List[str] ) -> str: kwargs.update(self.special_tokens_map ) return self.rust_tokenizer_class.from_pretrained(self.tmpdirname ,**lowerCamelCase_ ) def A__ ( self: Union[str, Any] ,lowerCamelCase_: List[Any] ) -> int: UpperCAmelCase_ : str = """lower newer""" UpperCAmelCase_ : Optional[Any] = """lower newer""" return input_text, output_text def A__ ( self: int ) -> Optional[int]: UpperCAmelCase_ : int = self.tokenizer_class(self.vocab_file ,self.merges_file ,**self.special_tokens_map ) UpperCAmelCase_ : int = """lower newer""" UpperCAmelCase_ : int = ["""l""", """o""", """w""", """er""", """\u0120""", """n""", """e""", """w""", """er"""] UpperCAmelCase_ : List[str] = tokenizer.tokenize(lowerCamelCase_ ) # , add_prefix_space=True) self.assertListEqual(lowerCamelCase_ ,lowerCamelCase_ ) UpperCAmelCase_ : Union[str, Any] = tokens + [tokenizer.unk_token] UpperCAmelCase_ : Dict = [0, 1, 2, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCamelCase_ ) ,lowerCamelCase_ ) def A__ ( self: Optional[Any] ) -> Dict: UpperCAmelCase_ : Optional[Any] = self.get_tokenizer() self.assertListEqual(tokenizer.encode("""Hello world!""" ,add_special_tokens=lowerCamelCase_ ) ,[0, 31414, 232, 328, 2] ) self.assertListEqual( tokenizer.encode("""Hello world! cécé herlolip 418""" ,add_special_tokens=lowerCamelCase_ ) ,[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2] ,) @slow def A__ ( self: List[Any] ) -> List[str]: UpperCAmelCase_ : List[Any] = self.tokenizer_class.from_pretrained("""allenai/longformer-base-4096""" ) UpperCAmelCase_ : Dict = tokenizer.encode("""sequence builders""" ,add_special_tokens=lowerCamelCase_ ) UpperCAmelCase_ : str = tokenizer.encode("""multi-sequence build""" ,add_special_tokens=lowerCamelCase_ ) UpperCAmelCase_ : Optional[Any] = tokenizer.encode( """sequence builders""" ,add_special_tokens=lowerCamelCase_ ,add_prefix_space=lowerCamelCase_ ) UpperCAmelCase_ : List[str] = tokenizer.encode( """sequence builders""" ,"""multi-sequence build""" ,add_special_tokens=lowerCamelCase_ ,add_prefix_space=lowerCamelCase_ ) UpperCAmelCase_ : Dict = tokenizer.build_inputs_with_special_tokens(lowerCamelCase_ ) UpperCAmelCase_ : str = tokenizer.build_inputs_with_special_tokens(lowerCamelCase_ ,lowerCamelCase_ ) assert encoded_sentence == encoded_text_from_decode assert encoded_pair == encoded_pair_from_decode def A__ ( self: Tuple ) -> Dict: UpperCAmelCase_ : int = self.get_tokenizer() UpperCAmelCase_ : List[str] = """Encode this sequence.""" UpperCAmelCase_ : Optional[int] = tokenizer.byte_encoder[""" """.encode("""utf-8""" )[0]] # Testing encoder arguments UpperCAmelCase_ : Dict = tokenizer.encode(lowerCamelCase_ ,add_special_tokens=lowerCamelCase_ ,add_prefix_space=lowerCamelCase_ ) UpperCAmelCase_ : Tuple = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertNotEqual(lowerCamelCase_ ,lowerCamelCase_ ) UpperCAmelCase_ : Any = tokenizer.encode(lowerCamelCase_ ,add_special_tokens=lowerCamelCase_ ,add_prefix_space=lowerCamelCase_ ) UpperCAmelCase_ : Optional[Any] = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertEqual(lowerCamelCase_ ,lowerCamelCase_ ) tokenizer.add_special_tokens({"""bos_token""": """<s>"""} ) UpperCAmelCase_ : str = tokenizer.encode(lowerCamelCase_ ,add_special_tokens=lowerCamelCase_ ) UpperCAmelCase_ : Optional[int] = tokenizer.convert_ids_to_tokens(encoded[1] )[0] self.assertNotEqual(lowerCamelCase_ ,lowerCamelCase_ ) # Testing spaces after special tokens UpperCAmelCase_ : List[str] = """<mask>""" tokenizer.add_special_tokens( {"""mask_token""": AddedToken(lowerCamelCase_ ,lstrip=lowerCamelCase_ ,rstrip=lowerCamelCase_ )} ) # mask token has a left space UpperCAmelCase_ : Optional[Any] = tokenizer.convert_tokens_to_ids(lowerCamelCase_ ) UpperCAmelCase_ : int = """Encode <mask> sequence""" UpperCAmelCase_ : Optional[int] = """Encode <mask>sequence""" UpperCAmelCase_ : Dict = tokenizer.encode(lowerCamelCase_ ) UpperCAmelCase_ : Optional[Any] = encoded.index(lowerCamelCase_ ) UpperCAmelCase_ : str = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertEqual(lowerCamelCase_ ,lowerCamelCase_ ) UpperCAmelCase_ : Union[str, Any] = tokenizer.encode(lowerCamelCase_ ) UpperCAmelCase_ : Union[str, Any] = encoded.index(lowerCamelCase_ ) UpperCAmelCase_ : str = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertNotEqual(lowerCamelCase_ ,lowerCamelCase_ ) def A__ ( self: Any ) -> List[Any]: pass def A__ ( self: Dict ) -> str: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): UpperCAmelCase_ : Optional[int] = self.rust_tokenizer_class.from_pretrained(lowerCamelCase_ ,**lowerCamelCase_ ) UpperCAmelCase_ : str = self.tokenizer_class.from_pretrained(lowerCamelCase_ ,**lowerCamelCase_ ) UpperCAmelCase_ : List[str] = """A, <mask> AllenNLP sentence.""" UpperCAmelCase_ : List[str] = tokenizer_r.encode_plus(lowerCamelCase_ ,add_special_tokens=lowerCamelCase_ ,return_token_type_ids=lowerCamelCase_ ) UpperCAmelCase_ : List[Any] = 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"""] ) ,) UpperCAmelCase_ : List[str] = tokenizer_r.convert_ids_to_tokens(tokens_r["""input_ids"""] ) UpperCAmelCase_ : Tuple = 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, 250, 6, 50264, 3823, 487, 21992, 3645, 4, 2] ) self.assertSequenceEqual(tokens_r["""input_ids"""] ,[0, 250, 6, 50264, 3823, 487, 21992, 3645, 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 A__ ( self: Dict ) -> int: for trim_offsets, add_prefix_space in itertools.product([True, False] ,repeat=2 ): UpperCAmelCase_ : int = self.rust_tokenizer_class.from_pretrained( self.tmpdirname ,use_fast=lowerCamelCase_ ,add_prefix_space=lowerCamelCase_ ,trim_offsets=lowerCamelCase_ ) UpperCAmelCase_ : Optional[int] = json.loads(tokenizer_r.backend_tokenizer.pre_tokenizer.__getstate__() ) UpperCAmelCase_ : Tuple = 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 A__ ( self: Union[str, Any] ) -> Tuple: # Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` and # `trim_offsets` for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): UpperCAmelCase_ : int = """hello""" # `hello` is a token in the vocabulary of `pretrained_name` UpperCAmelCase_ : List[str] = F'''{text_of_1_token} {text_of_1_token}''' UpperCAmelCase_ : Union[str, Any] = self.rust_tokenizer_class.from_pretrained( lowerCamelCase_ ,use_fast=lowerCamelCase_ ,add_prefix_space=lowerCamelCase_ ,trim_offsets=lowerCamelCase_ ) UpperCAmelCase_ : Optional[int] = 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_ )) ,) UpperCAmelCase_ : Optional[int] = self.rust_tokenizer_class.from_pretrained( lowerCamelCase_ ,use_fast=lowerCamelCase_ ,add_prefix_space=lowerCamelCase_ ,trim_offsets=lowerCamelCase_ ) UpperCAmelCase_ : str = 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_ )) ,) UpperCAmelCase_ : str = self.rust_tokenizer_class.from_pretrained( lowerCamelCase_ ,use_fast=lowerCamelCase_ ,add_prefix_space=lowerCamelCase_ ,trim_offsets=lowerCamelCase_ ) UpperCAmelCase_ : List[str] = 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_ )) ,) UpperCAmelCase_ : Any = self.rust_tokenizer_class.from_pretrained( lowerCamelCase_ ,use_fast=lowerCamelCase_ ,add_prefix_space=lowerCamelCase_ ,trim_offsets=lowerCamelCase_ ) UpperCAmelCase_ : Optional[Any] = 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_ )) ,) UpperCAmelCase_ : List[Any] = 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)), # ) UpperCAmelCase_ : List[Any] = self.rust_tokenizer_class.from_pretrained( lowerCamelCase_ ,use_fast=lowerCamelCase_ ,add_prefix_space=lowerCamelCase_ ,trim_offsets=lowerCamelCase_ ) UpperCAmelCase_ : Any = 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_ )) ,) UpperCAmelCase_ : str = self.rust_tokenizer_class.from_pretrained( lowerCamelCase_ ,use_fast=lowerCamelCase_ ,add_prefix_space=lowerCamelCase_ ,trim_offsets=lowerCamelCase_ ) UpperCAmelCase_ : Any = 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_ )) ,) UpperCAmelCase_ : int = self.rust_tokenizer_class.from_pretrained( lowerCamelCase_ ,use_fast=lowerCamelCase_ ,add_prefix_space=lowerCamelCase_ ,trim_offsets=lowerCamelCase_ ) UpperCAmelCase_ : Any = 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_ )) ,)
369
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_ = logging.getLogger(__name__) UpperCamelCase_ = '''pytorch_model.bin''' @dataclasses.dataclass class _snake_case : '''simple docstring''' A__ : str = dataclasses.field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models."} ) A__ : Optional[str] = dataclasses.field( default=__snake_case , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co."} , ) @dataclasses.dataclass class _snake_case : '''simple docstring''' A__ : str = dataclasses.field(metadata={"help": "A csv or a json file containing the training data."} ) A__ : str = dataclasses.field(metadata={"help": "A csv or a json file containing the data to predict on."} ) A__ : Optional[str] = dataclasses.field( default=__snake_case , metadata={"help": "A csv or a json file containing the validation data."} ) A__ : Optional[str] = dataclasses.field( default=__snake_case , metadata={"help": "The name of the task to train on."} , ) A__ : Optional[List[str]] = dataclasses.field( default=__snake_case , metadata={"help": "The list of labels for the task."} ) @dataclasses.dataclass class _snake_case : '''simple docstring''' A__ : str = dataclasses.field( metadata={"help": "The output directory where the model predictions and checkpoints will be written."} ) A__ : Optional[str] = dataclasses.field( default="accuracy" , metadata={"help": "The evaluation metric used for the task."} ) A__ : Optional[str] = dataclasses.field( default="no" , metadata={ "help": "The evaluation strategy to adopt during training. Possible values are: [\"no\", \"step\", \"epoch]" } , ) A__ : Optional[int] = dataclasses.field( default=10 , metadata={"help": "Number of evaluation calls with no improvement after which training will be stopped."} , ) A__ : Optional[float] = dataclasses.field( default=0.0 , metadata={ "help": "How much the specified evaluation metric must improve to satisfy early stopping conditions." } , ) A__ : Optional[bool] = dataclasses.field( default=__snake_case , metadata={"help": "Whether to filter the pseudo-labeled data based on the confidence score."} , ) A__ : Optional[bool] = dataclasses.field( default=__snake_case , metadata={"help": "Whether to filter the pseudo-labeled data based on the validation performance."} , ) A__ : Optional[bool] = dataclasses.field( default=__snake_case , metadata={"help": "Whether to fine-tune on labeled data after pseudo training."} , ) A__ : Optional[float] = dataclasses.field( default=0.0 , metadata={"help": "Confidence threshold for pseudo-labeled data filtering."} , ) A__ : Optional[int] = dataclasses.field( default=100 , metadata={"help": "Number of evaluation calls with no improvement after which training will be stopped."} , ) A__ : Optional[int] = dataclasses.field( default=__snake_case , metadata={"help": "Random seed for initialization."} , ) def lowerCamelCase_ ( _a : str , _a : List[Any] , _a : List[Any] , _a : Dict , _a : int , _a : Tuple ): '''simple docstring''' UpperCAmelCase_ : Tuple = datasets.concatenate_datasets([infer_input, infer_output] , axis=1 ) if args.do_filter_by_confidence: UpperCAmelCase_ : List[str] = dataset.filter(lambda _a : example["probability"] > args.confidence_threshold ) if args.do_filter_by_val_performance: assert eval_result >= 0.0 and eval_result <= 1.0 UpperCAmelCase_ : List[str] = int(eval_result * len(_a ) ) print(_a ) UpperCAmelCase_ : int = dataset.sort("""probability""" , reverse=_a ) UpperCAmelCase_ : Optional[int] = dataset.select(range(_a ) ) UpperCAmelCase_ : List[str] = dataset.remove_columns(["""label""", """probability"""] ) UpperCAmelCase_ : Optional[Any] = dataset.rename_column("""prediction""" , """label""" ) UpperCAmelCase_ : Union[str, Any] = dataset.map(lambda _a : {"label": idalabel[example["label"]]} ) UpperCAmelCase_ : int = dataset.shuffle(seed=args.seed ) UpperCAmelCase_ : int = os.path.join(_a , F'''train_pseudo.{args.data_file_extension}''' ) if args.data_file_extension == "csv": dataset.to_csv(_a , index=_a ) else: dataset.to_json(_a ) def lowerCamelCase_ ( _a : Any , _a : int , _a : Dict , _a : List[Any] , **_a : int ): '''simple docstring''' UpperCAmelCase_ : Optional[int] = 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() UpperCAmelCase_ : Tuple = STModelArguments(model_name_or_path=_a ) UpperCAmelCase_ : str = STDataArguments(train_file=_a , infer_file=_a ) UpperCAmelCase_ : Optional[Any] = STTrainingArguments(output_dir=_a ) UpperCAmelCase_ : Optional[Any] = argparse.Namespace() for arg_class in (model_args, data_args, training_args): for key, value in vars(_a ).items(): setattr(_a , _a , _a ) for key, value in kwargs.items(): if hasattr(_a , _a ): setattr(_a , _a , _a ) # Sanity checks UpperCAmelCase_ : List[str] = {} UpperCAmelCase_ : Any = 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 UpperCAmelCase_ : List[Any] = args.train_file UpperCAmelCase_ : Tuple = args.infer_file if args.evaluation_strategy != IntervalStrategy.NO.value: assert args.eval_file is not None UpperCAmelCase_ : Dict = args.eval_file for key in data_files: UpperCAmelCase_ : List[str] = 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: UpperCAmelCase_ : int = 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...""" ) UpperCAmelCase_ : int = F'''{args.output_dir}/self-train_iter-{{}}'''.format UpperCAmelCase_ : List[Any] = data_dir_format(0 ) if accelerator.is_main_process: if args.output_dir is not None: os.makedirs(args.output_dir , exist_ok=_a ) os.makedirs(_a , exist_ok=_a ) accelerator.wait_for_everyone() UpperCAmelCase_ : Any = None UpperCAmelCase_ : Tuple = None UpperCAmelCase_ : List[str] = 0 UpperCAmelCase_ : List[Any] = False # Show the progress bar UpperCAmelCase_ : List[str] = 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 ) ): UpperCAmelCase_ : Any = data_dir_format(_a ) assert os.path.exists(_a ) # Stage 1: initial fine-tuning for iteration = 0 or pseudo-training for # iteration > 0 UpperCAmelCase_ : List[str] = os.path.join(_a , """stage-1""" ) UpperCAmelCase_ : Optional[int] = { """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(_a , _a ): arguments_dict.update({key: value} ) UpperCAmelCase_ : Any = os.path.join(_a , """best-checkpoint""" , _a ) if os.path.exists(_a ): logger.info( """Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 1.""" , _a , _a , ) else: logger.info("""***** Running self-training: iteration: %d, stage: 1 *****""" , _a ) finetune(**_a ) accelerator.wait_for_everyone() assert os.path.exists(_a ) logger.info("""Self-training job completed: iteration: %d, stage: 1.""" , _a ) if iteration > 0 and args.finetune_on_labeled_data: # Stage 2 (optional): fine-tuning on the original labeled data UpperCAmelCase_ : Dict = os.path.join(_a , """best-checkpoint""" ) UpperCAmelCase_ : str = os.path.join(_a , """stage-2""" ) # Update arguments_dict UpperCAmelCase_ : Union[str, Any] = model_path UpperCAmelCase_ : Dict = data_files["""train"""] UpperCAmelCase_ : List[str] = current_output_dir UpperCAmelCase_ : str = os.path.join(_a , """best-checkpoint""" , _a ) if os.path.exists(_a ): logger.info( """Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 2.""" , _a , _a , ) else: logger.info("""***** Running self-training: iteration: %d, stage: 2 *****""" , _a ) finetune(**_a ) accelerator.wait_for_everyone() assert os.path.exists(_a ) logger.info("""Self-training job completed: iteration: %d, stage: 2.""" , _a ) UpperCAmelCase_ : Optional[Any] = iteration UpperCAmelCase_ : List[str] = data_dir_format(iteration + 1 ) UpperCAmelCase_ : List[str] = AutoConfig.from_pretrained(os.path.join(_a , """best-checkpoint""" ) ) UpperCAmelCase_ : str = config.idalabel UpperCAmelCase_ : Union[str, Any] = os.path.join(_a , """eval_results_best-checkpoint.json""" ) UpperCAmelCase_ : int = os.path.join(_a , """test_results_best-checkpoint.json""" ) assert os.path.exists(_a ) with open(_a , """r""" ) as f: UpperCAmelCase_ : Optional[int] = float(json.load(_a )[args.eval_metric] ) UpperCAmelCase_ : Dict = os.path.join(_a , """infer_output_best-checkpoint.csv""" ) assert os.path.exists(_a ) # Loading the dataset from local csv or json files. UpperCAmelCase_ : Optional[Any] = load_dataset(args.data_file_extension , data_files={"""data""": data_files["""infer"""]} )["""data"""] UpperCAmelCase_ : List[str] = load_dataset("""csv""" , data_files={"""data""": infer_output_file} )["""data"""] if accelerator.is_main_process: os.makedirs(_a , exist_ok=_a ) shutil.copy(_a , os.path.join(_a , F'''eval_results_iter-{iteration}.json''' ) ) if os.path.exists(_a ): shutil.copy(_a , os.path.join(_a , F'''test_results_iter-{iteration}.json''' ) ) create_pseudo_labeled_data(_a , _a , _a , _a , _a , _a ) accelerator.wait_for_everyone() UpperCAmelCase_ : Tuple = os.path.join(_a , F'''train_pseudo.{args.data_file_extension}''' ) if args.evaluation_strategy != IntervalStrategy.NO.value: UpperCAmelCase_ : Optional[Any] = eval_result if best_iteration is None: UpperCAmelCase_ : Optional[int] = new_iteration UpperCAmelCase_ : Union[str, Any] = new_eval_result else: if new_eval_result - best_eval_result > args.early_stopping_threshold: UpperCAmelCase_ : List[str] = new_iteration UpperCAmelCase_ : Union[str, Any] = new_eval_result UpperCAmelCase_ : int = 0 else: if new_eval_result == best_eval_result: UpperCAmelCase_ : Dict = new_iteration UpperCAmelCase_ : Optional[Any] = new_eval_result early_stopping_patience_counter += 1 if early_stopping_patience_counter >= args.early_stopping_patience: UpperCAmelCase_ : List[Any] = 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""" , _a ) logger.info("""Best evaluation result: %s = %f""" , args.eval_metric , _a ) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(_a , F'''eval_results_iter-{iteration}.json''' ) , os.path.join(_a , """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 , _a ) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(_a , F'''eval_results_iter-{args.max_selftrain_iterations - 1}.json''' ) , os.path.join(_a , """eval_results_best-iteration.json""" ) , )
59
0
"""simple docstring""" from __future__ import absolute_import, division, print_function, unicode_literals from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers import RobertaConfig from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward from transformers.models.roberta.modeling_roberta import ( ROBERTA_INPUTS_DOCSTRING, ROBERTA_START_DOCSTRING, RobertaEmbeddings, ) from .modeling_highway_bert import BertPreTrainedModel, DeeBertModel, HighwayException, entropy @add_start_docstrings( """The RoBERTa Model transformer with early exiting (DeeRoBERTa). """ , SCREAMING_SNAKE_CASE_ , ) class lowerCamelCase__ ( SCREAMING_SNAKE_CASE_ ): """simple docstring""" __a = RobertaConfig __a = """roberta""" def __init__( self : str , UpperCamelCase : Union[str, Any] ): '''simple docstring''' super().__init__(__UpperCAmelCase ) __UpperCAmelCase : Tuple = RobertaEmbeddings(__UpperCAmelCase ) self.init_weights() @add_start_docstrings( """RoBERTa Model (with early exiting - DeeRoBERTa) with a classifier on top, also takes care of multi-layer training. """ , SCREAMING_SNAKE_CASE_ , ) class lowerCamelCase__ ( SCREAMING_SNAKE_CASE_ ): """simple docstring""" __a = RobertaConfig __a = """roberta""" def __init__( self : List[str] , UpperCamelCase : Tuple ): '''simple docstring''' super().__init__(__UpperCAmelCase ) __UpperCAmelCase : Tuple = config.num_labels __UpperCAmelCase : Optional[Any] = config.num_hidden_layers __UpperCAmelCase : Tuple = DeeRobertaModel(__UpperCAmelCase ) __UpperCAmelCase : Optional[int] = nn.Dropout(config.hidden_dropout_prob ) __UpperCAmelCase : Tuple = nn.Linear(config.hidden_size , self.config.num_labels ) @add_start_docstrings_to_model_forward(__UpperCAmelCase ) def lowerCamelCase__ ( self : Optional[Any] , UpperCamelCase : Optional[Any]=None , UpperCamelCase : Any=None , UpperCamelCase : List[str]=None , UpperCamelCase : str=None , UpperCamelCase : int=None , UpperCamelCase : Optional[Any]=None , UpperCamelCase : Dict=None , UpperCamelCase : List[Any]=-1 , UpperCamelCase : Optional[int]=False , ): '''simple docstring''' __UpperCAmelCase : Optional[int] = self.num_layers try: __UpperCAmelCase : Tuple = self.roberta( __UpperCAmelCase , attention_mask=__UpperCAmelCase , token_type_ids=__UpperCAmelCase , position_ids=__UpperCAmelCase , head_mask=__UpperCAmelCase , inputs_embeds=__UpperCAmelCase , ) __UpperCAmelCase : List[str] = outputs[1] __UpperCAmelCase : int = self.dropout(__UpperCAmelCase ) __UpperCAmelCase : Optional[Any] = self.classifier(__UpperCAmelCase ) __UpperCAmelCase : str = (logits,) + outputs[2:] # add hidden states and attention if they are here except HighwayException as e: __UpperCAmelCase : List[str] = e.message __UpperCAmelCase : Dict = e.exit_layer __UpperCAmelCase : Optional[int] = outputs[0] if not self.training: __UpperCAmelCase : Union[str, Any] = entropy(__UpperCAmelCase ) __UpperCAmelCase : Optional[Any] = [] __UpperCAmelCase : Optional[Any] = [] if labels is not None: if self.num_labels == 1: # We are doing regression __UpperCAmelCase : int = MSELoss() __UpperCAmelCase : List[Any] = loss_fct(logits.view(-1 ) , labels.view(-1 ) ) else: __UpperCAmelCase : List[str] = CrossEntropyLoss() __UpperCAmelCase : int = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) # work with highway exits __UpperCAmelCase : Optional[int] = [] for highway_exit in outputs[-1]: __UpperCAmelCase : Tuple = highway_exit[0] if not self.training: highway_logits_all.append(__UpperCAmelCase ) highway_entropy.append(highway_exit[2] ) if self.num_labels == 1: # We are doing regression __UpperCAmelCase : List[str] = MSELoss() __UpperCAmelCase : int = loss_fct(highway_logits.view(-1 ) , labels.view(-1 ) ) else: __UpperCAmelCase : Optional[int] = CrossEntropyLoss() __UpperCAmelCase : Any = loss_fct(highway_logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) highway_losses.append(__UpperCAmelCase ) if train_highway: __UpperCAmelCase : Dict = (sum(highway_losses[:-1] ),) + outputs # exclude the final highway, of course else: __UpperCAmelCase : Optional[Any] = (loss,) + outputs if not self.training: __UpperCAmelCase : Optional[Any] = outputs + ((original_entropy, highway_entropy), exit_layer) if output_layer >= 0: __UpperCAmelCase : Union[str, Any] = ( (outputs[0],) + (highway_logits_all[output_layer],) + outputs[2:] ) # use the highway of the last layer return outputs # (loss), logits, (hidden_states), (attentions), entropy
115
"""simple docstring""" def UpperCamelCase ( UpperCAmelCase ) ->int: """simple docstring""" a_ = [[0 for _ in range(UpperCAmelCase )] for _ in range(m + 1 )] for i in range(m + 1 ): a_ = 1 for n in range(m + 1 ): for k in range(1 , UpperCAmelCase ): memo[n][k] += memo[n][k - 1] if n - k > 0: memo[n][k] += memo[n - k - 1][k] return memo[m][m - 1] if __name__ == "__main__": import sys if len(sys.argv) == 1: try: UpperCamelCase_ = int(input('Enter a number: ').strip()) print(partition(n)) except ValueError: print('Please enter a number.') else: try: UpperCamelCase_ = int(sys.argv[1]) print(partition(n)) except ValueError: print('Please pass a number.')
243
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowercase: Union[str, Any] = { "configuration_clap": [ "CLAP_PRETRAINED_MODEL_ARCHIVE_LIST", "ClapAudioConfig", "ClapConfig", "ClapTextConfig", ], "processing_clap": ["ClapProcessor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase: Dict = [ "CLAP_PRETRAINED_MODEL_ARCHIVE_LIST", "ClapModel", "ClapPreTrainedModel", "ClapTextModel", "ClapTextModelWithProjection", "ClapAudioModel", "ClapAudioModelWithProjection", ] _lowercase: List[Any] = ["ClapFeatureExtractor"] if TYPE_CHECKING: from .configuration_clap import ( CLAP_PRETRAINED_MODEL_ARCHIVE_LIST, ClapAudioConfig, ClapConfig, ClapTextConfig, ) from .processing_clap import ClapProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_clap import ClapFeatureExtractor from .modeling_clap import ( CLAP_PRETRAINED_MODEL_ARCHIVE_LIST, ClapAudioModel, ClapAudioModelWithProjection, ClapModel, ClapPreTrainedModel, ClapTextModel, ClapTextModelWithProjection, ) else: import sys _lowercase: List[str] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
71
import itertools import os from collections import Counter, defaultdict from concurrent.futures import ThreadPoolExecutor, as_completed import numpy as np import datasets from .execute import check_correctness _lowercase: Optional[Any] = "\\n@misc{chen2021evaluating,\n title={Evaluating Large Language Models Trained on Code},\n author={Mark Chen and Jerry Tworek and Heewoo Jun and Qiming Yuan \\nand Henrique Ponde de Oliveira Pinto and Jared Kaplan and Harri Edwards \\nand Yuri Burda and Nicholas Joseph and Greg Brockman and Alex Ray \\nand Raul Puri and Gretchen Krueger and Michael Petrov and Heidy Khlaaf \\nand Girish Sastry and Pamela Mishkin and Brooke Chan and Scott Gray \\nand Nick Ryder and Mikhail Pavlov and Alethea Power and Lukasz Kaiser \\nand Mohammad Bavarian and Clemens Winter and Philippe Tillet \\nand Felipe Petroski Such and Dave Cummings and Matthias Plappert \\nand Fotios Chantzis and Elizabeth Barnes and Ariel Herbert-Voss \\nand William Hebgen Guss and Alex Nichol and Alex Paino and Nikolas Tezak \\nand Jie Tang and Igor Babuschkin and Suchir Balaji and Shantanu Jain \\nand William Saunders and Christopher Hesse and Andrew N. Carr \\nand Jan Leike and Josh Achiam and Vedant Misra and Evan Morikawa \\nand Alec Radford and Matthew Knight and Miles Brundage and Mira Murati \\nand Katie Mayer and Peter Welinder and Bob McGrew and Dario Amodei \\nand Sam McCandlish and Ilya Sutskever and Wojciech Zaremba},\n year={2021},\n eprint={2107.03374},\n archivePrefix={arXiv},\n primaryClass={cs.LG}\n}\n" _lowercase: Union[str, Any] = "\\nThis metric implements the evaluation harness for the HumanEval problem solving dataset\ndescribed in the paper \"Evaluating Large Language Models Trained on Code\"\n(https://arxiv.org/abs/2107.03374).\n" _lowercase: Union[str, Any] = "\nCalculates how good are predictions given some references, using certain scores\nArgs:\n predictions: list of candidates to evaluate. Each candidates should be a list\n of strings with several code candidates to solve the problem.\n references: a list with a test for each prediction. Each test should evaluate the\n correctness of a code candidate.\n k: number of code candidates to consider in the evaluation (Default: [1, 10, 100])\n num_workers: number of workers used to evaluate the canidate programs (Default: 4).\n timeout:\nReturns:\n pass_at_k: dict with pass rates for each k\n results: dict with granular results of each unittest\nExamples:\n >>> code_eval = datasets.load_metric(\"code_eval\")\n >>> test_cases = [\"assert add(2,3)==5\"]\n >>> candidates = [[\"def add(a,b): return a*b\", \"def add(a, b): return a+b\"]]\n >>> pass_at_k, results = code_eval.compute(references=test_cases, predictions=candidates, k=[1, 2])\n >>> print(pass_at_k)\n {'pass@1': 0.5, 'pass@2': 1.0}\n" _lowercase: List[Any] = "\n################################################################################\n !!!WARNING!!!\n################################################################################\nThe \"code_eval\" metric executes untrusted model-generated code in Python.\nAlthough it is highly unlikely that model-generated code will do something\novertly malicious in response to this test suite, model-generated code may act\ndestructively due to a lack of model capability or alignment.\nUsers are strongly encouraged to sandbox this evaluation suite so that it\ndoes not perform destructive actions on their host or network. For more\ninformation on how OpenAI sandboxes its code, see the paper \"Evaluating Large\nLanguage Models Trained on Code\" (https://arxiv.org/abs/2107.03374).\n\nOnce you have read this disclaimer and taken appropriate precautions,\nset the environment variable HF_ALLOW_CODE_EVAL=\"1\". Within Python you can to this\nwith:\n\n>>> import os\n>>> os.environ[\"HF_ALLOW_CODE_EVAL\"] = \"1\"\n\n################################################################################\\n" _lowercase: List[Any] = "The MIT License\n\nCopyright (c) OpenAI (https://openai.com)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE." @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION ) class _lowercase ( datasets.Metric ): """simple docstring""" def UpperCamelCase_ (self ): """simple docstring""" return datasets.MetricInfo( # This is the description that will appear on the metrics page. description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Sequence(datasets.Value("string" ) ), "references": datasets.Value("string" ), } ) , homepage="https://github.com/openai/human-eval" , codebase_urls=["https://github.com/openai/human-eval"] , reference_urls=["https://github.com/openai/human-eval"] , license=_LICENSE , ) def UpperCamelCase_ (self , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_=[1, 10, 100] , lowerCamelCase_=4 , lowerCamelCase_=3.0 ): """simple docstring""" if os.getenv("HF_ALLOW_CODE_EVAL" , 0 ) != "1": raise ValueError(_WARNING ) if os.name == "nt": raise NotImplementedError("This metric is currently not supported on Windows." ) with ThreadPoolExecutor(max_workers=lowerCamelCase_ ) as executor: a = [] a = Counter() a = 0 a = defaultdict(lowerCamelCase_ ) for task_id, (candidates, test_case) in enumerate(zip(lowerCamelCase_ , lowerCamelCase_ ) ): for candidate in candidates: a = candidate + "\n" + test_case a = (test_program, timeout, task_id, completion_id[task_id]) a = executor.submit(lowerCamelCase_ , *lowerCamelCase_ ) futures.append(lowerCamelCase_ ) completion_id[task_id] += 1 n_samples += 1 for future in as_completed(lowerCamelCase_ ): a = future.result() results[result["task_id"]].append((result["completion_id"], result) ) a , a = [], [] for result in results.values(): result.sort() a = [r[1]["passed"] for r in result] total.append(len(lowerCamelCase_ ) ) correct.append(sum(lowerCamelCase_ ) ) a = np.array(lowerCamelCase_ ) a = np.array(lowerCamelCase_ ) a = k a = {F'''pass@{k}''': estimate_pass_at_k(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ).mean() for k in ks if (total >= k).all()} return pass_at_k, results def a( A : Optional[Any] , A : str , A : Dict ) -> Optional[int]: """simple docstring""" def estimator(A : int , A : int , A : int ) -> float: if n - c < k: return 1.0 return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1 , n + 1 ) ) if isinstance(A , A ): a = itertools.repeat(A , len(A ) ) else: assert len(A ) == len(A ) a = iter(A ) return np.array([estimator(int(A ) , int(A ) , A ) for n, c in zip(A , A )] )
71
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCAmelCase :Dict = logging.get_logger(__name__) _lowerCAmelCase :Optional[Any] = {'ctrl': 'https://huggingface.co/ctrl/resolve/main/config.json'} class _UpperCAmelCase ( a ): '''simple docstring''' a__ ='''ctrl''' a__ =['''past_key_values'''] a__ ={ '''max_position_embeddings''': '''n_positions''', '''hidden_size''': '''n_embd''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self , A=2_4_6_5_3_4 , A=2_5_6 , A=1_2_8_0 , A=8_1_9_2 , A=4_8 , A=1_6 , A=0.1 , A=0.1 , A=1E-6 , A=0.02 , A=True , **A , ) -> str: _UpperCAmelCase : List[str] = vocab_size _UpperCAmelCase : Dict = n_positions _UpperCAmelCase : Dict = n_embd _UpperCAmelCase : List[Any] = n_layer _UpperCAmelCase : Dict = n_head _UpperCAmelCase : List[str] = dff _UpperCAmelCase : List[str] = resid_pdrop _UpperCAmelCase : int = embd_pdrop _UpperCAmelCase : Dict = layer_norm_epsilon _UpperCAmelCase : Union[str, Any] = initializer_range _UpperCAmelCase : Optional[Any] = use_cache super().__init__(**A )
263
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available _lowerCAmelCase :str = { 'configuration_squeezebert': [ 'SQUEEZEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SqueezeBertConfig', 'SqueezeBertOnnxConfig', ], 'tokenization_squeezebert': ['SqueezeBertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase :Optional[int] = ['SqueezeBertTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase :str = [ 'SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'SqueezeBertForMaskedLM', 'SqueezeBertForMultipleChoice', 'SqueezeBertForQuestionAnswering', 'SqueezeBertForSequenceClassification', 'SqueezeBertForTokenClassification', 'SqueezeBertModel', 'SqueezeBertModule', 'SqueezeBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_squeezebert import ( SQUEEZEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, SqueezeBertConfig, SqueezeBertOnnxConfig, ) from .tokenization_squeezebert import SqueezeBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_squeezebert_fast import SqueezeBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_squeezebert import ( SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, SqueezeBertModel, SqueezeBertModule, SqueezeBertPreTrainedModel, ) else: import sys _lowerCAmelCase :Optional[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
263
1
import builtins import sys from ...utils.imports import _is_package_available from . import cursor, input from .helpers import Direction, clear_line, forceWrite, linebreak, move_cursor, reset_cursor, writeColor from .keymap import KEYMAP UpperCamelCase__ = False try: UpperCamelCase__ = _is_package_available('google.colab') except ModuleNotFoundError: pass @input.register class A : def __init__(self : Dict , __UpperCAmelCase : str = None , __UpperCAmelCase : list = [] ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase__ = 0 UpperCAmelCase__ = choices UpperCAmelCase__ = prompt if sys.platform == "win32": UpperCAmelCase__ = "*" else: UpperCAmelCase__ = "➔ " def lowercase_ (self : Optional[int] , __UpperCAmelCase : Dict , __UpperCAmelCase : str = "" ) -> List[str]: """simple docstring""" if sys.platform != "win32": writeColor(self.choices[index] , 3_2 , __UpperCAmelCase ) else: forceWrite(self.choices[index] , __UpperCAmelCase ) def lowercase_ (self : List[str] , __UpperCAmelCase : int ) -> List[str]: """simple docstring""" if index == self.position: forceWrite(f""" {self.arrow_char} """ ) self.write_choice(__UpperCAmelCase ) else: forceWrite(f""" {self.choices[index]}""" ) reset_cursor() def lowercase_ (self : str , __UpperCAmelCase : Direction , __UpperCAmelCase : int = 1 ) -> Tuple: """simple docstring""" UpperCAmelCase__ = self.position if direction == Direction.DOWN: if self.position + 1 >= len(self.choices ): return self.position += num_spaces else: if self.position - 1 < 0: return self.position -= num_spaces clear_line() self.print_choice(__UpperCAmelCase ) move_cursor(__UpperCAmelCase , direction.name ) self.print_choice(self.position ) @input.mark(KEYMAP["up"] ) def lowercase_ (self : Union[str, Any] ) -> Dict: """simple docstring""" self.move_direction(Direction.UP ) @input.mark(KEYMAP["down"] ) def lowercase_ (self : Tuple ) -> List[Any]: """simple docstring""" self.move_direction(Direction.DOWN ) @input.mark(KEYMAP["newline"] ) def lowercase_ (self : Optional[int] ) -> List[str]: """simple docstring""" move_cursor(len(self.choices ) - self.position , "DOWN" ) return self.position @input.mark(KEYMAP["interrupt"] ) def lowercase_ (self : Dict ) -> List[str]: """simple docstring""" move_cursor(len(self.choices ) - self.position , "DOWN" ) raise KeyboardInterrupt @input.mark_multiple(*[KEYMAP[str(__UpperCAmelCase )] for number in range(1_0 )] ) def lowercase_ (self : Optional[int] ) -> List[Any]: """simple docstring""" UpperCAmelCase__ = int(chr(self.current_selection ) ) UpperCAmelCase__ = index - self.position if index == self.position: return if index < len(self.choices ): if self.position > index: self.move_direction(Direction.UP , -movement ) elif self.position < index: self.move_direction(Direction.DOWN , __UpperCAmelCase ) else: return else: return def lowercase_ (self : str , __UpperCAmelCase : int = 0 ) -> Any: """simple docstring""" if self.prompt: linebreak() forceWrite(self.prompt , "\n" ) if in_colab: forceWrite("Please input a choice index (starting from 0), and press enter" , "\n" ) else: forceWrite("Please select a choice using the arrow or number keys, and selecting with enter" , "\n" ) UpperCAmelCase__ = default_choice for i in range(len(self.choices ) ): self.print_choice(__UpperCAmelCase ) forceWrite("\n" ) move_cursor(len(self.choices ) - self.position , "UP" ) with cursor.hide(): while True: if in_colab: try: UpperCAmelCase__ = int(builtins.input() ) except ValueError: UpperCAmelCase__ = default_choice else: UpperCAmelCase__ = self.handle_input() if choice is not None: reset_cursor() for _ in range(len(self.choices ) + 1 ): move_cursor(1 , "UP" ) clear_line() self.write_choice(__UpperCAmelCase , "\n" ) return choice
143
from typing import TYPE_CHECKING from ...utils import _LazyModule UpperCamelCase__ = {'tokenization_bertweet': ['BertweetTokenizer']} if TYPE_CHECKING: from .tokenization_bertweet import BertweetTokenizer else: import sys UpperCamelCase__ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
143
1
"""simple docstring""" def lowercase ( ) ->Optional[Any]: """simple docstring""" __snake_case : Dict = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] __snake_case : Optional[Any] = 6 __snake_case : Tuple = 1 __snake_case : Tuple = 1_901 __snake_case : Tuple = 0 while year < 2_001: day += 7 if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0): if day > days_per_month[month - 1] and month != 2: month += 1 __snake_case : str = day - days_per_month[month - 2] elif day > 29 and month == 2: month += 1 __snake_case : Optional[Any] = day - 29 else: if day > days_per_month[month - 1]: month += 1 __snake_case : Tuple = day - days_per_month[month - 2] if month > 12: year += 1 __snake_case : Tuple = 1 if year < 2_001 and day == 1: sundays += 1 return sundays if __name__ == "__main__": print(solution())
102
"""simple docstring""" import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from torchvision import transforms from transformers import BitImageProcessor, FocalNetConfig, FocalNetForImageClassification from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, PILImageResampling def lowercase ( _snake_case : Any ) ->Union[str, Any]: """simple docstring""" __snake_case : Tuple = [2, 2, 6, 2] if '''tiny''' in model_name else [2, 2, 18, 2] __snake_case : Dict = True if '''large''' in model_name or '''huge''' in model_name else False __snake_case : Optional[int] = True if '''large''' in model_name or '''huge''' in model_name else False __snake_case : Optional[int] = True if '''large''' in model_name or '''huge''' in model_name else False if "large" in model_name or "xlarge" in model_name or "huge" in model_name: if "fl3" in model_name: __snake_case : Tuple = [3, 3, 3, 3] __snake_case : Dict = [5, 5, 5, 5] elif "fl4" in model_name: __snake_case : Any = [4, 4, 4, 4] __snake_case : List[str] = [3, 3, 3, 3] if "tiny" in model_name or "small" in model_name or "base" in model_name: __snake_case : Optional[int] = [3, 3, 3, 3] if "lrf" in model_name: __snake_case : Any = [3, 3, 3, 3] else: __snake_case : int = [2, 2, 2, 2] if "tiny" in model_name: __snake_case : str = 96 elif "small" in model_name: __snake_case : Optional[int] = 96 elif "base" in model_name: __snake_case : Any = 128 elif "large" in model_name: __snake_case : Optional[Any] = 192 elif "xlarge" in model_name: __snake_case : List[Any] = 256 elif "huge" in model_name: __snake_case : Union[str, Any] = 352 # set label information __snake_case : Union[str, Any] = '''huggingface/label-files''' if "large" in model_name or "huge" in model_name: __snake_case : int = '''imagenet-22k-id2label.json''' else: __snake_case : Optional[Any] = '''imagenet-1k-id2label.json''' __snake_case : int = json.load(open(hf_hub_download(_snake_case , _snake_case , repo_type='''dataset''' ) , '''r''' ) ) __snake_case : Dict = {int(_snake_case ): v for k, v in idalabel.items()} __snake_case : Optional[int] = {v: k for k, v in idalabel.items()} __snake_case : Optional[Any] = FocalNetConfig( embed_dim=_snake_case , depths=_snake_case , focal_levels=_snake_case , focal_windows=_snake_case , use_conv_embed=_snake_case , idalabel=_snake_case , labelaid=_snake_case , use_post_layernorm=_snake_case , use_layerscale=_snake_case , ) return config def lowercase ( _snake_case : Dict ) ->List[Any]: """simple docstring""" if "patch_embed.proj" in name: __snake_case : Tuple = name.replace('''patch_embed.proj''' , '''embeddings.patch_embeddings.projection''' ) if "patch_embed.norm" in name: __snake_case : Tuple = name.replace('''patch_embed.norm''' , '''embeddings.norm''' ) if "layers" in name: __snake_case : List[Any] = '''encoder.''' + name if "encoder.layers" in name: __snake_case : Optional[Any] = name.replace('''encoder.layers''' , '''encoder.stages''' ) if "downsample.proj" in name: __snake_case : Any = name.replace('''downsample.proj''' , '''downsample.projection''' ) if "blocks" in name: __snake_case : List[str] = name.replace('''blocks''' , '''layers''' ) if "modulation.f.weight" in name or "modulation.f.bias" in name: __snake_case : Any = name.replace('''modulation.f''' , '''modulation.projection_in''' ) if "modulation.h.weight" in name or "modulation.h.bias" in name: __snake_case : List[Any] = name.replace('''modulation.h''' , '''modulation.projection_context''' ) if "modulation.proj.weight" in name or "modulation.proj.bias" in name: __snake_case : int = name.replace('''modulation.proj''' , '''modulation.projection_out''' ) if name == "norm.weight": __snake_case : Optional[Any] = '''layernorm.weight''' if name == "norm.bias": __snake_case : List[str] = '''layernorm.bias''' if "head" in name: __snake_case : Union[str, Any] = name.replace('''head''' , '''classifier''' ) else: __snake_case : int = '''focalnet.''' + name return name def lowercase ( _snake_case : Tuple , _snake_case : Dict , _snake_case : List[str]=False ) ->Any: """simple docstring""" __snake_case : List[Any] = { '''focalnet-tiny''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_tiny_srf.pth''', '''focalnet-tiny-lrf''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_tiny_lrf.pth''', '''focalnet-small''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_small_srf.pth''', '''focalnet-small-lrf''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_small_lrf.pth''', '''focalnet-base''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_base_srf.pth''', '''focalnet-base-lrf''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_base_lrf.pth''', '''focalnet-large-lrf-fl3''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_large_lrf_384.pth''', '''focalnet-large-lrf-fl4''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_large_lrf_384_fl4.pth''', '''focalnet-xlarge-lrf-fl3''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_xlarge_lrf_384.pth''', '''focalnet-xlarge-lrf-fl4''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_xlarge_lrf_384_fl4.pth''', } # fmt: on __snake_case : int = model_name_to_url[model_name] print('''Checkpoint URL: ''' , _snake_case ) __snake_case : int = torch.hub.load_state_dict_from_url(_snake_case , map_location='''cpu''' )['''model'''] # rename keys for key in state_dict.copy().keys(): __snake_case : str = state_dict.pop(_snake_case ) __snake_case : Tuple = val __snake_case : Any = get_focalnet_config(_snake_case ) __snake_case : List[Any] = FocalNetForImageClassification(_snake_case ) model.eval() # load state dict model.load_state_dict(_snake_case ) # verify conversion __snake_case : str = '''http://images.cocodataset.org/val2017/000000039769.jpg''' __snake_case : Any = BitImageProcessor( do_resize=_snake_case , size={'''shortest_edge''': 256} , resample=PILImageResampling.BILINEAR , do_center_crop=_snake_case , crop_size=224 , do_normalize=_snake_case , image_mean=_snake_case , image_std=_snake_case , ) __snake_case : List[str] = Image.open(requests.get(_snake_case , stream=_snake_case ).raw ) __snake_case : int = processor(images=_snake_case , return_tensors='''pt''' ) __snake_case : Optional[int] = transforms.Compose( [ transforms.Resize(256 ), transforms.CenterCrop(224 ), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406] , std=[0.229, 0.224, 0.225] ), ] ) __snake_case : Optional[Any] = image_transforms(_snake_case ).unsqueeze(0 ) # verify pixel_values assert torch.allclose(inputs.pixel_values , _snake_case , atol=1e-4 ) __snake_case : Tuple = model(**_snake_case ) __snake_case : str = outputs.logits.argmax(-1 ).item() print('''Predicted class:''' , model.config.idalabel[predicted_class_idx] ) print('''First values of logits:''' , outputs.logits[0, :3] ) if model_name == "focalnet-tiny": __snake_case : Any = torch.tensor([0.2166, -0.4368, 0.2191] ) elif model_name == "focalnet-tiny-lrf": __snake_case : int = torch.tensor([1.1669, 0.0125, -0.1695] ) elif model_name == "focalnet-small": __snake_case : Optional[int] = torch.tensor([0.4917, -0.0430, 0.1341] ) elif model_name == "focalnet-small-lrf": __snake_case : List[Any] = torch.tensor([-0.2588, -0.5342, -0.2331] ) elif model_name == "focalnet-base": __snake_case : Union[str, Any] = torch.tensor([-0.1655, -0.4090, -0.1730] ) elif model_name == "focalnet-base-lrf": __snake_case : List[str] = torch.tensor([0.5306, -0.0483, -0.3928] ) assert torch.allclose(outputs.logits[0, :3] , _snake_case , atol=1e-4 ) print('''Looks ok!''' ) if pytorch_dump_folder_path is not None: print(f"""Saving model and processor of {model_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(_snake_case ) processor.save_pretrained(_snake_case ) if push_to_hub: print(f"""Pushing model and processor of {model_name} to the hub...""" ) model.push_to_hub(f"""{model_name}""" ) processor.push_to_hub(f"""{model_name}""" ) if __name__ == "__main__": SCREAMING_SNAKE_CASE : Any = argparse.ArgumentParser() # Required parameters parser.add_argument( """--model_name""", default="""focalnet-tiny""", type=str, help="""Name of the FocalNet model you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) parser.add_argument( """--push_to_hub""", action="""store_true""", help="""Whether to push the model and processor to the hub.""", ) SCREAMING_SNAKE_CASE : str = parser.parse_args() convert_focalnet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
102
1
import datasets from .nmt_bleu import compute_bleu # From: https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py __lowerCamelCase : Union[str, Any] = """\ @INPROCEEDINGS{Papineni02bleu:a, author = {Kishore Papineni and Salim Roukos and Todd Ward and Wei-jing Zhu}, title = {BLEU: a Method for Automatic Evaluation of Machine Translation}, booktitle = {}, year = {2002}, pages = {311--318} } @inproceedings{lin-och-2004-orange, title = \"{ORANGE}: a Method for Evaluating Automatic Evaluation Metrics for Machine Translation\", author = \"Lin, Chin-Yew and Och, Franz Josef\", booktitle = \"{COLING} 2004: Proceedings of the 20th International Conference on Computational Linguistics\", month = \"aug 23{--}aug 27\", year = \"2004\", address = \"Geneva, Switzerland\", publisher = \"COLING\", url = \"https://www.aclweb.org/anthology/C04-1072\", pages = \"501--507\", } """ __lowerCamelCase : List[Any] = """\ BLEU (bilingual evaluation understudy) is an algorithm for evaluating the quality of text which has been machine-translated from one natural language to another. Quality is considered to be the correspondence between a machine's output and that of a human: \"the closer a machine translation is to a professional human translation, the better it is\" – this is the central idea behind BLEU. BLEU was one of the first metrics to claim a high correlation with human judgements of quality, and remains one of the most popular automated and inexpensive metrics. Scores are calculated for individual translated segments—generally sentences—by comparing them with a set of good quality reference translations. Those scores are then averaged over the whole corpus to reach an estimate of the translation's overall quality. Intelligibility or grammatical correctness are not taken into account[citation needed]. BLEU's output is always a number between 0 and 1. This value indicates how similar the candidate text is to the reference texts, with values closer to 1 representing more similar texts. Few human translations will attain a score of 1, since this would indicate that the candidate is identical to one of the reference translations. For this reason, it is not necessary to attain a score of 1. Because there are more opportunities to match, adding additional reference translations will increase the BLEU score. """ __lowerCamelCase : Dict = """ Computes BLEU score of translated segments against one or more references. Args: predictions: list of translations 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. max_order: Maximum n-gram order to use when computing BLEU score. smooth: Whether or not to apply Lin et al. 2004 smoothing. Returns: 'bleu': bleu score, 'precisions': geometric mean of n-gram precisions, 'brevity_penalty': brevity penalty, 'length_ratio': ratio of lengths, 'translation_length': translation_length, 'reference_length': reference_length Examples: >>> predictions = [ ... [\"hello\", \"there\", \"general\", \"kenobi\"], # tokenized prediction of the first sample ... [\"foo\", \"bar\", \"foobar\"] # tokenized prediction of the second sample ... ] >>> references = [ ... [[\"hello\", \"there\", \"general\", \"kenobi\"], [\"hello\", \"there\", \"!\"]], # tokenized references for the first sample (2 references) ... [[\"foo\", \"bar\", \"foobar\"]] # tokenized references for the second sample (1 reference) ... ] >>> bleu = datasets.load_metric(\"bleu\") >>> results = bleu.compute(predictions=predictions, references=references) >>> print(results[\"bleu\"]) 1.0 """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class SCREAMING_SNAKE_CASE__ ( datasets.Metric ): """simple docstring""" def _lowercase ( self : int ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Sequence(datasets.Value("string" , id="token" ) , id="sequence" ), "references": datasets.Sequence( datasets.Sequence(datasets.Value("string" , id="token" ) , id="sequence" ) , id="references" ), } ) , codebase_urls=["https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py"] , reference_urls=[ "https://en.wikipedia.org/wiki/BLEU", "https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213", ] , ) def _lowercase ( self : Any , __A : List[Any] , __A : Optional[int] , __A : Optional[int]=4 , __A : List[Any]=False ): snake_case__ : Any = compute_bleu( reference_corpus=__A , translation_corpus=__A , max_order=__A , smooth=__A ) ((snake_case__), (snake_case__), (snake_case__), (snake_case__), (snake_case__), (snake_case__)) : Any = score return { "bleu": bleu, "precisions": precisions, "brevity_penalty": bp, "length_ratio": ratio, "translation_length": translation_length, "reference_length": reference_length, }
286
import random import timeit from functools import wraps from typing import Callable, Optional from ..configuration_utils import PretrainedConfig from ..models.auto.modeling_tf_auto import TF_MODEL_MAPPING, TF_MODEL_WITH_LM_HEAD_MAPPING from ..utils import is_pyanvml_available, is_tf_available, logging from .benchmark_utils import ( Benchmark, Memory, MemorySummary, measure_peak_memory_cpu, start_memory_tracing, stop_memory_tracing, ) if is_tf_available(): import tensorflow as tf from tensorflow.python.framework.errors_impl import ResourceExhaustedError from .benchmark_args_tf import TensorFlowBenchmarkArguments if is_pyanvml_available(): import pyanvml.pyanvml as nvml __lowerCamelCase : List[Any] = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE ( snake_case_ : bool , snake_case_ : bool ): def run_func(snake_case_ : str ): @wraps(snake_case_ ) def run_in_eager_mode(*snake_case_ : str , **snake_case_ : Union[str, Any] ): return func(*snake_case_ , **snake_case_ ) @wraps(snake_case_ ) @tf.function(experimental_compile=snake_case_ ) def run_in_graph_mode(*snake_case_ : List[Any] , **snake_case_ : List[Any] ): return func(*snake_case_ , **snake_case_ ) if do_eager_mode is True: if use_xla is not False: raise ValueError( "Cannot run model in XLA, if `args.eager_mode` is set to `True`. Please set `args.eager_mode=False`." ) return run_in_eager_mode else: return run_in_graph_mode return run_func def SCREAMING_SNAKE_CASE ( snake_case_ : int , snake_case_ : int , snake_case_ : int ): snake_case__ : Dict = random.Random() snake_case__ : List[Any] = [rng.randint(0 , vocab_size - 1 ) for i in range(batch_size * sequence_length )] return tf.constant(snake_case_ , shape=(batch_size, sequence_length) , dtype=tf.intaa ) class SCREAMING_SNAKE_CASE__ ( UpperCamelCase_ ): """simple docstring""" a_ = 42 a_ = 42 a_ = "TensorFlow" @property def _lowercase ( self : List[str] ): return tf.__version__ def _lowercase ( self : List[str] , __A : str , __A : int , __A : int ): # initialize GPU on separate process snake_case__ : str = self.args.strategy if strategy is None: raise ValueError("A device strategy has to be initialized before using TensorFlow." ) snake_case__ : Dict = self._prepare_inference_func(__A , __A , __A ) return self._measure_speed(_inference ) def _lowercase ( self : Tuple , __A : str , __A : int , __A : int ): snake_case__ : Optional[int] = self.args.strategy if strategy is None: raise ValueError("A device strategy has to be initialized before using TensorFlow." ) snake_case__ : Any = self._prepare_train_func(__A , __A , __A ) return self._measure_speed(_train ) def _lowercase ( self : List[Any] , __A : str , __A : int , __A : int ): # initialize GPU on separate process if self.args.is_gpu: tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx] , __A ) snake_case__ : List[str] = self.args.strategy if strategy is None: raise ValueError("A device strategy has to be initialized before using TensorFlow." ) snake_case__ : Optional[Any] = self._prepare_inference_func(__A , __A , __A ) return self._measure_memory(_inference ) def _lowercase ( self : str , __A : str , __A : int , __A : int ): if self.args.is_gpu: tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx] , __A ) snake_case__ : List[Any] = self.args.strategy if strategy is None: raise ValueError("A device strategy has to be initialized before using TensorFlow." ) snake_case__ : int = self._prepare_train_func(__A , __A , __A ) return self._measure_memory(_train ) def _lowercase ( self : Union[str, Any] , __A : str , __A : int , __A : int ): snake_case__ : int = self.config_dict[model_name] if self.args.fpaa: raise NotImplementedError("Mixed precision is currently not supported." ) snake_case__ : Tuple = ( hasattr(__A , "architectures" ) and isinstance(config.architectures , __A ) and len(config.architectures ) > 0 ) if not self.args.only_pretrain_model and has_model_class_in_config: try: snake_case__ : Dict = "TF" + config.architectures[0] # prepend 'TF' for tensorflow model snake_case__ : Union[str, Any] = __import__("transformers" , fromlist=[model_class] ) snake_case__ : Any = getattr(__A , __A ) snake_case__ : Dict = model_cls(__A ) except ImportError: raise ImportError( f'''{model_class} does not exist. If you just want to test the pretrained model, you might want to''' " set `--only_pretrain_model` or `args.only_pretrain_model=True`." ) else: snake_case__ : Dict = TF_MODEL_MAPPING[config.__class__](__A ) # encoder-decoder has vocab size saved differently snake_case__ : Optional[int] = config.vocab_size if hasattr(__A , "vocab_size" ) else config.encoder.vocab_size snake_case__ : List[Any] = random_input_ids(__A , __A , __A ) @run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla ) def encoder_decoder_forward(): return model(__A , decoder_input_ids=__A , training=__A ) @run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla ) def encoder_forward(): return model(__A , training=__A ) snake_case__ : Optional[int] = encoder_decoder_forward if config.is_encoder_decoder else encoder_forward return _inference def _lowercase ( self : List[str] , __A : str , __A : int , __A : int ): snake_case__ : Optional[Any] = self.config_dict[model_name] if self.args.eager_mode is not False: raise ValueError("Training cannot be done in eager mode. Please make sure that `args.eager_mode = False`." ) if self.args.fpaa: raise NotImplementedError("Mixed precision is currently not supported." ) snake_case__ : Any = ( hasattr(__A , "architectures" ) and isinstance(config.architectures , __A ) and len(config.architectures ) > 0 ) if not self.args.only_pretrain_model and has_model_class_in_config: try: snake_case__ : Dict = "TF" + config.architectures[0] # prepend 'TF' for tensorflow model snake_case__ : List[Any] = __import__("transformers" , fromlist=[model_class] ) snake_case__ : Optional[int] = getattr(__A , __A ) snake_case__ : str = model_cls(__A ) except ImportError: raise ImportError( f'''{model_class} does not exist. If you just want to test the pretrained model, you might want to''' " set `--only_pretrain_model` or `args.only_pretrain_model=True`." ) else: snake_case__ : Union[str, Any] = TF_MODEL_WITH_LM_HEAD_MAPPING[config.__class__](__A ) # encoder-decoder has vocab size saved differently snake_case__ : Union[str, Any] = config.vocab_size if hasattr(__A , "vocab_size" ) else config.encoder.vocab_size snake_case__ : List[str] = random_input_ids(__A , __A , __A ) @run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla ) def encoder_decoder_train(): snake_case__ : str = model(__A , decoder_input_ids=__A , labels=__A , training=__A )[0] snake_case__ : Dict = tf.gradients(__A , model.trainable_variables ) return gradients @run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla ) def encoder_train(): snake_case__ : Optional[Any] = model(__A , labels=__A , training=__A )[0] snake_case__ : Dict = tf.gradients(__A , model.trainable_variables ) return gradients snake_case__ : int = encoder_decoder_train if config.is_encoder_decoder else encoder_train return _train def _lowercase ( self : int , __A : List[Any] ): with self.args.strategy.scope(): try: if self.args.is_tpu or self.args.use_xla: # run additional 10 times to stabilize compilation for tpu logger.info("Do inference on TPU. Running model 5 times to stabilize compilation" ) timeit.repeat(__A , repeat=1 , number=5 ) # as written in https://docs.python.org/2/library/timeit.html#timeit.Timer.repeat, min should be taken rather than the average snake_case__ : Optional[Any] = timeit.repeat( __A , repeat=self.args.repeat , number=1_0 , ) return min(__A ) / 1_0.0 except ResourceExhaustedError as e: self.print_fn(f'''Doesn\'t fit on GPU. {e}''' ) def _lowercase ( self : str , __A : Callable[[], None] ): logger.info( "Note that TensorFlow allocates more memory than " "it might need to speed up computation. " "The memory reported here corresponds to the memory " "reported by `nvidia-smi`, which can vary depending " "on total available memory on the GPU that is used." ) with self.args.strategy.scope(): try: if self.args.trace_memory_line_by_line: if not self.args.eager_mode: raise ValueError( "`args.eager_mode` is set to `False`. Make sure to run model in eager mode to measure memory" " consumption line by line." ) snake_case__ : Optional[int] = start_memory_tracing("transformers" ) if self.args.is_tpu: # tpu raise NotImplementedError( "Memory Benchmarking is currently not implemented for TPU. Please disable memory benchmarking" " with `args.memory=False`" ) elif self.args.is_gpu: # gpu if not is_pyanvml_available(): logger.warning( "py3nvml not installed, we won't log GPU memory usage. " "Install py3nvml (pip install py3nvml) to log information about GPU." ) snake_case__ : List[str] = "N/A" else: logger.info( "Measuring total GPU usage on GPU device. Make sure to not have additional processes" " running on the same GPU." ) # init nvml nvml.nvmlInit() func() snake_case__ : Any = nvml.nvmlDeviceGetHandleByIndex(self.args.device_idx ) snake_case__ : Optional[Any] = nvml.nvmlDeviceGetMemoryInfo(__A ) snake_case__ : Optional[int] = meminfo.used snake_case__ : Any = Memory(__A ) # shutdown nvml nvml.nvmlShutdown() else: # cpu if self.args.trace_memory_line_by_line: logger.info( "When enabling line by line tracing, the max peak memory for CPU is inaccurate in" " TensorFlow." ) snake_case__ : int = None else: snake_case__ : Any = measure_peak_memory_cpu(__A ) snake_case__ : Tuple = Memory(__A ) if isinstance(__A , __A ) else memory_bytes if self.args.trace_memory_line_by_line: snake_case__ : Optional[int] = stop_memory_tracing(__A ) if memory is None: snake_case__ : Dict = summary.total else: snake_case__ : List[str] = None return memory, summary except ResourceExhaustedError as e: self.print_fn(f'''Doesn\'t fit on GPU. {e}''' ) return "N/A", None
286
1
import torch from diffusers import DDPMScheduler from .test_schedulers import SchedulerCommonTest class __A( a ): snake_case_ = (DDPMScheduler,) def SCREAMING_SNAKE_CASE_ ( self , **_snake_case ) -> Any: '''simple docstring''' __a = { '''num_train_timesteps''': 1_000, '''beta_start''': 0.0001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', '''variance_type''': '''fixed_small''', '''clip_sample''': True, } config.update(**_snake_case ) return config def SCREAMING_SNAKE_CASE_ ( self ) -> List[Any]: '''simple docstring''' for timesteps in [1, 5, 100, 1_000]: self.check_over_configs(num_train_timesteps=_snake_case ) def SCREAMING_SNAKE_CASE_ ( self ) -> Tuple: '''simple docstring''' for beta_start, beta_end in zip([0.0001, 0.001, 0.01, 0.1] , [0.002, 0.02, 0.2, 2] ): self.check_over_configs(beta_start=_snake_case , beta_end=_snake_case ) def SCREAMING_SNAKE_CASE_ ( self ) -> str: '''simple docstring''' for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=_snake_case ) def SCREAMING_SNAKE_CASE_ ( self ) -> Tuple: '''simple docstring''' for variance in ["fixed_small", "fixed_large", "other"]: self.check_over_configs(variance_type=_snake_case ) def SCREAMING_SNAKE_CASE_ ( self ) -> Optional[Any]: '''simple docstring''' for clip_sample in [True, False]: self.check_over_configs(clip_sample=_snake_case ) def SCREAMING_SNAKE_CASE_ ( self ) -> int: '''simple docstring''' self.check_over_configs(thresholding=_snake_case ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs( thresholding=_snake_case , prediction_type=_snake_case , sample_max_value=_snake_case , ) def SCREAMING_SNAKE_CASE_ ( self ) -> Dict: '''simple docstring''' for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs(prediction_type=_snake_case ) def SCREAMING_SNAKE_CASE_ ( self ) -> str: '''simple docstring''' for t in [0, 500, 999]: self.check_over_forward(time_step=_snake_case ) def SCREAMING_SNAKE_CASE_ ( self ) -> Tuple: '''simple docstring''' __a = self.scheduler_classes[0] __a = self.get_scheduler_config() __a = scheduler_class(**_snake_case ) assert torch.sum(torch.abs(scheduler._get_variance(0 ) - 0.0 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(487 ) - 0.0_0979 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(999 ) - 0.02 ) ) < 1E-5 def SCREAMING_SNAKE_CASE_ ( self ) -> Optional[Any]: '''simple docstring''' __a = self.scheduler_classes[0] __a = self.get_scheduler_config() __a = scheduler_class(**_snake_case ) __a = len(_snake_case ) __a = self.dummy_model() __a = self.dummy_sample_deter __a = torch.manual_seed(0 ) for t in reversed(range(_snake_case ) ): # 1. predict noise residual __a = model(_snake_case , _snake_case ) # 2. predict previous mean of sample x_t-1 __a = scheduler.step(_snake_case , _snake_case , _snake_case , generator=_snake_case ).prev_sample # if t > 0: # noise = self.dummy_sample_deter # variance = scheduler.get_variance(t) ** (0.5) * noise # # sample = pred_prev_sample + variance __a = pred_prev_sample __a = torch.sum(torch.abs(_snake_case ) ) __a = torch.mean(torch.abs(_snake_case ) ) assert abs(result_sum.item() - 258.9606 ) < 1E-2 assert abs(result_mean.item() - 0.3372 ) < 1E-3 def SCREAMING_SNAKE_CASE_ ( self ) -> Optional[int]: '''simple docstring''' __a = self.scheduler_classes[0] __a = self.get_scheduler_config(prediction_type='''v_prediction''' ) __a = scheduler_class(**_snake_case ) __a = len(_snake_case ) __a = self.dummy_model() __a = self.dummy_sample_deter __a = torch.manual_seed(0 ) for t in reversed(range(_snake_case ) ): # 1. predict noise residual __a = model(_snake_case , _snake_case ) # 2. predict previous mean of sample x_t-1 __a = scheduler.step(_snake_case , _snake_case , _snake_case , generator=_snake_case ).prev_sample # if t > 0: # noise = self.dummy_sample_deter # variance = scheduler.get_variance(t) ** (0.5) * noise # # sample = pred_prev_sample + variance __a = pred_prev_sample __a = torch.sum(torch.abs(_snake_case ) ) __a = torch.mean(torch.abs(_snake_case ) ) assert abs(result_sum.item() - 202.0296 ) < 1E-2 assert abs(result_mean.item() - 0.2631 ) < 1E-3 def SCREAMING_SNAKE_CASE_ ( self ) -> Optional[Any]: '''simple docstring''' __a = self.scheduler_classes[0] __a = self.get_scheduler_config() __a = scheduler_class(**_snake_case ) __a = [100, 87, 50, 1, 0] scheduler.set_timesteps(timesteps=_snake_case ) __a = scheduler.timesteps for i, timestep in enumerate(_snake_case ): if i == len(_snake_case ) - 1: __a = -1 else: __a = timesteps[i + 1] __a = scheduler.previous_timestep(_snake_case ) __a = prev_t.item() self.assertEqual(_snake_case , _snake_case ) def SCREAMING_SNAKE_CASE_ ( self ) -> List[Any]: '''simple docstring''' __a = self.scheduler_classes[0] __a = self.get_scheduler_config() __a = scheduler_class(**_snake_case ) __a = [100, 87, 50, 51, 0] with self.assertRaises(_snake_case , msg='''`custom_timesteps` must be in descending order.''' ): scheduler.set_timesteps(timesteps=_snake_case ) def SCREAMING_SNAKE_CASE_ ( self ) -> Union[str, Any]: '''simple docstring''' __a = self.scheduler_classes[0] __a = self.get_scheduler_config() __a = scheduler_class(**_snake_case ) __a = [100, 87, 50, 1, 0] __a = len(_snake_case ) with self.assertRaises(_snake_case , msg='''Can only pass one of `num_inference_steps` or `custom_timesteps`.''' ): scheduler.set_timesteps(num_inference_steps=_snake_case , timesteps=_snake_case ) def SCREAMING_SNAKE_CASE_ ( self ) -> Dict: '''simple docstring''' __a = self.scheduler_classes[0] __a = self.get_scheduler_config() __a = scheduler_class(**_snake_case ) __a = [scheduler.config.num_train_timesteps] with self.assertRaises( _snake_case , msg='''`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}''' , ): scheduler.set_timesteps(timesteps=_snake_case )
6
def __lowerCAmelCase ( a__ , a__ , a__ ) -> list: __a = len(a__ ) __a = [[0] * n for i in range(a__ )] for i in range(a__ ): __a = y_points[i] for i in range(2 , a__ ): for j in range(a__ , a__ ): __a = ( (xa - x_points[j - i + 1]) * q[j][i - 1] - (xa - x_points[j]) * q[j - 1][i - 1] ) / (x_points[j] - x_points[j - i + 1]) return [q[n - 1][n - 1], q] if __name__ == "__main__": import doctest doctest.testmod()
6
1
import warnings from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast from ...onnx.utils import compute_effective_axis_dimension from ...utils import TensorType, is_torch_available, logging _lowerCAmelCase : Union[str, Any] = logging.get_logger(__name__) _lowerCAmelCase : List[Any] = { '''facebook/bart-large''': '''https://huggingface.co/facebook/bart-large/resolve/main/config.json''', # See all BART models at https://huggingface.co/models?filter=bart } class __magic_name__ ( lowerCamelCase__ ): """simple docstring""" __UpperCamelCase = '''bart''' __UpperCamelCase = ['''past_key_values'''] __UpperCamelCase = {'''num_attention_heads''': '''encoder_attention_heads''', '''hidden_size''': '''d_model'''} def __init__( self :Optional[int] , snake_case :Tuple=50_265 , snake_case :Dict=1_024 , snake_case :List[Any]=12 , snake_case :Union[str, Any]=4_096 , snake_case :Optional[int]=16 , snake_case :Any=12 , snake_case :Dict=4_096 , snake_case :List[str]=16 , snake_case :Tuple=0.0 , snake_case :Union[str, Any]=0.0 , snake_case :List[str]="gelu" , snake_case :List[str]=1_024 , snake_case :Dict=0.1 , snake_case :List[Any]=0.0 , snake_case :Tuple=0.0 , snake_case :str=0.02 , snake_case :Optional[int]=0.0 , snake_case :Dict=False , snake_case :Dict=True , snake_case :Tuple=3 , snake_case :List[str]=1 , snake_case :List[str]=0 , snake_case :Union[str, Any]=2 , snake_case :List[Any]=True , snake_case :Dict=2 , snake_case :int=2 , **snake_case :str , ): '''simple docstring''' A_ : Dict = vocab_size A_ : List[Any] = max_position_embeddings A_ : Any = d_model A_ : List[Any] = encoder_ffn_dim A_ : str = encoder_layers A_ : int = encoder_attention_heads A_ : int = decoder_ffn_dim A_ : Union[str, Any] = decoder_layers A_ : List[Any] = decoder_attention_heads A_ : List[Any] = dropout A_ : List[Any] = attention_dropout A_ : List[str] = activation_dropout A_ : List[Any] = activation_function A_ : Dict = init_std A_ : Optional[Any] = encoder_layerdrop A_ : Union[str, Any] = decoder_layerdrop A_ : str = classifier_dropout A_ : Optional[Any] = use_cache A_ : Tuple = encoder_layers A_ : Tuple = scale_embedding # scale factor will be sqrt(d_model) if True super().__init__( num_labels=snake_case , pad_token_id=snake_case , bos_token_id=snake_case , eos_token_id=snake_case , is_encoder_decoder=snake_case , decoder_start_token_id=snake_case , forced_eos_token_id=snake_case , **snake_case , ) # ensure backward compatibility for BART CNN models if self.forced_bos_token_id is None and kwargs.get("force_bos_token_to_be_generated" , snake_case ): A_ : str = self.bos_token_id warnings.warn( f"Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions. " "The config can simply be saved and uploaded again to be fixed." ) class __magic_name__ ( lowerCamelCase__ ): """simple docstring""" @property def SCREAMING_SNAKE_CASE ( self :int ): '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: A_ : int = OrderedDict( [ ("input_ids", {0: "batch", 1: "encoder_sequence"}), ("attention_mask", {0: "batch", 1: "encoder_sequence"}), ] ) if self.use_past: A_ : Optional[Any] = {0: "batch"} A_ : str = {0: "batch", 1: "past_decoder_sequence + sequence"} else: A_ : Tuple = {0: "batch", 1: "decoder_sequence"} A_ : Any = {0: "batch", 1: "decoder_sequence"} if self.use_past: self.fill_with_past_key_values_(snake_case , direction="inputs" ) elif self.task == "causal-lm": # TODO: figure this case out. A_ : Dict = OrderedDict( [ ("input_ids", {0: "batch", 1: "encoder_sequence"}), ("attention_mask", {0: "batch", 1: "encoder_sequence"}), ] ) if self.use_past: A_ : int = self.num_layers for i in range(snake_case ): A_ : Union[str, Any] = {0: "batch", 2: "past_sequence + sequence"} A_ : Any = {0: "batch", 2: "past_sequence + sequence"} else: A_ : int = OrderedDict( [ ("input_ids", {0: "batch", 1: "encoder_sequence"}), ("attention_mask", {0: "batch", 1: "encoder_sequence"}), ("decoder_input_ids", {0: "batch", 1: "decoder_sequence"}), ("decoder_attention_mask", {0: "batch", 1: "decoder_sequence"}), ] ) return common_inputs @property def SCREAMING_SNAKE_CASE ( self :str ): '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: A_ : Optional[Any] = super().outputs else: A_ : Union[str, Any] = super(snake_case , self ).outputs if self.use_past: A_ : List[str] = self.num_layers for i in range(snake_case ): A_ : Dict = {0: "batch", 2: "past_sequence + sequence"} A_ : Optional[Any] = {0: "batch", 2: "past_sequence + sequence"} return common_outputs def SCREAMING_SNAKE_CASE ( self :int , snake_case :PreTrainedTokenizer , snake_case :int = -1 , snake_case :int = -1 , snake_case :bool = False , snake_case :Optional[TensorType] = None , ): '''simple docstring''' A_ : Any = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( snake_case , snake_case , snake_case , snake_case , snake_case ) # Generate decoder inputs A_ : Tuple = seq_length if not self.use_past else 1 A_ : str = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( snake_case , snake_case , snake_case , snake_case , snake_case ) A_ : Tuple = {f"decoder_{name}": tensor for name, tensor in decoder_inputs.items()} A_ : Union[str, Any] = dict(**snake_case , **snake_case ) if self.use_past: if not is_torch_available(): raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed." ) else: import torch A_ : Tuple = common_inputs["input_ids"].shape A_ : List[Any] = common_inputs["decoder_input_ids"].shape[1] A_ : List[Any] = self.num_attention_heads A_ : List[Any] = ( batch, num_encoder_attention_heads, encoder_seq_length, self._config.hidden_size // num_encoder_attention_heads, ) A_ : List[str] = decoder_seq_length + 3 A_ : Any = ( batch, num_decoder_attention_heads, decoder_past_length, self._config.hidden_size // num_decoder_attention_heads, ) A_ : Tuple = torch.cat( [common_inputs["decoder_attention_mask"], torch.ones(snake_case , snake_case )] , dim=1 ) A_ : Optional[int] = [] # If the number of encoder and decoder layers are present in the model configuration, both are considered A_ : Optional[int] = self.num_layers A_ : Union[str, Any] = min(snake_case , snake_case ) A_ : int = max(snake_case , snake_case ) - min_num_layers A_ : Dict = "encoder" if num_encoder_layers > num_decoder_layers else "decoder" for _ in range(snake_case ): common_inputs["past_key_values"].append( ( torch.zeros(snake_case ), torch.zeros(snake_case ), torch.zeros(snake_case ), torch.zeros(snake_case ), ) ) # TODO: test this. A_ : Optional[int] = encoder_shape if remaining_side_name == "encoder" else decoder_shape for _ in range(snake_case , snake_case ): common_inputs["past_key_values"].append((torch.zeros(snake_case ), torch.zeros(snake_case )) ) return common_inputs def SCREAMING_SNAKE_CASE ( self :int , snake_case :PreTrainedTokenizer , snake_case :int = -1 , snake_case :int = -1 , snake_case :bool = False , snake_case :Optional[TensorType] = None , ): '''simple docstring''' A_ : Dict = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( snake_case , snake_case , snake_case , snake_case , snake_case ) if self.use_past: if not is_torch_available(): raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed." ) else: import torch A_ : Optional[Any] = common_inputs["input_ids"].shape # Not using the same length for past_key_values A_ : Tuple = seqlen + 2 A_ : Optional[Any] = self.num_layers A_ : Tuple = self.num_attention_heads A_ : int = ( batch, num_encoder_attention_heads, past_key_values_length, self._config.hidden_size // num_encoder_attention_heads, ) A_ : Dict = common_inputs["attention_mask"].dtype A_ : int = torch.cat( [common_inputs["attention_mask"], torch.ones(snake_case , snake_case , dtype=snake_case )] , dim=1 ) A_ : str = [ (torch.zeros(snake_case ), torch.zeros(snake_case )) for _ in range(snake_case ) ] return common_inputs def SCREAMING_SNAKE_CASE ( self :Union[str, Any] , snake_case :PreTrainedTokenizer , snake_case :int = -1 , snake_case :int = -1 , snake_case :bool = False , snake_case :Optional[TensorType] = None , ): '''simple docstring''' A_ : Union[str, Any] = compute_effective_axis_dimension( snake_case , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX A_ : Any = tokenizer.num_special_tokens_to_add(snake_case ) A_ : Optional[int] = compute_effective_axis_dimension( snake_case , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=snake_case ) # Generate dummy inputs according to compute batch and sequence A_ : Union[str, Any] = [" ".join([tokenizer.unk_token] ) * seq_length] * batch_size A_ : List[Any] = dict(tokenizer(snake_case , return_tensors=snake_case ) ) return common_inputs def SCREAMING_SNAKE_CASE ( self :Optional[Any] , snake_case :PreTrainedTokenizer , snake_case :int = -1 , snake_case :int = -1 , snake_case :bool = False , snake_case :Optional[TensorType] = None , ): '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: A_ : Optional[Any] = self._generate_dummy_inputs_for_default_and_seqaseq_lm( snake_case , batch_size=snake_case , seq_length=snake_case , is_pair=snake_case , framework=snake_case ) elif self.task == "causal-lm": A_ : Any = self._generate_dummy_inputs_for_causal_lm( snake_case , batch_size=snake_case , seq_length=snake_case , is_pair=snake_case , framework=snake_case ) else: A_ : List[Any] = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( snake_case , batch_size=snake_case , seq_length=snake_case , is_pair=snake_case , framework=snake_case ) return common_inputs def SCREAMING_SNAKE_CASE ( self :Tuple , snake_case :List[str] , snake_case :Optional[Any] , snake_case :int , snake_case :Dict ): '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: A_ : Dict = super()._flatten_past_key_values_(snake_case , snake_case , snake_case , snake_case ) else: A_ : List[str] = super(snake_case , self )._flatten_past_key_values_( snake_case , snake_case , snake_case , snake_case )
365
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) _lowerCAmelCase : List[Any] = { '''configuration_funnel''': ['''FUNNEL_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''FunnelConfig'''], '''convert_funnel_original_tf_checkpoint_to_pytorch''': [], '''tokenization_funnel''': ['''FunnelTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase : Any = ['''FunnelTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase : Tuple = [ '''FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST''', '''FunnelBaseModel''', '''FunnelForMaskedLM''', '''FunnelForMultipleChoice''', '''FunnelForPreTraining''', '''FunnelForQuestionAnswering''', '''FunnelForSequenceClassification''', '''FunnelForTokenClassification''', '''FunnelModel''', '''FunnelPreTrainedModel''', '''load_tf_weights_in_funnel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase : int = [ '''TF_FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFFunnelBaseModel''', '''TFFunnelForMaskedLM''', '''TFFunnelForMultipleChoice''', '''TFFunnelForPreTraining''', '''TFFunnelForQuestionAnswering''', '''TFFunnelForSequenceClassification''', '''TFFunnelForTokenClassification''', '''TFFunnelModel''', '''TFFunnelPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_funnel import FUNNEL_PRETRAINED_CONFIG_ARCHIVE_MAP, FunnelConfig from .tokenization_funnel import FunnelTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_funnel_fast import FunnelTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_funnel import ( FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST, FunnelBaseModel, FunnelForMaskedLM, FunnelForMultipleChoice, FunnelForPreTraining, FunnelForQuestionAnswering, FunnelForSequenceClassification, FunnelForTokenClassification, FunnelModel, FunnelPreTrainedModel, load_tf_weights_in_funnel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_funnel import ( TF_FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST, TFFunnelBaseModel, TFFunnelForMaskedLM, TFFunnelForMultipleChoice, TFFunnelForPreTraining, TFFunnelForQuestionAnswering, TFFunnelForSequenceClassification, TFFunnelForTokenClassification, TFFunnelModel, TFFunnelPreTrainedModel, ) else: import sys _lowerCAmelCase : Union[str, Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
70
0
"""simple docstring""" import argparse import os import sys from unittest.mock import patch import pytorch_lightning as pl import timeout_decorator import torch from distillation import SummarizationDistiller, distill_main from finetune import SummarizationModule, main from transformers import MarianMTModel from transformers.file_utils import cached_path from transformers.testing_utils import TestCasePlus, require_torch_gpu, slow from utils import load_json __UpperCAmelCase = 'sshleifer/mar_enro_6_3_student' class _SCREAMING_SNAKE_CASE ( A__ ): def __lowerCAmelCase ( self ) -> Optional[Any]: super().setUp() lowerCAmelCase_ :int = cached_path( """https://cdn-datasets.huggingface.co/translation/wmt_en_ro-tr40k-va0.5k-te0.5k.tar.gz""" , extract_compressed_file=__A , ) lowerCAmelCase_ :str = f"""{data_cached}/wmt_en_ro-tr40k-va0.5k-te0.5k""" @slow @require_torch_gpu def __lowerCAmelCase ( self ) -> Any: MarianMTModel.from_pretrained(__A ) @slow @require_torch_gpu def __lowerCAmelCase ( self ) -> Optional[Any]: lowerCAmelCase_ :str = { """$MAX_LEN""": 64, """$BS""": 64, """$GAS""": 1, """$ENRO_DIR""": self.data_dir, """facebook/mbart-large-cc25""": MARIAN_MODEL, # "val_check_interval=0.25": "val_check_interval=1.0", """--learning_rate=3e-5""": """--learning_rate 3e-4""", """--num_train_epochs 6""": """--num_train_epochs 1""", } # Clean up bash script lowerCAmelCase_ :int = (self.test_file_dir / """train_mbart_cc25_enro.sh""").open().read().split("""finetune.py""" )[1].strip() lowerCAmelCase_ :Tuple = bash_script.replace("""\\\n""" , """""" ).strip().replace("""\"$@\"""" , """""" ) for k, v in env_vars_to_replace.items(): lowerCAmelCase_ :List[Any] = bash_script.replace(__A , str(__A ) ) lowerCAmelCase_ :Any = self.get_auto_remove_tmp_dir() # bash_script = bash_script.replace("--fp16 ", "") lowerCAmelCase_ :Union[str, Any] = f""" --output_dir {output_dir} --tokenizer_name Helsinki-NLP/opus-mt-en-ro --sortish_sampler --do_predict --gpus 1 --freeze_encoder --n_train 40000 --n_val 500 --n_test 500 --fp16_opt_level O1 --num_sanity_val_steps 0 --eval_beams 2 """.split() # XXX: args.gpus > 1 : handle multi_gpu in the future lowerCAmelCase_ :Any = ["""finetune.py"""] + bash_script.split() + args with patch.object(__A , """argv""" , __A ): lowerCAmelCase_ :Optional[int] = argparse.ArgumentParser() lowerCAmelCase_ :str = pl.Trainer.add_argparse_args(__A ) lowerCAmelCase_ :Any = SummarizationModule.add_model_specific_args(__A , os.getcwd() ) lowerCAmelCase_ :List[Any] = parser.parse_args() lowerCAmelCase_ :Any = main(__A ) # Check metrics lowerCAmelCase_ :Tuple = load_json(model.metrics_save_path ) lowerCAmelCase_ :Union[str, Any] = metrics["""val"""][0] lowerCAmelCase_ :Any = metrics["""val"""][-1] self.assertEqual(len(metrics["""val"""] ) , (args.max_epochs / args.val_check_interval) ) assert isinstance(last_step_stats[f"""val_avg_{model.val_metric}"""] , __A ) self.assertGreater(last_step_stats["""val_avg_gen_time"""] , 0.0_1 ) # model hanging on generate. Maybe bad config was saved. (XXX: old comment/assert?) self.assertLessEqual(last_step_stats["""val_avg_gen_time"""] , 1.0 ) # test learning requirements: # 1. BLEU improves over the course of training by more than 2 pts self.assertGreater(last_step_stats["""val_avg_bleu"""] - first_step_stats["""val_avg_bleu"""] , 2 ) # 2. BLEU finishes above 17 self.assertGreater(last_step_stats["""val_avg_bleu"""] , 17 ) # 3. test BLEU and val BLEU within ~1.1 pt. self.assertLess(abs(metrics["""val"""][-1]["""val_avg_bleu"""] - metrics["""test"""][-1]["""test_avg_bleu"""] ) , 1.1 ) # check lightning ckpt can be loaded and has a reasonable statedict lowerCAmelCase_ :Optional[Any] = os.listdir(__A ) lowerCAmelCase_ :Any = [x for x in contents if x.endswith(""".ckpt""" )][0] lowerCAmelCase_ :int = os.path.join(args.output_dir , __A ) lowerCAmelCase_ :str = torch.load(__A , map_location="""cpu""" ) lowerCAmelCase_ :Union[str, Any] = """model.model.decoder.layers.0.encoder_attn_layer_norm.weight""" assert expected_key in ckpt["state_dict"] assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa # TODO: turn on args.do_predict when PL bug fixed. if args.do_predict: lowerCAmelCase_ :int = {os.path.basename(__A ) for p in contents} assert "test_generations.txt" in contents assert "test_results.txt" in contents # assert len(metrics["val"]) == desired_n_evals assert len(metrics["""test"""] ) == 1 class _SCREAMING_SNAKE_CASE ( A__ ): @timeout_decorator.timeout(600 ) @slow @require_torch_gpu def __lowerCAmelCase ( self ) -> int: lowerCAmelCase_ :Dict = f"""{self.test_file_dir_str}/test_data/wmt_en_ro""" lowerCAmelCase_ :Any = { """--fp16_opt_level=O1""": """""", """$MAX_LEN""": 128, """$BS""": 16, """$GAS""": 1, """$ENRO_DIR""": data_dir, """$m""": """sshleifer/student_marian_en_ro_6_1""", """val_check_interval=0.25""": """val_check_interval=1.0""", } # Clean up bash script lowerCAmelCase_ :Dict = ( (self.test_file_dir / """distil_marian_no_teacher.sh""").open().read().split("""distillation.py""" )[1].strip() ) lowerCAmelCase_ :str = bash_script.replace("""\\\n""" , """""" ).strip().replace("""\"$@\"""" , """""" ) lowerCAmelCase_ :Optional[Any] = bash_script.replace("""--fp16 """ , """ """ ) for k, v in env_vars_to_replace.items(): lowerCAmelCase_ :str = bash_script.replace(__A , str(__A ) ) lowerCAmelCase_ :Dict = self.get_auto_remove_tmp_dir() lowerCAmelCase_ :List[Any] = bash_script.replace("""--fp16""" , """""" ) lowerCAmelCase_ :Dict = 6 lowerCAmelCase_ :Any = ( ["""distillation.py"""] + bash_script.split() + [ f"""--output_dir={output_dir}""", """--gpus=1""", """--learning_rate=1e-3""", f"""--num_train_epochs={epochs}""", """--warmup_steps=10""", """--val_check_interval=1.0""", """--do_predict""", ] ) with patch.object(__A , """argv""" , __A ): lowerCAmelCase_ :Dict = argparse.ArgumentParser() lowerCAmelCase_ :int = pl.Trainer.add_argparse_args(__A ) lowerCAmelCase_ :int = SummarizationDistiller.add_model_specific_args(__A , os.getcwd() ) lowerCAmelCase_ :Any = parser.parse_args() # assert args.gpus == gpus THIS BREAKS for multi_gpu lowerCAmelCase_ :Optional[Any] = distill_main(__A ) # Check metrics lowerCAmelCase_ :Union[str, Any] = load_json(model.metrics_save_path ) lowerCAmelCase_ :List[Any] = metrics["""val"""][0] lowerCAmelCase_ :str = metrics["""val"""][-1] assert len(metrics["""val"""] ) >= (args.max_epochs / args.val_check_interval) # +1 accounts for val_sanity_check assert last_step_stats["val_avg_gen_time"] >= 0.0_1 assert first_step_stats["val_avg_bleu"] < last_step_stats["val_avg_bleu"] # model learned nothing assert 1.0 >= last_step_stats["val_avg_gen_time"] # model hanging on generate. Maybe bad config was saved. assert isinstance(last_step_stats[f"""val_avg_{model.val_metric}"""] , __A ) # check lightning ckpt can be loaded and has a reasonable statedict lowerCAmelCase_ :int = os.listdir(__A ) lowerCAmelCase_ :str = [x for x in contents if x.endswith(""".ckpt""" )][0] lowerCAmelCase_ :List[str] = os.path.join(args.output_dir , __A ) lowerCAmelCase_ :Optional[Any] = torch.load(__A , map_location="""cpu""" ) lowerCAmelCase_ :Tuple = """model.model.decoder.layers.0.encoder_attn_layer_norm.weight""" assert expected_key in ckpt["state_dict"] assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa # TODO: turn on args.do_predict when PL bug fixed. if args.do_predict: lowerCAmelCase_ :Tuple = {os.path.basename(__A ) for p in contents} assert "test_generations.txt" in contents assert "test_results.txt" in contents # assert len(metrics["val"]) == desired_n_evals assert len(metrics["""test"""] ) == 1
84
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowercase__ : int = {"""configuration_mbart""": ["""MBART_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MBartConfig""", """MBartOnnxConfig"""]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ : Optional[int] = ["""MBartTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ : Dict = ["""MBartTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ : Any = [ """MBART_PRETRAINED_MODEL_ARCHIVE_LIST""", """MBartForCausalLM""", """MBartForConditionalGeneration""", """MBartForQuestionAnswering""", """MBartForSequenceClassification""", """MBartModel""", """MBartPreTrainedModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ : Tuple = [ """TFMBartForConditionalGeneration""", """TFMBartModel""", """TFMBartPreTrainedModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ : Tuple = [ """FlaxMBartForConditionalGeneration""", """FlaxMBartForQuestionAnswering""", """FlaxMBartForSequenceClassification""", """FlaxMBartModel""", """FlaxMBartPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_mbart import MBART_PRETRAINED_CONFIG_ARCHIVE_MAP, MBartConfig, MBartOnnxConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart import MBartTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart_fast import MBartTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mbart import ( MBART_PRETRAINED_MODEL_ARCHIVE_LIST, MBartForCausalLM, MBartForConditionalGeneration, MBartForQuestionAnswering, MBartForSequenceClassification, MBartModel, MBartPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mbart import TFMBartForConditionalGeneration, TFMBartModel, TFMBartPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_mbart import ( FlaxMBartForConditionalGeneration, FlaxMBartForQuestionAnswering, FlaxMBartForSequenceClassification, FlaxMBartModel, FlaxMBartPreTrainedModel, ) else: import sys lowercase__ : int = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
224
0
from __future__ import annotations from collections.abc import Iterator class __A : def __init__( self , UpperCAmelCase_ ): lowerCamelCase =value lowerCamelCase =None lowerCamelCase =None class __A : def __init__( self , UpperCAmelCase_ ): lowerCamelCase =tree def _snake_case ( self , UpperCAmelCase_ ): if node is None: return 0 return node.value + ( self.depth_first_search(node.left ) + self.depth_first_search(node.right ) ) def __iter__( self ): yield self.depth_first_search(self.tree ) if __name__ == "__main__": import doctest doctest.testmod()
262
from json import JSONDecodeError # Workaround for requests.exceptions.JSONDecodeError import requests def _lowercase ( _UpperCAmelCase = "isbn/0140328726" ) -> dict: lowerCamelCase =olid.strip().strip("""/""" ) # Remove leading/trailing whitespace & slashes if new_olid.count("""/""" ) != 1: lowerCamelCase =F"""{olid} is not a valid Open Library olid""" raise ValueError(_UpperCAmelCase ) return requests.get(F"""https://openlibrary.org/{new_olid}.json""" ).json() def _lowercase ( _UpperCAmelCase ) -> dict: lowerCamelCase ={ """title""": """Title""", """publish_date""": """Publish date""", """authors""": """Authors""", """number_of_pages""": """Number of pages:""", """first_sentence""": """First sentence""", """isbn_10""": """ISBN (10)""", """isbn_13""": """ISBN (13)""", } lowerCamelCase ={better_key: ol_book_data[key] for key, better_key in desired_keys.items()} lowerCamelCase =[ get_openlibrary_data(author["""key"""] )["""name"""] for author in data["""Authors"""] ] lowerCamelCase =data["""First sentence"""]["""value"""] for key, value in data.items(): if isinstance(_UpperCAmelCase , _UpperCAmelCase ): lowerCamelCase =""", """.join(_UpperCAmelCase ) return data if __name__ == "__main__": import doctest doctest.testmod() while True: UpperCAmelCase__ : List[str] =input('''\nEnter the ISBN code to search (or \'quit\' to stop): ''').strip() if isbn.lower() in ("", "q", "quit", "exit", "stop"): break if len(isbn) not in (10, 13) or not isbn.isdigit(): print(F"Sorry, {isbn} is not a valid ISBN. Please, input a valid ISBN.") continue print(F"\nSearching Open Library for ISBN: {isbn}...\n") try: UpperCAmelCase__ : Dict =summarize_book(get_openlibrary_data(F"isbn/{isbn}")) print('''\n'''.join(F"{key}: {value}" for key, value in book_summary.items())) except JSONDecodeError: # Workaround for requests.exceptions.RequestException: print(F"Sorry, there are no results for ISBN: {isbn}.")
262
1
from ...configuration_utils import PretrainedConfig from ...utils import logging _snake_case : Tuple = logging.get_logger(__name__) _snake_case : str = { "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 a (_lowerCAmelCase ): """simple docstring""" __UpperCAmelCase : Optional[Any] = "vit_mae" def __init__( self : Optional[Any] , lowerCamelCase : Any=768 , lowerCamelCase : Tuple=12 , lowerCamelCase : List[Any]=12 , lowerCamelCase : Union[str, Any]=3072 , lowerCamelCase : Dict="gelu" , lowerCamelCase : Dict=0.0 , lowerCamelCase : Union[str, Any]=0.0 , lowerCamelCase : int=0.02 , lowerCamelCase : Any=1E-12 , lowerCamelCase : Dict=224 , lowerCamelCase : Dict=16 , lowerCamelCase : str=3 , lowerCamelCase : Tuple=True , lowerCamelCase : List[Any]=16 , lowerCamelCase : Optional[Any]=512 , lowerCamelCase : Tuple=8 , lowerCamelCase : Union[str, Any]=2048 , lowerCamelCase : Union[str, Any]=0.75 , lowerCamelCase : str=False , **lowerCamelCase : Optional[Any] , ) -> Optional[int]: super().__init__(**lowerCamelCase ) __snake_case : Any = hidden_size __snake_case : Optional[Any] = num_hidden_layers __snake_case : Optional[Any] = num_attention_heads __snake_case : Optional[int] = intermediate_size __snake_case : int = hidden_act __snake_case : Tuple = hidden_dropout_prob __snake_case : Dict = attention_probs_dropout_prob __snake_case : Tuple = initializer_range __snake_case : int = layer_norm_eps __snake_case : Optional[Any] = image_size __snake_case : List[str] = patch_size __snake_case : str = num_channels __snake_case : int = qkv_bias __snake_case : int = decoder_num_attention_heads __snake_case : Tuple = decoder_hidden_size __snake_case : Optional[Any] = decoder_num_hidden_layers __snake_case : List[Any] = decoder_intermediate_size __snake_case : Dict = mask_ratio __snake_case : Tuple = norm_pix_loss
123
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 _snake_case : int = logging.get_logger(__name__) class a : """simple docstring""" def __init__( self : Optional[int] , lowerCamelCase : str = None , lowerCamelCase : uuid.UUID = None , lowerCamelCase : Dict=None , lowerCamelCase : Union[str, Any]=None ) -> int: if not conversation_id: __snake_case : Optional[Any] = uuid.uuida() if past_user_inputs is None: __snake_case : List[Any] = [] if generated_responses is None: __snake_case : Optional[int] = [] __snake_case : uuid.UUID = conversation_id __snake_case : List[str] = past_user_inputs __snake_case : List[str] = generated_responses __snake_case : Optional[str] = text def __eq__( self : int , lowerCamelCase : List[str] ) -> Dict: 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 __snake_case ( self : Optional[int] , lowerCamelCase : str , lowerCamelCase : bool = False ) -> Optional[Any]: 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}".' ) __snake_case : Dict = 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: __snake_case : List[str] = text def __snake_case ( self : List[str] ) -> Dict: if self.new_user_input: self.past_user_inputs.append(self.new_user_input ) __snake_case : Optional[Any] = None def __snake_case ( self : List[str] , lowerCamelCase : str ) -> List[Any]: self.generated_responses.append(lowerCamelCase ) def __snake_case ( self : Optional[Any] ) -> List[str]: 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 : Optional[Any] ) -> Dict: __snake_case : Any = F'Conversation id: {self.uuid} \n' for is_user, text in self.iter_texts(): __snake_case : List[Any] = "user" if is_user else "bot" output += F'{name} >> {text} \n' return output @add_end_docstrings( _lowerCAmelCase , 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 a (_lowerCAmelCase ): """simple docstring""" def __init__( self : Optional[int] , *lowerCamelCase : Optional[Any] , **lowerCamelCase : List[str] ) -> Any: super().__init__(*lowerCamelCase , **lowerCamelCase ) if self.tokenizer.pad_token_id is None: __snake_case : Dict = self.tokenizer.eos_token def __snake_case ( self : Dict , lowerCamelCase : List[str]=None , lowerCamelCase : int=None , lowerCamelCase : Optional[Any]=None , **lowerCamelCase : Any ) -> Any: __snake_case : Union[str, Any] = {} __snake_case : Optional[int] = {} __snake_case : Optional[Any] = {} if min_length_for_response is not None: __snake_case : int = min_length_for_response if minimum_tokens is not None: __snake_case : Tuple = minimum_tokens if "max_length" in generate_kwargs: __snake_case : Any = 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: __snake_case : Any = clean_up_tokenization_spaces if generate_kwargs: forward_params.update(lowerCamelCase ) return preprocess_params, forward_params, postprocess_params def __call__( self : List[str] , lowerCamelCase : Union[Conversation, List[Conversation]] , lowerCamelCase : Optional[Any]=0 , **lowerCamelCase : Optional[Any] ) -> Union[str, Any]: __snake_case : Optional[Any] = super().__call__(lowerCamelCase , num_workers=lowerCamelCase , **lowerCamelCase ) if isinstance(lowerCamelCase , lowerCamelCase ) and len(lowerCamelCase ) == 1: return outputs[0] return outputs def __snake_case ( self : Any , lowerCamelCase : Conversation , lowerCamelCase : Any=32 ) -> Dict[str, Any]: 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" ): __snake_case : Tuple = self.tokenizer._build_conversation_input_ids(lowerCamelCase ) else: # If the tokenizer cannot handle conversations, we default to only the old version __snake_case : Tuple = self._legacy_parse_and_tokenize(lowerCamelCase ) if self.framework == "pt": __snake_case : Union[str, Any] = torch.LongTensor([input_ids] ) elif self.framework == "tf": __snake_case : Union[str, Any] = tf.constant([input_ids] ) return {"input_ids": input_ids, "conversation": conversation} def __snake_case ( self : List[str] , lowerCamelCase : Union[str, Any] , lowerCamelCase : Dict=10 , **lowerCamelCase : Tuple ) -> List[str]: __snake_case : Tuple = generate_kwargs.get("max_length" , self.model.config.max_length ) __snake_case : List[str] = 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})' ) __snake_case : Optional[int] = max_length - minimum_tokens __snake_case : List[Any] = model_inputs["input_ids"][:, -trim:] if "attention_mask" in model_inputs: __snake_case : str = model_inputs["attention_mask"][:, -trim:] __snake_case : Any = model_inputs.pop("conversation" ) __snake_case : str = max_length __snake_case : Optional[int] = self.model.generate(**lowerCamelCase , **lowerCamelCase ) if self.model.config.is_encoder_decoder: __snake_case : List[Any] = 1 else: __snake_case : Union[str, Any] = n return {"output_ids": output_ids[:, start_position:], "conversation": conversation} def __snake_case ( self : Any , lowerCamelCase : List[Any] , lowerCamelCase : Tuple=True ) -> Any: __snake_case : Optional[int] = model_outputs["output_ids"] __snake_case : Optional[Any] = self.tokenizer.decode( output_ids[0] , skip_special_tokens=lowerCamelCase , clean_up_tokenization_spaces=lowerCamelCase , ) __snake_case : Optional[int] = model_outputs["conversation"] conversation.mark_processed() conversation.append_response(lowerCamelCase ) return conversation def __snake_case ( self : Optional[Any] , lowerCamelCase : Conversation ) -> Dict: __snake_case : Optional[Any] = self.tokenizer.eos_token_id __snake_case : Any = [] 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: __snake_case : Tuple = input_ids[-self.tokenizer.model_max_length :] return input_ids
123
1
"""simple docstring""" UpperCamelCase_ ={} def a_ ( _lowercase , _lowercase , _lowercase ): # if we are absent twice, or late 3 consecutive days, # no further prize strings are possible if late == 3 or absent == 2: return 0 # if we have no days left, and have not failed any other rules, # we have a prize string if days == 0: return 1 # No easy solution, so now we need to do the recursive calculation # First, check if the combination is already in the cache, and # if yes, return the stored value from there since we already # know the number of possible prize strings from this point on _UpperCamelCase : int = (days, absent, late) if key in cache: return cache[key] # now we calculate the three possible ways that can unfold from # this point on, depending on our attendance today # 1) if we are late (but not absent), the "absent" counter stays as # it is, but the "late" counter increases by one _UpperCamelCase : int = _calculate(days - 1 , _lowercase , late + 1 ) # 2) if we are absent, the "absent" counter increases by 1, and the # "late" counter resets to 0 _UpperCamelCase : Any = _calculate(days - 1 , absent + 1 , 0 ) # 3) if we are on time, this resets the "late" counter and keeps the # absent counter _UpperCamelCase : Any = _calculate(days - 1 , _lowercase , 0 ) _UpperCamelCase : Dict = state_late + state_absent + state_ontime _UpperCamelCase : Optional[int] = prizestrings return prizestrings def a_ ( _lowercase = 30 ): return _calculate(_lowercase , absent=0 , late=0 ) if __name__ == "__main__": print(solution())
128
"""simple docstring""" import warnings from diffusers import StableDiffusionInpaintPipeline as StableDiffusionInpaintPipeline # noqa F401 warnings.warn( """The `inpainting.py` script is outdated. Please use directly `from diffusers import""" """ StableDiffusionInpaintPipeline` instead.""" )
128
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase__ : int = { """configuration_clipseg""": [ """CLIPSEG_PRETRAINED_CONFIG_ARCHIVE_MAP""", """CLIPSegConfig""", """CLIPSegTextConfig""", """CLIPSegVisionConfig""", ], """processing_clipseg""": ["""CLIPSegProcessor"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Tuple = [ """CLIPSEG_PRETRAINED_MODEL_ARCHIVE_LIST""", """CLIPSegModel""", """CLIPSegPreTrainedModel""", """CLIPSegTextModel""", """CLIPSegVisionModel""", """CLIPSegForImageSegmentation""", ] if TYPE_CHECKING: from .configuration_clipseg import ( CLIPSEG_PRETRAINED_CONFIG_ARCHIVE_MAP, CLIPSegConfig, CLIPSegTextConfig, CLIPSegVisionConfig, ) from .processing_clipseg import CLIPSegProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_clipseg import ( CLIPSEG_PRETRAINED_MODEL_ARCHIVE_LIST, CLIPSegForImageSegmentation, CLIPSegModel, CLIPSegPreTrainedModel, CLIPSegTextModel, CLIPSegVisionModel, ) else: import sys UpperCAmelCase__ : str = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
245
import gc import unittest from parameterized import parameterized from diffusers import FlaxUNetaDConditionModel from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import load_hf_numpy, require_flax, slow if is_flax_available(): import jax import jax.numpy as jnp @slow @require_flax class a__ ( unittest.TestCase ): """simple docstring""" def _lowercase ( self : Optional[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : int ) ->Dict: """simple docstring""" return f"gaussian_noise_s={seed}_shape={'_'.join([str(UpperCAmelCase__ ) for s in shape] )}.npy" def _lowercase ( self : Any ) ->Union[str, Any]: """simple docstring""" super().tearDown() gc.collect() def _lowercase ( self : str , UpperCAmelCase__ : str=0 , UpperCAmelCase__ : Tuple=(4, 4, 6_4, 6_4) , UpperCAmelCase__ : Optional[int]=False ) ->List[str]: """simple docstring""" SCREAMING_SNAKE_CASE : int = jnp.bfloataa if fpaa else jnp.floataa SCREAMING_SNAKE_CASE : Tuple = jnp.array(load_hf_numpy(self.get_file_format(UpperCAmelCase__ , UpperCAmelCase__ ) ) , dtype=UpperCAmelCase__ ) return image def _lowercase ( self : Tuple , UpperCAmelCase__ : Dict=False , UpperCAmelCase__ : Tuple="CompVis/stable-diffusion-v1-4" ) ->Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = jnp.bfloataa if fpaa else jnp.floataa SCREAMING_SNAKE_CASE : Dict = """bf16""" if fpaa else None SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[str] = FlaxUNetaDConditionModel.from_pretrained( UpperCAmelCase__ , subfolder="""unet""" , dtype=UpperCAmelCase__ , revision=UpperCAmelCase__ ) return model, params def _lowercase ( self : Optional[int] , UpperCAmelCase__ : int=0 , UpperCAmelCase__ : List[str]=(4, 7_7, 7_6_8) , UpperCAmelCase__ : Optional[Any]=False ) ->int: """simple docstring""" SCREAMING_SNAKE_CASE : str = jnp.bfloataa if fpaa else jnp.floataa SCREAMING_SNAKE_CASE : Union[str, Any] = jnp.array(load_hf_numpy(self.get_file_format(UpperCAmelCase__ , UpperCAmelCase__ ) ) , dtype=UpperCAmelCase__ ) return hidden_states @parameterized.expand( [ # fmt: off [8_3, 4, [-0.23_23, -0.13_04, 0.08_13, -0.30_93, -0.09_19, -0.15_71, -0.11_25, -0.58_06]], [1_7, 0.55, [-0.08_31, -0.24_43, 0.09_01, -0.09_19, 0.33_96, 0.01_03, -0.37_43, 0.07_01]], [8, 0.89, [-0.48_63, 0.08_59, 0.08_75, -0.16_58, 0.91_99, -0.01_14, 0.48_39, 0.46_39]], [3, 1_0_0_0, [-0.56_49, 0.24_02, -0.55_18, 0.12_48, 1.13_28, -0.24_43, -0.03_25, -1.00_78]], # fmt: on ] ) def _lowercase ( self : Union[str, Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[int] ) ->List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = self.get_unet_model(model_id="""CompVis/stable-diffusion-v1-4""" , fpaa=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE : Optional[int] = self.get_latents(UpperCAmelCase__ , fpaa=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE : Dict = self.get_encoder_hidden_states(UpperCAmelCase__ , fpaa=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE : List[str] = model.apply( {"""params""": params} , UpperCAmelCase__ , jnp.array(UpperCAmelCase__ , dtype=jnp.intaa ) , encoder_hidden_states=UpperCAmelCase__ , ).sample assert sample.shape == latents.shape SCREAMING_SNAKE_CASE : Union[str, Any] = jnp.asarray(jax.device_get((sample[-1, -2:, -2:, :2].flatten()) ) , dtype=jnp.floataa ) SCREAMING_SNAKE_CASE : str = jnp.array(UpperCAmelCase__ , dtype=jnp.floataa ) # Found torch (float16) and flax (bfloat16) outputs to be within this tolerance, in the same hardware assert jnp.allclose(UpperCAmelCase__ , UpperCAmelCase__ , atol=1e-2 ) @parameterized.expand( [ # fmt: off [8_3, 4, [0.15_14, 0.08_07, 0.16_24, 0.10_16, -0.18_96, 0.02_63, 0.06_77, 0.23_10]], [1_7, 0.55, [0.11_64, -0.02_16, 0.01_70, 0.15_89, -0.31_20, 0.10_05, -0.05_81, -0.14_58]], [8, 0.89, [-0.17_58, -0.01_69, 0.10_04, -0.14_11, 0.13_12, 0.11_03, -0.19_96, 0.21_39]], [3, 1_0_0_0, [0.12_14, 0.03_52, -0.07_31, -0.15_62, -0.09_94, -0.09_06, -0.23_40, -0.05_39]], # fmt: on ] ) def _lowercase ( self : int , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : int ) ->Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : str = self.get_unet_model(model_id="""stabilityai/stable-diffusion-2""" , fpaa=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE : List[str] = self.get_latents(UpperCAmelCase__ , shape=(4, 4, 9_6, 9_6) , fpaa=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE : Optional[Any] = self.get_encoder_hidden_states(UpperCAmelCase__ , shape=(4, 7_7, 1_0_2_4) , fpaa=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE : str = model.apply( {"""params""": params} , UpperCAmelCase__ , jnp.array(UpperCAmelCase__ , dtype=jnp.intaa ) , encoder_hidden_states=UpperCAmelCase__ , ).sample assert sample.shape == latents.shape SCREAMING_SNAKE_CASE : str = jnp.asarray(jax.device_get((sample[-1, -2:, -2:, :2].flatten()) ) , dtype=jnp.floataa ) SCREAMING_SNAKE_CASE : Dict = jnp.array(UpperCAmelCase__ , dtype=jnp.floataa ) # Found torch (float16) and flax (bfloat16) outputs to be within this tolerance, on the same hardware assert jnp.allclose(UpperCAmelCase__ , UpperCAmelCase__ , atol=1e-2 )
245
1
'''simple docstring''' import os from pathlib import Path from unittest.mock import patch import pytest import zstandard as zstd from datasets.download.download_config import DownloadConfig from datasets.utils.file_utils import ( OfflineModeIsEnabled, cached_path, fsspec_get, fsspec_head, ftp_get, ftp_head, get_from_cache, http_get, http_head, ) UpperCamelCase__ : List[str] = '\\n Text data.\n Second line of data.' UpperCamelCase__ : List[str] = 'file' @pytest.fixture(scope="""session""" ) def UpperCAmelCase ( a_ ) -> str: """simple docstring""" A_ : Optional[Any] = tmp_path_factory.mktemp("""data""" ) / (FILE_PATH + """.zstd""") A_ : List[Any] = bytes(a_ , """utf-8""" ) with zstd.open(a_ , """wb""" ) as f: f.write(a_ ) return path @pytest.fixture def UpperCAmelCase ( a_ ) -> Tuple: """simple docstring""" with open(os.path.join(tmpfs.local_root_dir , a_ ) , """w""" ) as f: f.write(a_ ) return FILE_PATH @pytest.mark.parametrize("""compression_format""" , ["""gzip""", """xz""", """zstd"""] ) def UpperCAmelCase ( a_ , a_ , a_ , a_ , a_ , a_ ) -> int: """simple docstring""" A_ : Dict = {"""gzip""": gz_file, """xz""": xz_file, """zstd""": zstd_path} A_ : Tuple = input_paths[compression_format] A_ : Optional[Any] = tmp_path / """cache""" A_ : str = DownloadConfig(cache_dir=a_ , extract_compressed_file=a_ ) A_ : int = cached_path(a_ , download_config=a_ ) with open(a_ ) as f: A_ : int = f.read() with open(a_ ) as f: A_ : Tuple = f.read() assert extracted_file_content == expected_file_content @pytest.mark.parametrize("""default_extracted""" , [True, False] ) @pytest.mark.parametrize("""default_cache_dir""" , [True, False] ) def UpperCAmelCase ( a_ , a_ , a_ , a_ , a_ ) -> str: """simple docstring""" A_ : Union[str, Any] = """custom_cache""" A_ : Any = """custom_extracted_dir""" A_ : List[Any] = tmp_path / """custom_extracted_path""" if default_extracted: A_ : List[Any] = ("""downloads""" if default_cache_dir else custom_cache_dir, """extracted""") else: monkeypatch.setattr("""datasets.config.EXTRACTED_DATASETS_DIR""" , a_ ) monkeypatch.setattr("""datasets.config.EXTRACTED_DATASETS_PATH""" , str(a_ ) ) A_ : Tuple = custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir) A_ : int = xz_file A_ : Tuple = ( DownloadConfig(extract_compressed_file=a_ ) if default_cache_dir else DownloadConfig(cache_dir=tmp_path / custom_cache_dir , extract_compressed_file=a_ ) ) A_ : Optional[Any] = cached_path(a_ , download_config=a_ ) assert Path(a_ ).parent.parts[-2:] == expected def UpperCAmelCase ( a_ ) -> Optional[Any]: """simple docstring""" A_ : str = str(Path(a_ ).resolve() ) assert cached_path(a_ ) == text_file # relative path A_ : int = str(Path(a_ ).resolve().relative_to(Path(os.getcwd() ) ) ) assert cached_path(a_ ) == text_file def UpperCAmelCase ( a_ ) -> Optional[Any]: """simple docstring""" A_ : Dict = str(tmp_path.resolve() / """__missing_file__.txt""" ) with pytest.raises(a_ ): cached_path(a_ ) # relative path A_ : Tuple = """./__missing_file__.txt""" with pytest.raises(a_ ): cached_path(a_ ) def UpperCAmelCase ( a_ ) -> List[str]: """simple docstring""" A_ : Optional[int] = get_from_cache(F"tmp://{tmpfs_file}" ) with open(a_ ) as f: A_ : Dict = f.read() assert output_file_content == FILE_CONTENT @patch("""datasets.config.HF_DATASETS_OFFLINE""" , a_ ) def UpperCAmelCase ( ) -> List[Any]: """simple docstring""" with pytest.raises(a_ ): cached_path("""https://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" , a_ ) def UpperCAmelCase ( a_ ) -> str: """simple docstring""" A_ : Optional[Any] = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(a_ ): http_get("""https://huggingface.co""" , temp_file=a_ ) with pytest.raises(a_ ): http_head("""https://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" , a_ ) def UpperCAmelCase ( a_ ) -> Optional[int]: """simple docstring""" A_ : Optional[Any] = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(a_ ): ftp_get("""ftp://huggingface.co""" , temp_file=a_ ) with pytest.raises(a_ ): ftp_head("""ftp://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" , a_ ) def UpperCAmelCase ( a_ ) -> int: """simple docstring""" A_ : str = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(a_ ): fsspec_get("""s3://huggingface.co""" , temp_file=a_ ) with pytest.raises(a_ ): fsspec_head("""s3://huggingface.co""" )
164
'''simple docstring''' def UpperCAmelCase ( a_ , a_ ) -> int: """simple docstring""" A_ : int = 1 # To kept the Calculated Value # Since C(n, k) = C(n, n-k) if k > (n - k): A_ : Tuple = n - k # Calculate C(n,k) for i in range(a_ ): result *= n - i result //= i + 1 return result def UpperCAmelCase ( a_ ) -> int: """simple docstring""" return binomial_coefficient(2 * node_count , a_ ) // (node_count + 1) def UpperCAmelCase ( a_ ) -> int: """simple docstring""" if n < 0: raise ValueError("""factorial() not defined for negative values""" ) A_ : Union[str, Any] = 1 for i in range(1 , n + 1 ): result *= i return result def UpperCAmelCase ( a_ ) -> int: """simple docstring""" return catalan_number(a_ ) * factorial(a_ ) if __name__ == "__main__": UpperCamelCase__ : Any = int(input('Enter the number of nodes: ').strip() or 0) if node_count <= 0: raise ValueError('We need some nodes to work with.') print( f'Given {node_count} nodes, there are {binary_tree_count(node_count)} ' f'binary trees and {catalan_number(node_count)} binary search trees.' )
164
1
import os from math import logaa def UpperCamelCase ( lowerCAmelCase__ = "base_exp.txt" ): '''simple docstring''' lowercase = 0 lowercase = 0 for i, line in enumerate(open(os.path.join(os.path.dirname(lowerCAmelCase__ ) , lowerCAmelCase__ ) ) ): lowercase , lowercase = list(map(lowerCAmelCase__ , line.split(''',''' ) ) ) if x * logaa(lowerCAmelCase__ ) > largest: lowercase = x * logaa(lowerCAmelCase__ ) lowercase = i + 1 return result if __name__ == "__main__": print(solution())
101
import random from .binary_exp_mod import bin_exp_mod def UpperCamelCase ( lowerCAmelCase__ , lowerCAmelCase__=1000 ): '''simple docstring''' if n < 2: return False if n % 2 == 0: return n == 2 # this means n is odd lowercase = n - 1 lowercase = 0 while d % 2 == 0: d /= 2 exp += 1 # n - 1=d*(2**exp) lowercase = 0 while count < prec: lowercase = random.randint(2 , n - 1 ) lowercase = bin_exp_mod(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) if b != 1: lowercase = True for _ in range(lowerCAmelCase__ ): if b == n - 1: lowercase = False break lowercase = b * b b %= n if flag: return False count += 1 return True if __name__ == "__main__": lowercase__ :Tuple = abs(int(input("Enter bound : ").strip())) print("Here's the list of primes:") print(", ".join(str(i) for i in range(n + 1) if is_prime_big(i)))
101
1
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from .tokenization_electra import ElectraTokenizer _A = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} _A = { '''vocab_file''': { '''google/electra-small-generator''': ( '''https://huggingface.co/google/electra-small-generator/resolve/main/vocab.txt''' ), '''google/electra-base-generator''': '''https://huggingface.co/google/electra-base-generator/resolve/main/vocab.txt''', '''google/electra-large-generator''': ( '''https://huggingface.co/google/electra-large-generator/resolve/main/vocab.txt''' ), '''google/electra-small-discriminator''': ( '''https://huggingface.co/google/electra-small-discriminator/resolve/main/vocab.txt''' ), '''google/electra-base-discriminator''': ( '''https://huggingface.co/google/electra-base-discriminator/resolve/main/vocab.txt''' ), '''google/electra-large-discriminator''': ( '''https://huggingface.co/google/electra-large-discriminator/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''google/electra-small-generator''': ( '''https://huggingface.co/google/electra-small-generator/resolve/main/tokenizer.json''' ), '''google/electra-base-generator''': ( '''https://huggingface.co/google/electra-base-generator/resolve/main/tokenizer.json''' ), '''google/electra-large-generator''': ( '''https://huggingface.co/google/electra-large-generator/resolve/main/tokenizer.json''' ), '''google/electra-small-discriminator''': ( '''https://huggingface.co/google/electra-small-discriminator/resolve/main/tokenizer.json''' ), '''google/electra-base-discriminator''': ( '''https://huggingface.co/google/electra-base-discriminator/resolve/main/tokenizer.json''' ), '''google/electra-large-discriminator''': ( '''https://huggingface.co/google/electra-large-discriminator/resolve/main/tokenizer.json''' ), }, } _A = { '''google/electra-small-generator''': 512, '''google/electra-base-generator''': 512, '''google/electra-large-generator''': 512, '''google/electra-small-discriminator''': 512, '''google/electra-base-discriminator''': 512, '''google/electra-large-discriminator''': 512, } _A = { '''google/electra-small-generator''': {'''do_lower_case''': True}, '''google/electra-base-generator''': {'''do_lower_case''': True}, '''google/electra-large-generator''': {'''do_lower_case''': True}, '''google/electra-small-discriminator''': {'''do_lower_case''': True}, '''google/electra-base-discriminator''': {'''do_lower_case''': True}, '''google/electra-large-discriminator''': {'''do_lower_case''': True}, } class lowercase_ ( __SCREAMING_SNAKE_CASE ): A__ : int = VOCAB_FILES_NAMES A__ : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP A__ : Any = PRETRAINED_INIT_CONFIGURATION A__ : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A__ : Optional[int] = ElectraTokenizer def __init__( self , __UpperCamelCase=None , __UpperCamelCase=None , __UpperCamelCase=True , __UpperCamelCase="[UNK]" , __UpperCamelCase="[SEP]" , __UpperCamelCase="[PAD]" , __UpperCamelCase="[CLS]" , __UpperCamelCase="[MASK]" , __UpperCamelCase=True , __UpperCamelCase=None , **__UpperCamelCase , ): """simple docstring""" super().__init__( __UpperCamelCase , tokenizer_file=__UpperCamelCase , do_lower_case=__UpperCamelCase , unk_token=__UpperCamelCase , sep_token=__UpperCamelCase , pad_token=__UpperCamelCase , cls_token=__UpperCamelCase , mask_token=__UpperCamelCase , tokenize_chinese_chars=__UpperCamelCase , strip_accents=__UpperCamelCase , **__UpperCamelCase , ) UpperCamelCase_ = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""" , __UpperCamelCase ) != do_lower_case or normalizer_state.get("""strip_accents""" , __UpperCamelCase ) != strip_accents or normalizer_state.get("""handle_chinese_chars""" , __UpperCamelCase ) != tokenize_chinese_chars ): UpperCamelCase_ = getattr(__UpperCamelCase , normalizer_state.pop("""type""" ) ) UpperCamelCase_ = do_lower_case UpperCamelCase_ = strip_accents UpperCamelCase_ = tokenize_chinese_chars UpperCamelCase_ = normalizer_class(**__UpperCamelCase ) UpperCamelCase_ = do_lower_case def lowerCamelCase_ ( self , __UpperCamelCase , __UpperCamelCase=None ): """simple docstring""" UpperCamelCase_ = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def lowerCamelCase_ ( self , __UpperCamelCase , __UpperCamelCase = None ): """simple docstring""" UpperCamelCase_ = [self.sep_token_id] UpperCamelCase_ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def lowerCamelCase_ ( self , __UpperCamelCase , __UpperCamelCase = None ): """simple docstring""" UpperCamelCase_ = self._tokenizer.model.save(__UpperCamelCase , name=__UpperCamelCase ) return tuple(__UpperCamelCase )
261
import argparse import json import math import os import time import traceback import zipfile from collections import Counter import requests def lowerCamelCase__ ( a__ : Dict , a__ : Dict=None ) -> Union[str, Any]: UpperCamelCase_ = None if token is not None: UpperCamelCase_ = {"""Accept""": """application/vnd.github+json""", """Authorization""": f'''Bearer {token}'''} UpperCamelCase_ = f'''https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100''' UpperCamelCase_ = requests.get(a__ , headers=a__ ).json() UpperCamelCase_ = {} try: job_links.update({job["""name"""]: job["""html_url"""] for job in result["""jobs"""]} ) UpperCamelCase_ = math.ceil((result["""total_count"""] - 100) / 100 ) for i in range(a__ ): UpperCamelCase_ = requests.get(url + f'''&page={i + 2}''' , headers=a__ ).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 lowerCamelCase__ ( a__ : Union[str, Any] , a__ : Any=None ) -> Optional[int]: UpperCamelCase_ = None if token is not None: UpperCamelCase_ = {"""Accept""": """application/vnd.github+json""", """Authorization""": f'''Bearer {token}'''} UpperCamelCase_ = f'''https://api.github.com/repos/huggingface/transformers/actions/runs/{worflow_run_id}/artifacts?per_page=100''' UpperCamelCase_ = requests.get(a__ , headers=a__ ).json() UpperCamelCase_ = {} try: artifacts.update({artifact["""name"""]: artifact["""archive_download_url"""] for artifact in result["""artifacts"""]} ) UpperCamelCase_ = math.ceil((result["""total_count"""] - 100) / 100 ) for i in range(a__ ): UpperCamelCase_ = requests.get(url + f'''&page={i + 2}''' , headers=a__ ).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 lowerCamelCase__ ( a__ : Dict , a__ : Tuple , a__ : Union[str, Any] , a__ : List[Any] ) -> List[Any]: UpperCamelCase_ = None if token is not None: UpperCamelCase_ = {"""Accept""": """application/vnd.github+json""", """Authorization""": f'''Bearer {token}'''} UpperCamelCase_ = requests.get(a__ , headers=a__ , allow_redirects=a__ ) UpperCamelCase_ = result.headers["""Location"""] UpperCamelCase_ = requests.get(a__ , allow_redirects=a__ ) UpperCamelCase_ = os.path.join(a__ , f'''{artifact_name}.zip''' ) with open(a__ , """wb""" ) as fp: fp.write(response.content ) def lowerCamelCase__ ( a__ : Dict , a__ : Tuple=None ) -> Optional[int]: UpperCamelCase_ = [] UpperCamelCase_ = [] UpperCamelCase_ = None with zipfile.ZipFile(a__ ) as z: for filename in z.namelist(): if not os.path.isdir(a__ ): # read the file if filename in ["failures_line.txt", "summary_short.txt", "job_name.txt"]: with z.open(a__ ) as f: for line in f: UpperCamelCase_ = line.decode("""UTF-8""" ).strip() if filename == "failures_line.txt": try: # `error_line` is the place where `error` occurs UpperCamelCase_ = line[: line.index(""": """ )] UpperCamelCase_ = 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 UpperCamelCase_ = line[len("""FAILED """ ) :] failed_tests.append(a__ ) elif filename == "job_name.txt": UpperCamelCase_ = line if len(a__ ) != len(a__ ): raise ValueError( f'''`errors` and `failed_tests` should have the same number of elements. Got {len(a__ )} for `errors` ''' f'''and {len(a__ )} for `failed_tests` instead. The test reports in {artifact_zip_path} have some''' """ problem.""" ) UpperCamelCase_ = None if job_name and job_links: UpperCamelCase_ = job_links.get(a__ , a__ ) # A list with elements of the form (line of error, error, failed test) UpperCamelCase_ = [x + [y] + [job_link] for x, y in zip(a__ , a__ )] return result def lowerCamelCase__ ( a__ : Any , a__ : Union[str, Any]=None ) -> Dict: UpperCamelCase_ = [] UpperCamelCase_ = [os.path.join(a__ , a__ ) for p in os.listdir(a__ ) if p.endswith(""".zip""" )] for p in paths: errors.extend(get_errors_from_single_artifact(a__ , job_links=a__ ) ) return errors def lowerCamelCase__ ( a__ : Union[str, Any] , a__ : Tuple=None ) -> List[Any]: UpperCamelCase_ = Counter() counter.update([x[1] for x in logs] ) UpperCamelCase_ = counter.most_common() UpperCamelCase_ = {} for error, count in counts: if error_filter is None or error not in error_filter: UpperCamelCase_ = {"""count""": count, """failed_tests""": [(x[2], x[0]) for x in logs if x[1] == error]} UpperCamelCase_ = dict(sorted(r.items() , key=lambda a__ : item[1]["count"] , reverse=a__ ) ) return r def lowerCamelCase__ ( a__ : Optional[int] ) -> Optional[Any]: UpperCamelCase_ = test.split("""::""" )[0] if test.startswith("""tests/models/""" ): UpperCamelCase_ = test.split("""/""" )[2] else: UpperCamelCase_ = None return test def lowerCamelCase__ ( a__ : List[str] , a__ : Optional[int]=None ) -> Dict: UpperCamelCase_ = [(x[0], x[1], get_model(x[2] )) for x in logs] UpperCamelCase_ = [x for x in logs if x[2] is not None] UpperCamelCase_ = {x[2] for x in logs} UpperCamelCase_ = {} for test in tests: UpperCamelCase_ = Counter() # count by errors in `test` counter.update([x[1] for x in logs if x[2] == test] ) UpperCamelCase_ = counter.most_common() UpperCamelCase_ = {error: count for error, count in counts if (error_filter is None or error not in error_filter)} UpperCamelCase_ = sum(error_counts.values() ) if n_errors > 0: UpperCamelCase_ = {"""count""": n_errors, """errors""": error_counts} UpperCamelCase_ = dict(sorted(r.items() , key=lambda a__ : item[1]["count"] , reverse=a__ ) ) return r def lowerCamelCase__ ( a__ : Any ) -> List[Any]: UpperCamelCase_ = """| no. | error | status |""" UpperCamelCase_ = """|-:|:-|:-|""" UpperCamelCase_ = [header, sep] for error in reduced_by_error: UpperCamelCase_ = reduced_by_error[error]["""count"""] UpperCamelCase_ = f'''| {count} | {error[:100]} | |''' lines.append(a__ ) return "\n".join(a__ ) def lowerCamelCase__ ( a__ : Optional[int] ) -> str: UpperCamelCase_ = """| model | no. of errors | major error | count |""" UpperCamelCase_ = """|-:|-:|-:|-:|""" UpperCamelCase_ = [header, sep] for model in reduced_by_model: UpperCamelCase_ = reduced_by_model[model]["""count"""] UpperCamelCase_ , UpperCamelCase_ = list(reduced_by_model[model]["""errors"""].items() )[0] UpperCamelCase_ = f'''| {model} | {count} | {error[:60]} | {_count} |''' lines.append(a__ ) return "\n".join(a__ ) if __name__ == "__main__": _A = 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.''') _A = parser.parse_args() os.makedirs(args.output_dir, exist_ok=True) _A = get_job_links(args.workflow_run_id, token=args.token) _A = {} # 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: _A = k.find(''' / ''') _A = k[index + len(''' / ''') :] _A = 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) _A = 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) _A = get_all_errors(args.output_dir, job_links=job_links) # `e[1]` is the error _A = Counter() counter.update([e[1] for e in errors]) # print the top 30 most common test errors _A = 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) _A = reduce_by_error(errors) _A = reduce_by_model(errors) _A = make_github_table(reduced_by_error) _A = 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)
261
1
'''simple docstring''' import sys __snake_case = ( '73167176531330624919225119674426574742355349194934' '96983520312774506326239578318016984801869478851843' '85861560789112949495459501737958331952853208805511' '12540698747158523863050715693290963295227443043557' '66896648950445244523161731856403098711121722383113' '62229893423380308135336276614282806444486645238749' '30358907296290491560440772390713810515859307960866' '70172427121883998797908792274921901699720888093776' '65727333001053367881220235421809751254540594752243' '52584907711670556013604839586446706324415722155397' '53697817977846174064955149290862569321978468622482' '83972241375657056057490261407972968652414535100474' '82166370484403199890008895243450658541227588666881' '16427171479924442928230863465674813919123162824586' '17866458359124566529476545682848912883142607690042' '24219022671055626321111109370544217506941658960408' '07198403850962455444362981230987879927244284909188' '84580156166097919133875499200524063689912560717606' '05886116467109405077541002256983155200055935729725' '71636269561882670428252483600823257530420752963450' ) def a ( __a ) -> int: '''simple docstring''' UpperCamelCase__ :str = 1 for digit in s: product *= int(a__ ) return product def a ( __a = N ) -> int: '''simple docstring''' UpperCamelCase__ :List[str] = -sys.maxsize - 1 UpperCamelCase__ :int = n[:13] UpperCamelCase__ :int = 13 while cur_index < len(a__ ) - 13: if int(n[cur_index] ) >= int(substr[0] ): UpperCamelCase__ :List[str] = substr[1:] + n[cur_index] cur_index += 1 else: UpperCamelCase__ :Tuple = max(a__ , str_eval(a__ ) ) UpperCamelCase__ :List[str] = n[cur_index : cur_index + 13] cur_index += 13 return largest_product if __name__ == "__main__": print(F"""{solution() = }""")
97
def __lowerCAmelCase ( a__ ) -> str: __a = [] __a = set({'''(''', '''[''', '''{'''} ) __a = set({''')''', ''']''', '''}'''} ) __a = {'''{''': '''}''', '''[''': ''']''', '''(''': ''')'''} for i in range(len(a__ ) ): if s[i] in open_brackets: stack.append(s[i] ) elif s[i] in closed_brackets and ( len(a__ ) == 0 or (len(a__ ) > 0 and open_to_closed[stack.pop()] != s[i]) ): return False return len(a__ ) == 0 def __lowerCAmelCase ( ) -> Dict: __a = input('''Enter sequence of brackets: ''' ) if is_balanced(a__ ): print(a__ , '''is balanced''' ) else: print(a__ , '''is not balanced''' ) if __name__ == "__main__": main()
6
0
"""simple docstring""" import faiss # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import requests # noqa: F401 # Here to have a nice missing dependency error message early on import sklearn # noqa: F401 # Here to have a nice missing dependency error message early on import tqdm # noqa: F401 # Here to have a nice missing dependency error message early on from mauve import compute_mauve # From: mauve-text import datasets __lowerCAmelCase : Union[str, Any] ="""\ @inproceedings{pillutla-etal:mauve:neurips2021, title={MAUVE: Measuring the Gap Between Neural Text and Human Text using Divergence Frontiers}, author={Pillutla, Krishna and Swayamdipta, Swabha and Zellers, Rowan and Thickstun, John and Welleck, Sean and Choi, Yejin and Harchaoui, Zaid}, booktitle = {NeurIPS}, year = {2021} } """ __lowerCAmelCase : Dict ="""\ MAUVE is a library built on PyTorch and HuggingFace Transformers to measure the gap between neural text and human text with the eponymous MAUVE measure. MAUVE summarizes both Type I and Type II errors measured softly using Kullback–Leibler (KL) divergences. For details, see the MAUVE paper: https://arxiv.org/abs/2102.01454 (Neurips, 2021). This metrics is a wrapper around the official implementation of MAUVE: https://github.com/krishnap25/mauve """ __lowerCAmelCase : List[str] =""" Calculates MAUVE scores between two lists of generated text and reference text. Args: predictions: list of generated text to score. Each predictions should be a string with tokens separated by spaces. references: list of reference for each prediction. Each reference should be a string with tokens separated by spaces. Optional Args: num_buckets: the size of the histogram to quantize P and Q. Options: 'auto' (default) or an integer pca_max_data: the number data points to use for PCA dimensionality reduction prior to clustering. If -1, use all the data. Default -1 kmeans_explained_var: amount of variance of the data to keep in dimensionality reduction by PCA. Default 0.9 kmeans_num_redo: number of times to redo k-means clustering (the best objective is kept). Default 5 kmeans_max_iter: maximum number of k-means iterations. Default 500 featurize_model_name: name of the model from which features are obtained. Default 'gpt2-large' Use one of ['gpt2', 'gpt2-medium', 'gpt2-large', 'gpt2-xl']. device_id: Device for featurization. Supply a GPU id (e.g. 0 or 3) to use GPU. If no GPU with this id is found, use CPU max_text_length: maximum number of tokens to consider. Default 1024 divergence_curve_discretization_size: Number of points to consider on the divergence curve. Default 25 mauve_scaling_factor: \"c\" from the paper. Default 5. verbose: If True (default), print running time updates seed: random seed to initialize k-means cluster assignments. Returns: mauve: MAUVE score, a number between 0 and 1. Larger values indicate that P and Q are closer, frontier_integral: Frontier Integral, a number between 0 and 1. Smaller values indicate that P and Q are closer, divergence_curve: a numpy.ndarray of shape (m, 2); plot it with matplotlib to view the divergence curve, p_hist: a discrete distribution, which is a quantized version of the text distribution p_text, q_hist: same as above, but with q_text. Examples: >>> # faiss segfaults in doctest for some reason, so the .compute call is not tested with doctest >>> import datasets >>> mauve = datasets.load_metric('mauve') >>> predictions = [\"hello there\", \"general kenobi\"] >>> references = [\"hello there\", \"general kenobi\"] >>> out = mauve.compute(predictions=predictions, references=references) # doctest: +SKIP >>> print(out.mauve) # doctest: +SKIP 1.0 """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _A ( datasets.Metric ): def A__ ( self ): """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage="""https://github.com/krishnap25/mauve""" , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""string""" , id="""sequence""" ), """references""": datasets.Value("""string""" , id="""sequence""" ), } ) , codebase_urls=["""https://github.com/krishnap25/mauve"""] , reference_urls=[ """https://arxiv.org/abs/2102.01454""", """https://github.com/krishnap25/mauve""", ] , ) def A__ ( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase=None , __lowerCAmelCase=None , __lowerCAmelCase=None , __lowerCAmelCase=None , __lowerCAmelCase="auto" , __lowerCAmelCase=-1 , __lowerCAmelCase=0.9 , __lowerCAmelCase=5 , __lowerCAmelCase=500 , __lowerCAmelCase="gpt2-large" , __lowerCAmelCase=-1 , __lowerCAmelCase=1024 , __lowerCAmelCase=25 , __lowerCAmelCase=5 , __lowerCAmelCase=True , __lowerCAmelCase=25 , ): """simple docstring""" lowercase = compute_mauve( p_text=__lowerCAmelCase , q_text=__lowerCAmelCase , p_features=__lowerCAmelCase , q_features=__lowerCAmelCase , p_tokens=__lowerCAmelCase , q_tokens=__lowerCAmelCase , num_buckets=__lowerCAmelCase , pca_max_data=__lowerCAmelCase , kmeans_explained_var=__lowerCAmelCase , kmeans_num_redo=__lowerCAmelCase , kmeans_max_iter=__lowerCAmelCase , featurize_model_name=__lowerCAmelCase , device_id=__lowerCAmelCase , max_text_length=__lowerCAmelCase , divergence_curve_discretization_size=__lowerCAmelCase , mauve_scaling_factor=__lowerCAmelCase , verbose=__lowerCAmelCase , seed=__lowerCAmelCase , ) return out
32
"""simple docstring""" def UpperCAmelCase__ ( lowerCAmelCase__ :list[list] ) -> list[list]: '''simple docstring''' lowercase = current_set.copy() for row_index, row in enumerate(lowerCAmelCase__ ): lowercase = row[0] for column_index, column in enumerate(lowerCAmelCase__ ): if magnitude == 0: lowercase = column continue lowercase = column / magnitude # Subtract to cancel term lowercase = current_set[0] lowercase = [first_row] lowercase = current_set[1::] for row in current_set: lowercase = [] # If first term is 0, it is already in form we want, so we preserve it if row[0] == 0: final_set.append(lowerCAmelCase__ ) continue for column_index in range(len(lowerCAmelCase__ ) ): temp_row.append(first_row[column_index] - row[column_index] ) final_set.append(lowerCAmelCase__ ) # Create next recursion iteration set if len(final_set[0] ) != 3: lowercase = final_set[0] lowercase = [] lowercase = [] for row in final_set[1::]: current_first_column.append(row[0] ) next_iteration.append(row[1::] ) lowercase = simplify(lowerCAmelCase__ ) for i in range(len(lowerCAmelCase__ ) ): resultant[i].insert(0 , current_first_column[i] ) resultant.insert(0 , lowerCAmelCase__ ) lowercase = resultant return final_set def UpperCAmelCase__ ( lowerCAmelCase__ :list[list] ) -> list: '''simple docstring''' if len(lowerCAmelCase__ ) == 0: raise IndexError("""solve_simultaneous() requires n lists of length n+1""" ) lowercase = len(lowerCAmelCase__ ) + 1 if any(len(lowerCAmelCase__ ) != _length for item in equations ): raise IndexError("""solve_simultaneous() requires n lists of length n+1""" ) for row in equations: if any(not isinstance(lowerCAmelCase__ , (int, float) ) for column in row ): raise ValueError("""solve_simultaneous() requires lists of integers""" ) if len(lowerCAmelCase__ ) == 1: return [equations[0][-1] / equations[0][0]] lowercase = equations.copy() if any(0 in row for row in data_set ): lowercase = data_set.copy() lowercase = [] for row_index, row in enumerate(lowerCAmelCase__ ): if 0 not in row: lowercase = data_set.pop(lowerCAmelCase__ ) break if not full_row: raise ValueError("""solve_simultaneous() requires at least 1 full equation""" ) data_set.insert(0 , lowerCAmelCase__ ) lowercase = data_set.copy() lowercase = simplify(lowerCAmelCase__ ) lowercase = simplified[::-1] lowercase = [] for row in simplified: lowercase = row[-1] if not solutions: if row[-2] == 0: solutions.append(0 ) continue solutions.append(current_solution / row[-2] ) continue lowercase = row.copy()[: len(lowerCAmelCase__ ) - 1 :] while temp_row[0] == 0: temp_row.pop(0 ) if len(lowerCAmelCase__ ) == 0: solutions.append(0 ) continue lowercase = temp_row[1::] lowercase = temp_row[::-1] for column_index, column in enumerate(lowerCAmelCase__ ): current_solution -= column * solutions[column_index] solutions.append(lowerCAmelCase__ ) lowercase = [] for item in solutions: final.append(float(round(lowerCAmelCase__ , 5 ) ) ) return final[::-1] if __name__ == "__main__": import doctest doctest.testmod() __lowerCAmelCase : List[str] =[ [2, 1, 1, 1, 1, 4], [1, 2, 1, 1, 1, 5], [1, 1, 2, 1, 1, 6], [1, 1, 1, 2, 1, 7], [1, 1, 1, 1, 2, 8], ] print(solve_simultaneous(eq)) print(solve_simultaneous([[4, 2]]))
32
1
from dataclasses import dataclass from typing import Tuple import numpy as np import torch @dataclass class UpperCamelCase_ : '''simple docstring''' UpperCAmelCase__ = 42 # [batch_size x 3] UpperCAmelCase__ = 42 # [batch_size x 3] UpperCAmelCase__ = 42 # [batch_size x 3] UpperCAmelCase__ = 42 # [batch_size x 3] UpperCAmelCase__ = 42 UpperCAmelCase__ = 42 UpperCAmelCase__ = 42 UpperCAmelCase__ = 42 UpperCAmelCase__ = 42 def SCREAMING_SNAKE_CASE ( self : Dict) ->Optional[Any]: '''simple docstring''' assert self.x.shape[0] == self.y.shape[0] == self.z.shape[0] == self.origin.shape[0] assert self.x.shape[1] == self.y.shape[1] == self.z.shape[1] == self.origin.shape[1] == 3 assert len(self.x.shape) == len(self.y.shape) == len(self.z.shape) == len(self.origin.shape) == 2 def SCREAMING_SNAKE_CASE ( self : Tuple) ->Dict: '''simple docstring''' return torch.from_numpy(np.array([self.width, self.height] , dtype=np.floataa)) def SCREAMING_SNAKE_CASE ( self : List[Any]) ->Any: '''simple docstring''' return torch.from_numpy(np.array([self.x_fov, self.y_fov] , dtype=np.floataa)) def SCREAMING_SNAKE_CASE ( self : List[str]) ->torch.Tensor: '''simple docstring''' A__ = torch.arange(self.height * self.width) A__ = torch.stack( [ pixel_indices % self.width, torch.div(lowercase_ , self.width , rounding_mode='''trunc'''), ] , axis=1 , ) return coords @property def SCREAMING_SNAKE_CASE ( self : Union[str, Any]) ->Optional[int]: '''simple docstring''' A__ , *A__ = self.shape A__ = int(np.prod(lowercase_)) A__ = self.get_image_coords() A__ = torch.broadcast_to(coords.unsqueeze(0) , [batch_size * inner_batch_size, *coords.shape]) A__ = self.get_camera_rays(lowercase_) A__ = rays.view(lowercase_ , inner_batch_size * self.height * self.width , 2 , 3) return rays def SCREAMING_SNAKE_CASE ( self : Dict , UpperCAmelCase__ : torch.Tensor) ->torch.Tensor: '''simple docstring''' A__ , *A__ , A__ = coords.shape assert n_coords == 2 assert batch_size == self.origin.shape[0] A__ = coords.view(lowercase_ , -1 , 2) A__ = self.resolution() A__ = self.fov() A__ = (flat.float() / (res - 1)) * 2 - 1 A__ = fracs * torch.tan(fov / 2) A__ = fracs.view(lowercase_ , -1 , 2) A__ = ( self.z.view(lowercase_ , 1 , 3) + self.x.view(lowercase_ , 1 , 3) * fracs[:, :, :1] + self.y.view(lowercase_ , 1 , 3) * fracs[:, :, 1:] ) A__ = directions / directions.norm(dim=-1 , keepdim=lowercase_) A__ = torch.stack( [ torch.broadcast_to(self.origin.view(lowercase_ , 1 , 3) , [batch_size, directions.shape[1], 3]), directions, ] , dim=2 , ) return rays.view(lowercase_ , *lowercase_ , 2 , 3) def SCREAMING_SNAKE_CASE ( self : Optional[int] , UpperCAmelCase__ : int , UpperCAmelCase__ : int) ->"DifferentiableProjectiveCamera": '''simple docstring''' assert width * self.height == height * self.width, "The aspect ratio should not change." return DifferentiableProjectiveCamera( origin=self.origin , x=self.x , y=self.y , z=self.z , width=lowercase_ , height=lowercase_ , x_fov=self.x_fov , y_fov=self.y_fov , ) def SCREAMING_SNAKE_CASE ( lowercase_ ) -> Optional[Any]: """simple docstring""" A__ = [] A__ = [] A__ = [] A__ = [] for theta in np.linspace(0 , 2 * np.pi , num=20 ): A__ = np.array([np.sin(lowercase_ ), np.cos(lowercase_ ), -0.5] ) z /= np.sqrt(np.sum(z**2 ) ) A__ = -z * 4 A__ = np.array([np.cos(lowercase_ ), -np.sin(lowercase_ ), 0.0] ) A__ = np.cross(lowercase_ , lowercase_ ) origins.append(lowercase_ ) xs.append(lowercase_ ) ys.append(lowercase_ ) zs.append(lowercase_ ) return DifferentiableProjectiveCamera( origin=torch.from_numpy(np.stack(lowercase_ , axis=0 ) ).float() , x=torch.from_numpy(np.stack(lowercase_ , axis=0 ) ).float() , y=torch.from_numpy(np.stack(lowercase_ , axis=0 ) ).float() , z=torch.from_numpy(np.stack(lowercase_ , axis=0 ) ).float() , width=lowercase_ , height=lowercase_ , x_fov=0.7 , y_fov=0.7 , shape=(1, len(lowercase_ )) , )
14
"""simple docstring""" class A_ : """simple docstring""" def __init__( self :List[str] , lowercase_ :int , lowercase_ :Optional[int]=None , lowercase_ :List[str]=None ) -> str: UpperCAmelCase = data UpperCAmelCase = previous UpperCAmelCase = next_node def __str__( self :Optional[Any] ) -> str: return f"""{self.data}""" def UpperCAmelCase__ ( self :int ) -> int: return self.data def UpperCAmelCase__ ( self :List[str] ) -> Any: return self.next def UpperCAmelCase__ ( self :Tuple ) -> Optional[int]: return self.previous class A_ : """simple docstring""" def __init__( self :Optional[Any] , lowercase_ :Optional[Any] ) -> str: UpperCAmelCase = head def __iter__( self :List[str] ) -> List[str]: return self def UpperCAmelCase__ ( self :int ) -> Any: if not self.current: raise StopIteration else: UpperCAmelCase = self.current.get_data() UpperCAmelCase = self.current.get_next() return value class A_ : """simple docstring""" def __init__( self :Union[str, Any] ) -> List[Any]: UpperCAmelCase = None # First node in list UpperCAmelCase = None # Last node in list def __str__( self :List[Any] ) -> Optional[Any]: UpperCAmelCase = self.head UpperCAmelCase = [] while current is not None: nodes.append(current.get_data() ) UpperCAmelCase = current.get_next() return " ".join(str(lowercase_ ) for node in nodes ) def __contains__( self :str , lowercase_ :int ) -> str: UpperCAmelCase = self.head while current: if current.get_data() == value: return True UpperCAmelCase = current.get_next() return False def __iter__( self :Tuple ) -> Dict: return LinkedListIterator(self.head ) def UpperCAmelCase__ ( self :Optional[int] ) -> Optional[Any]: if self.head: return self.head.get_data() return None def UpperCAmelCase__ ( self :Union[str, Any] ) -> List[str]: if self.tail: return self.tail.get_data() return None def UpperCAmelCase__ ( self :Union[str, Any] , lowercase_ :Node ) -> None: if self.head is None: UpperCAmelCase = node UpperCAmelCase = node else: self.insert_before_node(self.head , lowercase_ ) def UpperCAmelCase__ ( self :Any , lowercase_ :Node ) -> None: if self.head is None: self.set_head(lowercase_ ) else: self.insert_after_node(self.tail , lowercase_ ) def UpperCAmelCase__ ( self :List[str] , lowercase_ :int ) -> None: UpperCAmelCase = Node(lowercase_ ) if self.head is None: self.set_head(lowercase_ ) else: self.set_tail(lowercase_ ) def UpperCAmelCase__ ( self :int , lowercase_ :Node , lowercase_ :Node ) -> None: UpperCAmelCase = node UpperCAmelCase = node.previous if node.get_previous() is None: UpperCAmelCase = node_to_insert else: UpperCAmelCase = node_to_insert UpperCAmelCase = node_to_insert def UpperCAmelCase__ ( self :Union[str, Any] , lowercase_ :Node , lowercase_ :Node ) -> None: UpperCAmelCase = node UpperCAmelCase = node.next if node.get_next() is None: UpperCAmelCase = node_to_insert else: UpperCAmelCase = node_to_insert UpperCAmelCase = node_to_insert def UpperCAmelCase__ ( self :Any , lowercase_ :int , lowercase_ :int ) -> None: UpperCAmelCase = 1 UpperCAmelCase = Node(lowercase_ ) UpperCAmelCase = self.head while node: if current_position == position: self.insert_before_node(lowercase_ , lowercase_ ) return current_position += 1 UpperCAmelCase = node.next self.insert_after_node(self.tail , lowercase_ ) def UpperCAmelCase__ ( self :Optional[Any] , lowercase_ :int ) -> Node: UpperCAmelCase = self.head while node: if node.get_data() == item: return node UpperCAmelCase = node.get_next() raise Exception('Node not found' ) def UpperCAmelCase__ ( self :Any , lowercase_ :Optional[Any] ) -> Dict: if (node := self.get_node(lowercase_ )) is not None: if node == self.head: UpperCAmelCase = self.head.get_next() if node == self.tail: UpperCAmelCase = self.tail.get_previous() self.remove_node_pointers(lowercase_ ) @staticmethod def UpperCAmelCase__ ( lowercase_ :Node ) -> None: if node.get_next(): UpperCAmelCase = node.previous if node.get_previous(): UpperCAmelCase = node.next UpperCAmelCase = None UpperCAmelCase = None def UpperCAmelCase__ ( self :Union[str, Any] ) -> List[str]: return self.head is None def _lowerCAmelCase ( ): pass if __name__ == "__main__": import doctest doctest.testmod()
78
0
'''simple docstring''' import os import shutil import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np from datasets import Dataset from transformers.models.realm.configuration_realm import RealmConfig from transformers.models.realm.retrieval_realm import _REALM_BLOCK_RECORDS_FILENAME, RealmRetriever from transformers.models.realm.tokenization_realm import VOCAB_FILES_NAMES, RealmTokenizer class _lowerCAmelCase ( __UpperCAmelCase ): def _a (self ): A_ : Dict = tempfile.mkdtemp() A_ : Optional[int] = 5 # Realm tok A_ : Optional[Any] = [ """[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """test""", """question""", """this""", """is""", """the""", """first""", """second""", """third""", """fourth""", """fifth""", """record""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] A_ : Tuple = os.path.join(self.tmpdirname , """realm_tokenizer""" ) os.makedirs(lowercase , exist_ok=lowercase ) A_ : Union[str, Any] = os.path.join(lowercase , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) A_ : int = os.path.join(self.tmpdirname , """realm_block_records""" ) os.makedirs(lowercase , exist_ok=lowercase ) def _a (self ): return RealmTokenizer.from_pretrained(os.path.join(self.tmpdirname , """realm_tokenizer""" ) ) def _a (self ): shutil.rmtree(self.tmpdirname ) def _a (self ): A_ : Tuple = RealmConfig(num_block_records=self.num_block_records ) return config def _a (self ): A_ : List[Any] = Dataset.from_dict( { """id""": ["""0""", """1"""], """question""": ["""foo""", """bar"""], """answers""": [["""Foo""", """Bar"""], ["""Bar"""]], } ) return dataset def _a (self ): A_ : Any = np.array( [ b"""This is the first record""", b"""This is the second record""", b"""This is the third record""", b"""This is the fourth record""", b"""This is the fifth record""", b"""This is a longer longer longer record""", ] , dtype=lowercase , ) return block_records def _a (self ): A_ : Any = RealmRetriever( block_records=self.get_dummy_block_records() , tokenizer=self.get_tokenizer() , ) return retriever def _a (self ): A_ : int = self.get_config() A_ : Any = self.get_dummy_retriever() A_ : int = retriever.tokenizer A_ : str = np.array([0, 3] , dtype="""long""" ) A_ : List[str] = tokenizer(["""Test question"""] ).input_ids A_ : List[Any] = tokenizer( ["""the fourth"""] , add_special_tokens=lowercase , return_token_type_ids=lowercase , return_attention_mask=lowercase , ).input_ids A_ : List[str] = config.reader_seq_len A_, A_, A_, A_ : List[Any] = retriever( lowercase , lowercase , answer_ids=lowercase , max_length=lowercase , return_tensors="""np""" ) self.assertEqual(len(lowercase ) , 2 ) self.assertEqual(len(lowercase ) , 2 ) self.assertEqual(len(lowercase ) , 2 ) self.assertEqual(concat_inputs.input_ids.shape , (2, 10) ) self.assertEqual(concat_inputs.attention_mask.shape , (2, 10) ) self.assertEqual(concat_inputs.token_type_ids.shape , (2, 10) ) self.assertEqual(concat_inputs.special_tokens_mask.shape , (2, 10) ) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[0] ) , ["""[CLS]""", """test""", """question""", """[SEP]""", """this""", """is""", """the""", """first""", """record""", """[SEP]"""] , ) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[1] ) , ["""[CLS]""", """test""", """question""", """[SEP]""", """this""", """is""", """the""", """fourth""", """record""", """[SEP]"""] , ) def _a (self ): A_ : str = self.get_config() A_ : Optional[Any] = self.get_dummy_retriever() A_ : Dict = retriever.tokenizer A_ : Optional[Any] = np.array([0, 3, 5] , dtype="""long""" ) A_ : List[Any] = tokenizer(["""Test question"""] ).input_ids A_ : Any = tokenizer( ["""the fourth""", """longer longer"""] , add_special_tokens=lowercase , return_token_type_ids=lowercase , return_attention_mask=lowercase , ).input_ids A_ : List[str] = config.reader_seq_len A_, A_, A_, A_ : Optional[int] = retriever( lowercase , lowercase , answer_ids=lowercase , max_length=lowercase , return_tensors="""np""" ) self.assertEqual([False, True, True] , lowercase ) self.assertEqual([[-1, -1, -1], [6, -1, -1], [6, 7, 8]] , lowercase ) self.assertEqual([[-1, -1, -1], [7, -1, -1], [7, 8, 9]] , lowercase ) def _a (self ): A_ : Optional[int] = self.get_dummy_retriever() retriever.save_pretrained(os.path.join(self.tmpdirname , """realm_block_records""" ) ) # Test local path A_ : Dict = retriever.from_pretrained(os.path.join(self.tmpdirname , """realm_block_records""" ) ) self.assertEqual(retriever.block_records[0] , b"""This is the first record""" ) # Test mocked remote path with patch("""transformers.models.realm.retrieval_realm.hf_hub_download""" ) as mock_hf_hub_download: A_ : Optional[int] = os.path.join( os.path.join(self.tmpdirname , """realm_block_records""" ) , _REALM_BLOCK_RECORDS_FILENAME ) A_ : Dict = RealmRetriever.from_pretrained("""google/realm-cc-news-pretrained-openqa""" ) self.assertEqual(retriever.block_records[0] , b"""This is the first record""" )
135
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from diffusers import ( DDIMScheduler, KandinskyVaaInpaintPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class _lowerCAmelCase ( __UpperCAmelCase , unittest.TestCase ): __SCREAMING_SNAKE_CASE : Tuple = KandinskyVaaInpaintPipeline __SCREAMING_SNAKE_CASE : int = ['image_embeds', 'negative_image_embeds', 'image', 'mask_image'] __SCREAMING_SNAKE_CASE : str = [ 'image_embeds', 'negative_image_embeds', 'image', 'mask_image', ] __SCREAMING_SNAKE_CASE : Optional[Any] = [ 'generator', 'height', 'width', 'latents', 'guidance_scale', 'num_inference_steps', 'return_dict', 'guidance_scale', 'num_images_per_prompt', 'output_type', 'return_dict', ] __SCREAMING_SNAKE_CASE : List[str] = False @property def _a (self ): return 32 @property def _a (self ): return 32 @property def _a (self ): return self.time_input_dim @property def _a (self ): return self.time_input_dim * 4 @property def _a (self ): return 100 @property def _a (self ): torch.manual_seed(0 ) A_ : str = { """in_channels""": 9, # Out channels is double in channels because predicts mean and variance """out_channels""": 8, """addition_embed_type""": """image""", """down_block_types""": ("""ResnetDownsampleBlock2D""", """SimpleCrossAttnDownBlock2D"""), """up_block_types""": ("""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""), """mid_block_type""": """UNetMidBlock2DSimpleCrossAttn""", """block_out_channels""": (self.block_out_channels_a, self.block_out_channels_a * 2), """layers_per_block""": 1, """encoder_hid_dim""": self.text_embedder_hidden_size, """encoder_hid_dim_type""": """image_proj""", """cross_attention_dim""": self.cross_attention_dim, """attention_head_dim""": 4, """resnet_time_scale_shift""": """scale_shift""", """class_embed_type""": None, } A_ : str = UNetaDConditionModel(**lowercase ) return model @property def _a (self ): return { "block_out_channels": [32, 64], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def _a (self ): torch.manual_seed(0 ) A_ : int = VQModel(**self.dummy_movq_kwargs ) return model def _a (self ): A_ : Optional[Any] = self.dummy_unet A_ : Dict = self.dummy_movq A_ : List[Any] = DDIMScheduler( num_train_timesteps=1000 , beta_schedule="""linear""" , beta_start=0.0_00_85 , beta_end=0.0_12 , clip_sample=lowercase , set_alpha_to_one=lowercase , steps_offset=1 , prediction_type="""epsilon""" , thresholding=lowercase , ) A_ : Any = { """unet""": unet, """scheduler""": scheduler, """movq""": movq, } return components def _a (self , lowercase , lowercase=0 ): A_ : Optional[Any] = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(lowercase ) ).to(lowercase ) A_ : List[Any] = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( lowercase ) # create init_image A_ : Any = floats_tensor((1, 3, 64, 64) , rng=random.Random(lowercase ) ).to(lowercase ) A_ : Union[str, Any] = image.cpu().permute(0 , 2 , 3 , 1 )[0] A_ : Tuple = Image.fromarray(np.uinta(lowercase ) ).convert("""RGB""" ).resize((256, 256) ) # create mask A_ : List[str] = np.ones((64, 64) , dtype=np.floataa ) A_ : Any = 0 if str(lowercase ).startswith("""mps""" ): A_ : int = torch.manual_seed(lowercase ) else: A_ : Dict = torch.Generator(device=lowercase ).manual_seed(lowercase ) A_ : Any = { """image""": init_image, """mask_image""": mask, """image_embeds""": image_embeds, """negative_image_embeds""": negative_image_embeds, """generator""": generator, """height""": 64, """width""": 64, """num_inference_steps""": 2, """guidance_scale""": 4.0, """output_type""": """np""", } return inputs def _a (self ): A_ : List[str] = """cpu""" A_ : str = self.get_dummy_components() A_ : Any = self.pipeline_class(**lowercase ) A_ : List[Any] = pipe.to(lowercase ) pipe.set_progress_bar_config(disable=lowercase ) A_ : Union[str, Any] = pipe(**self.get_dummy_inputs(lowercase ) ) A_ : List[str] = output.images A_ : Union[str, Any] = pipe( **self.get_dummy_inputs(lowercase ) , return_dict=lowercase , )[0] A_ : List[str] = image[0, -3:, -3:, -1] A_ : Any = image_from_tuple[0, -3:, -3:, -1] print(F'image.shape {image.shape}' ) assert image.shape == (1, 64, 64, 3) A_ : Optional[int] = np.array( [0.50_77_59_03, 0.49_52_71_95, 0.48_82_45_43, 0.50_19_22_37, 0.48_64_49_06, 0.49_37_38_14, 0.4_78_05_98, 0.47_23_48_27, 0.48_32_78_48] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 ), F' expected_slice {expected_slice}, but got {image_slice.flatten()}' assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 ), F' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}' def _a (self ): super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class _lowerCAmelCase ( unittest.TestCase ): def _a (self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def _a (self ): A_ : Optional[Any] = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinskyv22/kandinskyv22_inpaint_cat_with_hat_fp16.npy""" ) A_ : Optional[Any] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinsky/cat.png""" ) A_ : Dict = np.ones((768, 768) , dtype=np.floataa ) A_ : Any = 0 A_ : str = """a hat""" A_ : Union[str, Any] = KandinskyVaaPriorPipeline.from_pretrained( """kandinsky-community/kandinsky-2-2-prior""" , torch_dtype=torch.floataa ) pipe_prior.to(lowercase ) A_ : Union[str, Any] = KandinskyVaaInpaintPipeline.from_pretrained( """kandinsky-community/kandinsky-2-2-decoder-inpaint""" , torch_dtype=torch.floataa ) A_ : str = pipeline.to(lowercase ) pipeline.set_progress_bar_config(disable=lowercase ) A_ : int = torch.Generator(device="""cpu""" ).manual_seed(0 ) A_, A_ : Dict = pipe_prior( lowercase , generator=lowercase , num_inference_steps=5 , negative_prompt="""""" , ).to_tuple() A_ : List[Any] = pipeline( image=lowercase , mask_image=lowercase , image_embeds=lowercase , negative_image_embeds=lowercase , generator=lowercase , num_inference_steps=100 , height=768 , width=768 , output_type="""np""" , ) A_ : Tuple = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(lowercase , lowercase )
135
1
'''simple docstring''' import unittest from transformers import AlbertTokenizer, AlbertTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin __snake_case =get_tests_dir("""fixtures/spiece.model""") @require_sentencepiece @require_tokenizers class UpperCAmelCase_ ( __lowercase , unittest.TestCase ): lowerCamelCase : List[str] = AlbertTokenizer lowerCamelCase : Dict = AlbertTokenizerFast lowerCamelCase : Optional[Any] = True lowerCamelCase : Any = True lowerCamelCase : str = True def __UpperCAmelCase ( self : int ) -> int: super().setUp() # We have a SentencePiece fixture for testing lowerCAmelCase = AlbertTokenizer(UpperCAmelCase__ ) tokenizer.save_pretrained(self.tmpdirname ) def __UpperCAmelCase ( self : Union[str, Any] , UpperCAmelCase__ : List[str] ) -> Union[str, Any]: lowerCAmelCase = 'this is a test' lowerCAmelCase = 'this is a test' return input_text, output_text def __UpperCAmelCase ( self : List[str] ) -> List[Any]: lowerCAmelCase = '<pad>' lowerCAmelCase = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCAmelCase__ ) , UpperCAmelCase__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCAmelCase__ ) , UpperCAmelCase__ ) def __UpperCAmelCase ( self : Tuple ) -> int: lowerCAmelCase = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<pad>' ) self.assertEqual(vocab_keys[1] , '<unk>' ) self.assertEqual(vocab_keys[-1] , '▁eloquent' ) self.assertEqual(len(UpperCAmelCase__ ) , 3_0_0_0_0 ) def __UpperCAmelCase ( self : str ) -> List[str]: self.assertEqual(self.get_tokenizer().vocab_size , 3_0_0_0_0 ) def __UpperCAmelCase ( self : Tuple ) -> Union[str, Any]: if not self.test_rust_tokenizer: return lowerCAmelCase = self.get_tokenizer() lowerCAmelCase = self.get_rust_tokenizer() lowerCAmelCase = 'I was born in 92000, and this is falsé.' lowerCAmelCase = tokenizer.tokenize(UpperCAmelCase__ ) lowerCAmelCase = rust_tokenizer.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) lowerCAmelCase = tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) lowerCAmelCase = rust_tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) lowerCAmelCase = self.get_rust_tokenizer() lowerCAmelCase = tokenizer.encode(UpperCAmelCase__ ) lowerCAmelCase = rust_tokenizer.encode(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) def __UpperCAmelCase ( self : str ) -> str: lowerCAmelCase = AlbertTokenizer(UpperCAmelCase__ , keep_accents=UpperCAmelCase__ ) lowerCAmelCase = tokenizer.tokenize('This is a test' ) self.assertListEqual(UpperCAmelCase__ , ['▁this', '▁is', '▁a', '▁test'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) , [4_8, 2_5, 2_1, 1_2_8_9] ) lowerCAmelCase = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( UpperCAmelCase__ , ['▁i', '▁was', '▁born', '▁in', '▁9', '2000', ',', '▁and', '▁this', '▁is', '▁fal', 's', 'é', '.'] ) lowerCAmelCase = tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , [3_1, 2_3, 3_8_6, 1_9, 5_6_1, 3_0_5_0, 1_5, 1_7, 4_8, 2_5, 8_2_5_6, 1_8, 1, 9] ) lowerCAmelCase = tokenizer.convert_ids_to_tokens(UpperCAmelCase__ ) self.assertListEqual( UpperCAmelCase__ , ['▁i', '▁was', '▁born', '▁in', '▁9', '2000', ',', '▁and', '▁this', '▁is', '▁fal', 's', '<unk>', '.'] , ) def __UpperCAmelCase ( self : str ) -> Tuple: lowerCAmelCase = AlbertTokenizer(UpperCAmelCase__ ) lowerCAmelCase = tokenizer.encode('sequence builders' ) lowerCAmelCase = tokenizer.encode('multi-sequence build' ) lowerCAmelCase = tokenizer.build_inputs_with_special_tokens(UpperCAmelCase__ ) lowerCAmelCase = tokenizer.build_inputs_with_special_tokens(UpperCAmelCase__ , UpperCAmelCase__ ) assert encoded_sentence == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [ tokenizer.sep_token_id ] @slow def __UpperCAmelCase ( self : Dict ) -> int: # fmt: off lowerCAmelCase = {'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'input_ids': [[2, 2_1_9_7_0, 1_3, 5, 6_0_9_2, 1_6_7, 2_8, 7_1_0_3, 2_1_5_3, 6_7_3, 8, 7_0_2_8, 1_2_0_5_1, 1_8, 1_7, 7_1_0_3, 2_1_5_3, 6_7_3, 8, 3_5_1_5, 1_8_6_8_4, 8, 4_4_6_1, 6, 1_9_2_7, 2_9_7, 8, 1_2_0_6_0, 2_6_0_7, 1_8, 1_3, 5, 4_4_6_1, 1_5, 1_0_5_3_8, 3_8, 8, 1_3_5, 1_5, 8_2_2, 5_8, 1_5, 9_9_3, 1_0_3_6_3, 1_5, 1_4_6_0, 8_0_0_5, 4_4_6_1, 1_5, 9_9_3, 2_5_5, 2_3_2_8, 9, 9, 9, 6, 2_6, 1_1_1_2, 8_1_6, 3_2_6_0, 1_3, 5, 1_0_3, 2_3_7_7, 6, 1_7, 1_1_1_2, 8_1_6, 2_7_8_2, 1_3, 5, 1_0_3, 1_0_6_4_1, 6, 2_9, 8_4, 2_5_1_2, 2_4_3_0, 7_8_2, 1_8_6_8_4, 2_7_6_1, 1_9, 8_0_8, 2_4_3_0, 2_5_5_6, 1_7, 8_5_5, 1_4_8_0, 9_4_7_7, 4_0_9_1, 1_2_8, 1_1_7_1_2, 1_5, 7_1_0_3, 2_1_5_3, 6_7_3, 1_7, 2_4_8_8_3, 9_9_9_0, 9, 3], [2, 1_1_5_0_2, 2_5, 1_0_0_6, 2_0, 7_8_2, 8, 1_1_8_0_9, 8_5_5, 1_7_3_2, 1_9_3_9_3, 1_8_6_6_7, 3_7, 3_6_7, 2_1_0_1_8, 6_9, 1_8_5_4, 3_4, 1_1_8_6_0, 1_9_1_2_4, 2_7, 1_5_6, 2_2_5, 1_7, 1_9_3, 4_1_4_1, 1_9, 6_5, 9_1_2_4, 9, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [2, 1_4, 2_2_3_1, 8_8_6, 2_3_8_5, 1_7_6_5_9, 8_4, 1_4, 1_6_7_9_2, 1_9_5_2, 9, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'token_type_ids': [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=UpperCAmelCase__ , model_name='albert-base-v2' , revision='6b6560eaf5ff2e250b00c50f380c5389a9c2d82e' , )
4
'''simple docstring''' import datasets from .nmt_bleu import compute_bleu # From: https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py __snake_case ="""\ @INPROCEEDINGS{Papineni02bleu:a, author = {Kishore Papineni and Salim Roukos and Todd Ward and Wei-jing Zhu}, title = {BLEU: a Method for Automatic Evaluation of Machine Translation}, booktitle = {}, year = {2002}, pages = {311--318} } @inproceedings{lin-och-2004-orange, title = \"{ORANGE}: a Method for Evaluating Automatic Evaluation Metrics for Machine Translation\", author = \"Lin, Chin-Yew and Och, Franz Josef\", booktitle = \"{COLING} 2004: Proceedings of the 20th International Conference on Computational Linguistics\", month = \"aug 23{--}aug 27\", year = \"2004\", address = \"Geneva, Switzerland\", publisher = \"COLING\", url = \"https://www.aclweb.org/anthology/C04-1072\", pages = \"501--507\", } """ __snake_case ="""\ BLEU (bilingual evaluation understudy) is an algorithm for evaluating the quality of text which has been machine-translated from one natural language to another. Quality is considered to be the correspondence between a machine's output and that of a human: \"the closer a machine translation is to a professional human translation, the better it is\" – this is the central idea behind BLEU. BLEU was one of the first metrics to claim a high correlation with human judgements of quality, and remains one of the most popular automated and inexpensive metrics. Scores are calculated for individual translated segments—generally sentences—by comparing them with a set of good quality reference translations. Those scores are then averaged over the whole corpus to reach an estimate of the translation's overall quality. Intelligibility or grammatical correctness are not taken into account[citation needed]. BLEU's output is always a number between 0 and 1. This value indicates how similar the candidate text is to the reference texts, with values closer to 1 representing more similar texts. Few human translations will attain a score of 1, since this would indicate that the candidate is identical to one of the reference translations. For this reason, it is not necessary to attain a score of 1. Because there are more opportunities to match, adding additional reference translations will increase the BLEU score. """ __snake_case =""" Computes BLEU score of translated segments against one or more references. Args: predictions: list of translations 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. max_order: Maximum n-gram order to use when computing BLEU score. smooth: Whether or not to apply Lin et al. 2004 smoothing. Returns: 'bleu': bleu score, 'precisions': geometric mean of n-gram precisions, 'brevity_penalty': brevity penalty, 'length_ratio': ratio of lengths, 'translation_length': translation_length, 'reference_length': reference_length Examples: >>> predictions = [ ... [\"hello\", \"there\", \"general\", \"kenobi\"], # tokenized prediction of the first sample ... [\"foo\", \"bar\", \"foobar\"] # tokenized prediction of the second sample ... ] >>> references = [ ... [[\"hello\", \"there\", \"general\", \"kenobi\"], [\"hello\", \"there\", \"!\"]], # tokenized references for the first sample (2 references) ... [[\"foo\", \"bar\", \"foobar\"]] # tokenized references for the second sample (1 reference) ... ] >>> bleu = datasets.load_metric(\"bleu\") >>> results = bleu.compute(predictions=predictions, references=references) >>> print(results[\"bleu\"]) 1.0 """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCAmelCase_ ( datasets.Metric ): def __UpperCAmelCase ( self : Tuple ) -> int: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Sequence(datasets.Value('string' , id='token' ) , id='sequence' ), 'references': datasets.Sequence( datasets.Sequence(datasets.Value('string' , id='token' ) , id='sequence' ) , id='references' ), } ) , codebase_urls=['https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py'] , reference_urls=[ 'https://en.wikipedia.org/wiki/BLEU', 'https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213', ] , ) def __UpperCAmelCase ( self : Optional[int] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Any , UpperCAmelCase__ : Union[str, Any]=4 , UpperCAmelCase__ : Optional[int]=False ) -> int: lowerCAmelCase = compute_bleu( reference_corpus=UpperCAmelCase__ , translation_corpus=UpperCAmelCase__ , max_order=UpperCAmelCase__ , smooth=UpperCAmelCase__ ) ((lowerCAmelCase) , (lowerCAmelCase) , (lowerCAmelCase) , (lowerCAmelCase) , (lowerCAmelCase) , (lowerCAmelCase)) = score return { "bleu": bleu, "precisions": precisions, "brevity_penalty": bp, "length_ratio": ratio, "translation_length": translation_length, "reference_length": reference_length, }
4
1
import math def A ( _lowercase , _lowercase ): SCREAMING_SNAKE_CASE : Union[str, Any] = len(_lowercase ) SCREAMING_SNAKE_CASE : List[Any] = int(math.floor(math.sqrt(_lowercase ) ) ) SCREAMING_SNAKE_CASE : Optional[Any] = 0 while arr[min(_lowercase , _lowercase ) - 1] < x: SCREAMING_SNAKE_CASE : List[Any] = step step += int(math.floor(math.sqrt(_lowercase ) ) ) if prev >= n: return -1 while arr[prev] < x: SCREAMING_SNAKE_CASE : Optional[Any] = prev + 1 if prev == min(_lowercase , _lowercase ): return -1 if arr[prev] == x: return prev return -1 if __name__ == "__main__": __UpperCamelCase : Any = input('Enter numbers separated by a comma:\n').strip() __UpperCamelCase : Optional[Any] = [int(item) for item in user_input.split(',')] __UpperCamelCase : int = int(input('Enter the number to be searched:\n')) __UpperCamelCase : Optional[Any] = jump_search(arr, x) if res == -1: print('Number not found!') else: print(f"""Number {x} is at index {res}""")
258
from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import BaseOutput, is_torch_available, is_transformers_available @dataclass class lowercase__ ( UpperCamelCase_): UpperCamelCase_ = 42 UpperCamelCase_ = 42 if is_transformers_available() and is_torch_available(): from .pipeline_semantic_stable_diffusion import SemanticStableDiffusionPipeline
258
1
"""simple docstring""" _a = 9.8_0665 def __a ( __lowerCamelCase, __lowerCamelCase, __lowerCamelCase = g ): if fluid_density <= 0: raise ValueError("Impossible fluid density" ) if volume < 0: raise ValueError("Impossible Object volume" ) if gravity <= 0: raise ValueError("Impossible Gravity" ) return fluid_density * gravity * volume if __name__ == "__main__": import doctest # run doctest doctest.testmod()
61
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase_ : Optional[Any] = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : str = ["""NllbTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : Dict = ["""NllbTokenizerFast"""] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_nllb import NllbTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_nllb_fast import NllbTokenizerFast else: import sys lowerCamelCase_ : int = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
81
0
import math import random from typing import Any from .hill_climbing import SearchProblem def __a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = math.inf , _SCREAMING_SNAKE_CASE = -math.inf , _SCREAMING_SNAKE_CASE = math.inf , _SCREAMING_SNAKE_CASE = -math.inf , _SCREAMING_SNAKE_CASE = False , _SCREAMING_SNAKE_CASE = 100 , _SCREAMING_SNAKE_CASE = 0.01 , _SCREAMING_SNAKE_CASE = 1 , ) ->Any: a__: Tuple = False a__: Tuple = search_prob a__: int = start_temperate a__: Dict = [] a__: List[str] = 0 a__: List[str] = None while not search_end: a__: Optional[int] = current_state.score() if best_state is None or current_score > best_state.score(): a__: List[Any] = current_state scores.append(_SCREAMING_SNAKE_CASE ) iterations += 1 a__: int = None a__: str = current_state.get_neighbors() while ( next_state is None and neighbors ): # till we do not find a neighbor that we can move to a__: Optional[int] = random.randint(0 , len(_SCREAMING_SNAKE_CASE ) - 1 ) # picking a random neighbor a__: Tuple = neighbors.pop(_SCREAMING_SNAKE_CASE ) a__: str = picked_neighbor.score() - current_score if ( picked_neighbor.x > max_x or picked_neighbor.x < min_x or picked_neighbor.y > max_y or picked_neighbor.y < min_y ): continue # neighbor outside our bounds if not find_max: a__: List[Any] = change * -1 # in case we are finding minimum if change > 0: # improves the solution a__: str = picked_neighbor else: a__: int = (math.e) ** ( change / current_temp ) # probability generation function if random.random() < probability: # random number within probability a__: Tuple = picked_neighbor a__: str = current_temp - (current_temp * rate_of_decrease) if current_temp < threshold_temp or next_state is None: # temperature below threshold, or could not find a suitable neighbor a__: List[Any] = True else: a__: Any = next_state if visualization: from matplotlib import pyplot as plt plt.plot(range(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) plt.xlabel('Iterations' ) plt.ylabel('Function values' ) plt.show() return best_state if __name__ == "__main__": def __a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Optional[int]: return (x**2) + (y**2) # starting the problem with initial coordinates (12, 47) lowercase__ = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_fa) lowercase__ = simulated_annealing( prob, find_max=False, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True ) print( 'The minimum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 ' f"and 50 > y > - 5 found via hill climbing: {local_min.score()}" ) # starting the problem with initial coordinates (12, 47) lowercase__ = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_fa) lowercase__ = simulated_annealing( prob, find_max=True, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True ) print( 'The maximum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 ' f"and 50 > y > - 5 found via hill climbing: {local_min.score()}" ) def __a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->List[Any]: return (3 * x**2) - (6 * y) lowercase__ = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa) lowercase__ = simulated_annealing(prob, find_max=False, visualization=True) print( 'The minimum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: ' f"{local_min.score()}" ) lowercase__ = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa) lowercase__ = simulated_annealing(prob, find_max=True, visualization=True) print( 'The maximum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: ' f"{local_min.score()}" )
358
"""simple docstring""" def __a ( _SCREAMING_SNAKE_CASE ) ->bool: return credit_card_number.startswith(('34', '35', '37', '4', '5', '6') ) def __a ( _SCREAMING_SNAKE_CASE ) ->bool: a__: Any = credit_card_number a__: Tuple = 0 a__: List[str] = len(_SCREAMING_SNAKE_CASE ) - 2 for i in range(_SCREAMING_SNAKE_CASE , -1 , -2 ): # double the value of every second digit a__: Tuple = int(cc_number[i] ) digit *= 2 # If doubling of a number results in a two digit number # i.e greater than 9(e.g., 6 × 2 = 12), # then add the digits of the product (e.g., 12: 1 + 2 = 3, 15: 1 + 5 = 6), # to get a single digit number. if digit > 9: digit %= 10 digit += 1 a__: Optional[Any] = cc_number[:i] + str(_SCREAMING_SNAKE_CASE ) + cc_number[i + 1 :] total += digit # Sum up the remaining digits for i in range(len(_SCREAMING_SNAKE_CASE ) - 1 , -1 , -2 ): total += int(cc_number[i] ) return total % 10 == 0 def __a ( _SCREAMING_SNAKE_CASE ) ->bool: a__: Optional[int] = F'{credit_card_number} is an invalid credit card number because' if not credit_card_number.isdigit(): print(F'{error_message} it has nonnumerical characters.' ) return False if not 13 <= len(_SCREAMING_SNAKE_CASE ) <= 16: print(F'{error_message} of its length.' ) return False if not validate_initial_digits(_SCREAMING_SNAKE_CASE ): print(F'{error_message} of its first two digits.' ) return False if not luhn_validation(_SCREAMING_SNAKE_CASE ): print(F'{error_message} it fails the Luhn check.' ) return False print(F'{credit_card_number} is a valid credit card number.' ) return True if __name__ == "__main__": import doctest doctest.testmod() validate_credit_card_number('4111111111111111') validate_credit_card_number('32323')
203
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase : Optional[Any] ={ '''configuration_xlm_roberta''': [ '''XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XLMRobertaConfig''', '''XLMRobertaOnnxConfig''', ], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Any =['''XLMRobertaTokenizer'''] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : List[Any] =['''XLMRobertaTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : str =[ '''XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XLMRobertaForCausalLM''', '''XLMRobertaForMaskedLM''', '''XLMRobertaForMultipleChoice''', '''XLMRobertaForQuestionAnswering''', '''XLMRobertaForSequenceClassification''', '''XLMRobertaForTokenClassification''', '''XLMRobertaModel''', '''XLMRobertaPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : List[Any] =[ '''TF_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFXLMRobertaForCausalLM''', '''TFXLMRobertaForMaskedLM''', '''TFXLMRobertaForMultipleChoice''', '''TFXLMRobertaForQuestionAnswering''', '''TFXLMRobertaForSequenceClassification''', '''TFXLMRobertaForTokenClassification''', '''TFXLMRobertaModel''', '''TFXLMRobertaPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Optional[int] =[ '''FLAX_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST''', '''FlaxXLMRobertaForMaskedLM''', '''FlaxXLMRobertaForCausalLM''', '''FlaxXLMRobertaForMultipleChoice''', '''FlaxXLMRobertaForQuestionAnswering''', '''FlaxXLMRobertaForSequenceClassification''', '''FlaxXLMRobertaForTokenClassification''', '''FlaxXLMRobertaModel''', '''FlaxXLMRobertaPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_xlm_roberta import ( XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMRobertaConfig, XLMRobertaOnnxConfig, ) try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlm_roberta import XLMRobertaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlm_roberta_fast import XLMRobertaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm_roberta import ( XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, XLMRobertaForCausalLM, XLMRobertaForMaskedLM, XLMRobertaForMultipleChoice, XLMRobertaForQuestionAnswering, XLMRobertaForSequenceClassification, XLMRobertaForTokenClassification, XLMRobertaModel, XLMRobertaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlm_roberta import ( TF_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLMRobertaForCausalLM, TFXLMRobertaForMaskedLM, TFXLMRobertaForMultipleChoice, TFXLMRobertaForQuestionAnswering, TFXLMRobertaForSequenceClassification, TFXLMRobertaForTokenClassification, TFXLMRobertaModel, TFXLMRobertaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_xlm_roberta import ( FLAX_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, FlaxXLMRobertaForCausalLM, FlaxXLMRobertaForMaskedLM, FlaxXLMRobertaForMultipleChoice, FlaxXLMRobertaForQuestionAnswering, FlaxXLMRobertaForSequenceClassification, FlaxXLMRobertaForTokenClassification, FlaxXLMRobertaModel, FlaxXLMRobertaPreTrainedModel, ) else: import sys lowerCamelCase : Union[str, Any] =_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
189
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) lowerCamelCase : Tuple =_symbol_database.Default() lowerCamelCase : List[str] =_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''' ) lowerCamelCase : str =globals() _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, '''sentencepiece_model_pb2''', _globals) if _descriptor._USE_C_DESCRIPTORS is False: lowerCamelCase : Optional[int] =None lowerCamelCase : Tuple =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" lowerCamelCase : List[str] =45 lowerCamelCase : List[Any] =1581 lowerCamelCase : Optional[int] =1517 lowerCamelCase : Tuple =1570 lowerCamelCase : Dict =1584 lowerCamelCase : Optional[Any] =1793 lowerCamelCase : Dict =1795 lowerCamelCase : Any =1916 lowerCamelCase : Dict =1864 lowerCamelCase : Dict =1905 lowerCamelCase : Dict =1919 lowerCamelCase : Union[str, Any] =2429 lowerCamelCase : List[Any] =2208 lowerCamelCase : List[Any] =2418 lowerCamelCase : List[str] =2323 lowerCamelCase : Dict =2407 # @@protoc_insertion_point(module_scope)
189
1
"""simple docstring""" import warnings from ...utils import logging from .image_processing_poolformer import PoolFormerImageProcessor snake_case__ : Tuple = logging.get_logger(__name__) class snake_case_( a__ ): def __init__( self : Optional[Any] , *UpperCamelCase_ : Optional[int] , **UpperCamelCase_ : List[str] ): warnings.warn( '''The class PoolFormerFeatureExtractor is deprecated and will be removed in version 5 of Transformers.''' ''' Please use PoolFormerImageProcessor instead.''' , UpperCamelCase_ , ) super().__init__(*UpperCamelCase_ , **UpperCamelCase_ )
360
"""simple docstring""" def _snake_case ( _snake_case : int = 50000000 ): lowerCAmelCase : List[str] = set() lowerCAmelCase : List[Any] = int((limit - 24) ** (1 / 2) ) lowerCAmelCase : Optional[int] = set(range(3 , prime_square_limit + 1 , 2 ) ) primes.add(2 ) for p in range(3 , prime_square_limit + 1 , 2 ): if p not in primes: continue primes.difference_update(set(range(p * p , prime_square_limit + 1 , _snake_case ) ) ) for primea in primes: lowerCAmelCase : Optional[Any] = primea * primea for primea in primes: lowerCAmelCase : List[Any] = primea * primea * primea if square + cube >= limit - 16: break for primea in primes: lowerCAmelCase : Tuple = primea * primea * primea * primea lowerCAmelCase : Tuple = square + cube + tetr if total >= limit: break ret.add(_snake_case ) return len(_snake_case ) if __name__ == "__main__": print(f"""{solution() = }""")
314
0
import json import os import unittest from transformers.models.roc_bert.tokenization_roc_bert import ( VOCAB_FILES_NAMES, RoCBertBasicTokenizer, RoCBertTokenizer, RoCBertWordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class lowercase__ ( __a , unittest.TestCase ): A__ : str =RoCBertTokenizer A__ : Tuple =None A__ : Optional[int] =False A__ : Optional[int] =True A__ : Any =filter_non_english def A_ ( self : Any ): super().setUp() SCREAMING_SNAKE_CASE__ = ["""[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """你""", """好""", """是""", """谁""", """a""", """b""", """c""", """d"""] SCREAMING_SNAKE_CASE__ = {} SCREAMING_SNAKE_CASE__ = {} for i, value in enumerate(_A ): SCREAMING_SNAKE_CASE__ = i SCREAMING_SNAKE_CASE__ = i SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['word_shape_file'] ) SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['word_pronunciation_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) with open(self.word_shape_file , 'w' , encoding='utf-8' ) as word_shape_writer: json.dump(_A , _A , ensure_ascii=_A ) with open(self.word_pronunciation_file , 'w' , encoding='utf-8' ) as word_pronunciation_writer: json.dump(_A , _A , ensure_ascii=_A ) def A_ ( self : Optional[int] ): SCREAMING_SNAKE_CASE__ = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) SCREAMING_SNAKE_CASE__ = tokenizer.tokenize('你好[SEP]你是谁' ) self.assertListEqual(_A , ['你', '好', '[SEP]', '你', '是', '谁'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_A ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(_A ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(_A ) , [5, 6, 2, 5, 7, 8] ) def A_ ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer() self.assertListEqual(tokenizer.tokenize('ah\u535A\u63A8zz' ) , ['ah', '\u535A', '\u63A8', 'zz'] ) def A_ ( self : str ): SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=_A ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['hello', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def A_ ( self : Any ): SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hällo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['h\u00E9llo'] ) def A_ ( self : int ): SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def A_ ( self : Tuple ): SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def A_ ( self : int ): SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=_A ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?'] ) def A_ ( self : str ): SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HäLLo', '!', 'how', 'Are', 'yoU', '?'] ) def A_ ( self : List[Any] ): SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HaLLo', '!', 'how', 'Are', 'yoU', '?'] ) def A_ ( self : Optional[int] ): SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=_A , never_split=['[UNK]'] ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? [UNK]' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?', '[UNK]'] ) def A_ ( self : int ): SCREAMING_SNAKE_CASE__ = ["""[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing"""] SCREAMING_SNAKE_CASE__ = {} for i, token in enumerate(_A ): SCREAMING_SNAKE_CASE__ = i SCREAMING_SNAKE_CASE__ = RoCBertWordpieceTokenizer(vocab=_A , unk_token='[UNK]' ) self.assertListEqual(tokenizer.tokenize('' ) , [] ) self.assertListEqual(tokenizer.tokenize('unwanted running' ) , ['un', '##want', '##ed', 'runn', '##ing'] ) self.assertListEqual(tokenizer.tokenize('unwantedX running' ) , ['[UNK]', 'runn', '##ing'] ) def A_ ( self : Dict ): self.assertTrue(_is_whitespace(' ' ) ) self.assertTrue(_is_whitespace('\t' ) ) self.assertTrue(_is_whitespace('\r' ) ) self.assertTrue(_is_whitespace('\n' ) ) self.assertTrue(_is_whitespace('\u00A0' ) ) self.assertFalse(_is_whitespace('A' ) ) self.assertFalse(_is_whitespace('-' ) ) def A_ ( self : Union[str, Any] ): self.assertTrue(_is_control('\u0005' ) ) self.assertFalse(_is_control('A' ) ) self.assertFalse(_is_control(' ' ) ) self.assertFalse(_is_control('\t' ) ) self.assertFalse(_is_control('\r' ) ) def A_ ( self : str ): self.assertTrue(_is_punctuation('-' ) ) self.assertTrue(_is_punctuation('$' ) ) self.assertTrue(_is_punctuation('`' ) ) self.assertTrue(_is_punctuation('.' ) ) self.assertFalse(_is_punctuation('A' ) ) self.assertFalse(_is_punctuation(' ' ) ) def A_ ( self : List[Any] ): SCREAMING_SNAKE_CASE__ = self.get_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(_A ) for t in ['Test', '\xad', 'test']] , [['[UNK]'], [], ['[UNK]']] ) if self.test_rust_tokenizer: SCREAMING_SNAKE_CASE__ = self.get_rust_tokenizer() self.assertListEqual( [rust_tokenizer.tokenize(_A ) for t in ['Test', '\xad', 'test']] , [['[UNK]'], [], ['[UNK]']] ) def A_ ( self : List[str] ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})' ): SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained(_A , **_A ) SCREAMING_SNAKE_CASE__ = F'A, naïve {tokenizer_r.mask_token} AllenNLP sentence.' SCREAMING_SNAKE_CASE__ = tokenizer_r.encode_plus( _A , return_attention_mask=_A , return_token_type_ids=_A , return_offsets_mapping=_A , add_special_tokens=_A , ) SCREAMING_SNAKE_CASE__ = tokenizer_r.do_lower_case if hasattr(_A , 'do_lower_case' ) else False SCREAMING_SNAKE_CASE__ = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), """A"""), ((1, 2), ""","""), ((3, 5), """na"""), ((5, 6), """##ï"""), ((6, 8), """##ve"""), ((9, 15), tokenizer_r.mask_token), ((16, 21), """Allen"""), ((21, 23), """##NL"""), ((23, 24), """##P"""), ((25, 33), """sentence"""), ((33, 34), """."""), ((0, 0), tokenizer_r.sep_token), ] if not do_lower_case else [ ((0, 0), tokenizer_r.cls_token), ((0, 1), """a"""), ((1, 2), ""","""), ((3, 8), """naive"""), ((9, 15), tokenizer_r.mask_token), ((16, 21), """allen"""), ((21, 23), """##nl"""), ((23, 24), """##p"""), ((25, 33), """sentence"""), ((33, 34), """."""), ((0, 0), tokenizer_r.sep_token), ] ) self.assertEqual( [e[1] for e in expected_results] , tokenizer_r.convert_ids_to_tokens(tokens['input_ids'] ) ) self.assertEqual([e[0] for e in expected_results] , tokens['offset_mapping'] ) def A_ ( self : List[Any] ): SCREAMING_SNAKE_CASE__ = ["""的""", """人""", """有"""] SCREAMING_SNAKE_CASE__ = """""".join(_A ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})' ): SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = self.tokenizer_class.from_pretrained(_A , **_A ) SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained(_A , **_A ) SCREAMING_SNAKE_CASE__ = tokenizer_p.encode(_A , add_special_tokens=_A ) SCREAMING_SNAKE_CASE__ = tokenizer_r.encode(_A , add_special_tokens=_A ) SCREAMING_SNAKE_CASE__ = tokenizer_r.convert_ids_to_tokens(_A ) SCREAMING_SNAKE_CASE__ = tokenizer_p.convert_ids_to_tokens(_A ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(_A , _A ) self.assertListEqual(_A , _A ) SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained(_A , **_A ) SCREAMING_SNAKE_CASE__ = self.tokenizer_class.from_pretrained(_A , **_A ) SCREAMING_SNAKE_CASE__ = tokenizer_r.encode(_A , add_special_tokens=_A ) SCREAMING_SNAKE_CASE__ = tokenizer_p.encode(_A , add_special_tokens=_A ) SCREAMING_SNAKE_CASE__ = tokenizer_r.convert_ids_to_tokens(_A ) SCREAMING_SNAKE_CASE__ = tokenizer_p.convert_ids_to_tokens(_A ) # it is expected that only the first Chinese character is not preceded by "##". SCREAMING_SNAKE_CASE__ = [ F'##{token}' if idx != 0 else token for idx, token in enumerate(_A ) ] self.assertListEqual(_A , _A ) self.assertListEqual(_A , _A ) @slow def A_ ( self : Optional[Any] ): SCREAMING_SNAKE_CASE__ = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) SCREAMING_SNAKE_CASE__ = tokenizer.encode('你好' , add_special_tokens=_A ) SCREAMING_SNAKE_CASE__ = tokenizer.encode('你是谁' , add_special_tokens=_A ) SCREAMING_SNAKE_CASE__ = tokenizer.build_inputs_with_special_tokens(_A ) SCREAMING_SNAKE_CASE__ = tokenizer.build_inputs_with_special_tokens(_A , _A ) assert encoded_sentence == [1] + text + [2] assert encoded_pair == [1] + text + [2] + text_a + [2] def A_ ( self : Any ): SCREAMING_SNAKE_CASE__ = self.get_tokenizers(do_lower_case=_A ) for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): SCREAMING_SNAKE_CASE__ = """你好,你是谁""" SCREAMING_SNAKE_CASE__ = tokenizer.tokenize(_A ) SCREAMING_SNAKE_CASE__ = tokenizer.convert_tokens_to_ids(_A ) SCREAMING_SNAKE_CASE__ = tokenizer.convert_tokens_to_shape_ids(_A ) SCREAMING_SNAKE_CASE__ = tokenizer.convert_tokens_to_pronunciation_ids(_A ) SCREAMING_SNAKE_CASE__ = tokenizer.prepare_for_model( _A , _A , _A , add_special_tokens=_A ) SCREAMING_SNAKE_CASE__ = tokenizer.encode_plus(_A , add_special_tokens=_A ) self.assertEqual(_A , _A )
176
"""simple docstring""" import argparse import collections import os import re from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_table.py lowerCamelCase__ : List[Any] = '''src/transformers''' lowerCamelCase__ : Union[str, Any] = '''docs/source/en''' lowerCamelCase__ : Optional[int] = '''.''' def UpperCamelCase ( _lowerCAmelCase : Any, _lowerCAmelCase : Optional[Any], _lowerCAmelCase : Optional[int] ) -> Union[str, Any]: with open(_lowerCAmelCase, """r""", encoding="""utf-8""", newline="""\n""" ) as f: _UpperCAmelCase : str = f.readlines() # Find the start prompt. _UpperCAmelCase : Dict = 0 while not lines[start_index].startswith(_lowerCAmelCase ): start_index += 1 start_index += 1 _UpperCAmelCase : List[Any] = start_index while not lines[end_index].startswith(_lowerCAmelCase ): end_index += 1 end_index -= 1 while len(lines[start_index] ) <= 1: start_index += 1 while len(lines[end_index] ) <= 1: end_index -= 1 end_index += 1 return "".join(lines[start_index:end_index] ), start_index, end_index, lines # Add here suffixes that are used to identify models, separated by | lowerCamelCase__ : Dict = '''Model|Encoder|Decoder|ForConditionalGeneration''' # Regexes that match TF/Flax/PT model names. lowerCamelCase__ : Union[str, Any] = re.compile(r'''TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)''') lowerCamelCase__ : Optional[int] = re.compile(r'''Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)''') # Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes. lowerCamelCase__ : Any = re.compile(r'''(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)''') # This is to make sure the transformers module imported is the one in the repo. lowerCamelCase__ : Union[str, Any] = direct_transformers_import(TRANSFORMERS_PATH) def UpperCamelCase ( _lowerCAmelCase : Union[str, Any] ) -> Any: _UpperCAmelCase : Optional[int] = re.finditer(""".+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)""", _lowerCAmelCase ) return [m.group(0 ) for m in matches] def UpperCamelCase ( _lowerCAmelCase : Any, _lowerCAmelCase : int ) -> Any: _UpperCAmelCase : Union[str, Any] = 2 if text == """✅""" or text == """❌""" else len(_lowerCAmelCase ) _UpperCAmelCase : str = (width - text_length) // 2 _UpperCAmelCase : List[Any] = width - text_length - left_indent return " " * left_indent + text + " " * right_indent def UpperCamelCase ( ) -> List[Any]: _UpperCAmelCase : int = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES _UpperCAmelCase : List[Any] = { name: config_maping_names[code] for code, name in transformers_module.MODEL_NAMES_MAPPING.items() if code in config_maping_names } _UpperCAmelCase : int = {name: config.replace("""Config""", """""" ) for name, config in model_name_to_config.items()} # Dictionaries flagging if each model prefix has a slow/fast tokenizer, backend in PT/TF/Flax. _UpperCAmelCase : Dict = collections.defaultdict(_lowerCAmelCase ) _UpperCAmelCase : List[str] = collections.defaultdict(_lowerCAmelCase ) _UpperCAmelCase : List[Any] = collections.defaultdict(_lowerCAmelCase ) _UpperCAmelCase : List[str] = collections.defaultdict(_lowerCAmelCase ) _UpperCAmelCase : str = collections.defaultdict(_lowerCAmelCase ) # Let's lookup through all transformers object (once). for attr_name in dir(_lowerCAmelCase ): _UpperCAmelCase : List[str] = None if attr_name.endswith("""Tokenizer""" ): _UpperCAmelCase : Optional[int] = slow_tokenizers _UpperCAmelCase : Optional[int] = attr_name[:-9] elif attr_name.endswith("""TokenizerFast""" ): _UpperCAmelCase : List[Any] = fast_tokenizers _UpperCAmelCase : str = attr_name[:-13] elif _re_tf_models.match(_lowerCAmelCase ) is not None: _UpperCAmelCase : Tuple = tf_models _UpperCAmelCase : Any = _re_tf_models.match(_lowerCAmelCase ).groups()[0] elif _re_flax_models.match(_lowerCAmelCase ) is not None: _UpperCAmelCase : Any = flax_models _UpperCAmelCase : List[Any] = _re_flax_models.match(_lowerCAmelCase ).groups()[0] elif _re_pt_models.match(_lowerCAmelCase ) is not None: _UpperCAmelCase : Union[str, Any] = pt_models _UpperCAmelCase : List[Any] = _re_pt_models.match(_lowerCAmelCase ).groups()[0] if lookup_dict is not None: while len(_lowerCAmelCase ) > 0: if attr_name in model_name_to_prefix.values(): _UpperCAmelCase : List[str] = True break # Try again after removing the last word in the name _UpperCAmelCase : Optional[Any] = """""".join(camel_case_split(_lowerCAmelCase )[:-1] ) # Let's build that table! _UpperCAmelCase : List[Any] = list(model_name_to_config.keys() ) model_names.sort(key=str.lower ) _UpperCAmelCase : List[Any] = ["""Model""", """Tokenizer slow""", """Tokenizer fast""", """PyTorch support""", """TensorFlow support""", """Flax Support"""] # We'll need widths to properly display everything in the center (+2 is to leave one extra space on each side). _UpperCAmelCase : List[Any] = [len(_lowerCAmelCase ) + 2 for c in columns] _UpperCAmelCase : Optional[int] = max([len(_lowerCAmelCase ) for name in model_names] ) + 2 # Build the table per se _UpperCAmelCase : Tuple = """|""" + """|""".join([_center_text(_lowerCAmelCase, _lowerCAmelCase ) for c, w in zip(_lowerCAmelCase, _lowerCAmelCase )] ) + """|\n""" # Use ":-----:" format to center-aligned table cell texts table += "|" + "|".join([""":""" + """-""" * (w - 2) + """:""" for w in widths] ) + "|\n" _UpperCAmelCase : Dict = {True: """✅""", False: """❌"""} for name in model_names: _UpperCAmelCase : Optional[int] = model_name_to_prefix[name] _UpperCAmelCase : Tuple = [ name, check[slow_tokenizers[prefix]], check[fast_tokenizers[prefix]], check[pt_models[prefix]], check[tf_models[prefix]], check[flax_models[prefix]], ] table += "|" + "|".join([_center_text(_lowerCAmelCase, _lowerCAmelCase ) for l, w in zip(_lowerCAmelCase, _lowerCAmelCase )] ) + "|\n" return table def UpperCamelCase ( _lowerCAmelCase : Any=False ) -> Dict: _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase : Any = _find_text_in_file( filename=os.path.join(_lowerCAmelCase, """index.md""" ), start_prompt="""<!--This table is updated automatically from the auto modules""", end_prompt="""<!-- End table-->""", ) _UpperCAmelCase : List[str] = get_model_table_from_auto_modules() if current_table != new_table: if overwrite: with open(os.path.join(_lowerCAmelCase, """index.md""" ), """w""", encoding="""utf-8""", newline="""\n""" ) as f: f.writelines(lines[:start_index] + [new_table] + lines[end_index:] ) else: raise ValueError( """The model table in the `index.md` has not been updated. Run `make fix-copies` to fix this.""" ) if __name__ == "__main__": lowerCamelCase__ : List[str] = argparse.ArgumentParser() parser.add_argument('''--fix_and_overwrite''', action='''store_true''', help='''Whether to fix inconsistencies.''') lowerCamelCase__ : List[Any] = parser.parse_args() check_model_table(args.fix_and_overwrite)
246
0
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, ChannelDimension, ImageInput, PILImageResampling, is_batched, to_numpy_array, valid_images, ) from ...utils import TensorType, logging __A = logging.get_logger(__name__) class lowercase_ ( UpperCamelCase__ ): UpperCamelCase_ : Any = ["""pixel_values"""] def __init__( self : Any , A__ : bool = True , A__ : Optional[Dict[str, int]] = None , A__ : PILImageResampling = PILImageResampling.BICUBIC , A__ : bool = True , A__ : bool = True , A__ : Union[int, float] = 1 / 255 , A__ : Dict[str, int] = None , A__ : bool = True , A__ : Optional[Union[float, List[float]]] = None , A__ : Optional[Union[float, List[float]]] = None , **A__ : Dict , ) -> List[str]: super().__init__(**__a ) _snake_case = size if size is not None else {'''height''': 224, '''width''': 224} _snake_case = get_size_dict(__a ) _snake_case = crop_size if crop_size is not None else {'''height''': 224, '''width''': 224} _snake_case = get_size_dict(__a , default_to_square=__a , param_name='''crop_size''' ) _snake_case = do_resize _snake_case = do_rescale _snake_case = do_normalize _snake_case = do_center_crop _snake_case = crop_size _snake_case = size _snake_case = resample _snake_case = rescale_factor _snake_case = image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN _snake_case = image_std if image_std is not None else IMAGENET_DEFAULT_STD def UpperCamelCase_ ( self : Tuple , A__ : np.ndarray , A__ : Dict[str, int] , A__ : PILImageResampling = PILImageResampling.BILINEAR , A__ : Optional[Union[str, ChannelDimension]] = None , **A__ : Optional[Any] , ) -> Optional[Any]: _snake_case = get_size_dict(__a ) if "shortest_edge" in size: _snake_case = get_resize_output_image_size(__a , size=size['''shortest_edge'''] , default_to_square=__a ) # size = get_resize_output_image_size(image, size["shortest_edge"], size["longest_edge"]) elif "height" in size and "width" in size: _snake_case = (size['''height'''], size['''width''']) else: raise ValueError(f"""Size must contain 'height' and 'width' keys or 'shortest_edge' key. Got {size.keys()}""" ) return resize(__a , size=__a , resample=__a , data_format=__a , **__a ) def UpperCamelCase_ ( self : List[Any] , A__ : np.ndarray , A__ : Dict[str, int] , A__ : Optional[Union[str, ChannelDimension]] = None , **A__ : int , ) -> Union[str, Any]: _snake_case = get_size_dict(__a ) if "height" not in size or "width" not in size: raise ValueError(f"""The `size` parameter must contain the keys (height, width). Got {size.keys()}""" ) return center_crop(__a , size=(size['''height'''], size['''width''']) , data_format=__a , **__a ) def UpperCamelCase_ ( self : str , A__ : np.ndarray , A__ : float , A__ : Optional[Union[str, ChannelDimension]] = None , **A__ : List[str] ) -> Optional[int]: return rescale(__a , scale=__a , data_format=__a , **__a ) def UpperCamelCase_ ( self : Any , A__ : np.ndarray , A__ : Union[float, List[float]] , A__ : Union[float, List[float]] , A__ : Optional[Union[str, ChannelDimension]] = None , **A__ : Dict , ) -> Any: return normalize(__a , mean=__a , std=__a , data_format=__a , **__a ) def UpperCamelCase_ ( self : Dict , A__ : ImageInput , A__ : Optional[bool] = None , A__ : Dict[str, int] = None , A__ : PILImageResampling = None , A__ : bool = None , A__ : int = None , A__ : Optional[bool] = None , A__ : Optional[float] = None , A__ : Optional[bool] = None , A__ : Optional[Union[float, List[float]]] = None , A__ : Optional[Union[float, List[float]]] = None , A__ : Optional[Union[str, TensorType]] = None , A__ : Union[str, ChannelDimension] = ChannelDimension.FIRST , **A__ : Dict , ) -> List[Any]: _snake_case = do_resize if do_resize is not None else self.do_resize _snake_case = do_rescale if do_rescale is not None else self.do_rescale _snake_case = do_normalize if do_normalize is not None else self.do_normalize _snake_case = do_center_crop if do_center_crop is not None else self.do_center_crop _snake_case = crop_size if crop_size is not None else self.crop_size _snake_case = get_size_dict(__a , param_name='''crop_size''' , default_to_square=__a ) _snake_case = resample if resample is not None else self.resample _snake_case = rescale_factor if rescale_factor is not None else self.rescale_factor _snake_case = image_mean if image_mean is not None else self.image_mean _snake_case = image_std if image_std is not None else self.image_std _snake_case = size if size is not None else self.size _snake_case = get_size_dict(__a ) if not is_batched(__a ): _snake_case = [images] if not valid_images(__a ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None: raise ValueError('''Size must be specified if do_resize is True.''' ) if do_center_crop and crop_size is None: raise ValueError('''Crop size must be specified if do_center_crop is True.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) # All transformations expect numpy arrays. _snake_case = [to_numpy_array(__a ) for image in images] if do_resize: _snake_case = [self.resize(image=__a , size=__a , resample=__a ) for image in images] if do_center_crop: _snake_case = [self.center_crop(image=__a , size=__a ) for image in images] if do_rescale: _snake_case = [self.rescale(image=__a , scale=__a ) for image in images] if do_normalize: _snake_case = [self.normalize(image=__a , mean=__a , std=__a ) for image in images] _snake_case = [to_channel_dimension_format(__a , __a ) for image in images] _snake_case = {'''pixel_values''': images} return BatchFeature(data=__a , tensor_type=__a )
368
def snake_case_(_UpperCamelCase , _UpperCamelCase ) -> str: """simple docstring""" if a < 0 or b < 0: raise ValueError('''the value of both inputs must be positive''' ) _snake_case = str(bin(_UpperCamelCase ) )[2:] # remove the leading "0b" _snake_case = str(bin(_UpperCamelCase ) )[2:] _snake_case = max(len(_UpperCamelCase ) , len(_UpperCamelCase ) ) return "0b" + "".join( str(int('''1''' in (char_a, char_b) ) ) for char_a, char_b in zip(a_binary.zfill(_UpperCamelCase ) , b_binary.zfill(_UpperCamelCase ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
278
0
import os import sys import unittest __a = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, 'utils')) import get_test_info # noqa: E402 from get_test_info import ( # noqa: E402 get_model_to_test_mapping, get_model_to_tester_mapping, get_test_to_tester_mapping, ) __a = os.path.join('tests', 'models', 'bert', 'test_modeling_bert.py') __a = os.path.join('tests', 'models', 'blip', 'test_modeling_blip.py') class lowercase__( unittest.TestCase ): """simple docstring""" def _lowercase ( self : int ) -> Any: lowercase_ = get_test_to_tester_mapping(_SCREAMING_SNAKE_CASE ) lowercase_ = get_test_to_tester_mapping(_SCREAMING_SNAKE_CASE ) lowercase_ = {'BertModelTest': 'BertModelTester'} lowercase_ = { 'BlipModelTest': 'BlipModelTester', 'BlipTextImageModelTest': 'BlipTextImageModelsModelTester', 'BlipTextModelTest': 'BlipTextModelTester', 'BlipTextRetrievalModelTest': 'BlipTextRetrievalModelTester', 'BlipVQAModelTest': 'BlipVQAModelTester', 'BlipVisionModelTest': 'BlipVisionModelTester', } self.assertEqual(get_test_info.to_json(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) self.assertEqual(get_test_info.to_json(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) def _lowercase ( self : Union[str, Any] ) -> Optional[int]: lowercase_ = get_model_to_test_mapping(_SCREAMING_SNAKE_CASE ) lowercase_ = get_model_to_test_mapping(_SCREAMING_SNAKE_CASE ) lowercase_ = { 'BertForMaskedLM': ['BertModelTest'], 'BertForMultipleChoice': ['BertModelTest'], 'BertForNextSentencePrediction': ['BertModelTest'], 'BertForPreTraining': ['BertModelTest'], 'BertForQuestionAnswering': ['BertModelTest'], 'BertForSequenceClassification': ['BertModelTest'], 'BertForTokenClassification': ['BertModelTest'], 'BertLMHeadModel': ['BertModelTest'], 'BertModel': ['BertModelTest'], } lowercase_ = { 'BlipForConditionalGeneration': ['BlipTextImageModelTest'], 'BlipForImageTextRetrieval': ['BlipTextRetrievalModelTest'], 'BlipForQuestionAnswering': ['BlipVQAModelTest'], 'BlipModel': ['BlipModelTest'], 'BlipTextModel': ['BlipTextModelTest'], 'BlipVisionModel': ['BlipVisionModelTest'], } self.assertEqual(get_test_info.to_json(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) self.assertEqual(get_test_info.to_json(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) def _lowercase ( self : Optional[Any] ) -> Union[str, Any]: lowercase_ = get_model_to_tester_mapping(_SCREAMING_SNAKE_CASE ) lowercase_ = get_model_to_tester_mapping(_SCREAMING_SNAKE_CASE ) lowercase_ = { 'BertForMaskedLM': ['BertModelTester'], 'BertForMultipleChoice': ['BertModelTester'], 'BertForNextSentencePrediction': ['BertModelTester'], 'BertForPreTraining': ['BertModelTester'], 'BertForQuestionAnswering': ['BertModelTester'], 'BertForSequenceClassification': ['BertModelTester'], 'BertForTokenClassification': ['BertModelTester'], 'BertLMHeadModel': ['BertModelTester'], 'BertModel': ['BertModelTester'], } lowercase_ = { 'BlipForConditionalGeneration': ['BlipTextImageModelsModelTester'], 'BlipForImageTextRetrieval': ['BlipTextRetrievalModelTester'], 'BlipForQuestionAnswering': ['BlipVQAModelTester'], 'BlipModel': ['BlipModelTester'], 'BlipTextModel': ['BlipTextModelTester'], 'BlipVisionModel': ['BlipVisionModelTester'], } self.assertEqual(get_test_info.to_json(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) self.assertEqual(get_test_info.to_json(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE )
30
import os from typing import Dict, List, Tuple, TypeVar, Union lowerCAmelCase : str = TypeVar('T') lowerCAmelCase : Optional[Any] = Union[List[T], Tuple[T, ...]] lowerCAmelCase : str = Union[T, List[T], Dict[str, T]] lowerCAmelCase : Union[str, Any] = Union[str, bytes, os.PathLike]
253
0
'''simple docstring''' import itertools from dataclasses import dataclass from typing import List, Optional import pyarrow as pa import pyarrow.parquet as pq import datasets from datasets.table import table_cast _lowerCAmelCase = datasets.utils.logging.get_logger(__name__) @dataclass class lowerCAmelCase_( datasets.BuilderConfig ): '''simple docstring''' __lowercase : int = 1_0_0_0_0 __lowercase : Optional[List[str]] = None __lowercase : Optional[datasets.Features] = None class lowerCAmelCase_( datasets.ArrowBasedBuilder ): '''simple docstring''' __lowercase : Optional[int] = ParquetConfig def UpperCAmelCase_ ( self ) -> Dict: return datasets.DatasetInfo(features=self.config.features ) def UpperCAmelCase_ ( self ,__UpperCAmelCase ) -> str: if not self.config.data_files: raise ValueError(F"""At least one data file must be specified, but got data_files={self.config.data_files}""" ) lowerCAmelCase__ : List[str] = dl_manager.download_and_extract(self.config.data_files ) if isinstance(__UpperCAmelCase ,(str, list, tuple) ): lowerCAmelCase__ : List[str] = data_files if isinstance(__UpperCAmelCase ,__UpperCAmelCase ): lowerCAmelCase__ : List[Any] = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive lowerCAmelCase__ : int = [dl_manager.iter_files(__UpperCAmelCase ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN ,gen_kwargs={"""files""": files} )] lowerCAmelCase__ : Union[str, Any] = [] for split_name, files in data_files.items(): if isinstance(__UpperCAmelCase ,__UpperCAmelCase ): lowerCAmelCase__ : Optional[int] = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive lowerCAmelCase__ : Union[str, Any] = [dl_manager.iter_files(__UpperCAmelCase ) for file in files] # Infer features is they are stoed in the arrow schema if self.info.features is None: for file in itertools.chain.from_iterable(__UpperCAmelCase ): with open(__UpperCAmelCase ,"""rb""" ) as f: lowerCAmelCase__ : Optional[Any] = datasets.Features.from_arrow_schema(pq.read_schema(__UpperCAmelCase ) ) break splits.append(datasets.SplitGenerator(name=__UpperCAmelCase ,gen_kwargs={"""files""": files} ) ) return splits def UpperCAmelCase_ ( self ,__UpperCAmelCase ) -> pa.Table: if self.info.features is not None: # more expensive cast to support nested features with keys in a different order # allows str <-> int/float or str to Audio for example lowerCAmelCase__ : Any = table_cast(__UpperCAmelCase ,self.info.features.arrow_schema ) return pa_table def UpperCAmelCase_ ( self ,__UpperCAmelCase ) -> Optional[Any]: lowerCAmelCase__ : List[Any] = self.info.features.arrow_schema if self.info.features is not None else None if self.info.features is not None and self.config.columns is not None: if sorted(field.name for field in schema ) != sorted(self.config.columns ): raise ValueError( F"""Tried to load parquet data with columns '{self.config.columns}' with mismatching features '{self.info.features}'""" ) for file_idx, file in enumerate(itertools.chain.from_iterable(__UpperCAmelCase ) ): with open(__UpperCAmelCase ,"""rb""" ) as f: lowerCAmelCase__ : Any = pq.ParquetFile(__UpperCAmelCase ) try: for batch_idx, record_batch in enumerate( parquet_file.iter_batches(batch_size=self.config.batch_size ,columns=self.config.columns ) ): lowerCAmelCase__ : Any = pa.Table.from_batches([record_batch] ) # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield F"""{file_idx}_{batch_idx}""", self._cast_table(__UpperCAmelCase ) except ValueError as e: logger.error(F"""Failed to read file '{file}' with error {type(__UpperCAmelCase )}: {e}""" ) raise
184
'''simple docstring''' def _SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelCase , UpperCamelCase ): """simple docstring""" def count_of_possible_combinations(UpperCamelCase ) -> int: if target < 0: return 0 if target == 0: return 1 return sum(count_of_possible_combinations(target - item ) for item in array ) return count_of_possible_combinations(UpperCamelCase ) def _SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelCase , UpperCamelCase ): """simple docstring""" def count_of_possible_combinations_with_dp_array( UpperCamelCase , UpperCamelCase ) -> int: if target < 0: return 0 if target == 0: return 1 if dp_array[target] != -1: return dp_array[target] lowerCAmelCase__ : Any = sum( count_of_possible_combinations_with_dp_array(target - item , UpperCamelCase ) for item in array ) lowerCAmelCase__ : Tuple = answer return answer lowerCAmelCase__ : Optional[int] = [-1] * (target + 1) return count_of_possible_combinations_with_dp_array(UpperCamelCase , UpperCamelCase ) def _SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelCase , UpperCamelCase ): """simple docstring""" lowerCAmelCase__ : str = [0] * (target + 1) lowerCAmelCase__ : List[Any] = 1 for i in range(1 , target + 1 ): for j in range(UpperCamelCase ): if i - array[j] >= 0: dp_array[i] += dp_array[i - array[j]] return dp_array[target] if __name__ == "__main__": import doctest doctest.testmod() _lowerCAmelCase = 3 _lowerCAmelCase = 5 _lowerCAmelCase = [1, 2, 5] print(combination_sum_iv(n, array, target))
184
1
"""simple docstring""" import unittest import torch from torch import nn from diffusers.models.activations import get_activation class snake_case ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self : List[Any] ): UpperCAmelCase__ = get_activation('swish' ) self.assertIsInstance(lowerCamelCase__ ,nn.SiLU ) self.assertEqual(act(torch.tensor(-100 ,dtype=torch.floataa ) ).item() ,0 ) self.assertNotEqual(act(torch.tensor(-1 ,dtype=torch.floataa ) ).item() ,0 ) self.assertEqual(act(torch.tensor(0 ,dtype=torch.floataa ) ).item() ,0 ) self.assertEqual(act(torch.tensor(20 ,dtype=torch.floataa ) ).item() ,20 ) def __lowerCAmelCase ( self : Optional[Any] ): UpperCAmelCase__ = get_activation('silu' ) self.assertIsInstance(lowerCamelCase__ ,nn.SiLU ) self.assertEqual(act(torch.tensor(-100 ,dtype=torch.floataa ) ).item() ,0 ) self.assertNotEqual(act(torch.tensor(-1 ,dtype=torch.floataa ) ).item() ,0 ) self.assertEqual(act(torch.tensor(0 ,dtype=torch.floataa ) ).item() ,0 ) self.assertEqual(act(torch.tensor(20 ,dtype=torch.floataa ) ).item() ,20 ) def __lowerCAmelCase ( self : Tuple ): UpperCAmelCase__ = get_activation('mish' ) self.assertIsInstance(lowerCamelCase__ ,nn.Mish ) self.assertEqual(act(torch.tensor(-200 ,dtype=torch.floataa ) ).item() ,0 ) self.assertNotEqual(act(torch.tensor(-1 ,dtype=torch.floataa ) ).item() ,0 ) self.assertEqual(act(torch.tensor(0 ,dtype=torch.floataa ) ).item() ,0 ) self.assertEqual(act(torch.tensor(20 ,dtype=torch.floataa ) ).item() ,20 ) def __lowerCAmelCase ( self : Optional[Any] ): UpperCAmelCase__ = get_activation('gelu' ) self.assertIsInstance(lowerCamelCase__ ,nn.GELU ) self.assertEqual(act(torch.tensor(-100 ,dtype=torch.floataa ) ).item() ,0 ) self.assertNotEqual(act(torch.tensor(-1 ,dtype=torch.floataa ) ).item() ,0 ) self.assertEqual(act(torch.tensor(0 ,dtype=torch.floataa ) ).item() ,0 ) self.assertEqual(act(torch.tensor(20 ,dtype=torch.floataa ) ).item() ,20 )
98
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices lowerCAmelCase : List[str] = logging.get_logger(__name__) class _A ( __magic_name__ , __magic_name__): SCREAMING_SNAKE_CASE : Dict = '''maskformer-swin''' SCREAMING_SNAKE_CASE : Dict = { '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self , _SCREAMING_SNAKE_CASE=224 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=96 , _SCREAMING_SNAKE_CASE=[2, 2, 6, 2] , _SCREAMING_SNAKE_CASE=[3, 6, 12, 24] , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=4.0 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=0.02 , _SCREAMING_SNAKE_CASE=1e-5 , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE , ): """simple docstring""" super().__init__(**_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE_ : Optional[Any] = image_size SCREAMING_SNAKE_CASE_ : List[str] = patch_size SCREAMING_SNAKE_CASE_ : Tuple = num_channels SCREAMING_SNAKE_CASE_ : List[Any] = embed_dim SCREAMING_SNAKE_CASE_ : Dict = depths SCREAMING_SNAKE_CASE_ : Dict = len(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE_ : Tuple = num_heads SCREAMING_SNAKE_CASE_ : List[Any] = window_size SCREAMING_SNAKE_CASE_ : List[Any] = mlp_ratio SCREAMING_SNAKE_CASE_ : Tuple = qkv_bias SCREAMING_SNAKE_CASE_ : Optional[int] = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : List[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : Union[str, Any] = drop_path_rate SCREAMING_SNAKE_CASE_ : List[Any] = hidden_act SCREAMING_SNAKE_CASE_ : Dict = use_absolute_embeddings SCREAMING_SNAKE_CASE_ : int = layer_norm_eps SCREAMING_SNAKE_CASE_ : Optional[Any] = initializer_range # we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model SCREAMING_SNAKE_CASE_ : str = int(embed_dim * 2 ** (len(_SCREAMING_SNAKE_CASE ) - 1) ) SCREAMING_SNAKE_CASE_ : List[str] = ['stem'] + [f"stage{idx}" for idx in range(1 , len(_SCREAMING_SNAKE_CASE ) + 1 )] SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Any = get_aligned_output_features_output_indices( out_features=_SCREAMING_SNAKE_CASE , out_indices=_SCREAMING_SNAKE_CASE , stage_names=self.stage_names )
253
0
'''simple docstring''' def lowerCamelCase__ ( __lowerCamelCase : Any ): '''simple docstring''' _UpperCAmelCase : int =current_set.copy() for row_index, row in enumerate(__lowerCAmelCase ): _UpperCAmelCase : Optional[Any] =row[0] for column_index, column in enumerate(__lowerCAmelCase ): if magnitude == 0: _UpperCAmelCase : Optional[int] =column continue _UpperCAmelCase : str =column / magnitude # Subtract to cancel term _UpperCAmelCase : Optional[Any] =current_set[0] _UpperCAmelCase : Any =[first_row] _UpperCAmelCase : Optional[Any] =current_set[1::] for row in current_set: _UpperCAmelCase : Tuple =[] # If first term is 0, it is already in form we want, so we preserve it if row[0] == 0: final_set.append(__lowerCAmelCase ) continue for column_index in range(len(__lowerCAmelCase ) ): temp_row.append(first_row[column_index] - row[column_index] ) final_set.append(__lowerCAmelCase ) # Create next recursion iteration set if len(final_set[0] ) != 3: _UpperCAmelCase : Any =final_set[0] _UpperCAmelCase : str =[] _UpperCAmelCase : str =[] for row in final_set[1::]: current_first_column.append(row[0] ) next_iteration.append(row[1::] ) _UpperCAmelCase : int =simplify(__lowerCAmelCase ) for i in range(len(__lowerCAmelCase ) ): resultant[i].insert(0 , current_first_column[i] ) resultant.insert(0 , __lowerCAmelCase ) _UpperCAmelCase : Dict =resultant return final_set def lowerCamelCase__ ( __lowerCamelCase : List[str] ): '''simple docstring''' if len(__lowerCAmelCase ) == 0: raise IndexError('solve_simultaneous() requires n lists of length n+1' ) _UpperCAmelCase : Tuple =len(__lowerCAmelCase ) + 1 if any(len(__lowerCAmelCase ) != _length for item in equations ): raise IndexError('solve_simultaneous() requires n lists of length n+1' ) for row in equations: if any(not isinstance(__lowerCAmelCase , (int, float) ) for column in row ): raise ValueError('solve_simultaneous() requires lists of integers' ) if len(__lowerCAmelCase ) == 1: return [equations[0][-1] / equations[0][0]] _UpperCAmelCase : Tuple =equations.copy() if any(0 in row for row in data_set ): _UpperCAmelCase : int =data_set.copy() _UpperCAmelCase : List[Any] =[] for row_index, row in enumerate(__lowerCAmelCase ): if 0 not in row: _UpperCAmelCase : str =data_set.pop(__lowerCAmelCase ) break if not full_row: raise ValueError('solve_simultaneous() requires at least 1 full equation' ) data_set.insert(0 , __lowerCAmelCase ) _UpperCAmelCase : Union[str, Any] =data_set.copy() _UpperCAmelCase : Optional[int] =simplify(__lowerCAmelCase ) _UpperCAmelCase : List[str] =simplified[::-1] _UpperCAmelCase : list =[] for row in simplified: _UpperCAmelCase : List[Any] =row[-1] if not solutions: if row[-2] == 0: solutions.append(0 ) continue solutions.append(current_solution / row[-2] ) continue _UpperCAmelCase : Any =row.copy()[: len(__lowerCAmelCase ) - 1 :] while temp_row[0] == 0: temp_row.pop(0 ) if len(__lowerCAmelCase ) == 0: solutions.append(0 ) continue _UpperCAmelCase : Any =temp_row[1::] _UpperCAmelCase : Optional[Any] =temp_row[::-1] for column_index, column in enumerate(__lowerCAmelCase ): current_solution -= column * solutions[column_index] solutions.append(__lowerCAmelCase ) _UpperCAmelCase : int =[] for item in solutions: final.append(float(round(__lowerCAmelCase , 5 ) ) ) return final[::-1] if __name__ == "__main__": import doctest doctest.testmod() lowercase =[ [2, 1, 1, 1, 1, 4], [1, 2, 1, 1, 1, 5], [1, 1, 2, 1, 1, 6], [1, 1, 1, 2, 1, 7], [1, 1, 1, 1, 2, 8], ] print(solve_simultaneous(eq)) print(solve_simultaneous([[4, 2]]))
362
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase =logging.get_logger(__name__) lowercase ={ 'vinvino02/glpn-kitti': 'https://huggingface.co/vinvino02/glpn-kitti/resolve/main/config.json', # See all GLPN models at https://huggingface.co/models?filter=glpn } class __magic_name__ ( lowerCAmelCase ): UpperCAmelCase ="glpn" def __init__( self , snake_case=3 , snake_case=4 , snake_case=[2, 2, 2, 2] , snake_case=[8, 4, 2, 1] , snake_case=[3_2, 6_4, 1_6_0, 2_5_6] , snake_case=[7, 3, 3, 3] , snake_case=[4, 2, 2, 2] , snake_case=[1, 2, 5, 8] , snake_case=[4, 4, 4, 4] , snake_case="gelu" , snake_case=0.0 , snake_case=0.0 , snake_case=0.02 , snake_case=0.1 , snake_case=1E-6 , snake_case=6_4 , snake_case=1_0 , snake_case=-1 , **snake_case , ) -> Tuple: '''simple docstring''' super().__init__(**snake_case) _UpperCAmelCase : Any =num_channels _UpperCAmelCase : List[str] =num_encoder_blocks _UpperCAmelCase : Optional[Any] =depths _UpperCAmelCase : str =sr_ratios _UpperCAmelCase : Dict =hidden_sizes _UpperCAmelCase : List[str] =patch_sizes _UpperCAmelCase : Any =strides _UpperCAmelCase : List[str] =mlp_ratios _UpperCAmelCase : Dict =num_attention_heads _UpperCAmelCase : List[str] =hidden_act _UpperCAmelCase : int =hidden_dropout_prob _UpperCAmelCase : List[Any] =attention_probs_dropout_prob _UpperCAmelCase : Union[str, Any] =initializer_range _UpperCAmelCase : Tuple =drop_path_rate _UpperCAmelCase : str =layer_norm_eps _UpperCAmelCase : Optional[int] =decoder_hidden_size _UpperCAmelCase : List[str] =max_depth _UpperCAmelCase : Dict =head_in_index
242
0
from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __snake_case :Optional[Any] = { '''configuration_mctct''': ['''MCTCT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MCTCTConfig'''], '''feature_extraction_mctct''': ['''MCTCTFeatureExtractor'''], '''processing_mctct''': ['''MCTCTProcessor'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case :str = [ '''MCTCT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MCTCTForCTC''', '''MCTCTModel''', '''MCTCTPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_mctct import MCTCT_PRETRAINED_CONFIG_ARCHIVE_MAP, MCTCTConfig from .feature_extraction_mctct import MCTCTFeatureExtractor from .processing_mctct import MCTCTProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mctct import MCTCT_PRETRAINED_MODEL_ARCHIVE_LIST, MCTCTForCTC, MCTCTModel, MCTCTPreTrainedModel else: import sys __snake_case :Optional[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
49
from typing import Optional from .. import Features, NamedSplit from ..packaged_modules.text.text import Text from ..utils.typing import NestedDataStructureLike, PathLike from .abc import AbstractDatasetReader class _A ( __UpperCAmelCase ): def __init__( self : Optional[int] , __SCREAMING_SNAKE_CASE : NestedDataStructureLike[PathLike] , __SCREAMING_SNAKE_CASE : Optional[NamedSplit] = None , __SCREAMING_SNAKE_CASE : Optional[Features] = None , __SCREAMING_SNAKE_CASE : str = None , __SCREAMING_SNAKE_CASE : bool = False , __SCREAMING_SNAKE_CASE : bool = False , __SCREAMING_SNAKE_CASE : Optional[int] = None , **__SCREAMING_SNAKE_CASE : List[str] , ): '''simple docstring''' super().__init__( __SCREAMING_SNAKE_CASE , split=__SCREAMING_SNAKE_CASE , features=__SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE , keep_in_memory=__SCREAMING_SNAKE_CASE , streaming=__SCREAMING_SNAKE_CASE , num_proc=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) __a = path_or_paths if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) else {self.split: path_or_paths} __a = Text( cache_dir=__SCREAMING_SNAKE_CASE , data_files=__SCREAMING_SNAKE_CASE , features=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) def _lowerCamelCase ( self : List[str]): '''simple docstring''' if self.streaming: __a = self.builder.as_streaming_dataset(split=self.split) # Build regular (map-style) dataset else: __a = None __a = None __a = None __a = None self.builder.download_and_prepare( download_config=__SCREAMING_SNAKE_CASE , download_mode=__SCREAMING_SNAKE_CASE , verification_mode=__SCREAMING_SNAKE_CASE , base_path=__SCREAMING_SNAKE_CASE , num_proc=self.num_proc , ) __a = self.builder.as_dataset( split=self.split , verification_mode=__SCREAMING_SNAKE_CASE , in_memory=self.keep_in_memory) return dataset
49
1
"""simple docstring""" def _snake_case ( _snake_case : int = 50000000 ): lowerCAmelCase : List[str] = set() lowerCAmelCase : List[Any] = int((limit - 24) ** (1 / 2) ) lowerCAmelCase : Optional[int] = set(range(3 , prime_square_limit + 1 , 2 ) ) primes.add(2 ) for p in range(3 , prime_square_limit + 1 , 2 ): if p not in primes: continue primes.difference_update(set(range(p * p , prime_square_limit + 1 , _snake_case ) ) ) for primea in primes: lowerCAmelCase : Optional[Any] = primea * primea for primea in primes: lowerCAmelCase : List[Any] = primea * primea * primea if square + cube >= limit - 16: break for primea in primes: lowerCAmelCase : Tuple = primea * primea * primea * primea lowerCAmelCase : Tuple = square + cube + tetr if total >= limit: break ret.add(_snake_case ) return len(_snake_case ) if __name__ == "__main__": print(f"""{solution() = }""")
314
"""simple docstring""" import sys from typing import Tuple import numpy as np import torch from PIL import Image from torch import nn from transformers.image_utils import PILImageResampling from utils import img_tensorize class snake_case_: def __init__( self : Dict , UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : int=sys.maxsize ): lowerCAmelCase : Tuple = '''bilinear''' lowerCAmelCase : List[Any] = max_size lowerCAmelCase : Optional[int] = short_edge_length def __call__( self : Optional[int] , UpperCamelCase_ : Optional[int] ): lowerCAmelCase : Tuple = [] for img in imgs: lowerCAmelCase, lowerCAmelCase : List[str] = img.shape[:2] # later: provide list and randomly choose index for resize lowerCAmelCase : int = np.random.randint(self.short_edge_length[0] , self.short_edge_length[1] + 1 ) if size == 0: return img lowerCAmelCase : Optional[Any] = size * 1.0 / min(UpperCamelCase_ , UpperCamelCase_ ) if h < w: lowerCAmelCase, lowerCAmelCase : List[str] = size, scale * w else: lowerCAmelCase, lowerCAmelCase : int = scale * h, size if max(UpperCamelCase_ , UpperCamelCase_ ) > self.max_size: lowerCAmelCase : Union[str, Any] = self.max_size * 1.0 / max(UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase : Tuple = newh * scale lowerCAmelCase : str = neww * scale lowerCAmelCase : Union[str, Any] = int(neww + 0.5 ) lowerCAmelCase : str = int(newh + 0.5 ) if img.dtype == np.uinta: lowerCAmelCase : Tuple = Image.fromarray(UpperCamelCase_ ) lowerCAmelCase : Optional[int] = pil_image.resize((neww, newh) , PILImageResampling.BILINEAR ) lowerCAmelCase : Union[str, Any] = np.asarray(UpperCamelCase_ ) else: lowerCAmelCase : List[str] = img.permute(2 , 0 , 1 ).unsqueeze(0 ) # 3, 0, 1) # hw(c) -> nchw lowerCAmelCase : Optional[int] = nn.functional.interpolate( UpperCamelCase_ , (newh, neww) , mode=self.interp_method , align_corners=UpperCamelCase_ ).squeeze(0 ) img_augs.append(UpperCamelCase_ ) return img_augs class snake_case_: def __init__( self : Tuple , UpperCamelCase_ : Any ): lowerCAmelCase : Any = ResizeShortestEdge([cfg.INPUT.MIN_SIZE_TEST, cfg.INPUT.MIN_SIZE_TEST] , cfg.INPUT.MAX_SIZE_TEST ) lowerCAmelCase : List[Any] = cfg.INPUT.FORMAT lowerCAmelCase : Tuple = cfg.SIZE_DIVISIBILITY lowerCAmelCase : int = cfg.PAD_VALUE lowerCAmelCase : Union[str, Any] = cfg.INPUT.MAX_SIZE_TEST lowerCAmelCase : Union[str, Any] = cfg.MODEL.DEVICE lowerCAmelCase : Union[str, Any] = torch.tensor(cfg.MODEL.PIXEL_STD ).to(self.device ).view(len(cfg.MODEL.PIXEL_STD ) , 1 , 1 ) lowerCAmelCase : List[Any] = torch.tensor(cfg.MODEL.PIXEL_MEAN ).to(self.device ).view(len(cfg.MODEL.PIXEL_STD ) , 1 , 1 ) lowerCAmelCase : Optional[int] = lambda UpperCamelCase_ : (x - self.pixel_mean) / self.pixel_std def lowerCamelCase__ ( self : Optional[int] , UpperCamelCase_ : List[Any] ): lowerCAmelCase : Dict = tuple(max(UpperCamelCase_ ) for s in zip(*[img.shape for img in images] ) ) lowerCAmelCase : Dict = [im.shape[-2:] for im in images] lowerCAmelCase : Dict = [ nn.functional.pad( UpperCamelCase_ , [0, max_size[-1] - size[1], 0, max_size[-2] - size[0]] , value=self.pad_value , ) for size, im in zip(UpperCamelCase_ , UpperCamelCase_ ) ] return torch.stack(UpperCamelCase_ ), torch.tensor(UpperCamelCase_ ) def __call__( self : List[str] , UpperCamelCase_ : str , UpperCamelCase_ : Optional[int]=False ): with torch.no_grad(): if not isinstance(UpperCamelCase_ , UpperCamelCase_ ): lowerCAmelCase : List[Any] = [images] if single_image: assert len(UpperCamelCase_ ) == 1 for i in range(len(UpperCamelCase_ ) ): if isinstance(images[i] , torch.Tensor ): images.insert(UpperCamelCase_ , images.pop(UpperCamelCase_ ).to(self.device ).float() ) elif not isinstance(images[i] , torch.Tensor ): images.insert( UpperCamelCase_ , torch.as_tensor(img_tensorize(images.pop(UpperCamelCase_ ) , input_format=self.input_format ) ) .to(self.device ) .float() , ) # resize smallest edge lowerCAmelCase : Dict = torch.tensor([im.shape[:2] for im in images] ) lowerCAmelCase : str = self.aug(UpperCamelCase_ ) # transpose images and convert to torch tensors # images = [torch.as_tensor(i.astype("float32")).permute(2, 0, 1).to(self.device) for i in images] # now normalize before pad to avoid useless arithmetic lowerCAmelCase : int = [self.normalizer(UpperCamelCase_ ) for x in images] # now pad them to do the following operations lowerCAmelCase, lowerCAmelCase : Optional[Any] = self.pad(UpperCamelCase_ ) # Normalize if self.size_divisibility > 0: raise NotImplementedError() # pad lowerCAmelCase : Union[str, Any] = torch.true_divide(UpperCamelCase_ , UpperCamelCase_ ) if single_image: return images[0], sizes[0], scales_yx[0] else: return images, sizes, scales_yx def _snake_case ( _snake_case : str , _snake_case : List[Any] ): boxes[:, 0::2] *= scale_yx[:, 1] boxes[:, 1::2] *= scale_yx[:, 0] return boxes def _snake_case ( _snake_case : Any , _snake_case : Tuple[int, int] ): assert torch.isfinite(_snake_case ).all(), "Box tensor contains infinite or NaN!" lowerCAmelCase, lowerCAmelCase : Optional[int] = box_size tensor[:, 0].clamp_(min=0 , max=_snake_case ) tensor[:, 1].clamp_(min=0 , max=_snake_case ) tensor[:, 2].clamp_(min=0 , max=_snake_case ) tensor[:, 3].clamp_(min=0 , max=_snake_case )
314
1
"""simple docstring""" from __future__ import annotations from collections.abc import Generator def UpperCAmelCase__ ( ): """simple docstring""" A_ : dict[int, int] = {} A_ : Optional[Any] = 2 while True: A_ : Union[str, Any] = factor_map.pop(_UpperCAmelCase , _UpperCAmelCase ) if factor: A_ : Optional[Any] = factor + prime while x in factor_map: x += factor A_ : Dict = factor else: A_ : List[str] = prime yield prime prime += 1 def UpperCAmelCase__ ( _UpperCAmelCase = 1E10 ): """simple docstring""" A_ : Optional[int] = sieve() A_ : List[str] = 1 while True: A_ : List[Any] = next(_UpperCAmelCase ) if (2 * prime * n) > limit: return n # Ignore the next prime as the reminder will be 2. next(_UpperCAmelCase ) n += 2 if __name__ == "__main__": print(solution())
286
"""simple docstring""" import re import jax.numpy as jnp from flax.traverse_util import flatten_dict, unflatten_dict from jax.random import PRNGKey from ..utils import logging lowerCamelCase_ : Tuple = logging.get_logger(__name__) def UpperCAmelCase__ ( _UpperCAmelCase ): """simple docstring""" A_ : Optional[Any] = R'\w+[.]\d+' A_ : int = re.findall(_UpperCAmelCase , _UpperCAmelCase ) for pat in pats: A_ : Optional[int] = key.replace(_UpperCAmelCase , '_'.join(pat.split('.' ) ) ) return key def UpperCAmelCase__ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): """simple docstring""" A_ : List[Any] = pt_tuple_key[:-1] + ('scale',) if ( any('norm' in str_ for str_ in pt_tuple_key ) and (pt_tuple_key[-1] == "bias") and (pt_tuple_key[:-1] + ("bias",) not in random_flax_state_dict) and (pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict) ): A_ : Union[str, Any] = pt_tuple_key[:-1] + ('scale',) return renamed_pt_tuple_key, pt_tensor elif pt_tuple_key[-1] in ["weight", "gamma"] and pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict: A_ : List[str] = pt_tuple_key[:-1] + ('scale',) return renamed_pt_tuple_key, pt_tensor # embedding if pt_tuple_key[-1] == "weight" and pt_tuple_key[:-1] + ("embedding",) in random_flax_state_dict: A_ : Optional[Any] = pt_tuple_key[:-1] + ('embedding',) return renamed_pt_tuple_key, pt_tensor # conv layer A_ : int = pt_tuple_key[:-1] + ('kernel',) if pt_tuple_key[-1] == "weight" and pt_tensor.ndim == 4: A_ : str = pt_tensor.transpose(2 , 3 , 1 , 0 ) return renamed_pt_tuple_key, pt_tensor # linear layer A_ : Optional[Any] = pt_tuple_key[:-1] + ('kernel',) if pt_tuple_key[-1] == "weight": A_ : Optional[Any] = pt_tensor.T return renamed_pt_tuple_key, pt_tensor # old PyTorch layer norm weight A_ : Tuple = pt_tuple_key[:-1] + ('weight',) if pt_tuple_key[-1] == "gamma": return renamed_pt_tuple_key, pt_tensor # old PyTorch layer norm bias A_ : Optional[int] = pt_tuple_key[:-1] + ('bias',) if pt_tuple_key[-1] == "beta": return renamed_pt_tuple_key, pt_tensor return pt_tuple_key, pt_tensor def UpperCAmelCase__ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=42 ): """simple docstring""" A_ : int = {k: v.numpy() for k, v in pt_state_dict.items()} # Step 2: Since the model is stateless, get random Flax params A_ : Union[str, Any] = flax_model.init_weights(PRNGKey(_UpperCAmelCase ) ) A_ : Optional[Any] = flatten_dict(_UpperCAmelCase ) A_ : Tuple = {} # Need to change some parameters name to match Flax names for pt_key, pt_tensor in pt_state_dict.items(): A_ : Any = rename_key(_UpperCAmelCase ) A_ : List[str] = tuple(renamed_pt_key.split('.' ) ) # Correctly rename weight parameters A_ , A_ : Union[str, Any] = rename_key_and_reshape_tensor(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) if flax_key in random_flax_state_dict: if flax_tensor.shape != random_flax_state_dict[flax_key].shape: raise ValueError( f"""PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape """ f"""{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}.""" ) # also add unexpected weight so that warning is thrown A_ : str = jnp.asarray(_UpperCAmelCase ) return unflatten_dict(_UpperCAmelCase )
286
1
"""simple docstring""" # Lint as: python3 import sys from collections.abc import Mapping from typing import TYPE_CHECKING import numpy as np import pyarrow as pa from .. import config from ..utils.py_utils import map_nested from .formatting import TensorFormatter if TYPE_CHECKING: import torch class _lowercase ( TensorFormatter[Mapping, 'torch.Tensor', Mapping] ): def __init__( self , UpperCAmelCase_=None , **UpperCAmelCase_ ) -> Any: super().__init__(features=UpperCAmelCase_ ) lowerCamelCase : Tuple = torch_tensor_kwargs import torch # noqa import torch at initialization def _UpperCamelCase ( self , UpperCAmelCase_ ) -> Union[str, Any]: import torch if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) and column: if all( isinstance(UpperCAmelCase_ , torch.Tensor ) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column ): return torch.stack(UpperCAmelCase_ ) return column def _UpperCamelCase ( self , UpperCAmelCase_ ) -> Any: import torch if isinstance(UpperCAmelCase_ , (str, bytes, type(UpperCAmelCase_ )) ): return value elif isinstance(UpperCAmelCase_ , (np.character, np.ndarray) ) and np.issubdtype(value.dtype , np.character ): return value.tolist() lowerCamelCase : str = {} if isinstance(UpperCAmelCase_ , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.integer ): lowerCamelCase : Dict = {'dtype': torch.intaa} elif isinstance(UpperCAmelCase_ , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.floating ): lowerCamelCase : Dict = {'dtype': torch.floataa} elif config.PIL_AVAILABLE and "PIL" in sys.modules: import PIL.Image if isinstance(UpperCAmelCase_ , PIL.Image.Image ): lowerCamelCase : Tuple = np.asarray(UpperCAmelCase_ ) return torch.tensor(UpperCAmelCase_ , **{**default_dtype, **self.torch_tensor_kwargs} ) def _UpperCamelCase ( self , UpperCAmelCase_ ) -> Optional[int]: import torch # support for torch, tf, jax etc. if hasattr(UpperCAmelCase_ , '__array__' ) and not isinstance(UpperCAmelCase_ , torch.Tensor ): lowerCamelCase : Dict = data_struct.__array__() # support for nested types like struct of list of struct if isinstance(UpperCAmelCase_ , np.ndarray ): if data_struct.dtype == object: # torch tensors cannot be instantied from an array of objects return self._consolidate([self.recursive_tensorize(UpperCAmelCase_ ) for substruct in data_struct] ) elif isinstance(UpperCAmelCase_ , (list, tuple) ): return self._consolidate([self.recursive_tensorize(UpperCAmelCase_ ) for substruct in data_struct] ) return self._tensorize(UpperCAmelCase_ ) def _UpperCamelCase ( self , UpperCAmelCase_ ) -> str: return map_nested(self._recursive_tensorize , UpperCAmelCase_ , map_list=UpperCAmelCase_ ) def _UpperCamelCase ( self , UpperCAmelCase_ ) -> Mapping: lowerCamelCase : Optional[Any] = self.numpy_arrow_extractor().extract_row(UpperCAmelCase_ ) lowerCamelCase : Any = self.python_features_decoder.decode_row(UpperCAmelCase_ ) return self.recursive_tensorize(UpperCAmelCase_ ) def _UpperCamelCase ( self , UpperCAmelCase_ ) -> "torch.Tensor": lowerCamelCase : int = self.numpy_arrow_extractor().extract_column(UpperCAmelCase_ ) lowerCamelCase : int = self.python_features_decoder.decode_column(UpperCAmelCase_ , pa_table.column_names[0] ) lowerCamelCase : Union[str, Any] = self.recursive_tensorize(UpperCAmelCase_ ) lowerCamelCase : str = self._consolidate(UpperCAmelCase_ ) return column def _UpperCamelCase ( self , UpperCAmelCase_ ) -> Mapping: lowerCamelCase : str = self.numpy_arrow_extractor().extract_batch(UpperCAmelCase_ ) lowerCamelCase : Any = self.python_features_decoder.decode_batch(UpperCAmelCase_ ) lowerCamelCase : Optional[int] = self.recursive_tensorize(UpperCAmelCase_ ) for column_name in batch: lowerCamelCase : int = self._consolidate(batch[column_name] ) return batch
205
"""simple docstring""" import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import numpy as np import pytest from datasets.arrow_dataset import Dataset from datasets.search import ElasticSearchIndex, FaissIndex, MissingIndex from .utils import require_elasticsearch, require_faiss _A = pytest.mark.integration @require_faiss class _lowercase ( __UpperCAmelCase ): def _UpperCamelCase ( self ) -> Union[str, Any]: lowerCamelCase : Any = Dataset.from_dict({'filename': ['my_name-train' + '_' + str(UpperCAmelCase_ ) for x in np.arange(30 ).tolist()]} ) return dset def _UpperCamelCase ( self ) -> List[Any]: import faiss lowerCamelCase : Dataset = self._create_dummy_dataset() lowerCamelCase : Optional[int] = dset.map( lambda UpperCAmelCase_ , UpperCAmelCase_ : {"vecs": i * np.ones(5 , dtype=np.floataa )} , with_indices=UpperCAmelCase_ , keep_in_memory=UpperCAmelCase_ ) lowerCamelCase : Dict = dset.add_faiss_index('vecs' , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT ) lowerCamelCase , lowerCamelCase : List[str] = dset.get_nearest_examples('vecs' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) dset.drop_index('vecs' ) def _UpperCamelCase ( self ) -> Tuple: import faiss lowerCamelCase : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name='vecs' , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT , ) lowerCamelCase , lowerCamelCase : str = dset.get_nearest_examples('vecs' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) def _UpperCamelCase ( self ) -> int: import faiss lowerCamelCase : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name='vecs' , metric_type=faiss.METRIC_INNER_PRODUCT , ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=UpperCAmelCase_ ) as tmp_file: dset.save_faiss_index('vecs' , tmp_file.name ) dset.load_faiss_index('vecs2' , tmp_file.name ) os.unlink(tmp_file.name ) lowerCamelCase , lowerCamelCase : List[str] = dset.get_nearest_examples('vecs2' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) def _UpperCamelCase ( self ) -> Any: lowerCamelCase : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name='vecs' ) dset.drop_index('vecs' ) self.assertRaises(UpperCAmelCase_ , partial(dset.get_nearest_examples , 'vecs2' , np.ones(5 , dtype=np.floataa ) ) ) def _UpperCamelCase ( self ) -> Union[str, Any]: from elasticsearch import Elasticsearch lowerCamelCase : Dataset = self._create_dummy_dataset() with patch('elasticsearch.Elasticsearch.search' ) as mocked_search, patch( 'elasticsearch.client.IndicesClient.create' ) as mocked_index_create, patch('elasticsearch.helpers.streaming_bulk' ) as mocked_bulk: lowerCamelCase : Tuple = {'acknowledged': True} mocked_bulk.return_value([(True, None)] * 30 ) lowerCamelCase : int = {'hits': {'hits': [{'_score': 1, '_id': 29}]}} lowerCamelCase : Optional[Any] = Elasticsearch() dset.add_elasticsearch_index('filename' , es_client=UpperCAmelCase_ ) lowerCamelCase , lowerCamelCase : str = dset.get_nearest_examples('filename' , 'my_name-train_29' ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) @require_faiss class _lowercase ( __UpperCAmelCase ): def _UpperCamelCase ( self ) -> Union[str, Any]: import faiss lowerCamelCase : str = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) # add vectors index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsNotNone(index.faiss_index ) self.assertEqual(index.faiss_index.ntotal , 5 ) index.add_vectors(np.zeros((5, 5) , dtype=np.floataa ) ) self.assertEqual(index.faiss_index.ntotal , 10 ) # single query lowerCamelCase : Optional[int] = np.zeros(5 , dtype=np.floataa ) lowerCamelCase : List[str] = 1 lowerCamelCase , lowerCamelCase : int = index.search(UpperCAmelCase_ ) self.assertRaises(UpperCAmelCase_ , index.search , query.reshape(-1 , 1 ) ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) # batched queries lowerCamelCase : Tuple = np.eye(5 , dtype=np.floataa )[::-1] lowerCamelCase , lowerCamelCase : List[str] = index.search_batch(UpperCAmelCase_ ) self.assertRaises(UpperCAmelCase_ , index.search_batch , queries[0] ) lowerCamelCase : List[str] = [scores[0] for scores in total_scores] lowerCamelCase : List[str] = [indices[0] for indices in total_indices] self.assertGreater(np.min(UpperCAmelCase_ ) , 0 ) self.assertListEqual([4, 3, 2, 1, 0] , UpperCAmelCase_ ) def _UpperCamelCase ( self ) -> Dict: import faiss lowerCamelCase : List[Any] = FaissIndex(string_factory='Flat' ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) lowerCamelCase : int = FaissIndex(string_factory='LSH' ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexLSH ) with self.assertRaises(UpperCAmelCase_ ): lowerCamelCase : str = FaissIndex(string_factory='Flat' , custom_index=faiss.IndexFlat(5 ) ) def _UpperCamelCase ( self ) -> Any: import faiss lowerCamelCase : Any = faiss.IndexFlat(5 ) lowerCamelCase : Any = FaissIndex(custom_index=UpperCAmelCase_ ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) def _UpperCamelCase ( self ) -> Any: import faiss lowerCamelCase : Any = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=UpperCAmelCase_ ) as tmp_file: index.save(tmp_file.name ) lowerCamelCase : List[str] = FaissIndex.load(tmp_file.name ) os.unlink(tmp_file.name ) lowerCamelCase : Dict = np.zeros(5 , dtype=np.floataa ) lowerCamelCase : Optional[Any] = 1 lowerCamelCase , lowerCamelCase : str = index.search(UpperCAmelCase_ ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) @require_faiss def UpperCAmelCase ( a_ ): '''simple docstring''' import faiss lowerCamelCase : int = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5, dtype=np.floataa ) ) lowerCamelCase : Union[str, Any] = 'index.faiss' lowerCamelCase : List[Any] = F"""mock://{index_name}""" index.save(a_, storage_options=mockfs.storage_options ) lowerCamelCase : Optional[int] = FaissIndex.load(a_, storage_options=mockfs.storage_options ) lowerCamelCase : str = np.zeros(5, dtype=np.floataa ) lowerCamelCase : str = 1 lowerCamelCase , lowerCamelCase : int = index.search(a_ ) assert scores[0] > 0 assert indices[0] == 1 @require_elasticsearch class _lowercase ( __UpperCAmelCase ): def _UpperCamelCase ( self ) -> int: from elasticsearch import Elasticsearch with patch('elasticsearch.Elasticsearch.search' ) as mocked_search, patch( 'elasticsearch.client.IndicesClient.create' ) as mocked_index_create, patch('elasticsearch.helpers.streaming_bulk' ) as mocked_bulk: lowerCamelCase : Union[str, Any] = Elasticsearch() lowerCamelCase : Optional[Any] = {'acknowledged': True} lowerCamelCase : str = ElasticSearchIndex(es_client=UpperCAmelCase_ ) mocked_bulk.return_value([(True, None)] * 3 ) index.add_documents(['foo', 'bar', 'foobar'] ) # single query lowerCamelCase : Tuple = 'foo' lowerCamelCase : List[str] = {'hits': {'hits': [{'_score': 1, '_id': 0}]}} lowerCamelCase , lowerCamelCase : Any = index.search(UpperCAmelCase_ ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # single query with timeout lowerCamelCase : Dict = 'foo' lowerCamelCase : Optional[Any] = {'hits': {'hits': [{'_score': 1, '_id': 0}]}} lowerCamelCase , lowerCamelCase : Optional[Any] = index.search(UpperCAmelCase_ , request_timeout=30 ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # batched queries lowerCamelCase : str = ['foo', 'bar', 'foobar'] lowerCamelCase : Union[str, Any] = {'hits': {'hits': [{'_score': 1, '_id': 1}]}} lowerCamelCase , lowerCamelCase : Optional[int] = index.search_batch(UpperCAmelCase_ ) lowerCamelCase : Dict = [scores[0] for scores in total_scores] lowerCamelCase : Optional[int] = [indices[0] for indices in total_indices] self.assertGreater(np.min(UpperCAmelCase_ ) , 0 ) self.assertListEqual([1, 1, 1] , UpperCAmelCase_ ) # batched queries with timeout lowerCamelCase : List[str] = ['foo', 'bar', 'foobar'] lowerCamelCase : str = {'hits': {'hits': [{'_score': 1, '_id': 1}]}} lowerCamelCase , lowerCamelCase : Dict = index.search_batch(UpperCAmelCase_ , request_timeout=30 ) lowerCamelCase : Dict = [scores[0] for scores in total_scores] lowerCamelCase : int = [indices[0] for indices in total_indices] self.assertGreater(np.min(UpperCAmelCase_ ) , 0 ) self.assertListEqual([1, 1, 1] , UpperCAmelCase_ )
205
1
def UpperCamelCase( __UpperCamelCase : float ,__UpperCamelCase : int ): if digit_amount > 0: return round(number - int(__UpperCamelCase ) ,__UpperCamelCase ) return number - int(__UpperCamelCase ) if __name__ == "__main__": print(decimal_isolate(1.5_3, 0)) print(decimal_isolate(3_5.3_4_5, 1)) print(decimal_isolate(3_5.3_4_5, 2)) print(decimal_isolate(3_5.3_4_5, 3)) print(decimal_isolate(-1_4.7_8_9, 3)) print(decimal_isolate(0, 2)) print(decimal_isolate(-1_4.1_2_3, 1)) print(decimal_isolate(-1_4.1_2_3, 2)) print(decimal_isolate(-1_4.1_2_3, 3))
103
'''simple docstring''' def UpperCamelCase_ ( snake_case_ : Union[str, Any]=2_81_23 ) -> str: '''simple docstring''' __lowerCAmelCase = [1] * (limit + 1) for i in range(2 , int(limit**0.5 ) + 1 ): sum_divs[i * i] += i for k in range(i + 1 , limit // i + 1 ): sum_divs[k * i] += k + i __lowerCAmelCase = set() __lowerCAmelCase = 0 for n in range(1 , limit + 1 ): if sum_divs[n] > n: abundants.add(snake_case_ ) if not any((n - a in abundants) for a in abundants ): res += n return res if __name__ == "__main__": print(solution())
229
0
import os import numpy import onnx def _a ( lowerCamelCase: Optional[Any] , lowerCamelCase: List[str] ) -> Optional[int]: '''simple docstring''' __A = a.name __A = b.name __A = '''''' __A = '''''' __A = a == b __A = name_a __A = name_b return res def _a ( lowerCamelCase: Union[str, Any] , lowerCamelCase: Optional[Any] , lowerCamelCase: Optional[Any] ) -> List[Any]: '''simple docstring''' for i, input_name in enumerate(node_proto.input ): if input_name == name: node_proto.input.insert(lowerCamelCase , lowerCamelCase ) node_proto.input.pop(i + 1 ) if node_proto.op_type == "If": _graph_replace_input_with(node_proto.attribute[0].g , lowerCamelCase , lowerCamelCase ) _graph_replace_input_with(node_proto.attribute[1].g , lowerCamelCase , lowerCamelCase ) if node_proto.op_type == "Loop": _graph_replace_input_with(node_proto.attribute[0].g , lowerCamelCase , lowerCamelCase ) def _a ( lowerCamelCase: str , lowerCamelCase: Any , lowerCamelCase: Optional[Any] ) -> Any: '''simple docstring''' for n in graph_proto.node: _node_replace_input_with(lowerCamelCase , lowerCamelCase , lowerCamelCase ) def _a ( lowerCamelCase: Union[str, Any] , lowerCamelCase: int , lowerCamelCase: Optional[Any] ) -> Union[str, Any]: '''simple docstring''' __A = list(model.graph.initializer ) __A = list(model_without_ext.graph.initializer ) for i, ref_i in ind_to_replace: assert inits_with_data[i].name == inits[i].name assert inits_with_data[ref_i].name == inits[ref_i].name assert i > ref_i __A = inits[i].name __A = inits[ref_i].name model_without_ext.graph.initializer.remove(inits[i] ) # for n in model.graph.node: _graph_replace_input_with(model_without_ext.graph , lowerCamelCase , lowerCamelCase ) def _a ( lowerCamelCase: Tuple ) -> int: '''simple docstring''' __A = os.path.dirname(lowerCamelCase ) __A = os.path.basename(lowerCamelCase ) __A = onnx.load(os.path.join(lowerCamelCase , lowerCamelCase ) ) __A = list(model.graph.initializer ) __A = set() __A = {} __A = [] __A = 0 for i in range(len(lowerCamelCase ) ): if i in dup_set: continue for j in range(i + 1 , len(lowerCamelCase ) ): if j in dup_set: continue if _is_equal_tensor_proto(inits[i] , inits[j] ): dup_set.add(lowerCamelCase ) dup_set.add(lowerCamelCase ) __A = inits[j].data_type __A = numpy.prod(inits[j].dims ) if dtype == 1: mem_size *= 4 elif dtype == 6: mem_size *= 4 elif dtype == 7 or dtype == 11: mem_size *= 8 else: print('''unexpected data type: ''' , lowerCamelCase ) total_reduced_size += mem_size __A = inits[i].name __A = inits[j].name if name_i in dup_map: dup_map[name_i].append(lowerCamelCase ) else: __A = [name_j] ind_to_replace.append((j, i) ) print('''total reduced size: ''' , total_reduced_size / 10_24 / 10_24 / 10_24 , '''GB''' ) __A = sorted(lowerCamelCase ) _remove_dup_initializers_from_model(lowerCamelCase , lowerCamelCase , lowerCamelCase ) __A = '''optimized_''' + model_file_name __A = os.path.join(lowerCamelCase , lowerCamelCase ) onnx.save(lowerCamelCase , lowerCamelCase ) return new_model
250
def _a ( lowerCamelCase: dict ) -> bool: '''simple docstring''' __A = set() # To detect a back edge, keep track of vertices currently in the recursion stack __A = set() return any( node not in visited and depth_first_search(lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ) for node in graph ) def _a ( lowerCamelCase: dict , lowerCamelCase: int , lowerCamelCase: set , lowerCamelCase: set ) -> bool: '''simple docstring''' visited.add(lowerCamelCase ) rec_stk.add(lowerCamelCase ) for node in graph[vertex]: if node not in visited: if depth_first_search(lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ): return True elif node in rec_stk: return True # The node needs to be removed from recursion stack before function ends rec_stk.remove(lowerCamelCase ) return False if __name__ == "__main__": from doctest import testmod testmod()
250
1
from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ : Tuple =logging.get_logger(__name__) lowerCAmelCase__ : Tuple ={ '''MIT/ast-finetuned-audioset-10-10-0.4593''': ( '''https://huggingface.co/MIT/ast-finetuned-audioset-10-10-0.4593/resolve/main/config.json''' ), } class UpperCAmelCase_ ( UpperCamelCase_ ): '''simple docstring''' UpperCamelCase__ : Union[str, Any] = "audio-spectrogram-transformer" def __init__( self , _A=768 , _A=12 , _A=12 , _A=3_072 , _A="gelu" , _A=0.0 , _A=0.0 , _A=0.0_2 , _A=1e-12 , _A=16 , _A=True , _A=10 , _A=10 , _A=1_024 , _A=128 , **_A , ): '''simple docstring''' super().__init__(**snake_case__ ) __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = patch_size __SCREAMING_SNAKE_CASE = qkv_bias __SCREAMING_SNAKE_CASE = frequency_stride __SCREAMING_SNAKE_CASE = time_stride __SCREAMING_SNAKE_CASE = max_length __SCREAMING_SNAKE_CASE = num_mel_bins
257
"""simple docstring""" import unittest import torch from torch import nn from diffusers.models.activations import get_activation class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): """simple docstring""" def lowercase__ ( self ): """simple docstring""" lowerCAmelCase : int = get_activation("swish" ) self.assertIsInstance(snake_case__ , nn.SiLU ) self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def lowercase__ ( self ): """simple docstring""" lowerCAmelCase : Union[str, Any] = get_activation("silu" ) self.assertIsInstance(snake_case__ , nn.SiLU ) self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def lowercase__ ( self ): """simple docstring""" lowerCAmelCase : Dict = get_activation("mish" ) self.assertIsInstance(snake_case__ , nn.Mish ) self.assertEqual(act(torch.tensor(-200 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def lowercase__ ( self ): """simple docstring""" lowerCAmelCase : Union[str, Any] = get_activation("gelu" ) self.assertIsInstance(snake_case__ , nn.GELU ) self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 )
108
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowercase_ = {'configuration_mbart': ['MBART_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MBartConfig', 'MBartOnnxConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ['MBartTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ['MBartTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ 'MBART_PRETRAINED_MODEL_ARCHIVE_LIST', 'MBartForCausalLM', 'MBartForConditionalGeneration', 'MBartForQuestionAnswering', 'MBartForSequenceClassification', 'MBartModel', 'MBartPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ 'TFMBartForConditionalGeneration', 'TFMBartModel', 'TFMBartPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ 'FlaxMBartForConditionalGeneration', 'FlaxMBartForQuestionAnswering', 'FlaxMBartForSequenceClassification', 'FlaxMBartModel', 'FlaxMBartPreTrainedModel', ] if TYPE_CHECKING: from .configuration_mbart import MBART_PRETRAINED_CONFIG_ARCHIVE_MAP, MBartConfig, MBartOnnxConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart import MBartTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart_fast import MBartTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mbart import ( MBART_PRETRAINED_MODEL_ARCHIVE_LIST, MBartForCausalLM, MBartForConditionalGeneration, MBartForQuestionAnswering, MBartForSequenceClassification, MBartModel, MBartPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mbart import TFMBartForConditionalGeneration, TFMBartModel, TFMBartPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_mbart import ( FlaxMBartForConditionalGeneration, FlaxMBartForQuestionAnswering, FlaxMBartForSequenceClassification, FlaxMBartModel, FlaxMBartPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
370
import json import os import tempfile import datasets from utils import generate_example_dataset, get_duration lowercase_ = 5_0_0_0_0 lowercase_ = 5_0_0_0 lowercase_ ,lowercase_ = os.path.split(__file__) lowercase_ = os.path.join(RESULTS_BASEPATH, 'results', RESULTS_FILENAME.replace('.py', '.json')) @get_duration def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): for i in range(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Tuple = dataset[i] @get_duration def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): for i in range(0 , len(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Optional[Any] = dataset[i : i + batch_size] @get_duration def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): with dataset.formatted_as(type=SCREAMING_SNAKE_CASE__ ): for i in range(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : str = dataset[i] @get_duration def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): with dataset.formatted_as(type=SCREAMING_SNAKE_CASE__ ): for i in range(0 , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : int = dataset[i : i + batch_size] def UpperCamelCase__ ( ): __lowerCamelCase : Union[str, Any] = {'num examples': SPEED_TEST_N_EXAMPLES} __lowerCamelCase : Optional[Any] = [ (read, {'length': SMALL_TEST}), (read, {'length': SPEED_TEST_N_EXAMPLES}), (read_batch, {'length': SPEED_TEST_N_EXAMPLES, 'batch_size': 10}), (read_batch, {'length': SPEED_TEST_N_EXAMPLES, 'batch_size': 100}), (read_batch, {'length': SPEED_TEST_N_EXAMPLES, 'batch_size': 1_000}), (read_formatted, {'type': 'numpy', 'length': SMALL_TEST}), (read_formatted, {'type': 'pandas', 'length': SMALL_TEST}), (read_formatted, {'type': 'torch', 'length': SMALL_TEST}), (read_formatted, {'type': 'tensorflow', 'length': SMALL_TEST}), (read_formatted_batch, {'type': 'numpy', 'length': SMALL_TEST, 'batch_size': 10}), (read_formatted_batch, {'type': 'numpy', 'length': SMALL_TEST, 'batch_size': 1_000}), ] __lowerCamelCase : Any = [ (read, {'length': SMALL_TEST}), (read, {'length': SPEED_TEST_N_EXAMPLES}), (read_batch, {'length': SPEED_TEST_N_EXAMPLES, 'batch_size': 10}), (read_batch, {'length': SPEED_TEST_N_EXAMPLES, 'batch_size': 100}), (read_batch, {'length': SPEED_TEST_N_EXAMPLES, 'batch_size': 1_000}), (read_formatted, {'type': 'numpy', 'length': SMALL_TEST}), (read_formatted_batch, {'type': 'numpy', 'length': SMALL_TEST, 'batch_size': 10}), (read_formatted_batch, {'type': 'numpy', 'length': SMALL_TEST, 'batch_size': 1_000}), ] with tempfile.TemporaryDirectory() as tmp_dir: print('generating dataset' ) __lowerCamelCase : Optional[int] = datasets.Features( {'list': datasets.Sequence(datasets.Value('float32' ) ), 'numbers': datasets.Value('float32' )} ) __lowerCamelCase : str = generate_example_dataset( os.path.join(SCREAMING_SNAKE_CASE__ , 'dataset.arrow' ) , SCREAMING_SNAKE_CASE__ , num_examples=SCREAMING_SNAKE_CASE__ , seq_shapes={'list': (100,)} , ) print('first set of iterations' ) for func, kwargs in functions: print(func.__name__ , str(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase : Optional[int] = func(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) print('shuffling dataset' ) __lowerCamelCase : str = dataset.shuffle() print('Second set of iterations (after shuffling' ) for func, kwargs in functions_shuffled: print('shuffled ' , func.__name__ , str(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase : int = func( SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) with open(SCREAMING_SNAKE_CASE__ , 'wb' ) as f: f.write(json.dumps(SCREAMING_SNAKE_CASE__ ).encode('utf-8' ) ) if __name__ == "__main__": # useful to run the profiler benchmark_iterating()
194
0
import os import shutil import sys import tempfile import unittest from pathlib import Path import pytest import transformers from transformers import ( BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, AutoTokenizer, BertConfig, BertTokenizer, BertTokenizerFast, CTRLTokenizer, GPTaTokenizer, GPTaTokenizerFast, PreTrainedTokenizerFast, RobertaTokenizer, RobertaTokenizerFast, is_tokenizers_available, ) from transformers.models.auto.configuration_auto import CONFIG_MAPPING, AutoConfig from transformers.models.auto.tokenization_auto import ( TOKENIZER_MAPPING, get_tokenizer_config, tokenizer_class_from_name, ) from transformers.models.roberta.configuration_roberta import RobertaConfig from transformers.testing_utils import ( DUMMY_DIFF_TOKENIZER_IDENTIFIER, DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, RequestCounter, require_tokenizers, slow, ) sys.path.append(str(Path(__file__).parent.parent.parent.parent / """utils""")) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_tokenization import CustomTokenizer # noqa E402 if is_tokenizers_available(): from test_module.custom_tokenization_fast import CustomTokenizerFast class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): def lowerCamelCase_ ( self : Tuple ): """simple docstring""" UpperCamelCase = 0 @slow def lowerCamelCase_ ( self : int ): """simple docstring""" for model_name in (x for x in BERT_PRETRAINED_CONFIG_ARCHIVE_MAP.keys() if "japanese" not in x): UpperCamelCase = AutoTokenizer.from_pretrained(lowerCamelCase_ ) self.assertIsNotNone(lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ , (BertTokenizer, BertTokenizerFast) ) self.assertGreater(len(lowerCamelCase_ ) , 0 ) for model_name in GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP.keys(): UpperCamelCase = AutoTokenizer.from_pretrained(lowerCamelCase_ ) self.assertIsNotNone(lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ , (GPTaTokenizer, GPTaTokenizerFast) ) self.assertGreater(len(lowerCamelCase_ ) , 0 ) def lowerCamelCase_ ( self : Optional[Any] ): """simple docstring""" UpperCamelCase = AutoTokenizer.from_pretrained(lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(tokenizer.vocab_size , 12 ) def lowerCamelCase_ ( self : Dict ): """simple docstring""" UpperCamelCase = AutoTokenizer.from_pretrained(lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ , (RobertaTokenizer, RobertaTokenizerFast) ) self.assertEqual(tokenizer.vocab_size , 20 ) def lowerCamelCase_ ( self : Tuple ): """simple docstring""" UpperCamelCase = AutoConfig.from_pretrained(lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ , lowerCamelCase_ ) # Check that tokenizer_type ≠ model_type UpperCamelCase = AutoTokenizer.from_pretrained(lowerCamelCase_ , config=lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(tokenizer.vocab_size , 12 ) def lowerCamelCase_ ( self : Optional[int] ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: shutil.copy("""./tests/fixtures/vocab.txt""" , os.path.join(lowerCamelCase_ , """vocab.txt""" ) ) UpperCamelCase = AutoTokenizer.from_pretrained(lowerCamelCase_ , tokenizer_type="""bert""" , use_fast=lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ , lowerCamelCase_ ) with tempfile.TemporaryDirectory() as tmp_dir: shutil.copy("""./tests/fixtures/vocab.json""" , os.path.join(lowerCamelCase_ , """vocab.json""" ) ) shutil.copy("""./tests/fixtures/merges.txt""" , os.path.join(lowerCamelCase_ , """merges.txt""" ) ) UpperCamelCase = AutoTokenizer.from_pretrained(lowerCamelCase_ , tokenizer_type="""gpt2""" , use_fast=lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ , lowerCamelCase_ ) @require_tokenizers def lowerCamelCase_ ( self : Tuple ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: shutil.copy("""./tests/fixtures/vocab.txt""" , os.path.join(lowerCamelCase_ , """vocab.txt""" ) ) UpperCamelCase = AutoTokenizer.from_pretrained(lowerCamelCase_ , tokenizer_type="""bert""" ) self.assertIsInstance(lowerCamelCase_ , lowerCamelCase_ ) with tempfile.TemporaryDirectory() as tmp_dir: shutil.copy("""./tests/fixtures/vocab.json""" , os.path.join(lowerCamelCase_ , """vocab.json""" ) ) shutil.copy("""./tests/fixtures/merges.txt""" , os.path.join(lowerCamelCase_ , """merges.txt""" ) ) UpperCamelCase = AutoTokenizer.from_pretrained(lowerCamelCase_ , tokenizer_type="""gpt2""" ) self.assertIsInstance(lowerCamelCase_ , lowerCamelCase_ ) def lowerCamelCase_ ( self : int ): """simple docstring""" with pytest.raises(lowerCamelCase_ ): AutoTokenizer.from_pretrained("""./""" , tokenizer_type="""xxx""" ) @require_tokenizers def lowerCamelCase_ ( self : Union[str, Any] ): """simple docstring""" for tokenizer_class in [BertTokenizer, BertTokenizerFast, AutoTokenizer]: UpperCamelCase = tokenizer_class.from_pretrained("""wietsedv/bert-base-dutch-cased""" ) self.assertIsInstance(lowerCamelCase_ , (BertTokenizer, BertTokenizerFast) ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ): self.assertEqual(tokenizer.basic_tokenizer.do_lower_case , lowerCamelCase_ ) else: self.assertEqual(tokenizer.do_lower_case , lowerCamelCase_ ) self.assertEqual(tokenizer.model_max_length , 512 ) @require_tokenizers def lowerCamelCase_ ( self : str ): """simple docstring""" for tokenizer_class in [BertTokenizer, BertTokenizerFast, AutoTokenizer]: with self.assertRaisesRegex( lowerCamelCase_ , """julien-c/herlolip-not-exists is not a local folder and is not a valid model identifier""" , ): UpperCamelCase = tokenizer_class.from_pretrained("""julien-c/herlolip-not-exists""" ) def lowerCamelCase_ ( self : Tuple ): """simple docstring""" UpperCamelCase = TOKENIZER_MAPPING.values() UpperCamelCase = [] for slow_tok, fast_tok in tokenizers: if slow_tok is not None: tokenizer_names.append(slow_tok.__name__ ) if fast_tok is not None: tokenizer_names.append(fast_tok.__name__ ) for tokenizer_name in tokenizer_names: # must find the right class tokenizer_class_from_name(lowerCamelCase_ ) @require_tokenizers def lowerCamelCase_ ( self : str ): """simple docstring""" self.assertIsInstance(AutoTokenizer.from_pretrained("""bert-base-cased""" , use_fast=lowerCamelCase_ ) , lowerCamelCase_ ) self.assertIsInstance(AutoTokenizer.from_pretrained("""bert-base-cased""" ) , lowerCamelCase_ ) @require_tokenizers def lowerCamelCase_ ( self : List[str] ): """simple docstring""" UpperCamelCase = AutoTokenizer.from_pretrained("""distilbert-base-uncased""" , do_lower_case=lowerCamelCase_ ) UpperCamelCase = """Hello, world. How are you?""" UpperCamelCase = tokenizer.tokenize(lowerCamelCase_ ) self.assertEqual("""[UNK]""" , tokens[0] ) UpperCamelCase = AutoTokenizer.from_pretrained("""microsoft/mpnet-base""" , do_lower_case=lowerCamelCase_ ) UpperCamelCase = tokenizer.tokenize(lowerCamelCase_ ) self.assertEqual("""[UNK]""" , tokens[0] ) @require_tokenizers def lowerCamelCase_ ( self : Tuple ): """simple docstring""" UpperCamelCase = AutoTokenizer.from_pretrained("""robot-test/dummy-tokenizer-fast-with-model-config""" ) self.assertEqual(type(lowerCamelCase_ ) , lowerCamelCase_ ) self.assertEqual(tokenizer.model_max_length , 512 ) self.assertEqual(tokenizer.vocab_size , 3_0000 ) self.assertEqual(tokenizer.unk_token , """[UNK]""" ) self.assertEqual(tokenizer.padding_side , """right""" ) self.assertEqual(tokenizer.truncation_side , """right""" ) def lowerCamelCase_ ( self : Union[str, Any] ): """simple docstring""" UpperCamelCase = AutoTokenizer.from_pretrained(lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ , (BertTokenizer, BertTokenizerFast) ) with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(lowerCamelCase_ ) UpperCamelCase = AutoTokenizer.from_pretrained(lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ , tokenizer.__class__ ) self.assertEqual(tokenizera.vocab_size , 12 ) def lowerCamelCase_ ( self : Optional[int] ): """simple docstring""" UpperCamelCase = AutoTokenizer.from_pretrained("""ctrl""" ) # There is no fast CTRL so this always gives us a slow tokenizer. self.assertIsInstance(lowerCamelCase_ , lowerCamelCase_ ) def lowerCamelCase_ ( self : List[Any] ): """simple docstring""" UpperCamelCase = get_tokenizer_config("""bert-base-cased""" ) UpperCamelCase = config.pop("""_commit_hash""" , lowerCamelCase_ ) # If we ever update bert-base-cased tokenizer config, this dict here will need to be updated. self.assertEqual(lowerCamelCase_ , {"""do_lower_case""": False} ) # This model does not have a tokenizer_config so we get back an empty dict. UpperCamelCase = get_tokenizer_config(lowerCamelCase_ ) self.assertDictEqual(lowerCamelCase_ , {} ) # A tokenizer saved with `save_pretrained` always creates a tokenizer config. UpperCamelCase = AutoTokenizer.from_pretrained(lowerCamelCase_ ) with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(lowerCamelCase_ ) UpperCamelCase = get_tokenizer_config(lowerCamelCase_ ) # Check the class of the tokenizer was properly saved (note that it always saves the slow class). self.assertEqual(config["""tokenizer_class"""] , """BertTokenizer""" ) def lowerCamelCase_ ( self : Optional[int] ): """simple docstring""" try: AutoConfig.register("""custom""" , lowerCamelCase_ ) AutoTokenizer.register(lowerCamelCase_ , slow_tokenizer_class=lowerCamelCase_ ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(lowerCamelCase_ ): AutoTokenizer.register(lowerCamelCase_ , slow_tokenizer_class=lowerCamelCase_ ) UpperCamelCase = CustomTokenizer.from_pretrained(lowerCamelCase_ ) with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(lowerCamelCase_ ) UpperCamelCase = AutoTokenizer.from_pretrained(lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ , lowerCamelCase_ ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] @require_tokenizers def lowerCamelCase_ ( self : Optional[int] ): """simple docstring""" try: AutoConfig.register("""custom""" , lowerCamelCase_ ) # Can register in two steps AutoTokenizer.register(lowerCamelCase_ , slow_tokenizer_class=lowerCamelCase_ ) self.assertEqual(TOKENIZER_MAPPING[CustomConfig] , (CustomTokenizer, None) ) AutoTokenizer.register(lowerCamelCase_ , fast_tokenizer_class=lowerCamelCase_ ) self.assertEqual(TOKENIZER_MAPPING[CustomConfig] , (CustomTokenizer, CustomTokenizerFast) ) del TOKENIZER_MAPPING._extra_content[CustomConfig] # Can register in one step AutoTokenizer.register( lowerCamelCase_ , slow_tokenizer_class=lowerCamelCase_ , fast_tokenizer_class=lowerCamelCase_ ) self.assertEqual(TOKENIZER_MAPPING[CustomConfig] , (CustomTokenizer, CustomTokenizerFast) ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(lowerCamelCase_ ): AutoTokenizer.register(lowerCamelCase_ , fast_tokenizer_class=lowerCamelCase_ ) # We pass through a bert tokenizer fast cause there is no converter slow to fast for our new toknizer # and that model does not have a tokenizer.json with tempfile.TemporaryDirectory() as tmp_dir: UpperCamelCase = BertTokenizerFast.from_pretrained(lowerCamelCase_ ) bert_tokenizer.save_pretrained(lowerCamelCase_ ) UpperCamelCase = CustomTokenizerFast.from_pretrained(lowerCamelCase_ ) with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(lowerCamelCase_ ) UpperCamelCase = AutoTokenizer.from_pretrained(lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ , lowerCamelCase_ ) UpperCamelCase = AutoTokenizer.from_pretrained(lowerCamelCase_ , use_fast=lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ , lowerCamelCase_ ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] def lowerCamelCase_ ( self : Optional[int] ): """simple docstring""" with self.assertRaises(lowerCamelCase_ ): UpperCamelCase = AutoTokenizer.from_pretrained("""hf-internal-testing/test_dynamic_tokenizer""" ) # If remote code is disabled, we can't load this config. with self.assertRaises(lowerCamelCase_ ): UpperCamelCase = AutoTokenizer.from_pretrained( """hf-internal-testing/test_dynamic_tokenizer""" , trust_remote_code=lowerCamelCase_ ) UpperCamelCase = AutoTokenizer.from_pretrained("""hf-internal-testing/test_dynamic_tokenizer""" , trust_remote_code=lowerCamelCase_ ) self.assertTrue(tokenizer.special_attribute_present ) # Test tokenizer can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(lowerCamelCase_ ) UpperCamelCase = AutoTokenizer.from_pretrained(lowerCamelCase_ , trust_remote_code=lowerCamelCase_ ) self.assertTrue(reloaded_tokenizer.special_attribute_present ) if is_tokenizers_available(): self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizerFast""" ) self.assertEqual(reloaded_tokenizer.__class__.__name__ , """NewTokenizerFast""" ) # Test we can also load the slow version UpperCamelCase = AutoTokenizer.from_pretrained( """hf-internal-testing/test_dynamic_tokenizer""" , trust_remote_code=lowerCamelCase_ , use_fast=lowerCamelCase_ ) self.assertTrue(tokenizer.special_attribute_present ) self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizer""" ) # Test tokenizer can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(lowerCamelCase_ ) UpperCamelCase = AutoTokenizer.from_pretrained(lowerCamelCase_ , trust_remote_code=lowerCamelCase_ , use_fast=lowerCamelCase_ ) self.assertEqual(reloaded_tokenizer.__class__.__name__ , """NewTokenizer""" ) self.assertTrue(reloaded_tokenizer.special_attribute_present ) else: self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizer""" ) self.assertEqual(reloaded_tokenizer.__class__.__name__ , """NewTokenizer""" ) @require_tokenizers def lowerCamelCase_ ( self : int ): """simple docstring""" class SCREAMING_SNAKE_CASE_ ( __lowerCAmelCase ): __lowerCAmelCase = False class SCREAMING_SNAKE_CASE_ ( __lowerCAmelCase ): __lowerCAmelCase = NewTokenizer __lowerCAmelCase = False try: AutoConfig.register("""custom""" , lowerCamelCase_ ) AutoTokenizer.register(lowerCamelCase_ , slow_tokenizer_class=lowerCamelCase_ ) AutoTokenizer.register(lowerCamelCase_ , fast_tokenizer_class=lowerCamelCase_ ) # If remote code is not set, the default is to use local UpperCamelCase = AutoTokenizer.from_pretrained("""hf-internal-testing/test_dynamic_tokenizer""" ) self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizerFast""" ) self.assertFalse(tokenizer.special_attribute_present ) UpperCamelCase = AutoTokenizer.from_pretrained("""hf-internal-testing/test_dynamic_tokenizer""" , use_fast=lowerCamelCase_ ) self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizer""" ) self.assertFalse(tokenizer.special_attribute_present ) # If remote code is disabled, we load the local one. UpperCamelCase = AutoTokenizer.from_pretrained( """hf-internal-testing/test_dynamic_tokenizer""" , trust_remote_code=lowerCamelCase_ ) self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizerFast""" ) self.assertFalse(tokenizer.special_attribute_present ) UpperCamelCase = AutoTokenizer.from_pretrained( """hf-internal-testing/test_dynamic_tokenizer""" , trust_remote_code=lowerCamelCase_ , use_fast=lowerCamelCase_ ) self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizer""" ) self.assertFalse(tokenizer.special_attribute_present ) # If remote is enabled, we load from the Hub UpperCamelCase = AutoTokenizer.from_pretrained( """hf-internal-testing/test_dynamic_tokenizer""" , trust_remote_code=lowerCamelCase_ ) self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizerFast""" ) self.assertTrue(tokenizer.special_attribute_present ) UpperCamelCase = AutoTokenizer.from_pretrained( """hf-internal-testing/test_dynamic_tokenizer""" , trust_remote_code=lowerCamelCase_ , use_fast=lowerCamelCase_ ) self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizer""" ) self.assertTrue(tokenizer.special_attribute_present ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] def lowerCamelCase_ ( self : Optional[int] ): """simple docstring""" UpperCamelCase = AutoTokenizer.from_pretrained( """hf-internal-testing/test_dynamic_tokenizer_legacy""" , trust_remote_code=lowerCamelCase_ ) self.assertTrue(tokenizer.special_attribute_present ) if is_tokenizers_available(): self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizerFast""" ) # Test we can also load the slow version UpperCamelCase = AutoTokenizer.from_pretrained( """hf-internal-testing/test_dynamic_tokenizer_legacy""" , trust_remote_code=lowerCamelCase_ , use_fast=lowerCamelCase_ ) self.assertTrue(tokenizer.special_attribute_present ) self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizer""" ) else: self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizer""" ) def lowerCamelCase_ ( self : List[str] ): """simple docstring""" with self.assertRaisesRegex( lowerCamelCase_ , """bert-base is not a local folder and is not a valid model identifier""" ): UpperCamelCase = AutoTokenizer.from_pretrained("""bert-base""" ) def lowerCamelCase_ ( self : Tuple ): """simple docstring""" with self.assertRaisesRegex( lowerCamelCase_ , R"""aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)""" ): UpperCamelCase = AutoTokenizer.from_pretrained(lowerCamelCase_ , revision="""aaaaaa""" ) def lowerCamelCase_ ( self : str ): """simple docstring""" UpperCamelCase = AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-bert""" ) with RequestCounter() as counter: UpperCamelCase = AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-bert""" ) self.assertEqual(counter.get_request_count , 0 ) self.assertEqual(counter.head_request_count , 1 ) self.assertEqual(counter.other_request_count , 0 )
343
from __future__ import annotations import copy import inspect import json import math import os import tempfile import unittest from importlib import import_module import numpy as np from transformers import ViTMAEConfig from transformers.file_utils import cached_property, is_tf_available, is_vision_available from transformers.testing_utils import require_tf, require_vision, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFViTMAEForPreTraining, TFViTMAEModel if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class SCREAMING_SNAKE_CASE_ : def __init__( self : Tuple , lowerCamelCase_ : Any , lowerCamelCase_ : Dict=13 , lowerCamelCase_ : str=30 , lowerCamelCase_ : List[str]=2 , lowerCamelCase_ : Union[str, Any]=3 , lowerCamelCase_ : Any=True , lowerCamelCase_ : int=True , lowerCamelCase_ : Tuple=32 , lowerCamelCase_ : Optional[Any]=2 , lowerCamelCase_ : int=4 , lowerCamelCase_ : str=37 , lowerCamelCase_ : Optional[Any]="gelu" , lowerCamelCase_ : Optional[int]=0.1 , lowerCamelCase_ : List[Any]=0.1 , lowerCamelCase_ : List[Any]=10 , lowerCamelCase_ : List[Any]=0.0_2 , lowerCamelCase_ : Optional[int]=3 , lowerCamelCase_ : List[Any]=0.6 , lowerCamelCase_ : Optional[Any]=None , ): """simple docstring""" UpperCamelCase = parent UpperCamelCase = batch_size UpperCamelCase = image_size UpperCamelCase = patch_size UpperCamelCase = num_channels UpperCamelCase = is_training UpperCamelCase = use_labels UpperCamelCase = hidden_size UpperCamelCase = num_hidden_layers UpperCamelCase = num_attention_heads UpperCamelCase = intermediate_size UpperCamelCase = hidden_act UpperCamelCase = hidden_dropout_prob UpperCamelCase = attention_probs_dropout_prob UpperCamelCase = type_sequence_label_size UpperCamelCase = initializer_range UpperCamelCase = mask_ratio UpperCamelCase = scope # in ViTMAE, the expected sequence length = (num_patches + 1) * (1 - config.mask_ratio), rounded above # (we add 1 for the [CLS] token) UpperCamelCase = (image_size // patch_size) ** 2 UpperCamelCase = int(math.ceil((1 - mask_ratio) * (num_patches + 1) ) ) def lowerCamelCase_ ( self : List[Any] ): """simple docstring""" UpperCamelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase = None if self.use_labels: UpperCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase = self.get_config() return config, pixel_values, labels def lowerCamelCase_ ( self : List[Any] ): """simple docstring""" return ViTMAEConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , decoder_hidden_size=self.hidden_size , decoder_num_hidden_layers=self.num_hidden_layers , decoder_num_attention_heads=self.num_attention_heads , decoder_intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=lowerCamelCase_ , initializer_range=self.initializer_range , mask_ratio=self.mask_ratio , ) def lowerCamelCase_ ( self : Any , lowerCamelCase_ : Union[str, Any] , lowerCamelCase_ : Any , lowerCamelCase_ : Union[str, Any] ): """simple docstring""" UpperCamelCase = TFViTMAEModel(config=lowerCamelCase_ ) UpperCamelCase = model(lowerCamelCase_ , training=lowerCamelCase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCamelCase_ ( self : List[str] , lowerCamelCase_ : Union[str, Any] , lowerCamelCase_ : List[str] , lowerCamelCase_ : str ): """simple docstring""" UpperCamelCase = TFViTMAEForPreTraining(lowerCamelCase_ ) UpperCamelCase = model(lowerCamelCase_ , training=lowerCamelCase_ ) # expected sequence length = num_patches UpperCamelCase = (self.image_size // self.patch_size) ** 2 UpperCamelCase = self.patch_size**2 * self.num_channels self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) ) # test greyscale images UpperCamelCase = 1 UpperCamelCase = TFViTMAEForPreTraining(lowerCamelCase_ ) UpperCamelCase = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) UpperCamelCase = model(lowerCamelCase_ , training=lowerCamelCase_ ) UpperCamelCase = self.patch_size**2 self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) ) def lowerCamelCase_ ( self : Dict ): """simple docstring""" UpperCamelCase = self.prepare_config_and_inputs() ((UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase)) = config_and_inputs UpperCamelCase = {"""pixel_values""": pixel_values} return config, inputs_dict @require_tf class SCREAMING_SNAKE_CASE_ ( __lowerCAmelCase , __lowerCAmelCase , unittest.TestCase ): __lowerCAmelCase = (TFViTMAEModel, TFViTMAEForPreTraining) if is_tf_available() else () __lowerCAmelCase = {"""feature-extraction""": TFViTMAEModel} if is_tf_available() else {} __lowerCAmelCase = False __lowerCAmelCase = False __lowerCAmelCase = False __lowerCAmelCase = False def lowerCamelCase_ ( self : List[Any] ): """simple docstring""" UpperCamelCase = TFViTMAEModelTester(self ) UpperCamelCase = ConfigTester(self , config_class=lowerCamelCase_ , has_text_modality=lowerCamelCase_ , hidden_size=37 ) def lowerCamelCase_ ( self : Optional[int] ): """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason="""ViTMAE does not use inputs_embeds""" ) def lowerCamelCase_ ( self : str ): """simple docstring""" pass def lowerCamelCase_ ( self : Tuple ): """simple docstring""" UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase = model_class(lowerCamelCase_ ) self.assertIsInstance(model.get_input_embeddings() , (tf.keras.layers.Layer) ) UpperCamelCase = model.get_output_embeddings() self.assertTrue(x is None or isinstance(lowerCamelCase_ , tf.keras.layers.Layer ) ) def lowerCamelCase_ ( self : Union[str, Any] ): """simple docstring""" UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase = model_class(lowerCamelCase_ ) UpperCamelCase = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase = [*signature.parameters.keys()] UpperCamelCase = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , lowerCamelCase_ ) def lowerCamelCase_ ( self : str ): """simple docstring""" UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCamelCase_ ) def lowerCamelCase_ ( self : int ): """simple docstring""" UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*lowerCamelCase_ ) def lowerCamelCase_ ( self : Dict ): """simple docstring""" np.random.seed(2 ) UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase = int((config.image_size // config.patch_size) ** 2 ) UpperCamelCase = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) for model_class in self.all_model_classes: UpperCamelCase = model_class(lowerCamelCase_ ) UpperCamelCase = self._prepare_for_class(lowerCamelCase_ , lowerCamelCase_ ) UpperCamelCase = model(lowerCamelCase_ , noise=lowerCamelCase_ ) UpperCamelCase = copy.deepcopy(self._prepare_for_class(lowerCamelCase_ , lowerCamelCase_ ) ) UpperCamelCase = model(**lowerCamelCase_ , noise=lowerCamelCase_ ) UpperCamelCase = outputs_dict[0].numpy() UpperCamelCase = outputs_keywords[0].numpy() self.assertLess(np.sum(np.abs(output_dict - output_keywords ) ) , 1E-6 ) def lowerCamelCase_ ( self : List[Any] ): """simple docstring""" np.random.seed(2 ) UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase = int((config.image_size // config.patch_size) ** 2 ) UpperCamelCase = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) def prepare_numpy_arrays(lowerCamelCase_ : List[Any] ): UpperCamelCase = {} for k, v in inputs_dict.items(): if tf.is_tensor(lowerCamelCase_ ): UpperCamelCase = v.numpy() else: UpperCamelCase = np.array(lowerCamelCase_ ) return inputs_np_dict for model_class in self.all_model_classes: UpperCamelCase = model_class(lowerCamelCase_ ) UpperCamelCase = self._prepare_for_class(lowerCamelCase_ , lowerCamelCase_ ) UpperCamelCase = prepare_numpy_arrays(lowerCamelCase_ ) UpperCamelCase = model(lowerCamelCase_ , noise=lowerCamelCase_ ) UpperCamelCase = model(**lowerCamelCase_ , noise=lowerCamelCase_ ) self.assert_outputs_same(lowerCamelCase_ , lowerCamelCase_ ) def lowerCamelCase_ ( self : Any , lowerCamelCase_ : Optional[int] , lowerCamelCase_ : Optional[int] , lowerCamelCase_ : Optional[int] ): """simple docstring""" np.random.seed(2 ) UpperCamelCase = int((tf_model.config.image_size // tf_model.config.patch_size) ** 2 ) UpperCamelCase = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) UpperCamelCase = tf.constant(lowerCamelCase_ ) # Add `noise` argument. # PT inputs will be prepared in `super().check_pt_tf_models()` with this added `noise` argument UpperCamelCase = tf_noise super().check_pt_tf_models(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) def lowerCamelCase_ ( self : Dict ): """simple docstring""" np.random.seed(2 ) UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase = { module_member for model_class in self.all_model_classes for module in (import_module(model_class.__module__ ),) for module_member_name in dir(lowerCamelCase_ ) if module_member_name.endswith("""MainLayer""" ) # This condition is required, since `modeling_tf_clip.py` has 3 classes whose names end with `MainLayer`. and module_member_name[: -len("""MainLayer""" )] == model_class.__name__[: -len("""Model""" )] for module_member in (getattr(lowerCamelCase_ , lowerCamelCase_ ),) if isinstance(lowerCamelCase_ , lowerCamelCase_ ) and tf.keras.layers.Layer in module_member.__bases__ and getattr(lowerCamelCase_ , """_keras_serializable""" , lowerCamelCase_ ) } UpperCamelCase = int((config.image_size // config.patch_size) ** 2 ) UpperCamelCase = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) UpperCamelCase = tf.convert_to_tensor(lowerCamelCase_ ) inputs_dict.update({"""noise""": noise} ) for main_layer_class in tf_main_layer_classes: UpperCamelCase = main_layer_class(lowerCamelCase_ ) UpperCamelCase = { name: tf.keras.Input(tensor.shape[1:] , dtype=tensor.dtype ) for name, tensor in inputs_dict.items() } UpperCamelCase = tf.keras.Model(lowerCamelCase_ , outputs=main_layer(lowerCamelCase_ ) ) UpperCamelCase = model(lowerCamelCase_ ) with tempfile.TemporaryDirectory() as tmpdirname: UpperCamelCase = os.path.join(lowerCamelCase_ , """keras_model.h5""" ) model.save(lowerCamelCase_ ) UpperCamelCase = tf.keras.models.load_model( lowerCamelCase_ , custom_objects={main_layer_class.__name__: main_layer_class} ) assert isinstance(lowerCamelCase_ , tf.keras.Model ) UpperCamelCase = model(lowerCamelCase_ ) self.assert_outputs_same(lowerCamelCase_ , lowerCamelCase_ ) @slow def lowerCamelCase_ ( self : Dict ): """simple docstring""" np.random.seed(2 ) UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase = int((config.image_size // config.patch_size) ** 2 ) UpperCamelCase = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) for model_class in self.all_model_classes: UpperCamelCase = model_class(lowerCamelCase_ ) UpperCamelCase = self._prepare_for_class(lowerCamelCase_ , lowerCamelCase_ ) UpperCamelCase = model(lowerCamelCase_ , noise=lowerCamelCase_ ) if model_class.__name__ == "TFViTMAEModel": UpperCamelCase = outputs.last_hidden_state.numpy() UpperCamelCase = 0 else: UpperCamelCase = outputs.logits.numpy() UpperCamelCase = 0 with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(lowerCamelCase_ , saved_model=lowerCamelCase_ ) UpperCamelCase = model_class.from_pretrained(lowerCamelCase_ ) UpperCamelCase = model(lowerCamelCase_ , noise=lowerCamelCase_ ) if model_class.__name__ == "TFViTMAEModel": UpperCamelCase = after_outputs["""last_hidden_state"""].numpy() UpperCamelCase = 0 else: UpperCamelCase = after_outputs["""logits"""].numpy() UpperCamelCase = 0 UpperCamelCase = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(lowerCamelCase_ , 1E-5 ) def lowerCamelCase_ ( self : List[str] ): """simple docstring""" np.random.seed(2 ) UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase = int((config.image_size // config.patch_size) ** 2 ) UpperCamelCase = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) for model_class in self.all_model_classes: UpperCamelCase = model_class(lowerCamelCase_ ) UpperCamelCase = self._prepare_for_class(lowerCamelCase_ , lowerCamelCase_ ) UpperCamelCase = model(lowerCamelCase_ , noise=lowerCamelCase_ ) UpperCamelCase = model.get_config() # make sure that returned config is jsonifiable, which is required by keras json.dumps(lowerCamelCase_ ) UpperCamelCase = model_class.from_config(model.get_config() ) # make sure it also accepts a normal config UpperCamelCase = model_class.from_config(model.config ) UpperCamelCase = new_model(lowerCamelCase_ ) # Build model new_model.set_weights(model.get_weights() ) UpperCamelCase = new_model(lowerCamelCase_ , noise=lowerCamelCase_ ) self.assert_outputs_same(lowerCamelCase_ , lowerCamelCase_ ) @unittest.skip( reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load to get deterministic results.""" ) def lowerCamelCase_ ( self : int ): """simple docstring""" pass @unittest.skip(reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load""" ) def lowerCamelCase_ ( self : Optional[int] ): """simple docstring""" pass @slow def lowerCamelCase_ ( self : Optional[int] ): """simple docstring""" UpperCamelCase = TFViTMAEModel.from_pretrained("""google/vit-base-patch16-224""" ) self.assertIsNotNone(lowerCamelCase_ ) def lowercase( ) -> int: '''simple docstring''' UpperCamelCase = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_tf @require_vision class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): @cached_property def lowerCamelCase_ ( self : Dict ): """simple docstring""" return ViTImageProcessor.from_pretrained("""facebook/vit-mae-base""" ) if is_vision_available() else None @slow def lowerCamelCase_ ( self : List[str] ): """simple docstring""" np.random.seed(2 ) UpperCamelCase = TFViTMAEForPreTraining.from_pretrained("""facebook/vit-mae-base""" ) UpperCamelCase = self.default_image_processor UpperCamelCase = prepare_img() UpperCamelCase = image_processor(images=lowerCamelCase_ , return_tensors="""tf""" ) # prepare a noise vector that will be also used for testing the TF model # (this way we can ensure that the PT and TF models operate on the same inputs) UpperCamelCase = ViTMAEConfig() UpperCamelCase = int((vit_mae_config.image_size // vit_mae_config.patch_size) ** 2 ) UpperCamelCase = np.random.uniform(size=(1, num_patches) ) # forward pass UpperCamelCase = model(**lowerCamelCase_ , noise=lowerCamelCase_ ) # verify the logits UpperCamelCase = tf.convert_to_tensor([1, 196, 768] ) self.assertEqual(outputs.logits.shape , lowerCamelCase_ ) UpperCamelCase = tf.convert_to_tensor( [[-0.0_5_4_8, -1.7_0_2_3, -0.9_3_2_5], [0.3_7_2_1, -0.5_6_7_0, -0.2_2_3_3], [0.8_2_3_5, -1.3_8_7_8, -0.3_5_2_4]] ) tf.debugging.assert_near(outputs.logits[0, :3, :3] , lowerCamelCase_ , atol=1E-4 )
343
1
def lowerCAmelCase_ ( __a ) -> list: """simple docstring""" if len(__a ) < 2: return collection def circle_sort_util(__a , __a , __a ) -> bool: lowerCamelCase__: str =False if low == high: return swapped lowerCamelCase__: Optional[int] =low lowerCamelCase__: Optional[Any] =high while left < right: if collection[left] > collection[right]: lowerCamelCase__ , lowerCamelCase__: List[Any] =( collection[right], collection[left], ) lowerCamelCase__: List[str] =True left += 1 right -= 1 if left == right and collection[left] > collection[right + 1]: lowerCamelCase__ , lowerCamelCase__: Union[str, Any] =( collection[right + 1], collection[left], ) lowerCamelCase__: List[str] =True lowerCamelCase__: Tuple =low + int((high - low) / 2 ) lowerCamelCase__: int =circle_sort_util(__a , __a , __a ) lowerCamelCase__: int =circle_sort_util(__a , mid + 1 , __a ) return swapped or left_swap or right_swap lowerCamelCase__: Any =True while is_not_sorted is True: lowerCamelCase__: Optional[int] =circle_sort_util(__a , 0 , len(__a ) - 1 ) return collection if __name__ == "__main__": __A = input("Enter numbers separated by a comma:\n").strip() __A = [int(item) for item in user_input.split(",")] print(circle_sort(unsorted))
273
import argparse import logging import pickle from collections import Counter logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO ) __A = logging.getLogger(__name__) if __name__ == "__main__": __A = argparse.ArgumentParser( description="Token Counts for smoothing the masking probabilities in MLM (cf XLM/word2vec)" ) parser.add_argument( "--data_file", type=str, default="data/dump.bert-base-uncased.pickle", help="The binarized dataset." ) parser.add_argument( "--token_counts_dump", type=str, default="data/token_counts.bert-base-uncased.pickle", help="The dump file." ) parser.add_argument("--vocab_size", default=3_0522, type=int) __A = parser.parse_args() logger.info(f'Loading data from {args.data_file}') with open(args.data_file, "rb") as fp: __A = pickle.load(fp) logger.info("Counting occurrences for MLM.") __A = Counter() for tk_ids in data: counter.update(tk_ids) __A = [0] * args.vocab_size for k, v in counter.items(): __A = v logger.info(f'Dump to {args.token_counts_dump}') with open(args.token_counts_dump, "wb") as handle: pickle.dump(counts, handle, protocol=pickle.HIGHEST_PROTOCOL)
273
1
"""simple docstring""" from pathlib import Path import fire from tqdm import tqdm def lowercase ( A_="ro" , A_="en" , A_="wmt16" , A_=None )-> None: '''simple docstring''' try: import datasets except (ModuleNotFoundError, ImportError): raise ImportError("run pip install datasets" ) a : List[Any] = F'''{src_lang}-{tgt_lang}''' print(F'''Converting {dataset}-{pair}''' ) a : Tuple = datasets.load_dataset(A_ , A_ ) if save_dir is None: a : Dict = F'''{dataset}-{pair}''' a : str = Path(A_ ) save_dir.mkdir(exist_ok=A_ ) for split in ds.keys(): print(F'''Splitting {split} with {ds[split].num_rows} records''' ) # to save to val.source, val.target like summary datasets a : Any = "val" if split == "validation" else split a : Tuple = save_dir.joinpath(F'''{fn}.source''' ) a : Any = save_dir.joinpath(F'''{fn}.target''' ) a : Tuple = src_path.open("w+" ) a : List[Any] = tgt_path.open("w+" ) # reader is the bottleneck so writing one record at a time doesn't slow things down for x in tqdm(ds[split] ): a : Any = x["translation"] src_fp.write(ex[src_lang] + "\n" ) tgt_fp.write(ex[tgt_lang] + "\n" ) print(F'''Saved {dataset} dataset to {save_dir}''' ) if __name__ == "__main__": fire.Fire(download_wmt_dataset)
40
from pathlib import Path import cva import numpy as np from matplotlib import pyplot as plt def lowerCAmelCase_ ( A_ ,A_ ,A_ ,A_ ,A_): UpperCamelCase__: List[str] = cva.getAffineTransform(A_ ,A_) return cva.warpAffine(A_ ,A_ ,(rows, cols)) if __name__ == "__main__": # read original image A__: Union[str, Any] = cva.imread( str(Path(__file__).resolve().parent.parent / '''image_data''' / '''lena.jpg''') ) # turn image in gray scale value A__: Tuple = cva.cvtColor(image, cva.COLOR_BGR2GRAY) # get image shape A__ , A__: List[Any] = gray_img.shape # set different points to rotate image A__: Tuple = np.array([[50, 50], [200, 50], [50, 200]], np.floataa) A__: Dict = np.array([[10, 100], [200, 50], [100, 250]], np.floataa) A__: Any = np.array([[50, 50], [150, 50], [120, 200]], np.floataa) A__: Union[str, Any] = np.array([[10, 100], [80, 50], [180, 250]], np.floataa) # add all rotated images in a list A__: str = [ gray_img, get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), ] # plot different image rotations A__: Optional[int] = plt.figure(1) A__: List[str] = ['''Original''', '''Rotation 1''', '''Rotation 2''', '''Rotation 3'''] for i, image in enumerate(images): plt.subplot(2, 2, i + 1), plt.imshow(image, '''gray''') plt.title(titles[i]) plt.axis('''off''') plt.subplots_adjust(left=0.0, bottom=0.05, right=1.0, top=0.95) plt.show()
149
0
import unittest from transformers import LiltConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, ) from transformers.models.lilt.modeling_lilt import LILT_PRETRAINED_MODEL_ARCHIVE_LIST class __A: """simple docstring""" def __init__( self , _snake_case , _snake_case=13 , _snake_case=7 , _snake_case=True , _snake_case=True , _snake_case=True , _snake_case=True , _snake_case=99 , _snake_case=24 , _snake_case=2 , _snake_case=6 , _snake_case=37 , _snake_case="gelu" , _snake_case=0.1 , _snake_case=0.1 , _snake_case=512 , _snake_case=16 , _snake_case=2 , _snake_case=0.02 , _snake_case=3 , _snake_case=None , _snake_case=1_000 , ) -> int: '''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 = scope __a = range_bbox def SCREAMING_SNAKE_CASE_ ( self ) -> Dict: '''simple docstring''' __a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __a = ids_tensor([self.batch_size, self.seq_length, 4] , self.range_bbox ) # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: __a = bbox[i, j, 3] __a = bbox[i, j, 1] __a = t if bbox[i, j, 2] < bbox[i, j, 0]: __a = bbox[i, j, 2] __a = bbox[i, j, 0] __a = t __a = None if self.use_input_mask: __a = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) __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 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 = self.get_config() return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels def SCREAMING_SNAKE_CASE_ ( self ) -> List[str]: '''simple docstring''' return LiltConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) def SCREAMING_SNAKE_CASE_ ( self , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , ) -> Any: '''simple docstring''' __a = LiltModel(config=_snake_case ) model.to(_snake_case ) model.eval() __a = model(_snake_case , bbox=_snake_case , attention_mask=_snake_case , token_type_ids=_snake_case ) __a = model(_snake_case , bbox=_snake_case , token_type_ids=_snake_case ) __a = model(_snake_case , bbox=_snake_case ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def SCREAMING_SNAKE_CASE_ ( self , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , ) -> List[str]: '''simple docstring''' __a = self.num_labels __a = LiltForTokenClassification(config=_snake_case ) model.to(_snake_case ) model.eval() __a = model( _snake_case , bbox=_snake_case , attention_mask=_snake_case , token_type_ids=_snake_case , labels=_snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def SCREAMING_SNAKE_CASE_ ( self , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , ) -> List[Any]: '''simple docstring''' __a = LiltForQuestionAnswering(config=_snake_case ) model.to(_snake_case ) model.eval() __a = model( _snake_case , bbox=_snake_case , attention_mask=_snake_case , token_type_ids=_snake_case , start_positions=_snake_case , end_positions=_snake_case , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def SCREAMING_SNAKE_CASE_ ( self ) -> Optional[int]: '''simple docstring''' __a = self.prepare_config_and_inputs() ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) = config_and_inputs __a = { '''input_ids''': input_ids, '''bbox''': bbox, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask, } return config, inputs_dict @require_torch class __A( a , a , a , unittest.TestCase ): """simple docstring""" snake_case_ = ( ( LiltModel, LiltForSequenceClassification, LiltForTokenClassification, LiltForQuestionAnswering, ) if is_torch_available() else () ) snake_case_ = ( { '''feature-extraction''': LiltModel, '''question-answering''': LiltForQuestionAnswering, '''text-classification''': LiltForSequenceClassification, '''token-classification''': LiltForTokenClassification, '''zero-shot''': LiltForSequenceClassification, } if is_torch_available() else {} ) snake_case_ = False snake_case_ = False def SCREAMING_SNAKE_CASE_ ( self , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case ) -> Optional[int]: '''simple docstring''' return True def SCREAMING_SNAKE_CASE_ ( self ) -> Optional[int]: '''simple docstring''' __a = LiltModelTester(self ) __a = ConfigTester(self , config_class=_snake_case , hidden_size=37 ) def SCREAMING_SNAKE_CASE_ ( self ) -> int: '''simple docstring''' self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE_ ( self ) -> Any: '''simple docstring''' __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_snake_case ) def SCREAMING_SNAKE_CASE_ ( self ) -> 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(*_snake_case ) def SCREAMING_SNAKE_CASE_ ( self ) -> Optional[int]: '''simple docstring''' __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_snake_case ) def SCREAMING_SNAKE_CASE_ ( self ) -> List[Any]: '''simple docstring''' __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*_snake_case ) @slow def SCREAMING_SNAKE_CASE_ ( self ) -> Union[str, Any]: '''simple docstring''' for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = LiltModel.from_pretrained(_snake_case ) self.assertIsNotNone(_snake_case ) @require_torch @slow class __A( unittest.TestCase ): """simple docstring""" def SCREAMING_SNAKE_CASE_ ( self ) -> List[str]: '''simple docstring''' __a = LiltModel.from_pretrained('''SCUT-DLVCLab/lilt-roberta-en-base''' ).to(_snake_case ) __a = torch.tensor([[1, 2]] , device=_snake_case ) __a = torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]] , device=_snake_case ) # forward pass with torch.no_grad(): __a = model(input_ids=_snake_case , bbox=_snake_case ) __a = torch.Size([1, 2, 768] ) __a = torch.tensor( [[-0.0653, 0.0950, -0.0061], [-0.0545, 0.0926, -0.0324]] , device=_snake_case , ) self.assertTrue(outputs.last_hidden_state.shape , _snake_case ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :, :3] , _snake_case , atol=1E-3 ) )
355
import inspect import os import unittest from dataclasses import dataclass import torch from accelerate import Accelerator, DistributedDataParallelKwargs, GradScalerKwargs from accelerate.state import AcceleratorState from accelerate.test_utils import execute_subprocess_async, require_cuda, require_multi_gpu from accelerate.utils import KwargsHandler @dataclass class __A( a ): snake_case_ = 0 snake_case_ = False snake_case_ = 3.0 class __A( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self ) -> Dict: '''simple docstring''' self.assertDictEqual(MockClass().to_kwargs() , {} ) self.assertDictEqual(MockClass(a=2 ).to_kwargs() , {'''a''': 2} ) self.assertDictEqual(MockClass(a=2 , b=_snake_case ).to_kwargs() , {'''a''': 2, '''b''': True} ) self.assertDictEqual(MockClass(a=2 , c=2.25 ).to_kwargs() , {'''a''': 2, '''c''': 2.25} ) @require_cuda def SCREAMING_SNAKE_CASE_ ( self ) -> str: '''simple docstring''' __a = GradScalerKwargs(init_scale=1_024 , growth_factor=2 ) AcceleratorState._reset_state() __a = Accelerator(mixed_precision='''fp16''' , kwargs_handlers=[scaler_handler] ) print(accelerator.use_fpaa ) __a = accelerator.scaler # Check the kwargs have been applied self.assertEqual(scaler._init_scale , 1024.0 ) self.assertEqual(scaler._growth_factor , 2.0 ) # Check the other values are at the default self.assertEqual(scaler._backoff_factor , 0.5 ) self.assertEqual(scaler._growth_interval , 2_000 ) self.assertEqual(scaler._enabled , _snake_case ) @require_multi_gpu def SCREAMING_SNAKE_CASE_ ( self ) -> int: '''simple docstring''' __a = ['''torchrun''', F"""--nproc_per_node={torch.cuda.device_count()}""", inspect.getfile(self.__class__ )] execute_subprocess_async(_snake_case , env=os.environ.copy() ) if __name__ == "__main__": A : List[str] = DistributedDataParallelKwargs(bucket_cap_mb=1_5, find_unused_parameters=True) A : Optional[Any] = Accelerator(kwargs_handlers=[ddp_scaler]) A : int = torch.nn.Linear(1_0_0, 2_0_0) A : Optional[int] = accelerator.prepare(model) # Check the values changed in kwargs A : List[Any] = '' A : Tuple = model.bucket_bytes_cap // (1_0_2_4 * 1_0_2_4) if observed_bucket_cap_map != 1_5: error_msg += F"Kwargs badly passed, should have `15` but found {observed_bucket_cap_map}.\n" if model.find_unused_parameters is not True: error_msg += F"Kwargs badly passed, should have `True` but found {model.find_unused_parameters}.\n" # Check the values of the defaults if model.dim != 0: error_msg += F"Default value not respected, should have `0` but found {model.dim}.\n" if model.broadcast_buffers is not True: error_msg += F"Default value not respected, should have `True` but found {model.broadcast_buffers}.\n" if model.gradient_as_bucket_view is not False: error_msg += F"Default value not respected, should have `False` but found {model.gradient_as_bucket_view}.\n" # Raise error at the end to make sure we don't stop at the first failure. if len(error_msg) > 0: raise ValueError(error_msg)
33
0
'''simple docstring''' import time import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch, torch_device from ..test_modeling_common import ids_tensor if is_torch_available(): import torch from transformers.generation import ( MaxLengthCriteria, MaxNewTokensCriteria, MaxTimeCriteria, StoppingCriteriaList, validate_stopping_criteria, ) @require_torch class lowerCamelCase_ ( unittest.TestCase ): def lowercase_ ( self : List[str] , _A : int ): '''simple docstring''' UpperCAmelCase__ : Any = 3 UpperCAmelCase__ : str = 250 UpperCAmelCase__ : Optional[Any] = ids_tensor((batch_size, length) , __lowerCAmelCase ) UpperCAmelCase__ : List[str] = torch.ones((batch_size, length) , device=__lowerCAmelCase , dtype=torch.float ) / length return input_ids, scores def lowercase_ ( self : int ): '''simple docstring''' UpperCAmelCase__ : List[str] = self._get_tensors(5 ) UpperCAmelCase__ : str = StoppingCriteriaList( [ MaxLengthCriteria(max_length=10 ), MaxTimeCriteria(max_time=0.1 ), ] ) self.assertFalse(criteria(__lowerCAmelCase , __lowerCAmelCase ) ) UpperCAmelCase__ : List[Any] = self._get_tensors(9 ) self.assertFalse(criteria(__lowerCAmelCase , __lowerCAmelCase ) ) UpperCAmelCase__ : Any = self._get_tensors(10 ) self.assertTrue(criteria(__lowerCAmelCase , __lowerCAmelCase ) ) def lowercase_ ( self : Optional[int] ): '''simple docstring''' UpperCAmelCase__ : Optional[Any] = MaxLengthCriteria(max_length=10 ) UpperCAmelCase__ : Optional[int] = self._get_tensors(5 ) self.assertFalse(criteria(__lowerCAmelCase , __lowerCAmelCase ) ) UpperCAmelCase__ : Any = self._get_tensors(9 ) self.assertFalse(criteria(__lowerCAmelCase , __lowerCAmelCase ) ) UpperCAmelCase__ : int = self._get_tensors(10 ) self.assertTrue(criteria(__lowerCAmelCase , __lowerCAmelCase ) ) def lowercase_ ( self : int ): '''simple docstring''' UpperCAmelCase__ : Tuple = MaxNewTokensCriteria(start_length=5 , max_new_tokens=5 ) UpperCAmelCase__ : Tuple = self._get_tensors(5 ) self.assertFalse(criteria(__lowerCAmelCase , __lowerCAmelCase ) ) UpperCAmelCase__ : Tuple = self._get_tensors(9 ) self.assertFalse(criteria(__lowerCAmelCase , __lowerCAmelCase ) ) UpperCAmelCase__ : Any = self._get_tensors(10 ) self.assertTrue(criteria(__lowerCAmelCase , __lowerCAmelCase ) ) UpperCAmelCase__ : str = StoppingCriteriaList([criteria] ) self.assertEqual(criteria_list.max_length , 10 ) def lowercase_ ( self : List[Any] ): '''simple docstring''' UpperCAmelCase__ : Optional[Any] = self._get_tensors(5 ) UpperCAmelCase__ : List[str] = MaxTimeCriteria(max_time=0.1 ) self.assertFalse(criteria(__lowerCAmelCase , __lowerCAmelCase ) ) UpperCAmelCase__ : Dict = MaxTimeCriteria(max_time=0.1 , initial_timestamp=time.time() - 0.2 ) self.assertTrue(criteria(__lowerCAmelCase , __lowerCAmelCase ) ) def lowercase_ ( self : List[str] ): '''simple docstring''' validate_stopping_criteria(StoppingCriteriaList([MaxLengthCriteria(10 )] ) , 10 ) with self.assertWarns(__lowerCAmelCase ): validate_stopping_criteria(StoppingCriteriaList([MaxLengthCriteria(10 )] ) , 11 ) UpperCAmelCase__ : Dict = validate_stopping_criteria(StoppingCriteriaList() , 11 ) self.assertEqual(len(__lowerCAmelCase ) , 1 )
181
"""simple docstring""" import argparse import torch from torch import nn from transformers import MBartConfig, MBartForConditionalGeneration def snake_case_ ( A_ : Any ): '''simple docstring''' _lowerCamelCase : Any = [ '''encoder.version''', '''decoder.version''', '''model.encoder.version''', '''model.decoder.version''', '''_float_tensor''', '''decoder.output_projection.weight''', ] for k in ignore_keys: state_dict.pop(A_, A_ ) def snake_case_ ( A_ : Union[str, Any] ): '''simple docstring''' _lowerCamelCase , _lowerCamelCase : Tuple = emb.weight.shape _lowerCamelCase : Dict = nn.Linear(A_, A_, bias=A_ ) _lowerCamelCase : str = emb.weight.data return lin_layer def snake_case_ ( A_ : str, A_ : Optional[int]="facebook/mbart-large-en-ro", A_ : Union[str, Any]=False, A_ : List[str]=False ): '''simple docstring''' _lowerCamelCase : Tuple = torch.load(A_, map_location='''cpu''' )['''model'''] remove_ignore_keys_(A_ ) _lowerCamelCase : int = state_dict['''encoder.embed_tokens.weight'''].shape[0] _lowerCamelCase : Any = MBartConfig.from_pretrained(A_, vocab_size=A_ ) if mbart_aa and finetuned: _lowerCamelCase : Any = '''relu''' _lowerCamelCase : Optional[int] = state_dict['''decoder.embed_tokens.weight'''] _lowerCamelCase : Any = MBartForConditionalGeneration(A_ ) model.model.load_state_dict(A_ ) if finetuned: _lowerCamelCase : str = make_linear_from_emb(model.model.shared ) return model if __name__ == "__main__": lowerCAmelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''fairseq_path''', type=str, help='''bart.large, bart.large.cnn or a path to a model.pt on local filesystem.''' ) parser.add_argument('''pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument( '''--hf_config''', default='''facebook/mbart-large-cc25''', type=str, help='''Which huggingface architecture to use: mbart-large''', ) parser.add_argument('''--mbart_50''', action='''store_true''', help='''whether the model is mMART-50 checkpoint''') parser.add_argument('''--finetuned''', action='''store_true''', help='''whether the model is a fine-tuned checkpoint''') lowerCAmelCase__ = parser.parse_args() lowerCAmelCase__ = convert_fairseq_mbart_checkpoint_from_disk( args.fairseq_path, hf_config_path=args.hf_config, finetuned=args.finetuned, mbart_aa=args.mbart_aa ) model.save_pretrained(args.pytorch_dump_folder_path)
72
0
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { "facebook/xlm-roberta-xl": "https://huggingface.co/facebook/xlm-roberta-xl/resolve/main/config.json", "facebook/xlm-roberta-xxl": "https://huggingface.co/facebook/xlm-roberta-xxl/resolve/main/config.json", # See all XLM-RoBERTa-XL models at https://huggingface.co/models?filter=xlm-roberta-xl } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Union[str, Any] = 'xlm-roberta-xl' def __init__( self , _a=250_880 , _a=2_560 , _a=36 , _a=32 , _a=10_240 , _a="gelu" , _a=0.1 , _a=0.1 , _a=514 , _a=1 , _a=0.02 , _a=1E-05 , _a=1 , _a=0 , _a=2 , _a="absolute" , _a=True , _a=None , **_a , ): super().__init__(pad_token_id=_a , bos_token_id=_a , eos_token_id=_a , **_a ) __a = vocab_size __a = hidden_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 = position_embedding_type __a = use_cache __a = classifier_dropout class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' @property def __UpperCAmelCase ( self ): if self.task == "multiple-choice": __a = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: __a = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ] )
11
"""simple docstring""" import math from collections import defaultdict from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput def lowercase ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Union[str, Any]=0.9_99 , lowerCAmelCase__ : List[str]="cosine" , ) -> Optional[int]: if alpha_transform_type == "cosine": def alpha_bar_fn(lowerCAmelCase__ : int ): return math.cos((t + 0.0_08) / 1.0_08 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(lowerCAmelCase__ : Optional[Any] ): return math.exp(t * -12.0 ) else: raise ValueError(f'''Unsupported alpha_tranform_type: {alpha_transform_type}''' ) __a = [] for i in range(lowerCAmelCase__ ): __a = i / num_diffusion_timesteps __a = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(lowerCAmelCase__ ) / alpha_bar_fn(lowerCAmelCase__ ) , lowerCAmelCase__ ) ) return torch.tensor(lowerCAmelCase__ , dtype=torch.floataa ) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Tuple = [e.name for e in KarrasDiffusionSchedulers] __UpperCAmelCase : str = 2 @register_to_config def __init__( self , _a = 1_000 , _a = 0.0_0085 , _a = 0.012 , _a = "linear" , _a = None , _a = "epsilon" , _a = "linspace" , _a = 0 , ): if trained_betas is not None: __a = torch.tensor(_a , dtype=torch.floataa ) elif beta_schedule == "linear": __a = torch.linspace(_a , _a , _a , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. __a = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , _a , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule __a = betas_for_alpha_bar(_a ) else: raise NotImplementedError(f'''{beta_schedule} does is not implemented for {self.__class__}''' ) __a = 1.0 - self.betas __a = torch.cumprod(self.alphas , dim=0 ) # set all values self.set_timesteps(_a , _a , _a ) def __UpperCAmelCase ( self , _a , _a=None ): if schedule_timesteps is None: __a = self.timesteps __a = (schedule_timesteps == timestep).nonzero() # The sigma index that is taken for the **very** first `step` # is always the second index (or the last index if there is only 1) # This way we can ensure we don't accidentally skip a sigma in # case we start in the middle of the denoising schedule (e.g. for image-to-image) if len(self._index_counter ) == 0: __a = 1 if len(_a ) > 1 else 0 else: __a = timestep.cpu().item() if torch.is_tensor(_a ) else timestep __a = self._index_counter[timestep_int] return indices[pos].item() @property def __UpperCAmelCase ( self ): # standard deviation of the initial noise distribution if self.config.timestep_spacing in ["linspace", "trailing"]: return self.sigmas.max() return (self.sigmas.max() ** 2 + 1) ** 0.5 def __UpperCAmelCase ( self , _a , _a , ): __a = self.index_for_timestep(_a ) if self.state_in_first_order: __a = self.sigmas[step_index] else: __a = self.sigmas_interpol[step_index] __a = sample / ((sigma**2 + 1) ** 0.5) return sample def __UpperCAmelCase ( self , _a , _a = None , _a = None , ): __a = num_inference_steps __a = num_train_timesteps or self.config.num_train_timesteps # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891 if self.config.timestep_spacing == "linspace": __a = np.linspace(0 , num_train_timesteps - 1 , _a , dtype=_a )[::-1].copy() elif self.config.timestep_spacing == "leading": __a = num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 __a = (np.arange(0 , _a ) * step_ratio).round()[::-1].copy().astype(_a ) timesteps += self.config.steps_offset elif self.config.timestep_spacing == "trailing": __a = num_train_timesteps / self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 __a = (np.arange(_a , 0 , -step_ratio )).round().copy().astype(_a ) timesteps -= 1 else: raise ValueError( f'''{self.config.timestep_spacing} is not supported. Please make sure to choose one of \'linspace\', \'leading\' or \'trailing\'.''' ) __a = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5 ) __a = torch.from_numpy(np.log(_a ) ).to(_a ) __a = np.interp(_a , np.arange(0 , len(_a ) ) , _a ) __a = np.concatenate([sigmas, [0.0]] ).astype(np.floataa ) __a = torch.from_numpy(_a ).to(device=_a ) # interpolate sigmas __a = sigmas.log().lerp(sigmas.roll(1 ).log() , 0.5 ).exp() __a = torch.cat([sigmas[:1], sigmas[1:].repeat_interleave(2 ), sigmas[-1:]] ) __a = torch.cat( [sigmas_interpol[:1], sigmas_interpol[1:].repeat_interleave(2 ), sigmas_interpol[-1:]] ) if str(_a ).startswith('''mps''' ): # mps does not support float64 __a = torch.from_numpy(_a ).to(_a , dtype=torch.floataa ) else: __a = torch.from_numpy(_a ).to(_a ) # interpolate timesteps __a = self.sigma_to_t(_a ).to(_a , dtype=timesteps.dtype ) __a = torch.stack((timesteps_interpol[1:-1, None], timesteps[1:, None]) , dim=-1 ).flatten() __a = torch.cat([timesteps[:1], interleaved_timesteps] ) __a = None # for exp beta schedules, such as the one for `pipeline_shap_e.py` # we need an index counter __a = defaultdict(_a ) def __UpperCAmelCase ( self , _a ): # get log sigma __a = sigma.log() # get distribution __a = log_sigma - self.log_sigmas[:, None] # get sigmas range __a = dists.ge(0 ).cumsum(dim=0 ).argmax(dim=0 ).clamp(max=self.log_sigmas.shape[0] - 2 ) __a = low_idx + 1 __a = self.log_sigmas[low_idx] __a = self.log_sigmas[high_idx] # interpolate sigmas __a = (low - log_sigma) / (low - high) __a = w.clamp(0 , 1 ) # transform interpolation to time range __a = (1 - w) * low_idx + w * high_idx __a = t.view(sigma.shape ) return t @property def __UpperCAmelCase ( self ): return self.sample is None def __UpperCAmelCase ( self , _a , _a , _a , _a = True , ): __a = self.index_for_timestep(_a ) # advance index counter by 1 __a = timestep.cpu().item() if torch.is_tensor(_a ) else timestep self._index_counter[timestep_int] += 1 if self.state_in_first_order: __a = self.sigmas[step_index] __a = self.sigmas_interpol[step_index + 1] __a = self.sigmas[step_index + 1] else: # 2nd order / KDPM2's method __a = self.sigmas[step_index - 1] __a = self.sigmas_interpol[step_index] __a = self.sigmas[step_index] # currently only gamma=0 is supported. This usually works best anyways. # We can support gamma in the future but then need to scale the timestep before # passing it to the model which requires a change in API __a = 0 __a = sigma * (gamma + 1) # Note: sigma_hat == sigma for now # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise if self.config.prediction_type == "epsilon": __a = sigma_hat if self.state_in_first_order else sigma_interpol __a = sample - sigma_input * model_output elif self.config.prediction_type == "v_prediction": __a = sigma_hat if self.state_in_first_order else sigma_interpol __a = model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + ( sample / (sigma_input**2 + 1) ) elif self.config.prediction_type == "sample": raise NotImplementedError('''prediction_type not implemented yet: sample''' ) else: raise ValueError( f'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`''' ) if self.state_in_first_order: # 2. Convert to an ODE derivative for 1st order __a = (sample - pred_original_sample) / sigma_hat # 3. delta timestep __a = sigma_interpol - sigma_hat # store for 2nd order step __a = sample else: # DPM-Solver-2 # 2. Convert to an ODE derivative for 2nd order __a = (sample - pred_original_sample) / sigma_interpol # 3. delta timestep __a = sigma_next - sigma_hat __a = self.sample __a = None __a = sample + derivative * dt if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=_a ) def __UpperCAmelCase ( self , _a , _a , _a , ): # Make sure sigmas and timesteps have the same device and dtype as original_samples __a = self.sigmas.to(device=original_samples.device , dtype=original_samples.dtype ) if original_samples.device.type == "mps" and torch.is_floating_point(_a ): # mps does not support float64 __a = self.timesteps.to(original_samples.device , dtype=torch.floataa ) __a = timesteps.to(original_samples.device , dtype=torch.floataa ) else: __a = self.timesteps.to(original_samples.device ) __a = timesteps.to(original_samples.device ) __a = [self.index_for_timestep(_a , _a ) for t in timesteps] __a = sigmas[step_indices].flatten() while len(sigma.shape ) < len(original_samples.shape ): __a = sigma.unsqueeze(-1 ) __a = original_samples + noise * sigma return noisy_samples def __len__( self ): return self.config.num_train_timesteps
11
1
"""simple docstring""" import requests snake_case_ = """""" # <-- Put your OpenWeatherMap appid here! snake_case_ = """https://api.openweathermap.org/data/2.5/""" def _lowerCAmelCase ( lowercase_ = "Chicago" , lowercase_ = APPID ): return requests.get(URL_BASE + 'weather' , params=locals() ).json() def _lowerCAmelCase ( lowercase_ = "Kolkata, India" , lowercase_ = APPID ): return requests.get(URL_BASE + 'forecast' , params=locals() ).json() def _lowerCAmelCase ( lowercase_ = 5_5.6_8 , lowercase_ = 1_2.5_7 , lowercase_ = APPID ): return requests.get(URL_BASE + 'onecall' , params=locals() ).json() if __name__ == "__main__": from pprint import pprint while True: snake_case_ = input("""Enter a location:""").strip() if location: pprint(current_weather(location)) else: break
78
"""simple docstring""" import os import sys a :Union[str, Any] = os.path.join(os.path.dirname(__file__), "src") sys.path.append(SRC_DIR) from transformers import ( AutoConfig, AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForQuestionAnswering, AutoModelForSequenceClassification, AutoTokenizer, add_start_docstrings, ) a :int = [ "torch", "numpy", "tokenizers", "filelock", "requests", "tqdm", "regex", "sentencepiece", "sacremoses", "importlib_metadata", "huggingface_hub", ] @add_start_docstrings(AutoConfig.__doc__ ) def _lowercase ( *__lowerCAmelCase , **__lowerCAmelCase ) -> Optional[Any]: return AutoConfig.from_pretrained(*__lowerCAmelCase , **__lowerCAmelCase ) @add_start_docstrings(AutoTokenizer.__doc__ ) def _lowercase ( *__lowerCAmelCase , **__lowerCAmelCase ) -> Union[str, Any]: return AutoTokenizer.from_pretrained(*__lowerCAmelCase , **__lowerCAmelCase ) @add_start_docstrings(AutoModel.__doc__ ) def _lowercase ( *__lowerCAmelCase , **__lowerCAmelCase ) -> Dict: return AutoModel.from_pretrained(*__lowerCAmelCase , **__lowerCAmelCase ) @add_start_docstrings(AutoModelForCausalLM.__doc__ ) def _lowercase ( *__lowerCAmelCase , **__lowerCAmelCase ) -> Optional[int]: return AutoModelForCausalLM.from_pretrained(*__lowerCAmelCase , **__lowerCAmelCase ) @add_start_docstrings(AutoModelForMaskedLM.__doc__ ) def _lowercase ( *__lowerCAmelCase , **__lowerCAmelCase ) -> List[str]: return AutoModelForMaskedLM.from_pretrained(*__lowerCAmelCase , **__lowerCAmelCase ) @add_start_docstrings(AutoModelForSequenceClassification.__doc__ ) def _lowercase ( *__lowerCAmelCase , **__lowerCAmelCase ) -> str: return AutoModelForSequenceClassification.from_pretrained(*__lowerCAmelCase , **__lowerCAmelCase ) @add_start_docstrings(AutoModelForQuestionAnswering.__doc__ ) def _lowercase ( *__lowerCAmelCase , **__lowerCAmelCase ) -> int: return AutoModelForQuestionAnswering.from_pretrained(*__lowerCAmelCase , **__lowerCAmelCase )
132
0
import os import sys import tempfile import torch from .state import AcceleratorState from .utils import PrecisionType, PrepareForLaunch, is_mps_available, patch_environment def __UpperCamelCase ( _A : Optional[Any] , _A : Tuple=() , _A : Any=None , _A : Union[str, Any]="no" , _A : Tuple="29500" ) ->str: """simple docstring""" lowerCamelCase_ =False lowerCamelCase_ =False if any(key.startswith("""KAGGLE""" ) for key in os.environ.keys() ): lowerCamelCase_ =True elif "IPython" in sys.modules: lowerCamelCase_ ="""google.colab""" in str(sys.modules["""IPython"""].get_ipython() ) try: lowerCamelCase_ =PrecisionType(mixed_precision.lower() ) except ValueError: raise ValueError( f'Unknown mixed_precision mode: {args.mixed_precision.lower()}. Choose between {PrecisionType.list()}.' ) if (in_colab or in_kaggle) and (os.environ.get("""TPU_NAME""" , _A ) is not None): # TPU launch import torch_xla.distributed.xla_multiprocessing as xmp if len(AcceleratorState._shared_state ) > 0: raise ValueError( """To train on TPU in Colab or Kaggle Kernel, the `Accelerator` should only be initialized inside """ """your training function. Restart your notebook and make sure no cells initializes an """ """`Accelerator`.""" ) if num_processes is None: lowerCamelCase_ =8 lowerCamelCase_ =PrepareForLaunch(_A , distributed_type="""TPU""" ) print(f'Launching a training on {num_processes} TPU cores.' ) xmp.spawn(_A , args=_A , nprocs=_A , start_method="""fork""" ) elif in_colab: # No need for a distributed launch otherwise as it's either CPU or one GPU. if torch.cuda.is_available(): print("""Launching training on one GPU.""" ) else: print("""Launching training on one CPU.""" ) function(*_A ) else: if num_processes is None: raise ValueError( """You have to specify the number of GPUs you would like to use, add `num_processes=...` to your call.""" ) if num_processes > 1: # Multi-GPU launch from torch.multiprocessing import start_processes from torch.multiprocessing.spawn import ProcessRaisedException if len(AcceleratorState._shared_state ) > 0: raise ValueError( """To launch a multi-GPU training from your notebook, the `Accelerator` should only be initialized """ """inside your training function. Restart your notebook and make sure no cells initializes an """ """`Accelerator`.""" ) if torch.cuda.is_initialized(): raise ValueError( """To launch a multi-GPU training from your notebook, you need to avoid running any instruction """ """using `torch.cuda` in any cell. Restart your notebook and make sure no cells use any CUDA """ """function.""" ) # torch.distributed will expect a few environment variable to be here. We set the ones common to each # process here (the other ones will be set be the launcher). with patch_environment( world_size=_A , master_addr="""127.0.01""" , master_port=_A , mixed_precision=_A ): lowerCamelCase_ =PrepareForLaunch(_A , distributed_type="""MULTI_GPU""" ) print(f'Launching training on {num_processes} GPUs.' ) try: start_processes(_A , args=_A , nprocs=_A , start_method="""fork""" ) except ProcessRaisedException as e: if "Cannot re-initialize CUDA in forked subprocess" in e.args[0]: raise RuntimeError( """CUDA has been initialized before the `notebook_launcher` could create a forked subprocess. """ """This likely stems from an outside import causing issues once the `notebook_launcher()` is called. """ """Please review your imports and test them when running the `notebook_launcher()` to identify """ """which one is problematic.""" ) from e else: # No need for a distributed launch otherwise as it's either CPU, GPU or MPS. if is_mps_available(): lowerCamelCase_ ="""1""" print("""Launching training on MPS.""" ) elif torch.cuda.is_available(): print("""Launching training on one GPU.""" ) else: print("""Launching training on CPU.""" ) function(*_A ) def __UpperCamelCase ( _A : Union[str, Any] , _A : Optional[Any]=() , _A : List[str]=2 ) ->Optional[int]: """simple docstring""" from torch.multiprocessing import start_processes with tempfile.NamedTemporaryFile() as tmp_file: # torch.distributed will expect a few environment variable to be here. We set the ones common to each # process here (the other ones will be set be the launcher). with patch_environment( world_size=_A , master_addr="""127.0.01""" , master_port="""29500""" , accelerate_mixed_precision="""no""" , accelerate_debug_rdv_file=tmp_file.name , accelerate_use_cpu="""yes""" , ): lowerCamelCase_ =PrepareForLaunch(_A , debug=_A ) start_processes(_A , args=_A , nprocs=_A , start_method="""fork""" )
49
import unittest from knapsack import greedy_knapsack as kp class _SCREAMING_SNAKE_CASE ( unittest.TestCase): def _snake_case ( self )-> Optional[Any]: lowerCamelCase_ =[10, 20, 30, 40, 50, 60] lowerCamelCase_ =[2, 4, 6, 8, 10, 12] lowerCamelCase_ =100 self.assertEqual(kp.calc_profit(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) , 210 ) def _snake_case ( self )-> Any: self.assertRaisesRegex(_SCREAMING_SNAKE_CASE , """max_weight must greater than zero.""" ) def _snake_case ( self )-> Dict: self.assertRaisesRegex(_SCREAMING_SNAKE_CASE , """Weight can not be negative.""" ) def _snake_case ( self )-> Dict: self.assertRaisesRegex(_SCREAMING_SNAKE_CASE , """Profit can not be negative.""" ) def _snake_case ( self )-> Tuple: self.assertRaisesRegex(_SCREAMING_SNAKE_CASE , """max_weight must greater than zero.""" ) def _snake_case ( self )-> Any: self.assertRaisesRegex( _SCREAMING_SNAKE_CASE , """The length of profit and weight must be same.""" ) if __name__ == "__main__": unittest.main()
49
1
def lowerCAmelCase_ ( __A, __A, __A ) -> int: '''simple docstring''' if len(__A ) != len(__A ): raise ValueError("The length of profit and weight must be same." ) if max_weight <= 0: raise ValueError("max_weight must greater than zero." ) if any(p < 0 for p in profit ): raise ValueError("Profit can not be negative." ) if any(w < 0 for w in weight ): raise ValueError("Weight can not be negative." ) # List created to store profit gained for the 1kg in case of each weight # respectively. Calculate and append profit/weight for each element. UpperCAmelCase__ = [p / w for p, w in zip(__A, __A )] # Creating a copy of the list and sorting profit/weight in ascending order UpperCAmelCase__ = sorted(__A ) # declaring useful variables UpperCAmelCase__ = len(__A ) UpperCAmelCase__ = 0 UpperCAmelCase__ = 0 UpperCAmelCase__ = 0 # loop till the total weight do not reach max limit e.g. 15 kg and till i<length while limit <= max_weight and i < length: # flag value for encountered greatest element in sorted_profit_by_weight UpperCAmelCase__ = sorted_profit_by_weight[length - i - 1] UpperCAmelCase__ = profit_by_weight.index(__A ) UpperCAmelCase__ = -1 # check if the weight encountered is less than the total weight # encountered before. if max_weight - limit >= weight[index]: limit += weight[index] # Adding profit gained for the given weight 1 === # weight[index]/weight[index] gain += 1 * profit[index] else: # Since the weight encountered is greater than limit, therefore take the # required number of remaining kgs and calculate profit for it. # weight remaining / weight[index] gain += (max_weight - limit) / weight[index] * profit[index] break i += 1 return gain if __name__ == "__main__": print( 'Input profits, weights, and then max_weight (all positive ints) separated by ' 'spaces.' ) UpperCamelCase__ = [int(x) for x in input('Input profits separated by spaces: ').split()] UpperCamelCase__ = [int(x) for x in input('Input weights separated by spaces: ').split()] UpperCamelCase__ = int(input('Max weight allowed: ')) # Function Call calc_profit(profit, weight, max_weight)
65
import math import random def lowerCAmelCase_ ( __A, __A = False ) -> float: '''simple docstring''' if deriv: return value * (1 - value) return 1 / (1 + math.exp(-value )) # Initial Value UpperCamelCase__ = 0.0_2 def lowerCAmelCase_ ( __A, __A ) -> float: '''simple docstring''' UpperCAmelCase__ = float(2 * (random.randint(1, 100 )) - 1 ) for _ in range(__A ): # Forward propagation UpperCAmelCase__ = sigmoid_function(INITIAL_VALUE * weight ) # How much did we miss? UpperCAmelCase__ = (expected / 100) - layer_a # Error delta UpperCAmelCase__ = layer_1_error * sigmoid_function(__A, __A ) # Update weight weight += INITIAL_VALUE * layer_1_delta return layer_a * 100 if __name__ == "__main__": import doctest doctest.testmod() UpperCamelCase__ = int(input('Expected value: ')) UpperCamelCase__ = int(input('Number of propagations: ')) print(forward_propagation(expected, number_propagations))
65
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) lowercase_ = {"configuration_reformer": ["REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "ReformerConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["ReformerTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["ReformerTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "ReformerAttention", "ReformerForMaskedLM", "ReformerForQuestionAnswering", "ReformerForSequenceClassification", "ReformerLayer", "ReformerModel", "ReformerModelWithLMHead", "ReformerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_reformer import REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, ReformerConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer import ReformerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer_fast import ReformerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_reformer import ( REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ReformerAttention, ReformerForMaskedLM, ReformerForQuestionAnswering, ReformerForSequenceClassification, ReformerLayer, ReformerModel, ReformerModelWithLMHead, ReformerPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
282
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
282
1
'''simple docstring''' def A__ ( UpperCAmelCase_=2_8_1_2_3 ): _UpperCamelCase : str = [1] * (limit + 1) for i in range(2 , int(limit**0.5 ) + 1 ): sum_divs[i * i] += i for k in range(i + 1 , limit // i + 1 ): sum_divs[k * i] += k + i _UpperCamelCase : str = set() _UpperCamelCase : List[Any] = 0 for n in range(1 , limit + 1 ): if sum_divs[n] > n: abundants.add(UpperCAmelCase_ ) if not any((n - a in abundants) for a in abundants ): res += n return res if __name__ == "__main__": print(solution())
83
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available lowerCamelCase : str = { "configuration_nezha": ["NEZHA_PRETRAINED_CONFIG_ARCHIVE_MAP", "NezhaConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : List[str] = [ "NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST", "NezhaForNextSentencePrediction", "NezhaForMaskedLM", "NezhaForPreTraining", "NezhaForMultipleChoice", "NezhaForQuestionAnswering", "NezhaForSequenceClassification", "NezhaForTokenClassification", "NezhaModel", "NezhaPreTrainedModel", ] if TYPE_CHECKING: from .configuration_nezha import NEZHA_PRETRAINED_CONFIG_ARCHIVE_MAP, NezhaConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_nezha import ( NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST, NezhaForMaskedLM, NezhaForMultipleChoice, NezhaForNextSentencePrediction, NezhaForPreTraining, NezhaForQuestionAnswering, NezhaForSequenceClassification, NezhaForTokenClassification, NezhaModel, NezhaPreTrainedModel, ) else: import sys lowerCamelCase : str = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
204
0
import unittest import numpy as np import torch from diffusers import DDIMPipeline, DDIMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow, torch_device from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class lowercase_ ( lowerCamelCase__ , unittest.TestCase ): '''simple docstring''' UpperCAmelCase : List[str] = DDIMPipeline UpperCAmelCase : Dict = UNCONDITIONAL_IMAGE_GENERATION_PARAMS UpperCAmelCase : str = PipelineTesterMixin.required_optional_params - { '''num_images_per_prompt''', '''latents''', '''callback''', '''callback_steps''', } UpperCAmelCase : Tuple = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS UpperCAmelCase : str = False def lowerCAmelCase_ ( self : int ): torch.manual_seed(0 ) _A = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=('DownBlock2D', 'AttnDownBlock2D') , up_block_types=('AttnUpBlock2D', 'UpBlock2D') , ) _A = DDIMScheduler() _A = {'unet': unet, 'scheduler': scheduler} return components def lowerCAmelCase_ ( self : Dict , _UpperCAmelCase : int , _UpperCAmelCase : Any=0 ): if str(__snake_case ).startswith('mps' ): _A = torch.manual_seed(__snake_case ) else: _A = torch.Generator(device=__snake_case ).manual_seed(__snake_case ) _A = { 'batch_size': 1, 'generator': generator, 'num_inference_steps': 2, 'output_type': 'numpy', } return inputs def lowerCAmelCase_ ( self : Dict ): _A = 'cpu' _A = self.get_dummy_components() _A = self.pipeline_class(**__snake_case ) pipe.to(__snake_case ) pipe.set_progress_bar_config(disable=__snake_case ) _A = self.get_dummy_inputs(__snake_case ) _A = pipe(**__snake_case ).images _A = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 32, 32, 3) ) _A = np.array( [1.0_0_0E0_0, 5.7_1_7E-0_1, 4.7_1_7E-0_1, 1.0_0_0E0_0, 0.0_0_0E0_0, 1.0_0_0E0_0, 3.0_0_0E-0_4, 0.0_0_0E0_0, 9.0_0_0E-0_4] ) _A = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(__snake_case , 1E-3 ) def lowerCAmelCase_ ( self : str ): super().test_dict_tuple_outputs_equivalent(expected_max_difference=3E-3 ) def lowerCAmelCase_ ( self : str ): super().test_save_load_local(expected_max_difference=3E-3 ) def lowerCAmelCase_ ( self : Tuple ): super().test_save_load_optional_components(expected_max_difference=3E-3 ) def lowerCAmelCase_ ( self : Tuple ): super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class lowercase_ ( unittest.TestCase ): '''simple docstring''' def lowerCAmelCase_ ( self : Optional[int] ): _A = 'google/ddpm-cifar10-32' _A = UNetaDModel.from_pretrained(__snake_case ) _A = DDIMScheduler() _A = DDIMPipeline(unet=__snake_case , scheduler=__snake_case ) ddim.to(__snake_case ) ddim.set_progress_bar_config(disable=__snake_case ) _A = torch.manual_seed(0 ) _A = ddim(generator=__snake_case , eta=0.0 , output_type='numpy' ).images _A = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) _A = np.array([0.1723, 0.1617, 0.1600, 0.1626, 0.1497, 0.1513, 0.1505, 0.1442, 0.1453] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def lowerCAmelCase_ ( self : Union[str, Any] ): _A = 'google/ddpm-ema-bedroom-256' _A = UNetaDModel.from_pretrained(__snake_case ) _A = DDIMScheduler.from_pretrained(__snake_case ) _A = DDIMPipeline(unet=__snake_case , scheduler=__snake_case ) ddpm.to(__snake_case ) ddpm.set_progress_bar_config(disable=__snake_case ) _A = torch.manual_seed(0 ) _A = ddpm(generator=__snake_case , output_type='numpy' ).images _A = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) _A = np.array([0.0060, 0.0201, 0.0344, 0.0024, 0.0018, 0.0002, 0.0022, 0.0000, 0.0069] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
358
"""simple docstring""" from dataclasses import dataclass from typing import Dict, Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, apply_forward_hook from .attention_processor import AttentionProcessor, AttnProcessor from .modeling_utils import ModelMixin from .vae import Decoder, DecoderOutput, DiagonalGaussianDistribution, Encoder @dataclass class lowercase_ ( __lowerCAmelCase ): '''simple docstring''' UpperCAmelCase : "DiagonalGaussianDistribution" class lowercase_ ( __lowerCAmelCase , __lowerCAmelCase ): '''simple docstring''' UpperCAmelCase : List[Any] = True @register_to_config def __init__( self : List[str] , _UpperCAmelCase : int = 3 , _UpperCAmelCase : int = 3 , _UpperCAmelCase : Tuple[str] = ("DownEncoderBlock2D",) , _UpperCAmelCase : Tuple[str] = ("UpDecoderBlock2D",) , _UpperCAmelCase : Tuple[int] = (64,) , _UpperCAmelCase : int = 1 , _UpperCAmelCase : str = "silu" , _UpperCAmelCase : int = 4 , _UpperCAmelCase : int = 32 , _UpperCAmelCase : int = 32 , _UpperCAmelCase : float = 0.1_8215 , ): super().__init__() # pass init params to Encoder _A = Encoder( in_channels=_UpperCAmelCase , out_channels=_UpperCAmelCase , down_block_types=_UpperCAmelCase , block_out_channels=_UpperCAmelCase , layers_per_block=_UpperCAmelCase , act_fn=_UpperCAmelCase , norm_num_groups=_UpperCAmelCase , double_z=_UpperCAmelCase , ) # pass init params to Decoder _A = Decoder( in_channels=_UpperCAmelCase , out_channels=_UpperCAmelCase , up_block_types=_UpperCAmelCase , block_out_channels=_UpperCAmelCase , layers_per_block=_UpperCAmelCase , norm_num_groups=_UpperCAmelCase , act_fn=_UpperCAmelCase , ) _A = nn.Convad(2 * latent_channels , 2 * latent_channels , 1 ) _A = nn.Convad(_UpperCAmelCase , _UpperCAmelCase , 1 ) _A = False _A = False # only relevant if vae tiling is enabled _A = self.config.sample_size _A = ( self.config.sample_size[0] if isinstance(self.config.sample_size , (list, tuple) ) else self.config.sample_size ) _A = int(sample_size / (2 ** (len(self.config.block_out_channels ) - 1)) ) _A = 0.25 def lowerCAmelCase_ ( self : Union[str, Any] , _UpperCAmelCase : int , _UpperCAmelCase : Tuple=False ): if isinstance(_UpperCAmelCase , (Encoder, Decoder) ): _A = value def lowerCAmelCase_ ( self : List[str] , _UpperCAmelCase : bool = True ): _A = use_tiling def lowerCAmelCase_ ( self : Union[str, Any] ): self.enable_tiling(_UpperCAmelCase ) def lowerCAmelCase_ ( self : Dict ): _A = True def lowerCAmelCase_ ( self : str ): _A = False @property # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors def lowerCAmelCase_ ( self : str ): _A = {} def fn_recursive_add_processors(_UpperCAmelCase : str , _UpperCAmelCase : torch.nn.Module , _UpperCAmelCase : Dict[str, AttentionProcessor] ): if hasattr(_UpperCAmelCase , 'set_processor' ): _A = module.processor for sub_name, child in module.named_children(): fn_recursive_add_processors(F'''{name}.{sub_name}''' , _UpperCAmelCase , _UpperCAmelCase ) return processors for name, module in self.named_children(): fn_recursive_add_processors(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) return processors def lowerCAmelCase_ ( self : str , _UpperCAmelCase : Union[AttentionProcessor, Dict[str, AttentionProcessor]] ): _A = len(self.attn_processors.keys() ) if isinstance(_UpperCAmelCase , _UpperCAmelCase ) and len(_UpperCAmelCase ) != count: raise ValueError( F'''A dict of processors was passed, but the number of processors {len(_UpperCAmelCase )} does not match the''' F''' number of attention layers: {count}. Please make sure to pass {count} processor classes.''' ) def fn_recursive_attn_processor(_UpperCAmelCase : str , _UpperCAmelCase : torch.nn.Module , _UpperCAmelCase : int ): if hasattr(_UpperCAmelCase , 'set_processor' ): if not isinstance(_UpperCAmelCase , _UpperCAmelCase ): module.set_processor(_UpperCAmelCase ) else: module.set_processor(processor.pop(F'''{name}.processor''' ) ) for sub_name, child in module.named_children(): fn_recursive_attn_processor(F'''{name}.{sub_name}''' , _UpperCAmelCase , _UpperCAmelCase ) for name, module in self.named_children(): fn_recursive_attn_processor(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) def lowerCAmelCase_ ( self : List[str] ): self.set_attn_processor(AttnProcessor() ) @apply_forward_hook def lowerCAmelCase_ ( self : int , _UpperCAmelCase : torch.FloatTensor , _UpperCAmelCase : bool = True ): if self.use_tiling and (x.shape[-1] > self.tile_sample_min_size or x.shape[-2] > self.tile_sample_min_size): return self.tiled_encode(_UpperCAmelCase , return_dict=_UpperCAmelCase ) if self.use_slicing and x.shape[0] > 1: _A = [self.encoder(_UpperCAmelCase ) for x_slice in x.split(1 )] _A = torch.cat(_UpperCAmelCase ) else: _A = self.encoder(_UpperCAmelCase ) _A = self.quant_conv(_UpperCAmelCase ) _A = DiagonalGaussianDistribution(_UpperCAmelCase ) if not return_dict: return (posterior,) return AutoencoderKLOutput(latent_dist=_UpperCAmelCase ) def lowerCAmelCase_ ( self : Any , _UpperCAmelCase : torch.FloatTensor , _UpperCAmelCase : bool = True ): if self.use_tiling and (z.shape[-1] > self.tile_latent_min_size or z.shape[-2] > self.tile_latent_min_size): return self.tiled_decode(_UpperCAmelCase , return_dict=_UpperCAmelCase ) _A = self.post_quant_conv(_UpperCAmelCase ) _A = self.decoder(_UpperCAmelCase ) if not return_dict: return (dec,) return DecoderOutput(sample=_UpperCAmelCase ) @apply_forward_hook def lowerCAmelCase_ ( self : str , _UpperCAmelCase : torch.FloatTensor , _UpperCAmelCase : bool = True ): if self.use_slicing and z.shape[0] > 1: _A = [self._decode(_UpperCAmelCase ).sample for z_slice in z.split(1 )] _A = torch.cat(_UpperCAmelCase ) else: _A = self._decode(_UpperCAmelCase ).sample if not return_dict: return (decoded,) return DecoderOutput(sample=_UpperCAmelCase ) def lowerCAmelCase_ ( self : str , _UpperCAmelCase : int , _UpperCAmelCase : Dict , _UpperCAmelCase : Any ): _A = min(a.shape[2] , b.shape[2] , _UpperCAmelCase ) for y in range(_UpperCAmelCase ): _A = a[:, :, -blend_extent + y, :] * (1 - y / blend_extent) + b[:, :, y, :] * (y / blend_extent) return b def lowerCAmelCase_ ( self : Optional[Any] , _UpperCAmelCase : List[str] , _UpperCAmelCase : List[Any] , _UpperCAmelCase : List[Any] ): _A = min(a.shape[3] , b.shape[3] , _UpperCAmelCase ) for x in range(_UpperCAmelCase ): _A = a[:, :, :, -blend_extent + x] * (1 - x / blend_extent) + b[:, :, :, x] * (x / blend_extent) return b def lowerCAmelCase_ ( self : str , _UpperCAmelCase : torch.FloatTensor , _UpperCAmelCase : bool = True ): _A = int(self.tile_sample_min_size * (1 - self.tile_overlap_factor) ) _A = int(self.tile_latent_min_size * self.tile_overlap_factor ) _A = self.tile_latent_min_size - blend_extent # Split the image into 512x512 tiles and encode them separately. _A = [] for i in range(0 , x.shape[2] , _UpperCAmelCase ): _A = [] for j in range(0 , x.shape[3] , _UpperCAmelCase ): _A = x[:, :, i : i + self.tile_sample_min_size, j : j + self.tile_sample_min_size] _A = self.encoder(_UpperCAmelCase ) _A = self.quant_conv(_UpperCAmelCase ) row.append(_UpperCAmelCase ) rows.append(_UpperCAmelCase ) _A = [] for i, row in enumerate(_UpperCAmelCase ): _A = [] for j, tile in enumerate(_UpperCAmelCase ): # blend the above tile and the left tile # to the current tile and add the current tile to the result row if i > 0: _A = self.blend_v(rows[i - 1][j] , _UpperCAmelCase , _UpperCAmelCase ) if j > 0: _A = self.blend_h(row[j - 1] , _UpperCAmelCase , _UpperCAmelCase ) result_row.append(tile[:, :, :row_limit, :row_limit] ) result_rows.append(torch.cat(_UpperCAmelCase , dim=3 ) ) _A = torch.cat(_UpperCAmelCase , dim=2 ) _A = DiagonalGaussianDistribution(_UpperCAmelCase ) if not return_dict: return (posterior,) return AutoencoderKLOutput(latent_dist=_UpperCAmelCase ) def lowerCAmelCase_ ( self : Tuple , _UpperCAmelCase : torch.FloatTensor , _UpperCAmelCase : bool = True ): _A = int(self.tile_latent_min_size * (1 - self.tile_overlap_factor) ) _A = int(self.tile_sample_min_size * self.tile_overlap_factor ) _A = self.tile_sample_min_size - blend_extent # Split z into overlapping 64x64 tiles and decode them separately. # The tiles have an overlap to avoid seams between tiles. _A = [] for i in range(0 , z.shape[2] , _UpperCAmelCase ): _A = [] for j in range(0 , z.shape[3] , _UpperCAmelCase ): _A = z[:, :, i : i + self.tile_latent_min_size, j : j + self.tile_latent_min_size] _A = self.post_quant_conv(_UpperCAmelCase ) _A = self.decoder(_UpperCAmelCase ) row.append(_UpperCAmelCase ) rows.append(_UpperCAmelCase ) _A = [] for i, row in enumerate(_UpperCAmelCase ): _A = [] for j, tile in enumerate(_UpperCAmelCase ): # blend the above tile and the left tile # to the current tile and add the current tile to the result row if i > 0: _A = self.blend_v(rows[i - 1][j] , _UpperCAmelCase , _UpperCAmelCase ) if j > 0: _A = self.blend_h(row[j - 1] , _UpperCAmelCase , _UpperCAmelCase ) result_row.append(tile[:, :, :row_limit, :row_limit] ) result_rows.append(torch.cat(_UpperCAmelCase , dim=3 ) ) _A = torch.cat(_UpperCAmelCase , dim=2 ) if not return_dict: return (dec,) return DecoderOutput(sample=_UpperCAmelCase ) def lowerCAmelCase_ ( self : List[str] , _UpperCAmelCase : torch.FloatTensor , _UpperCAmelCase : bool = False , _UpperCAmelCase : bool = True , _UpperCAmelCase : Optional[torch.Generator] = None , ): _A = sample _A = self.encode(_UpperCAmelCase ).latent_dist if sample_posterior: _A = posterior.sample(generator=_UpperCAmelCase ) else: _A = posterior.mode() _A = self.decode(_UpperCAmelCase ).sample if not return_dict: return (dec,) return DecoderOutput(sample=_UpperCAmelCase )
271
0
"""simple docstring""" from sklearn.metrics import recall_score import datasets __A = """ Recall is the fraction of the positive examples that were correctly labeled by the model as positive. It can be computed with the equation: Recall = TP / (TP + FN) Where TP is the true positives and FN is the false negatives. """ __A = """ Args: - **predictions** (`list` of `int`): The predicted labels. - **references** (`list` of `int`): The ground truth labels. - **labels** (`list` of `int`): The set of labels to include when `average` is not set to `binary`, and their order when average is `None`. Labels present in the data can be excluded in this input, for example to calculate a multiclass average ignoring a majority negative class, while labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in y_true and y_pred are used in sorted order. Defaults to None. - **pos_label** (`int`): The class label to use as the 'positive class' when calculating the recall. Defaults to `1`. - **average** (`string`): This parameter is required for multiclass/multilabel targets. If None, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `'binary'`. - `'binary'`: Only report results for the class specified by `pos_label`. This is applicable only if the target labels and predictions are binary. - `'micro'`: Calculate metrics globally by counting the total true positives, false negatives, and false positives. - `'macro'`: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account. - `'weighted'`: Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `'macro'` to account for label imbalance. Note that it can result in an F-score that is not between precision and recall. - `'samples'`: Calculate metrics for each instance, and find their average (only meaningful for multilabel classification). - **sample_weight** (`list` of `float`): Sample weights Defaults to `None`. - **zero_division** (): Sets the value to return when there is a zero division. Defaults to . - `'warn'`: If there is a zero division, the return value is `0`, but warnings are also raised. - `0`: If there is a zero division, the return value is `0`. - `1`: If there is a zero division, the return value is `1`. Returns: - **recall** (`float`, or `array` of `float`): Either the general recall score, or the recall scores for individual classes, depending on the values input to `labels` and `average`. Minimum possible value is 0. Maximum possible value is 1. A higher recall means that more of the positive examples have been labeled correctly. Therefore, a higher recall is generally considered better. Examples: Example 1-A simple example with some errors >>> recall_metric = datasets.load_metric('recall') >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1]) >>> print(results) {'recall': 0.6666666666666666} Example 2-The same example as Example 1, but with `pos_label=0` instead of the default `pos_label=1`. >>> recall_metric = datasets.load_metric('recall') >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], pos_label=0) >>> print(results) {'recall': 0.5} Example 3-The same example as Example 1, but with `sample_weight` included. >>> recall_metric = datasets.load_metric('recall') >>> sample_weight = [0.9, 0.2, 0.9, 0.3, 0.8] >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], sample_weight=sample_weight) >>> print(results) {'recall': 0.55} Example 4-A multiclass example, using different averages. >>> recall_metric = datasets.load_metric('recall') >>> predictions = [0, 2, 1, 0, 0, 1] >>> references = [0, 1, 2, 0, 1, 2] >>> results = recall_metric.compute(predictions=predictions, references=references, average='macro') >>> print(results) {'recall': 0.3333333333333333} >>> results = recall_metric.compute(predictions=predictions, references=references, average='micro') >>> print(results) {'recall': 0.3333333333333333} >>> results = recall_metric.compute(predictions=predictions, references=references, average='weighted') >>> print(results) {'recall': 0.3333333333333333} >>> results = recall_metric.compute(predictions=predictions, references=references, average=None) >>> print(results) {'recall': array([1., 0., 0.])} """ __A = """ @article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011} """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _lowerCAmelCase ( datasets.Metric ): """simple docstring""" def snake_case ( self ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Sequence(datasets.Value('int32' ) ), 'references': datasets.Sequence(datasets.Value('int32' ) ), } if self.config_name == 'multilabel' else { 'predictions': datasets.Value('int32' ), 'references': datasets.Value('int32' ), } ) , reference_urls=['https://scikit-learn.org/stable/modules/generated/sklearn.metrics.recall_score.html'] , ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase=None , __UpperCAmelCase=1 , __UpperCAmelCase="binary" , __UpperCAmelCase=None , __UpperCAmelCase="warn" , ): '''simple docstring''' lowerCAmelCase__ :List[Any] = recall_score( __UpperCAmelCase , __UpperCAmelCase , labels=__UpperCAmelCase , pos_label=__UpperCAmelCase , average=__UpperCAmelCase , sample_weight=__UpperCAmelCase , zero_division=__UpperCAmelCase , ) return {"recall": float(__UpperCAmelCase ) if score.size == 1 else score}
293
"""simple docstring""" import tempfile import unittest from transformers import AutoModelForSeqaSeqLM, AutoTokenizer from transformers.testing_utils import ( is_torch_available, require_optimum, require_torch, slow, ) if is_torch_available(): import torch @require_torch @require_optimum @slow class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = 'hf-internal-testing/tiny-random-t5' lowerCAmelCase__ :List[Any] = AutoTokenizer.from_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :str = AutoModelForSeqaSeqLM.from_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :Any = tokenizer('This is me' , return_tensors='pt' ) lowerCAmelCase__ :Dict = model.to_bettertransformer() self.assertTrue(any('BetterTransformer' in mod.__class__.__name__ for _, mod in model.named_modules() ) ) lowerCAmelCase__ :Optional[Any] = model.generate(**__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = model.reverse_bettertransformer() self.assertFalse(any('BetterTransformer' in mod.__class__.__name__ for _, mod in model.named_modules() ) ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :Any = AutoModelForSeqaSeqLM.from_pretrained(__UpperCAmelCase ) self.assertFalse( any('BetterTransformer' in mod.__class__.__name__ for _, mod in model_reloaded.named_modules() ) ) lowerCAmelCase__ :Union[str, Any] = model_reloaded.generate(**__UpperCAmelCase ) self.assertTrue(torch.allclose(__UpperCAmelCase , __UpperCAmelCase ) ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :int = 'hf-internal-testing/tiny-random-t5' lowerCAmelCase__ :Union[str, Any] = AutoModelForSeqaSeqLM.from_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :str = model.to_bettertransformer() with tempfile.TemporaryDirectory() as tmpdirname: with self.assertRaises(__UpperCAmelCase ): model.save_pretrained(__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = model.reverse_bettertransformer() model.save_pretrained(__UpperCAmelCase )
293
1
from typing import Optional import pyspark from .. import Features, NamedSplit from ..download import DownloadMode from ..packaged_modules.spark.spark import Spark from .abc import AbstractDatasetReader class lowerCAmelCase ( __lowercase ): def __init__( self : Union[str, Any] , UpperCAmelCase : Union[str, Any] , UpperCAmelCase : Optional[int] = None , UpperCAmelCase : Union[str, Any] = None , UpperCAmelCase : Tuple = True , UpperCAmelCase : int = None , UpperCAmelCase : List[str] = False , UpperCAmelCase : Optional[int] = None , UpperCAmelCase : Dict = True , UpperCAmelCase : Optional[int] = "arrow" , **UpperCAmelCase : List[str] , ) -> Union[str, Any]: super().__init__( split=_a , features=_a , cache_dir=_a , keep_in_memory=_a , streaming=_a , **_a , ) lowerCamelCase__ : Optional[int] = load_from_cache_file lowerCamelCase__ : List[Any] = file_format lowerCamelCase__ : Optional[int] = Spark( df=_a , features=_a , cache_dir=_a , working_dir=_a , **_a , ) def A_ ( self : List[str] ) -> Optional[Any]: if self.streaming: return self.builder.as_streaming_dataset(split=self.split ) lowerCamelCase__ : Union[str, Any] = None if self._load_from_cache_file else DownloadMode.FORCE_REDOWNLOAD self.builder.download_and_prepare( download_mode=_a , file_format=self._file_format , ) return self.builder.as_dataset(split=self.split )
365
from collections import deque class lowerCAmelCase : def __init__( self : str , UpperCAmelCase : str , UpperCAmelCase : int , UpperCAmelCase : int ) -> None: lowerCamelCase__ : Optional[int] = process_name # process name lowerCamelCase__ : Optional[int] = arrival_time # arrival time of the process # completion time of finished process or last interrupted time lowerCamelCase__ : str = arrival_time lowerCamelCase__ : List[Any] = burst_time # remaining burst time lowerCamelCase__ : Any = 0 # total time of the process wait in ready queue lowerCamelCase__ : Tuple = 0 # time from arrival time to completion time class lowerCAmelCase : def __init__( self : List[str] , UpperCAmelCase : int , UpperCAmelCase : list[int] , UpperCAmelCase : deque[Process] , UpperCAmelCase : int , ) -> None: # total number of mlfq's queues lowerCamelCase__ : Optional[int] = number_of_queues # time slice of queues that round robin algorithm applied lowerCamelCase__ : List[str] = time_slices # unfinished process is in this ready_queue lowerCamelCase__ : List[str] = queue # current time lowerCamelCase__ : Optional[Any] = current_time # finished process is in this sequence queue lowerCamelCase__ : deque[Process] = deque() def A_ ( self : Tuple ) -> list[str]: lowerCamelCase__ : Union[str, Any] = [] for i in range(len(self.finish_queue ) ): sequence.append(self.finish_queue[i].process_name ) return sequence def A_ ( self : Tuple , UpperCAmelCase : list[Process] ) -> list[int]: lowerCamelCase__ : Tuple = [] for i in range(len(UpperCAmelCase ) ): waiting_times.append(queue[i].waiting_time ) return waiting_times def A_ ( self : Union[str, Any] , UpperCAmelCase : list[Process] ) -> list[int]: lowerCamelCase__ : int = [] for i in range(len(UpperCAmelCase ) ): turnaround_times.append(queue[i].turnaround_time ) return turnaround_times def A_ ( self : Optional[int] , UpperCAmelCase : list[Process] ) -> list[int]: lowerCamelCase__ : Tuple = [] for i in range(len(UpperCAmelCase ) ): completion_times.append(queue[i].stop_time ) return completion_times def A_ ( self : str , UpperCAmelCase : deque[Process] ) -> list[int]: return [q.burst_time for q in queue] def A_ ( self : int , UpperCAmelCase : Process ) -> int: process.waiting_time += self.current_time - process.stop_time return process.waiting_time def A_ ( self : Optional[int] , UpperCAmelCase : deque[Process] ) -> deque[Process]: lowerCamelCase__ : deque[Process] = deque() # sequence deque of finished process while len(UpperCAmelCase ) != 0: lowerCamelCase__ : List[Any] = ready_queue.popleft() # current process # if process's arrival time is later than current time, update current time if self.current_time < cp.arrival_time: self.current_time += cp.arrival_time # update waiting time of current process self.update_waiting_time(UpperCAmelCase ) # update current time self.current_time += cp.burst_time # finish the process and set the process's burst-time 0 lowerCamelCase__ : Optional[int] = 0 # set the process's turnaround time because it is finished lowerCamelCase__ : Union[str, Any] = self.current_time - cp.arrival_time # set the completion time lowerCamelCase__ : Any = self.current_time # add the process to queue that has finished queue finished.append(UpperCAmelCase ) self.finish_queue.extend(UpperCAmelCase ) # add finished process to finish queue # FCFS will finish all remaining processes return finished def A_ ( self : str , UpperCAmelCase : deque[Process] , UpperCAmelCase : int ) -> tuple[deque[Process], deque[Process]]: lowerCamelCase__ : deque[Process] = deque() # sequence deque of terminated process # just for 1 cycle and unfinished processes will go back to queue for _ in range(len(UpperCAmelCase ) ): lowerCamelCase__ : Dict = ready_queue.popleft() # current process # if process's arrival time is later than current time, update current time if self.current_time < cp.arrival_time: self.current_time += cp.arrival_time # update waiting time of unfinished processes self.update_waiting_time(UpperCAmelCase ) # if the burst time of process is bigger than time-slice if cp.burst_time > time_slice: # use CPU for only time-slice self.current_time += time_slice # update remaining burst time cp.burst_time -= time_slice # update end point time lowerCamelCase__ : List[str] = self.current_time # locate the process behind the queue because it is not finished ready_queue.append(UpperCAmelCase ) else: # use CPU for remaining burst time self.current_time += cp.burst_time # set burst time 0 because the process is finished lowerCamelCase__ : Any = 0 # set the finish time lowerCamelCase__ : int = self.current_time # update the process' turnaround time because it is finished lowerCamelCase__ : Dict = self.current_time - cp.arrival_time # add the process to queue that has finished queue finished.append(UpperCAmelCase ) self.finish_queue.extend(UpperCAmelCase ) # add finished process to finish queue # return finished processes queue and remaining processes queue return finished, ready_queue def A_ ( self : Dict ) -> deque[Process]: # all queues except last one have round_robin algorithm for i in range(self.number_of_queues - 1 ): lowerCamelCase__ , lowerCamelCase__ : Any = self.round_robin( self.ready_queue , self.time_slices[i] ) # the last queue has first_come_first_served algorithm self.first_come_first_served(self.ready_queue ) return self.finish_queue if __name__ == "__main__": import doctest _UpperCAmelCase : List[str] = Process("""P1""", 0, 53) _UpperCAmelCase : Union[str, Any] = Process("""P2""", 0, 17) _UpperCAmelCase : int = Process("""P3""", 0, 68) _UpperCAmelCase : str = Process("""P4""", 0, 24) _UpperCAmelCase : Optional[int] = 3 _UpperCAmelCase : Optional[Any] = [17, 25] _UpperCAmelCase : Optional[int] = deque([Pa, Pa, Pa, Pa]) if len(time_slices) != number_of_queues - 1: raise SystemExit(0) doctest.testmod(extraglobs={"""queue""": deque([Pa, Pa, Pa, Pa])}) _UpperCAmelCase : Tuple = Process("""P1""", 0, 53) _UpperCAmelCase : Any = Process("""P2""", 0, 17) _UpperCAmelCase : Any = Process("""P3""", 0, 68) _UpperCAmelCase : List[Any] = Process("""P4""", 0, 24) _UpperCAmelCase : List[str] = 3 _UpperCAmelCase : Optional[int] = [17, 25] _UpperCAmelCase : Optional[int] = deque([Pa, Pa, Pa, Pa]) _UpperCAmelCase : Union[str, Any] = MLFQ(number_of_queues, time_slices, queue, 0) _UpperCAmelCase : Dict = mlfq.multi_level_feedback_queue() # print total waiting times of processes(P1, P2, P3, P4) print( F"""waiting time:\ \t\t\t{MLFQ.calculate_waiting_time(mlfq, [Pa, Pa, Pa, Pa])}""" ) # print completion times of processes(P1, P2, P3, P4) print( F"""completion time:\ \t\t{MLFQ.calculate_completion_time(mlfq, [Pa, Pa, Pa, Pa])}""" ) # print total turnaround times of processes(P1, P2, P3, P4) print( F"""turnaround time:\ \t\t{MLFQ.calculate_turnaround_time(mlfq, [Pa, Pa, Pa, Pa])}""" ) # print sequence of finished processes print( F"""sequence of finished processes:\ {mlfq.calculate_sequence_of_finish_queue()}""" )
45
0
from sklearn.metrics import fa_score, matthews_corrcoef import datasets from .record_evaluation import evaluate as evaluate_record __snake_case = "\\n@article{wang2019superglue,\n title={SuperGLUE: A Stickier Benchmark for General-Purpose Language Understanding Systems},\n author={Wang, Alex and Pruksachatkun, Yada and Nangia, Nikita and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R},\n journal={arXiv preprint arXiv:1905.00537},\n year={2019}\n}\n" __snake_case = "\\nSuperGLUE (https://super.gluebenchmark.com/) is a new benchmark styled after\nGLUE with a new set of more difficult language understanding tasks, improved\nresources, and a new public leaderboard.\n" __snake_case = "\nCompute SuperGLUE evaluation metric associated to each SuperGLUE dataset.\nArgs:\n predictions: list of predictions to score. Depending on the SuperGlUE subset:\n - for 'record': list of question-answer dictionaries with the following keys:\n - 'idx': index of the question as specified by the dataset\n - 'prediction_text': the predicted answer text\n - for 'multirc': list of question-answer dictionaries with the following keys:\n - 'idx': index of the question-answer pair as specified by the dataset\n - 'prediction': the predicted answer label\n - otherwise: list of predicted labels\n references: list of reference labels. Depending on the SuperGLUE subset:\n - for 'record': list of question-answers dictionaries with the following keys:\n - 'idx': index of the question as specified by the dataset\n - 'answers': list of possible answers\n - otherwise: list of reference labels\nReturns: depending on the SuperGLUE subset:\n - for 'record':\n - 'exact_match': Exact match between answer and gold answer\n - 'f1': F1 score\n - for 'multirc':\n - 'exact_match': Exact match between answer and gold answer\n - 'f1_m': Per-question macro-F1 score\n - 'f1_a': Average F1 score over all answers\n - for 'axb':\n 'matthews_correlation': Matthew Correlation\n - for 'cb':\n - 'accuracy': Accuracy\n - 'f1': F1 score\n - for all others:\n - 'accuracy': Accuracy\nExamples:\n\n >>> super_glue_metric = datasets.load_metric('super_glue', 'copa') # any of [\"copa\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"boolq\", \"axg\"]\n >>> predictions = [0, 1]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'accuracy': 1.0}\n\n >>> super_glue_metric = datasets.load_metric('super_glue', 'cb')\n >>> predictions = [0, 1]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'accuracy': 1.0, 'f1': 1.0}\n\n >>> super_glue_metric = datasets.load_metric('super_glue', 'record')\n >>> predictions = [{'idx': {'passage': 0, 'query': 0}, 'prediction_text': 'answer'}]\n >>> references = [{'idx': {'passage': 0, 'query': 0}, 'answers': ['answer', 'another_answer']}]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'exact_match': 1.0, 'f1': 1.0}\n\n >>> super_glue_metric = datasets.load_metric('super_glue', 'multirc')\n >>> predictions = [{'idx': {'answer': 0, 'paragraph': 0, 'question': 0}, 'prediction': 0}, {'idx': {'answer': 1, 'paragraph': 2, 'question': 3}, 'prediction': 1}]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'exact_match': 1.0, 'f1_m': 1.0, 'f1_a': 1.0}\n\n >>> super_glue_metric = datasets.load_metric('super_glue', 'axb')\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'matthews_correlation': 1.0}\n" def lowerCAmelCase_ ( __lowerCAmelCase , __lowerCAmelCase )-> int: '''simple docstring''' return float((preds == labels).mean() ) def lowerCAmelCase_ ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase="binary" )-> int: '''simple docstring''' UpperCAmelCase : Union[str, Any] =simple_accuracy(__lowerCAmelCase , __lowerCAmelCase ) UpperCAmelCase : int =float(fa_score(y_true=__lowerCAmelCase , y_pred=__lowerCAmelCase , average=__lowerCAmelCase ) ) return { "accuracy": acc, "f1": fa, } def lowerCAmelCase_ ( __lowerCAmelCase , __lowerCAmelCase )-> List[str]: '''simple docstring''' UpperCAmelCase : str ={} for id_pred, label in zip(__lowerCAmelCase , __lowerCAmelCase ): UpperCAmelCase : Any =f'''{id_pred['idx']['paragraph']}-{id_pred['idx']['question']}''' UpperCAmelCase : str =id_pred['''prediction'''] if question_id in question_map: question_map[question_id].append((pred, label) ) else: UpperCAmelCase : Dict =[(pred, label)] UpperCAmelCase : Union[str, Any] =[], [] for question, preds_labels in question_map.items(): UpperCAmelCase : Optional[int] =zip(*__lowerCAmelCase ) UpperCAmelCase : Dict =fa_score(y_true=__lowerCAmelCase , y_pred=__lowerCAmelCase , average='''macro''' ) fas.append(__lowerCAmelCase ) UpperCAmelCase : str =int(sum(pred == label for pred, label in preds_labels ) == len(__lowerCAmelCase ) ) ems.append(__lowerCAmelCase ) UpperCAmelCase : str =float(sum(__lowerCAmelCase ) / len(__lowerCAmelCase ) ) UpperCAmelCase : List[Any] =sum(__lowerCAmelCase ) / len(__lowerCAmelCase ) UpperCAmelCase : str =float(fa_score(y_true=__lowerCAmelCase , y_pred=[id_pred['''prediction'''] for id_pred in ids_preds] ) ) return {"exact_match": em, "f1_m": fa_m, "f1_a": fa_a} @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __snake_case ( datasets.Metric ): def UpperCAmelCase__ ( self ) -> Dict: '''simple docstring''' if self.config_name not in [ "boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg", ]: raise KeyError( '''You should supply a configuration name selected in ''' '''["boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg",]''' ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , codebase_urls=[] , reference_urls=[] , format='''numpy''' if not self.config_name == '''record''' and not self.config_name == '''multirc''' else None , ) def UpperCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' if self.config_name == "record": return { "predictions": { "idx": { "passage": datasets.Value('''int64''' ), "query": datasets.Value('''int64''' ), }, "prediction_text": datasets.Value('''string''' ), }, "references": { "idx": { "passage": datasets.Value('''int64''' ), "query": datasets.Value('''int64''' ), }, "answers": datasets.Sequence(datasets.Value('''string''' ) ), }, } elif self.config_name == "multirc": return { "predictions": { "idx": { "answer": datasets.Value('''int64''' ), "paragraph": datasets.Value('''int64''' ), "question": datasets.Value('''int64''' ), }, "prediction": datasets.Value('''int64''' ), }, "references": datasets.Value('''int64''' ), } else: return { "predictions": datasets.Value('''int64''' ), "references": datasets.Value('''int64''' ), } def UpperCAmelCase__ ( self , snake_case__ , snake_case__ ) -> Optional[Any]: '''simple docstring''' if self.config_name == "axb": return {"matthews_correlation": matthews_corrcoef(_snake_case , _snake_case )} elif self.config_name == "cb": return acc_and_fa(_snake_case , _snake_case , fa_avg='''macro''' ) elif self.config_name == "record": UpperCAmelCase : Dict =[ { '''qas''': [ {'''id''': ref['''idx''']['''query'''], '''answers''': [{'''text''': ans} for ans in ref['''answers''']]} for ref in references ] } ] UpperCAmelCase : Tuple ={pred['''idx''']['''query''']: pred['''prediction_text'''] for pred in predictions} return evaluate_record(_snake_case , _snake_case )[0] elif self.config_name == "multirc": return evaluate_multirc(_snake_case , _snake_case ) elif self.config_name in ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]: return {"accuracy": simple_accuracy(_snake_case , _snake_case )} else: raise KeyError( '''You should supply a configuration name selected in ''' '''["boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg",]''' )
348
from ..utils import DummyObject, requires_backends class __lowerCAmelCase ( metaclass=lowerCAmelCase_ ): """simple docstring""" A__ : Tuple = ['''speech'''] def __init__( self : List[Any] , *_snake_case : str , **_snake_case : List[Any] ): requires_backends(self , ['''speech'''] ) class __lowerCAmelCase ( metaclass=lowerCAmelCase_ ): """simple docstring""" A__ : List[Any] = ['''speech'''] def __init__( self : List[str] , *_snake_case : List[Any] , **_snake_case : Dict ): requires_backends(self , ['''speech'''] )
156
0
from __future__ import annotations import csv import requests from bsa import BeautifulSoup def _lowerCamelCase( lowercase__ = "" ) -> Union[str, Any]: '''simple docstring''' __lowercase= url or 'https://www.imdb.com/chart/top/?ref_=nv_mv_250' __lowercase= BeautifulSoup(requests.get(__UpperCamelCase ).text , 'html.parser' ) __lowercase= soup.find_all('td' , attrs='titleColumn' ) __lowercase= soup.find_all('td' , class_='ratingColumn imdbRating' ) return { title.a.text: float(rating.strong.text ) for title, rating in zip(__UpperCamelCase , __UpperCamelCase ) } def _lowerCamelCase( lowercase__ = "IMDb_Top_250_Movies.csv" ) -> Optional[Any]: '''simple docstring''' __lowercase= get_imdb_top_aaa_movies() with open(__UpperCamelCase , 'w' , newline='' ) as out_file: __lowercase= csv.writer(__UpperCamelCase ) writer.writerow(['Movie title', 'IMDb rating'] ) for title, rating in movies.items(): writer.writerow([title, rating] ) if __name__ == "__main__": write_movies()
369
import logging import os from dataclasses import dataclass, field from typing import Dict, Optional import datasets import numpy as np import tensorflow as tf from transformers import ( AutoConfig, AutoTokenizer, EvalPrediction, HfArgumentParser, PreTrainedTokenizer, TFAutoModelForSequenceClassification, TFTrainer, TFTrainingArguments, ) from transformers.utils import logging as hf_logging hf_logging.set_verbosity_info() hf_logging.enable_default_handler() hf_logging.enable_explicit_format() def _lowerCamelCase( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ = None , ) -> int: '''simple docstring''' __lowercase= {} if train_file is not None: __lowercase= [train_file] if eval_file is not None: __lowercase= [eval_file] if test_file is not None: __lowercase= [test_file] __lowercase= datasets.load_dataset('csv' , data_files=lowercase__ ) __lowercase= list(ds[list(files.keys() )[0]].features.keys() ) __lowercase= features_name.pop(lowercase__ ) __lowercase= list(set(ds[list(files.keys() )[0]][label_name] ) ) __lowercase= {label: i for i, label in enumerate(lowercase__ )} __lowercase= tokenizer.model_input_names __lowercase= {} if len(lowercase__ ) == 1: for k in files.keys(): __lowercase= ds[k].map( lambda lowercase__ : tokenizer.batch_encode_plus( example[features_name[0]] , truncation=lowercase__ , max_length=lowercase__ , padding='max_length' ) , batched=lowercase__ , ) elif len(lowercase__ ) == 2: for k in files.keys(): __lowercase= ds[k].map( lambda lowercase__ : tokenizer.batch_encode_plus( (example[features_name[0]], example[features_name[1]]) , truncation=lowercase__ , max_length=lowercase__ , padding='max_length' , ) , batched=lowercase__ , ) def gen_train(): for ex in transformed_ds[datasets.Split.TRAIN]: __lowercase= {k: v for k, v in ex.items() if k in input_names} __lowercase= labelaid[ex[label_name]] yield (d, label) def gen_val(): for ex in transformed_ds[datasets.Split.VALIDATION]: __lowercase= {k: v for k, v in ex.items() if k in input_names} __lowercase= labelaid[ex[label_name]] yield (d, label) def gen_test(): for ex in transformed_ds[datasets.Split.TEST]: __lowercase= {k: v for k, v in ex.items() if k in input_names} __lowercase= labelaid[ex[label_name]] yield (d, label) __lowercase= ( tf.data.Dataset.from_generator( lowercase__ , ({k: tf.intaa for k in input_names}, tf.intaa) , ({k: tf.TensorShape([None] ) for k in input_names}, tf.TensorShape([] )) , ) if datasets.Split.TRAIN in transformed_ds else None ) if train_ds is not None: __lowercase= train_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.TRAIN] ) ) ) __lowercase= ( tf.data.Dataset.from_generator( lowercase__ , ({k: tf.intaa for k in input_names}, tf.intaa) , ({k: tf.TensorShape([None] ) for k in input_names}, tf.TensorShape([] )) , ) if datasets.Split.VALIDATION in transformed_ds else None ) if val_ds is not None: __lowercase= val_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.VALIDATION] ) ) ) __lowercase= ( tf.data.Dataset.from_generator( lowercase__ , ({k: tf.intaa for k in input_names}, tf.intaa) , ({k: tf.TensorShape([None] ) for k in input_names}, tf.TensorShape([] )) , ) if datasets.Split.TEST in transformed_ds else None ) if test_ds is not None: __lowercase= test_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.TEST] ) ) ) return train_ds, val_ds, test_ds, labelaid lowerCAmelCase = logging.getLogger(__name__) @dataclass class A : UpperCamelCase_ : int =field(metadata={'''help''': '''Which column contains the label'''} ) UpperCamelCase_ : str =field(default=A_ , metadata={'''help''': '''The path of the training file'''} ) UpperCamelCase_ : Optional[str] =field(default=A_ , metadata={'''help''': '''The path of the development file'''} ) UpperCamelCase_ : Optional[str] =field(default=A_ , metadata={'''help''': '''The path of the test file'''} ) UpperCamelCase_ : int =field( default=128 , metadata={ '''help''': ( '''The maximum total input sequence length after tokenization. Sequences longer ''' '''than this will be truncated, sequences shorter will be padded.''' ) } , ) UpperCamelCase_ : bool =field( default=A_ , metadata={'''help''': '''Overwrite the cached training and evaluation sets'''} ) @dataclass class A : UpperCamelCase_ : str =field( metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''} ) UpperCamelCase_ : Optional[str] =field( default=A_ , metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''} ) UpperCamelCase_ : Optional[str] =field( default=A_ , metadata={'''help''': '''Pretrained tokenizer name or path if not the same as model_name'''} ) UpperCamelCase_ : bool =field(default=A_ , metadata={'''help''': '''Set this flag to use fast tokenization.'''} ) # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script, # or just modify its tokenizer_config.json. UpperCamelCase_ : Optional[str] =field( default=A_ , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''} , ) def _lowerCamelCase( ) -> Optional[Any]: '''simple docstring''' __lowercase= HfArgumentParser((ModelArguments, DataTrainingArguments, TFTrainingArguments) ) __lowercase, __lowercase, __lowercase= parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( F'Output directory ({training_args.output_dir}) already exists and is not empty. Use' ' --overwrite_output_dir to overcome.' ) # Setup logging logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' , datefmt='%m/%d/%Y %H:%M:%S' , level=logging.INFO , ) logger.info( F'n_replicas: {training_args.n_replicas}, distributed training: {bool(training_args.n_replicas > 1 )}, ' F'16-bits training: {training_args.fpaa}' ) logger.info(F'Training/evaluation parameters {training_args}' ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. __lowercase= AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) __lowercase, __lowercase, __lowercase, __lowercase= get_tfds( train_file=data_args.train_file , eval_file=data_args.dev_file , test_file=data_args.test_file , tokenizer=lowercase__ , label_column_id=data_args.label_column_id , max_seq_length=data_args.max_seq_length , ) __lowercase= AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=len(lowercase__ ) , labelaid=lowercase__ , idalabel={id: label for label, id in labelaid.items()} , finetuning_task='text-classification' , cache_dir=model_args.cache_dir , ) with training_args.strategy.scope(): __lowercase= TFAutoModelForSequenceClassification.from_pretrained( model_args.model_name_or_path , from_pt=bool('.bin' in model_args.model_name_or_path ) , config=lowercase__ , cache_dir=model_args.cache_dir , ) def compute_metrics(lowercase__ ) -> Dict: __lowercase= np.argmax(p.predictions , axis=1 ) return {"acc": (preds == p.label_ids).mean()} # Initialize our Trainer __lowercase= TFTrainer( model=lowercase__ , args=lowercase__ , train_dataset=lowercase__ , eval_dataset=lowercase__ , compute_metrics=lowercase__ , ) # Training if training_args.do_train: trainer.train() trainer.save_model() tokenizer.save_pretrained(training_args.output_dir ) # Evaluation __lowercase= {} if training_args.do_eval: logger.info('*** Evaluate ***' ) __lowercase= trainer.evaluate() __lowercase= os.path.join(training_args.output_dir , 'eval_results.txt' ) with open(lowercase__ , 'w' ) as writer: logger.info('***** Eval results *****' ) for key, value in result.items(): logger.info(F' {key} = {value}' ) writer.write(F'{key} = {value}\n' ) results.update(lowercase__ ) return results if __name__ == "__main__": main()
304
0
import random from typing import Any def __lowerCamelCase ( lowerCamelCase__ ): """simple docstring""" for _ in range(len(lowerCamelCase__ ) ): lowercase__ : int = random.randint(0 , len(lowerCamelCase__ ) - 1 ) lowercase__ : Dict = random.randint(0 , len(lowerCamelCase__ ) - 1 ) lowercase__ , lowercase__ : Tuple = data[b], data[a] return data if __name__ == "__main__": lowerCAmelCase__ = [0, 1, 2, 3, 4, 5, 6, 7] lowerCAmelCase__ = ['''python''', '''says''', '''hello''', '''!'''] print('''Fisher-Yates Shuffle:''') print('''List''', integers, strings) print('''FY Shuffle''', fisher_yates_shuffle(integers), fisher_yates_shuffle(strings))
130
from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import tensorflow as tf from transformers import AutoTokenizer, TFAutoModelForSeqaSeqLM @require_tf @require_sentencepiece @require_tokenizers class snake_case__(unittest.TestCase ): """simple docstring""" @slow def snake_case ( self : List[str] ): lowercase__ : int = TFAutoModelForSeqaSeqLM.from_pretrained("google/mt5-small" ) lowercase__ : Dict = AutoTokenizer.from_pretrained("google/mt5-small" ) lowercase__ : Dict = tokenizer("Hello there" , return_tensors="tf" ).input_ids lowercase__ : Any = tokenizer("Hi I am" , return_tensors="tf" ).input_ids lowercase__ : Union[str, Any] = model(SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ).loss lowercase__ : Dict = -tf.math.reduce_mean(SCREAMING_SNAKE_CASE ).numpy() lowercase__ : Optional[Any] = -21.228_168 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 2E-4 )
130
1
from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable lowerCAmelCase__ = {"""configuration_gpt_neox""": ["""GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GPTNeoXConfig"""]} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = ["""GPTNeoXTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ """GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST""", """GPTNeoXForCausalLM""", """GPTNeoXForQuestionAnswering""", """GPTNeoXForSequenceClassification""", """GPTNeoXForTokenClassification""", """GPTNeoXLayer""", """GPTNeoXModel""", """GPTNeoXPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_gpt_neox import GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXConfig try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_neox_fast import GPTNeoXTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox import ( GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, GPTNeoXLayer, GPTNeoXModel, GPTNeoXPreTrainedModel, ) else: import sys lowerCAmelCase__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
353
import os from argparse import ArgumentParser, Namespace from ..data import SingleSentenceClassificationProcessor as Processor from ..pipelines import TextClassificationPipeline from ..utils import is_tf_available, is_torch_available, logging from . import BaseTransformersCLICommand if not is_tf_available() and not is_torch_available(): raise RuntimeError('''At least one of PyTorch or TensorFlow 2.0+ should be installed to use CLI training''') # TF training parameters lowerCAmelCase__ = False lowerCAmelCase__ = False def __lowerCamelCase ( lowerCamelCase__ ): """simple docstring""" return TrainCommand(lowerCamelCase__ ) class snake_case__(_UpperCamelCase ): """simple docstring""" @staticmethod def snake_case ( SCREAMING_SNAKE_CASE : ArgumentParser ): lowercase__ : Optional[int] = parser.add_parser("train" , help="CLI tool to train a model on a task." ) train_parser.add_argument( "--train_data" , type=SCREAMING_SNAKE_CASE , required=SCREAMING_SNAKE_CASE , help="path to train (and optionally evaluation) dataset as a csv with tab separated labels and sentences." , ) train_parser.add_argument( "--column_label" , type=SCREAMING_SNAKE_CASE , default=0 , help="Column of the dataset csv file with example labels." ) train_parser.add_argument( "--column_text" , type=SCREAMING_SNAKE_CASE , default=1 , help="Column of the dataset csv file with example texts." ) train_parser.add_argument( "--column_id" , type=SCREAMING_SNAKE_CASE , default=2 , help="Column of the dataset csv file with example ids." ) train_parser.add_argument( "--skip_first_row" , action="store_true" , help="Skip the first row of the csv file (headers)." ) train_parser.add_argument("--validation_data" , type=SCREAMING_SNAKE_CASE , default="" , help="path to validation dataset." ) train_parser.add_argument( "--validation_split" , type=SCREAMING_SNAKE_CASE , default=0.1 , help="if validation dataset is not provided, fraction of train dataset to use as validation dataset." , ) train_parser.add_argument("--output" , type=SCREAMING_SNAKE_CASE , default="./" , help="path to saved the trained model." ) train_parser.add_argument( "--task" , type=SCREAMING_SNAKE_CASE , default="text_classification" , help="Task to train the model on." ) train_parser.add_argument( "--model" , type=SCREAMING_SNAKE_CASE , default="bert-base-uncased" , help="Model's name or path to stored model." ) train_parser.add_argument("--train_batch_size" , type=SCREAMING_SNAKE_CASE , default=32 , help="Batch size for training." ) train_parser.add_argument("--valid_batch_size" , type=SCREAMING_SNAKE_CASE , default=64 , help="Batch size for validation." ) train_parser.add_argument("--learning_rate" , type=SCREAMING_SNAKE_CASE , default=3E-5 , help="Learning rate." ) train_parser.add_argument("--adam_epsilon" , type=SCREAMING_SNAKE_CASE , default=1E-0_8 , help="Epsilon for Adam optimizer." ) train_parser.set_defaults(func=SCREAMING_SNAKE_CASE ) def __init__( self : int , SCREAMING_SNAKE_CASE : Namespace ): lowercase__ : int = logging.get_logger("transformers-cli/training" ) lowercase__ : List[Any] = "tf" if is_tf_available() else "torch" os.makedirs(args.output , exist_ok=SCREAMING_SNAKE_CASE ) lowercase__ : Optional[Any] = args.output lowercase__ : Union[str, Any] = args.column_label lowercase__ : Optional[int] = args.column_text lowercase__ : Optional[int] = args.column_id self.logger.info(f"""Loading {args.task} pipeline for {args.model}""" ) if args.task == "text_classification": lowercase__ : int = TextClassificationPipeline.from_pretrained(args.model ) elif args.task == "token_classification": raise NotImplementedError elif args.task == "question_answering": raise NotImplementedError self.logger.info(f"""Loading dataset from {args.train_data}""" ) lowercase__ : List[str] = Processor.create_from_csv( args.train_data , column_label=args.column_label , column_text=args.column_text , column_id=args.column_id , skip_first_row=args.skip_first_row , ) lowercase__ : Union[str, Any] = None if args.validation_data: self.logger.info(f"""Loading validation dataset from {args.validation_data}""" ) lowercase__ : Optional[int] = Processor.create_from_csv( args.validation_data , column_label=args.column_label , column_text=args.column_text , column_id=args.column_id , skip_first_row=args.skip_first_row , ) lowercase__ : Dict = args.validation_split lowercase__ : List[str] = args.train_batch_size lowercase__ : Any = args.valid_batch_size lowercase__ : Optional[int] = args.learning_rate lowercase__ : int = args.adam_epsilon def snake_case ( self : Dict ): if self.framework == "tf": return self.run_tf() return self.run_torch() def snake_case ( self : Union[str, Any] ): raise NotImplementedError def snake_case ( self : Union[str, Any] ): self.pipeline.fit( self.train_dataset , validation_data=self.valid_dataset , validation_split=self.validation_split , learning_rate=self.learning_rate , adam_epsilon=self.adam_epsilon , train_batch_size=self.train_batch_size , valid_batch_size=self.valid_batch_size , ) # Save trained pipeline self.pipeline.save_pretrained(self.output )
121
0
"""simple docstring""" class SCREAMING_SNAKE_CASE_ : """simple docstring""" def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__): __SCREAMING_SNAKE_CASE = name __SCREAMING_SNAKE_CASE = value __SCREAMING_SNAKE_CASE = weight def __repr__( self): return f"{self.__class__.__name__}({self.name}, {self.value}, {self.weight})" def snake_case_ ( self): return self.value def snake_case_ ( self): return self.name def snake_case_ ( self): return self.weight def snake_case_ ( self): return self.value / self.weight def _lowerCAmelCase ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ): __SCREAMING_SNAKE_CASE = [] for i in range(len(UpperCamelCase_ ) ): menu.append(Things(name[i] , value[i] , weight[i] ) ) return menu def _lowerCAmelCase ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ): __SCREAMING_SNAKE_CASE = sorted(UpperCamelCase_ , key=UpperCamelCase_ , reverse=UpperCamelCase_ ) __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE = 0.0, 0.0 for i in range(len(UpperCamelCase_ ) ): if (total_cost + items_copy[i].get_weight()) <= max_cost: result.append(items_copy[i] ) total_cost += items_copy[i].get_weight() total_value += items_copy[i].get_value() return (result, total_value) def _lowerCAmelCase ( ): pass if __name__ == "__main__": import doctest doctest.testmod()
100
"""simple docstring""" from math import isqrt, loga def _lowerCAmelCase ( UpperCamelCase_ ): __SCREAMING_SNAKE_CASE = [True] * max_number for i in range(2 , isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2 , UpperCamelCase_ , UpperCamelCase_ ): __SCREAMING_SNAKE_CASE = False return [i for i in range(2 , UpperCamelCase_ ) if is_prime[i]] def _lowerCAmelCase ( UpperCamelCase_ = 80_0800 , UpperCamelCase_ = 80_0800 ): __SCREAMING_SNAKE_CASE = degree * loga(UpperCamelCase_ ) __SCREAMING_SNAKE_CASE = int(UpperCamelCase_ ) __SCREAMING_SNAKE_CASE = calculate_prime_numbers(UpperCamelCase_ ) __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = len(UpperCamelCase_ ) - 1 while left < right: while ( prime_numbers[right] * loga(prime_numbers[left] ) + prime_numbers[left] * loga(prime_numbers[right] ) > upper_bound ): right -= 1 hybrid_integers_count += right - left left += 1 return hybrid_integers_count if __name__ == "__main__": print(F"""{solution() = }""")
100
1
import copy from typing import TYPE_CHECKING, Any, Mapping, Optional, OrderedDict from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto.configuration_auto import AutoConfig if TYPE_CHECKING: from ... import PreTrainedTokenizerBase, TensorType lowercase : Tuple = logging.get_logger(__name__) class UpperCAmelCase_ ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' A : Optional[Any] = 'vision-encoder-decoder' A : Optional[Any] = True def __init__( self , **_SCREAMING_SNAKE_CASE ) -> List[str]: super().__init__(**_SCREAMING_SNAKE_CASE ) if "encoder" not in kwargs or "decoder" not in kwargs: raise ValueError( f'''A configuraton of type {self.model_type} cannot be instantiated because ''' f'''not both `encoder` and `decoder` sub-configurations are passed, but only {kwargs}''' ) snake_case_ : Dict = kwargs.pop("encoder" ) snake_case_ : Optional[Any] = encoder_config.pop("model_type" ) snake_case_ : List[str] = kwargs.pop("decoder" ) snake_case_ : List[str] = decoder_config.pop("model_type" ) snake_case_ : List[Any] = AutoConfig.for_model(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) snake_case_ : List[Any] = AutoConfig.for_model(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) snake_case_ : Optional[Any] = True @classmethod def _lowerCAmelCase ( cls , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> PretrainedConfig: logger.info("Setting `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config" ) snake_case_ : Tuple = True snake_case_ : int = True return cls(encoder=encoder_config.to_dict() , decoder=decoder_config.to_dict() , **_SCREAMING_SNAKE_CASE ) def _lowerCAmelCase ( self ) -> Tuple: snake_case_ : List[str] = copy.deepcopy(self.__dict__ ) snake_case_ : str = self.encoder.to_dict() snake_case_ : int = self.decoder.to_dict() snake_case_ : Any = self.__class__.model_type return output class UpperCAmelCase_ ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' A : List[str] = version.parse('1.11' ) @property def _lowerCAmelCase ( self ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ] ) @property def _lowerCAmelCase ( self ) -> float: return 1e-4 @property def _lowerCAmelCase ( self ) -> Mapping[str, Mapping[int, str]]: return OrderedDict({"last_hidden_state": {0: "batch", 1: "encoder_sequence"}} ) class UpperCAmelCase_ ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' @property def _lowerCAmelCase ( self ) -> Mapping[str, Mapping[int, str]]: snake_case_ : Optional[Any] = OrderedDict() snake_case_ : Dict = {0: "batch", 1: "past_decoder_sequence + sequence"} snake_case_ : str = {0: "batch", 1: "past_decoder_sequence + sequence"} snake_case_ : Optional[Any] = {0: "batch", 1: "encoder_sequence"} return common_inputs def _lowerCAmelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = -1 , _SCREAMING_SNAKE_CASE = -1 , _SCREAMING_SNAKE_CASE = False , _SCREAMING_SNAKE_CASE = None , ) -> Mapping[str, Any]: import torch snake_case_ : Tuple = OrderedDict() snake_case_ : Union[str, Any] = super().generate_dummy_inputs( _SCREAMING_SNAKE_CASE , batch_size=_SCREAMING_SNAKE_CASE , seq_length=_SCREAMING_SNAKE_CASE , is_pair=_SCREAMING_SNAKE_CASE , framework=_SCREAMING_SNAKE_CASE ) snake_case_ , snake_case_ : Union[str, Any] = dummy_input["input_ids"].shape snake_case_ : List[Any] = (batch, encoder_sequence, self._config.encoder_hidden_size) snake_case_ : Optional[int] = dummy_input.pop("input_ids" ) snake_case_ : Optional[int] = dummy_input.pop("attention_mask" ) snake_case_ : Tuple = torch.zeros(_SCREAMING_SNAKE_CASE ) return common_inputs class UpperCAmelCase_ ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' @property def _lowerCAmelCase ( self ) -> None: pass def _lowerCAmelCase ( self , _SCREAMING_SNAKE_CASE ) -> OnnxConfig: return VisionEncoderDecoderEncoderOnnxConfig(_SCREAMING_SNAKE_CASE ) def _lowerCAmelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = "default" ) -> OnnxConfig: snake_case_ : Optional[int] = encoder_config.hidden_size return VisionEncoderDecoderDecoderOnnxConfig(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
36
import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_tf_available from transformers.testing_utils import require_tf if is_tf_available(): import tensorflow as tf from transformers import TensorFlowBenchmark, TensorFlowBenchmarkArguments @require_tf class UpperCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def _lowerCAmelCase ( self , _SCREAMING_SNAKE_CASE ) -> int: for model_result in results.values(): for batch_size, sequence_length in zip(model_result["bs"] , model_result["ss"] ): snake_case_ : List[Any] = model_result["result"][batch_size][sequence_length] self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) def _lowerCAmelCase ( self ) -> Tuple: snake_case_ : Dict = "sshleifer/tiny-gpt2" snake_case_ : Optional[Any] = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=_SCREAMING_SNAKE_CASE , inference=_SCREAMING_SNAKE_CASE , sequence_lengths=[8] , batch_sizes=[1] , eager_mode=_SCREAMING_SNAKE_CASE , multi_process=_SCREAMING_SNAKE_CASE , ) snake_case_ : Optional[Any] = TensorFlowBenchmark(_SCREAMING_SNAKE_CASE ) snake_case_ : Optional[Any] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _lowerCAmelCase ( self ) -> int: snake_case_ : List[Any] = "sgugger/tiny-distilbert-classification" snake_case_ : Optional[Any] = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=_SCREAMING_SNAKE_CASE , inference=_SCREAMING_SNAKE_CASE , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_SCREAMING_SNAKE_CASE , only_pretrain_model=_SCREAMING_SNAKE_CASE , ) snake_case_ : int = TensorFlowBenchmark(_SCREAMING_SNAKE_CASE ) snake_case_ : Union[str, Any] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _lowerCAmelCase ( self ) -> Tuple: snake_case_ : List[str] = "sshleifer/tiny-gpt2" snake_case_ : Optional[Any] = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=_SCREAMING_SNAKE_CASE , inference=_SCREAMING_SNAKE_CASE , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_SCREAMING_SNAKE_CASE , ) snake_case_ : Optional[Any] = TensorFlowBenchmark(_SCREAMING_SNAKE_CASE ) snake_case_ : int = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _lowerCAmelCase ( self ) -> int: snake_case_ : Union[str, Any] = "sshleifer/tiny-gpt2" snake_case_ : List[str] = AutoConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) snake_case_ : int = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=_SCREAMING_SNAKE_CASE , inference=_SCREAMING_SNAKE_CASE , sequence_lengths=[8] , batch_sizes=[1] , eager_mode=_SCREAMING_SNAKE_CASE , multi_process=_SCREAMING_SNAKE_CASE , ) snake_case_ : List[str] = TensorFlowBenchmark(_SCREAMING_SNAKE_CASE , [config] ) snake_case_ : Optional[int] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _lowerCAmelCase ( self ) -> List[str]: snake_case_ : str = "sshleifer/tiny-gpt2" snake_case_ : int = AutoConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) snake_case_ : Dict = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=_SCREAMING_SNAKE_CASE , inference=_SCREAMING_SNAKE_CASE , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_SCREAMING_SNAKE_CASE , ) snake_case_ : List[Any] = TensorFlowBenchmark(_SCREAMING_SNAKE_CASE , [config] ) snake_case_ : Union[str, Any] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _lowerCAmelCase ( self ) -> str: snake_case_ : List[str] = "sshleifer/tiny-gpt2" snake_case_ : Tuple = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=_SCREAMING_SNAKE_CASE , inference=_SCREAMING_SNAKE_CASE , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_SCREAMING_SNAKE_CASE , ) snake_case_ : List[str] = TensorFlowBenchmark(_SCREAMING_SNAKE_CASE ) snake_case_ : Dict = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def _lowerCAmelCase ( self ) -> Dict: snake_case_ : str = "sshleifer/tiny-gpt2" snake_case_ : str = AutoConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) snake_case_ : Dict = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=_SCREAMING_SNAKE_CASE , inference=_SCREAMING_SNAKE_CASE , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_SCREAMING_SNAKE_CASE , ) snake_case_ : Optional[Any] = TensorFlowBenchmark(_SCREAMING_SNAKE_CASE , [config] ) snake_case_ : str = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def _lowerCAmelCase ( self ) -> List[str]: snake_case_ : List[str] = "patrickvonplaten/t5-tiny-random" snake_case_ : Union[str, Any] = AutoConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) snake_case_ : Optional[Any] = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=_SCREAMING_SNAKE_CASE , inference=_SCREAMING_SNAKE_CASE , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_SCREAMING_SNAKE_CASE , ) snake_case_ : List[str] = TensorFlowBenchmark(_SCREAMING_SNAKE_CASE , configs=[config] ) snake_case_ : List[Any] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) @unittest.skipIf(is_tf_available() and len(tf.config.list_physical_devices("GPU" ) ) == 0 , "Cannot do xla on CPU." ) def _lowerCAmelCase ( self ) -> Dict: snake_case_ : int = "sshleifer/tiny-gpt2" snake_case_ : Tuple = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=_SCREAMING_SNAKE_CASE , inference=_SCREAMING_SNAKE_CASE , sequence_lengths=[8] , batch_sizes=[1] , use_xla=_SCREAMING_SNAKE_CASE , multi_process=_SCREAMING_SNAKE_CASE , ) snake_case_ : List[str] = TensorFlowBenchmark(_SCREAMING_SNAKE_CASE ) snake_case_ : str = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _lowerCAmelCase ( self ) -> Tuple: snake_case_ : Union[str, Any] = "sshleifer/tiny-gpt2" with tempfile.TemporaryDirectory() as tmp_dir: snake_case_ : Optional[int] = TensorFlowBenchmarkArguments( models=[MODEL_ID] , inference=_SCREAMING_SNAKE_CASE , save_to_csv=_SCREAMING_SNAKE_CASE , sequence_lengths=[8] , batch_sizes=[1] , inference_time_csv_file=os.path.join(_SCREAMING_SNAKE_CASE , "inf_time.csv" ) , inference_memory_csv_file=os.path.join(_SCREAMING_SNAKE_CASE , "inf_mem.csv" ) , env_info_csv_file=os.path.join(_SCREAMING_SNAKE_CASE , "env.csv" ) , multi_process=_SCREAMING_SNAKE_CASE , ) snake_case_ : Dict = TensorFlowBenchmark(_SCREAMING_SNAKE_CASE ) benchmark.run() self.assertTrue(Path(os.path.join(_SCREAMING_SNAKE_CASE , "inf_time.csv" ) ).exists() ) self.assertTrue(Path(os.path.join(_SCREAMING_SNAKE_CASE , "inf_mem.csv" ) ).exists() ) self.assertTrue(Path(os.path.join(_SCREAMING_SNAKE_CASE , "env.csv" ) ).exists() ) def _lowerCAmelCase ( self ) -> List[str]: snake_case_ : int = "sshleifer/tiny-gpt2" def _check_summary_is_not_empty(_SCREAMING_SNAKE_CASE ): self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , "sequential" ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , "cumulative" ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , "current" ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , "total" ) ) with tempfile.TemporaryDirectory() as tmp_dir: snake_case_ : Union[str, Any] = TensorFlowBenchmarkArguments( models=[MODEL_ID] , inference=_SCREAMING_SNAKE_CASE , sequence_lengths=[8] , batch_sizes=[1] , log_filename=os.path.join(_SCREAMING_SNAKE_CASE , "log.txt" ) , log_print=_SCREAMING_SNAKE_CASE , trace_memory_line_by_line=_SCREAMING_SNAKE_CASE , eager_mode=_SCREAMING_SNAKE_CASE , multi_process=_SCREAMING_SNAKE_CASE , ) snake_case_ : Tuple = TensorFlowBenchmark(_SCREAMING_SNAKE_CASE ) snake_case_ : int = benchmark.run() _check_summary_is_not_empty(result.inference_summary ) self.assertTrue(Path(os.path.join(_SCREAMING_SNAKE_CASE , "log.txt" ) ).exists() )
36
1
'''simple docstring''' import json import os import unittest from transformers import MgpstrTokenizer from transformers.models.mgp_str.tokenization_mgp_str import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class _lowercase ( _lowercase , unittest.TestCase ): a = MgpstrTokenizer a = False a = {} a = False def lowerCamelCase_ ( self: Dict ): super().setUp() # fmt: off lowerCamelCase__ : int = ["""[GO]""", """[s]""", """0""", """1""", """2""", """3""", """4""", """5""", """6""", """7""", """8""", """9""", """a""", """b""", """c""", """d""", """e""", """f""", """g""", """h""", """i""", """j""", """k""", """l""", """m""", """n""", """o""", """p""", """q""", """r""", """s""", """t""", """u""", """v""", """w""", """x""", """y""", """z"""] # fmt: on lowerCamelCase__ : Optional[Any] = dict(zip(UpperCamelCase__ , range(len(UpperCamelCase__ ) ) ) ) lowerCamelCase__ : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(UpperCamelCase__ ) + """\n""" ) def lowerCamelCase_ ( self: Optional[int] , **UpperCamelCase__: Optional[int] ): return MgpstrTokenizer.from_pretrained(self.tmpdirname , **UpperCamelCase__ ) def lowerCamelCase_ ( self: int , UpperCamelCase__: Union[str, Any] ): lowerCamelCase__ : Tuple = """tester""" lowerCamelCase__ : int = """tester""" return input_text, output_text @unittest.skip("""MGP-STR always lower cases letters.""" ) def lowerCamelCase_ ( self: str ): pass def lowerCamelCase_ ( self: Optional[int] ): lowerCamelCase__ : List[Any] = self.get_tokenizers(do_lower_case=UpperCamelCase__ ) for tokenizer in tokenizers: with self.subTest(F'''{tokenizer.__class__.__name__}''' ): lowerCamelCase__ : Union[str, Any] = """[SPECIAL_TOKEN]""" tokenizer.add_special_tokens({"""cls_token""": special_token} ) lowerCamelCase__ : List[str] = tokenizer.encode([special_token] , add_special_tokens=UpperCamelCase__ ) self.assertEqual(len(UpperCamelCase__ ) , 1 ) lowerCamelCase__ : Tuple = tokenizer.decode(UpperCamelCase__ , skip_special_tokens=UpperCamelCase__ ) self.assertTrue(special_token not in decoded ) def lowerCamelCase_ ( self: Union[str, Any] ): lowerCamelCase__ : Tuple = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F'''{tokenizer.__class__.__name__}''' ): lowerCamelCase__ , lowerCamelCase__ : Optional[Any] = self.get_input_output_texts(UpperCamelCase__ ) lowerCamelCase__ : Optional[Any] = tokenizer.tokenize(UpperCamelCase__ ) lowerCamelCase__ : List[Any] = tokenizer.convert_tokens_to_ids(UpperCamelCase__ ) lowerCamelCase__ : str = tokenizer.encode(UpperCamelCase__ , add_special_tokens=UpperCamelCase__ ) self.assertListEqual(UpperCamelCase__ , UpperCamelCase__ ) lowerCamelCase__ : Tuple = tokenizer.convert_ids_to_tokens(UpperCamelCase__ ) self.assertNotEqual(len(UpperCamelCase__ ) , 0 ) lowerCamelCase__ : Any = tokenizer.decode(UpperCamelCase__ ) self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ ) self.assertEqual(text_a.replace(""" """ , """""" ) , UpperCamelCase__ ) @unittest.skip("""MGP-STR tokenizer only handles one sequence.""" ) def lowerCamelCase_ ( self: str ): pass @unittest.skip("""inputs cannot be pretokenized in MgpstrTokenizer""" ) def lowerCamelCase_ ( self: Tuple ): pass
41
'''simple docstring''' def SCREAMING_SNAKE_CASE_ (UpperCamelCase = 1000 ) -> int: lowerCamelCase__ : str = -1 lowerCamelCase__ : Dict = 0 for a in range(1 , n // 3 ): # Solving the two equations a**2+b**2=c**2 and a+b+c=N eliminating c lowerCamelCase__ : Dict = (n * n - 2 * a * n) // (2 * n - 2 * a) lowerCamelCase__ : Any = n - a - b if c * c == (a * a + b * b): lowerCamelCase__ : Dict = a * b * c if candidate >= product: lowerCamelCase__ : Union[str, Any] = candidate return product if __name__ == "__main__": print(F'{solution() = }')
41
1
from .configuration_bert_masked import MaskedBertConfig from .modeling_bert_masked import ( MaskedBertForMultipleChoice, MaskedBertForQuestionAnswering, MaskedBertForSequenceClassification, MaskedBertForTokenClassification, MaskedBertModel, ) from .modules import *
370
import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST, OpenAIGPTConfig, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification, OpenAIGPTLMHeadModel, OpenAIGPTModel, ) class lowercase__ : def __init__( self : Dict , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Dict=13 , UpperCAmelCase_ : Optional[Any]=7 , UpperCAmelCase_ : Any=True , UpperCAmelCase_ : List[str]=True , UpperCAmelCase_ : List[str]=True , UpperCAmelCase_ : int=99 , UpperCAmelCase_ : Tuple=32 , UpperCAmelCase_ : int=5 , UpperCAmelCase_ : Tuple=4 , UpperCAmelCase_ : Tuple=37 , UpperCAmelCase_ : Optional[Any]="gelu" , UpperCAmelCase_ : Tuple=0.1 , UpperCAmelCase_ : Tuple=0.1 , UpperCAmelCase_ : Optional[Any]=512 , UpperCAmelCase_ : List[str]=16 , UpperCAmelCase_ : Any=2 , UpperCAmelCase_ : Dict=0.02 , UpperCAmelCase_ : Optional[int]=3 , UpperCAmelCase_ : Any=4 , UpperCAmelCase_ : Tuple=None , ): SCREAMING_SNAKE_CASE__ = parent SCREAMING_SNAKE_CASE__ = batch_size SCREAMING_SNAKE_CASE__ = seq_length SCREAMING_SNAKE_CASE__ = is_training SCREAMING_SNAKE_CASE__ = use_token_type_ids SCREAMING_SNAKE_CASE__ = use_labels SCREAMING_SNAKE_CASE__ = vocab_size SCREAMING_SNAKE_CASE__ = hidden_size SCREAMING_SNAKE_CASE__ = num_hidden_layers SCREAMING_SNAKE_CASE__ = num_attention_heads SCREAMING_SNAKE_CASE__ = intermediate_size SCREAMING_SNAKE_CASE__ = hidden_act SCREAMING_SNAKE_CASE__ = hidden_dropout_prob SCREAMING_SNAKE_CASE__ = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ = max_position_embeddings SCREAMING_SNAKE_CASE__ = type_vocab_size SCREAMING_SNAKE_CASE__ = type_sequence_label_size SCREAMING_SNAKE_CASE__ = initializer_range SCREAMING_SNAKE_CASE__ = num_labels SCREAMING_SNAKE_CASE__ = num_choices SCREAMING_SNAKE_CASE__ = scope SCREAMING_SNAKE_CASE__ = self.vocab_size - 1 def A_ ( self : List[Any] ): SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None if self.use_labels: SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ = OpenAIGPTConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , pad_token_id=self.pad_token_id , ) SCREAMING_SNAKE_CASE__ = ids_tensor([self.num_hidden_layers, self.num_attention_heads] , 2 ) return ( config, input_ids, head_mask, token_type_ids, sequence_labels, token_labels, choice_labels, ) def A_ ( self : Union[str, Any] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : List[str] , *UpperCAmelCase_ : List[str] ): SCREAMING_SNAKE_CASE__ = OpenAIGPTModel(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE__ = model(UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , head_mask=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE__ = model(UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE__ = model(UpperCAmelCase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def A_ ( self : Union[str, Any] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Any , UpperCAmelCase_ : Any , UpperCAmelCase_ : Tuple , *UpperCAmelCase_ : List[Any] ): SCREAMING_SNAKE_CASE__ = OpenAIGPTLMHeadModel(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE__ = model(UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def A_ ( self : str , UpperCAmelCase_ : int , UpperCAmelCase_ : int , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Union[str, Any] , *UpperCAmelCase_ : Union[str, Any] ): SCREAMING_SNAKE_CASE__ = OpenAIGPTDoubleHeadsModel(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE__ = model(UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def A_ ( self : int , UpperCAmelCase_ : Dict , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Any , *UpperCAmelCase_ : int ): SCREAMING_SNAKE_CASE__ = self.num_labels SCREAMING_SNAKE_CASE__ = OpenAIGPTForSequenceClassification(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ = model(UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def A_ ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE__ = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) = config_and_inputs SCREAMING_SNAKE_CASE__ = { 'input_ids': input_ids, 'token_type_ids': token_type_ids, 'head_mask': head_mask, } return config, inputs_dict @require_torch class lowercase__ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): A__ : Union[str, Any] =( (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification) if is_torch_available() else () ) A__ : Any =( (OpenAIGPTLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly A__ : Dict =( { """feature-extraction""": OpenAIGPTModel, """text-classification""": OpenAIGPTForSequenceClassification, """text-generation""": OpenAIGPTLMHeadModel, """zero-shot""": OpenAIGPTForSequenceClassification, } if is_torch_available() else {} ) def A_ ( self : str , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : List[Any] ): if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests": # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers. # `OpenAIGPTConfig` was never used in pipeline tests, either because of a missing checkpoint or because a # tiny config could not be created. return True return False def A_ ( self : List[str] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Dict=False ): SCREAMING_SNAKE_CASE__ = super()._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ , return_labels=UpperCAmelCase_ ) if return_labels: if model_class.__name__ == "OpenAIGPTDoubleHeadsModel": SCREAMING_SNAKE_CASE__ = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length) , dtype=torch.long , device=UpperCAmelCase_ , ) SCREAMING_SNAKE_CASE__ = inputs_dict['labels'] SCREAMING_SNAKE_CASE__ = inputs_dict['labels'] SCREAMING_SNAKE_CASE__ = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices) , dtype=torch.long , device=UpperCAmelCase_ , ) SCREAMING_SNAKE_CASE__ = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=UpperCAmelCase_ ) return inputs_dict def A_ ( self : Optional[int] ): SCREAMING_SNAKE_CASE__ = OpenAIGPTModelTester(self ) SCREAMING_SNAKE_CASE__ = ConfigTester(self , config_class=UpperCAmelCase_ , n_embd=37 ) def A_ ( self : Optional[int] ): self.config_tester.run_common_tests() def A_ ( self : Optional[int] ): SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_model(*UpperCAmelCase_ ) def A_ ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head_model(*UpperCAmelCase_ ) def A_ ( self : List[str] ): SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_double_lm_head_model(*UpperCAmelCase_ ) def A_ ( self : Optional[Any] ): SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*UpperCAmelCase_ ) @slow def A_ ( self : Optional[int] ): for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ = OpenAIGPTModel.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) @require_torch class lowercase__ ( unittest.TestCase ): @slow def A_ ( self : List[Any] ): SCREAMING_SNAKE_CASE__ = OpenAIGPTLMHeadModel.from_pretrained('openai-gpt' ) model.to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE__ = torch.tensor([[481, 4735, 544]] , dtype=torch.long , device=UpperCAmelCase_ ) # the president is SCREAMING_SNAKE_CASE__ = [ 481, 4735, 544, 246, 963, 870, 762, 239, 244, 40477, 244, 249, 719, 881, 487, 544, 240, 244, 603, 481, ] # the president is a very good man. " \n " i\'m sure he is, " said the SCREAMING_SNAKE_CASE__ = model.generate(UpperCAmelCase_ , do_sample=UpperCAmelCase_ ) self.assertListEqual(output_ids[0].tolist() , UpperCAmelCase_ )
169
0
from __future__ import annotations import os import tempfile import unittest from transformers import ConvBertConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFConvBertForMaskedLM, TFConvBertForMultipleChoice, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertModel, ) class A__ : def __init__( self , A_ , A_=13 , A_=7 , A_=True , A_=True , A_=True , A_=True , A_=99 , A_=32 , A_=2 , A_=4 , A_=37 , A_="gelu" , A_=0.1 , A_=0.1 , A_=512 , A_=16 , A_=2 , A_=0.02 , A_=3 , A_=4 , A_=None , ): '''simple docstring''' UpperCamelCase : int = parent UpperCamelCase : List[Any] = 13 UpperCamelCase : str = 7 UpperCamelCase : List[str] = True UpperCamelCase : Optional[Any] = True UpperCamelCase : str = True UpperCamelCase : List[str] = True UpperCamelCase : str = 99 UpperCamelCase : Optional[Any] = 384 UpperCamelCase : str = 2 UpperCamelCase : List[str] = 4 UpperCamelCase : Optional[Any] = 37 UpperCamelCase : Optional[Any] = """gelu""" UpperCamelCase : List[str] = 0.1 UpperCamelCase : Dict = 0.1 UpperCamelCase : List[str] = 512 UpperCamelCase : List[str] = 16 UpperCamelCase : Union[str, Any] = 2 UpperCamelCase : Optional[int] = 0.02 UpperCamelCase : int = 3 UpperCamelCase : Any = 4 UpperCamelCase : Optional[int] = 128 UpperCamelCase : Any = 2 UpperCamelCase : Optional[int] = 9 UpperCamelCase : int = 1 UpperCamelCase : List[Any] = None def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase : Tuple = None if self.use_input_mask: UpperCamelCase : str = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase : Dict = None if self.use_token_type_ids: UpperCamelCase : int = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCamelCase : int = None UpperCamelCase : List[Any] = None UpperCamelCase : Any = None if self.use_labels: UpperCamelCase : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase : Any = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase : Optional[int] = ConvBertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , return_dict=A_ , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ ): '''simple docstring''' UpperCamelCase : Optional[Any] = TFConvBertModel(config=A_ ) UpperCamelCase : Dict = {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids} UpperCamelCase : Dict = [input_ids, input_mask] UpperCamelCase : Optional[Any] = model(A_ ) UpperCamelCase : Optional[int] = model(A_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ ): '''simple docstring''' UpperCamelCase : Optional[int] = TFConvBertForMaskedLM(config=A_ ) UpperCamelCase : Optional[Any] = { """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } UpperCamelCase : List[str] = model(A_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ ): '''simple docstring''' UpperCamelCase : str = self.num_labels UpperCamelCase : Dict = TFConvBertForSequenceClassification(config=A_ ) UpperCamelCase : List[Any] = { """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } UpperCamelCase : Optional[Any] = model(A_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ ): '''simple docstring''' UpperCamelCase : str = self.num_choices UpperCamelCase : int = TFConvBertForMultipleChoice(config=A_ ) UpperCamelCase : List[Any] = tf.tile(tf.expand_dims(A_ , 1 ) , (1, self.num_choices, 1) ) UpperCamelCase : Dict = tf.tile(tf.expand_dims(A_ , 1 ) , (1, self.num_choices, 1) ) UpperCamelCase : Optional[Any] = tf.tile(tf.expand_dims(A_ , 1 ) , (1, self.num_choices, 1) ) UpperCamelCase : Dict = { """input_ids""": multiple_choice_inputs_ids, """attention_mask""": multiple_choice_input_mask, """token_type_ids""": multiple_choice_token_type_ids, } UpperCamelCase : Tuple = model(A_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ ): '''simple docstring''' UpperCamelCase : Optional[int] = self.num_labels UpperCamelCase : List[str] = TFConvBertForTokenClassification(config=A_ ) UpperCamelCase : Optional[int] = { """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } UpperCamelCase : List[str] = model(A_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ ): '''simple docstring''' UpperCamelCase : Optional[Any] = TFConvBertForQuestionAnswering(config=A_ ) UpperCamelCase : Dict = { """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } UpperCamelCase : List[Any] = model(A_ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : int = self.prepare_config_and_inputs() ( UpperCamelCase ) : Dict = config_and_inputs UpperCamelCase : List[Any] = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_tf class A__ ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): _UpperCAmelCase :str = ( ( TFConvBertModel, TFConvBertForMaskedLM, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertForMultipleChoice, ) if is_tf_available() else () ) _UpperCAmelCase :Union[str, Any] = ( { "feature-extraction": TFConvBertModel, "fill-mask": TFConvBertForMaskedLM, "question-answering": TFConvBertForQuestionAnswering, "text-classification": TFConvBertForSequenceClassification, "token-classification": TFConvBertForTokenClassification, "zero-shot": TFConvBertForSequenceClassification, } if is_tf_available() else {} ) _UpperCAmelCase :Any = False _UpperCAmelCase :List[Any] = False _UpperCAmelCase :str = False def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : List[Any] = TFConvBertModelTester(self ) UpperCamelCase : Any = ConfigTester(self , config_class=A_ , hidden_size=37 ) def __UpperCamelCase( self ): '''simple docstring''' self.config_tester.run_common_tests() def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*A_ ) @slow def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Any = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase : Tuple = True UpperCamelCase : List[Any] = True if hasattr(A_ , "use_cache" ): UpperCamelCase : Dict = True UpperCamelCase : int = getattr(self.model_tester , "encoder_seq_length" , self.model_tester.seq_length ) UpperCamelCase : Any = getattr(self.model_tester , "key_length" , A_ ) for model_class in self.all_model_classes: UpperCamelCase : List[str] = self._prepare_for_class(A_ , A_ ) UpperCamelCase : List[Any] = model_class(A_ ) UpperCamelCase : Any = len(model(A_ ) ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(A_ , saved_model=A_ ) UpperCamelCase : int = os.path.join(A_ , "saved_model" , "1" ) UpperCamelCase : Union[str, Any] = tf.keras.models.load_model(A_ ) UpperCamelCase : Any = model(A_ ) if self.is_encoder_decoder: UpperCamelCase : Optional[Any] = outputs["""encoder_hidden_states"""] UpperCamelCase : Dict = outputs["""encoder_attentions"""] else: UpperCamelCase : Tuple = outputs["""hidden_states"""] UpperCamelCase : Any = outputs["""attentions"""] self.assertEqual(len(A_ ) , A_ ) UpperCamelCase : int = getattr( self.model_tester , "expected_num_hidden_layers" , self.model_tester.num_hidden_layers + 1 ) self.assertEqual(len(A_ ) , A_ ) self.assertListEqual( list(output_hidden_states[0].shape[-2:] ) , [self.model_tester.seq_length, self.model_tester.hidden_size] , ) self.assertEqual(len(A_ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(output_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , ) @slow def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Any = TFConvBertModel.from_pretrained("YituTech/conv-bert-base" ) self.assertIsNotNone(A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : int = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase : List[Any] = True UpperCamelCase : Union[str, Any] = getattr(self.model_tester , "decoder_seq_length" , self.model_tester.seq_length ) UpperCamelCase : List[str] = getattr(self.model_tester , "encoder_seq_length" , self.model_tester.seq_length ) UpperCamelCase : Optional[int] = getattr(self.model_tester , "key_length" , A_ ) UpperCamelCase : Dict = getattr(self.model_tester , "key_length" , A_ ) def check_decoder_attentions_output(A_ ): UpperCamelCase : List[str] = len(A_ ) self.assertEqual(out_len % 2 , 0 ) UpperCamelCase : Union[str, Any] = outputs.decoder_attentions self.assertEqual(len(A_ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, decoder_seq_length, decoder_key_length] , ) def check_encoder_attentions_output(A_ ): UpperCamelCase : Tuple = [ t.numpy() for t in (outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions) ] self.assertEqual(len(A_ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , ) for model_class in self.all_model_classes: UpperCamelCase : str = True UpperCamelCase : Tuple = False UpperCamelCase : List[Any] = model_class(A_ ) UpperCamelCase : Dict = model(self._prepare_for_class(A_ , A_ ) ) UpperCamelCase : Union[str, Any] = len(A_ ) self.assertEqual(config.output_hidden_states , A_ ) check_encoder_attentions_output(A_ ) if self.is_encoder_decoder: UpperCamelCase : Optional[Any] = model_class(A_ ) UpperCamelCase : str = model(self._prepare_for_class(A_ , A_ ) ) self.assertEqual(config.output_hidden_states , A_ ) check_decoder_attentions_output(A_ ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] UpperCamelCase : Union[str, Any] = True UpperCamelCase : Optional[int] = model_class(A_ ) UpperCamelCase : Union[str, Any] = model(self._prepare_for_class(A_ , A_ ) ) self.assertEqual(config.output_hidden_states , A_ ) check_encoder_attentions_output(A_ ) # Check attention is always last and order is fine UpperCamelCase : Dict = True UpperCamelCase : Optional[Any] = True UpperCamelCase : List[Any] = model_class(A_ ) UpperCamelCase : Optional[Any] = model(self._prepare_for_class(A_ , A_ ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(A_ ) ) self.assertEqual(model.config.output_hidden_states , A_ ) check_encoder_attentions_output(A_ ) @require_tf class A__ ( unittest.TestCase ): @slow def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : int = TFConvBertModel.from_pretrained("YituTech/conv-bert-base" ) UpperCamelCase : Tuple = tf.constant([[0, 1, 2, 3, 4, 5]] ) UpperCamelCase : Dict = model(A_ )[0] UpperCamelCase : List[str] = [1, 6, 768] self.assertEqual(output.shape , A_ ) UpperCamelCase : Tuple = tf.constant( [ [ [-0.03_47_54_93, -0.4_68_60_34, -0.30_63_88_32], [0.22_63_72_48, -0.26_98_86_46, -0.7_42_34_24], [0.10_32_48_68, -0.45_01_35_08, -0.58_28_07_84], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , A_ , atol=1e-4 )
52
'''simple docstring''' import pytest from datasets.utils.sharding import _distribute_shards, _number_of_shards_in_gen_kwargs, _split_gen_kwargs @pytest.mark.parametrize( """kwargs, expected""" ,[ ({"""num_shards""": 0, """max_num_jobs""": 1}, []), ({"""num_shards""": 10, """max_num_jobs""": 1}, [range(10 )]), ({"""num_shards""": 10, """max_num_jobs""": 10}, [range(_UpperCAmelCase ,i + 1 ) for i in range(10 )]), ({"""num_shards""": 1, """max_num_jobs""": 10}, [range(1 )]), ({"""num_shards""": 10, """max_num_jobs""": 3}, [range(0 ,4 ), range(4 ,7 ), range(7 ,10 )]), ({"""num_shards""": 3, """max_num_jobs""": 10}, [range(0 ,1 ), range(1 ,2 ), range(2 ,3 )]), ] ,) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : Dict ) -> Optional[Any]: _a : Tuple =_distribute_shards(**_UpperCAmelCase ) assert out == expected @pytest.mark.parametrize( """gen_kwargs, max_num_jobs, expected""" ,[ ({"""foo""": 0}, 10, [{"""foo""": 0}]), ({"""shards""": [0, 1, 2, 3]}, 1, [{"""shards""": [0, 1, 2, 3]}]), ({"""shards""": [0, 1, 2, 3]}, 4, [{"""shards""": [0]}, {"""shards""": [1]}, {"""shards""": [2]}, {"""shards""": [3]}]), ({"""shards""": [0, 1]}, 4, [{"""shards""": [0]}, {"""shards""": [1]}]), ({"""shards""": [0, 1, 2, 3]}, 2, [{"""shards""": [0, 1]}, {"""shards""": [2, 3]}]), ] ,) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Tuple ,_UpperCAmelCase : List[Any] ,_UpperCAmelCase : Union[str, Any] ) -> List[str]: _a : List[str] =_split_gen_kwargs(_UpperCAmelCase ,_UpperCAmelCase ) assert out == expected @pytest.mark.parametrize( """gen_kwargs, expected""" ,[ ({"""foo""": 0}, 1), ({"""shards""": [0]}, 1), ({"""shards""": [0, 1, 2, 3]}, 4), ({"""shards""": [0, 1, 2, 3], """foo""": 0}, 4), ({"""shards""": [0, 1, 2, 3], """other""": (0, 1)}, 4), ({"""shards""": [0, 1, 2, 3], """shards2""": [0, 1]}, RuntimeError), ] ,) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : List[Any] ) -> Union[str, Any]: if expected is RuntimeError: with pytest.raises(_UpperCAmelCase ): _number_of_shards_in_gen_kwargs(_UpperCAmelCase ) else: _a : Dict =_number_of_shards_in_gen_kwargs(_UpperCAmelCase ) assert out == expected
276
0
'''simple docstring''' lowercase__ : int = [ """VerificationMode""", """Version""", """disable_progress_bar""", """enable_progress_bar""", """is_progress_bar_enabled""", """experimental""", ] from .info_utils import VerificationMode from .logging import disable_progress_bar, enable_progress_bar, is_progress_bar_enabled from .version import Version from .experimental import experimental
356
'''simple docstring''' def a__ ( lowercase : int, lowercase : int ) -> int: """simple docstring""" return x if y == 0 else greatest_common_divisor(lowercase, x % y ) def a__ ( lowercase : int, lowercase : int ) -> int: """simple docstring""" return (x * y) // greatest_common_divisor(lowercase, lowercase ) def a__ ( lowercase : int = 20 ) -> int: """simple docstring""" _UpperCamelCase = 1 for i in range(1, n + 1 ): _UpperCamelCase = lcm(lowercase, lowercase ) return g if __name__ == "__main__": print(F"""{solution() = }""")
287
0
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 _lowerCamelCase : Tuple = logging.get_logger(__name__) _lowerCamelCase : Optional[Any] = { '''artists_file''': '''artists.json''', '''lyrics_file''': '''lyrics.json''', '''genres_file''': '''genres.json''', } _lowerCamelCase : 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''', }, } _lowerCamelCase : Optional[Any] = { '''jukebox''': 512, } class SCREAMING_SNAKE_CASE__ ( UpperCAmelCase ): '''simple docstring''' _UpperCAmelCase : Optional[int] = VOCAB_FILES_NAMES _UpperCAmelCase : List[Any] = PRETRAINED_VOCAB_FILES_MAP _UpperCAmelCase : int = PRETRAINED_LYRIC_TOKENS_SIZES _UpperCAmelCase : Optional[Any] = ["input_ids", "attention_mask"] def __init__( self : Union[str, Any] , lowercase : Dict , lowercase : Union[str, Any] , lowercase : Union[str, Any] , lowercase : int=["v3", "v2", "v2"] , lowercase : List[Any]=512 , lowercase : Any=5 , lowercase : Any="<|endoftext|>" , **lowercase : Tuple , ): '''simple docstring''' _snake_case = AddedToken(lowercase , lstrip=lowercase , rstrip=lowercase ) if isinstance(lowercase , lowercase ) else unk_token super().__init__( unk_token=lowercase , n_genres=lowercase , version=lowercase , max_n_lyric_tokens=lowercase , **lowercase , ) _snake_case = version _snake_case = max_n_lyric_tokens _snake_case = n_genres with open(lowercase , encoding='utf-8' ) as vocab_handle: _snake_case = json.load(lowercase ) with open(lowercase , encoding='utf-8' ) as vocab_handle: _snake_case = json.load(lowercase ) with open(lowercase , encoding='utf-8' ) as vocab_handle: _snake_case = json.load(lowercase ) _snake_case = 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: _snake_case = oov.replace(R'\-\'' , R'\-+\'' ) _snake_case = regex.compile(lowercase ) _snake_case = {v: k for k, v in self.artists_encoder.items()} _snake_case = {v: k for k, v in self.genres_encoder.items()} _snake_case = {v: k for k, v in self.lyrics_encoder.items()} @property def A ( self : Optional[int] ): '''simple docstring''' return len(self.artists_encoder ) + len(self.genres_encoder ) + len(self.lyrics_encoder ) def A ( self : Tuple ): '''simple docstring''' return dict(self.artists_encoder , self.genres_encoder , self.lyrics_encoder ) def A ( self : Optional[int] , lowercase : List[Any] , lowercase : List[str] , lowercase : str ): '''simple docstring''' _snake_case = [self.artists_encoder.get(lowercase , 0 ) for artist in list_artists] for genres in range(len(lowercase ) ): _snake_case = [self.genres_encoder.get(lowercase , 0 ) for genre in list_genres[genres]] _snake_case = list_genres[genres] + [-1] * (self.n_genres - len(list_genres[genres] )) _snake_case = [[self.lyrics_encoder.get(lowercase , 0 ) for character in list_lyrics[0]], [], []] return artists_id, list_genres, lyric_ids def A ( self : List[Any] , lowercase : List[str] ): '''simple docstring''' return list(lowercase ) def A ( self : Tuple , lowercase : Tuple , lowercase : Dict , lowercase : Optional[int] , **lowercase : List[Any] ): '''simple docstring''' _snake_case , _snake_case , _snake_case = self.prepare_for_tokenization(lowercase , lowercase , lowercase ) _snake_case = self._tokenize(lowercase ) return artist, genre, lyrics def A ( self : Any , lowercase : str , lowercase : str , lowercase : str , lowercase : bool = False ): '''simple docstring''' for idx in range(len(self.version ) ): if self.version[idx] == "v3": _snake_case = artists[idx].lower() _snake_case = [genres[idx].lower()] else: _snake_case = self._normalize(artists[idx] ) + '.v2' _snake_case = [ self._normalize(lowercase ) + '.v2' for genre in genres[idx].split('_' ) ] # split is for the full dictionary with combined genres if self.version[0] == "v2": _snake_case = regex.compile(R'[^A-Za-z0-9.,:;!?\-\'\"()\[\] \t\n]+' ) _snake_case = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,:;!?-+\'\"()[] \t\n' _snake_case = {vocab[index]: index + 1 for index in range(len(lowercase ) )} _snake_case = 0 _snake_case = len(lowercase ) + 1 _snake_case = self.vocab _snake_case = {v: k for k, v in self.vocab.items()} _snake_case = '' else: _snake_case = regex.compile(R'[^A-Za-z0-9.,:;!?\-+\'\"()\[\] \t\n]+' ) _snake_case = self._run_strip_accents(lowercase ) _snake_case = lyrics.replace('\\' , '\n' ) _snake_case = self.out_of_vocab.sub('' , lowercase ), [], [] return artists, genres, lyrics def A ( self : Union[str, Any] , lowercase : List[str] ): '''simple docstring''' _snake_case = unicodedata.normalize('NFD' , lowercase ) _snake_case = [] for char in text: _snake_case = unicodedata.category(lowercase ) if cat == "Mn": continue output.append(lowercase ) return "".join(lowercase ) def A ( self : Tuple , lowercase : str ): '''simple docstring''' _snake_case = ( [chr(lowercase ) for i in range(ord('a' ) , ord('z' ) + 1 )] + [chr(lowercase ) for i in range(ord('A' ) , ord('Z' ) + 1 )] + [chr(lowercase ) for i in range(ord('0' ) , ord('9' ) + 1 )] + ['.'] ) _snake_case = frozenset(lowercase ) _snake_case = re.compile(R'_+' ) _snake_case = ''.join([c if c in accepted else '_' for c in text.lower()] ) _snake_case = pattern.sub('_' , lowercase ).strip('_' ) return text def A ( self : Any , lowercase : List[str] ): '''simple docstring''' return " ".join(lowercase ) def A ( self : Optional[Any] , lowercase : Optional[int] , lowercase : Optional[Union[str, TensorType]] = None , lowercase : bool = False ): '''simple docstring''' if not isinstance(lowercase , lowercase ): _snake_case = TensorType(lowercase ) # 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 _snake_case = tf.constant _snake_case = 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 _snake_case = torch.tensor _snake_case = 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 _snake_case = jnp.array _snake_case = _is_jax else: _snake_case = np.asarray _snake_case = _is_numpy # Do the tensor conversion in batch try: if prepend_batch_axis: _snake_case = [inputs] if not is_tensor(lowercase ): _snake_case = as_tensor(lowercase ) 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 : Optional[Any] , lowercase : Optional[int] , lowercase : Tuple , lowercase : Tuple="" , lowercase : Any="pt" ): '''simple docstring''' _snake_case = [0, 0, 0] _snake_case = [artist] * len(self.version ) _snake_case = [genres] * len(self.version ) _snake_case , _snake_case , _snake_case = self.tokenize(lowercase , lowercase , lowercase ) _snake_case , _snake_case , _snake_case = self._convert_token_to_id(lowercase , lowercase , lowercase ) _snake_case = [-INFINITY] * len(full_tokens[-1] ) _snake_case = [ self.convert_to_tensors( [input_ids + [artists_id[i]] + genres_ids[i] + full_tokens[i]] , tensor_type=lowercase ) for i in range(len(self.version ) ) ] return BatchEncoding({'input_ids': input_ids, 'attention_masks': attention_masks} ) def A ( self : Dict , lowercase : str , lowercase : Optional[str] = None ): '''simple docstring''' if not os.path.isdir(lowercase ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return _snake_case = os.path.join( lowercase , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['artists_file'] ) with open(lowercase , 'w' , encoding='utf-8' ) as f: f.write(json.dumps(self.artists_encoder , ensure_ascii=lowercase ) ) _snake_case = os.path.join( lowercase , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['genres_file'] ) with open(lowercase , 'w' , encoding='utf-8' ) as f: f.write(json.dumps(self.genres_encoder , ensure_ascii=lowercase ) ) _snake_case = os.path.join( lowercase , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['lyrics_file'] ) with open(lowercase , 'w' , encoding='utf-8' ) as f: f.write(json.dumps(self.lyrics_encoder , ensure_ascii=lowercase ) ) return (artists_file, genres_file, lyrics_file) def A ( self : Optional[Any] , lowercase : str , lowercase : List[str] , lowercase : Any ): '''simple docstring''' _snake_case = self.artists_decoder.get(lowercase ) _snake_case = [self.genres_decoder.get(lowercase ) for genre in genres_index] _snake_case = [self.lyrics_decoder.get(lowercase ) for character in lyric_index] return artist, genres, lyrics
282
import os from typing import Any, Callable, Dict, List, Optional, Tuple, Union import torch from torch import nn from ...models.controlnet import ControlNetModel, ControlNetOutput from ...models.modeling_utils import ModelMixin from ...utils import logging _lowerCamelCase : List[str] = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE__ ( UpperCAmelCase ): '''simple docstring''' def __init__( self : Dict , lowercase : Union[List[ControlNetModel], Tuple[ControlNetModel]] ): '''simple docstring''' super().__init__() _snake_case = nn.ModuleList(lowercase ) def A ( self : Optional[int] , lowercase : torch.FloatTensor , lowercase : Union[torch.Tensor, float, int] , lowercase : torch.Tensor , lowercase : List[torch.tensor] , lowercase : List[float] , lowercase : Optional[torch.Tensor] = None , lowercase : Optional[torch.Tensor] = None , lowercase : Optional[torch.Tensor] = None , lowercase : Optional[Dict[str, Any]] = None , lowercase : bool = False , lowercase : bool = True , ): '''simple docstring''' for i, (image, scale, controlnet) in enumerate(zip(lowercase , lowercase , self.nets ) ): _snake_case , _snake_case = controlnet( lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , ) # merge samples if i == 0: _snake_case , _snake_case = down_samples, mid_sample else: _snake_case = [ samples_prev + samples_curr for samples_prev, samples_curr in zip(lowercase , lowercase ) ] mid_block_res_sample += mid_sample return down_block_res_samples, mid_block_res_sample def A ( self : Dict , lowercase : Union[str, os.PathLike] , lowercase : bool = True , lowercase : Callable = None , lowercase : bool = False , lowercase : Optional[str] = None , ): '''simple docstring''' _snake_case = 0 _snake_case = save_directory for controlnet in self.nets: controlnet.save_pretrained( lowercase , is_main_process=lowercase , save_function=lowercase , safe_serialization=lowercase , variant=lowercase , ) idx += 1 _snake_case = model_path_to_save + f'''_{idx}''' @classmethod def A ( cls : Any , lowercase : Optional[Union[str, os.PathLike]] , **lowercase : List[str] ): '''simple docstring''' _snake_case = 0 _snake_case = [] # load controlnet and append to list until no controlnet directory exists anymore # first controlnet has to be saved under `./mydirectory/controlnet` to be compliant with `DiffusionPipeline.from_prertained` # second, third, ... controlnets have to be saved under `./mydirectory/controlnet_1`, `./mydirectory/controlnet_2`, ... _snake_case = pretrained_model_path while os.path.isdir(lowercase ): _snake_case = ControlNetModel.from_pretrained(lowercase , **lowercase ) controlnets.append(lowercase ) idx += 1 _snake_case = pretrained_model_path + f'''_{idx}''' logger.info(f'''{len(lowercase )} controlnets loaded from {pretrained_model_path}.''' ) if len(lowercase ) == 0: raise ValueError( f'''No ControlNets found under {os.path.dirname(lowercase )}. Expected at least {pretrained_model_path + '_0'}.''' ) return cls(lowercase )
282
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 __snake_case : Tuple =logging.get_logger(__name__) __snake_case : Tuple ={ 'google/mobilenet_v1_1.0_224': 'https://huggingface.co/google/mobilenet_v1_1.0_224/resolve/main/config.json', 'google/mobilenet_v1_0.75_192': 'https://huggingface.co/google/mobilenet_v1_0.75_192/resolve/main/config.json', # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1 } class lowerCamelCase__ ( lowerCamelCase__): '''simple docstring''' snake_case_ ="""mobilenet_v1""" def __init__(self ,__lowerCamelCase=3 ,__lowerCamelCase=2_24 ,__lowerCamelCase=1.0 ,__lowerCamelCase=8 ,__lowerCamelCase="relu6" ,__lowerCamelCase=True ,__lowerCamelCase=0.999 ,__lowerCamelCase=0.02 ,__lowerCamelCase=0.001 ,**__lowerCamelCase ,) -> List[Any]: """simple docstring""" super().__init__(**__lowerCamelCase ) if depth_multiplier <= 0: raise ValueError('''depth_multiplier must be greater than zero.''' ) lowerCAmelCase__ : Any = num_channels lowerCAmelCase__ : Optional[Any] = image_size lowerCAmelCase__ : Optional[int] = depth_multiplier lowerCAmelCase__ : Optional[int] = min_depth lowerCAmelCase__ : int = hidden_act lowerCAmelCase__ : List[Any] = tf_padding lowerCAmelCase__ : List[str] = classifier_dropout_prob lowerCAmelCase__ : List[Any] = initializer_range lowerCAmelCase__ : Optional[int] = layer_norm_eps class lowerCamelCase__ ( lowerCamelCase__): '''simple docstring''' snake_case_ =version.parse("""1.11""") @property def lowerCAmelCase__ (self ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" return OrderedDict([('''pixel_values''', {0: '''batch'''})] ) @property def lowerCAmelCase__ (self ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" if self.task == "image-classification": return OrderedDict([('''logits''', {0: '''batch'''})] ) else: return OrderedDict([('''last_hidden_state''', {0: '''batch'''}), ('''pooler_output''', {0: '''batch'''})] ) @property def lowerCAmelCase__ (self ) -> float: """simple docstring""" return 1e-4
368
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __snake_case : Any ={ 'configuration_blenderbot_small': [ 'BLENDERBOT_SMALL_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BlenderbotSmallConfig', 'BlenderbotSmallOnnxConfig', ], 'tokenization_blenderbot_small': ['BlenderbotSmallTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case : Union[str, Any] =['BlenderbotSmallTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case : List[str] =[ 'BLENDERBOT_SMALL_PRETRAINED_MODEL_ARCHIVE_LIST', 'BlenderbotSmallForCausalLM', 'BlenderbotSmallForConditionalGeneration', 'BlenderbotSmallModel', 'BlenderbotSmallPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case : str =[ 'TFBlenderbotSmallForConditionalGeneration', 'TFBlenderbotSmallModel', 'TFBlenderbotSmallPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case : Dict =[ 'FlaxBlenderbotSmallForConditionalGeneration', 'FlaxBlenderbotSmallModel', 'FlaxBlenderbotSmallPreTrainedModel', ] if TYPE_CHECKING: from .configuration_blenderbot_small import ( BLENDERBOT_SMALL_PRETRAINED_CONFIG_ARCHIVE_MAP, BlenderbotSmallConfig, BlenderbotSmallOnnxConfig, ) from .tokenization_blenderbot_small import BlenderbotSmallTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_blenderbot_small_fast import BlenderbotSmallTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blenderbot_small import ( BLENDERBOT_SMALL_PRETRAINED_MODEL_ARCHIVE_LIST, BlenderbotSmallForCausalLM, BlenderbotSmallForConditionalGeneration, BlenderbotSmallModel, BlenderbotSmallPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blenderbot_small import ( TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel, TFBlenderbotSmallPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_blenderbot_small import ( FlaxBlenderbotSmallForConditionalGeneration, FlaxBlenderbotSmallModel, FlaxBlenderbotSmallPreTrainedModel, ) else: import sys __snake_case : Optional[int] =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
94
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCAmelCase_ = {'''configuration_opt''': ['''OPT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''OPTConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ '''OPT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''OPTForCausalLM''', '''OPTModel''', '''OPTPreTrainedModel''', '''OPTForSequenceClassification''', '''OPTForQuestionAnswering''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = ['''TFOPTForCausalLM''', '''TFOPTModel''', '''TFOPTPreTrainedModel'''] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ '''FlaxOPTForCausalLM''', '''FlaxOPTModel''', '''FlaxOPTPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_opt import OPT_PRETRAINED_CONFIG_ARCHIVE_MAP, OPTConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_opt import ( OPT_PRETRAINED_MODEL_ARCHIVE_LIST, OPTForCausalLM, OPTForQuestionAnswering, OPTForSequenceClassification, OPTModel, OPTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_opt import TFOPTForCausalLM, TFOPTModel, TFOPTPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_opt import FlaxOPTForCausalLM, FlaxOPTModel, FlaxOPTPreTrainedModel else: import sys lowerCAmelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
8
'''simple docstring''' from __future__ import annotations class UpperCAmelCase : def __init__( self :Optional[int] , lowercase_ :int )-> None: A__ = order # a_{0} ... a_{k} A__ = [1.0] + [0.0] * order # b_{0} ... b_{k} A__ = [1.0] + [0.0] * order # x[n-1] ... x[n-k] A__ = [0.0] * self.order # y[n-1] ... y[n-k] A__ = [0.0] * self.order def UpperCAmelCase_ ( self :List[str] , lowercase_ :list[float] , lowercase_ :list[float] )-> None: if len(lowercase_ ) < self.order: A__ = [1.0, *a_coeffs] if len(lowercase_ ) != self.order + 1: A__ = ( F"Expected a_coeffs to have {self.order + 1} elements " F"for {self.order}-order filter, got {len(lowercase_ )}" ) raise ValueError(lowercase_ ) if len(lowercase_ ) != self.order + 1: A__ = ( F"Expected b_coeffs to have {self.order + 1} elements " F"for {self.order}-order filter, got {len(lowercase_ )}" ) raise ValueError(lowercase_ ) A__ = a_coeffs A__ = b_coeffs def UpperCAmelCase_ ( self :Optional[int] , lowercase_ :float )-> float: A__ = 0.0 # Start at index 1 and do index 0 at the end. for i in range(1 , self.order + 1 ): result += ( self.b_coeffs[i] * self.input_history[i - 1] - self.a_coeffs[i] * self.output_history[i - 1] ) A__ = (result + self.b_coeffs[0] * sample) / self.a_coeffs[0] A__ = self.input_history[:-1] A__ = self.output_history[:-1] A__ = sample A__ = result return result
237
0
"""simple docstring""" __A = range(2, 20 + 1) __A = [10**k for k in range(ks[-1] + 1)] __A = {} def a__ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> Any: __lowerCAmelCase: Dict = sum(a_i[j] for j in range(__SCREAMING_SNAKE_CASE , len(__SCREAMING_SNAKE_CASE ) ) ) __lowerCAmelCase: Tuple = sum(a_i[j] * base[j] for j in range(min(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) ) ) __lowerCAmelCase: Optional[Any] = 0, 0 __lowerCAmelCase: Tuple = n - i __lowerCAmelCase: Optional[int] = memo.get(__SCREAMING_SNAKE_CASE ) if sub_memo is not None: __lowerCAmelCase: List[str] = sub_memo.get(__SCREAMING_SNAKE_CASE ) if jumps is not None and len(__SCREAMING_SNAKE_CASE ) > 0: # find and make the largest jump without going over __lowerCAmelCase: Union[str, Any] = -1 for _k in range(len(__SCREAMING_SNAKE_CASE ) - 1 , -1 , -1 ): if jumps[_k][2] <= k and jumps[_k][1] <= max_dn: __lowerCAmelCase: Any = _k break if max_jump >= 0: __lowerCAmelCase: Dict = jumps[max_jump] # since the difference between jumps is cached, add c __lowerCAmelCase: Tuple = diff + c for j in range(min(__SCREAMING_SNAKE_CASE , len(__SCREAMING_SNAKE_CASE ) ) ): __lowerCAmelCase: int = divmod(__SCREAMING_SNAKE_CASE , 1_0 ) if new_c > 0: add(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else: __lowerCAmelCase: Optional[int] = [] else: __lowerCAmelCase: int = {c: []} __lowerCAmelCase: Union[str, Any] = sub_memo if dn >= max_dn or c + diff >= base[k]: return diff, dn if k > ks[0]: while True: # keep doing smaller jumps __lowerCAmelCase: Any = next_term(__SCREAMING_SNAKE_CASE , k - 1 , i + dn , __SCREAMING_SNAKE_CASE ) diff += _diff dn += terms_jumped if dn >= max_dn or c + diff >= base[k]: break else: # would be too small a jump, just compute sequential terms instead __lowerCAmelCase: Tuple = compute(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , i + dn , __SCREAMING_SNAKE_CASE ) diff += _diff dn += terms_jumped __lowerCAmelCase: Tuple = sub_memo[c] # keep jumps sorted by # of terms skipped __lowerCAmelCase: Any = 0 while j < len(__SCREAMING_SNAKE_CASE ): if jumps[j][1] > dn: break j += 1 # cache the jump for this value digitsum(b) and c sub_memo[c].insert(__SCREAMING_SNAKE_CASE , (diff, dn, k) ) return (diff, dn) def a__ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> int: if i >= n: return 0, i if k > len(__SCREAMING_SNAKE_CASE ): a_i.extend([0 for _ in range(k - len(__SCREAMING_SNAKE_CASE ) )] ) # note: a_i -> b * 10^k + c # ds_b -> digitsum(b) # ds_c -> digitsum(c) __lowerCAmelCase: List[Any] = i __lowerCAmelCase: Optional[int] = 0, 0, 0 for j in range(len(__SCREAMING_SNAKE_CASE ) ): if j >= k: ds_b += a_i[j] else: ds_c += a_i[j] while i < n: i += 1 __lowerCAmelCase: int = ds_c + ds_b diff += addend __lowerCAmelCase: Union[str, Any] = 0 for j in range(__SCREAMING_SNAKE_CASE ): __lowerCAmelCase: Tuple = a_i[j] + addend __lowerCAmelCase: Optional[Any] = divmod(__SCREAMING_SNAKE_CASE , 1_0 ) ds_c += a_i[j] if addend > 0: break if addend > 0: add(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) return diff, i - start_i def a__ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> Tuple: for j in range(__SCREAMING_SNAKE_CASE , len(__SCREAMING_SNAKE_CASE ) ): __lowerCAmelCase: List[str] = digits[j] + addend if s >= 1_0: __lowerCAmelCase: Union[str, Any] = divmod(__SCREAMING_SNAKE_CASE , 1_0 ) __lowerCAmelCase: Dict = addend // 1_0 + quotient else: __lowerCAmelCase: Union[str, Any] = s __lowerCAmelCase: Any = addend // 1_0 if addend == 0: break while addend > 0: __lowerCAmelCase: Union[str, Any] = divmod(__SCREAMING_SNAKE_CASE , 1_0 ) digits.append(__SCREAMING_SNAKE_CASE ) def a__ ( __SCREAMING_SNAKE_CASE = 1_0**1_5 ) -> int: __lowerCAmelCase: Any = [1] __lowerCAmelCase: Any = 1 __lowerCAmelCase: Tuple = 0 while True: __lowerCAmelCase: Union[str, Any] = next_term(__SCREAMING_SNAKE_CASE , 2_0 , i + dn , __SCREAMING_SNAKE_CASE ) dn += terms_jumped if dn == n - i: break __lowerCAmelCase: Optional[Any] = 0 for j in range(len(__SCREAMING_SNAKE_CASE ) ): a_n += digits[j] * 1_0**j return a_n if __name__ == "__main__": print(F'''{solution() = }''')
354
"""simple docstring""" # Lint as: python3 import os import re import urllib.parse from pathlib import Path from typing import Callable, List, Optional, Union from zipfile import ZipFile from ..utils.file_utils import cached_path, hf_github_url from ..utils.logging import get_logger from ..utils.version import Version __A = get_logger(__name__) class snake_case : SCREAMING_SNAKE_CASE_ : List[Any] = """dummy_data""" SCREAMING_SNAKE_CASE_ : List[Any] = """datasets""" SCREAMING_SNAKE_CASE_ : Any = False def __init__( self : List[str] , UpperCamelCase__ : str , UpperCamelCase__ : str , UpperCamelCase__ : Union[Version, str] , UpperCamelCase__ : Optional[str] = None , UpperCamelCase__ : bool = False , UpperCamelCase__ : bool = True , UpperCamelCase__ : Optional[List[Callable]] = None , )-> Optional[Any]: '''simple docstring''' __lowerCAmelCase: Optional[Any] = 0 __lowerCAmelCase: Tuple = dataset_name __lowerCAmelCase: Optional[Any] = cache_dir __lowerCAmelCase: Optional[int] = use_local_dummy_data __lowerCAmelCase: Optional[Any] = config # download_callbacks take a single url as input __lowerCAmelCase: List[Callable] = download_callbacks or [] # if False, it doesn't load existing files and it returns the paths of the dummy files relative # to the dummy_data zip file root __lowerCAmelCase: Union[str, Any] = load_existing_dummy_data # TODO(PVP, QL) might need to make this more general __lowerCAmelCase: List[str] = str(UpperCamelCase__) # to be downloaded __lowerCAmelCase: Dict = None __lowerCAmelCase: Dict = None @property def lowercase_ ( self : List[str])-> str: '''simple docstring''' if self._dummy_file is None: __lowerCAmelCase: Tuple = self.download_dummy_data() return self._dummy_file @property def lowercase_ ( self : Dict)-> Optional[Any]: '''simple docstring''' if self.config is not None: # structure is dummy / config_name / version_name return os.path.join("dummy" , self.config.name , self.version_name) # structure is dummy / version_name return os.path.join("dummy" , self.version_name) @property def lowercase_ ( self : List[str])-> Any: '''simple docstring''' return os.path.join(self.dummy_data_folder , "dummy_data.zip") def lowercase_ ( self : Optional[Any])-> List[str]: '''simple docstring''' __lowerCAmelCase: Dict = ( self.local_path_to_dummy_data if self.use_local_dummy_data is True else self.github_path_to_dummy_data ) __lowerCAmelCase: str = cached_path( UpperCamelCase__ , cache_dir=self.cache_dir , extract_compressed_file=UpperCamelCase__ , force_extract=UpperCamelCase__) return os.path.join(UpperCamelCase__ , self.dummy_file_name) @property def lowercase_ ( self : Dict)-> List[Any]: '''simple docstring''' return os.path.join(self.datasets_scripts_dir , self.dataset_name , self.dummy_zip_file) @property def lowercase_ ( self : Optional[Any])-> Tuple: '''simple docstring''' if self._bucket_url is None: __lowerCAmelCase: int = hf_github_url(self.dataset_name , self.dummy_zip_file.replace(os.sep , "/")) return self._bucket_url @property def lowercase_ ( self : str)-> Optional[int]: '''simple docstring''' if os.path.isdir(self.dummy_file): return self.dummy_file # else cut off path to file -> example `xsum`. return "/".join(self.dummy_file.replace(os.sep , "/").split("/")[:-1]) def lowercase_ ( self : List[Any] , UpperCamelCase__ : int , *UpperCamelCase__ : List[str])-> Optional[int]: '''simple docstring''' if self.load_existing_dummy_data: # dummy data is downloaded and tested __lowerCAmelCase: List[Any] = self.dummy_file else: # dummy data cannot be downloaded and only the path to dummy file is returned __lowerCAmelCase: str = self.dummy_file_name # special case when data_url is a dict if isinstance(UpperCamelCase__ , UpperCamelCase__): return self.create_dummy_data_dict(UpperCamelCase__ , UpperCamelCase__) elif isinstance(UpperCamelCase__ , (list, tuple)): return self.create_dummy_data_list(UpperCamelCase__ , UpperCamelCase__) else: return self.create_dummy_data_single(UpperCamelCase__ , UpperCamelCase__) def lowercase_ ( self : Dict , UpperCamelCase__ : Dict , *UpperCamelCase__ : int)-> Dict: '''simple docstring''' return self.download_and_extract(UpperCamelCase__) def lowercase_ ( self : Optional[Any] , UpperCamelCase__ : Dict , UpperCamelCase__ : Optional[Any])-> str: '''simple docstring''' return self.download_and_extract(UpperCamelCase__) def lowercase_ ( self : Optional[Any] , UpperCamelCase__ : List[Any] , *UpperCamelCase__ : int , **UpperCamelCase__ : str)-> List[str]: '''simple docstring''' return path def lowercase_ ( self : Optional[Any])-> Any: '''simple docstring''' return {} def lowercase_ ( self : Any , UpperCamelCase__ : Tuple , UpperCamelCase__ : int)-> Optional[Any]: '''simple docstring''' __lowerCAmelCase: Optional[int] = {} for key, single_urls in data_url.items(): for download_callback in self.download_callbacks: if isinstance(UpperCamelCase__ , UpperCamelCase__): for single_url in single_urls: download_callback(UpperCamelCase__) else: __lowerCAmelCase: Union[str, Any] = single_urls download_callback(UpperCamelCase__) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus if isinstance(UpperCamelCase__ , UpperCamelCase__): __lowerCAmelCase: Dict = [os.path.join(UpperCamelCase__ , urllib.parse.quote_plus(Path(UpperCamelCase__).name)) for x in single_urls] else: __lowerCAmelCase: Any = single_urls __lowerCAmelCase: Optional[int] = os.path.join(UpperCamelCase__ , urllib.parse.quote_plus(Path(UpperCamelCase__).name)) __lowerCAmelCase: Dict = value # make sure that values are unique if all(isinstance(UpperCamelCase__ , UpperCamelCase__) for i in dummy_data_dict.values()) and len(set(dummy_data_dict.values())) < len( dummy_data_dict.values()): # append key to value to make its name unique __lowerCAmelCase: Any = {key: value + key for key, value in dummy_data_dict.items()} return dummy_data_dict def lowercase_ ( self : Optional[int] , UpperCamelCase__ : int , UpperCamelCase__ : List[Any])-> int: '''simple docstring''' __lowerCAmelCase: Tuple = [] # trick: if there are many shards named like `data.txt-000001-of-00300`, only use the first one __lowerCAmelCase: Any = all(bool(re.findall("[0-9]{3,}-of-[0-9]{3,}" , UpperCamelCase__)) for url in data_url) __lowerCAmelCase: str = all( url.startswith("https://ftp.ncbi.nlm.nih.gov/pubmed/baseline/pubmed") for url in data_url) if data_url and (is_tf_records or is_pubmed_records): __lowerCAmelCase: Optional[int] = [data_url[0]] * len(UpperCamelCase__) for single_url in data_url: for download_callback in self.download_callbacks: download_callback(UpperCamelCase__) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus __lowerCAmelCase: Optional[Any] = os.path.join(UpperCamelCase__ , urllib.parse.quote_plus(single_url.split("/")[-1])) dummy_data_list.append(UpperCamelCase__) return dummy_data_list def lowercase_ ( self : str , UpperCamelCase__ : Tuple , UpperCamelCase__ : Union[str, Any])-> Optional[int]: '''simple docstring''' for download_callback in self.download_callbacks: download_callback(UpperCamelCase__) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus __lowerCAmelCase: List[Any] = os.path.join(UpperCamelCase__ , urllib.parse.quote_plus(data_url.split("/")[-1])) if os.path.exists(UpperCamelCase__) or not self.load_existing_dummy_data: return value else: # Backward compatibility, maybe deprecate at one point. # For many datasets with single url calls to dl_manager.download_and_extract, # the dummy_data.zip file is actually the zipped downloaded file # while now we expected the dummy_data.zip file to be a directory containing # the downloaded file. return path_to_dummy_data def lowercase_ ( self : List[str])-> Dict: '''simple docstring''' pass def lowercase_ ( self : Union[str, Any])-> Tuple: '''simple docstring''' pass def lowercase_ ( self : Dict , UpperCamelCase__ : str)-> int: '''simple docstring''' def _iter_archive_members(UpperCamelCase__ : str): # this preserves the order of the members inside the ZIP archive __lowerCAmelCase: Optional[Any] = Path(self.dummy_file).parent __lowerCAmelCase: Optional[int] = path.relative_to(UpperCamelCase__) with ZipFile(self.local_path_to_dummy_data) as zip_file: __lowerCAmelCase: Optional[int] = zip_file.namelist() for member in members: if member.startswith(relative_path.as_posix()): yield dummy_parent_path.joinpath(UpperCamelCase__) __lowerCAmelCase: str = Path(UpperCamelCase__) __lowerCAmelCase: Optional[Any] = _iter_archive_members(UpperCamelCase__) if self.use_local_dummy_data else path.rglob("*") for file_path in file_paths: if file_path.is_file() and not file_path.name.startswith((".", "__")): yield file_path.relative_to(UpperCamelCase__).as_posix(), file_path.open("rb") def lowercase_ ( self : str , UpperCamelCase__ : str)-> str: '''simple docstring''' if not isinstance(UpperCamelCase__ , UpperCamelCase__): __lowerCAmelCase: Dict = [paths] for path in paths: if os.path.isfile(UpperCamelCase__): if os.path.basename(UpperCamelCase__).startswith((".", "__")): return yield path else: for dirpath, dirnames, filenames in os.walk(UpperCamelCase__): if os.path.basename(UpperCamelCase__).startswith((".", "__")): continue dirnames.sort() for filename in sorted(UpperCamelCase__): if filename.startswith((".", "__")): continue yield os.path.join(UpperCamelCase__ , UpperCamelCase__)
108
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging a_ :int = logging.get_logger(__name__) a_ :List[Any] = { "bert-base-uncased": "https://huggingface.co/bert-base-uncased/resolve/main/config.json", "bert-large-uncased": "https://huggingface.co/bert-large-uncased/resolve/main/config.json", "bert-base-cased": "https://huggingface.co/bert-base-cased/resolve/main/config.json", "bert-large-cased": "https://huggingface.co/bert-large-cased/resolve/main/config.json", "bert-base-multilingual-uncased": "https://huggingface.co/bert-base-multilingual-uncased/resolve/main/config.json", "bert-base-multilingual-cased": "https://huggingface.co/bert-base-multilingual-cased/resolve/main/config.json", "bert-base-chinese": "https://huggingface.co/bert-base-chinese/resolve/main/config.json", "bert-base-german-cased": "https://huggingface.co/bert-base-german-cased/resolve/main/config.json", "bert-large-uncased-whole-word-masking": ( "https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/config.json" ), "bert-large-cased-whole-word-masking": ( "https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/config.json" ), "bert-large-uncased-whole-word-masking-finetuned-squad": ( "https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/config.json" ), "bert-large-cased-whole-word-masking-finetuned-squad": ( "https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/config.json" ), "bert-base-cased-finetuned-mrpc": "https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/config.json", "bert-base-german-dbmdz-cased": "https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/config.json", "bert-base-german-dbmdz-uncased": "https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/config.json", "cl-tohoku/bert-base-japanese": "https://huggingface.co/cl-tohoku/bert-base-japanese/resolve/main/config.json", "cl-tohoku/bert-base-japanese-whole-word-masking": ( "https://huggingface.co/cl-tohoku/bert-base-japanese-whole-word-masking/resolve/main/config.json" ), "cl-tohoku/bert-base-japanese-char": ( "https://huggingface.co/cl-tohoku/bert-base-japanese-char/resolve/main/config.json" ), "cl-tohoku/bert-base-japanese-char-whole-word-masking": ( "https://huggingface.co/cl-tohoku/bert-base-japanese-char-whole-word-masking/resolve/main/config.json" ), "TurkuNLP/bert-base-finnish-cased-v1": ( "https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/config.json" ), "TurkuNLP/bert-base-finnish-uncased-v1": ( "https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/config.json" ), "wietsedv/bert-base-dutch-cased": "https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/config.json", # See all BERT models at https://huggingface.co/models?filter=bert } class snake_case__ ( lowerCAmelCase_ ): """simple docstring""" _SCREAMING_SNAKE_CASE = """bert""" def __init__( self : Optional[Any], _snake_case : Optional[Any]=3_0_5_2_2, _snake_case : Any=7_6_8, _snake_case : Tuple=1_2, _snake_case : Union[str, Any]=1_2, _snake_case : int=3_0_7_2, _snake_case : List[Any]="gelu", _snake_case : str=0.1, _snake_case : Tuple=0.1, _snake_case : Optional[Any]=5_1_2, _snake_case : int=2, _snake_case : List[str]=0.0_2, _snake_case : Optional[int]=1e-12, _snake_case : Optional[Any]=0, _snake_case : Union[str, Any]="absolute", _snake_case : Any=True, _snake_case : Union[str, Any]=None, **_snake_case : str, ) ->str: super().__init__(pad_token_id=_snake_case, **_snake_case ) snake_case__ : Dict = vocab_size snake_case__ : Union[str, Any] = hidden_size snake_case__ : Union[str, Any] = num_hidden_layers snake_case__ : List[Any] = num_attention_heads snake_case__ : List[str] = hidden_act snake_case__ : List[str] = intermediate_size snake_case__ : Union[str, Any] = hidden_dropout_prob snake_case__ : Union[str, Any] = attention_probs_dropout_prob snake_case__ : str = max_position_embeddings snake_case__ : Tuple = type_vocab_size snake_case__ : Tuple = initializer_range snake_case__ : Optional[int] = layer_norm_eps snake_case__ : List[Any] = position_embedding_type snake_case__ : Tuple = use_cache snake_case__ : Tuple = classifier_dropout class snake_case__ ( lowerCAmelCase_ ): """simple docstring""" @property def lowercase_ ( self : Any ) ->Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": snake_case__ : Dict = {0: 'batch', 1: 'choice', 2: 'sequence'} else: snake_case__ : int = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ('token_type_ids', dynamic_axis), ] )
277
import argparse import json import os import torch from torch import nn from transformers import NllbMoeConfig, NllbMoeModel from transformers.modeling_utils import dtype_byte_size from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME def lowercase_ (A : List[str] ): snake_case__ : Tuple = [ 'encoder.version', 'decoder.version', 'model.encoder.version', 'model.decoder.version', 'decoder.output_projection.weight', '_float_tensor', 'encoder.embed_positions._float_tensor', 'decoder.embed_positions._float_tensor', ] for k in ignore_keys: state_dict.pop(A , A ) def lowercase_ (A : str ): snake_case__ , snake_case__ : Union[str, Any] = emb.weight.shape snake_case__ : str = nn.Linear(A , A , bias=A ) snake_case__ : str = emb.weight.data return lin_layer def lowercase_ (A : Optional[int] , A : Union[str, Any]=None ): snake_case__ : Any = {} for old_key in state_dict.keys(): snake_case__ : Tuple = old_key if "moe_layer.experts." in key: if expert_idx is not None: snake_case__ : int = key.replace('moe_layer.experts.0' , F'''ffn.experts.expert_{expert_idx}''' ) else: snake_case__ : Any = key.replace('moe_layer.experts.' , 'ffn.experts.expert_' ) if "gate" in key: snake_case__ : Dict = key.replace('.moe_layer.gate.wg' , '.ffn.router.classifier' ) if "fc2" and "experts" not in key: snake_case__ : str = key.replace('.fc2.' , '.ffn.fc2.' ) if "fc1" and "experts" not in key: snake_case__ : str = key.replace('.fc1.' , '.ffn.fc1.' ) if ".encoder_attn." in key: snake_case__ : Tuple = key.replace('.encoder_attn.' , '.cross_attention.' ) if "encoder_attn_layer_norm" in key: snake_case__ : Tuple = key.replace('encoder_attn_layer_norm' , 'cross_attention_layer_norm' ) if "final_layer_norm" in key: snake_case__ : Optional[int] = key.replace('final_layer_norm' , 'ff_layer_norm' ) snake_case__ : Dict = state_dict[old_key] return new_dict def lowercase_ (A : List[Any] , A : Tuple , A : List[Any] , A : List[str] , A : str = WEIGHTS_NAME ): snake_case__ : Dict = [] snake_case__ : str = 0 os.makedirs(A , exist_ok=A ) for expert in range(A ): snake_case__ : Tuple = switch_checkpoint_path + F'''-rank-{expert}.pt''' if os.path.isfile(A ): snake_case__ : Optional[Any] = torch.load(A )['model'] remove_ignore_keys_(A ) snake_case__ : Optional[Any] = rename_fairseq_keys(A , A ) snake_case__ : Dict = os.path.join( A , weights_name.replace('.bin' , F'''-{len(A )+1:05d}-of-???.bin''' ) ) torch.save(A , A ) sharded_state_dicts.append(expert_state.keys() ) total_size += sum([value.numel() for key, value in expert_state.items()] ) * dtype_byte_size( expert_state[list(A )[0]].dtype ) # Add the last block snake_case__ : Tuple = os.path.join(A , weights_name.replace('.bin' , F'''-{len(A )+1:05d}-of-???.bin''' ) ) snake_case__ : Union[str, Any] = torch.load(switch_checkpoint_path + '-shared.pt' )['model'] remove_ignore_keys_(A ) snake_case__ : str = rename_fairseq_keys(A , A ) snake_case__ : Any = shared_weights['decoder.embed_tokens.weight'] sharded_state_dicts.append(shared_weights.keys() ) # If we only have the shared weights (dummy model/experts saved on the same file) if len(A ) == 1: snake_case__ : Any = os.path.join(A , A ) torch.save(A , A ) return {weights_name: sharded_state_dicts[0]}, None else: torch.save(A , A ) # Otherwise, let's build the index snake_case__ : Tuple = {} for idx, shard in enumerate(A ): snake_case__ : Optional[int] = weights_name.replace('.bin' , F'''-{idx+1:05d}-of-{len(A ):05d}.bin''' ) snake_case__ : List[Any] = os.path.join(A , weights_name.replace('.bin' , F'''-{idx+1:05d}-of-???.bin''' ) ) os.rename(A , os.path.join(A , A ) ) for key in shard: snake_case__ : Any = shard_file # Add the metadata snake_case__ : int = {'total_size': total_size} snake_case__ : Dict = {'metadata': metadata, 'weight_map': weight_map} with open(os.path.join(A , A ) , 'w' , encoding='utf-8' ) as f: snake_case__ : Any = json.dumps(A , indent=2 , sort_keys=A ) + '\n' f.write(A ) return metadata, index if __name__ == "__main__": a_ :int = argparse.ArgumentParser() # Required parameters parser.add_argument( "--nllb_moe_checkpoint_path", default="/home/arthur_huggingface_co/fairseq/weights/checkpoints/model_moe_54b/checkpoint_2_300000", type=str, required=False, help="Path to a directory containing a folder per layer. Follows the original Google format.", ) parser.add_argument("--dtype", default="float32", type=str, required=False, help="dtype of the saved model") parser.add_argument( "--pytorch_dump_folder_path", default="/home/arthur_huggingface_co/fairseq/weights/checkpoints/hf-converted-moe-54b", type=str, required=False, help="Path to the output pytorch model.", ) a_ :Optional[Any] = parser.parse_args() a_ , a_ :Optional[Any] = shard_on_the_fly( args.nllb_moe_checkpoint_path, args.pytorch_dump_folder_path, 128, args.dtype, ) a_ :List[str] = NllbMoeConfig.from_pretrained( "facebook/nllb-200-3.3B", encoder_sparse_step=4, decoder_sparse_step=4, num_experts=128 ) config.save_pretrained(args.pytorch_dump_folder_path) a_ :int = NllbMoeModel.from_pretrained(args.pytorch_dump_folder_path) print("Done") model.save_pretrained(args.pytorch_dump_folder_path)
277
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 : int = logging.get_logger(__name__) __UpperCAmelCase : Any = {"vocab_file": "vocab.json", "merges_file": "merges.txt"} # See all BART models at https://huggingface.co/models?filter=bart __UpperCAmelCase : str = { "vocab_file": { "facebook/bart-base": "https://huggingface.co/facebook/bart-base/resolve/main/vocab.json", "facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/vocab.json", "facebook/bart-large-mnli": "https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json", "facebook/bart-large-cnn": "https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json", "facebook/bart-large-xsum": "https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json", "yjernite/bart_eli5": "https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json", }, "merges_file": { "facebook/bart-base": "https://huggingface.co/facebook/bart-base/resolve/main/merges.txt", "facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/merges.txt", "facebook/bart-large-mnli": "https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt", "facebook/bart-large-cnn": "https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt", "facebook/bart-large-xsum": "https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt", "yjernite/bart_eli5": "https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt", }, } __UpperCAmelCase : Optional[int] = { "facebook/bart-base": 1_024, "facebook/bart-large": 1_024, "facebook/bart-large-mnli": 1_024, "facebook/bart-large-cnn": 1_024, "facebook/bart-large-xsum": 1_024, "yjernite/bart_eli5": 1_024, } @lru_cache() def A__ ( ) -> List[str]: __snake_case: Optional[int] = ( list(range(ord("""!""") , ord("""~""") + 1)) + list(range(ord("""¡""") , ord("""¬""") + 1)) + list(range(ord("""®""") , ord("""ÿ""") + 1)) ) __snake_case: int = bs[:] __snake_case: Union[str, Any] = 0 for b in range(2**8): if b not in bs: bs.append(SCREAMING_SNAKE_CASE__) cs.append(2**8 + n) n += 1 __snake_case: Dict = [chr(SCREAMING_SNAKE_CASE__) for n in cs] return dict(zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__)) def A__ ( SCREAMING_SNAKE_CASE__) -> str: __snake_case: List[str] = set() __snake_case: List[str] = word[0] for char in word[1:]: pairs.add((prev_char, char)) __snake_case: Optional[int] = char return pairs class __snake_case ( __lowerCamelCase ): '''simple docstring''' lowerCAmelCase__ = VOCAB_FILES_NAMES lowerCAmelCase__ = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase__ = ["""input_ids""", """attention_mask"""] def __init__( self : List[str] , A : Dict , A : str , A : List[str]="replace" , A : Any="<s>" , A : List[Any]="</s>" , A : Union[str, Any]="</s>" , A : List[str]="<s>" , A : Optional[int]="<unk>" , A : Union[str, Any]="<pad>" , A : List[str]="<mask>" , A : Dict=False , **A : List[str] , ): __snake_case: Optional[Any] = AddedToken(A , lstrip=A , rstrip=A ) if isinstance(A , A ) else bos_token __snake_case: int = AddedToken(A , lstrip=A , rstrip=A ) if isinstance(A , A ) else eos_token __snake_case: str = AddedToken(A , lstrip=A , rstrip=A ) if isinstance(A , A ) else sep_token __snake_case: Dict = AddedToken(A , lstrip=A , rstrip=A ) if isinstance(A , A ) else cls_token __snake_case: Optional[int] = AddedToken(A , lstrip=A , rstrip=A ) if isinstance(A , A ) else unk_token __snake_case: List[str] = AddedToken(A , lstrip=A , rstrip=A ) if isinstance(A , A ) else pad_token # Mask token behave like a normal word, i.e. include the space before it __snake_case: Any = AddedToken(A , lstrip=A , rstrip=A ) if isinstance(A , A ) else mask_token super().__init__( errors=A , bos_token=A , eos_token=A , unk_token=A , sep_token=A , cls_token=A , pad_token=A , mask_token=A , add_prefix_space=A , **A , ) with open(A , encoding="""utf-8""" ) as vocab_handle: __snake_case: str = json.load(A ) __snake_case: int = {v: k for k, v in self.encoder.items()} __snake_case: Optional[Any] = errors # how to handle errors in decoding __snake_case: str = bytes_to_unicode() __snake_case: Any = {v: k for k, v in self.byte_encoder.items()} with open(A , encoding="""utf-8""" ) as merges_handle: __snake_case: Dict = merges_handle.read().split("""\n""" )[1:-1] __snake_case: Optional[int] = [tuple(merge.split() ) for merge in bpe_merges] __snake_case: List[str] = dict(zip(A , range(len(A ) ) ) ) __snake_case: str = {} __snake_case: int = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions __snake_case: Optional[Any] = re.compile(r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""" ) @property def UpperCAmelCase__ ( self : List[str] ): return len(self.encoder ) def UpperCAmelCase__ ( self : List[str] ): return dict(self.encoder , **self.added_tokens_encoder ) def UpperCAmelCase__ ( self : Tuple , A : Union[str, Any] ): if token in self.cache: return self.cache[token] __snake_case: Any = tuple(A ) __snake_case: Optional[int] = get_pairs(A ) if not pairs: return token while True: __snake_case: List[str] = min(A , key=lambda A : self.bpe_ranks.get(A , float("""inf""" ) ) ) if bigram not in self.bpe_ranks: break __snake_case , __snake_case: Any = bigram __snake_case: Optional[int] = [] __snake_case: Union[str, Any] = 0 while i < len(A ): try: __snake_case: Optional[int] = word.index(A , A ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) __snake_case: Any = j if word[i] == first and i < len(A ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 __snake_case: List[Any] = tuple(A ) __snake_case: Dict = new_word if len(A ) == 1: break else: __snake_case: List[str] = get_pairs(A ) __snake_case: Optional[int] = """ """.join(A ) __snake_case: List[Any] = word return word def UpperCAmelCase__ ( self : Union[str, Any] , A : List[Any] ): __snake_case: str = [] for token in re.findall(self.pat , A ): __snake_case: int = """""".join( self.byte_encoder[b] for b in token.encode("""utf-8""" ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(A ).split(""" """ ) ) return bpe_tokens def UpperCAmelCase__ ( self : Union[str, Any] , A : int ): return self.encoder.get(A , self.encoder.get(self.unk_token ) ) def UpperCAmelCase__ ( self : str , A : Any ): return self.decoder.get(A ) def UpperCAmelCase__ ( self : Optional[int] , A : str ): __snake_case: Optional[Any] = """""".join(A ) __snake_case: Any = bytearray([self.byte_decoder[c] for c in text] ).decode("""utf-8""" , errors=self.errors ) return text def UpperCAmelCase__ ( self : Union[str, Any] , A : str , A : Optional[str] = None ): if not os.path.isdir(A ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __snake_case: Any = os.path.join( A , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) __snake_case: Optional[Any] = os.path.join( A , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""merges_file"""] ) with open(A , """w""" , encoding="""utf-8""" ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=A , ensure_ascii=A ) + """\n""" ) __snake_case: Any = 0 with open(A , """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 A : 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!""" ) __snake_case: Union[str, Any] = token_index writer.write(""" """.join(A ) + """\n""" ) index += 1 return vocab_file, merge_file def UpperCAmelCase__ ( self : Union[str, Any] , A : List[int] , A : Optional[List[int]] = None ): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __snake_case: Dict = [self.cls_token_id] __snake_case: Optional[int] = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def UpperCAmelCase__ ( self : List[str] , A : List[int] , A : Optional[List[int]] = None , A : bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=A , token_ids_a=A , already_has_special_tokens=A ) if token_ids_a is None: return [1] + ([0] * len(A )) + [1] return [1] + ([0] * len(A )) + [1, 1] + ([0] * len(A )) + [1] def UpperCAmelCase__ ( self : Any , A : List[int] , A : Optional[List[int]] = None ): __snake_case: Any = [self.sep_token_id] __snake_case: Union[str, Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def UpperCAmelCase__ ( self : int , A : str , A : str=False , **A : Optional[Any] ): __snake_case: List[Any] = kwargs.pop("""add_prefix_space""" , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(A ) > 0 and not text[0].isspace()): __snake_case: Any = """ """ + text return (text, kwargs)
293
from __future__ import annotations import numpy as np def A__ ( SCREAMING_SNAKE_CASE__) -> List[str]: return np.maximum(0 , SCREAMING_SNAKE_CASE__) if __name__ == "__main__": print(np.array(relu([-1, 0, 5]))) # --> [0, 0, 5]
293
1
import argparse import os import torch from transformers import FlavaConfig, FlavaForPreTraining from transformers.models.flava.convert_dalle_to_flava_codebook import convert_dalle_checkpoint def __magic_name__ ( __a : Dict ): '''simple docstring''' return sum(param.float().sum() if """encoder.embeddings""" not in key else 0 for key, param in state_dict.items() ) def __magic_name__ ( __a : Optional[Any] , __a : Optional[Any] ): '''simple docstring''' UpperCamelCase__ = {} for key, value in state_dict.items(): if "text_encoder.embeddings" in key or "image_encoder.embeddings" in key: continue UpperCamelCase__ = key.replace("""heads.cmd.mim_head.cls.predictions""" , """mmm_image_head""" ) UpperCamelCase__ = key.replace("""heads.cmd.mlm_head.cls.predictions""" , """mmm_text_head""" ) UpperCamelCase__ = key.replace("""heads.cmd.itm_head.cls""" , """itm_head""" ) UpperCamelCase__ = key.replace("""heads.cmd.itm_head.pooler""" , """itm_head.pooler""" ) UpperCamelCase__ = key.replace("""heads.cmd.clip_head.logit_scale""" , """flava.logit_scale""" ) UpperCamelCase__ = key.replace("""heads.fairseq_mlm.cls.predictions""" , """mlm_head""" ) UpperCamelCase__ = key.replace("""heads.imagenet.mim_head.cls.predictions""" , """mim_head""" ) UpperCamelCase__ = key.replace("""mm_text_projection""" , """flava.text_to_mm_projection""" ) UpperCamelCase__ = key.replace("""mm_image_projection""" , """flava.image_to_mm_projection""" ) UpperCamelCase__ = key.replace("""image_encoder.module""" , """flava.image_model""" ) UpperCamelCase__ = key.replace("""text_encoder.module""" , """flava.text_model""" ) UpperCamelCase__ = key.replace("""mm_encoder.module.encoder.cls_token""" , """flava.multimodal_model.cls_token""" ) UpperCamelCase__ = key.replace("""mm_encoder.module""" , """flava.multimodal_model""" ) UpperCamelCase__ = key.replace("""text_projection""" , """flava.text_projection""" ) UpperCamelCase__ = key.replace("""image_projection""" , """flava.image_projection""" ) UpperCamelCase__ = value.float() for key, value in codebook_state_dict.items(): UpperCamelCase__ = value return upgrade @torch.no_grad() def __magic_name__ ( __a : Dict , __a : Any , __a : int , __a : Any=None ): '''simple docstring''' if config_path is not None: UpperCamelCase__ = FlavaConfig.from_pretrained(a_ ) else: UpperCamelCase__ = FlavaConfig() UpperCamelCase__ = FlavaForPreTraining(a_ ).eval() UpperCamelCase__ = convert_dalle_checkpoint(a_ , a_ , save_checkpoint=a_ ) if os.path.exists(a_ ): UpperCamelCase__ = torch.load(a_ , map_location="""cpu""" ) else: UpperCamelCase__ = torch.hub.load_state_dict_from_url(a_ , map_location="""cpu""" ) UpperCamelCase__ = upgrade_state_dict(a_ , a_ ) hf_model.load_state_dict(a_ ) UpperCamelCase__ = hf_model.state_dict() UpperCamelCase__ = count_parameters(a_ ) UpperCamelCase__ = count_parameters(a_ ) + count_parameters(a_ ) assert torch.allclose(a_ , a_ , atol=1E-3 ) hf_model.save_pretrained(a_ ) if __name__ == "__main__": lowerCamelCase_ = argparse.ArgumentParser() parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to flava checkpoint''') parser.add_argument('''--codebook_path''', default=None, type=str, help='''Path to flava codebook checkpoint''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') lowerCamelCase_ = parser.parse_args() convert_flava_checkpoint(args.checkpoint_path, args.codebook_path, args.pytorch_dump_folder_path, args.config_path)
244
'''simple docstring''' import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_barthez import BarthezTokenizer else: __a = None __a = logging.get_logger(__name__) __a = {'vocab_file': 'sentencepiece.bpe.model', 'tokenizer_file': 'tokenizer.json'} __a = { 'vocab_file': { 'moussaKam/mbarthez': 'https://huggingface.co/moussaKam/mbarthez/resolve/main/sentencepiece.bpe.model', 'moussaKam/barthez': 'https://huggingface.co/moussaKam/barthez/resolve/main/sentencepiece.bpe.model', 'moussaKam/barthez-orangesum-title': ( 'https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/sentencepiece.bpe.model' ), }, 'tokenizer_file': { 'moussaKam/mbarthez': 'https://huggingface.co/moussaKam/mbarthez/resolve/main/tokenizer.json', 'moussaKam/barthez': 'https://huggingface.co/moussaKam/barthez/resolve/main/tokenizer.json', 'moussaKam/barthez-orangesum-title': ( 'https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/tokenizer.json' ), }, } __a = { 'moussaKam/mbarthez': 1_024, 'moussaKam/barthez': 1_024, 'moussaKam/barthez-orangesum-title': 1_024, } __a = '▁' class A__ ( UpperCamelCase ): """simple docstring""" UpperCamelCase_ : List[Any] = VOCAB_FILES_NAMES UpperCamelCase_ : Any = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase_ : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase_ : int = ['''input_ids''', '''attention_mask'''] UpperCamelCase_ : List[str] = BarthezTokenizer def __init__( self : Optional[Any] , lowerCAmelCase__ : List[str]=None , lowerCAmelCase__ : Any=None , lowerCAmelCase__ : str="<s>" , lowerCAmelCase__ : Tuple="</s>" , lowerCAmelCase__ : Dict="</s>" , lowerCAmelCase__ : Tuple="<s>" , lowerCAmelCase__ : Any="<unk>" , lowerCAmelCase__ : Any="<pad>" , lowerCAmelCase__ : List[str]="<mask>" , **lowerCAmelCase__ : Dict , ) -> List[str]: """simple docstring""" _UpperCAmelCase : List[Any] = AddedToken(lowerCAmelCase__ , lstrip=lowerCAmelCase__ , rstrip=lowerCAmelCase__ ) if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) else mask_token super().__init__( lowerCAmelCase__ , tokenizer_file=lowerCAmelCase__ , bos_token=lowerCAmelCase__ , eos_token=lowerCAmelCase__ , unk_token=lowerCAmelCase__ , sep_token=lowerCAmelCase__ , cls_token=lowerCAmelCase__ , pad_token=lowerCAmelCase__ , mask_token=lowerCAmelCase__ , **lowerCAmelCase__ , ) _UpperCAmelCase : Any = vocab_file _UpperCAmelCase : Optional[Any] = False if not self.vocab_file else True def _lowerCAmelCase ( self : Optional[int] , lowerCAmelCase__ : List[int] , lowerCAmelCase__ : Optional[List[int]] = None ) -> List[int]: """simple docstring""" if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] _UpperCAmelCase : Optional[Any] = [self.cls_token_id] _UpperCAmelCase : int = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def _lowerCAmelCase ( self : str , lowerCAmelCase__ : List[int] , lowerCAmelCase__ : Optional[List[int]] = None ) -> List[int]: """simple docstring""" _UpperCAmelCase : Any = [self.sep_token_id] _UpperCAmelCase : List[str] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def _lowerCAmelCase ( self : Any , lowerCAmelCase__ : str , lowerCAmelCase__ : Optional[str] = None ) -> Tuple[str]: """simple docstring""" if not self.can_save_slow_tokenizer: raise ValueError( "Your fast tokenizer does not have the necessary information to save the vocabulary for a slow " "tokenizer." ) if not os.path.isdir(lowerCAmelCase__ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return _UpperCAmelCase : List[str] = os.path.join( lowerCAmelCase__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(lowerCAmelCase__ ): copyfile(self.vocab_file , lowerCAmelCase__ ) return (out_vocab_file,)
145
0
from collections import namedtuple lowerCamelCase_ = namedtuple("""from_to""", """from_ to""") lowerCamelCase_ = { """cubicmeter""": from_to(1, 1), """litre""": from_to(0.001, 1_0_0_0), """kilolitre""": from_to(1, 1), """gallon""": from_to(0.00454, 264.172), """cubicyard""": from_to(0.76455, 1.30795), """cubicfoot""": from_to(0.028, 35.3147), """cup""": from_to(0.000236588, 4226.75), } def lowerCamelCase ( a_ , a_ , a_ ) -> float: if from_type not in METRIC_CONVERSION: raise ValueError( F'''Invalid \'from_type\' value: {from_type!r} Supported values are:\n''' + ', '.join(a_ ) ) if to_type not in METRIC_CONVERSION: raise ValueError( F'''Invalid \'to_type\' value: {to_type!r}. Supported values are:\n''' + ', '.join(a_ ) ) return value * METRIC_CONVERSION[from_type].from_ * METRIC_CONVERSION[to_type].to if __name__ == "__main__": import doctest doctest.testmod()
14
from __future__ import annotations import unittest import numpy as np from transformers import OPTConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import GPTaTokenizer, TFOPTForCausalLM, TFOPTModel def lowerCamelCase ( a_ , a_ , a_=None , a_=None ) -> int: if attention_mask is None: lowerCAmelCase_ = tf.cast(tf.math.not_equal(a_ , config.pad_token_id ) , tf.inta ) return {"input_ids": input_ids, "attention_mask": attention_mask} @require_tf class a_ : '''simple docstring''' __a: Tuple = OPTConfig __a: Optional[Any] = {} __a: Tuple = '''gelu''' def __init__( self , lowercase_ , lowercase_=1_3 , lowercase_=7 , lowercase_=True , lowercase_=False , lowercase_=9_9 , lowercase_=1_6 , lowercase_=2 , lowercase_=4 , lowercase_=4 , lowercase_="gelu" , lowercase_=0.1 , lowercase_=0.1 , lowercase_=2_0 , lowercase_=2 , lowercase_=1 , lowercase_=0 , lowercase_=1_6 , lowercase_=1_6 , ) -> Any: '''simple docstring''' lowerCAmelCase_ = parent lowerCAmelCase_ = batch_size lowerCAmelCase_ = seq_length lowerCAmelCase_ = is_training lowerCAmelCase_ = use_labels lowerCAmelCase_ = vocab_size lowerCAmelCase_ = hidden_size lowerCAmelCase_ = num_hidden_layers lowerCAmelCase_ = num_attention_heads lowerCAmelCase_ = intermediate_size lowerCAmelCase_ = hidden_act lowerCAmelCase_ = hidden_dropout_prob lowerCAmelCase_ = attention_probs_dropout_prob lowerCAmelCase_ = max_position_embeddings lowerCAmelCase_ = eos_token_id lowerCAmelCase_ = pad_token_id lowerCAmelCase_ = bos_token_id lowerCAmelCase_ = embed_dim lowerCAmelCase_ = word_embed_proj_dim lowerCAmelCase_ = False def _lowercase ( self ) -> Tuple: '''simple docstring''' lowerCAmelCase_ = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) lowerCAmelCase_ = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) lowerCAmelCase_ = tf.concat([input_ids, eos_tensor] , axis=1 ) lowerCAmelCase_ = self.config_cls( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , embed_dim=self.embed_dim , word_embed_proj_dim=self.word_embed_proj_dim , is_encoder_decoder=lowercase_ , **self.config_updates , ) lowerCAmelCase_ = prepare_opt_inputs_dict(lowercase_ , lowercase_ ) return config, inputs_dict def _lowercase ( self , lowercase_ , lowercase_ ) -> str: '''simple docstring''' lowerCAmelCase_ = TFOPTModel(config=lowercase_ ) lowerCAmelCase_ = inputs_dict['input_ids'] lowerCAmelCase_ = input_ids[:1, :] lowerCAmelCase_ = inputs_dict['attention_mask'][:1, :] lowerCAmelCase_ = 1 # first forward pass lowerCAmelCase_ = model(lowercase_ , attention_mask=lowercase_ , use_cache=lowercase_ ) lowerCAmelCase_ , lowerCAmelCase_ = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids lowerCAmelCase_ = ids_tensor((self.batch_size, 3) , config.vocab_size ) lowerCAmelCase_ = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and lowerCAmelCase_ = tf.concat([input_ids, next_tokens] , axis=-1 ) lowerCAmelCase_ = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) lowerCAmelCase_ = model(lowercase_ , attention_mask=lowercase_ )[0] lowerCAmelCase_ = model(lowercase_ , attention_mask=lowercase_ , past_key_values=lowercase_ )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice lowerCAmelCase_ = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) lowerCAmelCase_ = output_from_no_past[:, -3:, random_slice_idx] lowerCAmelCase_ = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(lowercase_ , lowercase_ , rtol=1e-3 ) @require_tf class a_ ( a_ , a_ , unittest.TestCase ): '''simple docstring''' __a: Optional[int] = (TFOPTModel, TFOPTForCausalLM) if is_tf_available() else () __a: Optional[Any] = (TFOPTForCausalLM,) if is_tf_available() else () __a: Union[str, Any] = ( {'''feature-extraction''': TFOPTModel, '''text-generation''': TFOPTForCausalLM} if is_tf_available() else {} ) __a: int = False __a: List[Any] = False __a: Dict = False __a: List[Any] = 1_0 def _lowercase ( self ) -> Tuple: '''simple docstring''' lowerCAmelCase_ = TFOPTModelTester(self ) lowerCAmelCase_ = ConfigTester(self , config_class=lowercase_ ) def _lowercase ( self ) -> List[Any]: '''simple docstring''' self.config_tester.run_common_tests() def _lowercase ( self ) -> Union[str, Any]: '''simple docstring''' lowerCAmelCase_ = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*lowercase_ ) def _lowercase ( self ) -> Optional[Any]: '''simple docstring''' lowerCAmelCase_ , lowerCAmelCase_ = self.model_tester.prepare_config_and_inputs_for_common() def _get_word_embedding_weight(lowercase_ , lowercase_ ): if hasattr(lowercase_ , 'weight' ): return embedding_layer.weight else: # Here we build the word embeddings weights if not exists. # And then we retry to get the attribute once built. model.build() if hasattr(lowercase_ , 'weight' ): return embedding_layer.weight else: return None for model_class in self.all_model_classes: for size in [config.vocab_size - 1_0, config.vocab_size + 1_0]: # build the embeddings lowerCAmelCase_ = model_class(config=lowercase_ ) lowerCAmelCase_ = _get_word_embedding_weight(lowercase_ , model.get_input_embeddings() ) lowerCAmelCase_ = _get_word_embedding_weight(lowercase_ , model.get_output_embeddings() ) # reshape the embeddings model.resize_token_embeddings(lowercase_ ) lowerCAmelCase_ = _get_word_embedding_weight(lowercase_ , model.get_input_embeddings() ) lowerCAmelCase_ = _get_word_embedding_weight(lowercase_ , model.get_output_embeddings() ) # check that the resized embeddings size matches the desired size. lowerCAmelCase_ = size if size is not None else config.vocab_size self.assertEqual(new_input_embeddings.shape[0] , lowercase_ ) # check that weights remain the same after resizing lowerCAmelCase_ = True for pa, pa in zip(old_input_embeddings.value() , new_input_embeddings.value() ): if tf.math.reduce_sum(tf.math.abs(pa - pa ) ) > 0: lowerCAmelCase_ = False self.assertTrue(lowercase_ ) if old_output_embeddings is not None and new_output_embeddings is not None: self.assertEqual(new_output_embeddings.shape[0] , lowercase_ ) lowerCAmelCase_ = True for pa, pa in zip(old_output_embeddings.value() , new_output_embeddings.value() ): if tf.math.reduce_sum(tf.math.abs(pa - pa ) ) > 0: lowerCAmelCase_ = False self.assertTrue(lowercase_ ) def lowerCamelCase ( a_ ) -> Any: return tf.constant(a_ , dtype=tf.intaa ) @require_tf class a_ ( unittest.TestCase ): '''simple docstring''' __a: Optional[int] = 9_9 def _lowercase ( self ) -> Optional[Any]: '''simple docstring''' lowerCAmelCase_ = tf.ones((4, 1) , dtype=tf.intaa ) * 2 lowerCAmelCase_ = tf.concat([ids_tensor((4, 6) , self.vocab_size - 3 ) + 3, eos_column_vector] , axis=1 ) lowerCAmelCase_ = input_ids.shape[0] lowerCAmelCase_ = OPTConfig( vocab_size=self.vocab_size , hidden_size=2_4 , num_hidden_layers=2 , num_attention_heads=2 , ffn_dim=3_2 , max_position_embeddings=4_8 , eos_token_id=2 , pad_token_id=1 , bos_token_id=0 , ) return config, input_ids, batch_size @require_sentencepiece @require_tf class a_ ( unittest.TestCase ): '''simple docstring''' @slow def _lowercase ( self ) -> Optional[int]: '''simple docstring''' lowerCAmelCase_ = TFOPTModel.from_pretrained('facebook/opt-350m' ) lowerCAmelCase_ = _long_tensor([[0, 3_1_4_1_4, 2_3_2, 3_2_8, 7_4_0, 1_1_4_0, 1_2_6_9_5, 6_9, 4_6_0_7_8, 1_5_8_8, 2]] ) lowerCAmelCase_ = tf.not_equal(lowercase_ , model.config.pad_token_id ) with tf.GradientTape(): lowerCAmelCase_ = model(input_ids=lowercase_ , attention_mask=lowercase_ ).last_hidden_state lowerCAmelCase_ = (1, 1_1, 5_1_2) self.assertEqual(output.shape , lowercase_ ) lowerCAmelCase_ = tf.constant( [[-0.28_73, -1.92_18, -0.30_33], [-1.27_10, -0.13_38, -0.19_02], [0.40_95, 0.12_14, -1.31_21]] ) self.assertTrue(np.allclose(output[:, :3, :3] , lowercase_ , atol=4e-3 ) ) lowerCAmelCase_ = tf.function(lowercase_ , jit_compile=lowercase_ ) lowerCAmelCase_ = xla_generate(lowercase_ , lowercase_ )[0] self.assertTrue(np.allclose(output[:, :3, :3] , lowercase_ , atol=4e-2 ) ) @require_tf @slow class a_ ( unittest.TestCase ): '''simple docstring''' def _lowercase ( self ) -> Optional[int]: '''simple docstring''' super().setUp() lowerCAmelCase_ = 'facebook/opt-350m' def _lowercase ( self ) -> Union[str, Any]: '''simple docstring''' lowerCAmelCase_ = TFOPTForCausalLM.from_pretrained(self.path_model ) lowerCAmelCase_ = GPTaTokenizer.from_pretrained(self.path_model ) lowerCAmelCase_ = [ 'Today is a beautiful day and I want to', 'In the city of', 'Paris is the capital of France and', 'Computers and mobile phones have taken', ] # verify that prompt without BOS token is identical to Metaseq -> add_special_tokens=False lowerCAmelCase_ = tokenizer(lowercase_ , return_tensors='tf' , padding=lowercase_ , add_special_tokens=lowercase_ ) lowerCAmelCase_ = tf.math.reduce_mean(model(inputs.input_ids , attention_mask=inputs.attention_mask )[0] , axis=-1 ) lowerCAmelCase_ = tf.constant( [ [1.38_51, -13.89_23, -10.52_29, -10.75_33, -0.23_09, -10.23_84, -0.53_65, -9.09_47, -5.16_70], [-4.70_73, -10.62_76, -3.94_15, -21.52_42, -0.28_22, -0.28_22, -0.28_22, -0.28_22, -0.28_22], [0.62_47, -3.42_29, -8.91_79, -1.42_97, -14.16_50, 1.41_46, -9.02_18, -0.27_03, -0.27_03], [6.47_83, -1.99_13, -10.79_26, -2.33_36, 1.50_92, -0.99_74, -6.82_13, 1.34_77, 1.34_77], ] ) self.assertTrue(np.allclose(lowercase_ , lowercase_ , atol=1e-4 ) ) lowerCAmelCase_ = tf.function(lowercase_ , jit_compile=lowercase_ ) lowerCAmelCase_ = tf.math.reduce_mean(xla_generate(inputs.input_ids , attention_mask=inputs.attention_mask )[0] , axis=-1 ) self.assertTrue(np.allclose(lowercase_ , lowercase_ , atol=1e-4 ) ) @require_tf @slow class a_ ( unittest.TestCase ): '''simple docstring''' @property def _lowercase ( self ) -> List[str]: '''simple docstring''' return [ "Today is a beautiful day and I want", "In the city of", "Paris is the capital of France and", "Computers and mobile phones have taken", ] def _lowercase ( self ) -> str: '''simple docstring''' lowerCAmelCase_ = 'facebook/opt-125m' lowerCAmelCase_ = [ 'Today is a beautiful day and I want to', 'In the city of New York, the city', 'Paris is the capital of France and the capital', 'Computers and mobile phones have taken over the', ] lowerCAmelCase_ = [] lowerCAmelCase_ = GPTaTokenizer.from_pretrained(lowercase_ ) lowerCAmelCase_ = TFOPTForCausalLM.from_pretrained(lowercase_ ) for prompt in self.prompts: lowerCAmelCase_ = tokenizer(lowercase_ , return_tensors='tf' ).input_ids lowerCAmelCase_ = model.generate(lowercase_ , max_length=1_0 ) lowerCAmelCase_ = tokenizer.batch_decode(lowercase_ , skip_special_tokens=lowercase_ ) predicted_outputs += generated_string self.assertListEqual(lowercase_ , lowercase_ ) def _lowercase ( self ) -> Union[str, Any]: '''simple docstring''' lowerCAmelCase_ = 'facebook/opt-350m' lowerCAmelCase_ = GPTaTokenizer.from_pretrained(lowercase_ ) lowerCAmelCase_ = TFOPTForCausalLM.from_pretrained(lowercase_ ) lowerCAmelCase_ = 'left' # use different length sentences to test batching lowerCAmelCase_ = [ 'Hello, my dog is a little', 'Today, I', ] lowerCAmelCase_ = tokenizer(lowercase_ , return_tensors='tf' , padding=lowercase_ ) lowerCAmelCase_ = inputs['input_ids'] lowerCAmelCase_ = model.generate(input_ids=lowercase_ , attention_mask=inputs['attention_mask'] ) lowerCAmelCase_ = tokenizer(sentences[0] , return_tensors='tf' ).input_ids lowerCAmelCase_ = model.generate(input_ids=lowercase_ ) lowerCAmelCase_ = inputs_non_padded.shape[-1] - tf.math.reduce_sum( tf.cast(inputs['attention_mask'][-1] , tf.intaa ) ) lowerCAmelCase_ = tokenizer(sentences[1] , return_tensors='tf' ).input_ids lowerCAmelCase_ = model.generate(input_ids=lowercase_ , max_length=model.config.max_length - num_paddings ) lowerCAmelCase_ = tokenizer.batch_decode(lowercase_ , skip_special_tokens=lowercase_ ) lowerCAmelCase_ = tokenizer.decode(output_non_padded[0] , skip_special_tokens=lowercase_ ) lowerCAmelCase_ = tokenizer.decode(output_padded[0] , skip_special_tokens=lowercase_ ) lowerCAmelCase_ = [ 'Hello, my dog is a little bit of a dork.\nI\'m a little bit', 'Today, I was in the middle of a conversation with a friend about the', ] self.assertListEqual(lowercase_ , lowercase_ ) self.assertListEqual(lowercase_ , [non_padded_sentence, padded_sentence] ) def _lowercase ( self ) -> Dict: '''simple docstring''' lowerCAmelCase_ = 'facebook/opt-350m' lowerCAmelCase_ = [ 'Today is a beautiful day and I want to', 'In the city of San Francisco, the city', 'Paris is the capital of France and the capital', 'Computers and mobile phones have taken over the', ] lowerCAmelCase_ = [] lowerCAmelCase_ = GPTaTokenizer.from_pretrained(lowercase_ ) lowerCAmelCase_ = TFOPTForCausalLM.from_pretrained(lowercase_ ) for prompt in self.prompts: lowerCAmelCase_ = tokenizer(lowercase_ , return_tensors='tf' ).input_ids lowerCAmelCase_ = model.generate(lowercase_ , max_length=1_0 ) lowerCAmelCase_ = tokenizer.batch_decode(lowercase_ , skip_special_tokens=lowercase_ ) predicted_outputs += generated_string self.assertListEqual(lowercase_ , lowercase_ )
14
1
'''simple docstring''' import argparse import os import torch from diffusers import ( CMStochasticIterativeScheduler, ConsistencyModelPipeline, UNetaDModel, ) a : Dict = { 'sample_size': 32, 'in_channels': 3, 'out_channels': 3, 'layers_per_block': 2, 'num_class_embeds': 1000, 'block_out_channels': [32, 64], 'attention_head_dim': 8, 'down_block_types': [ 'ResnetDownsampleBlock2D', 'AttnDownBlock2D', ], 'up_block_types': [ 'AttnUpBlock2D', 'ResnetUpsampleBlock2D', ], 'resnet_time_scale_shift': 'scale_shift', 'upsample_type': 'resnet', 'downsample_type': 'resnet', } a : List[str] = { 'sample_size': 64, 'in_channels': 3, 'out_channels': 3, 'layers_per_block': 3, 'num_class_embeds': 1000, 'block_out_channels': [192, 192 * 2, 192 * 3, 192 * 4], 'attention_head_dim': 64, 'down_block_types': [ 'ResnetDownsampleBlock2D', 'AttnDownBlock2D', 'AttnDownBlock2D', 'AttnDownBlock2D', ], 'up_block_types': [ 'AttnUpBlock2D', 'AttnUpBlock2D', 'AttnUpBlock2D', 'ResnetUpsampleBlock2D', ], 'resnet_time_scale_shift': 'scale_shift', 'upsample_type': 'resnet', 'downsample_type': 'resnet', } a : Optional[Any] = { 'sample_size': 256, 'in_channels': 3, 'out_channels': 3, 'layers_per_block': 2, 'num_class_embeds': None, 'block_out_channels': [256, 256, 256 * 2, 256 * 2, 256 * 4, 256 * 4], 'attention_head_dim': 64, 'down_block_types': [ 'ResnetDownsampleBlock2D', 'ResnetDownsampleBlock2D', 'ResnetDownsampleBlock2D', 'AttnDownBlock2D', 'AttnDownBlock2D', 'AttnDownBlock2D', ], 'up_block_types': [ 'AttnUpBlock2D', 'AttnUpBlock2D', 'AttnUpBlock2D', 'ResnetUpsampleBlock2D', 'ResnetUpsampleBlock2D', 'ResnetUpsampleBlock2D', ], 'resnet_time_scale_shift': 'default', 'upsample_type': 'resnet', 'downsample_type': 'resnet', } a : Optional[Any] = { 'num_train_timesteps': 40, 'sigma_min': 0.002, 'sigma_max': 80.0, } a : List[Any] = { 'num_train_timesteps': 201, 'sigma_min': 0.002, 'sigma_max': 80.0, } a : int = { 'num_train_timesteps': 151, 'sigma_min': 0.002, 'sigma_max': 80.0, } def __magic_name__ ( __UpperCAmelCase ) -> Any: '''simple docstring''' if isinstance(__UpperCAmelCase, __UpperCAmelCase ): return v if v.lower() in ("yes", "true", "t", "y", "1"): return True elif v.lower() in ("no", "false", "f", "n", "0"): return False else: raise argparse.ArgumentTypeError('''boolean value expected''' ) def __magic_name__ ( __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase=False ) -> Dict: '''simple docstring''' snake_case_ = checkpoint[F"{old_prefix}.in_layers.0.weight"] snake_case_ = checkpoint[F"{old_prefix}.in_layers.0.bias"] snake_case_ = checkpoint[F"{old_prefix}.in_layers.2.weight"] snake_case_ = checkpoint[F"{old_prefix}.in_layers.2.bias"] snake_case_ = checkpoint[F"{old_prefix}.emb_layers.1.weight"] snake_case_ = checkpoint[F"{old_prefix}.emb_layers.1.bias"] snake_case_ = checkpoint[F"{old_prefix}.out_layers.0.weight"] snake_case_ = checkpoint[F"{old_prefix}.out_layers.0.bias"] snake_case_ = checkpoint[F"{old_prefix}.out_layers.3.weight"] snake_case_ = checkpoint[F"{old_prefix}.out_layers.3.bias"] if has_skip: snake_case_ = checkpoint[F"{old_prefix}.skip_connection.weight"] snake_case_ = checkpoint[F"{old_prefix}.skip_connection.bias"] return new_checkpoint def __magic_name__ ( __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase=None ) -> Union[str, Any]: '''simple docstring''' snake_case_ ,snake_case_ ,snake_case_ = checkpoint[F"{old_prefix}.qkv.weight"].chunk(3, dim=0 ) snake_case_ ,snake_case_ ,snake_case_ = checkpoint[F"{old_prefix}.qkv.bias"].chunk(3, dim=0 ) snake_case_ = checkpoint[F"{old_prefix}.norm.weight"] snake_case_ = checkpoint[F"{old_prefix}.norm.bias"] snake_case_ = weight_q.squeeze(-1 ).squeeze(-1 ) snake_case_ = bias_q.squeeze(-1 ).squeeze(-1 ) snake_case_ = weight_k.squeeze(-1 ).squeeze(-1 ) snake_case_ = bias_k.squeeze(-1 ).squeeze(-1 ) snake_case_ = weight_v.squeeze(-1 ).squeeze(-1 ) snake_case_ = bias_v.squeeze(-1 ).squeeze(-1 ) snake_case_ = ( checkpoint[F"{old_prefix}.proj_out.weight"].squeeze(-1 ).squeeze(-1 ) ) snake_case_ = checkpoint[F"{old_prefix}.proj_out.bias"].squeeze(-1 ).squeeze(-1 ) return new_checkpoint def __magic_name__ ( __UpperCAmelCase, __UpperCAmelCase ) -> Tuple: '''simple docstring''' snake_case_ = torch.load(__UpperCAmelCase, map_location='''cpu''' ) snake_case_ = {} snake_case_ = checkpoint['''time_embed.0.weight'''] snake_case_ = checkpoint['''time_embed.0.bias'''] snake_case_ = checkpoint['''time_embed.2.weight'''] snake_case_ = checkpoint['''time_embed.2.bias'''] if unet_config["num_class_embeds"] is not None: snake_case_ = checkpoint['''label_emb.weight'''] snake_case_ = checkpoint['''input_blocks.0.0.weight'''] snake_case_ = checkpoint['''input_blocks.0.0.bias'''] snake_case_ = unet_config['''down_block_types'''] snake_case_ = unet_config['''layers_per_block'''] snake_case_ = unet_config['''attention_head_dim'''] snake_case_ = unet_config['''block_out_channels'''] snake_case_ = 1 snake_case_ = channels_list[0] for i, layer_type in enumerate(__UpperCAmelCase ): snake_case_ = channels_list[i] snake_case_ = current_channels != prev_channels if layer_type == "ResnetDownsampleBlock2D": for j in range(__UpperCAmelCase ): snake_case_ = F"down_blocks.{i}.resnets.{j}" snake_case_ = F"input_blocks.{current_layer}.0" snake_case_ = True if j == 0 and downsample_block_has_skip else False snake_case_ = convert_resnet(__UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase, has_skip=__UpperCAmelCase ) current_layer += 1 elif layer_type == "AttnDownBlock2D": for j in range(__UpperCAmelCase ): snake_case_ = F"down_blocks.{i}.resnets.{j}" snake_case_ = F"input_blocks.{current_layer}.0" snake_case_ = True if j == 0 and downsample_block_has_skip else False snake_case_ = convert_resnet(__UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase, has_skip=__UpperCAmelCase ) snake_case_ = F"down_blocks.{i}.attentions.{j}" snake_case_ = F"input_blocks.{current_layer}.1" snake_case_ = convert_attention( __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase ) current_layer += 1 if i != len(__UpperCAmelCase ) - 1: snake_case_ = F"down_blocks.{i}.downsamplers.0" snake_case_ = F"input_blocks.{current_layer}.0" snake_case_ = convert_resnet(__UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase ) current_layer += 1 snake_case_ = current_channels # hardcoded the mid-block for now snake_case_ = '''mid_block.resnets.0''' snake_case_ = '''middle_block.0''' snake_case_ = convert_resnet(__UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase ) snake_case_ = '''mid_block.attentions.0''' snake_case_ = '''middle_block.1''' snake_case_ = convert_attention(__UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase ) snake_case_ = '''mid_block.resnets.1''' snake_case_ = '''middle_block.2''' snake_case_ = convert_resnet(__UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase ) snake_case_ = 0 snake_case_ = unet_config['''up_block_types'''] for i, layer_type in enumerate(__UpperCAmelCase ): if layer_type == "ResnetUpsampleBlock2D": for j in range(layers_per_block + 1 ): snake_case_ = F"up_blocks.{i}.resnets.{j}" snake_case_ = F"output_blocks.{current_layer}.0" snake_case_ = convert_resnet(__UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase, has_skip=__UpperCAmelCase ) current_layer += 1 if i != len(__UpperCAmelCase ) - 1: snake_case_ = F"up_blocks.{i}.upsamplers.0" snake_case_ = F"output_blocks.{current_layer-1}.1" snake_case_ = convert_resnet(__UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase ) elif layer_type == "AttnUpBlock2D": for j in range(layers_per_block + 1 ): snake_case_ = F"up_blocks.{i}.resnets.{j}" snake_case_ = F"output_blocks.{current_layer}.0" snake_case_ = convert_resnet(__UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase, has_skip=__UpperCAmelCase ) snake_case_ = F"up_blocks.{i}.attentions.{j}" snake_case_ = F"output_blocks.{current_layer}.1" snake_case_ = convert_attention( __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase ) current_layer += 1 if i != len(__UpperCAmelCase ) - 1: snake_case_ = F"up_blocks.{i}.upsamplers.0" snake_case_ = F"output_blocks.{current_layer-1}.2" snake_case_ = convert_resnet(__UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase ) snake_case_ = checkpoint['''out.0.weight'''] snake_case_ = checkpoint['''out.0.bias'''] snake_case_ = checkpoint['''out.2.weight'''] snake_case_ = checkpoint['''out.2.bias'''] return new_checkpoint if __name__ == "__main__": a : List[str] = argparse.ArgumentParser() parser.add_argument('--unet_path', default=None, type=str, required=True, help='Path to the unet.pt to convert.') parser.add_argument( '--dump_path', default=None, type=str, required=True, help='Path to output the converted UNet model.' ) parser.add_argument('--class_cond', default=True, type=str, help='Whether the model is class-conditional.') a : Any = parser.parse_args() a : List[Any] = strabool(args.class_cond) a : Any = os.path.basename(args.unet_path) print(f'''Checkpoint: {ckpt_name}''') # Get U-Net config if "imagenet64" in ckpt_name: a : str = IMAGENET_64_UNET_CONFIG elif "256" in ckpt_name and (("bedroom" in ckpt_name) or ("cat" in ckpt_name)): a : List[str] = LSUN_256_UNET_CONFIG elif "test" in ckpt_name: a : Optional[int] = TEST_UNET_CONFIG else: raise ValueError(f'''Checkpoint type {ckpt_name} is not currently supported.''') if not args.class_cond: a : List[Any] = None a : Optional[Any] = con_pt_to_diffuser(args.unet_path, unet_config) a : Tuple = UNetaDModel(**unet_config) image_unet.load_state_dict(converted_unet_ckpt) # Get scheduler config if "cd" in ckpt_name or "test" in ckpt_name: a : List[Any] = CD_SCHEDULER_CONFIG elif "ct" in ckpt_name and "imagenet64" in ckpt_name: a : Union[str, Any] = CT_IMAGENET_64_SCHEDULER_CONFIG elif "ct" in ckpt_name and "256" in ckpt_name and (("bedroom" in ckpt_name) or ("cat" in ckpt_name)): a : List[str] = CT_LSUN_256_SCHEDULER_CONFIG else: raise ValueError(f'''Checkpoint type {ckpt_name} is not currently supported.''') a : Dict = CMStochasticIterativeScheduler(**scheduler_config) a : Any = ConsistencyModelPipeline(unet=image_unet, scheduler=cm_scheduler) consistency_model.save_pretrained(args.dump_path)
56
'''simple docstring''' import math from typing import Callable, List, Optional, Union import numpy as np import PIL import torch from PIL import Image from transformers import CLIPTextModel, CLIPTokenizer from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline from diffusers.schedulers import DDIMScheduler, DDPMScheduler, LMSDiscreteScheduler, PNDMScheduler def UpperCamelCase__ ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase=[] ): """simple docstring""" _lowerCAmelCase = size[0] - overlap_pixels * 2 _lowerCAmelCase = size[1] - overlap_pixels * 2 for letter in ["l", "r"]: if letter in remove_borders: size_x += overlap_pixels for letter in ["t", "b"]: if letter in remove_borders: size_y += overlap_pixels _lowerCAmelCase = np.ones((size_y, size_x) , dtype=np.uinta ) * 2_55 _lowerCAmelCase = np.pad(lowerCAmelCase , mode="""linear_ramp""" , pad_width=lowerCAmelCase , end_values=0 ) if "l" in remove_borders: _lowerCAmelCase = mask[:, overlap_pixels : mask.shape[1]] if "r" in remove_borders: _lowerCAmelCase = mask[:, 0 : mask.shape[1] - overlap_pixels] if "t" in remove_borders: _lowerCAmelCase = mask[overlap_pixels : mask.shape[0], :] if "b" in remove_borders: _lowerCAmelCase = mask[0 : mask.shape[0] - overlap_pixels, :] return mask def UpperCamelCase__ ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ): """simple docstring""" return max(lowerCAmelCase , min(lowerCAmelCase , lowerCAmelCase ) ) def UpperCamelCase__ ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ): """simple docstring""" return ( clamp(rect[0] , min[0] , max[0] ), clamp(rect[1] , min[1] , max[1] ), clamp(rect[2] , min[0] , max[0] ), clamp(rect[3] , min[1] , max[1] ), ) def UpperCamelCase__ ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ): """simple docstring""" _lowerCAmelCase = list(lowerCAmelCase ) rect[0] -= overlap rect[1] -= overlap rect[2] += overlap rect[3] += overlap _lowerCAmelCase = clamp_rect(lowerCAmelCase , [0, 0] , [image_size[0], image_size[1]] ) return rect def UpperCamelCase__ ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ): """simple docstring""" _lowerCAmelCase = Image.new("""RGB""" , (tile.size[0] + original_slice, tile.size[1]) ) result.paste( original_image.resize((tile.size[0], tile.size[1]) , Image.BICUBIC ).crop( (slice_x, 0, slice_x + original_slice, tile.size[1]) ) , (0, 0) , ) result.paste(lowerCAmelCase , (original_slice, 0) ) return result def UpperCamelCase__ ( lowerCAmelCase , lowerCAmelCase ): """simple docstring""" _lowerCAmelCase = (original_image_slice * 4, 0, tile.size[0], tile.size[1]) _lowerCAmelCase = tile.crop(lowerCAmelCase ) return tile def UpperCamelCase__ ( lowerCAmelCase , lowerCAmelCase ): """simple docstring""" _lowerCAmelCase = n % d return n - divisor class UpperCAmelCase ( snake_case_ ): def __init__( self : List[Any] , __snake_case : AutoencoderKL , __snake_case : CLIPTextModel , __snake_case : CLIPTokenizer , __snake_case : UNetaDConditionModel , __snake_case : DDPMScheduler , __snake_case : Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] , __snake_case : int = 3_50 , ) -> int: super().__init__( vae=__snake_case , text_encoder=__snake_case , tokenizer=__snake_case , unet=__snake_case , low_res_scheduler=__snake_case , scheduler=__snake_case , max_noise_level=__snake_case , ) def lowercase__ ( self : List[Any] , __snake_case : List[Any] , __snake_case : List[Any] , __snake_case : Dict , __snake_case : List[Any] , __snake_case : int , __snake_case : Optional[Any] , __snake_case : Any , **__snake_case : str ) -> int: torch.manual_seed(0 ) _lowerCAmelCase = ( min(image.size[0] - (tile_size + original_image_slice) , x * tile_size ), min(image.size[1] - (tile_size + original_image_slice) , y * tile_size ), min(image.size[0] , (x + 1) * tile_size ), min(image.size[1] , (y + 1) * tile_size ), ) _lowerCAmelCase = add_overlap_rect(__snake_case , __snake_case , image.size ) _lowerCAmelCase = image.crop(__snake_case ) _lowerCAmelCase = ((crop_rect[0] + ((crop_rect[2] - crop_rect[0]) / 2)) / image.size[0]) * tile.size[0] _lowerCAmelCase = translated_slice_x - (original_image_slice / 2) _lowerCAmelCase = max(0 , __snake_case ) _lowerCAmelCase = squeeze_tile(__snake_case , __snake_case , __snake_case , __snake_case ) _lowerCAmelCase = to_input.size _lowerCAmelCase = to_input.resize((tile_size, tile_size) , Image.BICUBIC ) _lowerCAmelCase = super(__snake_case , self ).__call__(image=__snake_case , **__snake_case ).images[0] _lowerCAmelCase = upscaled_tile.resize((orig_input_size[0] * 4, orig_input_size[1] * 4) , Image.BICUBIC ) _lowerCAmelCase = unsqueeze_tile(__snake_case , __snake_case ) _lowerCAmelCase = upscaled_tile.resize((tile.size[0] * 4, tile.size[1] * 4) , Image.BICUBIC ) _lowerCAmelCase = [] if x == 0: remove_borders.append("""l""" ) elif crop_rect[2] == image.size[0]: remove_borders.append("""r""" ) if y == 0: remove_borders.append("""t""" ) elif crop_rect[3] == image.size[1]: remove_borders.append("""b""" ) _lowerCAmelCase = Image.fromarray( make_transparency_mask( (upscaled_tile.size[0], upscaled_tile.size[1]) , tile_border * 4 , remove_borders=__snake_case ) , mode="""L""" , ) final_image.paste( __snake_case , (crop_rect_with_overlap[0] * 4, crop_rect_with_overlap[1] * 4) , __snake_case ) @torch.no_grad() def __call__( self : Union[str, Any] , __snake_case : Union[str, List[str]] , __snake_case : Union[PIL.Image.Image, List[PIL.Image.Image]] , __snake_case : int = 75 , __snake_case : float = 9.0 , __snake_case : int = 50 , __snake_case : Optional[Union[str, List[str]]] = None , __snake_case : Optional[int] = 1 , __snake_case : float = 0.0 , __snake_case : Optional[torch.Generator] = None , __snake_case : Optional[torch.FloatTensor] = None , __snake_case : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __snake_case : int = 1 , __snake_case : int = 1_28 , __snake_case : int = 32 , __snake_case : int = 32 , ) -> str: _lowerCAmelCase = Image.new("""RGB""" , (image.size[0] * 4, image.size[1] * 4) ) _lowerCAmelCase = math.ceil(image.size[0] / tile_size ) _lowerCAmelCase = math.ceil(image.size[1] / tile_size ) _lowerCAmelCase = tcx * tcy _lowerCAmelCase = 0 for y in range(__snake_case ): for x in range(__snake_case ): self._process_tile( __snake_case , __snake_case , __snake_case , __snake_case , __snake_case , __snake_case , __snake_case , prompt=__snake_case , num_inference_steps=__snake_case , guidance_scale=__snake_case , noise_level=__snake_case , negative_prompt=__snake_case , num_images_per_prompt=__snake_case , eta=__snake_case , generator=__snake_case , latents=__snake_case , ) current_count += 1 if callback is not None: callback({"""progress""": current_count / total_tile_count, """image""": final_image} ) return final_image def UpperCamelCase__ ( ): """simple docstring""" _lowerCAmelCase = """stabilityai/stable-diffusion-x4-upscaler""" _lowerCAmelCase = StableDiffusionTiledUpscalePipeline.from_pretrained(lowerCAmelCase , revision="""fp16""" , torch_dtype=torch.floataa ) _lowerCAmelCase = pipe.to("""cuda""" ) _lowerCAmelCase = Image.open("""../../docs/source/imgs/diffusers_library.jpg""" ) def callback(lowerCAmelCase ): print(f"progress: {obj['progress']:.4f}" ) obj["image"].save("""diffusers_library_progress.jpg""" ) _lowerCAmelCase = pipe(image=lowerCAmelCase , prompt="""Black font, white background, vector""" , noise_level=40 , callback=lowerCAmelCase ) final_image.save("""diffusers_library.jpg""" ) if __name__ == "__main__": main()
70
0
"""simple docstring""" def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : Dict) -> List[str]: '''simple docstring''' if len(_lowerCamelCase) <= 1: return [tuple(_lowerCamelCase)] __UpperCamelCase : Any = [] def generate(_lowerCamelCase : List[str] , _lowerCamelCase : Dict): __UpperCamelCase : Dict = [0] * n res.append(tuple(_lowerCamelCase)) __UpperCamelCase : int = 0 while i < n: if c[i] < i: if i % 2 == 0: __UpperCamelCase : Optional[int] = arr[i], arr[0] else: __UpperCamelCase : Tuple = arr[i], arr[c[i]] res.append(tuple(_lowerCamelCase)) c[i] += 1 __UpperCamelCase : Optional[int] = 0 else: __UpperCamelCase : str = 0 i += 1 generate(len(_lowerCamelCase) , _lowerCamelCase) return res if __name__ == "__main__": lowercase : int = input('Enter numbers separated by a comma:\n').strip() lowercase : Tuple = [int(item) for item in user_input.split(',')] print(heaps(arr))
371
from __future__ import annotations from collections import deque from collections.abc import Iterator from dataclasses import dataclass @dataclass class lowerCamelCase__ : '''simple docstring''' _A = 42 _A = 42 class lowerCamelCase__ : '''simple docstring''' def __init__( self :Optional[Any] , a :int ) -> Tuple: __UpperCamelCase : list[list[Edge]] = [[] for _ in range(a )] __UpperCamelCase : str = size def __getitem__( self :str , a :int ) -> Iterator[Edge]: return iter(self._graph[vertex] ) @property def _lowerCamelCase ( self :Any ) -> List[str]: return self._size def _lowerCamelCase ( self :Dict , a :int , a :int , a :int ) -> Any: if weight not in (0, 1): raise ValueError("Edge weight must be either 0 or 1." ) if to_vertex < 0 or to_vertex >= self.size: raise ValueError("Vertex indexes must be in [0; size)." ) self._graph[from_vertex].append(Edge(a , a ) ) def _lowerCamelCase ( self :List[str] , a :int , a :int ) -> int | None: __UpperCamelCase : Union[str, Any] = deque([start_vertex] ) __UpperCamelCase : list[int | None] = [None] * self.size __UpperCamelCase : Dict = 0 while queue: __UpperCamelCase : Tuple = queue.popleft() __UpperCamelCase : int = distances[current_vertex] if current_distance is None: continue for edge in self[current_vertex]: __UpperCamelCase : Optional[Any] = current_distance + edge.weight __UpperCamelCase : Dict = distances[edge.destination_vertex] if ( isinstance(a , a ) and new_distance >= dest_vertex_distance ): continue __UpperCamelCase : Optional[Any] = new_distance if edge.weight == 0: queue.appendleft(edge.destination_vertex ) else: queue.append(edge.destination_vertex ) if distances[finish_vertex] is None: raise ValueError("No path from start_vertex to finish_vertex." ) return distances[finish_vertex] if __name__ == "__main__": import doctest doctest.testmod()
151
0
"""simple docstring""" from typing import Dict, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_torch_available, is_torch_tensor, logging if is_torch_available(): import torch UpperCAmelCase__ = logging.get_logger(__name__) class lowerCAmelCase__ ( A__ ): __a = ['''pixel_values'''] def __init__( self : Optional[Any] , _lowerCamelCase : bool = True , _lowerCamelCase : Optional[Dict[str, int]] = None , _lowerCamelCase : PILImageResampling = PILImageResampling.BILINEAR , _lowerCamelCase : bool = True , _lowerCamelCase : Dict[str, int] = None , _lowerCamelCase : bool = True , _lowerCamelCase : Union[int, float] = 1 / 255 , _lowerCamelCase : bool = True , _lowerCamelCase : Optional[Union[float, List[float]]] = None , _lowerCamelCase : Optional[Union[float, List[float]]] = None , **_lowerCamelCase : Tuple , ): super().__init__(**lowerCAmelCase__ ) _snake_case = size if size is not None else {'''shortest_edge''': 256} _snake_case = get_size_dict(lowerCAmelCase__ , default_to_square=lowerCAmelCase__ ) _snake_case = crop_size if crop_size is not None else {'''height''': 224, '''width''': 224} _snake_case = get_size_dict(lowerCAmelCase__ , param_name='''crop_size''' ) _snake_case = do_resize _snake_case = size _snake_case = resample _snake_case = do_center_crop _snake_case = crop_size _snake_case = do_rescale _snake_case = rescale_factor _snake_case = do_normalize _snake_case = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN _snake_case = image_std if image_std is not None else IMAGENET_STANDARD_STD def lowercase ( self : Any , _lowerCamelCase : np.ndarray , _lowerCamelCase : Dict[str, int] , _lowerCamelCase : PILImageResampling = PILImageResampling.BICUBIC , _lowerCamelCase : Optional[Union[str, ChannelDimension]] = None , **_lowerCamelCase : int , ): _snake_case = get_size_dict(lowerCAmelCase__ , default_to_square=lowerCAmelCase__ ) if "shortest_edge" not in size: raise ValueError(f'''The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}''' ) _snake_case = get_resize_output_image_size(lowerCAmelCase__ , size=size['''shortest_edge'''] , default_to_square=lowerCAmelCase__ ) return resize(lowerCAmelCase__ , size=lowerCAmelCase__ , resample=lowerCAmelCase__ , data_format=lowerCAmelCase__ , **lowerCAmelCase__ ) def lowercase ( self : List[Any] , _lowerCamelCase : np.ndarray , _lowerCamelCase : Dict[str, int] , _lowerCamelCase : Optional[Union[str, ChannelDimension]] = None , **_lowerCamelCase : str , ): _snake_case = get_size_dict(lowerCAmelCase__ ) if "height" not in size or "width" not in size: raise ValueError(f'''The `size` parameter must contain the keys `height` and `width`. Got {size.keys()}''' ) return center_crop(lowerCAmelCase__ , size=(size['''height'''], size['''width''']) , data_format=lowerCAmelCase__ , **lowerCAmelCase__ ) def lowercase ( self : Union[str, Any] , _lowerCamelCase : np.ndarray , _lowerCamelCase : float , _lowerCamelCase : Optional[Union[str, ChannelDimension]] = None , **_lowerCamelCase : int ): return rescale(lowerCAmelCase__ , scale=lowerCAmelCase__ , data_format=lowerCAmelCase__ , **lowerCAmelCase__ ) def lowercase ( self : Any , _lowerCamelCase : np.ndarray , _lowerCamelCase : Union[float, List[float]] , _lowerCamelCase : Union[float, List[float]] , _lowerCamelCase : Optional[Union[str, ChannelDimension]] = None , **_lowerCamelCase : str , ): return normalize(lowerCAmelCase__ , mean=lowerCAmelCase__ , std=lowerCAmelCase__ , data_format=lowerCAmelCase__ , **lowerCAmelCase__ ) def lowercase ( self : List[Any] , _lowerCamelCase : ImageInput , _lowerCamelCase : Optional[bool] = None , _lowerCamelCase : Dict[str, int] = None , _lowerCamelCase : PILImageResampling = None , _lowerCamelCase : bool = None , _lowerCamelCase : Dict[str, int] = None , _lowerCamelCase : Optional[bool] = None , _lowerCamelCase : Optional[float] = None , _lowerCamelCase : Optional[bool] = None , _lowerCamelCase : Optional[Union[float, List[float]]] = None , _lowerCamelCase : Optional[Union[float, List[float]]] = None , _lowerCamelCase : Optional[Union[str, TensorType]] = None , _lowerCamelCase : Union[str, ChannelDimension] = ChannelDimension.FIRST , **_lowerCamelCase : Optional[int] , ): _snake_case = do_resize if do_resize is not None else self.do_resize _snake_case = size if size is not None else self.size _snake_case = get_size_dict(lowerCAmelCase__ , default_to_square=lowerCAmelCase__ ) _snake_case = resample if resample is not None else self.resample _snake_case = do_center_crop if do_center_crop is not None else self.do_center_crop _snake_case = crop_size if crop_size is not None else self.crop_size _snake_case = get_size_dict(lowerCAmelCase__ , param_name='''crop_size''' ) _snake_case = do_rescale if do_rescale is not None else self.do_rescale _snake_case = rescale_factor if rescale_factor is not None else self.rescale_factor _snake_case = do_normalize if do_normalize is not None else self.do_normalize _snake_case = image_mean if image_mean is not None else self.image_mean _snake_case = image_std if image_std is not None else self.image_std _snake_case = make_list_of_images(lowerCAmelCase__ ) if not valid_images(lowerCAmelCase__ ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None: raise ValueError('''Size must be specified if do_resize is True.''' ) if do_center_crop and crop_size is None: raise ValueError('''Crop size must be specified if do_center_crop is True.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('''Image mean and std must be specified if do_normalize is True.''' ) # All transformations expect numpy arrays. _snake_case = [to_numpy_array(lowerCAmelCase__ ) for image in images] if do_resize: _snake_case = [self.resize(image=lowerCAmelCase__ , size=lowerCAmelCase__ , resample=lowerCAmelCase__ ) for image in images] if do_center_crop: _snake_case = [self.center_crop(image=lowerCAmelCase__ , size=lowerCAmelCase__ ) for image in images] if do_rescale: _snake_case = [self.rescale(image=lowerCAmelCase__ , scale=lowerCAmelCase__ ) for image in images] if do_normalize: _snake_case = [self.normalize(image=lowerCAmelCase__ , mean=lowerCAmelCase__ , std=lowerCAmelCase__ ) for image in images] _snake_case = [to_channel_dimension_format(lowerCAmelCase__ , lowerCAmelCase__ ) for image in images] _snake_case = {'''pixel_values''': images} return BatchFeature(data=lowerCAmelCase__ , tensor_type=lowerCAmelCase__ ) def lowercase ( self : int , _lowerCamelCase : Union[str, Any] , _lowerCamelCase : List[Tuple] = None ): _snake_case = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(lowerCAmelCase__ ) != len(lowerCAmelCase__ ): raise ValueError( '''Make sure that you pass in as many target sizes as the batch dimension of the logits''' ) if is_torch_tensor(lowerCAmelCase__ ): _snake_case = target_sizes.numpy() _snake_case = [] for idx in range(len(lowerCAmelCase__ ) ): _snake_case = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode='''bilinear''' , align_corners=lowerCAmelCase__ ) _snake_case = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(lowerCAmelCase__ ) else: _snake_case = logits.argmax(dim=1 ) _snake_case = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
288
from collections import Counter import numpy as np from sklearn import datasets from sklearn.model_selection import train_test_split __lowerCAmelCase : List[Any] =datasets.load_iris() __lowerCAmelCase : Tuple =np.array(data['data']) __lowerCAmelCase : Dict =np.array(data['target']) __lowerCAmelCase : List[str] =data['target_names'] __lowerCAmelCase ,__lowerCAmelCase ,__lowerCAmelCase ,__lowerCAmelCase : str =train_test_split(X, y) def _UpperCamelCase ( lowercase__ , lowercase__ ): return np.linalg.norm(np.array(lowercase__ ) - np.array(lowercase__ ) ) def _UpperCamelCase ( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__=5 ): __SCREAMING_SNAKE_CASE : Optional[int] = zip(lowercase__ , lowercase__ ) # List of distances of all points from the point to be classified __SCREAMING_SNAKE_CASE : Dict = [] for data_point in data: __SCREAMING_SNAKE_CASE : Tuple = euclidean_distance(data_point[0] , lowercase__ ) distances.append((distance, data_point[1]) ) # Choosing 'k' points with the least distances. __SCREAMING_SNAKE_CASE : int = [i[1] for i in sorted(lowercase__ )[:k]] # Most commonly occurring class among them # is the class into which the point is classified __SCREAMING_SNAKE_CASE : Any = Counter(lowercase__ ).most_common(1 )[0][0] return classes[result] if __name__ == "__main__": print(classifier(X_train, y_train, classes, [4.4, 3.1, 1.3, 1.4]))
9
0
lowerCamelCase__ = { '''meter''': '''m''', '''kilometer''': '''km''', '''megametre''': '''Mm''', '''gigametre''': '''Gm''', '''terametre''': '''Tm''', '''petametre''': '''Pm''', '''exametre''': '''Em''', '''zettametre''': '''Zm''', '''yottametre''': '''Ym''', } # Exponent of the factor(meter) lowerCamelCase__ = { '''m''': 0, '''km''': 3, '''Mm''': 6, '''Gm''': 9, '''Tm''': 12, '''Pm''': 15, '''Em''': 18, '''Zm''': 21, '''Ym''': 24, } def A(__a: float , __a: str , __a: str ): lowerCAmelCase_ = from_type.lower().strip("s" ) lowerCAmelCase_ = to_type.lower().strip("s" ) lowerCAmelCase_ = UNIT_SYMBOL.get(__a , __a ) lowerCAmelCase_ = UNIT_SYMBOL.get(__a , __a ) if from_sanitized not in METRIC_CONVERSION: lowerCAmelCase_ = ( F"Invalid 'from_type' value: {from_type!r}.\n" F"Conversion abbreviations are: {', '.join(__a )}" ) raise ValueError(__a ) if to_sanitized not in METRIC_CONVERSION: lowerCAmelCase_ = ( F"Invalid 'to_type' value: {to_type!r}.\n" F"Conversion abbreviations are: {', '.join(__a )}" ) raise ValueError(__a ) lowerCAmelCase_ = METRIC_CONVERSION[from_sanitized] lowerCAmelCase_ = METRIC_CONVERSION[to_sanitized] lowerCAmelCase_ = 1 if from_exponent > to_exponent: lowerCAmelCase_ = from_exponent - to_exponent else: lowerCAmelCase_ = -(to_exponent - from_exponent) return value * pow(10 , __a ) if __name__ == "__main__": from doctest import testmod testmod()
22
import warnings from ...utils import is_sklearn_available, requires_backends if is_sklearn_available(): from scipy.stats import pearsonr, spearmanr from sklearn.metrics import fa_score, matthews_corrcoef lowerCamelCase__ = ( '''This metric will be removed from the library soon, metrics should be handled with the 🤗 Evaluate ''' '''library. You can have a look at this example script for pointers: ''' '''https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py''' ) def A(__a: str , __a: List[Any] ): warnings.warn(__a , __a ) requires_backends(__a , "sklearn" ) return (preds == labels).mean() def A(__a: Any , __a: Any ): warnings.warn(__a , __a ) requires_backends(__a , "sklearn" ) lowerCAmelCase_ = simple_accuracy(__a , __a ) lowerCAmelCase_ = fa_score(y_true=__a , y_pred=__a ) return { "acc": acc, "f1": fa, "acc_and_f1": (acc + fa) / 2, } def A(__a: List[str] , __a: Optional[int] ): warnings.warn(__a , __a ) requires_backends(__a , "sklearn" ) lowerCAmelCase_ = pearsonr(__a , __a )[0] lowerCAmelCase_ = spearmanr(__a , __a )[0] return { "pearson": pearson_corr, "spearmanr": spearman_corr, "corr": (pearson_corr + spearman_corr) / 2, } def A(__a: Union[str, Any] , __a: Any , __a: str ): warnings.warn(__a , __a ) requires_backends(__a , "sklearn" ) assert len(__a ) == len(__a ), F"Predictions and labels have mismatched lengths {len(__a )} and {len(__a )}" if task_name == "cola": return {"mcc": matthews_corrcoef(__a , __a )} elif task_name == "sst-2": return {"acc": simple_accuracy(__a , __a )} elif task_name == "mrpc": return acc_and_fa(__a , __a ) elif task_name == "sts-b": return pearson_and_spearman(__a , __a ) elif task_name == "qqp": return acc_and_fa(__a , __a ) elif task_name == "mnli": return {"mnli/acc": simple_accuracy(__a , __a )} elif task_name == "mnli-mm": return {"mnli-mm/acc": simple_accuracy(__a , __a )} elif task_name == "qnli": return {"acc": simple_accuracy(__a , __a )} elif task_name == "rte": return {"acc": simple_accuracy(__a , __a )} elif task_name == "wnli": return {"acc": simple_accuracy(__a , __a )} elif task_name == "hans": return {"acc": simple_accuracy(__a , __a )} else: raise KeyError(__a ) def A(__a: int , __a: Optional[Any] , __a: Optional[Any] ): warnings.warn(__a , __a ) requires_backends(__a , "sklearn" ) if len(__a ) != len(__a ): raise ValueError(F"Predictions and labels have mismatched lengths {len(__a )} and {len(__a )}" ) if task_name == "xnli": return {"acc": simple_accuracy(__a , __a )} else: raise KeyError(__a )
22
1
"""simple docstring""" import os from distutils.util import strtobool def A_ ( _lowerCAmelCase : int, _lowerCAmelCase : Optional[int] ): """simple docstring""" for e in env_keys: _a = int(os.environ.get(_lowerCAmelCase, -1 ) ) if val >= 0: return val return default def A_ ( _lowerCAmelCase : List[Any], _lowerCAmelCase : int=False ): """simple docstring""" _a = os.environ.get(_lowerCAmelCase, str(_lowerCAmelCase ) ) return strtobool(_lowerCAmelCase ) == 1 # As its name indicates `strtobool` actually returns an int... def A_ ( _lowerCAmelCase : List[str], _lowerCAmelCase : int="no" ): """simple docstring""" _a = os.environ.get(_lowerCAmelCase, str(_lowerCAmelCase ) ) return value
320
import numpy # List of input, output pairs UpperCAmelCase : str = ( ((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 : List[str] = len(train_data) UpperCAmelCase : Dict = 0.0_0_9 def _A ( SCREAMING_SNAKE_CASE : Tuple , SCREAMING_SNAKE_CASE : Tuple="train" ): """simple docstring""" return calculate_hypothesis_value(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) - output( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def _A ( SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" a__ : Tuple =0 for i in range(len(SCREAMING_SNAKE_CASE ) - 1 ): hyp_val += data_input_tuple[i] * parameter_vector[i + 1] hyp_val += parameter_vector[0] return hyp_val def _A ( SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : Dict ): """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 _A ( SCREAMING_SNAKE_CASE : Optional[Any] , SCREAMING_SNAKE_CASE : Tuple ): """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 _A ( SCREAMING_SNAKE_CASE : Union[str, Any] , SCREAMING_SNAKE_CASE : int=m ): """simple docstring""" a__ : Any =0 for i in range(SCREAMING_SNAKE_CASE ): if index == -1: summation_value += _error(SCREAMING_SNAKE_CASE ) else: summation_value += _error(SCREAMING_SNAKE_CASE ) * train_data[i][0][index] return summation_value def _A ( SCREAMING_SNAKE_CASE : int ): """simple docstring""" a__ : Any =summation_of_cost_derivative(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) / m return cost_derivative_value def _A ( ): """simple docstring""" global parameter_vector # Tune these values to set a tolerance value for predicted output a__ : Dict =0.0_0_0_0_0_2 a__ : Union[str, Any] =0 a__ : Any =0 while True: j += 1 a__ : Any =[0, 0, 0, 0] for i in range(0 , len(SCREAMING_SNAKE_CASE ) ): a__ : Tuple =get_cost_derivative(i - 1 ) a__ : List[Any] =( parameter_vector[i] - LEARNING_RATE * cost_derivative ) if numpy.allclose( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , atol=SCREAMING_SNAKE_CASE , rtol=SCREAMING_SNAKE_CASE , ): break a__ : Optional[Any] =temp_parameter_vector print(("Number of iterations:", j) ) def _A ( ): """simple docstring""" for i in range(len(SCREAMING_SNAKE_CASE ) ): print(("Actual output value:", output(SCREAMING_SNAKE_CASE , "test" )) ) print(("Hypothesis output:", calculate_hypothesis_value(SCREAMING_SNAKE_CASE , "test" )) ) if __name__ == "__main__": run_gradient_descent() print("""\nTesting gradient descent for a linear hypothesis function.\n""") test_gradient_descent()
95
0
'''simple docstring''' import math _A : Union[str, Any] =10 _A : Any =7 _A : Dict =BALLS_PER_COLOUR * NUM_COLOURS def SCREAMING_SNAKE_CASE_ (UpperCamelCase = 20 ) -> str: lowerCamelCase__ : str = math.comb(UpperCamelCase , UpperCamelCase ) lowerCamelCase__ : str = math.comb(NUM_BALLS - BALLS_PER_COLOUR , UpperCamelCase ) lowerCamelCase__ : Union[str, Any] = NUM_COLOURS * (1 - missing_colour / total) return f'''{result:.9f}''' if __name__ == "__main__": print(solution(20))
129
'''simple docstring''' import argparse import requests import torch from PIL import Image from transformers import ViTMAEConfig, ViTMAEForPreTraining, ViTMAEImageProcessor def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> List[Any]: if "cls_token" in name: lowerCamelCase__ : Any = name.replace("""cls_token""" , """vit.embeddings.cls_token""" ) if "mask_token" in name: lowerCamelCase__ : Union[str, Any] = name.replace("""mask_token""" , """decoder.mask_token""" ) if "decoder_pos_embed" in name: lowerCamelCase__ : Tuple = name.replace("""decoder_pos_embed""" , """decoder.decoder_pos_embed""" ) if "pos_embed" in name and "decoder" not in name: lowerCamelCase__ : str = name.replace("""pos_embed""" , """vit.embeddings.position_embeddings""" ) if "patch_embed.proj" in name: lowerCamelCase__ : Optional[int] = name.replace("""patch_embed.proj""" , """vit.embeddings.patch_embeddings.projection""" ) if "patch_embed.norm" in name: lowerCamelCase__ : Any = name.replace("""patch_embed.norm""" , """vit.embeddings.norm""" ) if "decoder_blocks" in name: lowerCamelCase__ : Dict = name.replace("""decoder_blocks""" , """decoder.decoder_layers""" ) if "blocks" in name: lowerCamelCase__ : Union[str, Any] = name.replace("""blocks""" , """vit.encoder.layer""" ) if "attn.proj" in name: lowerCamelCase__ : List[Any] = name.replace("""attn.proj""" , """attention.output.dense""" ) if "attn" in name: lowerCamelCase__ : List[str] = name.replace("""attn""" , """attention.self""" ) if "norm1" in name: lowerCamelCase__ : Any = name.replace("""norm1""" , """layernorm_before""" ) if "norm2" in name: lowerCamelCase__ : Dict = name.replace("""norm2""" , """layernorm_after""" ) if "mlp.fc1" in name: lowerCamelCase__ : str = name.replace("""mlp.fc1""" , """intermediate.dense""" ) if "mlp.fc2" in name: lowerCamelCase__ : Union[str, Any] = name.replace("""mlp.fc2""" , """output.dense""" ) if "decoder_embed" in name: lowerCamelCase__ : Tuple = name.replace("""decoder_embed""" , """decoder.decoder_embed""" ) if "decoder_norm" in name: lowerCamelCase__ : Optional[int] = name.replace("""decoder_norm""" , """decoder.decoder_norm""" ) if "decoder_pred" in name: lowerCamelCase__ : int = name.replace("""decoder_pred""" , """decoder.decoder_pred""" ) if "norm.weight" in name and "decoder" not in name: lowerCamelCase__ : Union[str, Any] = name.replace("""norm.weight""" , """vit.layernorm.weight""" ) if "norm.bias" in name and "decoder" not in name: lowerCamelCase__ : Dict = name.replace("""norm.bias""" , """vit.layernorm.bias""" ) return name def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase ) -> Tuple: for key in orig_state_dict.copy().keys(): lowerCamelCase__ : List[str] = orig_state_dict.pop(UpperCamelCase ) if "qkv" in key: lowerCamelCase__ : List[Any] = key.split(""".""" ) lowerCamelCase__ : Optional[int] = int(key_split[1] ) if "decoder_blocks" in key: lowerCamelCase__ : str = config.decoder_hidden_size lowerCamelCase__ : List[Any] = """decoder.decoder_layers.""" if "weight" in key: lowerCamelCase__ : int = val[:dim, :] lowerCamelCase__ : int = val[dim : dim * 2, :] lowerCamelCase__ : Tuple = val[-dim:, :] elif "bias" in key: lowerCamelCase__ : Tuple = val[:dim] lowerCamelCase__ : Optional[int] = val[dim : dim * 2] lowerCamelCase__ : List[Any] = val[-dim:] else: lowerCamelCase__ : List[Any] = config.hidden_size lowerCamelCase__ : Optional[int] = """vit.encoder.layer.""" if "weight" in key: lowerCamelCase__ : str = val[:dim, :] lowerCamelCase__ : List[Any] = val[dim : dim * 2, :] lowerCamelCase__ : Optional[int] = val[-dim:, :] elif "bias" in key: lowerCamelCase__ : int = val[:dim] lowerCamelCase__ : List[Any] = val[dim : dim * 2] lowerCamelCase__ : Optional[int] = val[-dim:] else: lowerCamelCase__ : int = val return orig_state_dict def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase ) -> int: lowerCamelCase__ : Any = ViTMAEConfig() if "large" in checkpoint_url: lowerCamelCase__ : Any = 1024 lowerCamelCase__ : Optional[Any] = 4096 lowerCamelCase__ : List[str] = 24 lowerCamelCase__ : Union[str, Any] = 16 elif "huge" in checkpoint_url: lowerCamelCase__ : List[str] = 14 lowerCamelCase__ : Dict = 1280 lowerCamelCase__ : Tuple = 5120 lowerCamelCase__ : List[str] = 32 lowerCamelCase__ : Union[str, Any] = 16 lowerCamelCase__ : List[Any] = ViTMAEForPreTraining(UpperCamelCase ) lowerCamelCase__ : str = torch.hub.load_state_dict_from_url(UpperCamelCase , map_location="""cpu""" )["""model"""] lowerCamelCase__ : Union[str, Any] = ViTMAEImageProcessor(size=config.image_size ) lowerCamelCase__ : List[str] = convert_state_dict(UpperCamelCase , UpperCamelCase ) model.load_state_dict(UpperCamelCase ) model.eval() lowerCamelCase__ : Union[str, Any] = """https://user-images.githubusercontent.com/11435359/147738734-196fd92f-9260-48d5-ba7e-bf103d29364d.jpg""" lowerCamelCase__ : List[Any] = Image.open(requests.get(UpperCamelCase , stream=UpperCamelCase ).raw ) lowerCamelCase__ : str = ViTMAEImageProcessor(size=config.image_size ) lowerCamelCase__ : Any = image_processor(images=UpperCamelCase , return_tensors="""pt""" ) # forward pass torch.manual_seed(2 ) lowerCamelCase__ : Optional[Any] = model(**UpperCamelCase ) lowerCamelCase__ : Optional[Any] = outputs.logits if "large" in checkpoint_url: lowerCamelCase__ : List[Any] = torch.tensor( [[-0.7309, -0.7128, -1.0169], [-1.0161, -0.9058, -1.1878], [-1.0478, -0.9411, -1.1911]] ) elif "huge" in checkpoint_url: lowerCamelCase__ : Optional[Any] = torch.tensor( [[-1.1599, -0.9199, -1.2221], [-1.1952, -0.9269, -1.2307], [-1.2143, -0.9337, -1.2262]] ) else: lowerCamelCase__ : int = torch.tensor( [[-0.9192, -0.8481, -1.1259], [-1.1349, -1.0034, -1.2599], [-1.1757, -1.0429, -1.2726]] ) # verify logits assert torch.allclose(logits[0, :3, :3] , UpperCamelCase , atol=1E-4 ) print(f'''Saving model to {pytorch_dump_folder_path}''' ) model.save_pretrained(UpperCamelCase ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(UpperCamelCase ) if __name__ == "__main__": _A : str =argparse.ArgumentParser() # Required parameters parser.add_argument( '''--checkpoint_url''', default='''https://dl.fbaipublicfiles.com/mae/visualize/mae_visualize_vit_base.pth''', type=str, help='''URL of the checkpoint you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) _A : Tuple =parser.parse_args() convert_vit_mae_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
129
1
"""simple docstring""" from typing import List, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging _lowercase = logging.get_logger(__name__) _lowercase = { '''huggingface/informer-tourism-monthly''': ( '''https://huggingface.co/huggingface/informer-tourism-monthly/resolve/main/config.json''' ), # See all Informer models at https://huggingface.co/models?filter=informer } class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: List[str] = '''informer''' _lowerCamelCase: Dict = { '''hidden_size''': '''d_model''', '''num_attention_heads''': '''encoder_attention_heads''', '''num_hidden_layers''': '''encoder_layers''', } def __init__( self : Union[str, Any] ,A_ : Optional[int] = None ,A_ : Optional[int] = None ,A_ : str = "student_t" ,A_ : str = "nll" ,A_ : int = 1 ,A_ : List[int] = None ,A_ : Optional[Union[str, bool]] = "mean" ,A_ : int = 0 ,A_ : int = 0 ,A_ : int = 0 ,A_ : int = 0 ,A_ : Optional[List[int]] = None ,A_ : Optional[List[int]] = None ,A_ : int = 64 ,A_ : int = 32 ,A_ : int = 32 ,A_ : int = 2 ,A_ : int = 2 ,A_ : int = 2 ,A_ : int = 2 ,A_ : bool = True ,A_ : str = "gelu" ,A_ : float = 0.05 ,A_ : float = 0.1 ,A_ : float = 0.1 ,A_ : float = 0.1 ,A_ : float = 0.1 ,A_ : int = 100 ,A_ : float = 0.02 ,A_ : Tuple=True ,A_ : str = "prob" ,A_ : int = 5 ,A_ : bool = True ,**A_ : Any ,) -> Dict: # time series specific configuration A = prediction_length A = context_length or prediction_length A = distribution_output A = loss A = input_size A = num_time_features A = lags_sequence if lags_sequence is not None else [1, 2, 3, 4, 5, 6, 7] A = scaling A = num_dynamic_real_features A = num_static_real_features A = num_static_categorical_features # set cardinality if cardinality and num_static_categorical_features > 0: if len(A_ ) != num_static_categorical_features: raise ValueError( 'The cardinality should be a list of the same length as `num_static_categorical_features`' ) A = cardinality else: A = [0] # set embedding_dimension if embedding_dimension and num_static_categorical_features > 0: if len(A_ ) != num_static_categorical_features: raise ValueError( 'The embedding dimension should be a list of the same length as `num_static_categorical_features`' ) A = embedding_dimension else: A = [min(50 ,(cat + 1) // 2 ) for cat in self.cardinality] A = num_parallel_samples # Transformer architecture configuration A = input_size * len(self.lags_sequence ) + self._number_of_features A = d_model A = encoder_attention_heads A = decoder_attention_heads A = encoder_ffn_dim A = decoder_ffn_dim A = encoder_layers A = decoder_layers A = dropout A = attention_dropout A = activation_dropout A = encoder_layerdrop A = decoder_layerdrop A = activation_function A = init_std A = use_cache # Informer A = attention_type A = sampling_factor A = distil super().__init__(is_encoder_decoder=A_ ,**A_ ) @property def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> int: return ( sum(self.embedding_dimension ) + self.num_dynamic_real_features + self.num_time_features + self.num_static_real_features + self.input_size * 2 # the log1p(abs(loc)) and log(scale) features )
74
"""simple docstring""" import unittest from transformers import XLMConfig, is_torch_available from transformers.testing_utils import require_torch, slow, 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 ( XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMWithLMHeadModel, ) from transformers.models.xlm.modeling_xlm import XLM_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Optional[Any] ,A_ : str ,A_ : Dict=13 ,A_ : str=7 ,A_ : str=True ,A_ : Any=True ,A_ : Optional[Any]=True ,A_ : Any=True ,A_ : Optional[Any]=True ,A_ : Any=False ,A_ : str=False ,A_ : Tuple=False ,A_ : str=2 ,A_ : Optional[int]=99 ,A_ : Union[str, Any]=0 ,A_ : Optional[Any]=32 ,A_ : Optional[int]=5 ,A_ : Optional[int]=4 ,A_ : Union[str, Any]=0.1 ,A_ : List[str]=0.1 ,A_ : Union[str, Any]=512 ,A_ : Union[str, Any]=2 ,A_ : Any=0.02 ,A_ : List[str]=2 ,A_ : int=4 ,A_ : int="last" ,A_ : Dict=True ,A_ : Union[str, Any]=None ,A_ : Any=0 ,) -> List[Any]: A = parent A = batch_size A = seq_length A = is_training A = use_input_lengths A = use_token_type_ids A = use_labels A = gelu_activation A = sinusoidal_embeddings A = causal A = asm A = n_langs A = vocab_size A = n_special A = hidden_size A = num_hidden_layers A = num_attention_heads A = hidden_dropout_prob A = attention_probs_dropout_prob A = max_position_embeddings A = type_sequence_label_size A = initializer_range A = num_labels A = num_choices A = summary_type A = use_proj A = scope A = bos_token_id def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Union[str, Any]: A = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) A = random_attention_mask([self.batch_size, self.seq_length] ) A = None if self.use_input_lengths: A = ( ids_tensor([self.batch_size] ,vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length A = None if self.use_token_type_ids: A = ids_tensor([self.batch_size, self.seq_length] ,self.n_langs ) 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] ,2 ).float() A = ids_tensor([self.batch_size] ,self.num_choices ) A = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Dict: return XLMConfig( vocab_size=self.vocab_size ,n_special=self.n_special ,emb_dim=self.hidden_size ,n_layers=self.num_hidden_layers ,n_heads=self.num_attention_heads ,dropout=self.hidden_dropout_prob ,attention_dropout=self.attention_probs_dropout_prob ,gelu_activation=self.gelu_activation ,sinusoidal_embeddings=self.sinusoidal_embeddings ,asm=self.asm ,causal=self.causal ,n_langs=self.n_langs ,max_position_embeddings=self.max_position_embeddings ,initializer_range=self.initializer_range ,summary_type=self.summary_type ,use_proj=self.use_proj ,num_labels=self.num_labels ,bos_token_id=self.bos_token_id ,) def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : Any ,A_ : int ,A_ : Dict ,A_ : str ,A_ : Optional[Any] ,A_ : List[str] ,A_ : Union[str, Any] ,A_ : int ,A_ : str ,) -> Any: A = XLMModel(config=A_ ) model.to(A_ ) model.eval() A = model(A_ ,lengths=A_ ,langs=A_ ) A = model(A_ ,langs=A_ ) A = model(A_ ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : Any ,A_ : str ,A_ : Optional[int] ,A_ : Union[str, Any] ,A_ : Optional[int] ,A_ : str ,A_ : Any ,A_ : str ,A_ : Dict ,) -> Dict: A = XLMWithLMHeadModel(A_ ) model.to(A_ ) model.eval() A = model(A_ ,token_type_ids=A_ ,labels=A_ ) self.parent.assertEqual(result.loss.shape ,() ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : List[str] ,A_ : Union[str, Any] ,A_ : Union[str, Any] ,A_ : List[str] ,A_ : Any ,A_ : Optional[int] ,A_ : Optional[int] ,A_ : Optional[int] ,A_ : Optional[Any] ,) -> int: A = XLMForQuestionAnsweringSimple(A_ ) model.to(A_ ) model.eval() A = model(A_ ) A = model(A_ ,start_positions=A_ ,end_positions=A_ ) A = outputs self.parent.assertEqual(result.start_logits.shape ,(self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape ,(self.batch_size, self.seq_length) ) def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Tuple ,A_ : Optional[int] ,A_ : Any ,A_ : List[Any] ,A_ : int ,A_ : Tuple ,A_ : Tuple ,A_ : List[str] ,A_ : Optional[int] ,) -> List[Any]: A = XLMForQuestionAnswering(A_ ) model.to(A_ ) model.eval() A = model(A_ ) A = model( A_ ,start_positions=A_ ,end_positions=A_ ,cls_index=A_ ,is_impossible=A_ ,p_mask=A_ ,) A = model( A_ ,start_positions=A_ ,end_positions=A_ ,cls_index=A_ ,is_impossible=A_ ,) ((A) , ) = result_with_labels.to_tuple() A = model(A_ ,start_positions=A_ ,end_positions=A_ ) ((A) , ) = result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape ,() ) self.parent.assertEqual(result.start_top_log_probs.shape ,(self.batch_size, model.config.start_n_top) ) self.parent.assertEqual(result.start_top_index.shape ,(self.batch_size, model.config.start_n_top) ) self.parent.assertEqual( result.end_top_log_probs.shape ,(self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual( result.end_top_index.shape ,(self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual(result.cls_logits.shape ,(self.batch_size,) ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : Tuple ,A_ : int ,A_ : Optional[int] ,A_ : List[str] ,A_ : str ,A_ : Optional[Any] ,A_ : Optional[int] ,A_ : Optional[Any] ,A_ : List[Any] ,) -> Optional[int]: A = XLMForSequenceClassification(A_ ) model.to(A_ ) model.eval() A = model(A_ ) A = model(A_ ,labels=A_ ) self.parent.assertEqual(result.loss.shape ,() ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) def _SCREAMING_SNAKE_CASE ( self : int ,A_ : List[Any] ,A_ : str ,A_ : Optional[Any] ,A_ : List[Any] ,A_ : Optional[int] ,A_ : Tuple ,A_ : Union[str, Any] ,A_ : Optional[int] ,A_ : Optional[int] ,) -> List[str]: A = self.num_labels A = XLMForTokenClassification(A_ ) model.to(A_ ) model.eval() A = model(A_ ,attention_mask=A_ ,labels=A_ ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.num_labels) ) def _SCREAMING_SNAKE_CASE ( self : Dict ,A_ : Optional[int] ,A_ : Union[str, Any] ,A_ : List[str] ,A_ : Optional[int] ,A_ : List[str] ,A_ : Optional[Any] ,A_ : Union[str, Any] ,A_ : Dict ,A_ : List[Any] ,) -> List[str]: A = self.num_choices A = XLMForMultipleChoice(config=A_ ) model.to(A_ ) model.eval() A = input_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() A = token_type_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() A = input_mask.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() A = model( A_ ,attention_mask=A_ ,token_type_ids=A_ ,labels=A_ ,) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_choices) ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> int: A = self.prepare_config_and_inputs() ( ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ) = config_and_inputs A = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'lengths': input_lengths} return config, inputs_dict @require_torch class lowerCAmelCase_ ( _lowercase , _lowercase , _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: Union[str, Any] = ( ( XLMModel, XLMWithLMHeadModel, XLMForQuestionAnswering, XLMForSequenceClassification, XLMForQuestionAnsweringSimple, XLMForTokenClassification, XLMForMultipleChoice, ) if is_torch_available() else () ) _lowerCamelCase: str = ( (XLMWithLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Check other models whether language generation is also applicable _lowerCamelCase: Optional[int] = ( { '''feature-extraction''': XLMModel, '''fill-mask''': XLMWithLMHeadModel, '''question-answering''': XLMForQuestionAnsweringSimple, '''text-classification''': XLMForSequenceClassification, '''text-generation''': XLMWithLMHeadModel, '''token-classification''': XLMForTokenClassification, '''zero-shot''': XLMForSequenceClassification, } if is_torch_available() else {} ) def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : Optional[int] ,A_ : Union[str, Any] ,A_ : Union[str, Any] ,A_ : Any ,A_ : Any ) -> Any: if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith('Fast' ) ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def _SCREAMING_SNAKE_CASE ( self : int ,A_ : str ,A_ : Optional[int] ,A_ : List[Any]=False ) -> int: A = super()._prepare_for_class(A_ ,A_ ,return_labels=A_ ) if return_labels: if model_class.__name__ == "XLMForQuestionAnswering": A = torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=A_ ) A = torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=A_ ) return inputs_dict def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[Any]: A = XLMModelTester(self ) A = ConfigTester(self ,config_class=A_ ,emb_dim=37 ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> str: self.config_tester.run_common_tests() def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Any: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_model(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[Any]: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_lm_head(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> Tuple: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_simple_qa(*A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> List[Any]: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_qa(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Any: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_sequence_classif(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Optional[Any]: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_token_classif(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Any: A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_for_multiple_choice(*A_ ) def _SCREAMING_SNAKE_CASE ( self : Tuple ,A_ : Union[str, Any] ,A_ : Any ,A_ : str ,A_ : Tuple ,A_ : Any ,A_ : Any=False ,A_ : Any=1 ) -> List[Any]: self.assertIsInstance(A_ ,A_ ) self.assertListEqual( [isinstance(A_ ,A_ ) for iter_attentions in attentions] ,[True] * len(A_ ) ) self.assertEqual(len(A_ ) ,(max_length - min_length) * num_beam_groups ) for idx, iter_attentions in enumerate(A_ ): # adds PAD dummy token A = min_length + idx + 1 A = min_length + idx + 1 A = ( batch_size * num_beam_groups, config.num_attention_heads, tgt_len, src_len, ) # check attn size self.assertListEqual( [layer_attention.shape for layer_attention in iter_attentions] ,[expected_shape] * len(A_ ) ) def _SCREAMING_SNAKE_CASE ( self : Dict ,A_ : Optional[int] ,A_ : str ,A_ : Optional[int] ,A_ : int ,A_ : Any ,A_ : str=False ,A_ : Any=1 ) -> Tuple: self.assertIsInstance(A_ ,A_ ) self.assertListEqual( [isinstance(A_ ,A_ ) for iter_hidden_states in hidden_states] ,[True] * len(A_ ) ,) self.assertEqual(len(A_ ) ,(max_length - min_length) * num_beam_groups ) for idx, iter_hidden_states in enumerate(A_ ): # adds PAD dummy token A = min_length + idx + 1 A = (batch_size * num_beam_groups, seq_len, config.hidden_size) # check hidden size self.assertListEqual( [layer_hidden_states.shape for layer_hidden_states in iter_hidden_states] ,[expected_shape] * len(A_ ) ,) pass @slow def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Optional[Any]: for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A = XLMModel.from_pretrained(A_ ) self.assertIsNotNone(A_ ) @require_torch class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @slow def _SCREAMING_SNAKE_CASE ( self : Dict ) -> str: A = XLMWithLMHeadModel.from_pretrained('xlm-mlm-en-2048' ) model.to(A_ ) A = torch.tensor([[14, 447]] ,dtype=torch.long ,device=A_ ) # the president A = [ 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, ] # the president the president the president the president the president the president the president the president the president the president # TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference A = model.generate(A_ ,do_sample=A_ ) self.assertListEqual(output_ids[0].cpu().numpy().tolist() ,A_ )
74
1
"""simple docstring""" import argparse import pytorch_lightning as pl import torch from torch import nn from transformers import LongformerForQuestionAnswering, LongformerModel class __UpperCAmelCase( pl.LightningModule ): """simple docstring""" def __init__( self , snake_case__ ): '''simple docstring''' super().__init__() lowercase__ : int= model lowercase__ : Any= 2 lowercase__ : Union[str, Any]= nn.Linear(self.model.config.hidden_size , self.num_labels ) def UpperCAmelCase_ ( self ): '''simple docstring''' pass def lowercase__(A , A , A ) ->Any: """simple docstring""" lowercase__ : Optional[Any]= LongformerModel.from_pretrained(A ) lowercase__ : Optional[Any]= LightningModel(A ) lowercase__ : str= torch.load(A , map_location=torch.device("cpu" ) ) lightning_model.load_state_dict(ckpt["state_dict"] ) # init longformer question answering model lowercase__ : str= LongformerForQuestionAnswering.from_pretrained(A ) # transfer weights longformer_for_qa.longformer.load_state_dict(lightning_model.model.state_dict() ) longformer_for_qa.qa_outputs.load_state_dict(lightning_model.qa_outputs.state_dict() ) longformer_for_qa.eval() # save model longformer_for_qa.save_pretrained(A ) print(f'''Conversion successful. Model saved under {pytorch_dump_folder_path}''' ) if __name__ == "__main__": a : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( """--longformer_model""", default=None, type=str, required=True, help="""model identifier of longformer. Should be either `longformer-base-4096` or `longformer-large-4096`.""", ) parser.add_argument( """--longformer_question_answering_ckpt_path""", default=None, type=str, required=True, help="""Path the official PyTorch Lightning Checkpoint.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) a : int = parser.parse_args() convert_longformer_qa_checkpoint_to_pytorch( args.longformer_model, args.longformer_question_answering_ckpt_path, args.pytorch_dump_folder_path )
150
"""simple docstring""" from __future__ import annotations class __UpperCAmelCase: """simple docstring""" def __init__( self , snake_case__=None ): '''simple docstring''' lowercase__ : Union[str, Any]= data lowercase__ : Optional[Any]= None def __repr__( self ): '''simple docstring''' lowercase__ : str= [] lowercase__ : Tuple= self while temp: string_rep.append(F'''{temp.data}''' ) lowercase__ : Optional[int]= temp.next return "->".join(snake_case__ ) def lowercase__(A ) ->Dict: """simple docstring""" if not elements_list: raise Exception("The Elements List is empty" ) lowercase__ : Optional[int]= Node(elements_list[0] ) for i in range(1 , len(A ) ): lowercase__ : Optional[Any]= Node(elements_list[i] ) lowercase__ : str= current.next return head def lowercase__(A ) ->None: """simple docstring""" if head_node is not None and isinstance(A , A ): print_reverse(head_node.next ) print(head_node.data ) def lowercase__() ->str: """simple docstring""" from doctest import testmod testmod() lowercase__ : Optional[int]= make_linked_list([14, 52, 14, 12, 43] ) print("Linked List:" ) print(A ) print("Elements in Reverse:" ) print_reverse(A ) if __name__ == "__main__": main()
150
1
import argparse import os import sys from unittest.mock import patch import pytorch_lightning as pl import timeout_decorator import torch from distillation import SummarizationDistiller, distill_main from finetune import SummarizationModule, main from transformers import MarianMTModel from transformers.file_utils import cached_path from transformers.testing_utils import TestCasePlus, require_torch_gpu, slow from utils import load_json _lowerCamelCase ="sshleifer/mar_enro_6_3_student" class a_ ( lowerCamelCase_ ): """simple docstring""" def _lowerCAmelCase ( self : Union[str, Any] ): super().setUp() SCREAMING_SNAKE_CASE =cached_path( 'https://cdn-datasets.huggingface.co/translation/wmt_en_ro-tr40k-va0.5k-te0.5k.tar.gz' ,extract_compressed_file=snake_case ,) SCREAMING_SNAKE_CASE =f'{data_cached}/wmt_en_ro-tr40k-va0.5k-te0.5k' @slow @require_torch_gpu def _lowerCAmelCase ( self : Optional[int] ): MarianMTModel.from_pretrained(snake_case ) @slow @require_torch_gpu def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE ={ '$MAX_LEN': 64, '$BS': 64, '$GAS': 1, '$ENRO_DIR': self.data_dir, 'facebook/mbart-large-cc25': MARIAN_MODEL, # "val_check_interval=0.25": "val_check_interval=1.0", '--learning_rate=3e-5': '--learning_rate 3e-4', '--num_train_epochs 6': '--num_train_epochs 1', } # Clean up bash script SCREAMING_SNAKE_CASE =(self.test_file_dir / 'train_mbart_cc25_enro.sh').open().read().split('finetune.py' )[1].strip() SCREAMING_SNAKE_CASE =bash_script.replace('\\\n' ,'' ).strip().replace('"$@"' ,'' ) for k, v in env_vars_to_replace.items(): SCREAMING_SNAKE_CASE =bash_script.replace(snake_case ,str(snake_case ) ) SCREAMING_SNAKE_CASE =self.get_auto_remove_tmp_dir() # bash_script = bash_script.replace("--fp16 ", "") SCREAMING_SNAKE_CASE =f'\n --output_dir {output_dir}\n --tokenizer_name Helsinki-NLP/opus-mt-en-ro\n --sortish_sampler\n --do_predict\n --gpus 1\n --freeze_encoder\n --n_train 40000\n --n_val 500\n --n_test 500\n --fp16_opt_level O1\n --num_sanity_val_steps 0\n --eval_beams 2\n '.split() # XXX: args.gpus > 1 : handle multi_gpu in the future SCREAMING_SNAKE_CASE =['finetune.py'] + bash_script.split() + args with patch.object(snake_case ,'argv' ,snake_case ): SCREAMING_SNAKE_CASE =argparse.ArgumentParser() SCREAMING_SNAKE_CASE =pl.Trainer.add_argparse_args(snake_case ) SCREAMING_SNAKE_CASE =SummarizationModule.add_model_specific_args(snake_case ,os.getcwd() ) SCREAMING_SNAKE_CASE =parser.parse_args() SCREAMING_SNAKE_CASE =main(snake_case ) # Check metrics SCREAMING_SNAKE_CASE =load_json(model.metrics_save_path ) SCREAMING_SNAKE_CASE =metrics['val'][0] SCREAMING_SNAKE_CASE =metrics['val'][-1] self.assertEqual(len(metrics['val'] ) ,(args.max_epochs / args.val_check_interval) ) assert isinstance(last_step_stats[f'val_avg_{model.val_metric}'] ,snake_case ) self.assertGreater(last_step_stats['val_avg_gen_time'] ,0.01 ) # model hanging on generate. Maybe bad config was saved. (XXX: old comment/assert?) self.assertLessEqual(last_step_stats['val_avg_gen_time'] ,1.0 ) # test learning requirements: # 1. BLEU improves over the course of training by more than 2 pts self.assertGreater(last_step_stats['val_avg_bleu'] - first_step_stats['val_avg_bleu'] ,2 ) # 2. BLEU finishes above 17 self.assertGreater(last_step_stats['val_avg_bleu'] ,17 ) # 3. test BLEU and val BLEU within ~1.1 pt. self.assertLess(abs(metrics['val'][-1]['val_avg_bleu'] - metrics['test'][-1]['test_avg_bleu'] ) ,1.1 ) # check lightning ckpt can be loaded and has a reasonable statedict SCREAMING_SNAKE_CASE =os.listdir(snake_case ) SCREAMING_SNAKE_CASE =[x for x in contents if x.endswith('.ckpt' )][0] SCREAMING_SNAKE_CASE =os.path.join(args.output_dir ,snake_case ) SCREAMING_SNAKE_CASE =torch.load(snake_case ,map_location='cpu' ) SCREAMING_SNAKE_CASE ='model.model.decoder.layers.0.encoder_attn_layer_norm.weight' assert expected_key in ckpt["state_dict"] assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa # TODO: turn on args.do_predict when PL bug fixed. if args.do_predict: SCREAMING_SNAKE_CASE ={os.path.basename(snake_case ) for p in contents} assert "test_generations.txt" in contents assert "test_results.txt" in contents # assert len(metrics["val"]) == desired_n_evals assert len(metrics['test'] ) == 1 class a_ ( lowerCamelCase_ ): """simple docstring""" @timeout_decorator.timeout(600 ) @slow @require_torch_gpu def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =f'{self.test_file_dir_str}/test_data/wmt_en_ro' SCREAMING_SNAKE_CASE ={ '--fp16_opt_level=O1': '', '$MAX_LEN': 128, '$BS': 16, '$GAS': 1, '$ENRO_DIR': data_dir, '$m': 'sshleifer/student_marian_en_ro_6_1', 'val_check_interval=0.25': 'val_check_interval=1.0', } # Clean up bash script SCREAMING_SNAKE_CASE =( (self.test_file_dir / 'distil_marian_no_teacher.sh').open().read().split('distillation.py' )[1].strip() ) SCREAMING_SNAKE_CASE =bash_script.replace('\\\n' ,'' ).strip().replace('"$@"' ,'' ) SCREAMING_SNAKE_CASE =bash_script.replace('--fp16 ' ,' ' ) for k, v in env_vars_to_replace.items(): SCREAMING_SNAKE_CASE =bash_script.replace(snake_case ,str(snake_case ) ) SCREAMING_SNAKE_CASE =self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE =bash_script.replace('--fp16' ,'' ) SCREAMING_SNAKE_CASE =6 SCREAMING_SNAKE_CASE =( ['distillation.py'] + bash_script.split() + [ f'--output_dir={output_dir}', '--gpus=1', '--learning_rate=1e-3', f'--num_train_epochs={epochs}', '--warmup_steps=10', '--val_check_interval=1.0', '--do_predict', ] ) with patch.object(snake_case ,'argv' ,snake_case ): SCREAMING_SNAKE_CASE =argparse.ArgumentParser() SCREAMING_SNAKE_CASE =pl.Trainer.add_argparse_args(snake_case ) SCREAMING_SNAKE_CASE =SummarizationDistiller.add_model_specific_args(snake_case ,os.getcwd() ) SCREAMING_SNAKE_CASE =parser.parse_args() # assert args.gpus == gpus THIS BREAKS for multi_gpu SCREAMING_SNAKE_CASE =distill_main(snake_case ) # Check metrics SCREAMING_SNAKE_CASE =load_json(model.metrics_save_path ) SCREAMING_SNAKE_CASE =metrics['val'][0] SCREAMING_SNAKE_CASE =metrics['val'][-1] assert len(metrics['val'] ) >= (args.max_epochs / args.val_check_interval) # +1 accounts for val_sanity_check assert last_step_stats["val_avg_gen_time"] >= 0.01 assert first_step_stats["val_avg_bleu"] < last_step_stats["val_avg_bleu"] # model learned nothing assert 1.0 >= last_step_stats["val_avg_gen_time"] # model hanging on generate. Maybe bad config was saved. assert isinstance(last_step_stats[f'val_avg_{model.val_metric}'] ,snake_case ) # check lightning ckpt can be loaded and has a reasonable statedict SCREAMING_SNAKE_CASE =os.listdir(snake_case ) SCREAMING_SNAKE_CASE =[x for x in contents if x.endswith('.ckpt' )][0] SCREAMING_SNAKE_CASE =os.path.join(args.output_dir ,snake_case ) SCREAMING_SNAKE_CASE =torch.load(snake_case ,map_location='cpu' ) SCREAMING_SNAKE_CASE ='model.model.decoder.layers.0.encoder_attn_layer_norm.weight' assert expected_key in ckpt["state_dict"] assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa # TODO: turn on args.do_predict when PL bug fixed. if args.do_predict: SCREAMING_SNAKE_CASE ={os.path.basename(snake_case ) for p in contents} assert "test_generations.txt" in contents assert "test_results.txt" in contents # assert len(metrics["val"]) == desired_n_evals assert len(metrics['test'] ) == 1
334
import faiss # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import requests # noqa: F401 # Here to have a nice missing dependency error message early on import sklearn # noqa: F401 # Here to have a nice missing dependency error message early on import tqdm # noqa: F401 # Here to have a nice missing dependency error message early on from mauve import compute_mauve # From: mauve-text import datasets _lowerCamelCase ="\\n@inproceedings{pillutla-etal:mauve:neurips2021,\n title={MAUVE: Measuring the Gap Between Neural Text and Human Text using Divergence Frontiers},\n author={Pillutla, Krishna and Swayamdipta, Swabha and Zellers, Rowan and Thickstun, John and Welleck, Sean and Choi, Yejin and Harchaoui, Zaid},\n booktitle = {NeurIPS},\n year = {2021}\n}\n\n" _lowerCamelCase ="\\nMAUVE is a library built on PyTorch and HuggingFace Transformers to measure the gap between neural text and human text with the eponymous MAUVE measure.\n\nMAUVE summarizes both Type I and Type II errors measured softly using Kullback–Leibler (KL) divergences.\n\nFor details, see the MAUVE paper: https://arxiv.org/abs/2102.01454 (Neurips, 2021).\n\nThis metrics is a wrapper around the official implementation of MAUVE:\nhttps://github.com/krishnap25/mauve\n" _lowerCamelCase ="\nCalculates MAUVE scores between two lists of generated text and reference text.\nArgs:\n predictions: list of generated text to score. Each predictions\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\nOptional Args:\n num_buckets: the size of the histogram to quantize P and Q. Options: 'auto' (default) or an integer\n pca_max_data: the number data points to use for PCA dimensionality reduction prior to clustering. If -1, use all the data. Default -1\n kmeans_explained_var: amount of variance of the data to keep in dimensionality reduction by PCA. Default 0.9\n kmeans_num_redo: number of times to redo k-means clustering (the best objective is kept). Default 5\n kmeans_max_iter: maximum number of k-means iterations. Default 500\n featurize_model_name: name of the model from which features are obtained. Default 'gpt2-large' Use one of ['gpt2', 'gpt2-medium', 'gpt2-large', 'gpt2-xl'].\n device_id: Device for featurization. Supply a GPU id (e.g. 0 or 3) to use GPU. If no GPU with this id is found, use CPU\n max_text_length: maximum number of tokens to consider. Default 1024\n divergence_curve_discretization_size: Number of points to consider on the divergence curve. Default 25\n mauve_scaling_factor: \"c\" from the paper. Default 5.\n verbose: If True (default), print running time updates\n seed: random seed to initialize k-means cluster assignments.\nReturns:\n mauve: MAUVE score, a number between 0 and 1. Larger values indicate that P and Q are closer,\n frontier_integral: Frontier Integral, a number between 0 and 1. Smaller values indicate that P and Q are closer,\n divergence_curve: a numpy.ndarray of shape (m, 2); plot it with matplotlib to view the divergence curve,\n p_hist: a discrete distribution, which is a quantized version of the text distribution p_text,\n q_hist: same as above, but with q_text.\nExamples:\n\n >>> # faiss segfaults in doctest for some reason, so the .compute call is not tested with doctest\n >>> import datasets\n >>> mauve = datasets.load_metric('mauve')\n >>> predictions = [\"hello there\", \"general kenobi\"]\n >>> references = [\"hello there\", \"general kenobi\"]\n >>> out = mauve.compute(predictions=predictions, references=references) # doctest: +SKIP\n >>> print(out.mauve) # doctest: +SKIP\n 1.0\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a_ ( datasets.Metric ): """simple docstring""" def _lowerCAmelCase ( self : Tuple ): return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,homepage='https://github.com/krishnap25/mauve' ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { 'predictions': datasets.Value('string' ,id='sequence' ), 'references': datasets.Value('string' ,id='sequence' ), } ) ,codebase_urls=['https://github.com/krishnap25/mauve'] ,reference_urls=[ 'https://arxiv.org/abs/2102.01454', 'https://github.com/krishnap25/mauve', ] ,) def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : Optional[int] ,snake_case : str ,snake_case : List[str]=None ,snake_case : str=None ,snake_case : int=None ,snake_case : Union[str, Any]=None ,snake_case : Optional[int]="auto" ,snake_case : List[str]=-1 ,snake_case : Union[str, Any]=0.9 ,snake_case : Tuple=5 ,snake_case : Union[str, Any]=500 ,snake_case : Union[str, Any]="gpt2-large" ,snake_case : Union[str, Any]=-1 ,snake_case : Optional[Any]=1024 ,snake_case : Optional[Any]=25 ,snake_case : List[str]=5 ,snake_case : List[str]=True ,snake_case : Optional[Any]=25 ,): SCREAMING_SNAKE_CASE =compute_mauve( p_text=snake_case ,q_text=snake_case ,p_features=snake_case ,q_features=snake_case ,p_tokens=snake_case ,q_tokens=snake_case ,num_buckets=snake_case ,pca_max_data=snake_case ,kmeans_explained_var=snake_case ,kmeans_num_redo=snake_case ,kmeans_max_iter=snake_case ,featurize_model_name=snake_case ,device_id=snake_case ,max_text_length=snake_case ,divergence_curve_discretization_size=snake_case ,mauve_scaling_factor=snake_case ,verbose=snake_case ,seed=snake_case ,) return out
334
1
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging SCREAMING_SNAKE_CASE = logging.get_logger(__name__) SCREAMING_SNAKE_CASE = { "andreasmadsen/efficient_mlm_m0.40": ( "https://huggingface.co/andreasmadsen/efficient_mlm_m0.40/resolve/main/config.json" ), } class UpperCAmelCase_ ( _SCREAMING_SNAKE_CASE ): lowercase__ = '''roberta-prelayernorm''' def __init__( self : Tuple , snake_case_ : Any=50_265 , snake_case_ : Optional[int]=768 , snake_case_ : List[Any]=12 , snake_case_ : int=12 , snake_case_ : Optional[Any]=3_072 , snake_case_ : int="gelu" , snake_case_ : List[Any]=0.1 , snake_case_ : List[str]=0.1 , snake_case_ : Dict=512 , snake_case_ : Tuple=2 , snake_case_ : Optional[int]=0.02 , snake_case_ : Any=1e-12 , snake_case_ : int=1 , snake_case_ : Dict=0 , snake_case_ : Optional[Any]=2 , snake_case_ : List[Any]="absolute" , snake_case_ : int=True , snake_case_ : Tuple=None , **snake_case_ : Optional[int] , ) -> Dict: '''simple docstring''' super().__init__(pad_token_id=snake_case_ , bos_token_id=snake_case_ , eos_token_id=snake_case_ , **snake_case_ ) A__ = vocab_size A__ = hidden_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__ = position_embedding_type A__ = use_cache A__ = classifier_dropout class UpperCAmelCase_ ( _SCREAMING_SNAKE_CASE ): @property def __magic_name__ ( self : Dict ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task == "multiple-choice": A__ = {0: """batch""", 1: """choice""", 2: """sequence"""} else: A__ = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
351
"""simple docstring""" import unittest from transformers.testing_utils import CaptureStdout from transformers.tools.python_interpreter import evaluate def _SCREAMING_SNAKE_CASE ( lowercase_ ) -> int: return x + 2 class UpperCAmelCase_ ( unittest.TestCase ): def __magic_name__ ( self : Any ) -> Any: '''simple docstring''' A__ = "x = 3" A__ = {} A__ = evaluate(snake_case_ , {} , state=snake_case_ ) assert result == 3 self.assertDictEqual(snake_case_ , {"x": 3} ) A__ = "x = y" A__ = {"y": 5} A__ = evaluate(snake_case_ , {} , state=snake_case_ ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(snake_case_ , {"x": 5, "y": 5} ) def __magic_name__ ( self : Optional[Any] ) -> Any: '''simple docstring''' A__ = "y = add_two(x)" A__ = {"x": 3} A__ = evaluate(snake_case_ , {"add_two": add_two} , state=snake_case_ ) assert result == 5 self.assertDictEqual(snake_case_ , {"x": 3, "y": 5} ) # Won't work without the tool with CaptureStdout() as out: A__ = evaluate(snake_case_ , {} , state=snake_case_ ) assert result is None assert "tried to execute add_two" in out.out def __magic_name__ ( self : Dict ) -> List[str]: '''simple docstring''' A__ = "x = 3" A__ = {} A__ = evaluate(snake_case_ , {} , state=snake_case_ ) assert result == 3 self.assertDictEqual(snake_case_ , {"x": 3} ) def __magic_name__ ( self : Dict ) -> Optional[Any]: '''simple docstring''' A__ = "test_dict = {'x': x, 'y': add_two(x)}" A__ = {"x": 3} A__ = evaluate(snake_case_ , {"add_two": add_two} , state=snake_case_ ) self.assertDictEqual(snake_case_ , {"x": 3, "y": 5} ) self.assertDictEqual(snake_case_ , {"x": 3, "test_dict": {"x": 3, "y": 5}} ) def __magic_name__ ( self : int ) -> str: '''simple docstring''' A__ = "x = 3\ny = 5" A__ = {} A__ = evaluate(snake_case_ , {} , state=snake_case_ ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(snake_case_ , {"x": 3, "y": 5} ) def __magic_name__ ( self : Any ) -> List[Any]: '''simple docstring''' A__ = "text = f'This is x: {x}.'" A__ = {"x": 3} A__ = evaluate(snake_case_ , {} , state=snake_case_ ) # evaluate returns the value of the last assignment. assert result == "This is x: 3." self.assertDictEqual(snake_case_ , {"x": 3, "text": "This is x: 3."} ) def __magic_name__ ( self : str ) -> Optional[int]: '''simple docstring''' A__ = "if x <= 3:\n y = 2\nelse:\n y = 5" A__ = {"x": 3} A__ = evaluate(snake_case_ , {} , state=snake_case_ ) # evaluate returns the value of the last assignment. assert result == 2 self.assertDictEqual(snake_case_ , {"x": 3, "y": 2} ) A__ = {"x": 8} A__ = evaluate(snake_case_ , {} , state=snake_case_ ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(snake_case_ , {"x": 8, "y": 5} ) def __magic_name__ ( self : List[str] ) -> Tuple: '''simple docstring''' A__ = "test_list = [x, add_two(x)]" A__ = {"x": 3} A__ = evaluate(snake_case_ , {"add_two": add_two} , state=snake_case_ ) self.assertListEqual(snake_case_ , [3, 5] ) self.assertDictEqual(snake_case_ , {"x": 3, "test_list": [3, 5]} ) def __magic_name__ ( self : Tuple ) -> int: '''simple docstring''' A__ = "y = x" A__ = {"x": 3} A__ = evaluate(snake_case_ , {} , state=snake_case_ ) assert result == 3 self.assertDictEqual(snake_case_ , {"x": 3, "y": 3} ) def __magic_name__ ( self : str ) -> Dict: '''simple docstring''' A__ = "test_list = [x, add_two(x)]\ntest_list[1]" A__ = {"x": 3} A__ = evaluate(snake_case_ , {"add_two": add_two} , state=snake_case_ ) assert result == 5 self.assertDictEqual(snake_case_ , {"x": 3, "test_list": [3, 5]} ) A__ = "test_dict = {'x': x, 'y': add_two(x)}\ntest_dict['y']" A__ = {"x": 3} A__ = evaluate(snake_case_ , {"add_two": add_two} , state=snake_case_ ) assert result == 5 self.assertDictEqual(snake_case_ , {"x": 3, "test_dict": {"x": 3, "y": 5}} ) def __magic_name__ ( self : Optional[int] ) -> Tuple: '''simple docstring''' A__ = "x = 0\nfor i in range(3):\n x = i" A__ = {} A__ = evaluate(snake_case_ , {"range": range} , state=snake_case_ ) assert result == 2 self.assertDictEqual(snake_case_ , {"x": 2, "i": 2} )
230
0
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, BertTokenizer, BlipImageProcessor, BlipProcessor, PreTrainedTokenizerFast @require_vision class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCamelCase ( self : Dict ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE : Optional[Any] = BlipImageProcessor() SCREAMING_SNAKE_CASE : Optional[Any] = BertTokenizer.from_pretrained("hf-internal-testing/tiny-random-BertModel" ) SCREAMING_SNAKE_CASE : List[str] = BlipProcessor(a , a ) processor.save_pretrained(self.tmpdirname ) def __UpperCamelCase ( self : Any , **a : Tuple ) -> Dict: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **a ).tokenizer def __UpperCamelCase ( self : int , **a : List[Any] ) -> Union[str, Any]: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **a ).image_processor def __UpperCamelCase ( self : Tuple ) -> Optional[int]: """simple docstring""" shutil.rmtree(self.tmpdirname ) def __UpperCamelCase ( self : str ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE : Optional[Any] = [Image.fromarray(np.moveaxis(a , 0 , -1 ) ) for x in image_inputs] return image_inputs def __UpperCamelCase ( self : Optional[Any] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = BlipProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE : Optional[Any] = self.get_tokenizer(bos_token="(BOS)" , eos_token="(EOS)" ) SCREAMING_SNAKE_CASE : List[Any] = self.get_image_processor(do_normalize=a , padding_value=1.0 ) SCREAMING_SNAKE_CASE : Union[str, Any] = BlipProcessor.from_pretrained( self.tmpdirname , bos_token="(BOS)" , eos_token="(EOS)" , do_normalize=a , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , a ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , a ) def __UpperCamelCase ( self : Any ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE : Any = self.get_image_processor() SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer() SCREAMING_SNAKE_CASE : str = BlipProcessor(tokenizer=a , image_processor=a ) SCREAMING_SNAKE_CASE : Tuple = self.prepare_image_inputs() SCREAMING_SNAKE_CASE : Tuple = image_processor(a , return_tensors="np" ) SCREAMING_SNAKE_CASE : Dict = processor(images=a , 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 __UpperCamelCase ( self : Union[str, Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = self.get_image_processor() SCREAMING_SNAKE_CASE : int = self.get_tokenizer() SCREAMING_SNAKE_CASE : Optional[Any] = BlipProcessor(tokenizer=a , image_processor=a ) SCREAMING_SNAKE_CASE : List[str] = "lower newer" SCREAMING_SNAKE_CASE : Tuple = processor(text=a ) SCREAMING_SNAKE_CASE : str = tokenizer(a , return_token_type_ids=a ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def __UpperCamelCase ( self : Tuple ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = self.get_image_processor() SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer() SCREAMING_SNAKE_CASE : List[str] = BlipProcessor(tokenizer=a , image_processor=a ) SCREAMING_SNAKE_CASE : Any = "lower newer" SCREAMING_SNAKE_CASE : Optional[int] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE : Any = processor(text=a , images=a ) self.assertListEqual(list(inputs.keys() ) , ["pixel_values", "input_ids", "attention_mask"] ) # test if it raises when no input is passed with pytest.raises(a ): processor() def __UpperCamelCase ( self : Tuple ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE : str = self.get_image_processor() SCREAMING_SNAKE_CASE : Dict = self.get_tokenizer() SCREAMING_SNAKE_CASE : List[str] = BlipProcessor(tokenizer=a , image_processor=a ) SCREAMING_SNAKE_CASE : Optional[Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] SCREAMING_SNAKE_CASE : Union[str, Any] = processor.batch_decode(a ) SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer.batch_decode(a ) self.assertListEqual(a , a ) def __UpperCamelCase ( self : List[str] ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE : str = self.get_image_processor() SCREAMING_SNAKE_CASE : str = self.get_tokenizer() SCREAMING_SNAKE_CASE : List[str] = BlipProcessor(tokenizer=a , image_processor=a ) SCREAMING_SNAKE_CASE : Optional[int] = "lower newer" SCREAMING_SNAKE_CASE : Any = self.prepare_image_inputs() SCREAMING_SNAKE_CASE : Union[str, Any] = processor(text=a , images=a ) # For now the processor supports only ['pixel_values', 'input_ids', 'attention_mask'] self.assertListEqual(list(inputs.keys() ) , ["pixel_values", "input_ids", "attention_mask"] )
76
'''simple docstring''' import inspect import os import sys import unittest import accelerate from accelerate.test_utils import execute_subprocess_async, require_tpu class a__ ( unittest.TestCase ): def _lowerCamelCase ( self ): """simple docstring""" _lowercase : str = inspect.getfile(accelerate.test_utils ) _lowercase : List[str] = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ["scripts", "test_script.py"] ) _lowercase : str = os.path.sep.join(inspect.getfile(self.__class__ ).split(os.path.sep )[:-1] ) @require_tpu def _lowerCamelCase ( self ): """simple docstring""" _lowercase : Optional[Any] = f''' {self.test_dir}/xla_spawn.py --num_cores 8 {self.test_file_path} '''.split() _lowercase : Tuple = [sys.executable] + distributed_args execute_subprocess_async(_UpperCamelCase , env=os.environ.copy() )
250
0
'''simple docstring''' from typing import List, Optional, Tuple, Union import torch from torch import nn from torch.nn import CrossEntropyLoss from ... import AutoBackbone from ...modeling_outputs import SemanticSegmenterOutput from ...modeling_utils import PreTrainedModel from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, replace_return_docstrings from ...utils.backbone_utils import BackboneMixin from .configuration_upernet import UperNetConfig _a : Dict = [ """openmmlab/upernet-convnext-tiny""", # See all UperNet models at https://huggingface.co/models?filter=upernet ] # General docstring _a : Optional[Any] = """UperNetConfig""" class _UpperCAmelCase ( nn.Module ): def __init__( self,__SCREAMING_SNAKE_CASE,__SCREAMING_SNAKE_CASE,__SCREAMING_SNAKE_CASE,__SCREAMING_SNAKE_CASE = 0,__SCREAMING_SNAKE_CASE = False,__SCREAMING_SNAKE_CASE = 1,): '''simple docstring''' super().__init__() __lowerCAmelCase = nn.Convad( in_channels=__SCREAMING_SNAKE_CASE,out_channels=__SCREAMING_SNAKE_CASE,kernel_size=__SCREAMING_SNAKE_CASE,padding=__SCREAMING_SNAKE_CASE,bias=__SCREAMING_SNAKE_CASE,dilation=__SCREAMING_SNAKE_CASE,) __lowerCAmelCase = nn.BatchNormad(__SCREAMING_SNAKE_CASE ) __lowerCAmelCase = nn.ReLU() def lowerCamelCase__ ( self,__SCREAMING_SNAKE_CASE ): '''simple docstring''' __lowerCAmelCase = self.conv(__SCREAMING_SNAKE_CASE ) __lowerCAmelCase = self.batch_norm(__SCREAMING_SNAKE_CASE ) __lowerCAmelCase = self.activation(__SCREAMING_SNAKE_CASE ) return output class _UpperCAmelCase ( nn.Module ): def __init__( self,__SCREAMING_SNAKE_CASE,__SCREAMING_SNAKE_CASE,__SCREAMING_SNAKE_CASE ): '''simple docstring''' super().__init__() __lowerCAmelCase = [ nn.AdaptiveAvgPoolad(__SCREAMING_SNAKE_CASE ), UperNetConvModule(__SCREAMING_SNAKE_CASE,__SCREAMING_SNAKE_CASE,kernel_size=1 ), ] for i, layer in enumerate(self.layers ): self.add_module(str(__SCREAMING_SNAKE_CASE ),__SCREAMING_SNAKE_CASE ) def lowerCamelCase__ ( self,__SCREAMING_SNAKE_CASE ): '''simple docstring''' __lowerCAmelCase = input for layer in self.layers: __lowerCAmelCase = layer(__SCREAMING_SNAKE_CASE ) return hidden_state class _UpperCAmelCase ( nn.Module ): def __init__( self,__SCREAMING_SNAKE_CASE,__SCREAMING_SNAKE_CASE,__SCREAMING_SNAKE_CASE,__SCREAMING_SNAKE_CASE ): '''simple docstring''' super().__init__() __lowerCAmelCase = pool_scales __lowerCAmelCase = align_corners __lowerCAmelCase = in_channels __lowerCAmelCase = channels __lowerCAmelCase = [] for i, pool_scale in enumerate(__SCREAMING_SNAKE_CASE ): __lowerCAmelCase = UperNetPyramidPoolingBlock(pool_scale=__SCREAMING_SNAKE_CASE,in_channels=__SCREAMING_SNAKE_CASE,channels=__SCREAMING_SNAKE_CASE ) self.blocks.append(__SCREAMING_SNAKE_CASE ) self.add_module(str(__SCREAMING_SNAKE_CASE ),__SCREAMING_SNAKE_CASE ) def lowerCamelCase__ ( self,__SCREAMING_SNAKE_CASE ): '''simple docstring''' __lowerCAmelCase = [] for ppm in self.blocks: __lowerCAmelCase = ppm(__SCREAMING_SNAKE_CASE ) __lowerCAmelCase = nn.functional.interpolate( __SCREAMING_SNAKE_CASE,size=x.size()[2:],mode="""bilinear""",align_corners=self.align_corners ) ppm_outs.append(__SCREAMING_SNAKE_CASE ) return ppm_outs class _UpperCAmelCase ( nn.Module ): def __init__( self,__SCREAMING_SNAKE_CASE,__SCREAMING_SNAKE_CASE ): '''simple docstring''' super().__init__() __lowerCAmelCase = config __lowerCAmelCase = config.pool_scales # e.g. (1, 2, 3, 6) __lowerCAmelCase = in_channels __lowerCAmelCase = config.hidden_size __lowerCAmelCase = False __lowerCAmelCase = nn.Convad(self.channels,config.num_labels,kernel_size=1 ) # PSP Module __lowerCAmelCase = UperNetPyramidPoolingModule( self.pool_scales,self.in_channels[-1],self.channels,align_corners=self.align_corners,) __lowerCAmelCase = UperNetConvModule( self.in_channels[-1] + len(self.pool_scales ) * self.channels,self.channels,kernel_size=3,padding=1,) # FPN Module __lowerCAmelCase = nn.ModuleList() __lowerCAmelCase = nn.ModuleList() for in_channels in self.in_channels[:-1]: # skip the top layer __lowerCAmelCase = UperNetConvModule(__SCREAMING_SNAKE_CASE,self.channels,kernel_size=1 ) __lowerCAmelCase = UperNetConvModule(self.channels,self.channels,kernel_size=3,padding=1 ) self.lateral_convs.append(__SCREAMING_SNAKE_CASE ) self.fpn_convs.append(__SCREAMING_SNAKE_CASE ) __lowerCAmelCase = UperNetConvModule( len(self.in_channels ) * self.channels,self.channels,kernel_size=3,padding=1,) def lowerCamelCase__ ( self ): '''simple docstring''' self.apply(self._init_weights ) def lowerCamelCase__ ( self,__SCREAMING_SNAKE_CASE ): '''simple docstring''' if isinstance(__SCREAMING_SNAKE_CASE,nn.Convad ): module.weight.data.normal_(mean=0.0,std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() def lowerCamelCase__ ( self,__SCREAMING_SNAKE_CASE ): '''simple docstring''' __lowerCAmelCase = inputs[-1] __lowerCAmelCase = [x] psp_outs.extend(self.psp_modules(__SCREAMING_SNAKE_CASE ) ) __lowerCAmelCase = torch.cat(__SCREAMING_SNAKE_CASE,dim=1 ) __lowerCAmelCase = self.bottleneck(__SCREAMING_SNAKE_CASE ) return output def lowerCamelCase__ ( self,__SCREAMING_SNAKE_CASE ): '''simple docstring''' __lowerCAmelCase = [lateral_conv(encoder_hidden_states[i] ) for i, lateral_conv in enumerate(self.lateral_convs )] laterals.append(self.psp_forward(__SCREAMING_SNAKE_CASE ) ) # build top-down path __lowerCAmelCase = len(__SCREAMING_SNAKE_CASE ) for i in range(used_backbone_levels - 1,0,-1 ): __lowerCAmelCase = laterals[i - 1].shape[2:] __lowerCAmelCase = laterals[i - 1] + nn.functional.interpolate( laterals[i],size=__SCREAMING_SNAKE_CASE,mode="""bilinear""",align_corners=self.align_corners ) # build outputs __lowerCAmelCase = [self.fpn_convs[i](laterals[i] ) for i in range(used_backbone_levels - 1 )] # append psp feature fpn_outs.append(laterals[-1] ) for i in range(used_backbone_levels - 1,0,-1 ): __lowerCAmelCase = nn.functional.interpolate( fpn_outs[i],size=fpn_outs[0].shape[2:],mode="""bilinear""",align_corners=self.align_corners ) __lowerCAmelCase = torch.cat(__SCREAMING_SNAKE_CASE,dim=1 ) __lowerCAmelCase = self.fpn_bottleneck(__SCREAMING_SNAKE_CASE ) __lowerCAmelCase = self.classifier(__SCREAMING_SNAKE_CASE ) return output class _UpperCAmelCase ( nn.Module ): def __init__( self,__SCREAMING_SNAKE_CASE,__SCREAMING_SNAKE_CASE = 2,__SCREAMING_SNAKE_CASE = 3,__SCREAMING_SNAKE_CASE = 1 ): '''simple docstring''' super().__init__() __lowerCAmelCase = config __lowerCAmelCase = config.auxiliary_in_channels __lowerCAmelCase = config.auxiliary_channels __lowerCAmelCase = config.auxiliary_num_convs __lowerCAmelCase = config.auxiliary_concat_input __lowerCAmelCase = in_index __lowerCAmelCase = (kernel_size // 2) * dilation __lowerCAmelCase = [] convs.append( UperNetConvModule( self.in_channels,self.channels,kernel_size=__SCREAMING_SNAKE_CASE,padding=__SCREAMING_SNAKE_CASE,dilation=__SCREAMING_SNAKE_CASE ) ) for i in range(self.num_convs - 1 ): convs.append( UperNetConvModule( self.channels,self.channels,kernel_size=__SCREAMING_SNAKE_CASE,padding=__SCREAMING_SNAKE_CASE,dilation=__SCREAMING_SNAKE_CASE ) ) if self.num_convs == 0: __lowerCAmelCase = nn.Identity() else: __lowerCAmelCase = nn.Sequential(*__SCREAMING_SNAKE_CASE ) if self.concat_input: __lowerCAmelCase = UperNetConvModule( self.in_channels + self.channels,self.channels,kernel_size=__SCREAMING_SNAKE_CASE,padding=kernel_size // 2 ) __lowerCAmelCase = nn.Convad(self.channels,config.num_labels,kernel_size=1 ) def lowerCamelCase__ ( self ): '''simple docstring''' self.apply(self._init_weights ) def lowerCamelCase__ ( self,__SCREAMING_SNAKE_CASE ): '''simple docstring''' if isinstance(__SCREAMING_SNAKE_CASE,nn.Convad ): module.weight.data.normal_(mean=0.0,std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() def lowerCamelCase__ ( self,__SCREAMING_SNAKE_CASE ): '''simple docstring''' __lowerCAmelCase = encoder_hidden_states[self.in_index] __lowerCAmelCase = self.convs(__SCREAMING_SNAKE_CASE ) if self.concat_input: __lowerCAmelCase = self.conv_cat(torch.cat([hidden_states, output],dim=1 ) ) __lowerCAmelCase = self.classifier(__SCREAMING_SNAKE_CASE ) return output class _UpperCAmelCase ( lowerCAmelCase_ ): a : Tuple =UperNetConfig a : List[str] ="""pixel_values""" a : Dict =True def lowerCamelCase__ ( self,__SCREAMING_SNAKE_CASE ): '''simple docstring''' if isinstance(__SCREAMING_SNAKE_CASE,__SCREAMING_SNAKE_CASE ): module.backbone.init_weights() module.decode_head.init_weights() module.auxiliary_head.init_weights() def lowerCamelCase__ ( self ): '''simple docstring''' self.backbone.init_weights() self.decode_head.init_weights() self.auxiliary_head.init_weights() def lowerCamelCase__ ( self,__SCREAMING_SNAKE_CASE,__SCREAMING_SNAKE_CASE=False ): '''simple docstring''' if isinstance(__SCREAMING_SNAKE_CASE,__SCREAMING_SNAKE_CASE ): __lowerCAmelCase = value _a : Dict = r""" Parameters: This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. config ([`UperNetConfig`]): 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 [`~PreTrainedModel.from_pretrained`] method to load the model weights. """ _a : Optional[int] = r""" Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using [`AutoImageProcessor`]. See [`SegformerImageProcessor.__call__`] for details. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers in case the backbone has them. See `attentions` under returned tensors for more detail. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers of the backbone. 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( """UperNet framework leveraging any vision backbone e.g. for ADE20k, CityScapes.""" , lowerCAmelCase_ , ) class _UpperCAmelCase ( lowerCAmelCase_ ): def __init__( self,__SCREAMING_SNAKE_CASE ): '''simple docstring''' super().__init__(__SCREAMING_SNAKE_CASE ) __lowerCAmelCase = AutoBackbone.from_config(config.backbone_config ) # Semantic segmentation head(s) __lowerCAmelCase = UperNetHead(__SCREAMING_SNAKE_CASE,in_channels=self.backbone.channels ) __lowerCAmelCase = UperNetFCNHead(__SCREAMING_SNAKE_CASE ) if config.use_auxiliary_head else None # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(UPERNET_INPUTS_DOCSTRING.format("""batch_size, sequence_length""" ) ) @replace_return_docstrings(output_type=__SCREAMING_SNAKE_CASE,config_class=_CONFIG_FOR_DOC ) def lowerCamelCase__ ( self,__SCREAMING_SNAKE_CASE = None,__SCREAMING_SNAKE_CASE = None,__SCREAMING_SNAKE_CASE = None,__SCREAMING_SNAKE_CASE = None,__SCREAMING_SNAKE_CASE = None,): '''simple docstring''' __lowerCAmelCase = return_dict if return_dict is not None else self.config.use_return_dict __lowerCAmelCase = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __lowerCAmelCase = output_attentions if output_attentions is not None else self.config.output_attentions __lowerCAmelCase = self.backbone.forward_with_filtered_kwargs( __SCREAMING_SNAKE_CASE,output_hidden_states=__SCREAMING_SNAKE_CASE,output_attentions=__SCREAMING_SNAKE_CASE ) __lowerCAmelCase = outputs.feature_maps __lowerCAmelCase = self.decode_head(__SCREAMING_SNAKE_CASE ) __lowerCAmelCase = nn.functional.interpolate(__SCREAMING_SNAKE_CASE,size=pixel_values.shape[2:],mode="""bilinear""",align_corners=__SCREAMING_SNAKE_CASE ) __lowerCAmelCase = None if self.auxiliary_head is not None: __lowerCAmelCase = self.auxiliary_head(__SCREAMING_SNAKE_CASE ) __lowerCAmelCase = nn.functional.interpolate( __SCREAMING_SNAKE_CASE,size=pixel_values.shape[2:],mode="""bilinear""",align_corners=__SCREAMING_SNAKE_CASE ) __lowerCAmelCase = None if labels is not None: if self.config.num_labels == 1: raise ValueError("""The number of labels should be greater than one""" ) else: # compute weighted loss __lowerCAmelCase = CrossEntropyLoss(ignore_index=self.config.loss_ignore_index ) __lowerCAmelCase = loss_fct(__SCREAMING_SNAKE_CASE,__SCREAMING_SNAKE_CASE ) __lowerCAmelCase = loss_fct(__SCREAMING_SNAKE_CASE,__SCREAMING_SNAKE_CASE ) __lowerCAmelCase = main_loss + self.config.auxiliary_loss_weight * auxiliary_loss if not return_dict: if output_hidden_states: __lowerCAmelCase = (logits,) + outputs[1:] else: __lowerCAmelCase = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return SemanticSegmenterOutput( loss=__SCREAMING_SNAKE_CASE,logits=__SCREAMING_SNAKE_CASE,hidden_states=outputs.hidden_states,attentions=outputs.attentions,)
46
'''simple docstring''' import argparse import torch from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert from transformers.utils import logging logging.set_verbosity_info() def _lowerCAmelCase ( lowercase , lowercase , lowercase ) -> List[str]: # Initialise PyTorch model __lowerCAmelCase = BertConfig.from_json_file(lowercase ) print(f'Building PyTorch model from configuration: {config}' ) __lowerCAmelCase = BertForPreTraining(lowercase ) # Load weights from tf checkpoint load_tf_weights_in_bert(lowercase , lowercase , lowercase ) # Save pytorch-model print(f'Save PyTorch model to {pytorch_dump_path}' ) torch.save(model.state_dict() , lowercase ) if __name__ == "__main__": _a : Dict = argparse.ArgumentParser() # Required parameters parser.add_argument( """--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--bert_config_file""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained BERT model. \n""" """This specifies the model architecture.""" ), ) parser.add_argument( """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) _a : Optional[int] = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
46
1
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer from ...utils import logging lowerCAmelCase_ : int = logging.get_logger(__name__) lowerCAmelCase_ : str = '▁' lowerCAmelCase_ : Tuple = {'vocab_file': 'sentencepiece.bpe.model'} lowerCAmelCase_ : Union[str, Any] = { 'vocab_file': { 'facebook/mbart-large-50-one-to-many-mmt': ( 'https://huggingface.co/facebook/mbart-large-50-one-to-many-mmt/resolve/main/sentencepiece.bpe.model' ), } } lowerCAmelCase_ : int = { 'facebook/mbart-large-50-one-to-many-mmt': 10_24, } # fmt: off lowerCAmelCase_ : Optional[Any] = ['ar_AR', 'cs_CZ', 'de_DE', 'en_XX', 'es_XX', 'et_EE', 'fi_FI', 'fr_XX', 'gu_IN', 'hi_IN', 'it_IT', 'ja_XX', 'kk_KZ', 'ko_KR', 'lt_LT', 'lv_LV', 'my_MM', 'ne_NP', 'nl_XX', 'ro_RO', 'ru_RU', 'si_LK', 'tr_TR', 'vi_VN', 'zh_CN', 'af_ZA', 'az_AZ', 'bn_IN', 'fa_IR', 'he_IL', 'hr_HR', 'id_ID', 'ka_GE', 'km_KH', 'mk_MK', 'ml_IN', 'mn_MN', 'mr_IN', 'pl_PL', 'ps_AF', 'pt_XX', 'sv_SE', 'sw_KE', 'ta_IN', 'te_IN', 'th_TH', 'tl_XX', 'uk_UA', 'ur_PK', 'xh_ZA', 'gl_ES', 'sl_SI'] class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" __a =VOCAB_FILES_NAMES __a =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __a =PRETRAINED_VOCAB_FILES_MAP __a =['input_ids', 'attention_mask'] __a =[] __a =[] def __init__( self : Optional[int] , __a : Dict , __a : Optional[Any]=None , __a : Optional[int]=None , __a : Tuple="</s>" , __a : List[Any]="</s>" , __a : Any="<s>" , __a : int="<unk>" , __a : Dict="<pad>" , __a : Tuple="<mask>" , __a : Optional[Dict[str, Any]] = None , **__a : List[Any] , ): # Mask token behave like a normal word, i.e. include the space before it _a = AddedToken(__a , lstrip=__a , rstrip=__a ) if isinstance(__a , __a ) else mask_token _a = {} if sp_model_kwargs is None else sp_model_kwargs _a = kwargs.get("additional_special_tokens" , [] ) kwargs["additional_special_tokens"] += [ code for code in FAIRSEQ_LANGUAGE_CODES if code not in kwargs["additional_special_tokens"] ] super().__init__( src_lang=__a , tgt_lang=__a , eos_token=__a , unk_token=__a , sep_token=__a , cls_token=__a , pad_token=__a , mask_token=__a , sp_model_kwargs=self.sp_model_kwargs , **__a , ) _a = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__a ) ) _a = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # Mimic fairseq token-to-id alignment for the first 4 token _a = {"<s>": 0, "<pad>": 1, "</s>": 2, "<unk>": 3} # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab _a = 1 _a = len(self.sp_model ) _a = { code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(__a ) } _a = {v: k for k, v in self.lang_code_to_id.items()} _a = len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset self.fairseq_tokens_to_ids.update(self.lang_code_to_id ) _a = {v: k for k, v in self.fairseq_tokens_to_ids.items()} _a = src_lang if src_lang is not None else "en_XX" _a = self.lang_code_to_id[self._src_lang] _a = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) @property def UpperCamelCase__ ( self : int ): return len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset + 1 # Plus 1 for the mask token @property def UpperCamelCase__ ( self : Optional[int] ): return self._src_lang @src_lang.setter def UpperCamelCase__ ( self : Optional[Any] , __a : str ): _a = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def __getstate__( self : List[str] ): _a = self.__dict__.copy() _a = None return state def __setstate__( self : Union[str, Any] , __a : Dict ): _a = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): _a = {} _a = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def UpperCamelCase__ ( self : List[str] ): _a = {self.convert_ids_to_tokens(__a ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def UpperCamelCase__ ( self : Tuple , __a : str ): return self.sp_model.encode(__a , out_type=__a ) def UpperCamelCase__ ( self : Dict , __a : str ): if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] _a = self.sp_model.PieceToId(__a ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def UpperCamelCase__ ( self : Tuple , __a : int ): if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def UpperCamelCase__ ( self : Dict , __a : Dict ): _a = [] _a = "" _a = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(__a ) + token _a = True _a = [] else: current_sub_tokens.append(__a ) _a = False out_string += self.sp_model.decode(__a ) return out_string.strip() def UpperCamelCase__ ( self : List[str] , __a : str , __a : Optional[str] = None ): if not os.path.isdir(__a ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return _a = os.path.join( __a , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__a ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __a ) elif not os.path.isfile(self.vocab_file ): with open(__a , "wb" ) as fi: _a = self.sp_model.serialized_model_proto() fi.write(__a ) return (out_vocab_file,) def UpperCamelCase__ ( self : Optional[int] , __a : List[int] , __a : Optional[List[int]] = None , __a : bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__a , token_ids_a=__a , already_has_special_tokens=__a ) _a = [1] * len(self.prefix_tokens ) _a = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(__a )) + suffix_ones return prefix_ones + ([0] * len(__a )) + ([0] * len(__a )) + suffix_ones def UpperCamelCase__ ( self : Dict , __a : List[int] , __a : Optional[List[int]] = None ): if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def UpperCamelCase__ ( self : str , __a : str , __a : str , __a : Optional[str] , __a : Optional[str] , **__a : Tuple ): if src_lang is None or tgt_lang is None: raise ValueError("Translation requires a `src_lang` and a `tgt_lang` for this model" ) _a = src_lang _a = self(__a , add_special_tokens=__a , return_tensors=__a , **__a ) _a = self.convert_tokens_to_ids(__a ) _a = tgt_lang_id return inputs def UpperCamelCase__ ( self : List[str] , __a : List[str] , __a : str = "en_XX" , __a : Optional[List[str]] = None , __a : str = "ro_RO" , **__a : int , ): _a = src_lang _a = tgt_lang return super().prepare_seqaseq_batch(__a , __a , **__a ) def UpperCamelCase__ ( self : str ): return self.set_src_lang_special_tokens(self.src_lang ) def UpperCamelCase__ ( self : int ): return self.set_tgt_lang_special_tokens(self.tgt_lang ) def UpperCamelCase__ ( self : List[Any] , __a : str ): _a = self.lang_code_to_id[src_lang] _a = [self.cur_lang_code_id] _a = [self.eos_token_id] def UpperCamelCase__ ( self : Optional[Any] , __a : str ): _a = self.lang_code_to_id[tgt_lang] _a = [self.cur_lang_code_id] _a = [self.eos_token_id]
63
'''simple docstring''' from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable lowerCAmelCase_ : int = {'configuration_gpt_neox': ['GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP', 'GPTNeoXConfig']} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ : Optional[int] = ['GPTNeoXTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ : List[str] = [ 'GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST', 'GPTNeoXForCausalLM', 'GPTNeoXForQuestionAnswering', 'GPTNeoXForSequenceClassification', 'GPTNeoXForTokenClassification', 'GPTNeoXLayer', 'GPTNeoXModel', 'GPTNeoXPreTrainedModel', ] if TYPE_CHECKING: from .configuration_gpt_neox import GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXConfig try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_neox_fast import GPTNeoXTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox import ( GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, GPTNeoXLayer, GPTNeoXModel, GPTNeoXPreTrainedModel, ) else: import sys lowerCAmelCase_ : List[str] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
63
1
'''simple docstring''' import io import json import fsspec import pytest from datasets import Dataset, DatasetDict, Features, NamedSplit, Value from datasets.io.json import JsonDatasetReader, JsonDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" assert isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('''keep_in_memory''' , [False, True] ) def snake_case_ ( __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : Optional[int] = tmp_path / '''cache''' lowercase_ : int = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): lowercase_ : Tuple = JsonDatasetReader(__SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE , keep_in_memory=__SCREAMING_SNAKE_CASE ).read() _check_json_dataset(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( '''features''' , [ None, {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}, {'''col_1''': '''string''', '''col_2''': '''string''', '''col_3''': '''string'''}, {'''col_1''': '''int32''', '''col_2''': '''int32''', '''col_3''': '''int32'''}, {'''col_1''': '''float32''', '''col_2''': '''float32''', '''col_3''': '''float32'''}, ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : str ): """simple docstring""" lowercase_ : Union[str, Any] = tmp_path / '''cache''' lowercase_ : str = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} lowercase_ : str = features.copy() if features else default_expected_features lowercase_ : Tuple = ( Features({feature: Value(__SCREAMING_SNAKE_CASE ) for feature, dtype in features.items()} ) if features is not None else None ) lowercase_ : Any = JsonDatasetReader(__SCREAMING_SNAKE_CASE , features=__SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE ).read() _check_json_dataset(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( '''features''' , [ None, {'''col_3''': '''float64''', '''col_1''': '''string''', '''col_2''': '''int64'''}, ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Any ): """simple docstring""" lowercase_ : List[Any] = tmp_path / '''cache''' lowercase_ : Union[str, Any] = {'''col_3''': '''float64''', '''col_1''': '''string''', '''col_2''': '''int64'''} lowercase_ : Optional[Any] = features.copy() if features else default_expected_features lowercase_ : Any = ( Features({feature: Value(__SCREAMING_SNAKE_CASE ) for feature, dtype in features.items()} ) if features is not None else None ) lowercase_ : Tuple = JsonDatasetReader(__SCREAMING_SNAKE_CASE , features=__SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE ).read() assert isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_3", "col_1", "col_2"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : Tuple = {'''col_2''': '''int64''', '''col_3''': '''float64''', '''col_1''': '''string'''} lowercase_ : Dict = features.copy() lowercase_ : Tuple = ( Features({feature: Value(__SCREAMING_SNAKE_CASE ) for feature, dtype in features.items()} ) if features is not None else None ) lowercase_ : Dict = tmp_path / '''cache''' lowercase_ : List[str] = JsonDatasetReader(__SCREAMING_SNAKE_CASE , features=__SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE ).read() assert isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_2", "col_3", "col_1"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('''split''' , [None, NamedSplit('''train''' ), '''train''', '''test'''] ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" lowercase_ : Dict = tmp_path / '''cache''' lowercase_ : Any = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} lowercase_ : Tuple = JsonDatasetReader(__SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE , split=__SCREAMING_SNAKE_CASE ).read() _check_json_dataset(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) assert dataset.split == split if split else "train" @pytest.mark.parametrize('''path_type''' , [str, list] ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : List[Any] ): """simple docstring""" if issubclass(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase_ : List[str] = jsonl_path elif issubclass(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase_ : str = [jsonl_path] lowercase_ : Any = tmp_path / '''cache''' lowercase_ : str = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} lowercase_ : Optional[Any] = JsonDatasetReader(__SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE ).read() _check_json_dataset(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Union[str, Any]=("train",) ): """simple docstring""" assert isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) for split in splits: lowercase_ : Dict = dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('''keep_in_memory''' , [False, True] ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" lowercase_ : List[Any] = tmp_path / '''cache''' lowercase_ : Dict = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): lowercase_ : Tuple = JsonDatasetReader({'''train''': jsonl_path} , cache_dir=__SCREAMING_SNAKE_CASE , keep_in_memory=__SCREAMING_SNAKE_CASE ).read() _check_json_datasetdict(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( '''features''' , [ None, {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}, {'''col_1''': '''string''', '''col_2''': '''string''', '''col_3''': '''string'''}, {'''col_1''': '''int32''', '''col_2''': '''int32''', '''col_3''': '''int32'''}, {'''col_1''': '''float32''', '''col_2''': '''float32''', '''col_3''': '''float32'''}, ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : Dict = tmp_path / '''cache''' lowercase_ : Dict = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} lowercase_ : Dict = features.copy() if features else default_expected_features lowercase_ : int = ( Features({feature: Value(__SCREAMING_SNAKE_CASE ) for feature, dtype in features.items()} ) if features is not None else None ) lowercase_ : str = JsonDatasetReader({'''train''': jsonl_path} , features=__SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE ).read() _check_json_datasetdict(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize('''split''' , [None, NamedSplit('''train''' ), '''train''', '''test'''] ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Optional[int] ): """simple docstring""" if split: lowercase_ : Dict = {split: jsonl_path} else: lowercase_ : Optional[Any] = '''train''' lowercase_ : Dict = {'''train''': jsonl_path, '''test''': jsonl_path} lowercase_ : Union[str, Any] = tmp_path / '''cache''' lowercase_ : Optional[Any] = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} lowercase_ : Union[str, Any] = JsonDatasetReader(__SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE ).read() _check_json_datasetdict(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" return json.load(__SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" return [json.loads(__SCREAMING_SNAKE_CASE ) for line in buffer] class lowerCAmelCase__ : @pytest.mark.parametrize('''lines, load_json_function''' , [(True, load_json_lines), (False, load_json)] ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" with io.BytesIO() as buffer: JsonDatasetWriter(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , lines=__SCREAMING_SNAKE_CASE ).write() buffer.seek(0 ) lowercase_ : List[str] = load_json_function(__SCREAMING_SNAKE_CASE ) assert isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) assert isinstance(exported_content[0] , __SCREAMING_SNAKE_CASE ) assert len(__SCREAMING_SNAKE_CASE ) == 10 @pytest.mark.parametrize( '''orient, container, keys, len_at''' , [ ('''records''', list, {'''tokens''', '''labels''', '''answers''', '''id'''}, None), ('''split''', dict, {'''columns''', '''data'''}, '''data'''), ('''index''', dict, set('''0123456789''' ), None), ('''columns''', dict, {'''tokens''', '''labels''', '''answers''', '''id'''}, '''tokens'''), ('''values''', list, None, None), ('''table''', dict, {'''schema''', '''data'''}, '''data'''), ] , ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" with io.BytesIO() as buffer: JsonDatasetWriter(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , lines=__SCREAMING_SNAKE_CASE , orient=__SCREAMING_SNAKE_CASE ).write() buffer.seek(0 ) lowercase_ : Union[str, Any] = load_json(__SCREAMING_SNAKE_CASE ) assert isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(__SCREAMING_SNAKE_CASE , '''keys''' ) and not hasattr(exported_content[0] , '''keys''' ) if len_at: assert len(exported_content[len_at] ) == 10 else: assert len(__SCREAMING_SNAKE_CASE ) == 10 @pytest.mark.parametrize('''lines, load_json_function''' , [(True, load_json_lines), (False, load_json)] ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" with io.BytesIO() as buffer: JsonDatasetWriter(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , lines=__SCREAMING_SNAKE_CASE , num_proc=2 ).write() buffer.seek(0 ) lowercase_ : List[Any] = load_json_function(__SCREAMING_SNAKE_CASE ) assert isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) assert isinstance(exported_content[0] , __SCREAMING_SNAKE_CASE ) assert len(__SCREAMING_SNAKE_CASE ) == 10 @pytest.mark.parametrize( '''orient, container, keys, len_at''' , [ ('''records''', list, {'''tokens''', '''labels''', '''answers''', '''id'''}, None), ('''split''', dict, {'''columns''', '''data'''}, '''data'''), ('''index''', dict, set('''0123456789''' ), None), ('''columns''', dict, {'''tokens''', '''labels''', '''answers''', '''id'''}, '''tokens'''), ('''values''', list, None, None), ('''table''', dict, {'''schema''', '''data'''}, '''data'''), ] , ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" with io.BytesIO() as buffer: JsonDatasetWriter(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , lines=__SCREAMING_SNAKE_CASE , orient=__SCREAMING_SNAKE_CASE , num_proc=2 ).write() buffer.seek(0 ) lowercase_ : Optional[Any] = load_json(__SCREAMING_SNAKE_CASE ) assert isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(__SCREAMING_SNAKE_CASE , '''keys''' ) and not hasattr(exported_content[0] , '''keys''' ) if len_at: assert len(exported_content[len_at] ) == 10 else: assert len(__SCREAMING_SNAKE_CASE ) == 10 def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" with pytest.raises(__SCREAMING_SNAKE_CASE ): with io.BytesIO() as buffer: JsonDatasetWriter(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , num_proc=0 ) @pytest.mark.parametrize('''compression, extension''' , [('''gzip''', '''gz'''), ('''bz2''', '''bz2'''), ('''xz''', '''xz''')] ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Any = tmp_path_factory.mktemp('''data''' ) / F'''test.json.{extension}''' lowercase_ : Any = str(shared_datadir / F'''test_file.json.{extension}''' ) JsonDatasetWriter(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , compression=__SCREAMING_SNAKE_CASE ).write() with fsspec.open(__SCREAMING_SNAKE_CASE , '''rb''' , compression='''infer''' ) as f: lowercase_ : Tuple = f.read() with fsspec.open(__SCREAMING_SNAKE_CASE , '''rb''' , compression='''infer''' ) as f: lowercase_ : Union[str, Any] = f.read() assert exported_content == original_content
353
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging _lowercase : Optional[Any] = logging.get_logger(__name__) _lowercase : str = "▁" _lowercase : Optional[int] = {"vocab_file": "sentencepiece.bpe.model"} _lowercase : Dict = { "vocab_file": { "facebook/xglm-564M": "https://huggingface.co/facebook/xglm-564M/resolve/main/sentencepiece.bpe.model", } } _lowercase : Optional[Any] = { "facebook/xglm-564M": 2_0_4_8, } class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = VOCAB_FILES_NAMES lowerCAmelCase_ = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase_ = ['''input_ids''', '''attention_mask'''] def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE="<s>" , __SCREAMING_SNAKE_CASE="</s>" , __SCREAMING_SNAKE_CASE="</s>" , __SCREAMING_SNAKE_CASE="<s>" , __SCREAMING_SNAKE_CASE="<unk>" , __SCREAMING_SNAKE_CASE="<pad>" , __SCREAMING_SNAKE_CASE = None , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : Any = {} if sp_model_kwargs is None else sp_model_kwargs # Compatibility with the original tokenizer lowercase_ : Optional[Any] = 7 lowercase_ : List[Any] = [F'''<madeupword{i}>''' for i in range(self.num_madeup_words )] lowercase_ : Tuple = kwargs.get('''additional_special_tokens''' , [] ) kwargs["additional_special_tokens"] += [ word for word in madeup_words if word not in kwargs["additional_special_tokens"] ] super().__init__( bos_token=__SCREAMING_SNAKE_CASE , eos_token=__SCREAMING_SNAKE_CASE , unk_token=__SCREAMING_SNAKE_CASE , sep_token=__SCREAMING_SNAKE_CASE , cls_token=__SCREAMING_SNAKE_CASE , pad_token=__SCREAMING_SNAKE_CASE , sp_model_kwargs=self.sp_model_kwargs , **__SCREAMING_SNAKE_CASE , ) lowercase_ : int = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__SCREAMING_SNAKE_CASE ) ) lowercase_ : Dict = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab lowercase_ : List[Any] = 1 # Mimic fairseq token-to-id alignment for the first 4 token lowercase_ : Optional[Any] = {'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3} lowercase_ : Dict = len(self.sp_model ) lowercase_ : int = {F'''<madeupword{i}>''': sp_size + i + self.fairseq_offset for i in range(self.num_madeup_words )} self.fairseq_tokens_to_ids.update(__SCREAMING_SNAKE_CASE ) lowercase_ : List[str] = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self ): """simple docstring""" lowercase_ : List[Any] = self.__dict__.copy() lowercase_ : Optional[Any] = None lowercase_ : List[Any] = self.sp_model.serialized_model_proto() return state def __setstate__( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : List[Any] = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): lowercase_ : Optional[Any] = {} lowercase_ : int = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" if token_ids_a is None: return [self.sep_token_id] + token_ids_a lowercase_ : Optional[Any] = [self.sep_token_id] return sep + token_ids_a + sep + sep + token_ids_a def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = False ): """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__SCREAMING_SNAKE_CASE , token_ids_a=__SCREAMING_SNAKE_CASE , already_has_special_tokens=__SCREAMING_SNAKE_CASE ) if token_ids_a is None: return [1] + ([0] * len(__SCREAMING_SNAKE_CASE )) return [1] + ([0] * len(__SCREAMING_SNAKE_CASE )) + [1, 1] + ([0] * len(__SCREAMING_SNAKE_CASE )) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" lowercase_ : List[Any] = [self.sep_token_id] if token_ids_a is None: return len(sep + token_ids_a ) * [0] return len(sep + token_ids_a + sep + sep + token_ids_a ) * [0] @property def _snake_case ( self ): """simple docstring""" return len(self.sp_model ) + self.fairseq_offset + self.num_madeup_words def _snake_case ( self ): """simple docstring""" lowercase_ : Any = {self.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" return self.sp_model.encode(__SCREAMING_SNAKE_CASE , out_type=__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] lowercase_ : str = self.sp_model.PieceToId(__SCREAMING_SNAKE_CASE ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Dict = ''''''.join(__SCREAMING_SNAKE_CASE ).replace(__SCREAMING_SNAKE_CASE , ''' ''' ).strip() return out_string def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" if not os.path.isdir(__SCREAMING_SNAKE_CASE ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return lowercase_ : str = os.path.join( __SCREAMING_SNAKE_CASE , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__SCREAMING_SNAKE_CASE ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __SCREAMING_SNAKE_CASE ) elif not os.path.isfile(self.vocab_file ): with open(__SCREAMING_SNAKE_CASE , '''wb''' ) as fi: lowercase_ : Optional[int] = self.sp_model.serialized_model_proto() fi.write(__SCREAMING_SNAKE_CASE ) return (out_vocab_file,)
264
0
"""simple docstring""" import numpy as np def a__ ( SCREAMING_SNAKE_CASE : np.array ): '''simple docstring''' return (2 / (1 + np.exp(-2 * vector ))) - 1 if __name__ == "__main__": import doctest doctest.testmod()
108
import gc import unittest import torch from parameterized import parameterized from diffusers import AutoencoderKL from diffusers.utils import floats_tensor, load_hf_numpy, require_torch_gpu, slow, torch_all_close, torch_device from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class __A( a , a , unittest.TestCase ): snake_case_ = AutoencoderKL snake_case_ = '''sample''' snake_case_ = 1E-2 @property def SCREAMING_SNAKE_CASE_ ( self ) -> Optional[Any]: '''simple docstring''' __a = 4 __a = 3 __a = (32, 32) __a = floats_tensor((batch_size, num_channels) + sizes ).to(_snake_case ) return {"sample": image} @property def SCREAMING_SNAKE_CASE_ ( self ) -> Optional[Any]: '''simple docstring''' return (3, 32, 32) @property def SCREAMING_SNAKE_CASE_ ( self ) -> Union[str, Any]: '''simple docstring''' return (3, 32, 32) def SCREAMING_SNAKE_CASE_ ( self ) -> Dict: '''simple docstring''' __a = { '''block_out_channels''': [32, 64], '''in_channels''': 3, '''out_channels''': 3, '''down_block_types''': ['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''], '''up_block_types''': ['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''], '''latent_channels''': 4, } __a = self.dummy_input return init_dict, inputs_dict def SCREAMING_SNAKE_CASE_ ( self ) -> Tuple: '''simple docstring''' pass def SCREAMING_SNAKE_CASE_ ( self ) -> Optional[int]: '''simple docstring''' pass @unittest.skipIf(torch_device == '''mps''' , '''Gradient checkpointing skipped on MPS''' ) def SCREAMING_SNAKE_CASE_ ( self ) -> int: '''simple docstring''' __a , __a = self.prepare_init_args_and_inputs_for_common() __a = self.model_class(**_snake_case ) model.to(_snake_case ) assert not model.is_gradient_checkpointing and model.training __a = model(**_snake_case ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model.zero_grad() __a = torch.randn_like(_snake_case ) __a = (out - labels).mean() loss.backward() # re-instantiate the model now enabling gradient checkpointing __a = self.model_class(**_snake_case ) # clone model model_a.load_state_dict(model.state_dict() ) model_a.to(_snake_case ) model_a.enable_gradient_checkpointing() assert model_a.is_gradient_checkpointing and model_a.training __a = model_a(**_snake_case ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model_a.zero_grad() __a = (out_a - labels).mean() loss_a.backward() # compare the output and parameters gradients self.assertTrue((loss - loss_a).abs() < 1E-5 ) __a = dict(model.named_parameters() ) __a = dict(model_a.named_parameters() ) for name, param in named_params.items(): self.assertTrue(torch_all_close(param.grad.data , named_params_a[name].grad.data , atol=5E-5 ) ) def SCREAMING_SNAKE_CASE_ ( self ) -> Dict: '''simple docstring''' __a , __a = AutoencoderKL.from_pretrained('''fusing/autoencoder-kl-dummy''' , output_loading_info=_snake_case ) self.assertIsNotNone(_snake_case ) self.assertEqual(len(loading_info['''missing_keys'''] ) , 0 ) model.to(_snake_case ) __a = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def SCREAMING_SNAKE_CASE_ ( self ) -> List[str]: '''simple docstring''' __a = AutoencoderKL.from_pretrained('''fusing/autoencoder-kl-dummy''' ) __a = model.to(_snake_case ) model.eval() if torch_device == "mps": __a = torch.manual_seed(0 ) else: __a = torch.Generator(device=_snake_case ).manual_seed(0 ) __a = torch.randn( 1 , model.config.in_channels , model.config.sample_size , model.config.sample_size , generator=torch.manual_seed(0 ) , ) __a = image.to(_snake_case ) with torch.no_grad(): __a = model(_snake_case , sample_posterior=_snake_case , generator=_snake_case ).sample __a = output[0, -1, -3:, -3:].flatten().cpu() # Since the VAE Gaussian prior's generator is seeded on the appropriate device, # the expected output slices are not the same for CPU and GPU. if torch_device == "mps": __a = torch.tensor( [ -4.0_078E-01, -3.8_323E-04, -1.2_681E-01, -1.1_462E-01, 2.0_095E-01, 1.0_893E-01, -8.8_247E-02, -3.0_361E-01, -9.8_644E-03, ] ) elif torch_device == "cpu": __a = torch.tensor( [-0.1352, 0.0878, 0.0419, -0.0818, -0.1069, 0.0688, -0.1458, -0.4446, -0.0026] ) else: __a = torch.tensor( [-0.2421, 0.4642, 0.2507, -0.0438, 0.0682, 0.3160, -0.2018, -0.0727, 0.2485] ) self.assertTrue(torch_all_close(_snake_case , _snake_case , rtol=1E-2 ) ) @slow class __A( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self , _snake_case , _snake_case ) -> Optional[Any]: '''simple docstring''' return F"""gaussian_noise_s={seed}_shape={'_'.join([str(_snake_case ) for s in shape] )}.npy""" def SCREAMING_SNAKE_CASE_ ( self ) -> Dict: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE_ ( self , _snake_case=0 , _snake_case=(4, 3, 512, 512) , _snake_case=False ) -> Any: '''simple docstring''' __a = torch.floataa if fpaa else torch.floataa __a = torch.from_numpy(load_hf_numpy(self.get_file_format(_snake_case , _snake_case ) ) ).to(_snake_case ).to(_snake_case ) return image def SCREAMING_SNAKE_CASE_ ( self , _snake_case="CompVis/stable-diffusion-v1-4" , _snake_case=False ) -> Optional[Any]: '''simple docstring''' __a = '''fp16''' if fpaa else None __a = torch.floataa if fpaa else torch.floataa __a = AutoencoderKL.from_pretrained( _snake_case , subfolder='''vae''' , torch_dtype=_snake_case , revision=_snake_case , ) model.to(_snake_case ).eval() return model def SCREAMING_SNAKE_CASE_ ( self , _snake_case=0 ) -> Tuple: '''simple docstring''' if torch_device == "mps": return torch.manual_seed(_snake_case ) return torch.Generator(device=_snake_case ).manual_seed(_snake_case ) @parameterized.expand( [ # fmt: off [33, [-0.1603, 0.9878, -0.0495, -0.0790, -0.2709, 0.8375, -0.2060, -0.0824], [-0.2395, 0.0098, 0.0102, -0.0709, -0.2840, -0.0274, -0.0718, -0.1824]], [47, [-0.2376, 0.1168, 0.1332, -0.4840, -0.2508, -0.0791, -0.0493, -0.4089], [0.0350, 0.0847, 0.0467, 0.0344, -0.0842, -0.0547, -0.0633, -0.1131]], # fmt: on ] ) def SCREAMING_SNAKE_CASE_ ( self , _snake_case , _snake_case , _snake_case ) -> List[Any]: '''simple docstring''' __a = self.get_sd_vae_model() __a = self.get_sd_image(_snake_case ) __a = self.get_generator(_snake_case ) with torch.no_grad(): __a = model(_snake_case , generator=_snake_case , sample_posterior=_snake_case ).sample assert sample.shape == image.shape __a = sample[-1, -2:, -2:, :2].flatten().float().cpu() __a = torch.tensor(expected_slice_mps if torch_device == '''mps''' else expected_slice ) assert torch_all_close(_snake_case , _snake_case , atol=3E-3 ) @parameterized.expand( [ # fmt: off [33, [-0.0513, 0.0289, 1.3799, 0.2166, -0.2573, -0.0871, 0.5103, -0.0999]], [47, [-0.4128, -0.1320, -0.3704, 0.1965, -0.4116, -0.2332, -0.3340, 0.2247]], # fmt: on ] ) @require_torch_gpu def SCREAMING_SNAKE_CASE_ ( self , _snake_case , _snake_case ) -> Tuple: '''simple docstring''' __a = self.get_sd_vae_model(fpaa=_snake_case ) __a = self.get_sd_image(_snake_case , fpaa=_snake_case ) __a = self.get_generator(_snake_case ) with torch.no_grad(): __a = model(_snake_case , generator=_snake_case , sample_posterior=_snake_case ).sample assert sample.shape == image.shape __a = sample[-1, -2:, :2, -2:].flatten().float().cpu() __a = torch.tensor(_snake_case ) assert torch_all_close(_snake_case , _snake_case , atol=1E-2 ) @parameterized.expand( [ # fmt: off [33, [-0.1609, 0.9866, -0.0487, -0.0777, -0.2716, 0.8368, -0.2055, -0.0814], [-0.2395, 0.0098, 0.0102, -0.0709, -0.2840, -0.0274, -0.0718, -0.1824]], [47, [-0.2377, 0.1147, 0.1333, -0.4841, -0.2506, -0.0805, -0.0491, -0.4085], [0.0350, 0.0847, 0.0467, 0.0344, -0.0842, -0.0547, -0.0633, -0.1131]], # fmt: on ] ) def SCREAMING_SNAKE_CASE_ ( self , _snake_case , _snake_case , _snake_case ) -> Optional[int]: '''simple docstring''' __a = self.get_sd_vae_model() __a = self.get_sd_image(_snake_case ) with torch.no_grad(): __a = model(_snake_case ).sample assert sample.shape == image.shape __a = sample[-1, -2:, -2:, :2].flatten().float().cpu() __a = torch.tensor(expected_slice_mps if torch_device == '''mps''' else expected_slice ) assert torch_all_close(_snake_case , _snake_case , atol=3E-3 ) @parameterized.expand( [ # fmt: off [13, [-0.2051, -0.1803, -0.2311, -0.2114, -0.3292, -0.3574, -0.2953, -0.3323]], [37, [-0.2632, -0.2625, -0.2199, -0.2741, -0.4539, -0.4990, -0.3720, -0.4925]], # fmt: on ] ) @require_torch_gpu def SCREAMING_SNAKE_CASE_ ( self , _snake_case , _snake_case ) -> Optional[int]: '''simple docstring''' __a = self.get_sd_vae_model() __a = self.get_sd_image(_snake_case , shape=(3, 4, 64, 64) ) with torch.no_grad(): __a = model.decode(_snake_case ).sample assert list(sample.shape ) == [3, 3, 512, 512] __a = sample[-1, -2:, :2, -2:].flatten().cpu() __a = torch.tensor(_snake_case ) assert torch_all_close(_snake_case , _snake_case , atol=1E-3 ) @parameterized.expand( [ # fmt: off [27, [-0.0369, 0.0207, -0.0776, -0.0682, -0.1747, -0.1930, -0.1465, -0.2039]], [16, [-0.1628, -0.2134, -0.2747, -0.2642, -0.3774, -0.4404, -0.3687, -0.4277]], # fmt: on ] ) @require_torch_gpu def SCREAMING_SNAKE_CASE_ ( self , _snake_case , _snake_case ) -> Optional[Any]: '''simple docstring''' __a = self.get_sd_vae_model(fpaa=_snake_case ) __a = self.get_sd_image(_snake_case , shape=(3, 4, 64, 64) , fpaa=_snake_case ) with torch.no_grad(): __a = model.decode(_snake_case ).sample assert list(sample.shape ) == [3, 3, 512, 512] __a = sample[-1, -2:, :2, -2:].flatten().float().cpu() __a = torch.tensor(_snake_case ) assert torch_all_close(_snake_case , _snake_case , atol=5E-3 ) @parameterized.expand([(13,), (16,), (27,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason='''xformers is not required when using PyTorch 2.0.''' ) def SCREAMING_SNAKE_CASE_ ( self , _snake_case ) -> Union[str, Any]: '''simple docstring''' __a = self.get_sd_vae_model(fpaa=_snake_case ) __a = self.get_sd_image(_snake_case , shape=(3, 4, 64, 64) , fpaa=_snake_case ) with torch.no_grad(): __a = model.decode(_snake_case ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): __a = model.decode(_snake_case ).sample assert list(sample.shape ) == [3, 3, 512, 512] assert torch_all_close(_snake_case , _snake_case , atol=1E-1 ) @parameterized.expand([(13,), (16,), (37,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason='''xformers is not required when using PyTorch 2.0.''' ) def SCREAMING_SNAKE_CASE_ ( self , _snake_case ) -> List[str]: '''simple docstring''' __a = self.get_sd_vae_model() __a = self.get_sd_image(_snake_case , shape=(3, 4, 64, 64) ) with torch.no_grad(): __a = model.decode(_snake_case ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): __a = model.decode(_snake_case ).sample assert list(sample.shape ) == [3, 3, 512, 512] assert torch_all_close(_snake_case , _snake_case , atol=1E-2 ) @parameterized.expand( [ # fmt: off [33, [-0.3001, 0.0918, -2.6984, -3.9720, -3.2099, -5.0353, 1.7338, -0.2065, 3.4267]], [47, [-1.5030, -4.3871, -6.0355, -9.1157, -1.6661, -2.7853, 2.1607, -5.0823, 2.5633]], # fmt: on ] ) def SCREAMING_SNAKE_CASE_ ( self , _snake_case , _snake_case ) -> Optional[int]: '''simple docstring''' __a = self.get_sd_vae_model() __a = self.get_sd_image(_snake_case ) __a = self.get_generator(_snake_case ) with torch.no_grad(): __a = model.encode(_snake_case ).latent_dist __a = dist.sample(generator=_snake_case ) assert list(sample.shape ) == [image.shape[0], 4] + [i // 8 for i in image.shape[2:]] __a = sample[0, -1, -3:, -3:].flatten().cpu() __a = torch.tensor(_snake_case ) __a = 3E-3 if torch_device != '''mps''' else 1E-2 assert torch_all_close(_snake_case , _snake_case , atol=_snake_case )
6
0
import numpy as np from cva import COLOR_BGR2GRAY, cvtColor, imread from numpy import array, uinta from PIL import Image from digital_image_processing import change_contrast as cc from digital_image_processing import convert_to_negative as cn from digital_image_processing import sepia as sp from digital_image_processing.dithering import burkes as bs from digital_image_processing.edge_detection import canny from digital_image_processing.filters import convolve as conv from digital_image_processing.filters import gaussian_filter as gg from digital_image_processing.filters import local_binary_pattern as lbp from digital_image_processing.filters import median_filter as med from digital_image_processing.filters import sobel_filter as sob from digital_image_processing.resize import resize as rs __SCREAMING_SNAKE_CASE = imread(r"""digital_image_processing/image_data/lena_small.jpg""") __SCREAMING_SNAKE_CASE = cvtColor(img, COLOR_BGR2GRAY) def UpperCAmelCase ( ): A : List[str] = cn.convert_to_negative(_lowerCamelCase ) # assert negative_img array for at least one True assert negative_img.any() def UpperCAmelCase ( ): with Image.open("digital_image_processing/image_data/lena_small.jpg" ) as img: # Work around assertion for response assert str(cc.change_contrast(_lowerCamelCase , 110 ) ).startswith( "<PIL.Image.Image image mode=RGB size=100x100 at" ) def UpperCAmelCase ( ): A : Union[str, Any] = canny.gen_gaussian_kernel(9 , sigma=1.4 ) # Assert ambiguous array assert resp.all() def UpperCAmelCase ( ): A : Tuple = imread("digital_image_processing/image_data/lena_small.jpg" , 0 ) # assert ambiguous array for all == True assert canny_img.all() A : Tuple = canny.canny(_lowerCamelCase ) # assert canny array for at least one True assert canny_array.any() def UpperCAmelCase ( ): assert gg.gaussian_filter(_lowerCamelCase , 5 , sigma=0.9 ).all() def UpperCAmelCase ( ): # laplace diagonals A : Dict = array([[0.25, 0.5, 0.25], [0.5, -3, 0.5], [0.25, 0.5, 0.25]] ) A : int = conv.img_convolve(_lowerCamelCase , _lowerCamelCase ).astype(_lowerCamelCase ) assert res.any() def UpperCAmelCase ( ): assert med.median_filter(_lowerCamelCase , 3 ).any() def UpperCAmelCase ( ): A , A : Optional[int] = sob.sobel_filter(_lowerCamelCase ) assert grad.any() and theta.any() def UpperCAmelCase ( ): A : str = sp.make_sepia(_lowerCamelCase , 20 ) assert sepia.all() def UpperCAmelCase ( _lowerCamelCase = "digital_image_processing/image_data/lena_small.jpg" ): A : Any = bs.Burkes(imread(_lowerCamelCase , 1 ) , 120 ) burkes.process() assert burkes.output_img.any() def UpperCAmelCase ( _lowerCamelCase = "digital_image_processing/image_data/lena_small.jpg" , ): A : Tuple = rs.NearestNeighbour(imread(_lowerCamelCase , 1 ) , 400 , 200 ) nn.process() assert nn.output.any() def UpperCAmelCase ( ): A : List[Any] = "digital_image_processing/image_data/lena.jpg" # Reading the image and converting it to grayscale. A : Tuple = imread(_lowerCamelCase , 0 ) # Test for get_neighbors_pixel function() return not None A : Optional[int] = 0 A : Tuple = 0 A : str = image[x_coordinate][y_coordinate] A : List[Any] = lbp.get_neighbors_pixel( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) assert neighbors_pixels is not None # Test for local_binary_pattern function() # Create a numpy array as the same height and width of read image A : int = np.zeros((image.shape[0], image.shape[1]) ) # Iterating through the image and calculating the local binary pattern value # for each pixel. for i in range(0 , image.shape[0] ): for j in range(0 , image.shape[1] ): A : str = lbp.local_binary_value(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) assert lbp_image.any()
256
from math import atan, cos, radians, sin, tan from .haversine_distance import haversine_distance __SCREAMING_SNAKE_CASE = 637_8137.0 __SCREAMING_SNAKE_CASE = 635_6752.31_4245 __SCREAMING_SNAKE_CASE = 6378137 def UpperCAmelCase ( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): A : List[Any] = (AXIS_A - AXIS_B) / AXIS_A # Parametric latitudes # https://en.wikipedia.org/wiki/Latitude#Parametric_(or_reduced)_latitude A : Tuple = atan((1 - flattening) * tan(radians(_lowerCamelCase ) ) ) A : Tuple = atan((1 - flattening) * tan(radians(_lowerCamelCase ) ) ) # Compute central angle between two points # using haversine theta. sigma = haversine_distance / equatorial radius A : List[str] = haversine_distance(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) / EQUATORIAL_RADIUS # Intermediate P and Q values A : List[Any] = (b_lata + b_lata) / 2 A : Optional[Any] = (b_lata - b_lata) / 2 # Intermediate X value # X = (sigma - sin(sigma)) * sin^2Pcos^2Q / cos^2(sigma/2) A : List[str] = (sin(_lowerCamelCase ) ** 2) * (cos(_lowerCamelCase ) ** 2) A : Optional[int] = cos(sigma / 2 ) ** 2 A : int = (sigma - sin(_lowerCamelCase )) * (x_numerator / x_demonimator) # Intermediate Y value # Y = (sigma + sin(sigma)) * cos^2Psin^2Q / sin^2(sigma/2) A : List[str] = (cos(_lowerCamelCase ) ** 2) * (sin(_lowerCamelCase ) ** 2) A : Union[str, Any] = sin(sigma / 2 ) ** 2 A : int = (sigma + sin(_lowerCamelCase )) * (y_numerator / y_denominator) return EQUATORIAL_RADIUS * (sigma - ((flattening / 2) * (x_value + y_value))) if __name__ == "__main__": import doctest doctest.testmod()
256
1
"""simple docstring""" from math import sqrt def lowercase_ ( __UpperCAmelCase ) -> str: lowerCAmelCase__ : List[str] = 0 for i in range(1 , int(sqrt(a_ ) + 1 ) ): if n % i == 0 and i != sqrt(a_ ): total += i + n // i elif i == sqrt(a_ ): total += i return total - n def lowercase_ ( __UpperCAmelCase = 1_0000 ) -> List[str]: lowerCAmelCase__ : Dict = sum( i for i in range(1 , a_ ) if sum_of_divisors(sum_of_divisors(a_ ) ) == i and sum_of_divisors(a_ ) != i ) return total if __name__ == "__main__": print(solution(int(str(input()).strip())))
242
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __a = logging.get_logger(__name__) __a = { 'sayakpaul/vit-msn-base': 'https://huggingface.co/sayakpaul/vit-msn-base/resolve/main/config.json', # See all ViT MSN models at https://huggingface.co/models?filter=vit_msn } class A__ ( UpperCamelCase ): """simple docstring""" UpperCamelCase_ : Dict = '''vit_msn''' def __init__( self : Optional[int] , lowerCAmelCase__ : str=7_6_8 , lowerCAmelCase__ : List[str]=1_2 , lowerCAmelCase__ : int=1_2 , lowerCAmelCase__ : Optional[Any]=3_0_7_2 , lowerCAmelCase__ : Tuple="gelu" , lowerCAmelCase__ : Tuple=0.0 , lowerCAmelCase__ : str=0.0 , lowerCAmelCase__ : Dict=0.02 , lowerCAmelCase__ : int=1e-06 , lowerCAmelCase__ : Union[str, Any]=2_2_4 , lowerCAmelCase__ : Optional[int]=1_6 , lowerCAmelCase__ : List[str]=3 , lowerCAmelCase__ : str=True , **lowerCAmelCase__ : Optional[Any] , ) -> int: """simple docstring""" super().__init__(**lowerCAmelCase__ ) _UpperCAmelCase : Any = hidden_size _UpperCAmelCase : str = num_hidden_layers _UpperCAmelCase : int = num_attention_heads _UpperCAmelCase : Any = intermediate_size _UpperCAmelCase : Any = hidden_act _UpperCAmelCase : str = hidden_dropout_prob _UpperCAmelCase : Tuple = attention_probs_dropout_prob _UpperCAmelCase : Optional[Any] = initializer_range _UpperCAmelCase : Tuple = layer_norm_eps _UpperCAmelCase : int = image_size _UpperCAmelCase : Tuple = patch_size _UpperCAmelCase : Dict = num_channels _UpperCAmelCase : Optional[int] = qkv_bias
145
0
def __lowercase ( a__ , a__ ) -> bool: __SCREAMING_SNAKE_CASE = len(__lowerCAmelCase ) __SCREAMING_SNAKE_CASE = len(__lowerCAmelCase ) __SCREAMING_SNAKE_CASE = [[False for _ in range(m + 1 )] for _ in range(n + 1 )] __SCREAMING_SNAKE_CASE = True for i in range(__lowerCAmelCase ): for j in range(m + 1 ): if dp[i][j]: if j < m and a[i].upper() == b[j]: __SCREAMING_SNAKE_CASE = True if a[i].islower(): __SCREAMING_SNAKE_CASE = True return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
362
import logging import sys from dataclasses import dataclass, field from typing import Any, Dict, List, Optional, Union import librosa import torch from datasets import DatasetDict, load_dataset from packaging import version from torch import nn from transformers import ( HfArgumentParser, Trainer, TrainingArguments, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaForPreTraining, is_apex_available, trainer_utils, ) from transformers.models.wavaveca.modeling_wavaveca import _compute_mask_indices if is_apex_available(): from apex import amp if version.parse(version.parse(torch.__version__).base_version) >= version.parse('''1.6'''): lowerCAmelCase__ : Optional[int] =True from torch.cuda.amp import autocast lowerCAmelCase__ : List[Any] =logging.getLogger(__name__) @dataclass class UpperCAmelCase_ : '''simple docstring''' UpperCamelCase__ : str = field( metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''} ) UpperCamelCase__ : Optional[str] = field( default=UpperCamelCase_ , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''} , ) UpperCamelCase__ : Optional[bool] = field( default=UpperCamelCase_ , metadata={'''help''': '''Whether to freeze the feature extractor layers of the model.'''} ) UpperCamelCase__ : Optional[bool] = field( default=UpperCamelCase_ , metadata={'''help''': '''Whether to log verbose messages or not.'''} , ) UpperCamelCase__ : Optional[float] = field( default=2.0 , metadata={'''help''': '''Maximum temperature for gumbel softmax.'''} ) UpperCamelCase__ : Optional[float] = field( default=0.5 , metadata={'''help''': '''Minimum temperature for gumbel softmax.'''} ) UpperCamelCase__ : Optional[float] = field( default=0.9_9_9_9_9_5 , metadata={'''help''': '''Decay of gumbel temperature during training.'''} ) def __lowercase ( a__ , a__ ) -> Dict: logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' , datefmt='%m/%d/%Y %H:%M:%S' , handlers=[logging.StreamHandler(sys.stdout )] , ) __SCREAMING_SNAKE_CASE = logging.WARNING if model_args.verbose_logging: __SCREAMING_SNAKE_CASE = logging.DEBUG elif trainer_utils.is_main_process(training_args.local_rank ): __SCREAMING_SNAKE_CASE = logging.INFO logger.setLevel(a__ ) @dataclass class UpperCAmelCase_ : '''simple docstring''' UpperCamelCase__ : str = field( default=UpperCamelCase_ , metadata={'''help''': '''The name of the dataset to use (via the datasets library).'''} ) UpperCamelCase__ : Optional[str] = field( default=UpperCamelCase_ , metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''} ) UpperCamelCase__ : Optional[str] = field( default='''train''' , metadata={ '''help''': '''The name of the training data set split to use (via the datasets library). Defaults to \'train\'''' } , ) UpperCamelCase__ : Optional[str] = field( default='''validation''' , metadata={ '''help''': ( '''The name of the validation data set split to use (via the datasets library). Defaults to \'validation\'''' ) } , ) UpperCamelCase__ : Optional[str] = field( default='''file''' , metadata={'''help''': '''Column in the dataset that contains speech file path. Defaults to \'file\''''} , ) UpperCamelCase__ : bool = field( default=UpperCamelCase_ , metadata={'''help''': '''Overwrite the cached preprocessed datasets or not.'''} ) UpperCamelCase__ : Optional[int] = field( default=1 , metadata={ '''help''': '''The percentage of the train set used as validation set in case there\'s no validation split''' } , ) UpperCamelCase__ : Optional[int] = field( default=UpperCamelCase_ , metadata={'''help''': '''The number of processes to use for the preprocessing.'''} , ) UpperCamelCase__ : Optional[float] = field( default=2_0.0 , metadata={'''help''': '''Filter audio files that are longer than `max_duration_in_seconds` seconds'''} ) @dataclass class UpperCAmelCase_ : '''simple docstring''' UpperCamelCase__ : WavaVecaForPreTraining UpperCamelCase__ : WavaVecaFeatureExtractor UpperCamelCase__ : Union[bool, str] = "longest" UpperCamelCase__ : Optional[int] = None UpperCamelCase__ : Optional[int] = None def __call__( self , _A ): '''simple docstring''' __SCREAMING_SNAKE_CASE = self.feature_extractor.pad( _A , max_length=self.max_length , padding=self.padding , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors='pt' , ) __SCREAMING_SNAKE_CASE = self.model._get_feat_extract_output_lengths(batch['input_values'].shape[-1] ) __SCREAMING_SNAKE_CASE = batch['input_values'].shape[0] # make sure that no loss is computed on padded inputs if batch["attention_mask"] is not None: # compute real output lengths according to convolution formula __SCREAMING_SNAKE_CASE = self.model._get_feat_extract_output_lengths(batch['attention_mask'].sum(-1 ) ).to( torch.long ) __SCREAMING_SNAKE_CASE = torch.zeros( (batch_size, mask_indices_seq_length) , dtype=torch.long , device=batch['input_values'].device ) # these two operations makes sure that all values # before the output lengths indices are attended to __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = attention_mask.flip([-1] ).cumsum(-1 ).flip([-1] ).bool() # sample randomly masked indices __SCREAMING_SNAKE_CASE = _compute_mask_indices( (batch_size, mask_indices_seq_length) , self.model.config.mask_time_prob , self.model.config.mask_time_length , attention_mask=_A , min_masks=2 , ) return batch class UpperCAmelCase_ ( UpperCamelCase_ ): '''simple docstring''' def __init__( self , *_A , _A=1 , _A=0 , _A=1.0 , **_A ): '''simple docstring''' super().__init__(*_A , **_A ) __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = max_gumbel_temp __SCREAMING_SNAKE_CASE = min_gumbel_temp __SCREAMING_SNAKE_CASE = gumbel_temp_decay def _A ( self , _A , _A ): '''simple docstring''' model.train() __SCREAMING_SNAKE_CASE = self._prepare_inputs(_A ) if self.use_amp: with autocast(): __SCREAMING_SNAKE_CASE = self.compute_loss(_A , _A ) else: __SCREAMING_SNAKE_CASE = self.compute_loss(_A , _A ) if self.args.n_gpu > 1 or self.deepspeed: if model.module.config.ctc_loss_reduction == "mean": __SCREAMING_SNAKE_CASE = loss.mean() elif model.module.config.ctc_loss_reduction == "sum": __SCREAMING_SNAKE_CASE = loss.sum() / (inputs['mask_time_indices']).sum() else: raise ValueError(f"""{model.config.ctc_loss_reduction} is not valid. Choose one of ['mean', 'sum']""" ) if self.args.gradient_accumulation_steps > 1: __SCREAMING_SNAKE_CASE = loss / self.args.gradient_accumulation_steps if self.use_amp: self.scaler.scale(_A ).backward() elif self.use_apex: with amp.scale_loss(_A , self.optimizer ) as scaled_loss: scaled_loss.backward() elif self.deepspeed: self.deepspeed.backward(_A ) else: loss.backward() self.num_update_step += 1 # make sure gumbel softmax temperature is decayed if self.args.n_gpu > 1 or self.deepspeed: model.module.set_gumbel_temperature( max(self.max_gumbel_temp * self.gumbel_temp_decay**self.num_update_step , self.min_gumbel_temp ) ) else: model.set_gumbel_temperature( max(self.max_gumbel_temp * self.gumbel_temp_decay**self.num_update_step , self.min_gumbel_temp ) ) return loss.detach() def __lowercase ( ) -> Tuple: # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. __SCREAMING_SNAKE_CASE = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = parser.parse_args_into_dataclasses() configure_logger(a__ , a__ ) # Downloading and loading a dataset from the hub. __SCREAMING_SNAKE_CASE = load_dataset(data_args.dataset_name , data_args.dataset_config_name , cache_dir=model_args.cache_dir ) if "validation" not in datasets.keys(): # make sure only "validation" and "train" keys remain" __SCREAMING_SNAKE_CASE = DatasetDict() __SCREAMING_SNAKE_CASE = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=f"""{data_args.train_split_name}[:{data_args.validation_split_percentage}%]""" , cache_dir=model_args.cache_dir , ) __SCREAMING_SNAKE_CASE = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=f"""{data_args.train_split_name}[{data_args.validation_split_percentage}%:]""" , cache_dir=model_args.cache_dir , ) else: # make sure only "validation" and "train" keys remain" __SCREAMING_SNAKE_CASE = DatasetDict() __SCREAMING_SNAKE_CASE = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split='validation' , cache_dir=model_args.cache_dir , ) __SCREAMING_SNAKE_CASE = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=f"""{data_args.train_split_name}""" , cache_dir=model_args.cache_dir , ) # only normalized-inputs-training is supported __SCREAMING_SNAKE_CASE = WavaVecaFeatureExtractor.from_pretrained( model_args.model_name_or_path , cache_dir=model_args.cache_dir , do_normalize=a__ ) def prepare_dataset(a__ ): # check that all files have the correct sampling rate __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = librosa.load(batch[data_args.speech_file_column] , sr=feature_extractor.sampling_rate ) return batch # load audio files into numpy arrays __SCREAMING_SNAKE_CASE = datasets.map( a__ , num_proc=data_args.preprocessing_num_workers , remove_columns=datasets['train'].column_names ) # filter audio files that are too long __SCREAMING_SNAKE_CASE = vectorized_datasets.filter( lambda a__ : len(data['speech'] ) < int(data_args.max_duration_in_seconds * feature_extractor.sampling_rate ) ) def normalize(a__ ): return feature_extractor(batch['speech'] , sampling_rate=feature_extractor.sampling_rate ) # normalize and transform to `BatchFeatures` __SCREAMING_SNAKE_CASE = vectorized_datasets.map( a__ , batched=a__ , num_proc=data_args.preprocessing_num_workers , load_from_cache_file=not data_args.overwrite_cache , remove_columns=vectorized_datasets['train'].column_names , ) # pretraining is only supported for "newer" stable layer norm architecture # apply_spec_augment has to be True, mask_feature_prob has to be 0.0 __SCREAMING_SNAKE_CASE = WavaVecaConfig.from_pretrained( model_args.model_name_or_path , cache_dir=model_args.cache_dir , gradient_checkpointing=training_args.gradient_checkpointing , ) if not config.do_stable_layer_norm or config.feat_extract_norm != "layer": raise ValueError( 'PreTraining is only supported for ``config.do_stable_layer_norm=True`` and' ' ``config.feat_extract_norm=\'layer\'' ) __SCREAMING_SNAKE_CASE = WavaVecaForPreTraining(a__ ) __SCREAMING_SNAKE_CASE = DataCollatorForWavaVecaPretraining(model=a__ , feature_extractor=a__ ) __SCREAMING_SNAKE_CASE = WavaVecaPreTrainer( model=a__ , data_collator=a__ , args=a__ , train_dataset=vectorized_datasets['train'] , eval_dataset=vectorized_datasets['validation'] , tokenizer=a__ , max_gumbel_temp=model_args.max_gumbel_temperature , min_gumbel_temp=model_args.min_gumbel_temperature , gumbel_temp_decay=model_args.gumbel_temperature_decay , ) trainer.train() if __name__ == "__main__": main()
118
0
'''simple docstring''' def __lowerCAmelCase ( UpperCamelCase__ ) -> int: if not isinstance(UpperCamelCase__ , UpperCamelCase__ ): raise ValueError('''Input must be an integer''' ) if input_num <= 0: raise ValueError('''Input must be positive''' ) return sum( divisor for divisor in range(1 , input_num // 2 + 1 ) if input_num % divisor == 0 ) if __name__ == "__main__": import doctest doctest.testmod()
67
"""simple docstring""" 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 _lowercase ( __snake_case ) -> List[str]: if isinstance(__snake_case ,collections.abc.Iterable ): return x return (x, x) @require_flax class A__ : '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self: Optional[Any] , _SCREAMING_SNAKE_CASE: Dict , _SCREAMING_SNAKE_CASE: Optional[Any]) -> str: """simple docstring""" pass def _SCREAMING_SNAKE_CASE ( self: str) -> int: """simple docstring""" pass def _SCREAMING_SNAKE_CASE ( self: List[str]) -> Tuple: """simple docstring""" pass def _SCREAMING_SNAKE_CASE ( self: Any , _SCREAMING_SNAKE_CASE: np.ndarray , _SCREAMING_SNAKE_CASE: np.ndarray , _SCREAMING_SNAKE_CASE: float) -> List[Any]: """simple docstring""" __lowerCAmelCase : str = np.abs((a - b)).max() self.assertLessEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , F"""Difference between torch and flax is {diff} (>= {tol}).""") def _SCREAMING_SNAKE_CASE ( self: str , _SCREAMING_SNAKE_CASE: List[str] , _SCREAMING_SNAKE_CASE: Dict , _SCREAMING_SNAKE_CASE: Any , _SCREAMING_SNAKE_CASE: List[Any] , _SCREAMING_SNAKE_CASE: Any=None , **_SCREAMING_SNAKE_CASE: Tuple) -> List[str]: """simple docstring""" __lowerCAmelCase : Tuple = VisionTextDualEncoderConfig.from_vision_text_configs(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE) __lowerCAmelCase : List[str] = FlaxVisionTextDualEncoderModel(_SCREAMING_SNAKE_CASE) __lowerCAmelCase : Optional[int] = model(input_ids=_SCREAMING_SNAKE_CASE , pixel_values=_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE) 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] , _SCREAMING_SNAKE_CASE: str , _SCREAMING_SNAKE_CASE: Dict , _SCREAMING_SNAKE_CASE: Dict , _SCREAMING_SNAKE_CASE: List[Any] , _SCREAMING_SNAKE_CASE: Optional[Any]=None , **_SCREAMING_SNAKE_CASE: List[str]) -> Dict: """simple docstring""" __lowerCAmelCase , __lowerCAmelCase : List[Any] = self.get_vision_text_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE) __lowerCAmelCase : Union[str, Any] = {"vision_model": vision_model, "text_model": text_model} __lowerCAmelCase : Optional[Any] = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**_SCREAMING_SNAKE_CASE) __lowerCAmelCase : Union[str, Any] = model(input_ids=_SCREAMING_SNAKE_CASE , pixel_values=_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE) 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: Dict , _SCREAMING_SNAKE_CASE: List[Any] , _SCREAMING_SNAKE_CASE: List[str] , _SCREAMING_SNAKE_CASE: List[Any] , _SCREAMING_SNAKE_CASE: Optional[int] , _SCREAMING_SNAKE_CASE: List[Any]=None , **_SCREAMING_SNAKE_CASE: Tuple) -> str: """simple docstring""" __lowerCAmelCase , __lowerCAmelCase : Optional[Any] = self.get_vision_text_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE) __lowerCAmelCase : Optional[Any] = {"vision_model": vision_model, "text_model": text_model} __lowerCAmelCase : Any = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**_SCREAMING_SNAKE_CASE) __lowerCAmelCase : Optional[Any] = model(input_ids=_SCREAMING_SNAKE_CASE , pixel_values=_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE) __lowerCAmelCase : Any = output[0] with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(_SCREAMING_SNAKE_CASE) __lowerCAmelCase : Union[str, Any] = FlaxVisionTextDualEncoderModel.from_pretrained(_SCREAMING_SNAKE_CASE) __lowerCAmelCase : int = model(input_ids=_SCREAMING_SNAKE_CASE , pixel_values=_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE) __lowerCAmelCase : Union[str, Any] = after_output[0] __lowerCAmelCase : Any = np.amax(np.abs(out_a - out_a)) self.assertLessEqual(_SCREAMING_SNAKE_CASE , 1e-3) def _SCREAMING_SNAKE_CASE ( self: Tuple , _SCREAMING_SNAKE_CASE: Optional[int] , _SCREAMING_SNAKE_CASE: Optional[Any] , _SCREAMING_SNAKE_CASE: int , _SCREAMING_SNAKE_CASE: Optional[int] , _SCREAMING_SNAKE_CASE: Any=None , **_SCREAMING_SNAKE_CASE: List[str]) -> Optional[int]: """simple docstring""" __lowerCAmelCase , __lowerCAmelCase : Any = self.get_vision_text_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE) __lowerCAmelCase : Union[str, Any] = {"vision_model": vision_model, "text_model": text_model} __lowerCAmelCase : Optional[Any] = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**_SCREAMING_SNAKE_CASE) __lowerCAmelCase : Optional[Any] = model( input_ids=_SCREAMING_SNAKE_CASE , pixel_values=_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , output_attentions=_SCREAMING_SNAKE_CASE) __lowerCAmelCase : Optional[Any] = output.vision_model_output.attentions self.assertEqual(len(_SCREAMING_SNAKE_CASE) , vision_config.num_hidden_layers) # in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token) __lowerCAmelCase : List[str] = to_atuple(vision_model.config.image_size) __lowerCAmelCase : Any = to_atuple(vision_model.config.patch_size) __lowerCAmelCase : Union[str, Any] = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) __lowerCAmelCase : Tuple = num_patches + 1 self.assertEqual(vision_attentions[0].shape[-3:] , (vision_config.num_attention_heads, seq_len, seq_len)) __lowerCAmelCase : Union[str, Any] = output.text_model_output.attentions self.assertEqual(len(_SCREAMING_SNAKE_CASE) , 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: List[str] , _SCREAMING_SNAKE_CASE: Union[str, Any] , _SCREAMING_SNAKE_CASE: Optional[int] , _SCREAMING_SNAKE_CASE: int) -> str: """simple docstring""" pt_model.to(_SCREAMING_SNAKE_CASE) pt_model.eval() # prepare inputs __lowerCAmelCase : Union[str, Any] = inputs_dict __lowerCAmelCase : Union[str, Any] = {k: torch.tensor(v.tolist()) for k, v in flax_inputs.items()} with torch.no_grad(): __lowerCAmelCase : Any = pt_model(**_SCREAMING_SNAKE_CASE).to_tuple() __lowerCAmelCase : List[Any] = fx_model(**_SCREAMING_SNAKE_CASE).to_tuple() self.assertEqual(len(_SCREAMING_SNAKE_CASE) , len(_SCREAMING_SNAKE_CASE) , "Output lengths differ between Flax and PyTorch") for fx_output, pt_output in zip(fx_outputs[:4] , pt_outputs[:4]): self.assert_almost_equals(_SCREAMING_SNAKE_CASE , pt_output.numpy() , 4e-2) # PT -> Flax with tempfile.TemporaryDirectory() as tmpdirname: pt_model.save_pretrained(_SCREAMING_SNAKE_CASE) __lowerCAmelCase : str = FlaxVisionTextDualEncoderModel.from_pretrained(_SCREAMING_SNAKE_CASE , from_pt=_SCREAMING_SNAKE_CASE) __lowerCAmelCase : int = fx_model_loaded(**_SCREAMING_SNAKE_CASE).to_tuple() self.assertEqual(len(_SCREAMING_SNAKE_CASE) , len(_SCREAMING_SNAKE_CASE) , "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(_SCREAMING_SNAKE_CASE , pt_output.numpy() , 4e-2) # Flax -> PT with tempfile.TemporaryDirectory() as tmpdirname: fx_model.save_pretrained(_SCREAMING_SNAKE_CASE) __lowerCAmelCase : Union[str, Any] = VisionTextDualEncoderModel.from_pretrained(_SCREAMING_SNAKE_CASE , from_flax=_SCREAMING_SNAKE_CASE) pt_model_loaded.to(_SCREAMING_SNAKE_CASE) pt_model_loaded.eval() with torch.no_grad(): __lowerCAmelCase : Optional[Any] = pt_model_loaded(**_SCREAMING_SNAKE_CASE).to_tuple() self.assertEqual(len(_SCREAMING_SNAKE_CASE) , len(_SCREAMING_SNAKE_CASE) , "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(_SCREAMING_SNAKE_CASE , pt_output_loaded.numpy() , 4e-2) def _SCREAMING_SNAKE_CASE ( self: Union[str, Any] , _SCREAMING_SNAKE_CASE: Optional[Any] , _SCREAMING_SNAKE_CASE: Optional[int] , _SCREAMING_SNAKE_CASE: Dict) -> Optional[Any]: """simple docstring""" __lowerCAmelCase : Union[str, Any] = VisionTextDualEncoderConfig.from_vision_text_configs(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE) __lowerCAmelCase : Dict = VisionTextDualEncoderModel(_SCREAMING_SNAKE_CASE) __lowerCAmelCase : str = FlaxVisionTextDualEncoderModel(_SCREAMING_SNAKE_CASE) __lowerCAmelCase : str = convert_pytorch_state_dict_to_flax(pt_model.state_dict() , _SCREAMING_SNAKE_CASE) __lowerCAmelCase : Optional[Any] = fx_state self.check_pt_flax_equivalence(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE) def _SCREAMING_SNAKE_CASE ( self: List[Any] , _SCREAMING_SNAKE_CASE: Optional[int] , _SCREAMING_SNAKE_CASE: Tuple , _SCREAMING_SNAKE_CASE: Dict) -> str: """simple docstring""" __lowerCAmelCase : Optional[int] = VisionTextDualEncoderConfig.from_vision_text_configs(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE) __lowerCAmelCase : Dict = VisionTextDualEncoderModel(_SCREAMING_SNAKE_CASE) __lowerCAmelCase : Tuple = FlaxVisionTextDualEncoderModel(_SCREAMING_SNAKE_CASE) __lowerCAmelCase : int = load_flax_weights_in_pytorch_model(_SCREAMING_SNAKE_CASE , fx_model.params) self.check_pt_flax_equivalence(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE) def _SCREAMING_SNAKE_CASE ( self: List[Any]) -> str: """simple docstring""" __lowerCAmelCase : List[str] = self.prepare_config_and_inputs() self.check_model_from_pretrained_configs(**_SCREAMING_SNAKE_CASE) def _SCREAMING_SNAKE_CASE ( self: Dict) -> int: """simple docstring""" __lowerCAmelCase : List[Any] = self.prepare_config_and_inputs() self.check_vision_text_dual_encoder_from_pretrained(**_SCREAMING_SNAKE_CASE) def _SCREAMING_SNAKE_CASE ( self: List[Any]) -> List[Any]: """simple docstring""" __lowerCAmelCase : Dict = self.prepare_config_and_inputs() self.check_save_load(**_SCREAMING_SNAKE_CASE) def _SCREAMING_SNAKE_CASE ( self: int) -> Dict: """simple docstring""" __lowerCAmelCase : List[str] = self.prepare_config_and_inputs() self.check_vision_text_output_attention(**_SCREAMING_SNAKE_CASE) @is_pt_flax_cross_test def _SCREAMING_SNAKE_CASE ( self: Union[str, Any]) -> Any: """simple docstring""" __lowerCAmelCase : Dict = self.prepare_config_and_inputs() __lowerCAmelCase : List[Any] = config_inputs_dict.pop("vision_config") __lowerCAmelCase : str = config_inputs_dict.pop("text_config") __lowerCAmelCase : Union[str, Any] = config_inputs_dict self.check_equivalence_pt_to_flax(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE) self.check_equivalence_flax_to_pt(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE) @slow def _SCREAMING_SNAKE_CASE ( self: str) -> Dict: """simple docstring""" __lowerCAmelCase , __lowerCAmelCase : Dict = self.get_pretrained_model_and_inputs() __lowerCAmelCase : Union[str, Any] = model_a(**_SCREAMING_SNAKE_CASE) __lowerCAmelCase : List[str] = outputs[0] with tempfile.TemporaryDirectory() as tmp_dirname: model_a.save_pretrained(_SCREAMING_SNAKE_CASE) __lowerCAmelCase : List[Any] = FlaxVisionTextDualEncoderModel.from_pretrained(_SCREAMING_SNAKE_CASE) __lowerCAmelCase : Union[str, Any] = model_a(**_SCREAMING_SNAKE_CASE) __lowerCAmelCase : List[str] = after_outputs[0] __lowerCAmelCase : List[Any] = np.amax(np.abs(out_a - out_a)) self.assertLessEqual(_SCREAMING_SNAKE_CASE , 1e-5) @require_flax class A__ ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self: List[str]) -> List[Any]: """simple docstring""" __lowerCAmelCase : Any = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained( "hf-internal-testing/tiny-random-vit" , "hf-internal-testing/tiny-bert" , vision_from_pt=_SCREAMING_SNAKE_CASE , text_from_pt=_SCREAMING_SNAKE_CASE , ) __lowerCAmelCase : Union[str, Any] = 13 __lowerCAmelCase : Optional[int] = floats_tensor( [ batch_size, model.config.vision_config.num_channels, model.config.vision_config.image_size, model.config.vision_config.image_size, ]) __lowerCAmelCase : List[Any] = ids_tensor([batch_size, 4] , model.config.text_config.vocab_size) __lowerCAmelCase : List[Any] = random_attention_mask([batch_size, 4]) __lowerCAmelCase : str = {"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask} return model, inputs def _SCREAMING_SNAKE_CASE ( self: int , _SCREAMING_SNAKE_CASE: Union[str, Any] , _SCREAMING_SNAKE_CASE: Union[str, Any]) -> Optional[int]: """simple docstring""" __lowerCAmelCase : List[str] = FlaxViTModel(_SCREAMING_SNAKE_CASE) __lowerCAmelCase : Union[str, Any] = FlaxBertModel(_SCREAMING_SNAKE_CASE) return vision_model, text_model def _SCREAMING_SNAKE_CASE ( self: Optional[int]) -> int: """simple docstring""" __lowerCAmelCase : List[Any] = FlaxViTModelTester(self) __lowerCAmelCase : Optional[Any] = FlaxBertModelTester(self) __lowerCAmelCase : int = vit_model_tester.prepare_config_and_inputs() __lowerCAmelCase : List[str] = bert_model_tester.prepare_config_and_inputs() __lowerCAmelCase , __lowerCAmelCase : Tuple = vision_config_and_inputs __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase : Union[str, Any] = 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 A__ ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self: Dict) -> List[str]: """simple docstring""" __lowerCAmelCase : Optional[int] = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained( "hf-internal-testing/tiny-random-clip" , "hf-internal-testing/tiny-bert" , vision_from_pt=_SCREAMING_SNAKE_CASE , text_from_pt=_SCREAMING_SNAKE_CASE , ) __lowerCAmelCase : Optional[int] = 13 __lowerCAmelCase : List[str] = floats_tensor( [ batch_size, model.config.vision_config.num_channels, model.config.vision_config.image_size, model.config.vision_config.image_size, ]) __lowerCAmelCase : Any = ids_tensor([batch_size, 4] , model.config.text_config.vocab_size) __lowerCAmelCase : str = random_attention_mask([batch_size, 4]) __lowerCAmelCase : Optional[int] = {"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask} return model, inputs def _SCREAMING_SNAKE_CASE ( self: Optional[Any] , _SCREAMING_SNAKE_CASE: int , _SCREAMING_SNAKE_CASE: Union[str, Any]) -> int: """simple docstring""" __lowerCAmelCase : int = FlaxCLIPVisionModel(_SCREAMING_SNAKE_CASE) __lowerCAmelCase : List[str] = FlaxBertModel(_SCREAMING_SNAKE_CASE) return vision_model, text_model def _SCREAMING_SNAKE_CASE ( self: Union[str, Any]) -> Optional[Any]: """simple docstring""" __lowerCAmelCase : List[Any] = FlaxCLIPVisionModelTester(self) __lowerCAmelCase : str = FlaxBertModelTester(self) __lowerCAmelCase : Optional[Any] = clip_model_tester.prepare_config_and_inputs() __lowerCAmelCase : Dict = bert_model_tester.prepare_config_and_inputs() __lowerCAmelCase , __lowerCAmelCase : Any = vision_config_and_inputs __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase : List[Any] = 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 A__ ( unittest.TestCase ): '''simple docstring''' @slow def _SCREAMING_SNAKE_CASE ( self: List[str]) -> List[str]: """simple docstring""" __lowerCAmelCase : Dict = FlaxVisionTextDualEncoderModel.from_pretrained("clip-italian/clip-italian" , logit_scale_init_value=1.0) __lowerCAmelCase : str = VisionTextDualEncoderProcessor.from_pretrained("clip-italian/clip-italian") __lowerCAmelCase : Tuple = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") __lowerCAmelCase : Optional[int] = processor( text=["una foto di un gatto", "una foto di un cane"] , images=_SCREAMING_SNAKE_CASE , padding=_SCREAMING_SNAKE_CASE , return_tensors="np") __lowerCAmelCase : List[str] = model(**_SCREAMING_SNAKE_CASE) # 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]) , ) __lowerCAmelCase : List[str] = np.array([[1.228_4727, 0.310_4122]]) self.assertTrue(np.allclose(outputs.logits_per_image , _SCREAMING_SNAKE_CASE , atol=1e-3))
269
0
"""simple docstring""" import argparse from transformers import TaConfig, TaForConditionalGeneration, load_tf_weights_in_ta from transformers.utils import logging logging.set_verbosity_info() def _snake_case ( _snake_case : int , _snake_case : Union[str, Any] , _snake_case : Tuple ) -> Union[str, Any]: '''simple docstring''' _A = TaConfig.from_json_file(_snake_case ) print(F'''Building PyTorch model from configuration: {config}''' ) _A = TaForConditionalGeneration(_snake_case ) # Load weights from tf checkpoint load_tf_weights_in_ta(_snake_case , _snake_case , _snake_case ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) model.save_pretrained(_snake_case ) if __name__ == "__main__": a = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--tf_checkpoint_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained 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.''' ) a = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path)
271
"""simple docstring""" import argparse import json from typing import List from ltp import LTP from transformers import BertTokenizer def _snake_case ( _snake_case : Dict ) -> Any: '''simple docstring''' if ( (cp >= 0X4e00 and cp <= 0X9fff) or (cp >= 0X3400 and cp <= 0X4dbf) # or (cp >= 0X2_0000 and cp <= 0X2_a6df) # or (cp >= 0X2_a700 and cp <= 0X2_b73f) # or (cp >= 0X2_b740 and cp <= 0X2_b81f) # or (cp >= 0X2_b820 and cp <= 0X2_ceaf) # or (cp >= 0Xf900 and cp <= 0Xfaff) or (cp >= 0X2_f800 and cp <= 0X2_fa1f) # ): # return True return False def _snake_case ( _snake_case : str ) -> Tuple: '''simple docstring''' for char in word: _A = ord(_snake_case ) if not _is_chinese_char(_snake_case ): return 0 return 1 def _snake_case ( _snake_case : List[str] ) -> Optional[Any]: '''simple docstring''' _A = set() for token in tokens: _A = len(_snake_case ) > 1 and is_chinese(_snake_case ) if chinese_word: word_set.add(_snake_case ) _A = list(_snake_case ) return word_list def _snake_case ( _snake_case : List[str] , _snake_case : set() ) -> Optional[Any]: '''simple docstring''' if not chinese_word_set: return bert_tokens _A = max([len(_snake_case ) for w in chinese_word_set] ) _A = bert_tokens _A , _A = 0, len(_snake_case ) while start < end: _A = True if is_chinese(bert_word[start] ): _A = min(end - start , _snake_case ) for i in range(_snake_case , 1 , -1 ): _A = ''.join(bert_word[start : start + i] ) if whole_word in chinese_word_set: for j in range(start + 1 , start + i ): _A = '##' + bert_word[j] _A = start + i _A = False break if single_word: start += 1 return bert_word def _snake_case ( _snake_case : List[str] , _snake_case : LTP , _snake_case : BertTokenizer ) -> str: '''simple docstring''' _A = [] for i in range(0 , len(_snake_case ) , 1_00 ): _A = ltp_tokenizer.seg(lines[i : i + 1_00] )[0] _A = [get_chinese_word(_snake_case ) for r in res] ltp_res.extend(_snake_case ) assert len(_snake_case ) == len(_snake_case ) _A = [] for i in range(0 , len(_snake_case ) , 1_00 ): _A = bert_tokenizer(lines[i : i + 1_00] , add_special_tokens=_snake_case , truncation=_snake_case , max_length=5_12 ) bert_res.extend(res['input_ids'] ) assert len(_snake_case ) == len(_snake_case ) _A = [] for input_ids, chinese_word in zip(_snake_case , _snake_case ): _A = [] for id in input_ids: _A = bert_tokenizer._convert_id_to_token(_snake_case ) input_tokens.append(_snake_case ) _A = add_sub_symbol(_snake_case , _snake_case ) _A = [] # We only save pos of chinese subwords start with ##, which mean is part of a whole word. for i, token in enumerate(_snake_case ): if token[:2] == "##": _A = token[2:] # save chinese tokens' pos if len(_snake_case ) == 1 and _is_chinese_char(ord(_snake_case ) ): ref_id.append(_snake_case ) ref_ids.append(_snake_case ) assert len(_snake_case ) == len(_snake_case ) return ref_ids def _snake_case ( _snake_case : List[str] ) -> Dict: '''simple docstring''' with open(args.file_name , 'r' , encoding='utf-8' ) as f: _A = f.readlines() _A = [line.strip() for line in data if len(_snake_case ) > 0 and not line.isspace()] # avoid delimiter like '\u2029' _A = LTP(args.ltp ) # faster in GPU device _A = BertTokenizer.from_pretrained(args.bert ) _A = prepare_ref(_snake_case , _snake_case , _snake_case ) with open(args.save_path , 'w' , encoding='utf-8' ) as f: _A = [json.dumps(_snake_case ) + '\n' for ref in ref_ids] f.writelines(_snake_case ) if __name__ == "__main__": a = argparse.ArgumentParser(description='''prepare_chinese_ref''') parser.add_argument( '''--file_name''', type=str, default='''./resources/chinese-demo.txt''', help='''file need process, same as training data in lm''', ) parser.add_argument( '''--ltp''', type=str, default='''./resources/ltp''', help='''resources for LTP tokenizer, usually a path''' ) parser.add_argument('''--bert''', type=str, default='''./resources/robert''', help='''resources for Bert tokenizer''') parser.add_argument('''--save_path''', type=str, default='''./resources/ref.txt''', help='''path to save res''') a = parser.parse_args() main(args)
271
1