code
stringlengths
82
54.1k
code_codestyle
int64
0
699
style_context
stringlengths
111
35.6k
style_context_codestyle
int64
0
699
label
int64
0
1
import random from typing import Any def lowerCAmelCase_ ( __a ) -> list[Any]: """simple docstring""" for _ in range(len(__a ) ): lowerCamelCase__: Tuple =random.randint(0 , len(__a ) - 1 ) lowerCamelCase__: str =random.randint(0 , len(__a ) - 1 ) lowerCamelCase__ , lowerCamelCase__: Optional[int] =data[b], data[a] return data if __name__ == "__main__": __A = [0, 1, 2, 3, 4, 5, 6, 7] __A = ["python", "says", "hello", "!"] print("Fisher-Yates Shuffle:") print("List", integers, strings) print("FY Shuffle", fisher_yates_shuffle(integers), fisher_yates_shuffle(strings))
59
from __future__ import annotations from math import pi def lowerCAmelCase_ ( __a , __a , __a ) -> dict[str, float]: """simple docstring""" if (inductance, frequency, reactance).count(0 ) != 1: raise ValueError("One and only one argument must be 0" ) if inductance < 0: raise ValueError("Inductance cannot be negative" ) if frequency < 0: raise ValueError("Frequency cannot be negative" ) if reactance < 0: raise ValueError("Inductive reactance cannot be negative" ) if inductance == 0: return {"inductance": reactance / (2 * pi * frequency)} elif frequency == 0: return {"frequency": reactance / (2 * pi * inductance)} elif reactance == 0: return {"reactance": 2 * pi * frequency * inductance} else: raise ValueError("Exactly one argument must be 0" ) if __name__ == "__main__": import doctest doctest.testmod()
59
1
import os # Precomputes a list of the 100 first triangular numbers __A = [int(0.5 * n * (n + 1)) for n in range(1, 101)] def lowerCAmelCase_ ( ) -> List[str]: """simple docstring""" lowerCamelCase__: Optional[Any] =os.path.dirname(os.path.realpath(__a ) ) lowerCamelCase__: Optional[int] =os.path.join(__a , "words.txt" ) lowerCamelCase__: Dict ="" with open(__a ) as f: lowerCamelCase__: int =f.readline() lowerCamelCase__: Any =[word.strip("\"" ) for word in words.strip("\r\n" ).split("," )] lowerCamelCase__: Optional[Any] =[ word for word in [sum(ord(__a ) - 64 for x in word ) for word in words] if word in TRIANGULAR_NUMBERS ] return len(__a ) if __name__ == "__main__": print(solution())
59
import pyarrow.parquet as pq import pytest from datasets import Audio, Dataset, DatasetDict, Features, NamedSplit, Sequence, Value, config from datasets.features.image import Image from datasets.io.parquet import ParquetDatasetReader, ParquetDatasetWriter, get_writer_batch_size from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def lowerCAmelCase_ ( __a , __a ) -> List[Any]: """simple docstring""" assert isinstance(__a , __a ) 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 lowerCAmelCase_ ( __a , __a , __a ) -> Any: """simple docstring""" lowerCamelCase__: Any =tmp_path / "cache" lowerCamelCase__: Optional[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(): lowerCamelCase__: Tuple =ParquetDatasetReader(__a , cache_dir=__a , keep_in_memory=__a ).read() _check_parquet_dataset(__a , __a ) @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 lowerCAmelCase_ ( __a , __a , __a ) -> List[str]: """simple docstring""" lowerCamelCase__: int =tmp_path / "cache" lowerCamelCase__: Tuple ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: Union[str, Any] =features.copy() if features else default_expected_features lowerCamelCase__: Optional[int] =( Features({feature: Value(__a ) for feature, dtype in features.items()} ) if features is not None else None ) lowerCamelCase__: int =ParquetDatasetReader(__a , features=__a , cache_dir=__a ).read() _check_parquet_dataset(__a , __a ) @pytest.mark.parametrize("split" , [None, NamedSplit("train" ), "train", "test"] ) def lowerCAmelCase_ ( __a , __a , __a ) -> Any: """simple docstring""" lowerCamelCase__: Any =tmp_path / "cache" lowerCamelCase__: Optional[Any] ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: Optional[Any] =ParquetDatasetReader(__a , cache_dir=__a , split=__a ).read() _check_parquet_dataset(__a , __a ) assert dataset.split == split if split else "train" @pytest.mark.parametrize("path_type" , [str, list] ) def lowerCAmelCase_ ( __a , __a , __a ) -> int: """simple docstring""" if issubclass(__a , __a ): lowerCamelCase__: List[Any] =parquet_path elif issubclass(__a , __a ): lowerCamelCase__: str =[parquet_path] lowerCamelCase__: Tuple =tmp_path / "cache" lowerCamelCase__: Optional[Any] ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: int =ParquetDatasetReader(__a , cache_dir=__a ).read() _check_parquet_dataset(__a , __a ) def lowerCAmelCase_ ( __a , __a , __a=("train",) ) -> Dict: """simple docstring""" assert isinstance(__a , __a ) for split in splits: lowerCamelCase__: Tuple =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 lowerCAmelCase_ ( __a , __a , __a ) -> Any: """simple docstring""" lowerCamelCase__: List[Any] =tmp_path / "cache" lowerCamelCase__: Optional[Any] ={"col_1": "string", "col_2": "int64", "col_3": "float64"} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): lowerCamelCase__: Tuple =ParquetDatasetReader( {"train": parquet_path} , cache_dir=__a , keep_in_memory=__a ).read() _check_parquet_datasetdict(__a , __a ) @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 lowerCAmelCase_ ( __a , __a , __a ) -> Optional[Any]: """simple docstring""" lowerCamelCase__: Tuple =tmp_path / "cache" lowerCamelCase__: Optional[int] ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: List[Any] =features.copy() if features else default_expected_features lowerCamelCase__: int =( Features({feature: Value(__a ) for feature, dtype in features.items()} ) if features is not None else None ) lowerCamelCase__: Optional[Any] =ParquetDatasetReader({"train": parquet_path} , features=__a , cache_dir=__a ).read() _check_parquet_datasetdict(__a , __a ) @pytest.mark.parametrize("split" , [None, NamedSplit("train" ), "train", "test"] ) def lowerCAmelCase_ ( __a , __a , __a ) -> Union[str, Any]: """simple docstring""" if split: lowerCamelCase__: Any ={split: parquet_path} else: lowerCamelCase__: int ="train" lowerCamelCase__: Any ={"train": parquet_path, "test": parquet_path} lowerCamelCase__: str =tmp_path / "cache" lowerCamelCase__: Any ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: int =ParquetDatasetReader(__a , cache_dir=__a ).read() _check_parquet_datasetdict(__a , __a , splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() ) def lowerCAmelCase_ ( __a , __a ) -> int: """simple docstring""" lowerCamelCase__: List[str] =ParquetDatasetWriter(__a , tmp_path / "foo.parquet" ) assert writer.write() > 0 lowerCamelCase__: List[str] =pq.ParquetFile(tmp_path / "foo.parquet" ) lowerCamelCase__: List[str] =pf.read() assert dataset.data.table == output_table def lowerCAmelCase_ ( __a , __a ) -> List[str]: """simple docstring""" lowerCamelCase__: List[str] =str(shared_datadir / "test_image_rgb.jpg" ) lowerCamelCase__: Union[str, Any] ={"image": [image_path]} lowerCamelCase__: Optional[Any] =Features({"image": Image()} ) lowerCamelCase__: Optional[int] =Dataset.from_dict(__a , features=__a ) lowerCamelCase__: Optional[int] =ParquetDatasetWriter(__a , tmp_path / "foo.parquet" ) assert writer.write() > 0 lowerCamelCase__: Dict =Dataset.from_parquet(str(tmp_path / "foo.parquet" ) ) assert dataset.features == reloaded_dataset.features lowerCamelCase__: Optional[Any] =ParquetDatasetReader(str(tmp_path / "foo.parquet" ) , streaming=__a ).read() assert dataset.features == reloaded_iterable_dataset.features @pytest.mark.parametrize( "feature, expected" , [ (Features({"foo": Value("int32" )} ), None), (Features({"image": Image(), "foo": Value("int32" )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS), (Features({"nested": Sequence(Audio() )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS), ] , ) def lowerCAmelCase_ ( __a , __a ) -> Optional[Any]: """simple docstring""" assert get_writer_batch_size(__a ) == expected
59
1
def lowerCAmelCase_ ( __a ) -> None: """simple docstring""" lowerCamelCase__: List[Any] =generate_pascal_triangle(__a ) for row_idx in range(__a ): # Print left spaces for _ in range(num_rows - row_idx - 1 ): print(end=" " ) # Print row values for col_idx in range(row_idx + 1 ): if col_idx != row_idx: print(triangle[row_idx][col_idx] , end=" " ) else: print(triangle[row_idx][col_idx] , end="" ) print() def lowerCAmelCase_ ( __a ) -> list[list[int]]: """simple docstring""" if not isinstance(__a , __a ): raise TypeError("The input value of 'num_rows' should be 'int'" ) if num_rows == 0: return [] elif num_rows < 0: raise ValueError( "The input value of 'num_rows' should be greater than or equal to 0" ) lowerCamelCase__: list[list[int]] =[] for current_row_idx in range(__a ): lowerCamelCase__: Any =populate_current_row(__a , __a ) triangle.append(__a ) return triangle def lowerCAmelCase_ ( __a , __a ) -> list[int]: """simple docstring""" lowerCamelCase__: Dict =[-1] * (current_row_idx + 1) # first and last elements of current row are equal to 1 lowerCamelCase__ , lowerCamelCase__: Dict =1, 1 for current_col_idx in range(1 , __a ): calculate_current_element( __a , __a , __a , __a ) return current_row def lowerCAmelCase_ ( __a , __a , __a , __a , ) -> None: """simple docstring""" lowerCamelCase__: Dict =triangle[current_row_idx - 1][current_col_idx - 1] lowerCamelCase__: List[Any] =triangle[current_row_idx - 1][current_col_idx] lowerCamelCase__: int =above_to_left_elt + above_to_right_elt def lowerCAmelCase_ ( __a ) -> list[list[int]]: """simple docstring""" if not isinstance(__a , __a ): raise TypeError("The input value of 'num_rows' should be 'int'" ) if num_rows == 0: return [] elif num_rows < 0: raise ValueError( "The input value of 'num_rows' should be greater than or equal to 0" ) lowerCamelCase__: list[list[int]] =[[1]] for row_index in range(1 , __a ): lowerCamelCase__: str =[0] + result[-1] + [0] lowerCamelCase__: List[str] =row_index + 1 # Calculate the number of distinct elements in a row lowerCamelCase__: str =sum(divmod(__a , 2 ) ) lowerCamelCase__: Union[str, Any] =[ temp_row[i - 1] + temp_row[i] for i in range(1 , distinct_elements + 1 ) ] lowerCamelCase__: Optional[int] =row_first_half[: (row_index + 1) // 2] row_second_half.reverse() lowerCamelCase__: Optional[int] =row_first_half + row_second_half result.append(__a ) return result def lowerCAmelCase_ ( ) -> None: """simple docstring""" from collections.abc import Callable from timeit import timeit def benchmark_a_function(__a , __a ) -> None: lowerCamelCase__: Union[str, Any] =F"""{func.__name__}({value})""" lowerCamelCase__: Any =timeit(F"""__main__.{call}""" , setup="import __main__" ) # print(f"{call:38} = {func(value)} -- {timing:.4f} seconds") print(F"""{call:38} -- {timing:.4f} seconds""" ) for value in range(15 ): # (1, 7, 14): for func in (generate_pascal_triangle, generate_pascal_triangle_optimized): benchmark_a_function(__a , __a ) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
59
import unittest from transformers.models.xlm_prophetnet.tokenization_xlm_prophetnet import SPIECE_UNDERLINE, XLMProphetNetTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin __A = get_tests_dir("fixtures/test_sentencepiece.model") @require_sentencepiece class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowercase_ = XLMProphetNetTokenizer lowercase_ = False lowercase_ = True def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Optional[Any]: '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing lowerCamelCase__: Any =XLMProphetNetTokenizer(UpperCAmelCase_ , keep_accents=UpperCAmelCase_) tokenizer.save_pretrained(self.tmpdirname) def SCREAMING_SNAKE_CASE_ (self : str) ->str: '''simple docstring''' lowerCamelCase__: List[Any] ="[PAD]" lowerCamelCase__: Tuple =0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCAmelCase_) , UpperCAmelCase_) self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCAmelCase_) , UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Dict) ->int: '''simple docstring''' lowerCamelCase__: List[Any] =list(self.get_tokenizer().get_vocab().keys()) self.assertEqual(vocab_keys[0] , "[PAD]") self.assertEqual(vocab_keys[1] , "[CLS]") self.assertEqual(vocab_keys[-1] , "j") self.assertEqual(len(UpperCAmelCase_) , 1_012) def SCREAMING_SNAKE_CASE_ (self : Dict) ->Union[str, Any]: '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 1_012) def SCREAMING_SNAKE_CASE_ (self : Any) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Optional[Any] =XLMProphetNetTokenizer(UpperCAmelCase_ , keep_accents=UpperCAmelCase_) lowerCamelCase__: 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]] , ) lowerCamelCase__: Optional[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", "é", ".", ] , ) lowerCamelCase__: Any =tokenizer.convert_tokens_to_ids(UpperCAmelCase_) self.assertListEqual( UpperCAmelCase_ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, -9, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, -9, 4] ] , ) lowerCamelCase__: 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]", ".", ] , ) @cached_property def SCREAMING_SNAKE_CASE_ (self : Any) ->int: '''simple docstring''' return XLMProphetNetTokenizer.from_pretrained("microsoft/xprophetnet-large-wiki100-cased") @slow def SCREAMING_SNAKE_CASE_ (self : List[str]) ->List[str]: '''simple docstring''' lowerCamelCase__: Optional[int] ="Hello World!" lowerCamelCase__: Dict =[35_389, 6_672, 49, 2] self.assertListEqual(UpperCAmelCase_ , self.big_tokenizer.encode(UpperCAmelCase_)) @slow def SCREAMING_SNAKE_CASE_ (self : int) ->Union[str, Any]: '''simple docstring''' lowerCamelCase__: Any ={"input_ids": [[11_073, 82_783, 18, 26, 82_783, 549, 51_540, 248, 17_209, 1_301, 217, 20, 215_186, 1_325, 147, 17_209, 1_301, 217, 20, 56_370, 53, 122_020, 20, 16_477, 27, 87_355, 4_548, 20, 4_728, 78_392, 17, 159_969, 18, 26, 24_491, 629, 15, 538, 22_704, 5_439, 15, 2_788, 24_491, 9_885, 15, 43_534, 605, 15, 814, 18_403, 33_200, 29, 15, 43_534, 24_458, 12_410, 111, 24_966, 83_669, 9_637, 144_068, 26, 850, 22_346, 27, 147, 24_966, 83_669, 83_490, 26, 39_113, 735, 27, 689, 656, 2_800, 1_339, 4_600, 53, 122_020, 115_785, 34, 816, 1_339, 46_887, 18, 147, 53_905, 1_951, 42_238, 41_170, 17_732, 834, 436, 15, 27_523, 98_733, 217, 147, 5_542, 4_981, 930, 17_347, 16, 2], [20_091, 629, 94, 82_786, 58, 490, 20, 1_528, 84, 53_905, 344, 80_592, 110_128, 18_822, 5_267, 1_306, 62, 152_537, 308, 7_997, 401, 124_427, 549, 35_442, 225, 109, 15_055, 25_748, 147, 7_119, 43_712, 34, 767, 135_366, 18, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [592, 63_784, 119_466, 17, 147_808, 88_214, 18, 656, 81, 32, 3_296, 10_280, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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="microsoft/xprophetnet-large-wiki100-cased" , revision="1acad1643ddd54a44df6a1b797ada8373685d90e" , )
59
1
import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, BatchEncoding, MBartaaTokenizer, MBartaaTokenizerFast, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, slow, ) from ...test_tokenization_common import TokenizerTesterMixin __A = get_tests_dir("fixtures/test_sentencepiece.model") if is_torch_available(): from transformers.models.mbart.modeling_mbart import shift_tokens_right __A = 25_0004 __A = 25_0020 @require_sentencepiece @require_tokenizers class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowercase_ = MBartaaTokenizer lowercase_ = MBartaaTokenizerFast lowercase_ = True lowercase_ = True def SCREAMING_SNAKE_CASE_ (self : Union[str, Any]) ->Any: '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing lowerCamelCase__: List[Any] =MBartaaTokenizer(UpperCAmelCase_ , src_lang="en_XX" , tgt_lang="ro_RO" , keep_accents=UpperCAmelCase_) tokenizer.save_pretrained(self.tmpdirname) def SCREAMING_SNAKE_CASE_ (self : Any) ->str: '''simple docstring''' lowerCamelCase__: Tuple ="<s>" lowerCamelCase__: str =0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCAmelCase_) , UpperCAmelCase_) self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCAmelCase_) , UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : int) ->Tuple: '''simple docstring''' lowerCamelCase__: List[Any] =list(self.get_tokenizer().get_vocab().keys()) self.assertEqual(vocab_keys[0] , "<s>") self.assertEqual(vocab_keys[1] , "<pad>") self.assertEqual(vocab_keys[-1] , "<mask>") self.assertEqual(len(UpperCAmelCase_) , 1_054) def SCREAMING_SNAKE_CASE_ (self : Dict) ->List[str]: '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 1_054) def SCREAMING_SNAKE_CASE_ (self : Union[str, Any]) ->Dict: '''simple docstring''' lowerCamelCase__: Union[str, Any] =MBartaaTokenizer(UpperCAmelCase_ , src_lang="en_XX" , tgt_lang="ro_RO" , keep_accents=UpperCAmelCase_) lowerCamelCase__: Any =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]] , ) lowerCamelCase__: Optional[int] =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", "é", "."] , ) lowerCamelCase__: List[str] =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] ] , ) lowerCamelCase__: List[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>", "."] , ) @slow def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Any: '''simple docstring''' lowerCamelCase__: Optional[Any] ={"input_ids": [[250_004, 11_062, 82_772, 7, 15, 82_772, 538, 51_529, 237, 17_198, 1_290, 206, 9, 215_175, 1_314, 136, 17_198, 1_290, 206, 9, 56_359, 42, 122_009, 9, 16_466, 16, 87_344, 4_537, 9, 4_717, 78_381, 6, 159_958, 7, 15, 24_480, 618, 4, 527, 22_693, 5_428, 4, 2_777, 24_480, 9_874, 4, 43_523, 594, 4, 803, 18_392, 33_189, 18, 4, 43_523, 24_447, 12_399, 100, 24_955, 83_658, 9_626, 144_057, 15, 839, 22_335, 16, 136, 24_955, 83_658, 83_479, 15, 39_102, 724, 16, 678, 645, 2_789, 1_328, 4_589, 42, 122_009, 115_774, 23, 805, 1_328, 46_876, 7, 136, 53_894, 1_940, 42_227, 41_159, 17_721, 823, 425, 4, 27_512, 98_722, 206, 136, 5_531, 4_970, 919, 17_336, 5, 2], [250_004, 20_080, 618, 83, 82_775, 47, 479, 9, 1_517, 73, 53_894, 333, 80_581, 110_117, 18_811, 5_256, 1_295, 51, 152_526, 297, 7_986, 390, 124_416, 538, 35_431, 214, 98, 15_044, 25_737, 136, 7_108, 43_701, 23, 756, 135_355, 7, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [250_004, 581, 63_773, 119_455, 6, 147_797, 88_203, 7, 645, 70, 21, 3_285, 10_269, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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="facebook/mbart-large-50" , revision="d3913889c59cd5c9e456b269c376325eabad57e2" , ) def SCREAMING_SNAKE_CASE_ (self : str) ->Optional[Any]: '''simple docstring''' if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return lowerCamelCase__: Tuple =(self.rust_tokenizer_class, "hf-internal-testing/tiny-random-mbart50", {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})"""): lowerCamelCase__: int =self.rust_tokenizer_class.from_pretrained(UpperCAmelCase_ , **UpperCAmelCase_) lowerCamelCase__: List[Any] =self.tokenizer_class.from_pretrained(UpperCAmelCase_ , **UpperCAmelCase_) lowerCamelCase__: Any =tempfile.mkdtemp() lowerCamelCase__: Tuple =tokenizer_r.save_pretrained(UpperCAmelCase_) lowerCamelCase__: Tuple =tokenizer_p.save_pretrained(UpperCAmelCase_) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any("tokenizer.json" in f for f in tokenizer_r_files)) lowerCamelCase__: Dict =tuple(f for f in tokenizer_r_files if "tokenizer.json" not in f) self.assertSequenceEqual(UpperCAmelCase_ , UpperCAmelCase_) # Checks everything loads correctly in the same way lowerCamelCase__: List[str] =tokenizer_r.from_pretrained(UpperCAmelCase_) lowerCamelCase__: List[str] =tokenizer_p.from_pretrained(UpperCAmelCase_) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(UpperCAmelCase_ , UpperCAmelCase_)) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(UpperCAmelCase_) # Save tokenizer rust, legacy_format=True lowerCamelCase__: Tuple =tempfile.mkdtemp() lowerCamelCase__: List[Any] =tokenizer_r.save_pretrained(UpperCAmelCase_ , legacy_format=UpperCAmelCase_) lowerCamelCase__: str =tokenizer_p.save_pretrained(UpperCAmelCase_) # Checks it save with the same files self.assertSequenceEqual(UpperCAmelCase_ , UpperCAmelCase_) # Checks everything loads correctly in the same way lowerCamelCase__: Dict =tokenizer_r.from_pretrained(UpperCAmelCase_) lowerCamelCase__: List[str] =tokenizer_p.from_pretrained(UpperCAmelCase_) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(UpperCAmelCase_ , UpperCAmelCase_)) shutil.rmtree(UpperCAmelCase_) # Save tokenizer rust, legacy_format=False lowerCamelCase__: Tuple =tempfile.mkdtemp() lowerCamelCase__: Dict =tokenizer_r.save_pretrained(UpperCAmelCase_ , legacy_format=UpperCAmelCase_) lowerCamelCase__: Dict =tokenizer_p.save_pretrained(UpperCAmelCase_) # Checks it saved the tokenizer.json file self.assertTrue(any("tokenizer.json" in f for f in tokenizer_r_files)) # Checks everything loads correctly in the same way lowerCamelCase__: Union[str, Any] =tokenizer_r.from_pretrained(UpperCAmelCase_) lowerCamelCase__: int =tokenizer_p.from_pretrained(UpperCAmelCase_) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(UpperCAmelCase_ , UpperCAmelCase_)) shutil.rmtree(UpperCAmelCase_) @require_torch @require_sentencepiece @require_tokenizers class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' lowercase_ = "facebook/mbart-large-50-one-to-many-mmt" lowercase_ = [ " UN Chief Says There Is No Military Solution in Syria", " Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for Syria is that \"there is no military solution\" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.", ] lowercase_ = [ "Şeful ONU declară că nu există o soluţie militară în Siria", "Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei" " pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi că noi arme nu vor" " face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.", ] lowercase_ = [EN_CODE, 8274, 12_7873, 2_5916, 7, 8622, 2071, 438, 6_7485, 53, 18_7895, 23, 5_1712, 2] @classmethod def SCREAMING_SNAKE_CASE_ (cls : int) ->List[str]: '''simple docstring''' lowerCamelCase__: MBartaaTokenizer =MBartaaTokenizer.from_pretrained( cls.checkpoint_name , src_lang="en_XX" , tgt_lang="ro_RO") lowerCamelCase__: Union[str, Any] =1 return cls def SCREAMING_SNAKE_CASE_ (self : Dict) ->Optional[int]: '''simple docstring''' self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["ar_AR"] , 250_001) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["en_EN"] , 250_004) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["ro_RO"] , 250_020) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["mr_IN"] , 250_038) def SCREAMING_SNAKE_CASE_ (self : Dict) ->Dict: '''simple docstring''' lowerCamelCase__: Union[str, Any] =self.tokenizer.batch_encode_plus(self.src_text).input_ids[0] self.assertListEqual(self.expected_src_tokens , UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->Any: '''simple docstring''' self.assertIn(UpperCAmelCase_ , self.tokenizer.all_special_ids) lowerCamelCase__: Tuple =[RO_CODE, 884, 9_019, 96, 9, 916, 86_792, 36, 18_743, 15_596, 5, 2] lowerCamelCase__: Dict =self.tokenizer.decode(UpperCAmelCase_ , skip_special_tokens=UpperCAmelCase_) lowerCamelCase__: Optional[int] =self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=UpperCAmelCase_) self.assertEqual(UpperCAmelCase_ , UpperCAmelCase_) self.assertNotIn(self.tokenizer.eos_token , UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : int) ->Tuple: '''simple docstring''' lowerCamelCase__: List[Any] =["this is gunna be a long sentence " * 20] assert isinstance(src_text[0] , UpperCAmelCase_) lowerCamelCase__: str =10 lowerCamelCase__: Union[str, Any] =self.tokenizer(UpperCAmelCase_ , max_length=UpperCAmelCase_ , truncation=UpperCAmelCase_).input_ids[0] self.assertEqual(ids[0] , UpperCAmelCase_) self.assertEqual(ids[-1] , 2) self.assertEqual(len(UpperCAmelCase_) , UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[str]) ->str: '''simple docstring''' self.assertListEqual(self.tokenizer.convert_tokens_to_ids(["<mask>", "ar_AR"]) , [250_053, 250_001]) def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Dict =tempfile.mkdtemp() lowerCamelCase__: int =self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(UpperCAmelCase_) lowerCamelCase__: Any =MBartaaTokenizer.from_pretrained(UpperCAmelCase_) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , UpperCAmelCase_) @require_torch def SCREAMING_SNAKE_CASE_ (self : Any) ->int: '''simple docstring''' lowerCamelCase__: Union[str, Any] =self.tokenizer(self.src_text , text_target=self.tgt_text , padding=UpperCAmelCase_ , return_tensors="pt") lowerCamelCase__: List[Any] =shift_tokens_right(batch["labels"] , self.tokenizer.pad_token_id) # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 assert batch.input_ids[1][0] == EN_CODE assert batch.input_ids[1][-1] == 2 assert batch.labels[1][0] == RO_CODE assert batch.labels[1][-1] == 2 assert batch.decoder_input_ids[1][:2].tolist() == [2, RO_CODE] @require_torch def SCREAMING_SNAKE_CASE_ (self : int) ->Optional[Any]: '''simple docstring''' lowerCamelCase__: List[str] =self.tokenizer( self.src_text , text_target=self.tgt_text , padding=UpperCAmelCase_ , truncation=UpperCAmelCase_ , max_length=len(self.expected_src_tokens) , return_tensors="pt" , ) lowerCamelCase__: Optional[Any] =shift_tokens_right(batch["labels"] , self.tokenizer.pad_token_id) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_) self.assertEqual((2, 14) , batch.input_ids.shape) self.assertEqual((2, 14) , batch.attention_mask.shape) lowerCamelCase__: Optional[Any] =batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , UpperCAmelCase_) self.assertEqual(2 , batch.decoder_input_ids[0, 0]) # decoder_start_token_id # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [EN_CODE]) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id]) def SCREAMING_SNAKE_CASE_ (self : Any) ->List[str]: '''simple docstring''' lowerCamelCase__: int =self.tokenizer(self.src_text , padding=UpperCAmelCase_ , truncation=UpperCAmelCase_ , max_length=3 , return_tensors="pt") lowerCamelCase__: str =self.tokenizer( text_target=self.tgt_text , padding=UpperCAmelCase_ , truncation=UpperCAmelCase_ , max_length=10 , return_tensors="pt") lowerCamelCase__: Optional[Any] =targets["input_ids"] lowerCamelCase__: Tuple =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 SCREAMING_SNAKE_CASE_ (self : str) ->Optional[int]: '''simple docstring''' lowerCamelCase__: List[str] =self.tokenizer._build_translation_inputs( "A test" , return_tensors="pt" , src_lang="en_XX" , tgt_lang="ar_AR") self.assertEqual( nested_simplify(UpperCAmelCase_) , { # en_XX, A, test, EOS "input_ids": [[250_004, 62, 3_034, 2]], "attention_mask": [[1, 1, 1, 1]], # ar_AR "forced_bos_token_id": 250_001, } , )
59
import os import shutil import tempfile import unittest import numpy as np from transformers import AutoTokenizer, BarkProcessor from transformers.testing_utils import require_torch, slow @require_torch class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ (self : List[str]) ->str: '''simple docstring''' lowerCamelCase__: Union[str, Any] ="ylacombe/bark-small" lowerCamelCase__: Tuple =tempfile.mkdtemp() lowerCamelCase__: Tuple ="en_speaker_1" lowerCamelCase__: Optional[int] ="This is a test string" lowerCamelCase__: List[str] ="speaker_embeddings_path.json" lowerCamelCase__: int ="speaker_embeddings" def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , **UpperCAmelCase_ : Any) ->Tuple: '''simple docstring''' return AutoTokenizer.from_pretrained(self.checkpoint , **UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[str]) ->Union[str, Any]: '''simple docstring''' shutil.rmtree(self.tmpdirname) def SCREAMING_SNAKE_CASE_ (self : int) ->Any: '''simple docstring''' lowerCamelCase__: List[Any] =self.get_tokenizer() lowerCamelCase__: List[str] =BarkProcessor(tokenizer=UpperCAmelCase_) processor.save_pretrained(self.tmpdirname) lowerCamelCase__: Dict =BarkProcessor.from_pretrained(self.tmpdirname) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab()) @slow def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Tuple: '''simple docstring''' lowerCamelCase__: Tuple =BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) processor.save_pretrained( self.tmpdirname , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , speaker_embeddings_directory=self.speaker_embeddings_directory , ) lowerCamelCase__: Dict =self.get_tokenizer(bos_token="(BOS)" , eos_token="(EOS)") lowerCamelCase__: Any =BarkProcessor.from_pretrained( self.tmpdirname , self.speaker_embeddings_dict_path , bos_token="(BOS)" , eos_token="(EOS)" , ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab()) def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->int: '''simple docstring''' lowerCamelCase__: Any =BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) lowerCamelCase__: List[str] =35 lowerCamelCase__: Optional[Any] =2 lowerCamelCase__: Optional[Any] =8 lowerCamelCase__: Optional[int] ={ "semantic_prompt": np.ones(UpperCAmelCase_), "coarse_prompt": np.ones((nb_codebooks_coarse, seq_len)), "fine_prompt": np.ones((nb_codebooks_total, seq_len)), } # test providing already loaded voice_preset lowerCamelCase__: Any =processor(text=self.input_string , voice_preset=UpperCAmelCase_) lowerCamelCase__: int =inputs["history_prompt"] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(UpperCAmelCase_ , np.array([])).tolist()) # test loading voice preset from npz file lowerCamelCase__: Union[str, Any] =os.path.join(self.tmpdirname , "file.npz") np.savez(UpperCAmelCase_ , **UpperCAmelCase_) lowerCamelCase__: Tuple =processor(text=self.input_string , voice_preset=UpperCAmelCase_) lowerCamelCase__: Optional[Any] =inputs["history_prompt"] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(UpperCAmelCase_ , np.array([])).tolist()) # test loading voice preset from the hub lowerCamelCase__: Any =processor(text=self.input_string , voice_preset=self.voice_preset) def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Union[str, Any]: '''simple docstring''' lowerCamelCase__: str =self.get_tokenizer() lowerCamelCase__: Dict =BarkProcessor(tokenizer=UpperCAmelCase_) lowerCamelCase__: List[Any] =processor(text=self.input_string) lowerCamelCase__: Optional[int] =tokenizer( self.input_string , padding="max_length" , max_length=256 , add_special_tokens=UpperCAmelCase_ , return_attention_mask=UpperCAmelCase_ , return_token_type_ids=UpperCAmelCase_ , ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key].squeeze().tolist())
59
1
import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = "Speech2TextFeatureExtractor" lowercase_ = "Speech2TextTokenizer" def __init__(self : Optional[Any] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Optional[Any]) ->Any: '''simple docstring''' super().__init__(UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: Dict =self.feature_extractor lowerCamelCase__: Tuple =False def __call__(self : Optional[int] , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : Tuple) ->Optional[Any]: '''simple docstring''' if self._in_target_context_manager: return self.current_processor(*UpperCAmelCase_ , **UpperCAmelCase_) if "raw_speech" in kwargs: warnings.warn("Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.") lowerCamelCase__: Any =kwargs.pop("raw_speech") else: lowerCamelCase__: List[Any] =kwargs.pop("audio" , UpperCAmelCase_) lowerCamelCase__: Dict =kwargs.pop("sampling_rate" , UpperCAmelCase_) lowerCamelCase__: List[Any] =kwargs.pop("text" , UpperCAmelCase_) if len(UpperCAmelCase_) > 0: lowerCamelCase__: int =args[0] lowerCamelCase__: Optional[int] =args[1:] if audio is None and text is None: raise ValueError("You need to specify either an `audio` or `text` input to process.") if audio is not None: lowerCamelCase__: List[Any] =self.feature_extractor(UpperCAmelCase_ , *UpperCAmelCase_ , sampling_rate=UpperCAmelCase_ , **UpperCAmelCase_) if text is not None: lowerCamelCase__: List[Any] =self.tokenizer(UpperCAmelCase_ , **UpperCAmelCase_) if text is None: return inputs elif audio is None: return encodings else: lowerCamelCase__: List[str] =encodings["input_ids"] return inputs def SCREAMING_SNAKE_CASE_ (self : int , *UpperCAmelCase_ : Any , **UpperCAmelCase_ : Dict) ->List[str]: '''simple docstring''' return self.tokenizer.batch_decode(*UpperCAmelCase_ , **UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , *UpperCAmelCase_ : Union[str, Any] , **UpperCAmelCase_ : str) ->Tuple: '''simple docstring''' return self.tokenizer.decode(*UpperCAmelCase_ , **UpperCAmelCase_) @contextmanager def SCREAMING_SNAKE_CASE_ (self : List[str]) ->Optional[Any]: '''simple docstring''' warnings.warn( "`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your " "labels by using the argument `text` of the regular `__call__` method (either in the same call as " "your audio inputs, or in a separate call.") lowerCamelCase__: int =True lowerCamelCase__: Any =self.tokenizer yield lowerCamelCase__: Tuple =self.feature_extractor lowerCamelCase__: str =False
59
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = ["image_processor", "tokenizer"] lowercase_ = "CLIPImageProcessor" lowercase_ = ("XLMRobertaTokenizer", "XLMRobertaTokenizerFast") def __init__(self : List[Any] , UpperCAmelCase_ : int=None , UpperCAmelCase_ : List[Any]=None , **UpperCAmelCase_ : List[str]) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Union[str, Any] =None if "feature_extractor" in kwargs: warnings.warn( "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`" " instead." , UpperCAmelCase_ , ) lowerCamelCase__: int =kwargs.pop("feature_extractor") lowerCamelCase__: int =image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("You need to specify an `image_processor`.") if tokenizer is None: raise ValueError("You need to specify a `tokenizer`.") super().__init__(UpperCAmelCase_ , UpperCAmelCase_) def __call__(self : List[Any] , UpperCAmelCase_ : str=None , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : int=None , **UpperCAmelCase_ : Any) ->Union[str, Any]: '''simple docstring''' if text is None and images is None: raise ValueError("You have to specify either text or images. Both cannot be none.") if text is not None: lowerCamelCase__: List[Any] =self.tokenizer(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_) if images is not None: lowerCamelCase__: int =self.image_processor(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_) if text is not None and images is not None: lowerCamelCase__: str =image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**UpperCAmelCase_) , tensor_type=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[str] , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : Optional[Any]) ->Dict: '''simple docstring''' return self.tokenizer.batch_decode(*UpperCAmelCase_ , **UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Optional[int] , *UpperCAmelCase_ : int , **UpperCAmelCase_ : Any) ->Optional[Any]: '''simple docstring''' return self.tokenizer.decode(*UpperCAmelCase_ , **UpperCAmelCase_) @property def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Optional[Any] =self.tokenizer.model_input_names lowerCamelCase__: str =self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
59
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) __A = { "configuration_convnext": ["CONVNEXT_PRETRAINED_CONFIG_ARCHIVE_MAP", "ConvNextConfig", "ConvNextOnnxConfig"] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ["ConvNextFeatureExtractor"] __A = ["ConvNextImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ "CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST", "ConvNextForImageClassification", "ConvNextModel", "ConvNextPreTrainedModel", "ConvNextBackbone", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ "TFConvNextForImageClassification", "TFConvNextModel", "TFConvNextPreTrainedModel", ] if TYPE_CHECKING: from .configuration_convnext import CONVNEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, ConvNextConfig, ConvNextOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_convnext import ConvNextFeatureExtractor from .image_processing_convnext import ConvNextImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_convnext import ( CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST, ConvNextBackbone, ConvNextForImageClassification, ConvNextModel, ConvNextPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_convnext import TFConvNextForImageClassification, TFConvNextModel, TFConvNextPreTrainedModel else: import sys __A = _LazyModule(__name__, globals()["__file__"], _import_structure)
59
from datetime import datetime import matplotlib.pyplot as plt import torch def lowerCAmelCase_ ( __a ) -> Any: """simple docstring""" for param in module.parameters(): lowerCamelCase__: Tuple =False def lowerCAmelCase_ ( ) -> Optional[int]: """simple docstring""" lowerCamelCase__: List[str] ="cuda" if torch.cuda.is_available() else "cpu" if torch.backends.mps.is_available() and torch.backends.mps.is_built(): lowerCamelCase__: str ="mps" if device == "mps": print( "WARNING: MPS currently doesn't seem to work, and messes up backpropagation without any visible torch" " errors. I recommend using CUDA on a colab notebook or CPU instead if you're facing inexplicable issues" " with generations." ) return device def lowerCAmelCase_ ( __a ) -> List[str]: """simple docstring""" lowerCamelCase__: Union[str, Any] =plt.imshow(__a ) fig.axes.get_xaxis().set_visible(__a ) fig.axes.get_yaxis().set_visible(__a ) plt.show() def lowerCAmelCase_ ( ) -> Optional[Any]: """simple docstring""" lowerCamelCase__: List[str] =datetime.now() lowerCamelCase__: str =current_time.strftime("%H:%M:%S" ) return timestamp
59
1
import argparse import json import os import sys import tempfile import unittest from argparse import Namespace from dataclasses import dataclass, field from enum import Enum from pathlib import Path from typing import List, Literal, Optional import yaml from transformers import HfArgumentParser, TrainingArguments from transformers.hf_argparser import make_choice_type_function, string_to_bool # Since Python 3.10, we can use the builtin `|` operator for Union types # See PEP 604: https://peps.python.org/pep-0604 __A = sys.version_info >= (3, 10) def lowerCAmelCase_ ( __a=None , __a=None ) -> Tuple: """simple docstring""" return field(default_factory=lambda: default , metadata=__a ) @dataclass class _SCREAMING_SNAKE_CASE : '''simple docstring''' lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 @dataclass class _SCREAMING_SNAKE_CASE : '''simple docstring''' lowercase_ = 42 lowercase_ = field(default="toto" , metadata={"help": "help message"} ) @dataclass class _SCREAMING_SNAKE_CASE : '''simple docstring''' lowercase_ = False lowercase_ = True lowercase_ = None class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = "titi" lowercase_ = "toto" class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = "titi" lowercase_ = "toto" lowercase_ = 42 @dataclass class _SCREAMING_SNAKE_CASE : '''simple docstring''' lowercase_ = "toto" def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Union[str, Any]: '''simple docstring''' lowerCamelCase__: List[str] =BasicEnum(self.foo) @dataclass class _SCREAMING_SNAKE_CASE : '''simple docstring''' lowercase_ = "toto" def SCREAMING_SNAKE_CASE_ (self : str) ->Tuple: '''simple docstring''' lowerCamelCase__: Tuple =MixedTypeEnum(self.foo) @dataclass class _SCREAMING_SNAKE_CASE : '''simple docstring''' lowercase_ = None lowercase_ = field(default=__SCREAMING_SNAKE_CASE , metadata={"help": "help message"} ) lowercase_ = None lowercase_ = list_field(default=[] ) lowercase_ = list_field(default=[] ) @dataclass class _SCREAMING_SNAKE_CASE : '''simple docstring''' lowercase_ = list_field(default=[] ) lowercase_ = list_field(default=[1, 2, 3] ) lowercase_ = list_field(default=["Hallo", "Bonjour", "Hello"] ) lowercase_ = list_field(default=[0.1, 0.2, 0.3] ) @dataclass class _SCREAMING_SNAKE_CASE : '''simple docstring''' lowercase_ = field() lowercase_ = field() lowercase_ = field() def SCREAMING_SNAKE_CASE_ (self : int) ->Tuple: '''simple docstring''' lowerCamelCase__: str =BasicEnum(self.required_enum) @dataclass class _SCREAMING_SNAKE_CASE : '''simple docstring''' lowercase_ = 42 lowercase_ = field() lowercase_ = None lowercase_ = field(default="toto" , metadata={"help": "help message"} ) lowercase_ = list_field(default=["Hallo", "Bonjour", "Hello"] ) if is_python_no_less_than_3_10: @dataclass class _SCREAMING_SNAKE_CASE : '''simple docstring''' lowercase_ = False lowercase_ = True lowercase_ = None @dataclass class _SCREAMING_SNAKE_CASE : '''simple docstring''' lowercase_ = None lowercase_ = field(default=__SCREAMING_SNAKE_CASE , metadata={"help": "help message"} ) lowercase_ = None lowercase_ = list_field(default=[] ) lowercase_ = list_field(default=[] ) class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ (self : str , UpperCAmelCase_ : argparse.ArgumentParser , UpperCAmelCase_ : argparse.ArgumentParser) ->Union[str, Any]: '''simple docstring''' self.assertEqual(len(a._actions) , len(b._actions)) for x, y in zip(a._actions , b._actions): lowerCamelCase__: Any ={k: v for k, v in vars(UpperCAmelCase_).items() if k != "container"} lowerCamelCase__: Optional[Any] ={k: v for k, v in vars(UpperCAmelCase_).items() if k != "container"} # Choices with mixed type have custom function as "type" # So we need to compare results directly for equality if xx.get("choices" , UpperCAmelCase_) and yy.get("choices" , UpperCAmelCase_): for expected_choice in yy["choices"] + xx["choices"]: self.assertEqual(xx["type"](UpperCAmelCase_) , yy["type"](UpperCAmelCase_)) del xx["type"], yy["type"] self.assertEqual(UpperCAmelCase_ , UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Any) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Optional[int] =HfArgumentParser(UpperCAmelCase_) lowerCamelCase__: Dict =argparse.ArgumentParser() expected.add_argument("--foo" , type=UpperCAmelCase_ , required=UpperCAmelCase_) expected.add_argument("--bar" , type=UpperCAmelCase_ , required=UpperCAmelCase_) expected.add_argument("--baz" , type=UpperCAmelCase_ , required=UpperCAmelCase_) expected.add_argument("--flag" , type=UpperCAmelCase_ , default=UpperCAmelCase_ , const=UpperCAmelCase_ , nargs="?") self.argparsersEqual(UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: Optional[Any] =["--foo", "1", "--baz", "quux", "--bar", "0.5"] ((lowerCamelCase__) , ): str =parser.parse_args_into_dataclasses(UpperCAmelCase_ , look_for_args_file=UpperCAmelCase_) self.assertFalse(example.flag) def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->Dict: '''simple docstring''' lowerCamelCase__: Union[str, Any] =HfArgumentParser(UpperCAmelCase_) lowerCamelCase__: Tuple =argparse.ArgumentParser() expected.add_argument("--foo" , default=42 , type=UpperCAmelCase_) expected.add_argument("--baz" , default="toto" , type=UpperCAmelCase_ , help="help message") self.argparsersEqual(UpperCAmelCase_ , UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->Dict: '''simple docstring''' lowerCamelCase__: List[str] =argparse.ArgumentParser() expected.add_argument("--foo" , type=UpperCAmelCase_ , default=UpperCAmelCase_ , const=UpperCAmelCase_ , nargs="?") expected.add_argument("--baz" , type=UpperCAmelCase_ , default=UpperCAmelCase_ , const=UpperCAmelCase_ , nargs="?") # A boolean no_* argument always has to come after its "default: True" regular counter-part # and its default must be set to False expected.add_argument("--no_baz" , action="store_false" , default=UpperCAmelCase_ , dest="baz") expected.add_argument("--opt" , type=UpperCAmelCase_ , default=UpperCAmelCase_) lowerCamelCase__: Tuple =[WithDefaultBoolExample] if is_python_no_less_than_3_10: dataclass_types.append(UpperCAmelCase_) for dataclass_type in dataclass_types: lowerCamelCase__: int =HfArgumentParser(UpperCAmelCase_) self.argparsersEqual(UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: Any =parser.parse_args([]) self.assertEqual(UpperCAmelCase_ , Namespace(foo=UpperCAmelCase_ , baz=UpperCAmelCase_ , opt=UpperCAmelCase_)) lowerCamelCase__: Optional[Any] =parser.parse_args(["--foo", "--no_baz"]) self.assertEqual(UpperCAmelCase_ , Namespace(foo=UpperCAmelCase_ , baz=UpperCAmelCase_ , opt=UpperCAmelCase_)) lowerCamelCase__: Any =parser.parse_args(["--foo", "--baz"]) self.assertEqual(UpperCAmelCase_ , Namespace(foo=UpperCAmelCase_ , baz=UpperCAmelCase_ , opt=UpperCAmelCase_)) lowerCamelCase__: Any =parser.parse_args(["--foo", "True", "--baz", "True", "--opt", "True"]) self.assertEqual(UpperCAmelCase_ , Namespace(foo=UpperCAmelCase_ , baz=UpperCAmelCase_ , opt=UpperCAmelCase_)) lowerCamelCase__: str =parser.parse_args(["--foo", "False", "--baz", "False", "--opt", "False"]) self.assertEqual(UpperCAmelCase_ , Namespace(foo=UpperCAmelCase_ , baz=UpperCAmelCase_ , opt=UpperCAmelCase_)) def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Any: '''simple docstring''' lowerCamelCase__: str =HfArgumentParser(UpperCAmelCase_) lowerCamelCase__: str =argparse.ArgumentParser() expected.add_argument( "--foo" , default="toto" , choices=["titi", "toto", 42] , type=make_choice_type_function(["titi", "toto", 42]) , ) self.argparsersEqual(UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: str =parser.parse_args([]) self.assertEqual(args.foo , "toto") lowerCamelCase__: Union[str, Any] =parser.parse_args_into_dataclasses([])[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.toto) lowerCamelCase__: int =parser.parse_args(["--foo", "titi"]) self.assertEqual(args.foo , "titi") lowerCamelCase__: List[str] =parser.parse_args_into_dataclasses(["--foo", "titi"])[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.titi) lowerCamelCase__: Optional[Any] =parser.parse_args(["--foo", "42"]) self.assertEqual(args.foo , 42) lowerCamelCase__: Optional[Any] =parser.parse_args_into_dataclasses(["--foo", "42"])[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.fourtytwo) def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->str: '''simple docstring''' @dataclass class _SCREAMING_SNAKE_CASE : '''simple docstring''' lowercase_ = "toto" lowerCamelCase__: Tuple =HfArgumentParser(UpperCAmelCase_) lowerCamelCase__: Dict =argparse.ArgumentParser() expected.add_argument( "--foo" , default="toto" , choices=("titi", "toto", 42) , type=make_choice_type_function(["titi", "toto", 42]) , ) self.argparsersEqual(UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: int =parser.parse_args([]) self.assertEqual(args.foo , "toto") lowerCamelCase__: str =parser.parse_args(["--foo", "titi"]) self.assertEqual(args.foo , "titi") lowerCamelCase__: int =parser.parse_args(["--foo", "42"]) self.assertEqual(args.foo , 42) def SCREAMING_SNAKE_CASE_ (self : int) ->Optional[Any]: '''simple docstring''' lowerCamelCase__: str =HfArgumentParser(UpperCAmelCase_) lowerCamelCase__: List[Any] =argparse.ArgumentParser() expected.add_argument("--foo_int" , nargs="+" , default=[] , type=UpperCAmelCase_) expected.add_argument("--bar_int" , nargs="+" , default=[1, 2, 3] , type=UpperCAmelCase_) expected.add_argument("--foo_str" , nargs="+" , default=["Hallo", "Bonjour", "Hello"] , type=UpperCAmelCase_) expected.add_argument("--foo_float" , nargs="+" , default=[0.1, 0.2, 0.3] , type=UpperCAmelCase_) self.argparsersEqual(UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: Tuple =parser.parse_args([]) self.assertEqual( UpperCAmelCase_ , Namespace(foo_int=[] , bar_int=[1, 2, 3] , foo_str=["Hallo", "Bonjour", "Hello"] , foo_float=[0.1, 0.2, 0.3]) , ) lowerCamelCase__: Optional[Any] =parser.parse_args("--foo_int 1 --bar_int 2 3 --foo_str a b c --foo_float 0.1 0.7".split()) self.assertEqual(UpperCAmelCase_ , Namespace(foo_int=[1] , bar_int=[2, 3] , foo_str=["a", "b", "c"] , foo_float=[0.1, 0.7])) def SCREAMING_SNAKE_CASE_ (self : str) ->Dict: '''simple docstring''' lowerCamelCase__: List[str] =argparse.ArgumentParser() expected.add_argument("--foo" , default=UpperCAmelCase_ , type=UpperCAmelCase_) expected.add_argument("--bar" , default=UpperCAmelCase_ , type=UpperCAmelCase_ , help="help message") expected.add_argument("--baz" , default=UpperCAmelCase_ , type=UpperCAmelCase_) expected.add_argument("--ces" , nargs="+" , default=[] , type=UpperCAmelCase_) expected.add_argument("--des" , nargs="+" , default=[] , type=UpperCAmelCase_) lowerCamelCase__: str =[OptionalExample] if is_python_no_less_than_3_10: dataclass_types.append(UpperCAmelCase_) for dataclass_type in dataclass_types: lowerCamelCase__: Optional[int] =HfArgumentParser(UpperCAmelCase_) self.argparsersEqual(UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: List[str] =parser.parse_args([]) self.assertEqual(UpperCAmelCase_ , Namespace(foo=UpperCAmelCase_ , bar=UpperCAmelCase_ , baz=UpperCAmelCase_ , ces=[] , des=[])) lowerCamelCase__: Union[str, Any] =parser.parse_args("--foo 12 --bar 3.14 --baz 42 --ces a b c --des 1 2 3".split()) self.assertEqual(UpperCAmelCase_ , Namespace(foo=12 , bar=3.14 , baz="42" , ces=["a", "b", "c"] , des=[1, 2, 3])) def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Dict: '''simple docstring''' lowerCamelCase__: Dict =HfArgumentParser(UpperCAmelCase_) lowerCamelCase__: Union[str, Any] =argparse.ArgumentParser() expected.add_argument("--required_list" , nargs="+" , type=UpperCAmelCase_ , required=UpperCAmelCase_) expected.add_argument("--required_str" , type=UpperCAmelCase_ , required=UpperCAmelCase_) expected.add_argument( "--required_enum" , type=make_choice_type_function(["titi", "toto"]) , choices=["titi", "toto"] , required=UpperCAmelCase_ , ) self.argparsersEqual(UpperCAmelCase_ , UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Dict) ->str: '''simple docstring''' lowerCamelCase__: Union[str, Any] =HfArgumentParser(UpperCAmelCase_) lowerCamelCase__: int =argparse.ArgumentParser() expected.add_argument("--foo" , type=UpperCAmelCase_ , required=UpperCAmelCase_) expected.add_argument( "--required_enum" , type=make_choice_type_function(["titi", "toto"]) , choices=["titi", "toto"] , required=UpperCAmelCase_ , ) expected.add_argument("--opt" , type=UpperCAmelCase_ , default=UpperCAmelCase_) expected.add_argument("--baz" , default="toto" , type=UpperCAmelCase_ , help="help message") expected.add_argument("--foo_str" , nargs="+" , default=["Hallo", "Bonjour", "Hello"] , type=UpperCAmelCase_) self.argparsersEqual(UpperCAmelCase_ , UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->Optional[int]: '''simple docstring''' lowerCamelCase__: List[str] =HfArgumentParser(UpperCAmelCase_) lowerCamelCase__: Tuple ={ "foo": 12, "bar": 3.14, "baz": "42", "flag": True, } lowerCamelCase__: List[Any] =parser.parse_dict(UpperCAmelCase_)[0] lowerCamelCase__: Dict =BasicExample(**UpperCAmelCase_) self.assertEqual(UpperCAmelCase_ , UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->int: '''simple docstring''' lowerCamelCase__: List[Any] =HfArgumentParser(UpperCAmelCase_) lowerCamelCase__: List[Any] ={ "foo": 12, "bar": 3.14, "baz": "42", "flag": True, "extra": 42, } self.assertRaises(UpperCAmelCase_ , parser.parse_dict , UpperCAmelCase_ , allow_extra_keys=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Any: '''simple docstring''' lowerCamelCase__: List[str] =HfArgumentParser(UpperCAmelCase_) lowerCamelCase__: List[Any] ={ "foo": 12, "bar": 3.14, "baz": "42", "flag": True, } with tempfile.TemporaryDirectory() as tmp_dir: lowerCamelCase__: List[Any] =os.path.join(UpperCAmelCase_ , "temp_json") os.mkdir(UpperCAmelCase_) with open(temp_local_path + ".json" , "w+") as f: json.dump(UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: Optional[int] =parser.parse_yaml_file(Path(temp_local_path + ".json"))[0] lowerCamelCase__: Union[str, Any] =BasicExample(**UpperCAmelCase_) self.assertEqual(UpperCAmelCase_ , UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->List[Any]: '''simple docstring''' lowerCamelCase__: int =HfArgumentParser(UpperCAmelCase_) lowerCamelCase__: List[str] ={ "foo": 12, "bar": 3.14, "baz": "42", "flag": True, } with tempfile.TemporaryDirectory() as tmp_dir: lowerCamelCase__: Optional[int] =os.path.join(UpperCAmelCase_ , "temp_yaml") os.mkdir(UpperCAmelCase_) with open(temp_local_path + ".yaml" , "w+") as f: yaml.dump(UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: List[str] =parser.parse_yaml_file(Path(temp_local_path + ".yaml"))[0] lowerCamelCase__: List[Any] =BasicExample(**UpperCAmelCase_) self.assertEqual(UpperCAmelCase_ , UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Any) ->str: '''simple docstring''' lowerCamelCase__: Optional[Any] =HfArgumentParser(UpperCAmelCase_) self.assertIsNotNone(UpperCAmelCase_)
59
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __A = { "configuration_pix2struct": [ "PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP", "Pix2StructConfig", "Pix2StructTextConfig", "Pix2StructVisionConfig", ], "processing_pix2struct": ["Pix2StructProcessor"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ["Pix2StructImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ "PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST", "Pix2StructPreTrainedModel", "Pix2StructForConditionalGeneration", "Pix2StructVisionModel", "Pix2StructTextModel", ] if TYPE_CHECKING: from .configuration_pixastruct import ( PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP, PixaStructConfig, PixaStructTextConfig, PixaStructVisionConfig, ) from .processing_pixastruct import PixaStructProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_pixastruct import PixaStructImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_pixastruct import ( PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST, PixaStructForConditionalGeneration, PixaStructPreTrainedModel, PixaStructTextModel, PixaStructVisionModel, ) else: import sys __A = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
59
1
def lowerCAmelCase_ ( __a = 10 ) -> str: """simple docstring""" if not isinstance(__a , __a ) or n < 0: raise ValueError("Invalid input" ) lowerCamelCase__: Any =10**n lowerCamelCase__: int =28433 * (pow(2 , 7830457 , __a )) + 1 return str(number % modulus ) if __name__ == "__main__": from doctest import testmod testmod() print(f'{solution(10) = }')
59
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_distilbert import DistilBertTokenizer __A = logging.get_logger(__name__) __A = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} __A = { "vocab_file": { "distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/vocab.txt", "distilbert-base-uncased-distilled-squad": ( "https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/vocab.txt" ), "distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/vocab.txt", "distilbert-base-cased-distilled-squad": ( "https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/vocab.txt" ), "distilbert-base-german-cased": "https://huggingface.co/distilbert-base-german-cased/resolve/main/vocab.txt", "distilbert-base-multilingual-cased": ( "https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/vocab.txt" ), }, "tokenizer_file": { "distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/tokenizer.json", "distilbert-base-uncased-distilled-squad": ( "https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/tokenizer.json" ), "distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/tokenizer.json", "distilbert-base-cased-distilled-squad": ( "https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/tokenizer.json" ), "distilbert-base-german-cased": ( "https://huggingface.co/distilbert-base-german-cased/resolve/main/tokenizer.json" ), "distilbert-base-multilingual-cased": ( "https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/tokenizer.json" ), }, } __A = { "distilbert-base-uncased": 512, "distilbert-base-uncased-distilled-squad": 512, "distilbert-base-cased": 512, "distilbert-base-cased-distilled-squad": 512, "distilbert-base-german-cased": 512, "distilbert-base-multilingual-cased": 512, } __A = { "distilbert-base-uncased": {"do_lower_case": True}, "distilbert-base-uncased-distilled-squad": {"do_lower_case": True}, "distilbert-base-cased": {"do_lower_case": False}, "distilbert-base-cased-distilled-squad": {"do_lower_case": False}, "distilbert-base-german-cased": {"do_lower_case": False}, "distilbert-base-multilingual-cased": {"do_lower_case": False}, } class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = VOCAB_FILES_NAMES lowercase_ = PRETRAINED_VOCAB_FILES_MAP lowercase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase_ = PRETRAINED_INIT_CONFIGURATION lowercase_ = ["input_ids", "attention_mask"] lowercase_ = DistilBertTokenizer def __init__(self : Tuple , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : int=None , UpperCAmelCase_ : Any=True , UpperCAmelCase_ : List[Any]="[UNK]" , UpperCAmelCase_ : Dict="[SEP]" , UpperCAmelCase_ : Dict="[PAD]" , UpperCAmelCase_ : Optional[int]="[CLS]" , UpperCAmelCase_ : str="[MASK]" , UpperCAmelCase_ : Any=True , UpperCAmelCase_ : List[str]=None , **UpperCAmelCase_ : List[str] , ) ->str: '''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_ , ) lowerCamelCase__: Union[str, Any] =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 ): lowerCamelCase__: List[str] =getattr(UpperCAmelCase_ , normalizer_state.pop("type")) lowerCamelCase__: Optional[int] =do_lower_case lowerCamelCase__: int =strip_accents lowerCamelCase__: Any =tokenize_chinese_chars lowerCamelCase__: Any =normalizer_class(**UpperCAmelCase_) lowerCamelCase__: str =do_lower_case def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : int , UpperCAmelCase_ : Union[str, Any]=None) ->Dict: '''simple docstring''' lowerCamelCase__: str =[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 SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None) ->List[int]: '''simple docstring''' lowerCamelCase__: str =[self.sep_token_id] lowerCamelCase__: str =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep) * [0] return len(cls + token_ids_a + sep) * [0] + len(token_ids_a + sep) * [1] def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] = None) ->Tuple[str]: '''simple docstring''' lowerCamelCase__: str =self._tokenizer.model.save(UpperCAmelCase_ , name=UpperCAmelCase_) return tuple(UpperCAmelCase_)
59
1
from collections import defaultdict from typing import Optional from ..image_utils import load_image from ..utils import ( add_end_docstrings, is_torch_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_MASK_GENERATION_MAPPING __A = logging.get_logger(__name__) @add_end_docstrings(__SCREAMING_SNAKE_CASE ) class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__(self : List[Any] , **UpperCAmelCase_ : Any) ->Any: '''simple docstring''' super().__init__(**UpperCAmelCase_) requires_backends(self , "vision") requires_backends(self , "torch") if self.framework != "pt": raise ValueError(F"""The {self.__class__} is only available in PyTorch.""") self.check_model_type(UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Tuple , **UpperCAmelCase_ : List[Any]) ->Tuple: '''simple docstring''' lowerCamelCase__: Optional[int] ={} lowerCamelCase__: Tuple ={} lowerCamelCase__: str ={} # preprocess args if "points_per_batch" in kwargs: lowerCamelCase__: Optional[Any] =kwargs["points_per_batch"] if "points_per_crop" in kwargs: lowerCamelCase__: int =kwargs["points_per_crop"] if "crops_n_layers" in kwargs: lowerCamelCase__: Any =kwargs["crops_n_layers"] if "crop_overlap_ratio" in kwargs: lowerCamelCase__: Tuple =kwargs["crop_overlap_ratio"] if "crop_n_points_downscale_factor" in kwargs: lowerCamelCase__: List[Any] =kwargs["crop_n_points_downscale_factor"] # postprocess args if "pred_iou_thresh" in kwargs: lowerCamelCase__: List[str] =kwargs["pred_iou_thresh"] if "stability_score_offset" in kwargs: lowerCamelCase__: int =kwargs["stability_score_offset"] if "mask_threshold" in kwargs: lowerCamelCase__: Optional[int] =kwargs["mask_threshold"] if "stability_score_thresh" in kwargs: lowerCamelCase__: str =kwargs["stability_score_thresh"] if "crops_nms_thresh" in kwargs: lowerCamelCase__: Any =kwargs["crops_nms_thresh"] if "output_rle_mask" in kwargs: lowerCamelCase__: List[Any] =kwargs["output_rle_mask"] if "output_bboxes_mask" in kwargs: lowerCamelCase__: List[str] =kwargs["output_bboxes_mask"] return preprocess_kwargs, forward_params, postprocess_kwargs def __call__(self : int , UpperCAmelCase_ : Dict , *UpperCAmelCase_ : Dict , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : Optional[Any]=None , **UpperCAmelCase_ : Dict) ->Optional[Any]: '''simple docstring''' return super().__call__(UpperCAmelCase_ , *UpperCAmelCase_ , num_workers=UpperCAmelCase_ , batch_size=UpperCAmelCase_ , **UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[Any]=64 , UpperCAmelCase_ : int = 0 , UpperCAmelCase_ : float = 512 / 1_500 , UpperCAmelCase_ : Optional[int] = 32 , UpperCAmelCase_ : Optional[int] = 1 , ) ->Dict: '''simple docstring''' lowerCamelCase__: Dict =load_image(UpperCAmelCase_) lowerCamelCase__: List[str] =self.image_processor.size["longest_edge"] lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Union[str, Any] =self.image_processor.generate_crop_boxes( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: str =self.image_processor(images=UpperCAmelCase_ , return_tensors="pt") with self.device_placement(): if self.framework == "pt": lowerCamelCase__: str =self.get_inference_context() with inference_context(): lowerCamelCase__: Union[str, Any] =self._ensure_tensor_on_device(UpperCAmelCase_ , device=self.device) lowerCamelCase__: Optional[Any] =self.model.get_image_embeddings(model_inputs.pop("pixel_values")) lowerCamelCase__: str =image_embeddings lowerCamelCase__: int =grid_points.shape[1] lowerCamelCase__: int =points_per_batch if points_per_batch is not None else n_points if points_per_batch <= 0: raise ValueError( "Cannot have points_per_batch<=0. Must be >=1 to returned batched outputs. " "To return all points at once, set points_per_batch to None") for i in range(0 , UpperCAmelCase_ , UpperCAmelCase_): lowerCamelCase__: int =grid_points[:, i : i + points_per_batch, :, :] lowerCamelCase__: Optional[Any] =input_labels[:, i : i + points_per_batch] lowerCamelCase__: Dict =i == n_points - points_per_batch yield { "input_points": batched_points, "input_labels": labels, "input_boxes": crop_boxes, "is_last": is_last, **model_inputs, } def SCREAMING_SNAKE_CASE_ (self : str , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Dict=0.88 , UpperCAmelCase_ : Optional[Any]=0.95 , UpperCAmelCase_ : Tuple=0 , UpperCAmelCase_ : Any=1 , ) ->Optional[Any]: '''simple docstring''' lowerCamelCase__: Any =model_inputs.pop("input_boxes") lowerCamelCase__: Dict =model_inputs.pop("is_last") lowerCamelCase__: int =model_inputs.pop("original_sizes").tolist() lowerCamelCase__: Union[str, Any] =model_inputs.pop("reshaped_input_sizes").tolist() lowerCamelCase__: Union[str, Any] =self.model(**UpperCAmelCase_) # post processing happens here in order to avoid CPU GPU copies of ALL the masks lowerCamelCase__: Optional[int] =model_outputs["pred_masks"] lowerCamelCase__: Union[str, Any] =self.image_processor.post_process_masks( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , binarize=UpperCAmelCase_) lowerCamelCase__: Optional[Any] =model_outputs["iou_scores"] lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Any =self.image_processor.filter_masks( masks[0] , iou_scores[0] , original_sizes[0] , input_boxes[0] , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , ) return { "masks": masks, "is_last": is_last, "boxes": boxes, "iou_scores": iou_scores, } def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : Any , UpperCAmelCase_ : Optional[int]=False , UpperCAmelCase_ : List[str]=False , UpperCAmelCase_ : Optional[int]=0.7 , ) ->Tuple: '''simple docstring''' lowerCamelCase__: Any =[] lowerCamelCase__: Optional[int] =[] lowerCamelCase__: List[str] =[] for model_output in model_outputs: all_scores.append(model_output.pop("iou_scores")) all_masks.extend(model_output.pop("masks")) all_boxes.append(model_output.pop("boxes")) lowerCamelCase__: str =torch.cat(UpperCAmelCase_) lowerCamelCase__: List[str] =torch.cat(UpperCAmelCase_) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Dict =self.image_processor.post_process_for_mask_generation( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: List[str] =defaultdict(UpperCAmelCase_) for output in model_outputs: for k, v in output.items(): extra[k].append(UpperCAmelCase_) lowerCamelCase__: Any ={} if output_rle_mask: lowerCamelCase__: Union[str, Any] =rle_mask if output_bboxes_mask: lowerCamelCase__: int =bounding_boxes return {"masks": output_masks, "scores": iou_scores, **optional, **extra}
59
import operator as op def lowerCAmelCase_ ( __a ) -> Tuple: """simple docstring""" lowerCamelCase__: Optional[Any] =[] lowerCamelCase__: Tuple =lambda __a , __a : int(x / y ) # noqa: E731 integer division operation lowerCamelCase__: Tuple ={ "^": op.pow, "*": op.mul, "/": div, "+": op.add, "-": op.sub, } # operators & their respective operation # print table header print("Symbol".center(8 ) , "Action".center(12 ) , "Stack" , sep=" | " ) print("-" * (30 + len(__a )) ) for x in post_fix: if x.isdigit(): # if x in digit stack.append(__a ) # append x to stack # output in tabular format print(x.rjust(8 ) , ("push(" + x + ")").ljust(12 ) , ",".join(__a ) , sep=" | " ) else: lowerCamelCase__: List[Any] =stack.pop() # pop stack # output in tabular format print("".rjust(8 ) , ("pop(" + b + ")").ljust(12 ) , ",".join(__a ) , sep=" | " ) lowerCamelCase__: Optional[Any] =stack.pop() # pop stack # output in tabular format print("".rjust(8 ) , ("pop(" + a + ")").ljust(12 ) , ",".join(__a ) , sep=" | " ) stack.append( str(opr[x](int(__a ) , int(__a ) ) ) ) # evaluate the 2 values popped from stack & push result to stack # output in tabular format print( x.rjust(8 ) , ("push(" + a + x + b + ")").ljust(12 ) , ",".join(__a ) , sep=" | " , ) return int(stack[0] ) if __name__ == "__main__": __A = input("\n\nEnter a Postfix Equation (space separated) = ").split(" ") print("\n\tResult = ", solve(Postfix))
59
1
import argparse import random import joblib import numpy as np import torch from igf.igf import ( SecondaryLearner, collect_objective_set, compute_perplexity, generate_datasets, load_gpta, recopy_gpta, set_seed, train_secondary_learner, ) from torch.utils.data import DataLoader, RandomSampler from transformers import GPTaLMHeadModel def lowerCAmelCase_ ( __a=32 , __a=10 , __a=100 , __a=1026 , __a=True , __a="data/tokenized_stories_train_wikitext103.jbl" , __a="igf_context_pairs.jbl" , ) -> str: """simple docstring""" set_seed(3 ) # generate train_data and objective_set lowerCamelCase__ , lowerCamelCase__: Tuple =generate_datasets( __a , __a , number=__a , min_len=1026 , trim=__a ) # keeps model same across runs set_seed(4 ) # model, lm_optimizer, lm_scheduler = recopy_gpt2(model, device, max_steps) # store original model weights # can we train on GPU? lowerCamelCase__: List[Any] =torch.device("cuda:0" if torch.cuda.is_available() else "cpu" ) # load pretrained model lowerCamelCase__: List[Any] =load_gpta("gpt2" ).to(__a ) print("computing perplexity on objective set" ) lowerCamelCase__: Tuple =compute_perplexity(__a , __a , __a ).item() print("perplexity on objective set:" , __a ) # collect igf pairs and save to file demo.jbl collect_objective_set(__a , __a , __a , __a , __a , __a , __a , __a ) # clean up, delete model and data we don't need anymore del model, train_data, objective_set torch.cuda.empty_cache() def lowerCAmelCase_ ( __a , __a=15 , __a=128 , __a=100 , __a="igf_model.pt" , ) -> Optional[int]: """simple docstring""" set_seed(42 ) # Load pre-trained model lowerCamelCase__: int =GPTaLMHeadModel.from_pretrained("gpt2" ) # Initialize secondary learner to use embedding weights of model lowerCamelCase__: str =SecondaryLearner(__a ) # Train secondary learner lowerCamelCase__: List[Any] =train_secondary_learner( __a , __a , max_epochs=__a , batch_size=__a , eval_freq=100 , igf_model_path=__a , ) del model, secondary_learner_train_data torch.cuda.empty_cache() return secondary_learner def lowerCAmelCase_ ( __a , __a , __a , __a=32 , __a=1000 , __a=16 , __a=1.0 , __a=recopy_gpta , __a=None , __a=10 , __a="gpt2_finetuned.pt" , ) -> Optional[int]: """simple docstring""" lowerCamelCase__: Tuple =torch.device("cuda:0" if torch.cuda.is_available() else "cpu" ) lowerCamelCase__: List[str] =RandomSampler(__a ) lowerCamelCase__: Any =DataLoader(__a , sampler=__a ) lowerCamelCase__: List[Any] =max_steps // (len(__a )) + 1 lowerCamelCase__: List[Any] =0 lowerCamelCase__: int =torch.zeros((1, context_len) , dtype=torch.long , device=__a ) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: List[Any] =recopy_model(__a , __a , __a ) model.train() if secondary_learner is not None: secondary_learner.to(__a ) secondary_learner.eval() lowerCamelCase__: int =[] lowerCamelCase__: List[Any] =0 lowerCamelCase__: Union[str, Any] =[] lowerCamelCase__: str =[] # Compute the performance of the transformer model at the beginning lowerCamelCase__: int =compute_perplexity(__a , __a , __a ) test_perps.append(__a ) print("Test perplexity, step" , __a , ":" , __a ) for epoch in range(int(__a ) ): for step, example in enumerate(__a ): torch.cuda.empty_cache() lowerCamelCase__: Union[str, Any] =random.randint(0 , example.size(2 ) - context_len - 1 ) lowerCamelCase__: Tuple =example[0, 0, start : start + context_len] lm_optimizer.zero_grad() lowerCamelCase__: List[Any] =model(__a , labels=__a ) lowerCamelCase__: Any =True if secondary_learner is not None: lowerCamelCase__: Dict =secondary_learner.forward( torch.tensor(__a , dtype=torch.long , device=__a ).unsqueeze(0 ) )[0].item() observed_qs.append(float(__a ) ) # Here we implement the simple non-constant threshold for the predicted IG(X) value # We will decay the selectivity of our secondary learner filter from # 1 standard deviation above average to 1 below average after 10 batches. if global_step == 10: lowerCamelCase__: Optional[Any] =-1 if predicted_q < threshold: lowerCamelCase__: Tuple =False # If we passed the filter, add the context to the batch! if do_backprop: contexts.append(np.array(context.cpu() ) ) lowerCamelCase__: Any =outputs[0] lm_loss.backward() examples += 1 del outputs # Once the batch is filled with enough contexts, backprop on the batch. if examples == batch_size: torch.cuda.empty_cache() lowerCamelCase__: Optional[int] =0 # Do LM backprop torch.nn.utils.clip_grad_norm_(model.parameters() , 3.0 ) lm_optimizer.step() lm_scheduler.step() # Update learning rate schedule global_step += 1 # Compute the performance of the transformer model at this batch if global_step % eval_interval == 0: lowerCamelCase__: List[str] =compute_perplexity(__a , __a , __a ) test_perps.append(__a ) print("Test perplexity, step" , __a , ":" , __a ) # Break out of the loop after 60 batches if max_steps > 0 and global_step > 60: break if max_steps > 0 and global_step > 60: break # save finetuned transformer model torch.save(model.state_dict() , __a ) torch.cuda.empty_cache() # Do some cleaning up so we can reinitialize for the next run of this function del lm_optimizer del lm_scheduler return model def lowerCAmelCase_ ( ) -> Optional[Any]: """simple docstring""" lowerCamelCase__: Any =argparse.ArgumentParser(description="Fine-tune a transformer model with IGF on a language modeling task" ) # Required parameters parser.add_argument( "--data_dir" , default=__a , type=__a , required=__a , help="The input data dir. Should contain data files for WikiText." , ) parser.add_argument( "--model_name_or_path" , default=__a , type=__a , required=__a , help="Path to pretrained model or model identifier from huggingface.co/models" , ) parser.add_argument( "--data_file" , type=__a , default=__a , help=( "A jbl file containing tokenized data which can be split as objective dataset, " "train_dataset and test_dataset." ) , ) parser.add_argument( "--igf_data_file" , type=__a , default=__a , help="A jbl file containing the context and information gain pairs to train secondary learner." , ) parser.add_argument( "--output_dir" , default=__a , type=__a , required=__a , help="The output directory where the final fine-tuned model is stored." , ) parser.add_argument( "--tokenizer_name" , default=__a , type=__a , help="Pretrained tokenizer name or path if not the same as model_name" , ) parser.add_argument("--seed" , type=__a , default=__a , help="A seed for reproducible training." ) parser.add_argument( "--context_len" , default=32 , type=__a , help=( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) , ) parser.add_argument( "--size_objective_set" , default=100 , type=__a , help="number of articles that are long enough to be used as our objective set" , ) parser.add_argument( "--eval_freq" , default=100 , type=__a , help="secondary model evaluation is triggered at eval_freq" ) parser.add_argument("--max_steps" , default=1000 , type=__a , help="To calculate training epochs" ) parser.add_argument( "--secondary_learner_batch_size" , default=128 , type=__a , help="batch size of training data for secondary learner" , ) parser.add_argument( "--batch_size" , default=16 , type=__a , help="batch size of training data of language model(gpt2) " ) parser.add_argument( "--eval_interval" , default=10 , type=__a , help=( "decay the selectivity of our secondary learner filter from" "1 standard deviation above average to 1 below average after 10 batches" ) , ) parser.add_argument( "--number" , default=100 , type=__a , help="The number of examples split to be used as objective_set/test_data" ) parser.add_argument( "--min_len" , default=1026 , type=__a , help="The minimum length of the article to be used as objective set" ) parser.add_argument( "--secondary_learner_max_epochs" , default=15 , type=__a , help="number of epochs to train secondary learner" ) parser.add_argument("--trim" , default=__a , type=__a , help="truncate the example if it exceeds context length" ) parser.add_argument( "--threshold" , default=1.0 , type=__a , help=( "The threshold value used by secondary learner to filter the train_data and allow only" " informative data as input to the model" ) , ) parser.add_argument("--finetuned_model_name" , default="gpt2_finetuned.pt" , type=__a , help="finetuned_model_name" ) parser.add_argument( "--recopy_model" , default=__a , type=__a , help="Reset the model to the original pretrained GPT-2 weights after each iteration" , ) # function calls # Collecting *n* pairs of context and information gain(X, IG(X)) for training the secondary learner generate_n_pairs( context_len=32 , max_steps=10 , size_objective_set=100 , min_len=1026 , trim=__a , data_file="data/tokenized_stories_train_wikitext103.jbl" , igf_data_file="igf_context_pairs.jbl" , ) # Load train data for secondary learner lowerCamelCase__: List[str] =joblib.load("data/IGF_values.jbl" ) # Train secondary learner lowerCamelCase__: Optional[Any] =training_secondary_learner( __a , secondary_learner_max_epochs=15 , secondary_learner_batch_size=128 , eval_freq=100 , igf_model_path="igf_model.pt" , ) # load pretrained gpt2 model lowerCamelCase__: Tuple =GPTaLMHeadModel.from_pretrained("gpt2" ) set_seed(42 ) # Generate train and test data to train and evaluate gpt2 model lowerCamelCase__ , lowerCamelCase__: Optional[Any] =generate_datasets( context_len=32 , file="data/tokenized_stories_train_wikitext103.jbl" , number=100 , min_len=1026 , trim=__a ) # fine-tuning of the gpt2 model using igf (Information Gain Filtration) finetune( __a , __a , __a , context_len=32 , max_steps=1000 , batch_size=16 , threshold=1.0 , recopy_model=__a , secondary_learner=__a , eval_interval=10 , finetuned_model_name="gpt2_finetuned.pt" , ) if __name__ == "__main__": main()
59
from collections import defaultdict from typing import Optional from ..image_utils import load_image from ..utils import ( add_end_docstrings, is_torch_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_MASK_GENERATION_MAPPING __A = logging.get_logger(__name__) @add_end_docstrings(__SCREAMING_SNAKE_CASE ) class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__(self : List[Any] , **UpperCAmelCase_ : Any) ->Any: '''simple docstring''' super().__init__(**UpperCAmelCase_) requires_backends(self , "vision") requires_backends(self , "torch") if self.framework != "pt": raise ValueError(F"""The {self.__class__} is only available in PyTorch.""") self.check_model_type(UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Tuple , **UpperCAmelCase_ : List[Any]) ->Tuple: '''simple docstring''' lowerCamelCase__: Optional[int] ={} lowerCamelCase__: Tuple ={} lowerCamelCase__: str ={} # preprocess args if "points_per_batch" in kwargs: lowerCamelCase__: Optional[Any] =kwargs["points_per_batch"] if "points_per_crop" in kwargs: lowerCamelCase__: int =kwargs["points_per_crop"] if "crops_n_layers" in kwargs: lowerCamelCase__: Any =kwargs["crops_n_layers"] if "crop_overlap_ratio" in kwargs: lowerCamelCase__: Tuple =kwargs["crop_overlap_ratio"] if "crop_n_points_downscale_factor" in kwargs: lowerCamelCase__: List[Any] =kwargs["crop_n_points_downscale_factor"] # postprocess args if "pred_iou_thresh" in kwargs: lowerCamelCase__: List[str] =kwargs["pred_iou_thresh"] if "stability_score_offset" in kwargs: lowerCamelCase__: int =kwargs["stability_score_offset"] if "mask_threshold" in kwargs: lowerCamelCase__: Optional[int] =kwargs["mask_threshold"] if "stability_score_thresh" in kwargs: lowerCamelCase__: str =kwargs["stability_score_thresh"] if "crops_nms_thresh" in kwargs: lowerCamelCase__: Any =kwargs["crops_nms_thresh"] if "output_rle_mask" in kwargs: lowerCamelCase__: List[Any] =kwargs["output_rle_mask"] if "output_bboxes_mask" in kwargs: lowerCamelCase__: List[str] =kwargs["output_bboxes_mask"] return preprocess_kwargs, forward_params, postprocess_kwargs def __call__(self : int , UpperCAmelCase_ : Dict , *UpperCAmelCase_ : Dict , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : Optional[Any]=None , **UpperCAmelCase_ : Dict) ->Optional[Any]: '''simple docstring''' return super().__call__(UpperCAmelCase_ , *UpperCAmelCase_ , num_workers=UpperCAmelCase_ , batch_size=UpperCAmelCase_ , **UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[Any]=64 , UpperCAmelCase_ : int = 0 , UpperCAmelCase_ : float = 512 / 1_500 , UpperCAmelCase_ : Optional[int] = 32 , UpperCAmelCase_ : Optional[int] = 1 , ) ->Dict: '''simple docstring''' lowerCamelCase__: Dict =load_image(UpperCAmelCase_) lowerCamelCase__: List[str] =self.image_processor.size["longest_edge"] lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Union[str, Any] =self.image_processor.generate_crop_boxes( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: str =self.image_processor(images=UpperCAmelCase_ , return_tensors="pt") with self.device_placement(): if self.framework == "pt": lowerCamelCase__: str =self.get_inference_context() with inference_context(): lowerCamelCase__: Union[str, Any] =self._ensure_tensor_on_device(UpperCAmelCase_ , device=self.device) lowerCamelCase__: Optional[Any] =self.model.get_image_embeddings(model_inputs.pop("pixel_values")) lowerCamelCase__: str =image_embeddings lowerCamelCase__: int =grid_points.shape[1] lowerCamelCase__: int =points_per_batch if points_per_batch is not None else n_points if points_per_batch <= 0: raise ValueError( "Cannot have points_per_batch<=0. Must be >=1 to returned batched outputs. " "To return all points at once, set points_per_batch to None") for i in range(0 , UpperCAmelCase_ , UpperCAmelCase_): lowerCamelCase__: int =grid_points[:, i : i + points_per_batch, :, :] lowerCamelCase__: Optional[Any] =input_labels[:, i : i + points_per_batch] lowerCamelCase__: Dict =i == n_points - points_per_batch yield { "input_points": batched_points, "input_labels": labels, "input_boxes": crop_boxes, "is_last": is_last, **model_inputs, } def SCREAMING_SNAKE_CASE_ (self : str , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Dict=0.88 , UpperCAmelCase_ : Optional[Any]=0.95 , UpperCAmelCase_ : Tuple=0 , UpperCAmelCase_ : Any=1 , ) ->Optional[Any]: '''simple docstring''' lowerCamelCase__: Any =model_inputs.pop("input_boxes") lowerCamelCase__: Dict =model_inputs.pop("is_last") lowerCamelCase__: int =model_inputs.pop("original_sizes").tolist() lowerCamelCase__: Union[str, Any] =model_inputs.pop("reshaped_input_sizes").tolist() lowerCamelCase__: Union[str, Any] =self.model(**UpperCAmelCase_) # post processing happens here in order to avoid CPU GPU copies of ALL the masks lowerCamelCase__: Optional[int] =model_outputs["pred_masks"] lowerCamelCase__: Union[str, Any] =self.image_processor.post_process_masks( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , binarize=UpperCAmelCase_) lowerCamelCase__: Optional[Any] =model_outputs["iou_scores"] lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Any =self.image_processor.filter_masks( masks[0] , iou_scores[0] , original_sizes[0] , input_boxes[0] , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , ) return { "masks": masks, "is_last": is_last, "boxes": boxes, "iou_scores": iou_scores, } def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : Any , UpperCAmelCase_ : Optional[int]=False , UpperCAmelCase_ : List[str]=False , UpperCAmelCase_ : Optional[int]=0.7 , ) ->Tuple: '''simple docstring''' lowerCamelCase__: Any =[] lowerCamelCase__: Optional[int] =[] lowerCamelCase__: List[str] =[] for model_output in model_outputs: all_scores.append(model_output.pop("iou_scores")) all_masks.extend(model_output.pop("masks")) all_boxes.append(model_output.pop("boxes")) lowerCamelCase__: str =torch.cat(UpperCAmelCase_) lowerCamelCase__: List[str] =torch.cat(UpperCAmelCase_) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Dict =self.image_processor.post_process_for_mask_generation( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: List[str] =defaultdict(UpperCAmelCase_) for output in model_outputs: for k, v in output.items(): extra[k].append(UpperCAmelCase_) lowerCamelCase__: Any ={} if output_rle_mask: lowerCamelCase__: Union[str, Any] =rle_mask if output_bboxes_mask: lowerCamelCase__: int =bounding_boxes return {"masks": output_masks, "scores": iou_scores, **optional, **extra}
59
1
import copy import unittest from transformers.models.auto import get_values from transformers.testing_utils import require_torch, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_MULTIPLE_CHOICE_MAPPING, MODEL_FOR_QUESTION_ANSWERING_MAPPING, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, LayoutLMvaForQuestionAnswering, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaModel, ) from transformers.models.layoutlmva.modeling_layoutlmva import LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class _SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__(self : Tuple , UpperCAmelCase_ : Dict , UpperCAmelCase_ : List[Any]=2 , UpperCAmelCase_ : List[str]=3 , UpperCAmelCase_ : Dict=4 , UpperCAmelCase_ : Optional[Any]=2 , UpperCAmelCase_ : Union[str, Any]=7 , UpperCAmelCase_ : Any=True , UpperCAmelCase_ : Dict=True , UpperCAmelCase_ : List[Any]=True , UpperCAmelCase_ : List[Any]=True , UpperCAmelCase_ : Any=99 , UpperCAmelCase_ : Dict=36 , UpperCAmelCase_ : Any=3 , UpperCAmelCase_ : Dict=4 , UpperCAmelCase_ : Optional[int]=37 , UpperCAmelCase_ : int="gelu" , UpperCAmelCase_ : List[Any]=0.1 , UpperCAmelCase_ : Optional[Any]=0.1 , UpperCAmelCase_ : Union[str, Any]=512 , UpperCAmelCase_ : List[Any]=16 , UpperCAmelCase_ : Dict=2 , UpperCAmelCase_ : Optional[int]=0.02 , UpperCAmelCase_ : List[str]=6 , UpperCAmelCase_ : Tuple=6 , UpperCAmelCase_ : Dict=3 , UpperCAmelCase_ : Union[str, Any]=4 , UpperCAmelCase_ : Any=None , UpperCAmelCase_ : Union[str, Any]=1_000 , ) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Any =parent lowerCamelCase__: Any =batch_size lowerCamelCase__: Union[str, Any] =num_channels lowerCamelCase__: str =image_size lowerCamelCase__: Any =patch_size lowerCamelCase__: Optional[Any] =text_seq_length lowerCamelCase__: Optional[Any] =is_training lowerCamelCase__: List[str] =use_input_mask lowerCamelCase__: List[str] =use_token_type_ids lowerCamelCase__: List[Any] =use_labels lowerCamelCase__: Tuple =vocab_size lowerCamelCase__: Optional[Any] =hidden_size lowerCamelCase__: Optional[int] =num_hidden_layers lowerCamelCase__: Tuple =num_attention_heads lowerCamelCase__: List[Any] =intermediate_size lowerCamelCase__: Optional[Any] =hidden_act lowerCamelCase__: List[str] =hidden_dropout_prob lowerCamelCase__: Optional[Any] =attention_probs_dropout_prob lowerCamelCase__: Any =max_position_embeddings lowerCamelCase__: str =type_vocab_size lowerCamelCase__: str =type_sequence_label_size lowerCamelCase__: Optional[int] =initializer_range lowerCamelCase__: Union[str, Any] =coordinate_size lowerCamelCase__: Optional[Any] =shape_size lowerCamelCase__: int =num_labels lowerCamelCase__: str =num_choices lowerCamelCase__: List[Any] =scope lowerCamelCase__: List[str] =range_bbox # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token) lowerCamelCase__: List[Any] =text_seq_length lowerCamelCase__: Any =(image_size // patch_size) ** 2 + 1 lowerCamelCase__: int =self.text_seq_length + self.image_seq_length def SCREAMING_SNAKE_CASE_ (self : Tuple) ->List[str]: '''simple docstring''' lowerCamelCase__: Optional[Any] =ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size) lowerCamelCase__: Any =ids_tensor([self.batch_size, self.text_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]: lowerCamelCase__: Optional[int] =bbox[i, j, 3] lowerCamelCase__: int =bbox[i, j, 1] lowerCamelCase__: Tuple =t if bbox[i, j, 2] < bbox[i, j, 0]: lowerCamelCase__: Tuple =bbox[i, j, 2] lowerCamelCase__: List[str] =bbox[i, j, 0] lowerCamelCase__: Any =t lowerCamelCase__: List[Any] =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) lowerCamelCase__: Optional[int] =None if self.use_input_mask: lowerCamelCase__: List[str] =random_attention_mask([self.batch_size, self.text_seq_length]) lowerCamelCase__: Any =None if self.use_token_type_ids: lowerCamelCase__: List[Any] =ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size) lowerCamelCase__: List[Any] =None lowerCamelCase__: List[str] =None if self.use_labels: lowerCamelCase__: List[str] =ids_tensor([self.batch_size] , self.type_sequence_label_size) lowerCamelCase__: Optional[Any] =ids_tensor([self.batch_size, self.text_seq_length] , self.num_labels) lowerCamelCase__: List[Any] =LayoutLMvaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , coordinate_size=self.coordinate_size , shape_size=self.shape_size , input_size=self.image_size , patch_size=self.patch_size , ) return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : int , UpperCAmelCase_ : Dict , UpperCAmelCase_ : int , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[Any]) ->List[str]: '''simple docstring''' lowerCamelCase__: Dict =LayoutLMvaModel(config=UpperCAmelCase_) model.to(UpperCAmelCase_) model.eval() # text + image lowerCamelCase__: Optional[int] =model(UpperCAmelCase_ , pixel_values=UpperCAmelCase_) lowerCamelCase__: Optional[Any] =model( UpperCAmelCase_ , bbox=UpperCAmelCase_ , pixel_values=UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_) lowerCamelCase__: Union[str, Any] =model(UpperCAmelCase_ , bbox=UpperCAmelCase_ , pixel_values=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_) lowerCamelCase__: Union[str, Any] =model(UpperCAmelCase_ , bbox=UpperCAmelCase_ , pixel_values=UpperCAmelCase_) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) # text only lowerCamelCase__: List[str] =model(UpperCAmelCase_) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size)) # image only lowerCamelCase__: List[str] =model(pixel_values=UpperCAmelCase_) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size)) def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : int , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : int , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : str) ->List[str]: '''simple docstring''' lowerCamelCase__: Union[str, Any] =self.num_labels lowerCamelCase__: Optional[int] =LayoutLMvaForSequenceClassification(UpperCAmelCase_) model.to(UpperCAmelCase_) model.eval() lowerCamelCase__: List[Any] =model( UpperCAmelCase_ , bbox=UpperCAmelCase_ , pixel_values=UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , labels=UpperCAmelCase_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : int , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : int) ->Optional[Any]: '''simple docstring''' lowerCamelCase__: Optional[Any] =self.num_labels lowerCamelCase__: List[str] =LayoutLMvaForTokenClassification(config=UpperCAmelCase_) model.to(UpperCAmelCase_) model.eval() lowerCamelCase__: int =model( UpperCAmelCase_ , bbox=UpperCAmelCase_ , pixel_values=UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , labels=UpperCAmelCase_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels)) def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : int , UpperCAmelCase_ : Dict , UpperCAmelCase_ : str , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : List[Any]) ->Tuple: '''simple docstring''' lowerCamelCase__: Tuple =LayoutLMvaForQuestionAnswering(config=UpperCAmelCase_) model.to(UpperCAmelCase_) model.eval() lowerCamelCase__: Tuple =model( UpperCAmelCase_ , bbox=UpperCAmelCase_ , pixel_values=UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , start_positions=UpperCAmelCase_ , end_positions=UpperCAmelCase_ , ) 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 : Tuple) ->List[Any]: '''simple docstring''' lowerCamelCase__: List[Any] =self.prepare_config_and_inputs() ( ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ): Tuple =config_and_inputs lowerCamelCase__: List[str] ={ "input_ids": input_ids, "bbox": bbox, "pixel_values": pixel_values, "token_type_ids": token_type_ids, "attention_mask": input_mask, } return config, inputs_dict @require_torch class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowercase_ = False lowercase_ = False lowercase_ = False lowercase_ = ( ( LayoutLMvaModel, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaForQuestionAnswering, ) if is_torch_available() else () ) lowercase_ = ( {"document-question-answering": LayoutLMvaForQuestionAnswering, "feature-extraction": LayoutLMvaModel} if is_torch_available() else {} ) def SCREAMING_SNAKE_CASE_ (self : Dict , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Union[str, Any]) ->Tuple: '''simple docstring''' return True def SCREAMING_SNAKE_CASE_ (self : Union[str, Any]) ->Dict: '''simple docstring''' lowerCamelCase__: List[Any] =LayoutLMvaModelTester(self) lowerCamelCase__: Any =ConfigTester(self , config_class=UpperCAmelCase_ , hidden_size=37) def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Dict=False) ->Dict: '''simple docstring''' lowerCamelCase__: Tuple =copy.deepcopy(UpperCAmelCase_) if model_class in get_values(UpperCAmelCase_): lowerCamelCase__: Dict ={ k: v.unsqueeze(1).expand(-1 , self.model_tester.num_choices , -1).contiguous() if isinstance(UpperCAmelCase_ , torch.Tensor) and v.ndim > 1 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(UpperCAmelCase_): lowerCamelCase__: List[str] =torch.ones(self.model_tester.batch_size , dtype=torch.long , device=UpperCAmelCase_) elif model_class in get_values(UpperCAmelCase_): lowerCamelCase__: Tuple =torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=UpperCAmelCase_) lowerCamelCase__: List[str] =torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=UpperCAmelCase_) elif model_class in [ *get_values(UpperCAmelCase_), ]: lowerCamelCase__: int =torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=UpperCAmelCase_) elif model_class in [ *get_values(UpperCAmelCase_), ]: lowerCamelCase__: Optional[int] =torch.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=torch.long , device=UpperCAmelCase_ , ) return inputs_dict def SCREAMING_SNAKE_CASE_ (self : Dict) ->Dict: '''simple docstring''' self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE_ (self : List[str]) ->Dict: '''simple docstring''' lowerCamelCase__: List[Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[str]) ->Dict: '''simple docstring''' lowerCamelCase__: Union[str, Any] =self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: lowerCamelCase__: int =type self.model_tester.create_and_check_model(*UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[str]) ->Union[str, Any]: '''simple docstring''' lowerCamelCase__: Dict =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[str]) ->Tuple: '''simple docstring''' lowerCamelCase__: Optional[Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->List[Any]: '''simple docstring''' lowerCamelCase__: Any =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*UpperCAmelCase_) @slow def SCREAMING_SNAKE_CASE_ (self : int) ->str: '''simple docstring''' for model_name in LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCamelCase__: List[str] =LayoutLMvaModel.from_pretrained(UpperCAmelCase_) self.assertIsNotNone(UpperCAmelCase_) def lowerCAmelCase_ ( ) -> Tuple: """simple docstring""" lowerCamelCase__: str =Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @cached_property def SCREAMING_SNAKE_CASE_ (self : Union[str, Any]) ->Union[str, Any]: '''simple docstring''' return LayoutLMvaImageProcessor(apply_ocr=UpperCAmelCase_) if is_vision_available() else None @slow def SCREAMING_SNAKE_CASE_ (self : Dict) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Any =LayoutLMvaModel.from_pretrained("microsoft/layoutlmv3-base").to(UpperCAmelCase_) lowerCamelCase__: Optional[int] =self.default_image_processor lowerCamelCase__: Union[str, Any] =prepare_img() lowerCamelCase__: str =image_processor(images=UpperCAmelCase_ , return_tensors="pt").pixel_values.to(UpperCAmelCase_) lowerCamelCase__: Optional[Any] =torch.tensor([[1, 2]]) lowerCamelCase__: Optional[Any] =torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]]).unsqueeze(0) # forward pass lowerCamelCase__: List[Any] =model( input_ids=input_ids.to(UpperCAmelCase_) , bbox=bbox.to(UpperCAmelCase_) , pixel_values=pixel_values.to(UpperCAmelCase_) , ) # verify the logits lowerCamelCase__: List[Any] =torch.Size((1, 199, 768)) self.assertEqual(outputs.last_hidden_state.shape , UpperCAmelCase_) lowerCamelCase__: List[str] =torch.tensor( [[-0.0529, 0.3618, 0.1632], [-0.1587, -0.1667, -0.0400], [-0.1557, -0.1671, -0.0505]]).to(UpperCAmelCase_) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3] , UpperCAmelCase_ , atol=1E-4))
59
from transformers import BertTokenizerFast from .custom_tokenization import CustomTokenizer class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = CustomTokenizer pass
59
1
import math import numpy as np import qiskit from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute def lowerCAmelCase_ ( __a = 3 ) -> qiskit.result.counts.Counts: """simple docstring""" if isinstance(__a , __a ): raise TypeError("number of qubits must be a integer." ) if number_of_qubits <= 0: raise ValueError("number of qubits must be > 0." ) if math.floor(__a ) != number_of_qubits: raise ValueError("number of qubits must be exact integer." ) if number_of_qubits > 10: raise ValueError("number of qubits too large to simulate(>10)." ) lowerCamelCase__: Optional[int] =QuantumRegister(__a , "qr" ) lowerCamelCase__: Tuple =ClassicalRegister(__a , "cr" ) lowerCamelCase__: Union[str, Any] =QuantumCircuit(__a , __a ) lowerCamelCase__: Optional[int] =number_of_qubits for i in range(__a ): quantum_circuit.h(number_of_qubits - i - 1 ) counter -= 1 for j in range(__a ): quantum_circuit.cp(np.pi / 2 ** (counter - j) , __a , __a ) for k in range(number_of_qubits // 2 ): quantum_circuit.swap(__a , number_of_qubits - k - 1 ) # measure all the qubits quantum_circuit.measure(__a , __a ) # simulate with 10000 shots lowerCamelCase__: List[str] =Aer.get_backend("qasm_simulator" ) lowerCamelCase__: Tuple =execute(__a , __a , shots=10000 ) return job.result().get_counts(__a ) if __name__ == "__main__": print( f'Total count for quantum fourier transform state is: \ {quantum_fourier_transform(3)}' )
59
import inspect import os import unittest import torch import accelerate from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_multi_gpu from accelerate.utils import patch_environment class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ (self : Dict) ->Optional[int]: '''simple docstring''' lowerCamelCase__: List[Any] =inspect.getfile(accelerate.test_utils) lowerCamelCase__: List[Any] =os.path.sep.join(mod_file.split(os.path.sep)[:-1] + ["scripts", "test_script.py"]) lowerCamelCase__: Any =os.path.sep.join( mod_file.split(os.path.sep)[:-1] + ["scripts", "test_distributed_data_loop.py"]) lowerCamelCase__: Tuple =os.path.sep.join(mod_file.split(os.path.sep)[:-1] + ["scripts", "test_ops.py"]) @require_multi_gpu def SCREAMING_SNAKE_CASE_ (self : str) ->str: '''simple docstring''' print(F"""Found {torch.cuda.device_count()} devices.""") lowerCamelCase__: Union[str, Any] =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", self.test_file_path] with patch_environment(omp_num_threads=1): execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy()) @require_multi_gpu def SCREAMING_SNAKE_CASE_ (self : List[str]) ->List[Any]: '''simple docstring''' print(F"""Found {torch.cuda.device_count()} devices.""") lowerCamelCase__: Dict =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", self.operation_file_path] print(F"""Command: {cmd}""") with patch_environment(omp_num_threads=1): execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy()) @require_multi_gpu def SCREAMING_SNAKE_CASE_ (self : Dict) ->Tuple: '''simple docstring''' lowerCamelCase__: int =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", inspect.getfile(self.__class__)] with patch_environment(omp_num_threads=1): execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy()) @require_multi_gpu def SCREAMING_SNAKE_CASE_ (self : str) ->List[Any]: '''simple docstring''' print(F"""Found {torch.cuda.device_count()} devices, using 2 devices only""") lowerCamelCase__: int =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", self.data_loop_file_path] with patch_environment(omp_num_threads=1 , cuda_visible_devices="0,1"): execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy()) if __name__ == "__main__": __A = Accelerator() __A = (accelerator.state.process_index + 2, 10) __A = torch.randint(0, 10, shape).to(accelerator.device) __A = "" __A = accelerator.pad_across_processes(tensor) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += f"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." if not torch.equal(tensora[: accelerator.state.process_index + 2], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[accelerator.state.process_index + 2 :] == 0): error_msg += "Padding was not done with the right value (0)." __A = accelerator.pad_across_processes(tensor, pad_first=True) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += f"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." __A = accelerator.state.num_processes - accelerator.state.process_index - 1 if not torch.equal(tensora[index:], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[:index] == 0): error_msg += "Padding was not done with the right value (0)." # 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)
59
1
def lowerCAmelCase_ ( __a = 600851475143 ) -> int: """simple docstring""" try: lowerCamelCase__: Union[str, Any] =int(__a ) except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int." ) if n <= 0: raise ValueError("Parameter n must be greater than or equal to one." ) lowerCamelCase__: Optional[Any] =1 lowerCamelCase__: List[Any] =2 while i * i <= n: while n % i == 0: lowerCamelCase__: List[Any] =i n //= i i += 1 if n > 1: lowerCamelCase__: Optional[Any] =n return int(__a ) if __name__ == "__main__": print(f'{solution() = }')
59
from typing import List, Optional, Tuple, Union import PIL import torch from torchvision import transforms from diffusers.pipeline_utils import DiffusionPipeline, ImagePipelineOutput from diffusers.schedulers import DDIMScheduler from diffusers.utils import randn_tensor __A = transforms.Compose( [ transforms.Resize((256, 256)), transforms.ToTensor(), transforms.Normalize([0.5], [0.5]), ] ) def lowerCAmelCase_ ( __a ) -> str: """simple docstring""" if isinstance(__a , torch.Tensor ): return image elif isinstance(__a , PIL.Image.Image ): lowerCamelCase__: Any =[image] lowerCamelCase__: Optional[Any] =[trans(img.convert("RGB" ) ) for img in image] lowerCamelCase__: Dict =torch.stack(__a ) return image class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__(self : Any , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Tuple) ->int: '''simple docstring''' super().__init__() # make sure scheduler can always be converted to DDIM lowerCamelCase__: Tuple =DDIMScheduler.from_config(scheduler.config) self.register_modules(unet=UpperCAmelCase_ , scheduler=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Union[str, Any]) ->Dict: '''simple docstring''' if strength < 0 or strength > 1: raise ValueError(F"""The value of strength should in [0.0, 1.0] but is {strength}""") def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Tuple) ->Tuple: '''simple docstring''' lowerCamelCase__: int =min(int(num_inference_steps * strength) , UpperCAmelCase_) lowerCamelCase__: str =max(num_inference_steps - init_timestep , 0) lowerCamelCase__: int =self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[int]=None) ->Optional[int]: '''simple docstring''' if not isinstance(UpperCAmelCase_ , (torch.Tensor, PIL.Image.Image, list)): raise ValueError( F"""`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(UpperCAmelCase_)}""") lowerCamelCase__: Optional[int] =image.to(device=UpperCAmelCase_ , dtype=UpperCAmelCase_) if isinstance(UpperCAmelCase_ , UpperCAmelCase_) and len(UpperCAmelCase_) != batch_size: raise ValueError( F"""You have passed a list of generators of length {len(UpperCAmelCase_)}, but requested an effective batch""" F""" size of {batch_size}. Make sure the batch size matches the length of the generators.""") lowerCamelCase__: Dict =init_latents.shape lowerCamelCase__: int =randn_tensor(UpperCAmelCase_ , generator=UpperCAmelCase_ , device=UpperCAmelCase_ , dtype=UpperCAmelCase_) # get latents print("add noise to latents at timestep" , UpperCAmelCase_) lowerCamelCase__: Union[str, Any] =self.scheduler.add_noise(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: int =init_latents return latents @torch.no_grad() def __call__(self : Tuple , UpperCAmelCase_ : Union[torch.FloatTensor, PIL.Image.Image] = None , UpperCAmelCase_ : float = 0.8 , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , UpperCAmelCase_ : float = 0.0 , UpperCAmelCase_ : int = 50 , UpperCAmelCase_ : Optional[bool] = None , UpperCAmelCase_ : Optional[str] = "pil" , UpperCAmelCase_ : bool = True , ) ->Union[ImagePipelineOutput, Tuple]: '''simple docstring''' self.check_inputs(UpperCAmelCase_) # 2. Preprocess image lowerCamelCase__: Dict =preprocess(UpperCAmelCase_) # 3. set timesteps self.scheduler.set_timesteps(UpperCAmelCase_ , device=self.device) lowerCamelCase__ , lowerCamelCase__: str =self.get_timesteps(UpperCAmelCase_ , UpperCAmelCase_ , self.device) lowerCamelCase__: Optional[int] =timesteps[:1].repeat(UpperCAmelCase_) # 4. Prepare latent variables lowerCamelCase__: int =self.prepare_latents(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , self.unet.dtype , self.device , UpperCAmelCase_) lowerCamelCase__: Tuple =latents # 5. Denoising loop for t in self.progress_bar(UpperCAmelCase_): # 1. predict noise model_output lowerCamelCase__: Dict =self.unet(UpperCAmelCase_ , UpperCAmelCase_).sample # 2. predict previous mean of image x_t-1 and add variance depending on eta # eta corresponds to η in paper and should be between [0, 1] # do x_t -> x_t-1 lowerCamelCase__: Optional[int] =self.scheduler.step( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , eta=UpperCAmelCase_ , use_clipped_model_output=UpperCAmelCase_ , generator=UpperCAmelCase_ , ).prev_sample lowerCamelCase__: str =(image / 2 + 0.5).clamp(0 , 1) lowerCamelCase__: Optional[Any] =image.cpu().permute(0 , 2 , 3 , 1).numpy() if output_type == "pil": lowerCamelCase__: Dict =self.numpy_to_pil(UpperCAmelCase_) if not return_dict: return (image, latent_timestep.item()) return ImagePipelineOutput(images=UpperCAmelCase_)
59
1
from typing import Any, Callable, Dict, List, Optional, Union import torch from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker __A = "CompVis/stable-diffusion-v1-1" __A = "CompVis/stable-diffusion-v1-2" __A = "CompVis/stable-diffusion-v1-3" __A = "CompVis/stable-diffusion-v1-4" class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__(self : Tuple , UpperCAmelCase_ : AutoencoderKL , UpperCAmelCase_ : CLIPTextModel , UpperCAmelCase_ : CLIPTokenizer , UpperCAmelCase_ : UNetaDConditionModel , UpperCAmelCase_ : Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] , UpperCAmelCase_ : StableDiffusionSafetyChecker , UpperCAmelCase_ : CLIPImageProcessor , UpperCAmelCase_ : bool = True , ) ->Union[str, Any]: '''simple docstring''' super()._init_() lowerCamelCase__: Tuple =StableDiffusionPipeline.from_pretrained(UpperCAmelCase_) lowerCamelCase__: List[str] =StableDiffusionPipeline.from_pretrained(UpperCAmelCase_) lowerCamelCase__: Optional[Any] =StableDiffusionPipeline.from_pretrained(UpperCAmelCase_) lowerCamelCase__: str =StableDiffusionPipeline( vae=UpperCAmelCase_ , text_encoder=UpperCAmelCase_ , tokenizer=UpperCAmelCase_ , unet=UpperCAmelCase_ , scheduler=UpperCAmelCase_ , safety_checker=UpperCAmelCase_ , feature_extractor=UpperCAmelCase_ , requires_safety_checker=UpperCAmelCase_ , ) self.register_modules(pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea) @property def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Dict[str, Any]: '''simple docstring''' return {k: getattr(self , UpperCAmelCase_) for k in self.config.keys() if not k.startswith("_")} def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : Optional[Union[str, int]] = "auto") ->Tuple: '''simple docstring''' if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory lowerCamelCase__: Tuple =self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[str]) ->Optional[Any]: '''simple docstring''' self.enable_attention_slicing(UpperCAmelCase_) @torch.no_grad() def SCREAMING_SNAKE_CASE_ (self : Dict , UpperCAmelCase_ : Union[str, List[str]] , UpperCAmelCase_ : int = 512 , UpperCAmelCase_ : int = 512 , UpperCAmelCase_ : int = 50 , UpperCAmelCase_ : float = 7.5 , UpperCAmelCase_ : Optional[Union[str, List[str]]] = None , UpperCAmelCase_ : Optional[int] = 1 , UpperCAmelCase_ : float = 0.0 , UpperCAmelCase_ : Optional[torch.Generator] = None , UpperCAmelCase_ : Optional[torch.FloatTensor] = None , UpperCAmelCase_ : Optional[str] = "pil" , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , UpperCAmelCase_ : int = 1 , **UpperCAmelCase_ : Optional[int] , ) ->Dict: '''simple docstring''' return self.pipea( prompt=UpperCAmelCase_ , height=UpperCAmelCase_ , width=UpperCAmelCase_ , num_inference_steps=UpperCAmelCase_ , guidance_scale=UpperCAmelCase_ , negative_prompt=UpperCAmelCase_ , num_images_per_prompt=UpperCAmelCase_ , eta=UpperCAmelCase_ , generator=UpperCAmelCase_ , latents=UpperCAmelCase_ , output_type=UpperCAmelCase_ , return_dict=UpperCAmelCase_ , callback=UpperCAmelCase_ , callback_steps=UpperCAmelCase_ , **UpperCAmelCase_ , ) @torch.no_grad() def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : Union[str, List[str]] , UpperCAmelCase_ : int = 512 , UpperCAmelCase_ : int = 512 , UpperCAmelCase_ : int = 50 , UpperCAmelCase_ : float = 7.5 , UpperCAmelCase_ : Optional[Union[str, List[str]]] = None , UpperCAmelCase_ : Optional[int] = 1 , UpperCAmelCase_ : float = 0.0 , UpperCAmelCase_ : Optional[torch.Generator] = None , UpperCAmelCase_ : Optional[torch.FloatTensor] = None , UpperCAmelCase_ : Optional[str] = "pil" , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , UpperCAmelCase_ : int = 1 , **UpperCAmelCase_ : int , ) ->int: '''simple docstring''' return self.pipea( prompt=UpperCAmelCase_ , height=UpperCAmelCase_ , width=UpperCAmelCase_ , num_inference_steps=UpperCAmelCase_ , guidance_scale=UpperCAmelCase_ , negative_prompt=UpperCAmelCase_ , num_images_per_prompt=UpperCAmelCase_ , eta=UpperCAmelCase_ , generator=UpperCAmelCase_ , latents=UpperCAmelCase_ , output_type=UpperCAmelCase_ , return_dict=UpperCAmelCase_ , callback=UpperCAmelCase_ , callback_steps=UpperCAmelCase_ , **UpperCAmelCase_ , ) @torch.no_grad() def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , UpperCAmelCase_ : Union[str, List[str]] , UpperCAmelCase_ : int = 512 , UpperCAmelCase_ : int = 512 , UpperCAmelCase_ : int = 50 , UpperCAmelCase_ : float = 7.5 , UpperCAmelCase_ : Optional[Union[str, List[str]]] = None , UpperCAmelCase_ : Optional[int] = 1 , UpperCAmelCase_ : float = 0.0 , UpperCAmelCase_ : Optional[torch.Generator] = None , UpperCAmelCase_ : Optional[torch.FloatTensor] = None , UpperCAmelCase_ : Optional[str] = "pil" , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , UpperCAmelCase_ : int = 1 , **UpperCAmelCase_ : Dict , ) ->List[str]: '''simple docstring''' return self.pipea( prompt=UpperCAmelCase_ , height=UpperCAmelCase_ , width=UpperCAmelCase_ , num_inference_steps=UpperCAmelCase_ , guidance_scale=UpperCAmelCase_ , negative_prompt=UpperCAmelCase_ , num_images_per_prompt=UpperCAmelCase_ , eta=UpperCAmelCase_ , generator=UpperCAmelCase_ , latents=UpperCAmelCase_ , output_type=UpperCAmelCase_ , return_dict=UpperCAmelCase_ , callback=UpperCAmelCase_ , callback_steps=UpperCAmelCase_ , **UpperCAmelCase_ , ) @torch.no_grad() def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : Union[str, List[str]] , UpperCAmelCase_ : int = 512 , UpperCAmelCase_ : int = 512 , UpperCAmelCase_ : int = 50 , UpperCAmelCase_ : float = 7.5 , UpperCAmelCase_ : Optional[Union[str, List[str]]] = None , UpperCAmelCase_ : Optional[int] = 1 , UpperCAmelCase_ : float = 0.0 , UpperCAmelCase_ : Optional[torch.Generator] = None , UpperCAmelCase_ : Optional[torch.FloatTensor] = None , UpperCAmelCase_ : Optional[str] = "pil" , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , UpperCAmelCase_ : int = 1 , **UpperCAmelCase_ : List[str] , ) ->List[str]: '''simple docstring''' return self.pipea( prompt=UpperCAmelCase_ , height=UpperCAmelCase_ , width=UpperCAmelCase_ , num_inference_steps=UpperCAmelCase_ , guidance_scale=UpperCAmelCase_ , negative_prompt=UpperCAmelCase_ , num_images_per_prompt=UpperCAmelCase_ , eta=UpperCAmelCase_ , generator=UpperCAmelCase_ , latents=UpperCAmelCase_ , output_type=UpperCAmelCase_ , return_dict=UpperCAmelCase_ , callback=UpperCAmelCase_ , callback_steps=UpperCAmelCase_ , **UpperCAmelCase_ , ) @torch.no_grad() def SCREAMING_SNAKE_CASE_ (self : str , UpperCAmelCase_ : Union[str, List[str]] , UpperCAmelCase_ : int = 512 , UpperCAmelCase_ : int = 512 , UpperCAmelCase_ : int = 50 , UpperCAmelCase_ : float = 7.5 , UpperCAmelCase_ : Optional[Union[str, List[str]]] = None , UpperCAmelCase_ : Optional[int] = 1 , UpperCAmelCase_ : float = 0.0 , UpperCAmelCase_ : Optional[torch.Generator] = None , UpperCAmelCase_ : Optional[torch.FloatTensor] = None , UpperCAmelCase_ : Optional[str] = "pil" , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , UpperCAmelCase_ : int = 1 , **UpperCAmelCase_ : List[Any] , ) ->List[str]: '''simple docstring''' lowerCamelCase__: Dict ="cuda" if torch.cuda.is_available() else "cpu" self.to(UpperCAmelCase_) # Checks if the height and width are divisible by 8 or not if height % 8 != 0 or width % 8 != 0: raise ValueError(F"""`height` and `width` must be divisible by 8 but are {height} and {width}.""") # Get first result from Stable Diffusion Checkpoint v1.1 lowerCamelCase__: int =self.textaimg_sda_a( prompt=UpperCAmelCase_ , height=UpperCAmelCase_ , width=UpperCAmelCase_ , num_inference_steps=UpperCAmelCase_ , guidance_scale=UpperCAmelCase_ , negative_prompt=UpperCAmelCase_ , num_images_per_prompt=UpperCAmelCase_ , eta=UpperCAmelCase_ , generator=UpperCAmelCase_ , latents=UpperCAmelCase_ , output_type=UpperCAmelCase_ , return_dict=UpperCAmelCase_ , callback=UpperCAmelCase_ , callback_steps=UpperCAmelCase_ , **UpperCAmelCase_ , ) # Get first result from Stable Diffusion Checkpoint v1.2 lowerCamelCase__: Any =self.textaimg_sda_a( prompt=UpperCAmelCase_ , height=UpperCAmelCase_ , width=UpperCAmelCase_ , num_inference_steps=UpperCAmelCase_ , guidance_scale=UpperCAmelCase_ , negative_prompt=UpperCAmelCase_ , num_images_per_prompt=UpperCAmelCase_ , eta=UpperCAmelCase_ , generator=UpperCAmelCase_ , latents=UpperCAmelCase_ , output_type=UpperCAmelCase_ , return_dict=UpperCAmelCase_ , callback=UpperCAmelCase_ , callback_steps=UpperCAmelCase_ , **UpperCAmelCase_ , ) # Get first result from Stable Diffusion Checkpoint v1.3 lowerCamelCase__: Dict =self.textaimg_sda_a( prompt=UpperCAmelCase_ , height=UpperCAmelCase_ , width=UpperCAmelCase_ , num_inference_steps=UpperCAmelCase_ , guidance_scale=UpperCAmelCase_ , negative_prompt=UpperCAmelCase_ , num_images_per_prompt=UpperCAmelCase_ , eta=UpperCAmelCase_ , generator=UpperCAmelCase_ , latents=UpperCAmelCase_ , output_type=UpperCAmelCase_ , return_dict=UpperCAmelCase_ , callback=UpperCAmelCase_ , callback_steps=UpperCAmelCase_ , **UpperCAmelCase_ , ) # Get first result from Stable Diffusion Checkpoint v1.4 lowerCamelCase__: Tuple =self.textaimg_sda_a( prompt=UpperCAmelCase_ , height=UpperCAmelCase_ , width=UpperCAmelCase_ , num_inference_steps=UpperCAmelCase_ , guidance_scale=UpperCAmelCase_ , negative_prompt=UpperCAmelCase_ , num_images_per_prompt=UpperCAmelCase_ , eta=UpperCAmelCase_ , generator=UpperCAmelCase_ , latents=UpperCAmelCase_ , output_type=UpperCAmelCase_ , return_dict=UpperCAmelCase_ , callback=UpperCAmelCase_ , callback_steps=UpperCAmelCase_ , **UpperCAmelCase_ , ) # Get all result images into a single list and pass it via StableDiffusionPipelineOutput for final result return StableDiffusionPipelineOutput([resa[0], resa[0], resa[0], resa[0]])
59
import argparse import os import pickle import sys import torch from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils from transformers.models.transfo_xl.tokenization_transfo_xl import CORPUS_NAME, VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() # We do this to be able to load python 2 datasets pickles # See e.g. https://stackoverflow.com/questions/2121874/python-pickling-after-changing-a-modules-directory/2121918#2121918 __A = data_utils.TransfoXLTokenizer __A = data_utils.TransfoXLCorpus __A = data_utils __A = data_utils def lowerCAmelCase_ ( __a , __a , __a , __a ) -> List[str]: """simple docstring""" if transfo_xl_dataset_file: # Convert a pre-processed corpus (see original TensorFlow repo) with open(__a , "rb" ) as fp: lowerCamelCase__: Optional[Any] =pickle.load(__a , encoding="latin1" ) # Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term) lowerCamelCase__: Union[str, Any] =pytorch_dump_folder_path + "/" + VOCAB_FILES_NAMES["pretrained_vocab_file"] print(F"""Save vocabulary to {pytorch_vocab_dump_path}""" ) lowerCamelCase__: Any =corpus.vocab.__dict__ torch.save(__a , __a ) lowerCamelCase__: Dict =corpus.__dict__ corpus_dict_no_vocab.pop("vocab" , __a ) lowerCamelCase__: List[str] =pytorch_dump_folder_path + "/" + CORPUS_NAME print(F"""Save dataset to {pytorch_dataset_dump_path}""" ) torch.save(__a , __a ) if tf_checkpoint_path: # Convert a pre-trained TensorFlow model lowerCamelCase__: Optional[Any] =os.path.abspath(__a ) lowerCamelCase__: Dict =os.path.abspath(__a ) print(F"""Converting Transformer XL checkpoint from {tf_path} with config at {config_path}.""" ) # Initialise PyTorch model if transfo_xl_config_file == "": lowerCamelCase__: int =TransfoXLConfig() else: lowerCamelCase__: Any =TransfoXLConfig.from_json_file(__a ) print(F"""Building PyTorch model from configuration: {config}""" ) lowerCamelCase__: List[Any] =TransfoXLLMHeadModel(__a ) lowerCamelCase__: List[str] =load_tf_weights_in_transfo_xl(__a , __a , __a ) # Save pytorch-model lowerCamelCase__: List[str] =os.path.join(__a , __a ) lowerCamelCase__: Tuple =os.path.join(__a , __a ) print(F"""Save PyTorch model to {os.path.abspath(__a )}""" ) torch.save(model.state_dict() , __a ) print(F"""Save configuration file to {os.path.abspath(__a )}""" ) with open(__a , "w" , encoding="utf-8" ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": __A = argparse.ArgumentParser() parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the folder to store the PyTorch model or dataset/vocab.", ) parser.add_argument( "--tf_checkpoint_path", default="", type=str, help="An optional path to a TensorFlow checkpoint path to be converted.", ) parser.add_argument( "--transfo_xl_config_file", default="", type=str, help=( "An optional config json file corresponding to the pre-trained BERT model. \n" "This specifies the model architecture." ), ) parser.add_argument( "--transfo_xl_dataset_file", default="", type=str, help="An optional dataset file to be converted in a vocabulary.", ) __A = parser.parse_args() convert_transfo_xl_checkpoint_to_pytorch( args.tf_checkpoint_path, args.transfo_xl_config_file, args.pytorch_dump_folder_path, args.transfo_xl_dataset_file, )
59
1
from typing import Callable, List, Optional, Tuple, Union import torch from transformers import CLIPTextModel, CLIPTokenizer from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin, TransformeraDModel, VQModel from ...schedulers import VQDiffusionScheduler from ...utils import logging from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput __A = logging.get_logger(__name__) # pylint: disable=invalid-name class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): '''simple docstring''' @register_to_config def __init__(self : str , UpperCAmelCase_ : bool , UpperCAmelCase_ : Optional[int] = None , UpperCAmelCase_ : Optional[int] = None) ->Any: '''simple docstring''' super().__init__() lowerCamelCase__: Any =learnable if self.learnable: assert hidden_size is not None, "learnable=True requires `hidden_size` to be set" assert length is not None, "learnable=True requires `length` to be set" lowerCamelCase__: int =torch.zeros(UpperCAmelCase_ , UpperCAmelCase_) else: lowerCamelCase__: Optional[int] =None lowerCamelCase__: Tuple =torch.nn.Parameter(UpperCAmelCase_) class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 def __init__(self : Union[str, Any] , UpperCAmelCase_ : VQModel , UpperCAmelCase_ : CLIPTextModel , UpperCAmelCase_ : CLIPTokenizer , UpperCAmelCase_ : TransformeraDModel , UpperCAmelCase_ : VQDiffusionScheduler , UpperCAmelCase_ : LearnedClassifierFreeSamplingEmbeddings , ) ->Optional[Any]: '''simple docstring''' super().__init__() self.register_modules( vqvae=UpperCAmelCase_ , transformer=UpperCAmelCase_ , text_encoder=UpperCAmelCase_ , tokenizer=UpperCAmelCase_ , scheduler=UpperCAmelCase_ , learned_classifier_free_sampling_embeddings=UpperCAmelCase_ , ) def SCREAMING_SNAKE_CASE_ (self : Union[str, Any] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : int , UpperCAmelCase_ : List[Any]) ->List[Any]: '''simple docstring''' lowerCamelCase__: Optional[Any] =len(UpperCAmelCase_) if isinstance(UpperCAmelCase_ , UpperCAmelCase_) else 1 # get prompt text embeddings lowerCamelCase__: Optional[Any] =self.tokenizer( UpperCAmelCase_ , padding="max_length" , max_length=self.tokenizer.model_max_length , return_tensors="pt" , ) lowerCamelCase__: List[Any] =text_inputs.input_ids if text_input_ids.shape[-1] > self.tokenizer.model_max_length: lowerCamelCase__: Union[str, Any] =self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :]) logger.warning( "The following part of your input was truncated because CLIP can only handle sequences up to" F""" {self.tokenizer.model_max_length} tokens: {removed_text}""") lowerCamelCase__: Tuple =text_input_ids[:, : self.tokenizer.model_max_length] lowerCamelCase__: Optional[int] =self.text_encoder(text_input_ids.to(self.device))[0] # NOTE: This additional step of normalizing the text embeddings is from VQ-Diffusion. # While CLIP does normalize the pooled output of the text transformer when combining # the image and text embeddings, CLIP does not directly normalize the last hidden state. # # CLIP normalizing the pooled output. # https://github.com/huggingface/transformers/blob/d92e22d1f28324f513f3080e5c47c071a3916721/src/transformers/models/clip/modeling_clip.py#L1052-L1053 lowerCamelCase__: List[str] =prompt_embeds / prompt_embeds.norm(dim=-1 , keepdim=UpperCAmelCase_) # duplicate text embeddings for each generation per prompt lowerCamelCase__: Tuple =prompt_embeds.repeat_interleave(UpperCAmelCase_ , dim=0) if do_classifier_free_guidance: if self.learned_classifier_free_sampling_embeddings.learnable: lowerCamelCase__: Tuple =self.learned_classifier_free_sampling_embeddings.embeddings lowerCamelCase__: str =negative_prompt_embeds.unsqueeze(0).repeat(UpperCAmelCase_ , 1 , 1) else: lowerCamelCase__: Any =[""] * batch_size lowerCamelCase__: List[str] =text_input_ids.shape[-1] lowerCamelCase__: List[Any] =self.tokenizer( UpperCAmelCase_ , padding="max_length" , max_length=UpperCAmelCase_ , truncation=UpperCAmelCase_ , return_tensors="pt" , ) lowerCamelCase__: int =self.text_encoder(uncond_input.input_ids.to(self.device))[0] # See comment for normalizing text embeddings lowerCamelCase__: List[str] =negative_prompt_embeds / negative_prompt_embeds.norm(dim=-1 , keepdim=UpperCAmelCase_) # duplicate unconditional embeddings for each generation per prompt, using mps friendly method lowerCamelCase__: Any =negative_prompt_embeds.shape[1] lowerCamelCase__: Optional[Any] =negative_prompt_embeds.repeat(1 , UpperCAmelCase_ , 1) lowerCamelCase__: int =negative_prompt_embeds.view(batch_size * num_images_per_prompt , UpperCAmelCase_ , -1) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes lowerCamelCase__: Tuple =torch.cat([negative_prompt_embeds, prompt_embeds]) return prompt_embeds @torch.no_grad() def __call__(self : Optional[Any] , UpperCAmelCase_ : Union[str, List[str]] , UpperCAmelCase_ : int = 100 , UpperCAmelCase_ : float = 5.0 , UpperCAmelCase_ : float = 1.0 , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , UpperCAmelCase_ : Optional[torch.FloatTensor] = None , UpperCAmelCase_ : Optional[str] = "pil" , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , UpperCAmelCase_ : int = 1 , ) ->Union[ImagePipelineOutput, Tuple]: '''simple docstring''' if isinstance(UpperCAmelCase_ , UpperCAmelCase_): lowerCamelCase__: int =1 elif isinstance(UpperCAmelCase_ , UpperCAmelCase_): lowerCamelCase__: Union[str, Any] =len(UpperCAmelCase_) else: raise ValueError(F"""`prompt` has to be of type `str` or `list` but is {type(UpperCAmelCase_)}""") lowerCamelCase__: List[str] =batch_size * num_images_per_prompt lowerCamelCase__: Optional[int] =guidance_scale > 1.0 lowerCamelCase__: Tuple =self._encode_prompt(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_) if (callback_steps is None) or ( callback_steps is not None and (not isinstance(UpperCAmelCase_ , UpperCAmelCase_) or callback_steps <= 0) ): raise ValueError( F"""`callback_steps` has to be a positive integer but is {callback_steps} of type""" F""" {type(UpperCAmelCase_)}.""") # get the initial completely masked latents unless the user supplied it lowerCamelCase__: Any =(batch_size, self.transformer.num_latent_pixels) if latents is None: lowerCamelCase__: List[Any] =self.transformer.num_vector_embeds - 1 lowerCamelCase__: Tuple =torch.full(UpperCAmelCase_ , UpperCAmelCase_).to(self.device) else: if latents.shape != latents_shape: raise ValueError(F"""Unexpected latents shape, got {latents.shape}, expected {latents_shape}""") if (latents < 0).any() or (latents >= self.transformer.num_vector_embeds).any(): raise ValueError( "Unexpected latents value(s). All latents be valid embedding indices i.e. in the range 0," F""" {self.transformer.num_vector_embeds - 1} (inclusive).""") lowerCamelCase__: int =latents.to(self.device) # set timesteps self.scheduler.set_timesteps(UpperCAmelCase_ , device=self.device) lowerCamelCase__: str =self.scheduler.timesteps.to(self.device) lowerCamelCase__: Union[str, Any] =latents for i, t in enumerate(self.progress_bar(UpperCAmelCase_)): # expand the sample if we are doing classifier free guidance lowerCamelCase__: Optional[Any] =torch.cat([sample] * 2) if do_classifier_free_guidance else sample # predict the un-noised image # model_output == `log_p_x_0` lowerCamelCase__: Optional[int] =self.transformer(UpperCAmelCase_ , encoder_hidden_states=UpperCAmelCase_ , timestep=UpperCAmelCase_).sample if do_classifier_free_guidance: lowerCamelCase__ , lowerCamelCase__: Any =model_output.chunk(2) lowerCamelCase__: Optional[Any] =model_output_uncond + guidance_scale * (model_output_text - model_output_uncond) model_output -= torch.logsumexp(UpperCAmelCase_ , dim=1 , keepdim=UpperCAmelCase_) lowerCamelCase__: Optional[int] =self.truncate(UpperCAmelCase_ , UpperCAmelCase_) # remove `log(0)`'s (`-inf`s) lowerCamelCase__: Optional[Any] =model_output.clamp(-70) # compute the previous noisy sample x_t -> x_t-1 lowerCamelCase__: str =self.scheduler.step(UpperCAmelCase_ , timestep=UpperCAmelCase_ , sample=UpperCAmelCase_ , generator=UpperCAmelCase_).prev_sample # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: int =self.vqvae.config.vq_embed_dim lowerCamelCase__: Union[str, Any] =(batch_size, self.transformer.height, self.transformer.width, embedding_channels) lowerCamelCase__: int =self.vqvae.quantize.get_codebook_entry(UpperCAmelCase_ , shape=UpperCAmelCase_) lowerCamelCase__: str =self.vqvae.decode(UpperCAmelCase_ , force_not_quantize=UpperCAmelCase_).sample lowerCamelCase__: Optional[int] =(image / 2 + 0.5).clamp(0 , 1) lowerCamelCase__: int =image.cpu().permute(0 , 2 , 3 , 1).numpy() if output_type == "pil": lowerCamelCase__: List[Any] =self.numpy_to_pil(UpperCAmelCase_) if not return_dict: return (image,) return ImagePipelineOutput(images=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : torch.FloatTensor , UpperCAmelCase_ : float) ->torch.FloatTensor: '''simple docstring''' lowerCamelCase__ , lowerCamelCase__: Tuple =torch.sort(UpperCAmelCase_ , 1 , descending=UpperCAmelCase_) lowerCamelCase__: List[str] =torch.exp(UpperCAmelCase_) lowerCamelCase__: Union[str, Any] =sorted_p_x_0.cumsum(dim=1) < truncation_rate # Ensure that at least the largest probability is not zeroed out lowerCamelCase__: Optional[int] =torch.full_like(keep_mask[:, 0:1, :] , UpperCAmelCase_) lowerCamelCase__: int =torch.cat((all_true, keep_mask) , dim=1) lowerCamelCase__: str =keep_mask[:, :-1, :] lowerCamelCase__: Dict =keep_mask.gather(1 , indices.argsort(1)) lowerCamelCase__: List[Any] =log_p_x_0.clone() lowerCamelCase__: int =-torch.inf # -inf = log(0) return rv
59
from collections import UserDict from typing import List, Union from ..utils import ( add_end_docstrings, is_tf_available, is_torch_available, is_vision_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING from ..tf_utils import stable_softmax __A = logging.get_logger(__name__) @add_end_docstrings(__SCREAMING_SNAKE_CASE ) class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__(self : Optional[int] , **UpperCAmelCase_ : List[Any]) ->List[str]: '''simple docstring''' super().__init__(**UpperCAmelCase_) requires_backends(self , "vision") self.check_model_type( TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING if self.framework == "tf" else MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING) def __call__(self : List[str] , UpperCAmelCase_ : Union[str, List[str], "Image", List["Image"]] , **UpperCAmelCase_ : List[Any]) ->Tuple: '''simple docstring''' return super().__call__(UpperCAmelCase_ , **UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[Any] , **UpperCAmelCase_ : Optional[int]) ->Any: '''simple docstring''' lowerCamelCase__: Optional[int] ={} if "candidate_labels" in kwargs: lowerCamelCase__: Tuple =kwargs["candidate_labels"] if "hypothesis_template" in kwargs: lowerCamelCase__: Tuple =kwargs["hypothesis_template"] return preprocess_params, {}, {} def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Dict=None , UpperCAmelCase_ : Optional[Any]="This is a photo of {}.") ->str: '''simple docstring''' lowerCamelCase__: int =load_image(UpperCAmelCase_) lowerCamelCase__: Any =self.image_processor(images=[image] , return_tensors=self.framework) lowerCamelCase__: Any =candidate_labels lowerCamelCase__: List[str] =[hypothesis_template.format(UpperCAmelCase_) for x in candidate_labels] lowerCamelCase__: int =self.tokenizer(UpperCAmelCase_ , return_tensors=self.framework , padding=UpperCAmelCase_) lowerCamelCase__: str =[text_inputs] return inputs def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Any) ->Tuple: '''simple docstring''' lowerCamelCase__: int =model_inputs.pop("candidate_labels") lowerCamelCase__: List[str] =model_inputs.pop("text_inputs") if isinstance(text_inputs[0] , UpperCAmelCase_): lowerCamelCase__: List[Any] =text_inputs[0] else: # Batching case. lowerCamelCase__: List[Any] =text_inputs[0][0] lowerCamelCase__: List[str] =self.model(**UpperCAmelCase_ , **UpperCAmelCase_) lowerCamelCase__: str ={ "candidate_labels": candidate_labels, "logits": outputs.logits_per_image, } return model_outputs def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , UpperCAmelCase_ : Union[str, Any]) ->int: '''simple docstring''' lowerCamelCase__: List[Any] =model_outputs.pop("candidate_labels") lowerCamelCase__: Optional[int] =model_outputs["logits"][0] if self.framework == "pt": lowerCamelCase__: Optional[Any] =logits.softmax(dim=-1).squeeze(-1) lowerCamelCase__: Optional[Any] =probs.tolist() if not isinstance(UpperCAmelCase_ , UpperCAmelCase_): lowerCamelCase__: Optional[int] =[scores] elif self.framework == "tf": lowerCamelCase__: List[str] =stable_softmax(UpperCAmelCase_ , axis=-1) lowerCamelCase__: Optional[int] =probs.numpy().tolist() else: raise ValueError(F"""Unsupported framework: {self.framework}""") lowerCamelCase__: Optional[int] =[ {"score": score, "label": candidate_label} for score, candidate_label in sorted(zip(UpperCAmelCase_ , UpperCAmelCase_) , key=lambda UpperCAmelCase_: -x[0]) ] return result
59
1
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging __A = logging.get_logger(__name__) __A = { "google/pix2struct-textcaps-base": ( "https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json" ), } class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = "pix2struct_text_model" lowercase_ = ["past_key_values"] lowercase_ = { "hidden_size": "hidden_size", "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__(self : Any , UpperCAmelCase_ : str=50_244 , UpperCAmelCase_ : Union[str, Any]=768 , UpperCAmelCase_ : Optional[Any]=64 , UpperCAmelCase_ : Optional[Any]=2_048 , UpperCAmelCase_ : Tuple=12 , UpperCAmelCase_ : int=12 , UpperCAmelCase_ : List[str]=32 , UpperCAmelCase_ : List[str]=128 , UpperCAmelCase_ : List[str]=0.1 , UpperCAmelCase_ : List[Any]=1E-6 , UpperCAmelCase_ : int=1.0 , UpperCAmelCase_ : int="gelu_new" , UpperCAmelCase_ : Dict=0 , UpperCAmelCase_ : List[Any]=False , UpperCAmelCase_ : Tuple=0 , UpperCAmelCase_ : Tuple=1 , UpperCAmelCase_ : Tuple=False , UpperCAmelCase_ : Union[str, Any]=True , **UpperCAmelCase_ : str , ) ->Optional[Any]: '''simple docstring''' lowerCamelCase__: str =vocab_size lowerCamelCase__: Tuple =hidden_size lowerCamelCase__: Any =d_kv lowerCamelCase__: Union[str, Any] =d_ff lowerCamelCase__: Optional[int] =num_layers lowerCamelCase__: Any =num_heads lowerCamelCase__: Dict =relative_attention_num_buckets lowerCamelCase__: Optional[Any] =relative_attention_max_distance lowerCamelCase__: int =dropout_rate lowerCamelCase__: Optional[Any] =layer_norm_epsilon lowerCamelCase__: Union[str, Any] =initializer_factor lowerCamelCase__: Any =use_cache lowerCamelCase__: List[Any] =eos_token_id lowerCamelCase__: List[Any] =decoder_start_token_id # for backwards compatibility lowerCamelCase__: Tuple =dense_act_fn super().__init__( pad_token_id=UpperCAmelCase_ , eos_token_id=UpperCAmelCase_ , decoder_start_token_id=UpperCAmelCase_ , tie_word_embeddings=UpperCAmelCase_ , is_decoder=UpperCAmelCase_ , **UpperCAmelCase_ , ) @classmethod def SCREAMING_SNAKE_CASE_ (cls : Tuple , UpperCAmelCase_ : Union[str, os.PathLike] , **UpperCAmelCase_ : List[Any]) ->"PretrainedConfig": '''simple docstring''' cls._set_token_in_kwargs(UpperCAmelCase_) lowerCamelCase__ , lowerCamelCase__: List[Any] =cls.get_config_dict(UpperCAmelCase_ , **UpperCAmelCase_) # get the text config dict if we are loading from Pix2StructConfig if config_dict.get("model_type") == "pix2struct": lowerCamelCase__: int =config_dict["text_config"] if "model_type" in config_dict and hasattr(cls , "model_type") and config_dict["model_type"] != cls.model_type: logger.warning( F"""You are using a model of type {config_dict["model_type"]} to instantiate a model of type """ F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""") return cls.from_dict(UpperCAmelCase_ , **UpperCAmelCase_) class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = "pix2struct_vision_model" def __init__(self : Union[str, Any] , UpperCAmelCase_ : Tuple=768 , UpperCAmelCase_ : Optional[int]=768 , UpperCAmelCase_ : int=2_048 , UpperCAmelCase_ : Optional[Any]=64 , UpperCAmelCase_ : str=12 , UpperCAmelCase_ : List[str]=12 , UpperCAmelCase_ : Optional[Any]="gelu_new" , UpperCAmelCase_ : Union[str, Any]=1E-6 , UpperCAmelCase_ : Union[str, Any]=0.0 , UpperCAmelCase_ : Union[str, Any]=0.0 , UpperCAmelCase_ : Dict=1E-1_0 , UpperCAmelCase_ : Any=1.0 , UpperCAmelCase_ : Tuple=4_096 , UpperCAmelCase_ : Optional[Any]=32 , UpperCAmelCase_ : Dict=128 , **UpperCAmelCase_ : Tuple , ) ->int: '''simple docstring''' super().__init__(**UpperCAmelCase_) lowerCamelCase__: int =hidden_size lowerCamelCase__: str =patch_embed_hidden_size lowerCamelCase__: Tuple =d_ff lowerCamelCase__: Optional[int] =dropout_rate lowerCamelCase__: Dict =num_hidden_layers lowerCamelCase__: Any =num_attention_heads lowerCamelCase__: str =initializer_range lowerCamelCase__: str =initializer_factor lowerCamelCase__: List[Any] =attention_dropout lowerCamelCase__: Optional[Any] =layer_norm_eps lowerCamelCase__: int =dense_act_fn lowerCamelCase__: Union[str, Any] =seq_len lowerCamelCase__: List[Any] =relative_attention_num_buckets lowerCamelCase__: Union[str, Any] =relative_attention_max_distance lowerCamelCase__: str =d_kv @classmethod def SCREAMING_SNAKE_CASE_ (cls : List[Any] , UpperCAmelCase_ : Union[str, os.PathLike] , **UpperCAmelCase_ : Any) ->"PretrainedConfig": '''simple docstring''' cls._set_token_in_kwargs(UpperCAmelCase_) lowerCamelCase__ , lowerCamelCase__: List[str] =cls.get_config_dict(UpperCAmelCase_ , **UpperCAmelCase_) # get the vision config dict if we are loading from Pix2StructConfig if config_dict.get("model_type") == "pix2struct": lowerCamelCase__: int =config_dict["vision_config"] if "model_type" in config_dict and hasattr(cls , "model_type") and config_dict["model_type"] != cls.model_type: logger.warning( F"""You are using a model of type {config_dict["model_type"]} to instantiate a model of type """ F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""") return cls.from_dict(UpperCAmelCase_ , **UpperCAmelCase_) class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = "pix2struct" lowercase_ = True def __init__(self : Optional[Any] , UpperCAmelCase_ : Any=None , UpperCAmelCase_ : Any=None , UpperCAmelCase_ : Optional[Any]=1.0 , UpperCAmelCase_ : int=0.02 , UpperCAmelCase_ : Optional[Any]=False , UpperCAmelCase_ : Any=False , UpperCAmelCase_ : List[Any]=True , **UpperCAmelCase_ : Optional[int] , ) ->Union[str, Any]: '''simple docstring''' super().__init__(tie_word_embeddings=UpperCAmelCase_ , is_encoder_decoder=UpperCAmelCase_ , **UpperCAmelCase_) if text_config is None: lowerCamelCase__: Optional[Any] ={} logger.info("text_config is None. Initializing the Pix2StructTextConfig with default values.") if vision_config is None: lowerCamelCase__: str ={} logger.info("vision_config is None. Initializing the Pix2StructVisionConfig with default values.") lowerCamelCase__: Any =PixaStructTextConfig(**UpperCAmelCase_) lowerCamelCase__: List[Any] =PixaStructVisionConfig(**UpperCAmelCase_) lowerCamelCase__: Tuple =self.text_config.decoder_start_token_id lowerCamelCase__: Dict =self.text_config.pad_token_id lowerCamelCase__: Any =self.text_config.eos_token_id lowerCamelCase__: str =initializer_factor lowerCamelCase__: List[Any] =initializer_range lowerCamelCase__: List[str] =self.initializer_range lowerCamelCase__: Dict =self.initializer_range lowerCamelCase__: int =is_vqa @classmethod def SCREAMING_SNAKE_CASE_ (cls : Any , UpperCAmelCase_ : PixaStructTextConfig , UpperCAmelCase_ : PixaStructVisionConfig , **UpperCAmelCase_ : Dict) ->Tuple: '''simple docstring''' return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->Optional[Any]: '''simple docstring''' lowerCamelCase__: str =copy.deepcopy(self.__dict__) lowerCamelCase__: Any =self.text_config.to_dict() lowerCamelCase__: Dict =self.vision_config.to_dict() lowerCamelCase__: Optional[int] =self.__class__.model_type return output
59
import json import os from dataclasses import dataclass from functools import partial from typing import Callable import flax.linen as nn import jax import jax.numpy as jnp import joblib import optax import wandb from flax import jax_utils, struct, traverse_util from flax.serialization import from_bytes, to_bytes from flax.training import train_state from flax.training.common_utils import shard from tqdm.auto import tqdm from transformers import BigBirdConfig, FlaxBigBirdForQuestionAnswering from transformers.models.big_bird.modeling_flax_big_bird import FlaxBigBirdForQuestionAnsweringModule class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = 42 lowercase_ = jnp.floataa lowercase_ = True def SCREAMING_SNAKE_CASE_ (self : Any) ->List[str]: '''simple docstring''' super().setup() lowerCamelCase__: int =nn.Dense(5 , dtype=self.dtype) def __call__(self : Dict , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : Any) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Optional[Any] =super().__call__(*UpperCAmelCase_ , **UpperCAmelCase_) lowerCamelCase__: int =self.cls(outputs[2]) return outputs[:2] + (cls_out,) class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = FlaxBigBirdForNaturalQuestionsModule def lowerCAmelCase_ ( __a , __a , __a , __a , __a , __a ) -> Tuple: """simple docstring""" def cross_entropy(__a , __a , __a=None ): lowerCamelCase__: Tuple =logits.shape[-1] lowerCamelCase__: Tuple =(labels[..., None] == jnp.arange(__a )[None]).astype("f4" ) lowerCamelCase__: str =jax.nn.log_softmax(__a , axis=-1 ) lowerCamelCase__: Optional[Any] =-jnp.sum(labels * logits , axis=-1 ) if reduction is not None: lowerCamelCase__: Optional[Any] =reduction(__a ) return loss lowerCamelCase__: str =partial(__a , reduction=jnp.mean ) lowerCamelCase__: str =cross_entropy(__a , __a ) lowerCamelCase__: Optional[int] =cross_entropy(__a , __a ) lowerCamelCase__: Optional[Any] =cross_entropy(__a , __a ) return (start_loss + end_loss + pooled_loss) / 3 @dataclass class _SCREAMING_SNAKE_CASE : '''simple docstring''' lowercase_ = "google/bigbird-roberta-base" lowercase_ = 3000 lowercase_ = 1_0500 lowercase_ = 128 lowercase_ = 3 lowercase_ = 1 lowercase_ = 5 # tx_args lowercase_ = 3E-5 lowercase_ = 0.0 lowercase_ = 2_0000 lowercase_ = 0.0095 lowercase_ = "bigbird-roberta-natural-questions" lowercase_ = "training-expt" lowercase_ = "data/nq-training.jsonl" lowercase_ = "data/nq-validation.jsonl" def SCREAMING_SNAKE_CASE_ (self : Tuple) ->List[str]: '''simple docstring''' os.makedirs(self.base_dir , exist_ok=UpperCAmelCase_) lowerCamelCase__: Optional[Any] =os.path.join(self.base_dir , self.save_dir) lowerCamelCase__: List[str] =self.batch_size_per_device * jax.device_count() @dataclass class _SCREAMING_SNAKE_CASE : '''simple docstring''' lowercase_ = 42 lowercase_ = 4096 # no dynamic padding on TPUs def __call__(self : List[Any] , UpperCAmelCase_ : Optional[Any]) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Optional[Any] =self.collate_fn(UpperCAmelCase_) lowerCamelCase__: List[Any] =jax.tree_util.tree_map(UpperCAmelCase_ , UpperCAmelCase_) return batch def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : List[str]) ->List[Any]: '''simple docstring''' lowerCamelCase__ , lowerCamelCase__: List[Any] =self.fetch_inputs(features["input_ids"]) lowerCamelCase__: Union[str, Any] ={ "input_ids": jnp.array(UpperCAmelCase_ , dtype=jnp.intaa), "attention_mask": jnp.array(UpperCAmelCase_ , dtype=jnp.intaa), "start_labels": jnp.array(features["start_token"] , dtype=jnp.intaa), "end_labels": jnp.array(features["end_token"] , dtype=jnp.intaa), "pooled_labels": jnp.array(features["category"] , dtype=jnp.intaa), } return batch def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : list) ->Optional[Any]: '''simple docstring''' lowerCamelCase__: Tuple =[self._fetch_inputs(UpperCAmelCase_) for ids in input_ids] return zip(*UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[Any] , UpperCAmelCase_ : list) ->Any: '''simple docstring''' lowerCamelCase__: Optional[Any] =[1 for _ in range(len(UpperCAmelCase_))] while len(UpperCAmelCase_) < self.max_length: input_ids.append(self.pad_id) attention_mask.append(0) return input_ids, attention_mask def lowerCAmelCase_ ( __a , __a , __a=None ) -> str: """simple docstring""" if seed is not None: lowerCamelCase__: Any =dataset.shuffle(seed=__a ) for i in range(len(__a ) // batch_size ): lowerCamelCase__: Any =dataset[i * batch_size : (i + 1) * batch_size] yield dict(__a ) @partial(jax.pmap , axis_name="batch" ) def lowerCAmelCase_ ( __a , __a , **__a ) -> List[str]: """simple docstring""" def loss_fn(__a ): lowerCamelCase__: Optional[int] =model_inputs.pop("start_labels" ) lowerCamelCase__: int =model_inputs.pop("end_labels" ) lowerCamelCase__: List[str] =model_inputs.pop("pooled_labels" ) lowerCamelCase__: Optional[int] =state.apply_fn(**__a , params=__a , dropout_rng=__a , train=__a ) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: List[Any] =outputs return state.loss_fn( __a , __a , __a , __a , __a , __a , ) lowerCamelCase__ , lowerCamelCase__: int =jax.random.split(__a ) lowerCamelCase__: Optional[Any] =jax.value_and_grad(__a ) lowerCamelCase__ , lowerCamelCase__: List[str] =grad_fn(state.params ) lowerCamelCase__: Optional[Any] =jax.lax.pmean({"loss": loss} , axis_name="batch" ) lowerCamelCase__: List[str] =jax.lax.pmean(__a , "batch" ) lowerCamelCase__: List[str] =state.apply_gradients(grads=__a ) return state, metrics, new_drp_rng @partial(jax.pmap , axis_name="batch" ) def lowerCAmelCase_ ( __a , **__a ) -> List[Any]: """simple docstring""" lowerCamelCase__: int =model_inputs.pop("start_labels" ) lowerCamelCase__: List[str] =model_inputs.pop("end_labels" ) lowerCamelCase__: int =model_inputs.pop("pooled_labels" ) lowerCamelCase__: Optional[Any] =state.apply_fn(**__a , params=state.params , train=__a ) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: List[str] =outputs lowerCamelCase__: Optional[int] =state.loss_fn(__a , __a , __a , __a , __a , __a ) lowerCamelCase__: Optional[Any] =jax.lax.pmean({"loss": loss} , axis_name="batch" ) return metrics class _SCREAMING_SNAKE_CASE ( train_state.TrainState ): '''simple docstring''' lowercase_ = struct.field(pytree_node=__SCREAMING_SNAKE_CASE ) @dataclass class _SCREAMING_SNAKE_CASE : '''simple docstring''' lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = None def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : int=None) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Dict =model.params lowerCamelCase__: Tuple =TrainState.create( apply_fn=model.__call__ , params=UpperCAmelCase_ , tx=UpperCAmelCase_ , loss_fn=UpperCAmelCase_ , ) if ckpt_dir is not None: lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Any =restore_checkpoint(UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: Tuple ={ "lr": args.lr, "init_lr": args.init_lr, "warmup_steps": args.warmup_steps, "num_train_steps": num_train_steps, "weight_decay": args.weight_decay, } lowerCamelCase__ , lowerCamelCase__: List[Any] =build_tx(**UpperCAmelCase_) lowerCamelCase__: str =train_state.TrainState( step=UpperCAmelCase_ , apply_fn=model.__call__ , params=UpperCAmelCase_ , tx=UpperCAmelCase_ , opt_state=UpperCAmelCase_ , ) lowerCamelCase__: Tuple =args lowerCamelCase__: Tuple =data_collator lowerCamelCase__: str =lr lowerCamelCase__: Dict =params lowerCamelCase__: List[str] =jax_utils.replicate(UpperCAmelCase_) return state def SCREAMING_SNAKE_CASE_ (self : List[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Tuple) ->Optional[Any]: '''simple docstring''' lowerCamelCase__: Tuple =self.args lowerCamelCase__: Any =len(UpperCAmelCase_) // args.batch_size lowerCamelCase__: List[str] =jax.random.PRNGKey(0) lowerCamelCase__: Optional[Any] =jax.random.split(UpperCAmelCase_ , jax.device_count()) for epoch in range(args.max_epochs): lowerCamelCase__: Union[str, Any] =jnp.array(0 , dtype=jnp.floataa) lowerCamelCase__: str =get_batched_dataset(UpperCAmelCase_ , args.batch_size , seed=UpperCAmelCase_) lowerCamelCase__: Dict =0 for batch in tqdm(UpperCAmelCase_ , total=UpperCAmelCase_ , desc=F"""Running EPOCH-{epoch}"""): lowerCamelCase__: List[str] =self.data_collator(UpperCAmelCase_) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Optional[int] =self.train_step_fn(UpperCAmelCase_ , UpperCAmelCase_ , **UpperCAmelCase_) running_loss += jax_utils.unreplicate(metrics["loss"]) i += 1 if i % args.logging_steps == 0: lowerCamelCase__: Optional[int] =jax_utils.unreplicate(state.step) lowerCamelCase__: List[Any] =running_loss.item() / i lowerCamelCase__: Tuple =self.scheduler_fn(state_step - 1) lowerCamelCase__: Union[str, Any] =self.evaluate(UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: Dict ={ "step": state_step.item(), "eval_loss": eval_loss.item(), "tr_loss": tr_loss, "lr": lr.item(), } tqdm.write(str(UpperCAmelCase_)) self.logger.log(UpperCAmelCase_ , commit=UpperCAmelCase_) if i % args.save_steps == 0: self.save_checkpoint(args.save_dir + F"""-e{epoch}-s{i}""" , state=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : str , UpperCAmelCase_ : str) ->Any: '''simple docstring''' lowerCamelCase__: List[Any] =get_batched_dataset(UpperCAmelCase_ , self.args.batch_size) lowerCamelCase__: List[str] =len(UpperCAmelCase_) // self.args.batch_size lowerCamelCase__: str =jnp.array(0 , dtype=jnp.floataa) lowerCamelCase__: Optional[Any] =0 for batch in tqdm(UpperCAmelCase_ , total=UpperCAmelCase_ , desc="Evaluating ... "): lowerCamelCase__: int =self.data_collator(UpperCAmelCase_) lowerCamelCase__: str =self.val_step_fn(UpperCAmelCase_ , **UpperCAmelCase_) running_loss += jax_utils.unreplicate(metrics["loss"]) i += 1 return running_loss / i def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[int]) ->int: '''simple docstring''' lowerCamelCase__: Any =jax_utils.unreplicate(UpperCAmelCase_) print(F"""SAVING CHECKPOINT IN {save_dir}""" , end=" ... ") self.model_save_fn(UpperCAmelCase_ , params=state.params) with open(os.path.join(UpperCAmelCase_ , "opt_state.msgpack") , "wb") as f: f.write(to_bytes(state.opt_state)) joblib.dump(self.args , os.path.join(UpperCAmelCase_ , "args.joblib")) joblib.dump(self.data_collator , os.path.join(UpperCAmelCase_ , "data_collator.joblib")) with open(os.path.join(UpperCAmelCase_ , "training_state.json") , "w") as f: json.dump({"step": state.step.item()} , UpperCAmelCase_) print("DONE") def lowerCAmelCase_ ( __a , __a ) -> str: """simple docstring""" print(F"""RESTORING CHECKPOINT FROM {save_dir}""" , end=" ... " ) with open(os.path.join(__a , "flax_model.msgpack" ) , "rb" ) as f: lowerCamelCase__: Tuple =from_bytes(state.params , f.read() ) with open(os.path.join(__a , "opt_state.msgpack" ) , "rb" ) as f: lowerCamelCase__: Optional[int] =from_bytes(state.opt_state , f.read() ) lowerCamelCase__: Any =joblib.load(os.path.join(__a , "args.joblib" ) ) lowerCamelCase__: Union[str, Any] =joblib.load(os.path.join(__a , "data_collator.joblib" ) ) with open(os.path.join(__a , "training_state.json" ) , "r" ) as f: lowerCamelCase__: Optional[Any] =json.load(__a ) lowerCamelCase__: Any =training_state["step"] print("DONE" ) return params, opt_state, step, args, data_collator def lowerCAmelCase_ ( __a , __a , __a , __a ) -> Optional[int]: """simple docstring""" lowerCamelCase__: int =num_train_steps - warmup_steps lowerCamelCase__: str =optax.linear_schedule(init_value=__a , end_value=__a , transition_steps=__a ) lowerCamelCase__: Optional[Any] =optax.linear_schedule(init_value=__a , end_value=1e-7 , transition_steps=__a ) lowerCamelCase__: List[Any] =optax.join_schedules(schedules=[warmup_fn, decay_fn] , boundaries=[warmup_steps] ) return lr def lowerCAmelCase_ ( __a , __a , __a , __a , __a ) -> str: """simple docstring""" def weight_decay_mask(__a ): lowerCamelCase__: List[str] =traverse_util.flatten_dict(__a ) lowerCamelCase__: List[str] ={k: (v[-1] != "bias" and v[-2:] != ("LayerNorm", "scale")) for k, v in params.items()} return traverse_util.unflatten_dict(__a ) lowerCamelCase__: Optional[Any] =scheduler_fn(__a , __a , __a , __a ) lowerCamelCase__: Tuple =optax.adamw(learning_rate=__a , weight_decay=__a , mask=__a ) return tx, lr
59
1
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __A = logging.get_logger(__name__) __A = { "YituTech/conv-bert-base": "https://huggingface.co/YituTech/conv-bert-base/resolve/main/config.json", "YituTech/conv-bert-medium-small": ( "https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/config.json" ), "YituTech/conv-bert-small": "https://huggingface.co/YituTech/conv-bert-small/resolve/main/config.json", # See all ConvBERT models at https://huggingface.co/models?filter=convbert } class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = "convbert" def __init__(self : List[str] , UpperCAmelCase_ : Any=30_522 , UpperCAmelCase_ : Optional[int]=768 , UpperCAmelCase_ : Optional[int]=12 , UpperCAmelCase_ : Optional[Any]=12 , UpperCAmelCase_ : List[str]=3_072 , UpperCAmelCase_ : Dict="gelu" , UpperCAmelCase_ : int=0.1 , UpperCAmelCase_ : Any=0.1 , UpperCAmelCase_ : List[str]=512 , UpperCAmelCase_ : List[str]=2 , UpperCAmelCase_ : Tuple=0.02 , UpperCAmelCase_ : List[str]=1E-1_2 , UpperCAmelCase_ : Optional[int]=1 , UpperCAmelCase_ : Union[str, Any]=0 , UpperCAmelCase_ : Tuple=2 , UpperCAmelCase_ : Optional[int]=768 , UpperCAmelCase_ : Dict=2 , UpperCAmelCase_ : Optional[int]=9 , UpperCAmelCase_ : List[str]=1 , UpperCAmelCase_ : Union[str, Any]=None , **UpperCAmelCase_ : Optional[int] , ) ->List[Any]: '''simple docstring''' super().__init__( pad_token_id=UpperCAmelCase_ , bos_token_id=UpperCAmelCase_ , eos_token_id=UpperCAmelCase_ , **UpperCAmelCase_ , ) lowerCamelCase__: Any =vocab_size lowerCamelCase__: Optional[Any] =hidden_size lowerCamelCase__: List[Any] =num_hidden_layers lowerCamelCase__: List[str] =num_attention_heads lowerCamelCase__: Dict =intermediate_size lowerCamelCase__: List[Any] =hidden_act lowerCamelCase__: List[str] =hidden_dropout_prob lowerCamelCase__: List[Any] =attention_probs_dropout_prob lowerCamelCase__: Union[str, Any] =max_position_embeddings lowerCamelCase__: str =type_vocab_size lowerCamelCase__: str =initializer_range lowerCamelCase__: Optional[Any] =layer_norm_eps lowerCamelCase__: Optional[int] =embedding_size lowerCamelCase__: List[str] =head_ratio lowerCamelCase__: Optional[Any] =conv_kernel_size lowerCamelCase__: int =num_groups lowerCamelCase__: List[str] =classifier_dropout class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' @property def SCREAMING_SNAKE_CASE_ (self : Union[str, Any]) ->Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task == "multiple-choice": lowerCamelCase__: Any ={0: "batch", 1: "choice", 2: "sequence"} else: lowerCamelCase__: str ={0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ("token_type_ids", dynamic_axis), ])
59
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = ["image_processor", "tokenizer"] lowercase_ = "ChineseCLIPImageProcessor" lowercase_ = ("BertTokenizer", "BertTokenizerFast") def __init__(self : Any , UpperCAmelCase_ : List[str]=None , UpperCAmelCase_ : Union[str, Any]=None , **UpperCAmelCase_ : str) ->Dict: '''simple docstring''' lowerCamelCase__: str =None if "feature_extractor" in kwargs: warnings.warn( "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`" " instead." , UpperCAmelCase_ , ) lowerCamelCase__: Tuple =kwargs.pop("feature_extractor") lowerCamelCase__: Optional[int] =image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("You need to specify an `image_processor`.") if tokenizer is None: raise ValueError("You need to specify a `tokenizer`.") super().__init__(UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: Optional[int] =self.image_processor def __call__(self : int , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : List[Any]=None , **UpperCAmelCase_ : Dict) ->Optional[int]: '''simple docstring''' if text is None and images is None: raise ValueError("You have to specify either text or images. Both cannot be none.") if text is not None: lowerCamelCase__: Dict =self.tokenizer(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_) if images is not None: lowerCamelCase__: List[str] =self.image_processor(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_) if text is not None and images is not None: lowerCamelCase__: Union[str, Any] =image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**UpperCAmelCase_) , tensor_type=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : int) ->str: '''simple docstring''' return self.tokenizer.batch_decode(*UpperCAmelCase_ , **UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Any , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : List[Any]) ->Dict: '''simple docstring''' return self.tokenizer.decode(*UpperCAmelCase_ , **UpperCAmelCase_) @property def SCREAMING_SNAKE_CASE_ (self : int) ->List[str]: '''simple docstring''' lowerCamelCase__: str =self.tokenizer.model_input_names lowerCamelCase__: Union[str, Any] =self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names)) @property def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->str: '''simple docstring''' warnings.warn( "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead." , UpperCAmelCase_ , ) return self.image_processor_class
59
1
def lowerCAmelCase_ ( __a ) -> list[list[float]]: """simple docstring""" lowerCamelCase__: list[list[float]] =[] for data in source_data: for i, el in enumerate(__a ): if len(__a ) < i + 1: data_lists.append([] ) data_lists[i].append(float(__a ) ) return data_lists def lowerCAmelCase_ ( __a , __a ) -> list[list[float]]: """simple docstring""" lowerCamelCase__: list[list[float]] =[] for dlist, weight in zip(__a , __a ): lowerCamelCase__: Dict =min(__a ) lowerCamelCase__: List[str] =max(__a ) lowerCamelCase__: list[float] =[] # for weight 0 score is 1 - actual score if weight == 0: for item in dlist: try: score.append(1 - ((item - mind) / (maxd - mind)) ) except ZeroDivisionError: score.append(1 ) elif weight == 1: for item in dlist: try: score.append((item - mind) / (maxd - mind) ) except ZeroDivisionError: score.append(0 ) # weight not 0 or 1 else: lowerCamelCase__: int =F"""Invalid weight of {weight:f} provided""" raise ValueError(__a ) score_lists.append(__a ) return score_lists def lowerCAmelCase_ ( __a ) -> list[float]: """simple docstring""" lowerCamelCase__: list[float] =[0 for i in range(len(score_lists[0] ) )] for slist in score_lists: for j, ele in enumerate(__a ): lowerCamelCase__: Dict =final_scores[j] + ele return final_scores def lowerCAmelCase_ ( __a , __a ) -> list[list[float]]: """simple docstring""" lowerCamelCase__: List[Any] =get_data(__a ) lowerCamelCase__: List[str] =calculate_each_score(__a , __a ) lowerCamelCase__: Union[str, Any] =generate_final_scores(__a ) # append scores to source data for i, ele in enumerate(__a ): source_data[i].append(__a ) return source_data
59
from math import ceil, sqrt def lowerCAmelCase_ ( __a = 1000000 ) -> int: """simple docstring""" lowerCamelCase__: Any =0 for outer_width in range(3 , (limit // 4) + 2 ): if outer_width**2 > limit: lowerCamelCase__: Optional[int] =max(ceil(sqrt(outer_width**2 - limit ) ) , 1 ) else: lowerCamelCase__: Tuple =1 if (outer_width - hole_width_lower_bound) % 2: hole_width_lower_bound += 1 answer += (outer_width - hole_width_lower_bound - 2) // 2 + 1 return answer if __name__ == "__main__": print(f'{solution() = }')
59
1
import math import sys def lowerCAmelCase_ ( __a ) -> int: """simple docstring""" if number != int(__a ): raise ValueError("the value of input must be a natural number" ) if number < 0: raise ValueError("the value of input must not be a negative number" ) if number == 0: return 1 lowerCamelCase__: int =[-1] * (number + 1) lowerCamelCase__: Tuple =0 for i in range(1 , number + 1 ): lowerCamelCase__: List[Any] =sys.maxsize lowerCamelCase__: Union[str, Any] =int(math.sqrt(__a ) ) for j in range(1 , root + 1 ): lowerCamelCase__: Tuple =1 + answers[i - (j**2)] lowerCamelCase__: Union[str, Any] =min(__a , __a ) lowerCamelCase__: Optional[int] =answer return answers[number] if __name__ == "__main__": import doctest doctest.testmod()
59
def lowerCAmelCase_ ( __a = 50000000 ) -> int: """simple docstring""" lowerCamelCase__: Any =set() lowerCamelCase__: int =int((limit - 24) ** (1 / 2) ) lowerCamelCase__: Tuple =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 , __a ) ) ) for primea in primes: lowerCamelCase__: Optional[int] =primea * primea for primea in primes: lowerCamelCase__: List[str] =primea * primea * primea if square + cube >= limit - 16: break for primea in primes: lowerCamelCase__: int =primea * primea * primea * primea lowerCamelCase__: Optional[Any] =square + cube + tetr if total >= limit: break ret.add(__a ) return len(__a ) if __name__ == "__main__": print(f'{solution() = }')
59
1
from math import pow, sqrt def lowerCAmelCase_ ( *__a ) -> bool: """simple docstring""" lowerCamelCase__: Union[str, Any] =len(__a ) > 0 and all(value > 0.0 for value in values ) return result def lowerCAmelCase_ ( __a , __a ) -> float | ValueError: """simple docstring""" return ( round(sqrt(molar_mass_a / molar_mass_a ) , 6 ) if validate(__a , __a ) else ValueError("Input Error: Molar mass values must greater than 0." ) ) def lowerCAmelCase_ ( __a , __a , __a ) -> float | ValueError: """simple docstring""" return ( round(effusion_rate * sqrt(molar_mass_a / molar_mass_a ) , 6 ) if validate(__a , __a , __a ) else ValueError( "Input Error: Molar mass and effusion rate values must greater than 0." ) ) def lowerCAmelCase_ ( __a , __a , __a ) -> float | ValueError: """simple docstring""" return ( round(effusion_rate / sqrt(molar_mass_a / molar_mass_a ) , 6 ) if validate(__a , __a , __a ) else ValueError( "Input Error: Molar mass and effusion rate values must greater than 0." ) ) def lowerCAmelCase_ ( __a , __a , __a ) -> float | ValueError: """simple docstring""" return ( round(molar_mass / pow(effusion_rate_a / effusion_rate_a , 2 ) , 6 ) if validate(__a , __a , __a ) else ValueError( "Input Error: Molar mass and effusion rate values must greater than 0." ) ) def lowerCAmelCase_ ( __a , __a , __a ) -> float | ValueError: """simple docstring""" return ( round(pow(effusion_rate_a / effusion_rate_a , 2 ) / molar_mass , 6 ) if validate(__a , __a , __a ) else ValueError( "Input Error: Molar mass and effusion rate values must greater than 0." ) )
59
from __future__ import annotations from decimal import Decimal from math import * # noqa: F403 from sympy import diff def lowerCAmelCase_ ( __a , __a , __a = 10**-10 ) -> float: """simple docstring""" lowerCamelCase__: List[str] =a while True: lowerCamelCase__: Optional[Any] =Decimal(__a ) - ( Decimal(eval(__a ) ) / Decimal(eval(str(diff(__a ) ) ) ) # noqa: S307 ) # This number dictates the accuracy of the answer if abs(eval(__a ) ) < precision: # noqa: S307 return float(__a ) # Let's Execute if __name__ == "__main__": # Find root of trigonometric function # Find value of pi print(f'The root of sin(x) = 0 is {newton_raphson("sin(x)", 2)}') # Find root of polynomial print(f'The root of x**2 - 5*x + 2 = 0 is {newton_raphson("x**2 - 5*x + 2", 0.4)}') # Find Square Root of 5 print(f'The root of log(x) - 1 = 0 is {newton_raphson("log(x) - 1", 2)}') # Exponential Roots print(f'The root of exp(x) - 1 = 0 is {newton_raphson("exp(x) - 1", 0)}')
59
1
from ...configuration_utils import PretrainedConfig from ...utils import logging __A = logging.get_logger(__name__) __A = { "microsoft/cvt-13": "https://huggingface.co/microsoft/cvt-13/resolve/main/config.json", # See all Cvt models at https://huggingface.co/models?filter=cvt } class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = "cvt" def __init__(self : List[str] , UpperCAmelCase_ : int=3 , UpperCAmelCase_ : List[Any]=[7, 3, 3] , UpperCAmelCase_ : List[Any]=[4, 2, 2] , UpperCAmelCase_ : Union[str, Any]=[2, 1, 1] , UpperCAmelCase_ : Optional[int]=[64, 192, 384] , UpperCAmelCase_ : List[Any]=[1, 3, 6] , UpperCAmelCase_ : Union[str, Any]=[1, 2, 10] , UpperCAmelCase_ : List[Any]=[4.0, 4.0, 4.0] , UpperCAmelCase_ : int=[0.0, 0.0, 0.0] , UpperCAmelCase_ : Dict=[0.0, 0.0, 0.0] , UpperCAmelCase_ : List[Any]=[0.0, 0.0, 0.1] , UpperCAmelCase_ : str=[True, True, True] , UpperCAmelCase_ : Optional[Any]=[False, False, True] , UpperCAmelCase_ : Optional[Any]=["dw_bn", "dw_bn", "dw_bn"] , UpperCAmelCase_ : Dict=[3, 3, 3] , UpperCAmelCase_ : Optional[int]=[1, 1, 1] , UpperCAmelCase_ : Optional[int]=[2, 2, 2] , UpperCAmelCase_ : Any=[1, 1, 1] , UpperCAmelCase_ : List[Any]=[1, 1, 1] , UpperCAmelCase_ : Tuple=0.02 , UpperCAmelCase_ : Union[str, Any]=1E-1_2 , **UpperCAmelCase_ : Optional[Any] , ) ->str: '''simple docstring''' super().__init__(**UpperCAmelCase_) lowerCamelCase__: Optional[int] =num_channels lowerCamelCase__: Any =patch_sizes lowerCamelCase__: List[Any] =patch_stride lowerCamelCase__: List[str] =patch_padding lowerCamelCase__: str =embed_dim lowerCamelCase__: int =num_heads lowerCamelCase__: int =depth lowerCamelCase__: Dict =mlp_ratio lowerCamelCase__: Union[str, Any] =attention_drop_rate lowerCamelCase__: List[str] =drop_rate lowerCamelCase__: Optional[Any] =drop_path_rate lowerCamelCase__: Union[str, Any] =qkv_bias lowerCamelCase__: List[str] =cls_token lowerCamelCase__: Dict =qkv_projection_method lowerCamelCase__: Tuple =kernel_qkv lowerCamelCase__: Any =padding_kv lowerCamelCase__: List[Any] =stride_kv lowerCamelCase__: str =padding_q lowerCamelCase__: int =stride_q lowerCamelCase__: str =initializer_range lowerCamelCase__: List[str] =layer_norm_eps
59
import numpy as np from numpy import ndarray from scipy.optimize import Bounds, LinearConstraint, minimize def lowerCAmelCase_ ( __a ) -> float: """simple docstring""" return np.dot(__a , __a ) class _SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__(self : List[str] , *, UpperCAmelCase_ : float = np.inf , UpperCAmelCase_ : str = "linear" , UpperCAmelCase_ : float = 0.0 , ) ->None: '''simple docstring''' lowerCamelCase__: Dict =regularization lowerCamelCase__: Any =gamma if kernel == "linear": lowerCamelCase__: Dict =self.__linear elif kernel == "rbf": if self.gamma == 0: raise ValueError("rbf kernel requires gamma") if not isinstance(self.gamma , (float, int)): raise ValueError("gamma must be float or int") if not self.gamma > 0: raise ValueError("gamma must be > 0") lowerCamelCase__: Tuple =self.__rbf # in the future, there could be a default value like in sklearn # sklear: def_gamma = 1/(n_features * X.var()) (wiki) # previously it was 1/(n_features) else: lowerCamelCase__: Optional[Any] =F"""Unknown kernel: {kernel}""" raise ValueError(UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : ndarray , UpperCAmelCase_ : ndarray) ->float: '''simple docstring''' return np.dot(UpperCAmelCase_ , UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : ndarray , UpperCAmelCase_ : ndarray) ->float: '''simple docstring''' return np.exp(-(self.gamma * norm_squared(vectora - vectora))) def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : list[ndarray] , UpperCAmelCase_ : ndarray) ->None: '''simple docstring''' lowerCamelCase__: Optional[Any] =observations lowerCamelCase__: Optional[int] =classes # using Wolfe's Dual to calculate w. # Primal problem: minimize 1/2*norm_squared(w) # constraint: yn(w . xn + b) >= 1 # # With l a vector # Dual problem: maximize sum_n(ln) - # 1/2 * sum_n(sum_m(ln*lm*yn*ym*xn . xm)) # constraint: self.C >= ln >= 0 # and sum_n(ln*yn) = 0 # Then we get w using w = sum_n(ln*yn*xn) # At the end we can get b ~= mean(yn - w . xn) # # Since we use kernels, we only need l_star to calculate b # and to classify observations ((lowerCamelCase__) , ): List[str] =np.shape(UpperCAmelCase_) def to_minimize(UpperCAmelCase_ : ndarray) -> float: lowerCamelCase__: int =0 ((lowerCamelCase__) , ): Optional[Any] =np.shape(UpperCAmelCase_) for i in range(UpperCAmelCase_): for j in range(UpperCAmelCase_): s += ( candidate[i] * candidate[j] * classes[i] * classes[j] * self.kernel(observations[i] , observations[j]) ) return 1 / 2 * s - sum(UpperCAmelCase_) lowerCamelCase__: List[Any] =LinearConstraint(UpperCAmelCase_ , 0 , 0) lowerCamelCase__: str =Bounds(0 , self.regularization) lowerCamelCase__: Union[str, Any] =minimize( UpperCAmelCase_ , np.ones(UpperCAmelCase_) , bounds=UpperCAmelCase_ , constraints=[ly_contraint]).x lowerCamelCase__: str =l_star # calculating mean offset of separation plane to points lowerCamelCase__: Tuple =0 for i in range(UpperCAmelCase_): for j in range(UpperCAmelCase_): s += classes[i] - classes[i] * self.optimum[i] * self.kernel( observations[i] , observations[j]) lowerCamelCase__: int =s / n def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : ndarray) ->int: '''simple docstring''' lowerCamelCase__: Optional[Any] =sum( self.optimum[n] * self.classes[n] * self.kernel(self.observations[n] , UpperCAmelCase_) for n in range(len(self.classes))) return 1 if s + self.offset >= 0 else -1 if __name__ == "__main__": import doctest doctest.testmod()
59
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __A = { "configuration_git": ["GIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "GitConfig", "GitVisionConfig"], "processing_git": ["GitProcessor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ "GIT_PRETRAINED_MODEL_ARCHIVE_LIST", "GitForCausalLM", "GitModel", "GitPreTrainedModel", "GitVisionModel", ] if TYPE_CHECKING: from .configuration_git import GIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GitConfig, GitVisionConfig from .processing_git import GitProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_git import ( GIT_PRETRAINED_MODEL_ARCHIVE_LIST, GitForCausalLM, GitModel, GitPreTrainedModel, GitVisionModel, ) else: import sys __A = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
59
import logging import os from typing import Dict, List, Optional, Union import torch import torch.nn as nn from accelerate.utils.imports import ( is_abit_bnb_available, is_abit_bnb_available, is_bnb_available, ) from ..big_modeling import dispatch_model, init_empty_weights from .dataclasses import BnbQuantizationConfig from .modeling import ( find_tied_parameters, get_balanced_memory, infer_auto_device_map, load_checkpoint_in_model, offload_weight, set_module_tensor_to_device, ) if is_bnb_available(): import bitsandbytes as bnb from copy import deepcopy __A = logging.getLogger(__name__) def lowerCAmelCase_ ( __a , __a , __a = None , __a = None , __a = None , __a = None , __a = None , __a = False , ) -> str: """simple docstring""" lowerCamelCase__: int =bnb_quantization_config.load_in_abit lowerCamelCase__: Any =bnb_quantization_config.load_in_abit if load_in_abit and not is_abit_bnb_available(): raise ImportError( "You have a version of `bitsandbytes` that is not compatible with 8bit quantization," " make sure you have the latest version of `bitsandbytes` installed." ) if load_in_abit and not is_abit_bnb_available(): raise ValueError( "You have a version of `bitsandbytes` that is not compatible with 4bit quantization," "make sure you have the latest version of `bitsandbytes` installed." ) lowerCamelCase__: List[Any] =[] # custom device map if isinstance(__a , __a ) and len(device_map.keys() ) > 1: lowerCamelCase__: Optional[int] =[key for key, value in device_map.items() if value in ["disk", "cpu"]] # We keep some modules such as the lm_head in their original dtype for numerical stability reasons if bnb_quantization_config.skip_modules is None: lowerCamelCase__: Any =get_keys_to_not_convert(__a ) # add cpu modules to skip modules only for 4-bit modules if load_in_abit: bnb_quantization_config.skip_modules.extend(__a ) lowerCamelCase__: List[str] =bnb_quantization_config.skip_modules # We add the modules we want to keep in full precision if bnb_quantization_config.keep_in_fpaa_modules is None: lowerCamelCase__: List[Any] =[] lowerCamelCase__: int =bnb_quantization_config.keep_in_fpaa_modules modules_to_not_convert.extend(__a ) # compatibility with peft lowerCamelCase__: List[str] =load_in_abit lowerCamelCase__: int =load_in_abit lowerCamelCase__: Tuple =get_parameter_device(__a ) if model_device.type != "meta": # quantization of an already loaded model logger.warning( "It is not recommended to quantize a loaded model. " "The model should be instantiated under the `init_empty_weights` context manager." ) lowerCamelCase__: Tuple =replace_with_bnb_layers(__a , __a , modules_to_not_convert=__a ) # convert param to the right dtype lowerCamelCase__: Dict =bnb_quantization_config.torch_dtype for name, param in model.state_dict().items(): if any(module_to_keep_in_fpaa in name for module_to_keep_in_fpaa in keep_in_fpaa_modules ): param.to(torch.floataa ) if param.dtype != torch.floataa: lowerCamelCase__: str =name.replace(".weight" , "" ).replace(".bias" , "" ) lowerCamelCase__: Optional[Any] =getattr(__a , __a , __a ) if param is not None: param.to(torch.floataa ) elif torch.is_floating_point(__a ): param.to(__a ) if model_device.type == "cuda": # move everything to cpu in the first place because we can't do quantization if the weights are already on cuda model.cuda(torch.cuda.current_device() ) torch.cuda.empty_cache() elif torch.cuda.is_available(): model.to(torch.cuda.current_device() ) else: raise RuntimeError("No GPU found. A GPU is needed for quantization." ) logger.info( F"""The model device type is {model_device.type}. However, cuda is needed for quantization.""" "We move the model to cuda." ) return model elif weights_location is None: raise RuntimeError( F"""`weights_location` needs to be the folder path containing the weights of the model, but we found {weights_location} """ ) else: with init_empty_weights(): lowerCamelCase__: str =replace_with_bnb_layers( __a , __a , modules_to_not_convert=__a ) lowerCamelCase__: Optional[Any] =get_quantized_model_device_map( __a , __a , __a , max_memory=__a , no_split_module_classes=__a , ) if offload_state_dict is None and device_map is not None and "disk" in device_map.values(): lowerCamelCase__: Any =True lowerCamelCase__: List[str] =any(x in list(device_map.values() ) for x in ["cpu", "disk"] ) load_checkpoint_in_model( __a , __a , __a , dtype=bnb_quantization_config.torch_dtype , offload_folder=__a , offload_state_dict=__a , keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules , offload_abit_bnb=load_in_abit and offload , ) return dispatch_model(__a , device_map=__a , offload_dir=__a ) def lowerCAmelCase_ ( __a , __a , __a=None , __a=None , __a=None ) -> str: """simple docstring""" if device_map is None: if torch.cuda.is_available(): lowerCamelCase__: str ={"": torch.cuda.current_device()} else: raise RuntimeError("No GPU found. A GPU is needed for quantization." ) logger.info("The device_map was not initialized." "Setting device_map to `{'':torch.cuda.current_device()}`." ) if isinstance(__a , __a ): if device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]: raise ValueError( "If passing a string for `device_map`, please choose 'auto', 'balanced', 'balanced_low_0' or " "'sequential'." ) lowerCamelCase__: Optional[int] ={} special_dtypes.update( { name: bnb_quantization_config.torch_dtype for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.skip_modules ) } ) special_dtypes.update( { name: torch.floataa for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.keep_in_fpaa_modules ) } ) lowerCamelCase__: Optional[Any] ={} lowerCamelCase__: str =special_dtypes lowerCamelCase__: List[str] =no_split_module_classes lowerCamelCase__: Dict =bnb_quantization_config.target_dtype # get max_memory for each device. if device_map != "sequential": lowerCamelCase__: Optional[Any] =get_balanced_memory( __a , low_zero=(device_map == "balanced_low_0") , max_memory=__a , **__a , ) lowerCamelCase__: Union[str, Any] =max_memory lowerCamelCase__: Dict =infer_auto_device_map(__a , **__a ) if isinstance(__a , __a ): # check if don't have any quantized module on the cpu lowerCamelCase__: Union[str, Any] =bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules lowerCamelCase__: List[Any] ={ key: device_map[key] for key in device_map.keys() if key not in modules_not_to_convert } for device in ["cpu", "disk"]: if device in device_map_without_some_modules.values(): if bnb_quantization_config.load_in_abit: raise ValueError( "\n Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit\n the quantized model. If you want to dispatch the model on the CPU or the disk while keeping\n these modules in `torch_dtype`, you need to pass a custom `device_map` to\n `load_and_quantize_model`. Check\n https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk\n for more details.\n " ) else: logger.info( "Some modules are are offloaded to the CPU or the disk. Note that these modules will be converted to 8-bit" ) del device_map_without_some_modules return device_map def lowerCAmelCase_ ( __a , __a , __a=None , __a=None ) -> Optional[Any]: """simple docstring""" if modules_to_not_convert is None: lowerCamelCase__: List[Any] =[] lowerCamelCase__ , lowerCamelCase__: Any =_replace_with_bnb_layers( __a , __a , __a , __a ) if not has_been_replaced: logger.warning( "You are loading your model in 8bit or 4bit but no linear modules were found in your model." " this can happen for some architectures such as gpt2 that uses Conv1D instead of Linear layers." " Please double check your model architecture, or submit an issue on github if you think this is" " a bug." ) return model def lowerCAmelCase_ ( __a , __a , __a=None , __a=None , ) -> List[Any]: """simple docstring""" lowerCamelCase__: Optional[int] =False for name, module in model.named_children(): if current_key_name is None: lowerCamelCase__: Optional[Any] =[] current_key_name.append(__a ) if isinstance(__a , nn.Linear ) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` lowerCamelCase__: List[str] =".".join(__a ) lowerCamelCase__: Optional[Any] =True for key in modules_to_not_convert: if ( (key in current_key_name_str) and (key + "." in current_key_name_str) ) or key == current_key_name_str: lowerCamelCase__: int =False break if proceed: # Load bnb module with empty weight and replace ``nn.Linear` module if bnb_quantization_config.load_in_abit: lowerCamelCase__: Optional[int] =bnb.nn.LinearabitLt( module.in_features , module.out_features , module.bias is not None , has_fpaa_weights=__a , threshold=bnb_quantization_config.llm_inta_threshold , ) elif bnb_quantization_config.load_in_abit: lowerCamelCase__: Dict =bnb.nn.Linearabit( module.in_features , module.out_features , module.bias is not None , bnb_quantization_config.bnb_abit_compute_dtype , compress_statistics=bnb_quantization_config.bnb_abit_use_double_quant , quant_type=bnb_quantization_config.bnb_abit_quant_type , ) else: raise ValueError("load_in_8bit and load_in_4bit can't be both False" ) lowerCamelCase__: Dict =module.weight.data if module.bias is not None: lowerCamelCase__: List[Any] =module.bias.data bnb_module.requires_grad_(__a ) setattr(__a , __a , __a ) lowerCamelCase__: int =True if len(list(module.children() ) ) > 0: lowerCamelCase__ , lowerCamelCase__: List[str] =_replace_with_bnb_layers( __a , __a , __a , __a ) lowerCamelCase__: Union[str, Any] =has_been_replaced | _has_been_replaced # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def lowerCAmelCase_ ( __a ) -> List[Any]: """simple docstring""" with init_empty_weights(): lowerCamelCase__: Any =deepcopy(__a ) # this has 0 cost since it is done inside `init_empty_weights` context manager` lowerCamelCase__: str =find_tied_parameters(__a ) # For compatibility with Accelerate < 0.18 if isinstance(__a , __a ): lowerCamelCase__: int =sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() ) else: lowerCamelCase__: str =sum(__a , [] ) lowerCamelCase__: str =len(__a ) > 0 # Check if it is a base model lowerCamelCase__: Optional[Any] =False if hasattr(__a , "base_model_prefix" ): lowerCamelCase__: Union[str, Any] =not hasattr(__a , model.base_model_prefix ) # Ignore this for base models (BertModel, GPT2Model, etc.) if (not has_tied_params) and is_base_model: return [] # otherwise they have an attached head lowerCamelCase__: Optional[int] =list(model.named_children() ) lowerCamelCase__: Optional[int] =[list_modules[-1][0]] # add last module together with tied weights lowerCamelCase__: Union[str, Any] =set(__a ) - set(__a ) lowerCamelCase__: List[str] =list(set(__a ) ) + list(__a ) # remove ".weight" from the keys lowerCamelCase__: List[Any] =[".weight", ".bias"] lowerCamelCase__: Tuple =[] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: lowerCamelCase__: Optional[Any] =name.replace(__a , "" ) filtered_module_names.append(__a ) return filtered_module_names def lowerCAmelCase_ ( __a ) -> Tuple: """simple docstring""" for m in model.modules(): if isinstance(__a , bnb.nn.Linearabit ): return True return False def lowerCAmelCase_ ( __a ) -> List[str]: """simple docstring""" return next(parameter.parameters() ).device def lowerCAmelCase_ ( __a , __a , __a , __a , __a , __a , __a ) -> Any: """simple docstring""" if fpaa_statistics is None: set_module_tensor_to_device(__a , __a , 0 , dtype=__a , value=__a ) lowerCamelCase__: Dict =param_name lowerCamelCase__: Tuple =model if "." in tensor_name: lowerCamelCase__: Any =tensor_name.split("." ) for split in splits[:-1]: lowerCamelCase__: Any =getattr(__a , __a ) if new_module is None: raise ValueError(F"""{module} has no attribute {split}.""" ) lowerCamelCase__: str =new_module lowerCamelCase__: int =splits[-1] # offload weights lowerCamelCase__: str =False offload_weight(module._parameters[tensor_name] , __a , __a , index=__a ) if hasattr(module._parameters[tensor_name] , "SCB" ): offload_weight( module._parameters[tensor_name].SCB , param_name.replace("weight" , "SCB" ) , __a , index=__a , ) else: offload_weight(__a , __a , __a , index=__a ) offload_weight(__a , param_name.replace("weight" , "SCB" ) , __a , index=__a ) set_module_tensor_to_device(__a , __a , "meta" , dtype=__a , value=torch.empty(*param.size() ) )
59
1
from ...configuration_utils import PretrainedConfig from ...utils import logging __A = logging.get_logger(__name__) class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = "timm_backbone" def __init__(self : int , UpperCAmelCase_ : Any=None , UpperCAmelCase_ : Tuple=3 , UpperCAmelCase_ : List[Any]=True , UpperCAmelCase_ : Optional[int]=True , UpperCAmelCase_ : List[str]=None , **UpperCAmelCase_ : Optional[int] , ) ->Union[str, Any]: '''simple docstring''' super().__init__(**UpperCAmelCase_) lowerCamelCase__: int =backbone lowerCamelCase__: Optional[int] =num_channels lowerCamelCase__: Any =features_only lowerCamelCase__: Union[str, Any] =use_pretrained_backbone lowerCamelCase__: str =True lowerCamelCase__: Dict =out_indices if out_indices is not None else (-1,)
59
from __future__ import annotations from math import pi def lowerCAmelCase_ ( __a , __a , __a ) -> dict[str, float]: """simple docstring""" if (inductance, frequency, reactance).count(0 ) != 1: raise ValueError("One and only one argument must be 0" ) if inductance < 0: raise ValueError("Inductance cannot be negative" ) if frequency < 0: raise ValueError("Frequency cannot be negative" ) if reactance < 0: raise ValueError("Inductive reactance cannot be negative" ) if inductance == 0: return {"inductance": reactance / (2 * pi * frequency)} elif frequency == 0: return {"frequency": reactance / (2 * pi * inductance)} elif reactance == 0: return {"reactance": 2 * pi * frequency * inductance} else: raise ValueError("Exactly one argument must be 0" ) if __name__ == "__main__": import doctest doctest.testmod()
59
1
import warnings from ...utils import logging from .image_processing_layoutlmva import LayoutLMvaImageProcessor __A = logging.get_logger(__name__) class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__(self : Optional[int] , *UpperCAmelCase_ : List[str] , **UpperCAmelCase_ : Tuple) ->None: '''simple docstring''' warnings.warn( "The class LayoutLMv2FeatureExtractor is deprecated and will be removed in version 5 of Transformers." " Please use LayoutLMv2ImageProcessor instead." , UpperCAmelCase_ , ) super().__init__(*UpperCAmelCase_ , **UpperCAmelCase_)
59
import pyarrow.parquet as pq import pytest from datasets import Audio, Dataset, DatasetDict, Features, NamedSplit, Sequence, Value, config from datasets.features.image import Image from datasets.io.parquet import ParquetDatasetReader, ParquetDatasetWriter, get_writer_batch_size from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def lowerCAmelCase_ ( __a , __a ) -> List[Any]: """simple docstring""" assert isinstance(__a , __a ) 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 lowerCAmelCase_ ( __a , __a , __a ) -> Any: """simple docstring""" lowerCamelCase__: Any =tmp_path / "cache" lowerCamelCase__: Optional[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(): lowerCamelCase__: Tuple =ParquetDatasetReader(__a , cache_dir=__a , keep_in_memory=__a ).read() _check_parquet_dataset(__a , __a ) @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 lowerCAmelCase_ ( __a , __a , __a ) -> List[str]: """simple docstring""" lowerCamelCase__: int =tmp_path / "cache" lowerCamelCase__: Tuple ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: Union[str, Any] =features.copy() if features else default_expected_features lowerCamelCase__: Optional[int] =( Features({feature: Value(__a ) for feature, dtype in features.items()} ) if features is not None else None ) lowerCamelCase__: int =ParquetDatasetReader(__a , features=__a , cache_dir=__a ).read() _check_parquet_dataset(__a , __a ) @pytest.mark.parametrize("split" , [None, NamedSplit("train" ), "train", "test"] ) def lowerCAmelCase_ ( __a , __a , __a ) -> Any: """simple docstring""" lowerCamelCase__: Any =tmp_path / "cache" lowerCamelCase__: Optional[Any] ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: Optional[Any] =ParquetDatasetReader(__a , cache_dir=__a , split=__a ).read() _check_parquet_dataset(__a , __a ) assert dataset.split == split if split else "train" @pytest.mark.parametrize("path_type" , [str, list] ) def lowerCAmelCase_ ( __a , __a , __a ) -> int: """simple docstring""" if issubclass(__a , __a ): lowerCamelCase__: List[Any] =parquet_path elif issubclass(__a , __a ): lowerCamelCase__: str =[parquet_path] lowerCamelCase__: Tuple =tmp_path / "cache" lowerCamelCase__: Optional[Any] ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: int =ParquetDatasetReader(__a , cache_dir=__a ).read() _check_parquet_dataset(__a , __a ) def lowerCAmelCase_ ( __a , __a , __a=("train",) ) -> Dict: """simple docstring""" assert isinstance(__a , __a ) for split in splits: lowerCamelCase__: Tuple =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 lowerCAmelCase_ ( __a , __a , __a ) -> Any: """simple docstring""" lowerCamelCase__: List[Any] =tmp_path / "cache" lowerCamelCase__: Optional[Any] ={"col_1": "string", "col_2": "int64", "col_3": "float64"} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): lowerCamelCase__: Tuple =ParquetDatasetReader( {"train": parquet_path} , cache_dir=__a , keep_in_memory=__a ).read() _check_parquet_datasetdict(__a , __a ) @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 lowerCAmelCase_ ( __a , __a , __a ) -> Optional[Any]: """simple docstring""" lowerCamelCase__: Tuple =tmp_path / "cache" lowerCamelCase__: Optional[int] ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: List[Any] =features.copy() if features else default_expected_features lowerCamelCase__: int =( Features({feature: Value(__a ) for feature, dtype in features.items()} ) if features is not None else None ) lowerCamelCase__: Optional[Any] =ParquetDatasetReader({"train": parquet_path} , features=__a , cache_dir=__a ).read() _check_parquet_datasetdict(__a , __a ) @pytest.mark.parametrize("split" , [None, NamedSplit("train" ), "train", "test"] ) def lowerCAmelCase_ ( __a , __a , __a ) -> Union[str, Any]: """simple docstring""" if split: lowerCamelCase__: Any ={split: parquet_path} else: lowerCamelCase__: int ="train" lowerCamelCase__: Any ={"train": parquet_path, "test": parquet_path} lowerCamelCase__: str =tmp_path / "cache" lowerCamelCase__: Any ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: int =ParquetDatasetReader(__a , cache_dir=__a ).read() _check_parquet_datasetdict(__a , __a , splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() ) def lowerCAmelCase_ ( __a , __a ) -> int: """simple docstring""" lowerCamelCase__: List[str] =ParquetDatasetWriter(__a , tmp_path / "foo.parquet" ) assert writer.write() > 0 lowerCamelCase__: List[str] =pq.ParquetFile(tmp_path / "foo.parquet" ) lowerCamelCase__: List[str] =pf.read() assert dataset.data.table == output_table def lowerCAmelCase_ ( __a , __a ) -> List[str]: """simple docstring""" lowerCamelCase__: List[str] =str(shared_datadir / "test_image_rgb.jpg" ) lowerCamelCase__: Union[str, Any] ={"image": [image_path]} lowerCamelCase__: Optional[Any] =Features({"image": Image()} ) lowerCamelCase__: Optional[int] =Dataset.from_dict(__a , features=__a ) lowerCamelCase__: Optional[int] =ParquetDatasetWriter(__a , tmp_path / "foo.parquet" ) assert writer.write() > 0 lowerCamelCase__: Dict =Dataset.from_parquet(str(tmp_path / "foo.parquet" ) ) assert dataset.features == reloaded_dataset.features lowerCamelCase__: Optional[Any] =ParquetDatasetReader(str(tmp_path / "foo.parquet" ) , streaming=__a ).read() assert dataset.features == reloaded_iterable_dataset.features @pytest.mark.parametrize( "feature, expected" , [ (Features({"foo": Value("int32" )} ), None), (Features({"image": Image(), "foo": Value("int32" )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS), (Features({"nested": Sequence(Audio() )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS), ] , ) def lowerCAmelCase_ ( __a , __a ) -> Optional[Any]: """simple docstring""" assert get_writer_batch_size(__a ) == expected
59
1
import argparse import os # New Code # import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils import find_executable_batch_size ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to ensure out-of-memory errors never # interrupt training, and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## __A = 16 __A = 32 def lowerCAmelCase_ ( __a , __a = 16 ) -> int: """simple docstring""" lowerCamelCase__: List[str] =AutoTokenizer.from_pretrained("bert-base-cased" ) lowerCamelCase__: Dict =load_dataset("glue" , "mrpc" ) def tokenize_function(__a ): # max_length=None => use the model max length (it's actually the default) lowerCamelCase__: Tuple =tokenizer(examples["sentence1"] , examples["sentence2"] , truncation=__a , max_length=__a ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): lowerCamelCase__: Any =datasets.map( __a , batched=__a , remove_columns=["idx", "sentence1", "sentence2"] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library lowerCamelCase__: List[str] =tokenized_datasets.rename_column("label" , "labels" ) def collate_fn(__a ): # On TPU it's best to pad everything to the same length or training will be very slow. lowerCamelCase__: Dict =128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": lowerCamelCase__: Union[str, Any] =16 elif accelerator.mixed_precision != "no": lowerCamelCase__: Optional[Any] =8 else: lowerCamelCase__: List[str] =None return tokenizer.pad( __a , padding="longest" , max_length=__a , pad_to_multiple_of=__a , return_tensors="pt" , ) # Instantiate dataloaders. lowerCamelCase__: Optional[Any] =DataLoader( tokenized_datasets["train"] , shuffle=__a , collate_fn=__a , batch_size=__a ) lowerCamelCase__: List[str] =DataLoader( tokenized_datasets["validation"] , shuffle=__a , collate_fn=__a , batch_size=__a ) return train_dataloader, eval_dataloader # For testing only if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": from accelerate.test_utils.training import mocked_dataloaders __A = mocked_dataloaders # noqa: F811 def lowerCAmelCase_ ( __a , __a ) -> int: """simple docstring""" if os.environ.get("TESTING_MOCKED_DATALOADERS" , __a ) == "1": lowerCamelCase__: int =2 # Initialize accelerator lowerCamelCase__: Any =Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs lowerCamelCase__: Tuple =config["lr"] lowerCamelCase__: List[str] =int(config["num_epochs"] ) lowerCamelCase__: List[str] =int(config["seed"] ) lowerCamelCase__: Optional[int] =int(config["batch_size"] ) lowerCamelCase__: Any =evaluate.load("glue" , "mrpc" ) # New Code # # We now can define an inner training loop function. It should take a batch size as the only parameter, # and build the dataloaders in there. # It also gets our decorator @find_executable_batch_size(starting_batch_size=__a ) def inner_training_loop(__a ): # And now just move everything below under this function # We need to bring in the Accelerator object from earlier nonlocal accelerator # And reset all of its attributes that could hold onto any memory: accelerator.free_memory() # Then we can declare the model, optimizer, and everything else: set_seed(__a ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) lowerCamelCase__: str =AutoModelForSequenceClassification.from_pretrained("bert-base-cased" , return_dict=__a ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). lowerCamelCase__: str =model.to(accelerator.device ) # Instantiate optimizer lowerCamelCase__: Union[str, Any] =AdamW(params=model.parameters() , lr=__a ) lowerCamelCase__ , lowerCamelCase__: List[Any] =get_dataloaders(__a , __a ) # Instantiate scheduler lowerCamelCase__: List[str] =get_linear_schedule_with_warmup( optimizer=__a , num_warmup_steps=100 , num_training_steps=(len(__a ) * num_epochs) , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Optional[int] =accelerator.prepare( __a , __a , __a , __a , __a ) # Now we train the model for epoch in range(__a ): model.train() for step, batch in enumerate(__a ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) lowerCamelCase__: str =model(**__a ) lowerCamelCase__: Any =outputs.loss accelerator.backward(__a ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(__a ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): lowerCamelCase__: Any =model(**__a ) lowerCamelCase__: Dict =outputs.logits.argmax(dim=-1 ) lowerCamelCase__ , lowerCamelCase__: Optional[Any] =accelerator.gather_for_metrics((predictions, batch["labels"]) ) metric.add_batch( predictions=__a , references=__a , ) lowerCamelCase__: List[str] =metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F"""epoch {epoch}:""" , __a ) # New Code # # And call it at the end with no arguments # Note: You could also refactor this outside of your training loop function inner_training_loop() def lowerCAmelCase_ ( ) -> Union[str, Any]: """simple docstring""" lowerCamelCase__: Optional[int] =argparse.ArgumentParser(description="Simple example of training script." ) parser.add_argument( "--mixed_precision" , type=__a , default=__a , choices=["no", "fp16", "bf16", "fp8"] , help="Whether to use mixed precision. Choose" "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10." "and an Nvidia Ampere GPU." , ) parser.add_argument("--cpu" , action="store_true" , help="If passed, will train on the CPU." ) lowerCamelCase__: List[Any] =parser.parse_args() lowerCamelCase__: Optional[int] ={"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16} training_function(__a , __a ) if __name__ == "__main__": main()
59
import unittest from transformers.models.xlm_prophetnet.tokenization_xlm_prophetnet import SPIECE_UNDERLINE, XLMProphetNetTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin __A = get_tests_dir("fixtures/test_sentencepiece.model") @require_sentencepiece class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowercase_ = XLMProphetNetTokenizer lowercase_ = False lowercase_ = True def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Optional[Any]: '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing lowerCamelCase__: Any =XLMProphetNetTokenizer(UpperCAmelCase_ , keep_accents=UpperCAmelCase_) tokenizer.save_pretrained(self.tmpdirname) def SCREAMING_SNAKE_CASE_ (self : str) ->str: '''simple docstring''' lowerCamelCase__: List[Any] ="[PAD]" lowerCamelCase__: Tuple =0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCAmelCase_) , UpperCAmelCase_) self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCAmelCase_) , UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Dict) ->int: '''simple docstring''' lowerCamelCase__: List[Any] =list(self.get_tokenizer().get_vocab().keys()) self.assertEqual(vocab_keys[0] , "[PAD]") self.assertEqual(vocab_keys[1] , "[CLS]") self.assertEqual(vocab_keys[-1] , "j") self.assertEqual(len(UpperCAmelCase_) , 1_012) def SCREAMING_SNAKE_CASE_ (self : Dict) ->Union[str, Any]: '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 1_012) def SCREAMING_SNAKE_CASE_ (self : Any) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Optional[Any] =XLMProphetNetTokenizer(UpperCAmelCase_ , keep_accents=UpperCAmelCase_) lowerCamelCase__: 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]] , ) lowerCamelCase__: Optional[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", "é", ".", ] , ) lowerCamelCase__: Any =tokenizer.convert_tokens_to_ids(UpperCAmelCase_) self.assertListEqual( UpperCAmelCase_ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, -9, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, -9, 4] ] , ) lowerCamelCase__: 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]", ".", ] , ) @cached_property def SCREAMING_SNAKE_CASE_ (self : Any) ->int: '''simple docstring''' return XLMProphetNetTokenizer.from_pretrained("microsoft/xprophetnet-large-wiki100-cased") @slow def SCREAMING_SNAKE_CASE_ (self : List[str]) ->List[str]: '''simple docstring''' lowerCamelCase__: Optional[int] ="Hello World!" lowerCamelCase__: Dict =[35_389, 6_672, 49, 2] self.assertListEqual(UpperCAmelCase_ , self.big_tokenizer.encode(UpperCAmelCase_)) @slow def SCREAMING_SNAKE_CASE_ (self : int) ->Union[str, Any]: '''simple docstring''' lowerCamelCase__: Any ={"input_ids": [[11_073, 82_783, 18, 26, 82_783, 549, 51_540, 248, 17_209, 1_301, 217, 20, 215_186, 1_325, 147, 17_209, 1_301, 217, 20, 56_370, 53, 122_020, 20, 16_477, 27, 87_355, 4_548, 20, 4_728, 78_392, 17, 159_969, 18, 26, 24_491, 629, 15, 538, 22_704, 5_439, 15, 2_788, 24_491, 9_885, 15, 43_534, 605, 15, 814, 18_403, 33_200, 29, 15, 43_534, 24_458, 12_410, 111, 24_966, 83_669, 9_637, 144_068, 26, 850, 22_346, 27, 147, 24_966, 83_669, 83_490, 26, 39_113, 735, 27, 689, 656, 2_800, 1_339, 4_600, 53, 122_020, 115_785, 34, 816, 1_339, 46_887, 18, 147, 53_905, 1_951, 42_238, 41_170, 17_732, 834, 436, 15, 27_523, 98_733, 217, 147, 5_542, 4_981, 930, 17_347, 16, 2], [20_091, 629, 94, 82_786, 58, 490, 20, 1_528, 84, 53_905, 344, 80_592, 110_128, 18_822, 5_267, 1_306, 62, 152_537, 308, 7_997, 401, 124_427, 549, 35_442, 225, 109, 15_055, 25_748, 147, 7_119, 43_712, 34, 767, 135_366, 18, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [592, 63_784, 119_466, 17, 147_808, 88_214, 18, 656, 81, 32, 3_296, 10_280, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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="microsoft/xprophetnet-large-wiki100-cased" , revision="1acad1643ddd54a44df6a1b797ada8373685d90e" , )
59
1
from ...configuration_utils import PretrainedConfig from ...utils import logging __A = logging.get_logger(__name__) __A = { "MIT/ast-finetuned-audioset-10-10-0.4593": ( "https://huggingface.co/MIT/ast-finetuned-audioset-10-10-0.4593/resolve/main/config.json" ), } class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = "audio-spectrogram-transformer" def __init__(self : Optional[int] , UpperCAmelCase_ : Optional[Any]=768 , UpperCAmelCase_ : Optional[int]=12 , UpperCAmelCase_ : Any=12 , UpperCAmelCase_ : List[Any]=3_072 , UpperCAmelCase_ : Optional[int]="gelu" , UpperCAmelCase_ : Optional[int]=0.0 , UpperCAmelCase_ : Tuple=0.0 , UpperCAmelCase_ : str=0.02 , UpperCAmelCase_ : Optional[int]=1E-1_2 , UpperCAmelCase_ : str=16 , UpperCAmelCase_ : List[str]=True , UpperCAmelCase_ : Any=10 , UpperCAmelCase_ : Optional[Any]=10 , UpperCAmelCase_ : Dict=1_024 , UpperCAmelCase_ : Dict=128 , **UpperCAmelCase_ : str , ) ->int: '''simple docstring''' super().__init__(**UpperCAmelCase_) lowerCamelCase__: Optional[Any] =hidden_size lowerCamelCase__: Union[str, Any] =num_hidden_layers lowerCamelCase__: Optional[int] =num_attention_heads lowerCamelCase__: Optional[int] =intermediate_size lowerCamelCase__: Tuple =hidden_act lowerCamelCase__: Any =hidden_dropout_prob lowerCamelCase__: Any =attention_probs_dropout_prob lowerCamelCase__: Union[str, Any] =initializer_range lowerCamelCase__: int =layer_norm_eps lowerCamelCase__: Dict =patch_size lowerCamelCase__: Tuple =qkv_bias lowerCamelCase__: Tuple =frequency_stride lowerCamelCase__: Tuple =time_stride lowerCamelCase__: str =max_length lowerCamelCase__: int =num_mel_bins
59
import os import shutil import tempfile import unittest import numpy as np from transformers import AutoTokenizer, BarkProcessor from transformers.testing_utils import require_torch, slow @require_torch class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ (self : List[str]) ->str: '''simple docstring''' lowerCamelCase__: Union[str, Any] ="ylacombe/bark-small" lowerCamelCase__: Tuple =tempfile.mkdtemp() lowerCamelCase__: Tuple ="en_speaker_1" lowerCamelCase__: Optional[int] ="This is a test string" lowerCamelCase__: List[str] ="speaker_embeddings_path.json" lowerCamelCase__: int ="speaker_embeddings" def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , **UpperCAmelCase_ : Any) ->Tuple: '''simple docstring''' return AutoTokenizer.from_pretrained(self.checkpoint , **UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[str]) ->Union[str, Any]: '''simple docstring''' shutil.rmtree(self.tmpdirname) def SCREAMING_SNAKE_CASE_ (self : int) ->Any: '''simple docstring''' lowerCamelCase__: List[Any] =self.get_tokenizer() lowerCamelCase__: List[str] =BarkProcessor(tokenizer=UpperCAmelCase_) processor.save_pretrained(self.tmpdirname) lowerCamelCase__: Dict =BarkProcessor.from_pretrained(self.tmpdirname) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab()) @slow def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Tuple: '''simple docstring''' lowerCamelCase__: Tuple =BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) processor.save_pretrained( self.tmpdirname , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , speaker_embeddings_directory=self.speaker_embeddings_directory , ) lowerCamelCase__: Dict =self.get_tokenizer(bos_token="(BOS)" , eos_token="(EOS)") lowerCamelCase__: Any =BarkProcessor.from_pretrained( self.tmpdirname , self.speaker_embeddings_dict_path , bos_token="(BOS)" , eos_token="(EOS)" , ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab()) def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->int: '''simple docstring''' lowerCamelCase__: Any =BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) lowerCamelCase__: List[str] =35 lowerCamelCase__: Optional[Any] =2 lowerCamelCase__: Optional[Any] =8 lowerCamelCase__: Optional[int] ={ "semantic_prompt": np.ones(UpperCAmelCase_), "coarse_prompt": np.ones((nb_codebooks_coarse, seq_len)), "fine_prompt": np.ones((nb_codebooks_total, seq_len)), } # test providing already loaded voice_preset lowerCamelCase__: Any =processor(text=self.input_string , voice_preset=UpperCAmelCase_) lowerCamelCase__: int =inputs["history_prompt"] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(UpperCAmelCase_ , np.array([])).tolist()) # test loading voice preset from npz file lowerCamelCase__: Union[str, Any] =os.path.join(self.tmpdirname , "file.npz") np.savez(UpperCAmelCase_ , **UpperCAmelCase_) lowerCamelCase__: Tuple =processor(text=self.input_string , voice_preset=UpperCAmelCase_) lowerCamelCase__: Optional[Any] =inputs["history_prompt"] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(UpperCAmelCase_ , np.array([])).tolist()) # test loading voice preset from the hub lowerCamelCase__: Any =processor(text=self.input_string , voice_preset=self.voice_preset) def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Union[str, Any]: '''simple docstring''' lowerCamelCase__: str =self.get_tokenizer() lowerCamelCase__: Dict =BarkProcessor(tokenizer=UpperCAmelCase_) lowerCamelCase__: List[Any] =processor(text=self.input_string) lowerCamelCase__: Optional[int] =tokenizer( self.input_string , padding="max_length" , max_length=256 , add_special_tokens=UpperCAmelCase_ , return_attention_mask=UpperCAmelCase_ , return_token_type_ids=UpperCAmelCase_ , ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key].squeeze().tolist())
59
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) __A = { "configuration_layoutlmv3": [ "LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP", "LayoutLMv3Config", "LayoutLMv3OnnxConfig", ], "processing_layoutlmv3": ["LayoutLMv3Processor"], "tokenization_layoutlmv3": ["LayoutLMv3Tokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ["LayoutLMv3TokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ "LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST", "LayoutLMv3ForQuestionAnswering", "LayoutLMv3ForSequenceClassification", "LayoutLMv3ForTokenClassification", "LayoutLMv3Model", "LayoutLMv3PreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ "TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST", "TFLayoutLMv3ForQuestionAnswering", "TFLayoutLMv3ForSequenceClassification", "TFLayoutLMv3ForTokenClassification", "TFLayoutLMv3Model", "TFLayoutLMv3PreTrainedModel", ] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ["LayoutLMv3FeatureExtractor"] __A = ["LayoutLMv3ImageProcessor"] if TYPE_CHECKING: from .configuration_layoutlmva import ( LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP, LayoutLMvaConfig, LayoutLMvaOnnxConfig, ) from .processing_layoutlmva import LayoutLMvaProcessor from .tokenization_layoutlmva import LayoutLMvaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutlmva_fast import LayoutLMvaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_layoutlmva import ( LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, LayoutLMvaForQuestionAnswering, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaModel, LayoutLMvaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_layoutlmva import ( TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, TFLayoutLMvaModel, TFLayoutLMvaPreTrainedModel, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_layoutlmva import LayoutLMvaFeatureExtractor from .image_processing_layoutlmva import LayoutLMvaImageProcessor else: import sys __A = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
59
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = ["image_processor", "tokenizer"] lowercase_ = "CLIPImageProcessor" lowercase_ = ("XLMRobertaTokenizer", "XLMRobertaTokenizerFast") def __init__(self : List[Any] , UpperCAmelCase_ : int=None , UpperCAmelCase_ : List[Any]=None , **UpperCAmelCase_ : List[str]) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Union[str, Any] =None if "feature_extractor" in kwargs: warnings.warn( "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`" " instead." , UpperCAmelCase_ , ) lowerCamelCase__: int =kwargs.pop("feature_extractor") lowerCamelCase__: int =image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("You need to specify an `image_processor`.") if tokenizer is None: raise ValueError("You need to specify a `tokenizer`.") super().__init__(UpperCAmelCase_ , UpperCAmelCase_) def __call__(self : List[Any] , UpperCAmelCase_ : str=None , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : int=None , **UpperCAmelCase_ : Any) ->Union[str, Any]: '''simple docstring''' if text is None and images is None: raise ValueError("You have to specify either text or images. Both cannot be none.") if text is not None: lowerCamelCase__: List[Any] =self.tokenizer(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_) if images is not None: lowerCamelCase__: int =self.image_processor(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_) if text is not None and images is not None: lowerCamelCase__: str =image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**UpperCAmelCase_) , tensor_type=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[str] , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : Optional[Any]) ->Dict: '''simple docstring''' return self.tokenizer.batch_decode(*UpperCAmelCase_ , **UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Optional[int] , *UpperCAmelCase_ : int , **UpperCAmelCase_ : Any) ->Optional[Any]: '''simple docstring''' return self.tokenizer.decode(*UpperCAmelCase_ , **UpperCAmelCase_) @property def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Optional[Any] =self.tokenizer.model_input_names lowerCamelCase__: str =self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
59
1
from __future__ import annotations import typing from collections import Counter def lowerCAmelCase_ ( __a ) -> typing.Counter[int]: """simple docstring""" lowerCamelCase__: typing.Counter[int] =Counter() for base in range(1 , max_perimeter + 1 ): for perpendicular in range(__a , max_perimeter + 1 ): lowerCamelCase__: Dict =(base * base + perpendicular * perpendicular) ** 0.5 if hypotenuse == int(__a ): lowerCamelCase__: str =int(base + perpendicular + hypotenuse ) if perimeter > max_perimeter: continue triplets[perimeter] += 1 return triplets def lowerCAmelCase_ ( __a = 1000 ) -> int: """simple docstring""" lowerCamelCase__: Union[str, Any] =pythagorean_triple(__a ) return triplets.most_common(1 )[0][0] if __name__ == "__main__": print(f'Perimeter {solution()} has maximum solutions')
59
from datetime import datetime import matplotlib.pyplot as plt import torch def lowerCAmelCase_ ( __a ) -> Any: """simple docstring""" for param in module.parameters(): lowerCamelCase__: Tuple =False def lowerCAmelCase_ ( ) -> Optional[int]: """simple docstring""" lowerCamelCase__: List[str] ="cuda" if torch.cuda.is_available() else "cpu" if torch.backends.mps.is_available() and torch.backends.mps.is_built(): lowerCamelCase__: str ="mps" if device == "mps": print( "WARNING: MPS currently doesn't seem to work, and messes up backpropagation without any visible torch" " errors. I recommend using CUDA on a colab notebook or CPU instead if you're facing inexplicable issues" " with generations." ) return device def lowerCAmelCase_ ( __a ) -> List[str]: """simple docstring""" lowerCamelCase__: Union[str, Any] =plt.imshow(__a ) fig.axes.get_xaxis().set_visible(__a ) fig.axes.get_yaxis().set_visible(__a ) plt.show() def lowerCAmelCase_ ( ) -> Optional[Any]: """simple docstring""" lowerCamelCase__: List[str] =datetime.now() lowerCamelCase__: str =current_time.strftime("%H:%M:%S" ) return timestamp
59
1
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING __A = logging.get_logger(__name__) __A = { "ut/deta": "https://huggingface.co/ut/deta/resolve/main/config.json", } class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = "deta" lowercase_ = { "hidden_size": "d_model", "num_attention_heads": "encoder_attention_heads", } def __init__(self : Optional[Any] , UpperCAmelCase_ : int=None , UpperCAmelCase_ : Optional[Any]=900 , UpperCAmelCase_ : Dict=2_048 , UpperCAmelCase_ : int=6 , UpperCAmelCase_ : List[str]=2_048 , UpperCAmelCase_ : Optional[Any]=8 , UpperCAmelCase_ : str=6 , UpperCAmelCase_ : Optional[Any]=1_024 , UpperCAmelCase_ : Union[str, Any]=8 , UpperCAmelCase_ : str=0.0 , UpperCAmelCase_ : str=True , UpperCAmelCase_ : List[str]="relu" , UpperCAmelCase_ : Optional[int]=256 , UpperCAmelCase_ : int=0.1 , UpperCAmelCase_ : Optional[int]=0.0 , UpperCAmelCase_ : Optional[int]=0.0 , UpperCAmelCase_ : Dict=0.02 , UpperCAmelCase_ : Any=1.0 , UpperCAmelCase_ : List[str]=True , UpperCAmelCase_ : Union[str, Any]=False , UpperCAmelCase_ : List[str]="sine" , UpperCAmelCase_ : Any=5 , UpperCAmelCase_ : Dict=4 , UpperCAmelCase_ : Tuple=4 , UpperCAmelCase_ : str=True , UpperCAmelCase_ : List[Any]=300 , UpperCAmelCase_ : Optional[int]=True , UpperCAmelCase_ : str=True , UpperCAmelCase_ : List[str]=1 , UpperCAmelCase_ : Any=5 , UpperCAmelCase_ : int=2 , UpperCAmelCase_ : Optional[int]=1 , UpperCAmelCase_ : int=1 , UpperCAmelCase_ : Any=5 , UpperCAmelCase_ : str=2 , UpperCAmelCase_ : int=0.1 , UpperCAmelCase_ : Dict=0.25 , **UpperCAmelCase_ : Dict , ) ->int: '''simple docstring''' if backbone_config is None: logger.info("`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.") lowerCamelCase__: Any =CONFIG_MAPPING["resnet"](out_features=["stage2", "stage3", "stage4"]) else: if isinstance(UpperCAmelCase_ , UpperCAmelCase_): lowerCamelCase__: List[str] =backbone_config.pop("model_type") lowerCamelCase__: Any =CONFIG_MAPPING[backbone_model_type] lowerCamelCase__: Any =config_class.from_dict(UpperCAmelCase_) lowerCamelCase__: Any =backbone_config lowerCamelCase__: Optional[Any] =num_queries lowerCamelCase__: Any =max_position_embeddings lowerCamelCase__: List[Any] =d_model lowerCamelCase__: Dict =encoder_ffn_dim lowerCamelCase__: Any =encoder_layers lowerCamelCase__: List[Any] =encoder_attention_heads lowerCamelCase__: Dict =decoder_ffn_dim lowerCamelCase__: Any =decoder_layers lowerCamelCase__: Any =decoder_attention_heads lowerCamelCase__: Any =dropout lowerCamelCase__: Optional[int] =attention_dropout lowerCamelCase__: str =activation_dropout lowerCamelCase__: Tuple =activation_function lowerCamelCase__: int =init_std lowerCamelCase__: str =init_xavier_std lowerCamelCase__: List[Any] =encoder_layerdrop lowerCamelCase__: Optional[Any] =auxiliary_loss lowerCamelCase__: Optional[int] =position_embedding_type # deformable attributes lowerCamelCase__: str =num_feature_levels lowerCamelCase__: List[str] =encoder_n_points lowerCamelCase__: Optional[int] =decoder_n_points lowerCamelCase__: Optional[Any] =two_stage lowerCamelCase__: Optional[int] =two_stage_num_proposals lowerCamelCase__: str =with_box_refine lowerCamelCase__: Union[str, Any] =assign_first_stage if two_stage is True and with_box_refine is False: raise ValueError("If two_stage is True, with_box_refine must be True.") # Hungarian matcher lowerCamelCase__: Optional[Any] =class_cost lowerCamelCase__: Tuple =bbox_cost lowerCamelCase__: Tuple =giou_cost # Loss coefficients lowerCamelCase__: List[str] =mask_loss_coefficient lowerCamelCase__: int =dice_loss_coefficient lowerCamelCase__: List[Any] =bbox_loss_coefficient lowerCamelCase__: Any =giou_loss_coefficient lowerCamelCase__: Optional[Any] =eos_coefficient lowerCamelCase__: List[Any] =focal_alpha super().__init__(is_encoder_decoder=UpperCAmelCase_ , **UpperCAmelCase_) @property def SCREAMING_SNAKE_CASE_ (self : List[str]) ->int: '''simple docstring''' return self.encoder_attention_heads @property def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->int: '''simple docstring''' return self.d_model def SCREAMING_SNAKE_CASE_ (self : Dict) ->Dict: '''simple docstring''' lowerCamelCase__: Dict =copy.deepcopy(self.__dict__) lowerCamelCase__: Any =self.backbone_config.to_dict() lowerCamelCase__: str =self.__class__.model_type return output
59
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __A = { "configuration_pix2struct": [ "PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP", "Pix2StructConfig", "Pix2StructTextConfig", "Pix2StructVisionConfig", ], "processing_pix2struct": ["Pix2StructProcessor"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ["Pix2StructImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ "PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST", "Pix2StructPreTrainedModel", "Pix2StructForConditionalGeneration", "Pix2StructVisionModel", "Pix2StructTextModel", ] if TYPE_CHECKING: from .configuration_pixastruct import ( PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP, PixaStructConfig, PixaStructTextConfig, PixaStructVisionConfig, ) from .processing_pixastruct import PixaStructProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_pixastruct import PixaStructImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_pixastruct import ( PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST, PixaStructForConditionalGeneration, PixaStructPreTrainedModel, PixaStructTextModel, PixaStructVisionModel, ) else: import sys __A = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
59
1
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __A = logging.get_logger(__name__) __A = { "google/bigbird-roberta-base": "https://huggingface.co/google/bigbird-roberta-base/resolve/main/config.json", "google/bigbird-roberta-large": "https://huggingface.co/google/bigbird-roberta-large/resolve/main/config.json", "google/bigbird-base-trivia-itc": "https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/config.json", # See all BigBird models at https://huggingface.co/models?filter=big_bird } class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = "big_bird" def __init__(self : List[str] , UpperCAmelCase_ : int=50_358 , UpperCAmelCase_ : List[str]=768 , UpperCAmelCase_ : Optional[int]=12 , UpperCAmelCase_ : Union[str, Any]=12 , UpperCAmelCase_ : Optional[Any]=3_072 , UpperCAmelCase_ : Union[str, Any]="gelu_new" , UpperCAmelCase_ : Any=0.1 , UpperCAmelCase_ : List[Any]=0.1 , UpperCAmelCase_ : Optional[Any]=4_096 , UpperCAmelCase_ : Union[str, Any]=2 , UpperCAmelCase_ : Optional[Any]=0.02 , UpperCAmelCase_ : Tuple=1E-1_2 , UpperCAmelCase_ : Optional[Any]=True , UpperCAmelCase_ : Dict=0 , UpperCAmelCase_ : List[str]=1 , UpperCAmelCase_ : Dict=2 , UpperCAmelCase_ : Optional[Any]=66 , UpperCAmelCase_ : Optional[Any]="block_sparse" , UpperCAmelCase_ : Any=True , UpperCAmelCase_ : List[str]=False , UpperCAmelCase_ : Optional[Any]=64 , UpperCAmelCase_ : List[Any]=3 , UpperCAmelCase_ : int=None , **UpperCAmelCase_ : Optional[Any] , ) ->Dict: '''simple docstring''' super().__init__( pad_token_id=UpperCAmelCase_ , bos_token_id=UpperCAmelCase_ , eos_token_id=UpperCAmelCase_ , sep_token_id=UpperCAmelCase_ , **UpperCAmelCase_ , ) lowerCamelCase__: List[Any] =vocab_size lowerCamelCase__: str =max_position_embeddings lowerCamelCase__: Union[str, Any] =hidden_size lowerCamelCase__: Optional[Any] =num_hidden_layers lowerCamelCase__: Union[str, Any] =num_attention_heads lowerCamelCase__: Optional[Any] =intermediate_size lowerCamelCase__: Dict =hidden_act lowerCamelCase__: List[str] =hidden_dropout_prob lowerCamelCase__: Optional[int] =attention_probs_dropout_prob lowerCamelCase__: List[Any] =initializer_range lowerCamelCase__: Union[str, Any] =type_vocab_size lowerCamelCase__: Any =layer_norm_eps lowerCamelCase__: Tuple =use_cache lowerCamelCase__: Optional[int] =rescale_embeddings lowerCamelCase__: int =attention_type lowerCamelCase__: List[str] =use_bias lowerCamelCase__: int =block_size lowerCamelCase__: Tuple =num_random_blocks lowerCamelCase__: Union[str, Any] =classifier_dropout class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' @property def SCREAMING_SNAKE_CASE_ (self : Union[str, Any]) ->Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task == "multiple-choice": lowerCamelCase__: Optional[int] ={0: "batch", 1: "choice", 2: "sequence"} else: lowerCamelCase__: str ={0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ])
59
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_distilbert import DistilBertTokenizer __A = logging.get_logger(__name__) __A = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} __A = { "vocab_file": { "distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/vocab.txt", "distilbert-base-uncased-distilled-squad": ( "https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/vocab.txt" ), "distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/vocab.txt", "distilbert-base-cased-distilled-squad": ( "https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/vocab.txt" ), "distilbert-base-german-cased": "https://huggingface.co/distilbert-base-german-cased/resolve/main/vocab.txt", "distilbert-base-multilingual-cased": ( "https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/vocab.txt" ), }, "tokenizer_file": { "distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/tokenizer.json", "distilbert-base-uncased-distilled-squad": ( "https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/tokenizer.json" ), "distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/tokenizer.json", "distilbert-base-cased-distilled-squad": ( "https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/tokenizer.json" ), "distilbert-base-german-cased": ( "https://huggingface.co/distilbert-base-german-cased/resolve/main/tokenizer.json" ), "distilbert-base-multilingual-cased": ( "https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/tokenizer.json" ), }, } __A = { "distilbert-base-uncased": 512, "distilbert-base-uncased-distilled-squad": 512, "distilbert-base-cased": 512, "distilbert-base-cased-distilled-squad": 512, "distilbert-base-german-cased": 512, "distilbert-base-multilingual-cased": 512, } __A = { "distilbert-base-uncased": {"do_lower_case": True}, "distilbert-base-uncased-distilled-squad": {"do_lower_case": True}, "distilbert-base-cased": {"do_lower_case": False}, "distilbert-base-cased-distilled-squad": {"do_lower_case": False}, "distilbert-base-german-cased": {"do_lower_case": False}, "distilbert-base-multilingual-cased": {"do_lower_case": False}, } class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = VOCAB_FILES_NAMES lowercase_ = PRETRAINED_VOCAB_FILES_MAP lowercase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase_ = PRETRAINED_INIT_CONFIGURATION lowercase_ = ["input_ids", "attention_mask"] lowercase_ = DistilBertTokenizer def __init__(self : Tuple , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : int=None , UpperCAmelCase_ : Any=True , UpperCAmelCase_ : List[Any]="[UNK]" , UpperCAmelCase_ : Dict="[SEP]" , UpperCAmelCase_ : Dict="[PAD]" , UpperCAmelCase_ : Optional[int]="[CLS]" , UpperCAmelCase_ : str="[MASK]" , UpperCAmelCase_ : Any=True , UpperCAmelCase_ : List[str]=None , **UpperCAmelCase_ : List[str] , ) ->str: '''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_ , ) lowerCamelCase__: Union[str, Any] =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 ): lowerCamelCase__: List[str] =getattr(UpperCAmelCase_ , normalizer_state.pop("type")) lowerCamelCase__: Optional[int] =do_lower_case lowerCamelCase__: int =strip_accents lowerCamelCase__: Any =tokenize_chinese_chars lowerCamelCase__: Any =normalizer_class(**UpperCAmelCase_) lowerCamelCase__: str =do_lower_case def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : int , UpperCAmelCase_ : Union[str, Any]=None) ->Dict: '''simple docstring''' lowerCamelCase__: str =[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 SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None) ->List[int]: '''simple docstring''' lowerCamelCase__: str =[self.sep_token_id] lowerCamelCase__: str =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep) * [0] return len(cls + token_ids_a + sep) * [0] + len(token_ids_a + sep) * [1] def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] = None) ->Tuple[str]: '''simple docstring''' lowerCamelCase__: str =self._tokenizer.model.save(UpperCAmelCase_ , name=UpperCAmelCase_) return tuple(UpperCAmelCase_)
59
1
from transformers import BertTokenizerFast from .custom_tokenization import CustomTokenizer class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = CustomTokenizer pass
59
import operator as op def lowerCAmelCase_ ( __a ) -> Tuple: """simple docstring""" lowerCamelCase__: Optional[Any] =[] lowerCamelCase__: Tuple =lambda __a , __a : int(x / y ) # noqa: E731 integer division operation lowerCamelCase__: Tuple ={ "^": op.pow, "*": op.mul, "/": div, "+": op.add, "-": op.sub, } # operators & their respective operation # print table header print("Symbol".center(8 ) , "Action".center(12 ) , "Stack" , sep=" | " ) print("-" * (30 + len(__a )) ) for x in post_fix: if x.isdigit(): # if x in digit stack.append(__a ) # append x to stack # output in tabular format print(x.rjust(8 ) , ("push(" + x + ")").ljust(12 ) , ",".join(__a ) , sep=" | " ) else: lowerCamelCase__: List[Any] =stack.pop() # pop stack # output in tabular format print("".rjust(8 ) , ("pop(" + b + ")").ljust(12 ) , ",".join(__a ) , sep=" | " ) lowerCamelCase__: Optional[Any] =stack.pop() # pop stack # output in tabular format print("".rjust(8 ) , ("pop(" + a + ")").ljust(12 ) , ",".join(__a ) , sep=" | " ) stack.append( str(opr[x](int(__a ) , int(__a ) ) ) ) # evaluate the 2 values popped from stack & push result to stack # output in tabular format print( x.rjust(8 ) , ("push(" + a + x + b + ")").ljust(12 ) , ",".join(__a ) , sep=" | " , ) return int(stack[0] ) if __name__ == "__main__": __A = input("\n\nEnter a Postfix Equation (space separated) = ").split(" ") print("\n\tResult = ", solve(Postfix))
59
1
def lowerCAmelCase_ ( __a , __a , __a , __a ) -> int: """simple docstring""" lowerCamelCase__ , lowerCamelCase__: Optional[int] =len(__a ), len(grid[0] ) if ( min(__a , __a ) < 0 or row == row_length or col == col_length or (row, col) in visit or grid[row][col] == 1 ): return 0 if row == row_length - 1 and col == col_length - 1: return 1 visit.add((row, col) ) lowerCamelCase__: str =0 count += depth_first_search(__a , row + 1 , __a , __a ) count += depth_first_search(__a , row - 1 , __a , __a ) count += depth_first_search(__a , __a , col + 1 , __a ) count += depth_first_search(__a , __a , col - 1 , __a ) visit.remove((row, col) ) return count if __name__ == "__main__": import doctest doctest.testmod()
59
from collections import defaultdict from typing import Optional from ..image_utils import load_image from ..utils import ( add_end_docstrings, is_torch_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_MASK_GENERATION_MAPPING __A = logging.get_logger(__name__) @add_end_docstrings(__SCREAMING_SNAKE_CASE ) class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__(self : List[Any] , **UpperCAmelCase_ : Any) ->Any: '''simple docstring''' super().__init__(**UpperCAmelCase_) requires_backends(self , "vision") requires_backends(self , "torch") if self.framework != "pt": raise ValueError(F"""The {self.__class__} is only available in PyTorch.""") self.check_model_type(UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Tuple , **UpperCAmelCase_ : List[Any]) ->Tuple: '''simple docstring''' lowerCamelCase__: Optional[int] ={} lowerCamelCase__: Tuple ={} lowerCamelCase__: str ={} # preprocess args if "points_per_batch" in kwargs: lowerCamelCase__: Optional[Any] =kwargs["points_per_batch"] if "points_per_crop" in kwargs: lowerCamelCase__: int =kwargs["points_per_crop"] if "crops_n_layers" in kwargs: lowerCamelCase__: Any =kwargs["crops_n_layers"] if "crop_overlap_ratio" in kwargs: lowerCamelCase__: Tuple =kwargs["crop_overlap_ratio"] if "crop_n_points_downscale_factor" in kwargs: lowerCamelCase__: List[Any] =kwargs["crop_n_points_downscale_factor"] # postprocess args if "pred_iou_thresh" in kwargs: lowerCamelCase__: List[str] =kwargs["pred_iou_thresh"] if "stability_score_offset" in kwargs: lowerCamelCase__: int =kwargs["stability_score_offset"] if "mask_threshold" in kwargs: lowerCamelCase__: Optional[int] =kwargs["mask_threshold"] if "stability_score_thresh" in kwargs: lowerCamelCase__: str =kwargs["stability_score_thresh"] if "crops_nms_thresh" in kwargs: lowerCamelCase__: Any =kwargs["crops_nms_thresh"] if "output_rle_mask" in kwargs: lowerCamelCase__: List[Any] =kwargs["output_rle_mask"] if "output_bboxes_mask" in kwargs: lowerCamelCase__: List[str] =kwargs["output_bboxes_mask"] return preprocess_kwargs, forward_params, postprocess_kwargs def __call__(self : int , UpperCAmelCase_ : Dict , *UpperCAmelCase_ : Dict , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : Optional[Any]=None , **UpperCAmelCase_ : Dict) ->Optional[Any]: '''simple docstring''' return super().__call__(UpperCAmelCase_ , *UpperCAmelCase_ , num_workers=UpperCAmelCase_ , batch_size=UpperCAmelCase_ , **UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[Any]=64 , UpperCAmelCase_ : int = 0 , UpperCAmelCase_ : float = 512 / 1_500 , UpperCAmelCase_ : Optional[int] = 32 , UpperCAmelCase_ : Optional[int] = 1 , ) ->Dict: '''simple docstring''' lowerCamelCase__: Dict =load_image(UpperCAmelCase_) lowerCamelCase__: List[str] =self.image_processor.size["longest_edge"] lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Union[str, Any] =self.image_processor.generate_crop_boxes( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: str =self.image_processor(images=UpperCAmelCase_ , return_tensors="pt") with self.device_placement(): if self.framework == "pt": lowerCamelCase__: str =self.get_inference_context() with inference_context(): lowerCamelCase__: Union[str, Any] =self._ensure_tensor_on_device(UpperCAmelCase_ , device=self.device) lowerCamelCase__: Optional[Any] =self.model.get_image_embeddings(model_inputs.pop("pixel_values")) lowerCamelCase__: str =image_embeddings lowerCamelCase__: int =grid_points.shape[1] lowerCamelCase__: int =points_per_batch if points_per_batch is not None else n_points if points_per_batch <= 0: raise ValueError( "Cannot have points_per_batch<=0. Must be >=1 to returned batched outputs. " "To return all points at once, set points_per_batch to None") for i in range(0 , UpperCAmelCase_ , UpperCAmelCase_): lowerCamelCase__: int =grid_points[:, i : i + points_per_batch, :, :] lowerCamelCase__: Optional[Any] =input_labels[:, i : i + points_per_batch] lowerCamelCase__: Dict =i == n_points - points_per_batch yield { "input_points": batched_points, "input_labels": labels, "input_boxes": crop_boxes, "is_last": is_last, **model_inputs, } def SCREAMING_SNAKE_CASE_ (self : str , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Dict=0.88 , UpperCAmelCase_ : Optional[Any]=0.95 , UpperCAmelCase_ : Tuple=0 , UpperCAmelCase_ : Any=1 , ) ->Optional[Any]: '''simple docstring''' lowerCamelCase__: Any =model_inputs.pop("input_boxes") lowerCamelCase__: Dict =model_inputs.pop("is_last") lowerCamelCase__: int =model_inputs.pop("original_sizes").tolist() lowerCamelCase__: Union[str, Any] =model_inputs.pop("reshaped_input_sizes").tolist() lowerCamelCase__: Union[str, Any] =self.model(**UpperCAmelCase_) # post processing happens here in order to avoid CPU GPU copies of ALL the masks lowerCamelCase__: Optional[int] =model_outputs["pred_masks"] lowerCamelCase__: Union[str, Any] =self.image_processor.post_process_masks( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , binarize=UpperCAmelCase_) lowerCamelCase__: Optional[Any] =model_outputs["iou_scores"] lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Any =self.image_processor.filter_masks( masks[0] , iou_scores[0] , original_sizes[0] , input_boxes[0] , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , ) return { "masks": masks, "is_last": is_last, "boxes": boxes, "iou_scores": iou_scores, } def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : Any , UpperCAmelCase_ : Optional[int]=False , UpperCAmelCase_ : List[str]=False , UpperCAmelCase_ : Optional[int]=0.7 , ) ->Tuple: '''simple docstring''' lowerCamelCase__: Any =[] lowerCamelCase__: Optional[int] =[] lowerCamelCase__: List[str] =[] for model_output in model_outputs: all_scores.append(model_output.pop("iou_scores")) all_masks.extend(model_output.pop("masks")) all_boxes.append(model_output.pop("boxes")) lowerCamelCase__: str =torch.cat(UpperCAmelCase_) lowerCamelCase__: List[str] =torch.cat(UpperCAmelCase_) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Dict =self.image_processor.post_process_for_mask_generation( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: List[str] =defaultdict(UpperCAmelCase_) for output in model_outputs: for k, v in output.items(): extra[k].append(UpperCAmelCase_) lowerCamelCase__: Any ={} if output_rle_mask: lowerCamelCase__: Union[str, Any] =rle_mask if output_bboxes_mask: lowerCamelCase__: int =bounding_boxes return {"masks": output_masks, "scores": iou_scores, **optional, **extra}
59
1
import numpy as np import skfuzzy as fuzz if __name__ == "__main__": # Create universe of discourse in Python using linspace () __A = np.linspace(start=0, stop=75, num=75, endpoint=True, retstep=False) # Create two fuzzy sets by defining any membership function # (trapmf(), gbellmf(), gaussmf(), etc). __A = [0, 25, 50] __A = [25, 50, 75] __A = fuzz.membership.trimf(X, abca) __A = fuzz.membership.trimf(X, abca) # Compute the different operations using inbuilt functions. __A = np.ones(75) __A = np.zeros((75,)) # 1. Union = max(µA(x), µB(x)) __A = fuzz.fuzzy_or(X, young, X, middle_aged)[1] # 2. Intersection = min(µA(x), µB(x)) __A = fuzz.fuzzy_and(X, young, X, middle_aged)[1] # 3. Complement (A) = (1- min(µA(x)) __A = fuzz.fuzzy_not(young) # 4. Difference (A/B) = min(µA(x),(1- µB(x))) __A = fuzz.fuzzy_and(X, young, X, fuzz.fuzzy_not(middle_aged)[1])[1] # 5. Algebraic Sum = [µA(x) + µB(x) – (µA(x) * µB(x))] __A = young + middle_aged - (young * middle_aged) # 6. Algebraic Product = (µA(x) * µB(x)) __A = young * middle_aged # 7. Bounded Sum = min[1,(µA(x), µB(x))] __A = fuzz.fuzzy_and(X, one, X, young + middle_aged)[1] # 8. Bounded difference = min[0,(µA(x), µB(x))] __A = fuzz.fuzzy_or(X, zero, X, young - middle_aged)[1] # max-min composition # max-product composition # Plot each set A, set B and each operation result using plot() and subplot(). from matplotlib import pyplot as plt plt.figure() plt.subplot(4, 3, 1) plt.plot(X, young) plt.title("Young") plt.grid(True) plt.subplot(4, 3, 2) plt.plot(X, middle_aged) plt.title("Middle aged") plt.grid(True) plt.subplot(4, 3, 3) plt.plot(X, union) plt.title("union") plt.grid(True) plt.subplot(4, 3, 4) plt.plot(X, intersection) plt.title("intersection") plt.grid(True) plt.subplot(4, 3, 5) plt.plot(X, complement_a) plt.title("complement_a") plt.grid(True) plt.subplot(4, 3, 6) plt.plot(X, difference) plt.title("difference a/b") plt.grid(True) plt.subplot(4, 3, 7) plt.plot(X, alg_sum) plt.title("alg_sum") plt.grid(True) plt.subplot(4, 3, 8) plt.plot(X, alg_product) plt.title("alg_product") plt.grid(True) plt.subplot(4, 3, 9) plt.plot(X, bdd_sum) plt.title("bdd_sum") plt.grid(True) plt.subplot(4, 3, 10) plt.plot(X, bdd_difference) plt.title("bdd_difference") plt.grid(True) plt.subplots_adjust(hspace=0.5) plt.show()
59
from transformers import BertTokenizerFast from .custom_tokenization import CustomTokenizer class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = CustomTokenizer pass
59
1
import argparse import gc import json import os import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler __A = 16 __A = 32 def lowerCAmelCase_ ( __a ) -> Tuple: """simple docstring""" return int(x / 2**20 ) class _SCREAMING_SNAKE_CASE : '''simple docstring''' def __enter__(self : List[str]) ->Optional[int]: '''simple docstring''' gc.collect() torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() # reset the peak gauge to zero lowerCamelCase__: Tuple =torch.cuda.memory_allocated() return self def __exit__(self : List[Any] , *UpperCAmelCase_ : Optional[Any]) ->str: '''simple docstring''' gc.collect() torch.cuda.empty_cache() lowerCamelCase__: Tuple =torch.cuda.memory_allocated() lowerCamelCase__: Dict =torch.cuda.max_memory_allocated() lowerCamelCase__: Optional[int] =bamb(self.end - self.begin) lowerCamelCase__: List[str] =bamb(self.peak - self.begin) # print(f"delta used/peak {self.used:4d}/{self.peaked:4d}") def lowerCAmelCase_ ( __a , __a = 16 , __a = "bert-base-cased" , __a = 320 , __a = 160 , ) -> Optional[int]: """simple docstring""" lowerCamelCase__: Optional[Any] =AutoTokenizer.from_pretrained(__a ) lowerCamelCase__: Any =load_dataset( "glue" , "mrpc" , split={"train": F"""train[:{n_train}]""", "validation": F"""validation[:{n_val}]"""} ) def tokenize_function(__a ): # max_length=None => use the model max length (it's actually the default) lowerCamelCase__: Optional[int] =tokenizer(examples["sentence1"] , examples["sentence2"] , truncation=__a , max_length=__a ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset lowerCamelCase__: Any =datasets.map( __a , batched=__a , remove_columns=["idx", "sentence1", "sentence2"] , load_from_cache_file=__a ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library lowerCamelCase__: Optional[Any] =tokenized_datasets.rename_column("label" , "labels" ) def collate_fn(__a ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(__a , padding="max_length" , max_length=128 , return_tensors="pt" ) return tokenizer.pad(__a , padding="longest" , return_tensors="pt" ) # Instantiate dataloaders. lowerCamelCase__: List[Any] =DataLoader( tokenized_datasets["train"] , shuffle=__a , collate_fn=__a , batch_size=__a ) lowerCamelCase__: Dict =DataLoader( tokenized_datasets["validation"] , shuffle=__a , collate_fn=__a , batch_size=__a ) return train_dataloader, eval_dataloader def lowerCAmelCase_ ( __a , __a ) -> int: """simple docstring""" lowerCamelCase__: Union[str, Any] =Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs lowerCamelCase__: List[Any] =config["lr"] lowerCamelCase__: List[Any] =int(config["num_epochs"] ) lowerCamelCase__: List[str] =int(config["seed"] ) lowerCamelCase__: Tuple =int(config["batch_size"] ) lowerCamelCase__: Union[str, Any] =args.model_name_or_path set_seed(__a ) lowerCamelCase__ , lowerCamelCase__: List[str] =get_dataloaders(__a , __a , __a , args.n_train , args.n_val ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) lowerCamelCase__: Union[str, Any] =AutoModelForSequenceClassification.from_pretrained(__a , return_dict=__a ) # Instantiate optimizer lowerCamelCase__: List[str] =( AdamW if accelerator.state.deepspeed_plugin is None or "optimizer" not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) lowerCamelCase__: Optional[int] =optimizer_cls(params=model.parameters() , lr=__a ) if accelerator.state.deepspeed_plugin is not None: lowerCamelCase__: int =accelerator.state.deepspeed_plugin.deepspeed_config[ "gradient_accumulation_steps" ] else: lowerCamelCase__: Dict =1 lowerCamelCase__: Optional[int] =(len(__a ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): lowerCamelCase__: int =get_linear_schedule_with_warmup( optimizer=__a , num_warmup_steps=0 , num_training_steps=__a , ) else: lowerCamelCase__: Optional[int] =DummyScheduler(__a , total_num_steps=__a , warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Tuple =accelerator.prepare( __a , __a , __a , __a , __a ) # We need to keep track of how many total steps we have iterated over lowerCamelCase__: Union[str, Any] =0 # We also need to keep track of the stating epoch so files are named properly lowerCamelCase__: Union[str, Any] =0 # Now we train the model lowerCamelCase__: Tuple ={} for epoch in range(__a , __a ): with TorchTracemalloc() as tracemalloc: model.train() for step, batch in enumerate(__a ): lowerCamelCase__: List[str] =model(**__a ) lowerCamelCase__: Optional[Any] =outputs.loss lowerCamelCase__: Dict =loss / gradient_accumulation_steps accelerator.backward(__a ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 # Printing the GPU memory usage details such as allocated memory, peak memory, and total memory usage accelerator.print("Memory before entering the train : {}".format(bamb(tracemalloc.begin ) ) ) accelerator.print("Memory consumed at the end of the train (end-begin): {}".format(tracemalloc.used ) ) accelerator.print("Peak Memory consumed during the train (max-begin): {}".format(tracemalloc.peaked ) ) accelerator.print( "Total Peak Memory consumed during the train (max): {}".format( tracemalloc.peaked + bamb(tracemalloc.begin ) ) ) lowerCamelCase__: str =tracemalloc.peaked + bamb(tracemalloc.begin ) if args.peak_memory_upper_bound is not None: assert ( train_total_peak_memory[F"""epoch-{epoch}"""] <= args.peak_memory_upper_bound ), "Peak memory usage exceeded the upper bound" accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir , "peak_memory_utilization.json" ) , "w" ) as f: json.dump(__a , __a ) def lowerCAmelCase_ ( ) -> Optional[int]: """simple docstring""" lowerCamelCase__: Union[str, Any] =argparse.ArgumentParser(description="Simple example of training script tracking peak GPU memory usage." ) parser.add_argument( "--model_name_or_path" , type=__a , default="bert-base-cased" , help="Path to pretrained model or model identifier from huggingface.co/models." , required=__a , ) parser.add_argument( "--output_dir" , type=__a , default="." , help="Optional save directory where all checkpoint folders will be stored. Default is the current working directory." , ) parser.add_argument( "--peak_memory_upper_bound" , type=__a , default=__a , help="The upper bound of peak memory usage in MB. If set, the training will throw an error if the peak memory usage exceeds this value." , ) parser.add_argument( "--n_train" , type=__a , default=320 , help="Number of training examples to use." , ) parser.add_argument( "--n_val" , type=__a , default=160 , help="Number of validation examples to use." , ) parser.add_argument( "--num_epochs" , type=__a , default=1 , help="Number of train epochs." , ) lowerCamelCase__: Optional[int] =parser.parse_args() lowerCamelCase__: Any ={"lr": 2e-5, "num_epochs": args.num_epochs, "seed": 42, "batch_size": 16} training_function(__a , __a ) if __name__ == "__main__": main()
59
import inspect import os import unittest import torch import accelerate from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_multi_gpu from accelerate.utils import patch_environment class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ (self : Dict) ->Optional[int]: '''simple docstring''' lowerCamelCase__: List[Any] =inspect.getfile(accelerate.test_utils) lowerCamelCase__: List[Any] =os.path.sep.join(mod_file.split(os.path.sep)[:-1] + ["scripts", "test_script.py"]) lowerCamelCase__: Any =os.path.sep.join( mod_file.split(os.path.sep)[:-1] + ["scripts", "test_distributed_data_loop.py"]) lowerCamelCase__: Tuple =os.path.sep.join(mod_file.split(os.path.sep)[:-1] + ["scripts", "test_ops.py"]) @require_multi_gpu def SCREAMING_SNAKE_CASE_ (self : str) ->str: '''simple docstring''' print(F"""Found {torch.cuda.device_count()} devices.""") lowerCamelCase__: Union[str, Any] =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", self.test_file_path] with patch_environment(omp_num_threads=1): execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy()) @require_multi_gpu def SCREAMING_SNAKE_CASE_ (self : List[str]) ->List[Any]: '''simple docstring''' print(F"""Found {torch.cuda.device_count()} devices.""") lowerCamelCase__: Dict =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", self.operation_file_path] print(F"""Command: {cmd}""") with patch_environment(omp_num_threads=1): execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy()) @require_multi_gpu def SCREAMING_SNAKE_CASE_ (self : Dict) ->Tuple: '''simple docstring''' lowerCamelCase__: int =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", inspect.getfile(self.__class__)] with patch_environment(omp_num_threads=1): execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy()) @require_multi_gpu def SCREAMING_SNAKE_CASE_ (self : str) ->List[Any]: '''simple docstring''' print(F"""Found {torch.cuda.device_count()} devices, using 2 devices only""") lowerCamelCase__: int =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", self.data_loop_file_path] with patch_environment(omp_num_threads=1 , cuda_visible_devices="0,1"): execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy()) if __name__ == "__main__": __A = Accelerator() __A = (accelerator.state.process_index + 2, 10) __A = torch.randint(0, 10, shape).to(accelerator.device) __A = "" __A = accelerator.pad_across_processes(tensor) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += f"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." if not torch.equal(tensora[: accelerator.state.process_index + 2], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[accelerator.state.process_index + 2 :] == 0): error_msg += "Padding was not done with the right value (0)." __A = accelerator.pad_across_processes(tensor, pad_first=True) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += f"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." __A = accelerator.state.num_processes - accelerator.state.process_index - 1 if not torch.equal(tensora[index:], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[:index] == 0): error_msg += "Padding was not done with the right value (0)." # 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)
59
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) __A = {"configuration_deit": ["DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "DeiTConfig", "DeiTOnnxConfig"]} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ["DeiTFeatureExtractor"] __A = ["DeiTImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ "DEIT_PRETRAINED_MODEL_ARCHIVE_LIST", "DeiTForImageClassification", "DeiTForImageClassificationWithTeacher", "DeiTForMaskedImageModeling", "DeiTModel", "DeiTPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ "TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFDeiTForImageClassification", "TFDeiTForImageClassificationWithTeacher", "TFDeiTForMaskedImageModeling", "TFDeiTModel", "TFDeiTPreTrainedModel", ] if TYPE_CHECKING: from .configuration_deit import DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP, DeiTConfig, DeiTOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_deit import DeiTFeatureExtractor from .image_processing_deit import DeiTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_deit import ( DEIT_PRETRAINED_MODEL_ARCHIVE_LIST, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, DeiTModel, DeiTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_deit import ( TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, TFDeiTModel, TFDeiTPreTrainedModel, ) else: import sys __A = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
59
from typing import List, Optional, Tuple, Union import PIL import torch from torchvision import transforms from diffusers.pipeline_utils import DiffusionPipeline, ImagePipelineOutput from diffusers.schedulers import DDIMScheduler from diffusers.utils import randn_tensor __A = transforms.Compose( [ transforms.Resize((256, 256)), transforms.ToTensor(), transforms.Normalize([0.5], [0.5]), ] ) def lowerCAmelCase_ ( __a ) -> str: """simple docstring""" if isinstance(__a , torch.Tensor ): return image elif isinstance(__a , PIL.Image.Image ): lowerCamelCase__: Any =[image] lowerCamelCase__: Optional[Any] =[trans(img.convert("RGB" ) ) for img in image] lowerCamelCase__: Dict =torch.stack(__a ) return image class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__(self : Any , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Tuple) ->int: '''simple docstring''' super().__init__() # make sure scheduler can always be converted to DDIM lowerCamelCase__: Tuple =DDIMScheduler.from_config(scheduler.config) self.register_modules(unet=UpperCAmelCase_ , scheduler=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Union[str, Any]) ->Dict: '''simple docstring''' if strength < 0 or strength > 1: raise ValueError(F"""The value of strength should in [0.0, 1.0] but is {strength}""") def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Tuple) ->Tuple: '''simple docstring''' lowerCamelCase__: int =min(int(num_inference_steps * strength) , UpperCAmelCase_) lowerCamelCase__: str =max(num_inference_steps - init_timestep , 0) lowerCamelCase__: int =self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[int]=None) ->Optional[int]: '''simple docstring''' if not isinstance(UpperCAmelCase_ , (torch.Tensor, PIL.Image.Image, list)): raise ValueError( F"""`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(UpperCAmelCase_)}""") lowerCamelCase__: Optional[int] =image.to(device=UpperCAmelCase_ , dtype=UpperCAmelCase_) if isinstance(UpperCAmelCase_ , UpperCAmelCase_) and len(UpperCAmelCase_) != batch_size: raise ValueError( F"""You have passed a list of generators of length {len(UpperCAmelCase_)}, but requested an effective batch""" F""" size of {batch_size}. Make sure the batch size matches the length of the generators.""") lowerCamelCase__: Dict =init_latents.shape lowerCamelCase__: int =randn_tensor(UpperCAmelCase_ , generator=UpperCAmelCase_ , device=UpperCAmelCase_ , dtype=UpperCAmelCase_) # get latents print("add noise to latents at timestep" , UpperCAmelCase_) lowerCamelCase__: Union[str, Any] =self.scheduler.add_noise(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: int =init_latents return latents @torch.no_grad() def __call__(self : Tuple , UpperCAmelCase_ : Union[torch.FloatTensor, PIL.Image.Image] = None , UpperCAmelCase_ : float = 0.8 , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , UpperCAmelCase_ : float = 0.0 , UpperCAmelCase_ : int = 50 , UpperCAmelCase_ : Optional[bool] = None , UpperCAmelCase_ : Optional[str] = "pil" , UpperCAmelCase_ : bool = True , ) ->Union[ImagePipelineOutput, Tuple]: '''simple docstring''' self.check_inputs(UpperCAmelCase_) # 2. Preprocess image lowerCamelCase__: Dict =preprocess(UpperCAmelCase_) # 3. set timesteps self.scheduler.set_timesteps(UpperCAmelCase_ , device=self.device) lowerCamelCase__ , lowerCamelCase__: str =self.get_timesteps(UpperCAmelCase_ , UpperCAmelCase_ , self.device) lowerCamelCase__: Optional[int] =timesteps[:1].repeat(UpperCAmelCase_) # 4. Prepare latent variables lowerCamelCase__: int =self.prepare_latents(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , self.unet.dtype , self.device , UpperCAmelCase_) lowerCamelCase__: Tuple =latents # 5. Denoising loop for t in self.progress_bar(UpperCAmelCase_): # 1. predict noise model_output lowerCamelCase__: Dict =self.unet(UpperCAmelCase_ , UpperCAmelCase_).sample # 2. predict previous mean of image x_t-1 and add variance depending on eta # eta corresponds to η in paper and should be between [0, 1] # do x_t -> x_t-1 lowerCamelCase__: Optional[int] =self.scheduler.step( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , eta=UpperCAmelCase_ , use_clipped_model_output=UpperCAmelCase_ , generator=UpperCAmelCase_ , ).prev_sample lowerCamelCase__: str =(image / 2 + 0.5).clamp(0 , 1) lowerCamelCase__: Optional[Any] =image.cpu().permute(0 , 2 , 3 , 1).numpy() if output_type == "pil": lowerCamelCase__: Dict =self.numpy_to_pil(UpperCAmelCase_) if not return_dict: return (image, latent_timestep.item()) return ImagePipelineOutput(images=UpperCAmelCase_)
59
1
from ...configuration_utils import PretrainedConfig from ...utils import logging __A = logging.get_logger(__name__) __A = { "edbeeching/decision-transformer-gym-hopper-medium": ( "https://huggingface.co/edbeeching/decision-transformer-gym-hopper-medium/resolve/main/config.json" ), # See all DecisionTransformer models at https://huggingface.co/models?filter=decision_transformer } class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = "decision_transformer" lowercase_ = ["past_key_values"] lowercase_ = { "max_position_embeddings": "n_positions", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__(self : str , UpperCAmelCase_ : Optional[int]=17 , UpperCAmelCase_ : int=4 , UpperCAmelCase_ : int=128 , UpperCAmelCase_ : Union[str, Any]=4_096 , UpperCAmelCase_ : str=True , UpperCAmelCase_ : List[Any]=1 , UpperCAmelCase_ : List[str]=1_024 , UpperCAmelCase_ : Tuple=3 , UpperCAmelCase_ : List[str]=1 , UpperCAmelCase_ : str=None , UpperCAmelCase_ : str="relu" , UpperCAmelCase_ : List[str]=0.1 , UpperCAmelCase_ : Tuple=0.1 , UpperCAmelCase_ : List[Any]=0.1 , UpperCAmelCase_ : Any=1E-5 , UpperCAmelCase_ : str=0.02 , UpperCAmelCase_ : List[str]=True , UpperCAmelCase_ : int=True , UpperCAmelCase_ : Optional[int]=50_256 , UpperCAmelCase_ : Optional[Any]=50_256 , UpperCAmelCase_ : int=False , UpperCAmelCase_ : Dict=False , **UpperCAmelCase_ : Tuple , ) ->Tuple: '''simple docstring''' lowerCamelCase__: List[str] =state_dim lowerCamelCase__: str =act_dim lowerCamelCase__: Optional[Any] =hidden_size lowerCamelCase__: Any =max_ep_len lowerCamelCase__: Any =action_tanh lowerCamelCase__: List[str] =vocab_size lowerCamelCase__: Optional[int] =n_positions lowerCamelCase__: str =n_layer lowerCamelCase__: List[Any] =n_head lowerCamelCase__: List[Any] =n_inner lowerCamelCase__: str =activation_function lowerCamelCase__: str =resid_pdrop lowerCamelCase__: Any =embd_pdrop lowerCamelCase__: str =attn_pdrop lowerCamelCase__: Tuple =layer_norm_epsilon lowerCamelCase__: Optional[int] =initializer_range lowerCamelCase__: str =scale_attn_weights lowerCamelCase__: Optional[Any] =use_cache lowerCamelCase__: Any =scale_attn_by_inverse_layer_idx lowerCamelCase__: List[Any] =reorder_and_upcast_attn lowerCamelCase__: Tuple =bos_token_id lowerCamelCase__: List[Any] =eos_token_id super().__init__(bos_token_id=UpperCAmelCase_ , eos_token_id=UpperCAmelCase_ , **UpperCAmelCase_)
59
import argparse import os import pickle import sys import torch from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils from transformers.models.transfo_xl.tokenization_transfo_xl import CORPUS_NAME, VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() # We do this to be able to load python 2 datasets pickles # See e.g. https://stackoverflow.com/questions/2121874/python-pickling-after-changing-a-modules-directory/2121918#2121918 __A = data_utils.TransfoXLTokenizer __A = data_utils.TransfoXLCorpus __A = data_utils __A = data_utils def lowerCAmelCase_ ( __a , __a , __a , __a ) -> List[str]: """simple docstring""" if transfo_xl_dataset_file: # Convert a pre-processed corpus (see original TensorFlow repo) with open(__a , "rb" ) as fp: lowerCamelCase__: Optional[Any] =pickle.load(__a , encoding="latin1" ) # Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term) lowerCamelCase__: Union[str, Any] =pytorch_dump_folder_path + "/" + VOCAB_FILES_NAMES["pretrained_vocab_file"] print(F"""Save vocabulary to {pytorch_vocab_dump_path}""" ) lowerCamelCase__: Any =corpus.vocab.__dict__ torch.save(__a , __a ) lowerCamelCase__: Dict =corpus.__dict__ corpus_dict_no_vocab.pop("vocab" , __a ) lowerCamelCase__: List[str] =pytorch_dump_folder_path + "/" + CORPUS_NAME print(F"""Save dataset to {pytorch_dataset_dump_path}""" ) torch.save(__a , __a ) if tf_checkpoint_path: # Convert a pre-trained TensorFlow model lowerCamelCase__: Optional[Any] =os.path.abspath(__a ) lowerCamelCase__: Dict =os.path.abspath(__a ) print(F"""Converting Transformer XL checkpoint from {tf_path} with config at {config_path}.""" ) # Initialise PyTorch model if transfo_xl_config_file == "": lowerCamelCase__: int =TransfoXLConfig() else: lowerCamelCase__: Any =TransfoXLConfig.from_json_file(__a ) print(F"""Building PyTorch model from configuration: {config}""" ) lowerCamelCase__: List[Any] =TransfoXLLMHeadModel(__a ) lowerCamelCase__: List[str] =load_tf_weights_in_transfo_xl(__a , __a , __a ) # Save pytorch-model lowerCamelCase__: List[str] =os.path.join(__a , __a ) lowerCamelCase__: Tuple =os.path.join(__a , __a ) print(F"""Save PyTorch model to {os.path.abspath(__a )}""" ) torch.save(model.state_dict() , __a ) print(F"""Save configuration file to {os.path.abspath(__a )}""" ) with open(__a , "w" , encoding="utf-8" ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": __A = argparse.ArgumentParser() parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the folder to store the PyTorch model or dataset/vocab.", ) parser.add_argument( "--tf_checkpoint_path", default="", type=str, help="An optional path to a TensorFlow checkpoint path to be converted.", ) parser.add_argument( "--transfo_xl_config_file", default="", type=str, help=( "An optional config json file corresponding to the pre-trained BERT model. \n" "This specifies the model architecture." ), ) parser.add_argument( "--transfo_xl_dataset_file", default="", type=str, help="An optional dataset file to be converted in a vocabulary.", ) __A = parser.parse_args() convert_transfo_xl_checkpoint_to_pytorch( args.tf_checkpoint_path, args.transfo_xl_config_file, args.pytorch_dump_folder_path, args.transfo_xl_dataset_file, )
59
1
def lowerCAmelCase_ ( __a = 3 , __a = 7 , __a = 1000000 ) -> int: """simple docstring""" lowerCamelCase__: Union[str, Any] =0 lowerCamelCase__: Optional[int] =1 for current_denominator in range(1 , limit + 1 ): lowerCamelCase__: List[Any] =current_denominator * numerator // denominator if current_denominator % denominator == 0: current_numerator -= 1 if current_numerator * max_denominator > current_denominator * max_numerator: lowerCamelCase__: Optional[int] =current_numerator lowerCamelCase__: int =current_denominator return max_numerator if __name__ == "__main__": print(solution(numerator=3, denominator=7, limit=100_0000))
59
from collections import UserDict from typing import List, Union from ..utils import ( add_end_docstrings, is_tf_available, is_torch_available, is_vision_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING from ..tf_utils import stable_softmax __A = logging.get_logger(__name__) @add_end_docstrings(__SCREAMING_SNAKE_CASE ) class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__(self : Optional[int] , **UpperCAmelCase_ : List[Any]) ->List[str]: '''simple docstring''' super().__init__(**UpperCAmelCase_) requires_backends(self , "vision") self.check_model_type( TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING if self.framework == "tf" else MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING) def __call__(self : List[str] , UpperCAmelCase_ : Union[str, List[str], "Image", List["Image"]] , **UpperCAmelCase_ : List[Any]) ->Tuple: '''simple docstring''' return super().__call__(UpperCAmelCase_ , **UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[Any] , **UpperCAmelCase_ : Optional[int]) ->Any: '''simple docstring''' lowerCamelCase__: Optional[int] ={} if "candidate_labels" in kwargs: lowerCamelCase__: Tuple =kwargs["candidate_labels"] if "hypothesis_template" in kwargs: lowerCamelCase__: Tuple =kwargs["hypothesis_template"] return preprocess_params, {}, {} def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Dict=None , UpperCAmelCase_ : Optional[Any]="This is a photo of {}.") ->str: '''simple docstring''' lowerCamelCase__: int =load_image(UpperCAmelCase_) lowerCamelCase__: Any =self.image_processor(images=[image] , return_tensors=self.framework) lowerCamelCase__: Any =candidate_labels lowerCamelCase__: List[str] =[hypothesis_template.format(UpperCAmelCase_) for x in candidate_labels] lowerCamelCase__: int =self.tokenizer(UpperCAmelCase_ , return_tensors=self.framework , padding=UpperCAmelCase_) lowerCamelCase__: str =[text_inputs] return inputs def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Any) ->Tuple: '''simple docstring''' lowerCamelCase__: int =model_inputs.pop("candidate_labels") lowerCamelCase__: List[str] =model_inputs.pop("text_inputs") if isinstance(text_inputs[0] , UpperCAmelCase_): lowerCamelCase__: List[Any] =text_inputs[0] else: # Batching case. lowerCamelCase__: List[Any] =text_inputs[0][0] lowerCamelCase__: List[str] =self.model(**UpperCAmelCase_ , **UpperCAmelCase_) lowerCamelCase__: str ={ "candidate_labels": candidate_labels, "logits": outputs.logits_per_image, } return model_outputs def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , UpperCAmelCase_ : Union[str, Any]) ->int: '''simple docstring''' lowerCamelCase__: List[Any] =model_outputs.pop("candidate_labels") lowerCamelCase__: Optional[int] =model_outputs["logits"][0] if self.framework == "pt": lowerCamelCase__: Optional[Any] =logits.softmax(dim=-1).squeeze(-1) lowerCamelCase__: Optional[Any] =probs.tolist() if not isinstance(UpperCAmelCase_ , UpperCAmelCase_): lowerCamelCase__: Optional[int] =[scores] elif self.framework == "tf": lowerCamelCase__: List[str] =stable_softmax(UpperCAmelCase_ , axis=-1) lowerCamelCase__: Optional[int] =probs.numpy().tolist() else: raise ValueError(F"""Unsupported framework: {self.framework}""") lowerCamelCase__: Optional[int] =[ {"score": score, "label": candidate_label} for score, candidate_label in sorted(zip(UpperCAmelCase_ , UpperCAmelCase_) , key=lambda UpperCAmelCase_: -x[0]) ] return result
59
1
from dataclasses import dataclass from typing import Optional import torch from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .attention import BasicTransformerBlock from .modeling_utils import ModelMixin @dataclass class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = 42 class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): '''simple docstring''' @register_to_config def __init__(self : Dict , UpperCAmelCase_ : int = 16 , UpperCAmelCase_ : int = 88 , UpperCAmelCase_ : Optional[int] = None , UpperCAmelCase_ : Optional[int] = None , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : float = 0.0 , UpperCAmelCase_ : int = 32 , UpperCAmelCase_ : Optional[int] = None , UpperCAmelCase_ : bool = False , UpperCAmelCase_ : Optional[int] = None , UpperCAmelCase_ : str = "geglu" , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : bool = True , ) ->Optional[Any]: '''simple docstring''' super().__init__() lowerCamelCase__: int =num_attention_heads lowerCamelCase__: Union[str, Any] =attention_head_dim lowerCamelCase__: Optional[int] =num_attention_heads * attention_head_dim lowerCamelCase__: Tuple =in_channels lowerCamelCase__: Optional[Any] =torch.nn.GroupNorm(num_groups=UpperCAmelCase_ , num_channels=UpperCAmelCase_ , eps=1E-6 , affine=UpperCAmelCase_) lowerCamelCase__: List[Any] =nn.Linear(UpperCAmelCase_ , UpperCAmelCase_) # 3. Define transformers blocks lowerCamelCase__: Dict =nn.ModuleList( [ BasicTransformerBlock( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , dropout=UpperCAmelCase_ , cross_attention_dim=UpperCAmelCase_ , activation_fn=UpperCAmelCase_ , attention_bias=UpperCAmelCase_ , double_self_attention=UpperCAmelCase_ , norm_elementwise_affine=UpperCAmelCase_ , ) for d in range(UpperCAmelCase_) ]) lowerCamelCase__: Tuple =nn.Linear(UpperCAmelCase_ , UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any]=None , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : Dict=None , UpperCAmelCase_ : Tuple=1 , UpperCAmelCase_ : Any=None , UpperCAmelCase_ : bool = True , ) ->Dict: '''simple docstring''' lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Dict =hidden_states.shape lowerCamelCase__: Any =batch_frames // num_frames lowerCamelCase__: Optional[Any] =hidden_states lowerCamelCase__: List[str] =hidden_states[None, :].reshape(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: List[str] =hidden_states.permute(0 , 2 , 1 , 3 , 4) lowerCamelCase__: List[Any] =self.norm(UpperCAmelCase_) lowerCamelCase__: List[str] =hidden_states.permute(0 , 3 , 4 , 2 , 1).reshape(batch_size * height * width , UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: List[Any] =self.proj_in(UpperCAmelCase_) # 2. Blocks for block in self.transformer_blocks: lowerCamelCase__: int =block( UpperCAmelCase_ , encoder_hidden_states=UpperCAmelCase_ , timestep=UpperCAmelCase_ , cross_attention_kwargs=UpperCAmelCase_ , class_labels=UpperCAmelCase_ , ) # 3. Output lowerCamelCase__: Any =self.proj_out(UpperCAmelCase_) lowerCamelCase__: Union[str, Any] =( hidden_states[None, None, :] .reshape(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_) .permute(0 , 3 , 4 , 1 , 2) .contiguous() ) lowerCamelCase__: List[Any] =hidden_states.reshape(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: int =hidden_states + residual if not return_dict: return (output,) return TransformerTemporalModelOutput(sample=UpperCAmelCase_)
59
import json import os from dataclasses import dataclass from functools import partial from typing import Callable import flax.linen as nn import jax import jax.numpy as jnp import joblib import optax import wandb from flax import jax_utils, struct, traverse_util from flax.serialization import from_bytes, to_bytes from flax.training import train_state from flax.training.common_utils import shard from tqdm.auto import tqdm from transformers import BigBirdConfig, FlaxBigBirdForQuestionAnswering from transformers.models.big_bird.modeling_flax_big_bird import FlaxBigBirdForQuestionAnsweringModule class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = 42 lowercase_ = jnp.floataa lowercase_ = True def SCREAMING_SNAKE_CASE_ (self : Any) ->List[str]: '''simple docstring''' super().setup() lowerCamelCase__: int =nn.Dense(5 , dtype=self.dtype) def __call__(self : Dict , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : Any) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Optional[Any] =super().__call__(*UpperCAmelCase_ , **UpperCAmelCase_) lowerCamelCase__: int =self.cls(outputs[2]) return outputs[:2] + (cls_out,) class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = FlaxBigBirdForNaturalQuestionsModule def lowerCAmelCase_ ( __a , __a , __a , __a , __a , __a ) -> Tuple: """simple docstring""" def cross_entropy(__a , __a , __a=None ): lowerCamelCase__: Tuple =logits.shape[-1] lowerCamelCase__: Tuple =(labels[..., None] == jnp.arange(__a )[None]).astype("f4" ) lowerCamelCase__: str =jax.nn.log_softmax(__a , axis=-1 ) lowerCamelCase__: Optional[Any] =-jnp.sum(labels * logits , axis=-1 ) if reduction is not None: lowerCamelCase__: Optional[Any] =reduction(__a ) return loss lowerCamelCase__: str =partial(__a , reduction=jnp.mean ) lowerCamelCase__: str =cross_entropy(__a , __a ) lowerCamelCase__: Optional[int] =cross_entropy(__a , __a ) lowerCamelCase__: Optional[Any] =cross_entropy(__a , __a ) return (start_loss + end_loss + pooled_loss) / 3 @dataclass class _SCREAMING_SNAKE_CASE : '''simple docstring''' lowercase_ = "google/bigbird-roberta-base" lowercase_ = 3000 lowercase_ = 1_0500 lowercase_ = 128 lowercase_ = 3 lowercase_ = 1 lowercase_ = 5 # tx_args lowercase_ = 3E-5 lowercase_ = 0.0 lowercase_ = 2_0000 lowercase_ = 0.0095 lowercase_ = "bigbird-roberta-natural-questions" lowercase_ = "training-expt" lowercase_ = "data/nq-training.jsonl" lowercase_ = "data/nq-validation.jsonl" def SCREAMING_SNAKE_CASE_ (self : Tuple) ->List[str]: '''simple docstring''' os.makedirs(self.base_dir , exist_ok=UpperCAmelCase_) lowerCamelCase__: Optional[Any] =os.path.join(self.base_dir , self.save_dir) lowerCamelCase__: List[str] =self.batch_size_per_device * jax.device_count() @dataclass class _SCREAMING_SNAKE_CASE : '''simple docstring''' lowercase_ = 42 lowercase_ = 4096 # no dynamic padding on TPUs def __call__(self : List[Any] , UpperCAmelCase_ : Optional[Any]) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Optional[Any] =self.collate_fn(UpperCAmelCase_) lowerCamelCase__: List[Any] =jax.tree_util.tree_map(UpperCAmelCase_ , UpperCAmelCase_) return batch def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : List[str]) ->List[Any]: '''simple docstring''' lowerCamelCase__ , lowerCamelCase__: List[Any] =self.fetch_inputs(features["input_ids"]) lowerCamelCase__: Union[str, Any] ={ "input_ids": jnp.array(UpperCAmelCase_ , dtype=jnp.intaa), "attention_mask": jnp.array(UpperCAmelCase_ , dtype=jnp.intaa), "start_labels": jnp.array(features["start_token"] , dtype=jnp.intaa), "end_labels": jnp.array(features["end_token"] , dtype=jnp.intaa), "pooled_labels": jnp.array(features["category"] , dtype=jnp.intaa), } return batch def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : list) ->Optional[Any]: '''simple docstring''' lowerCamelCase__: Tuple =[self._fetch_inputs(UpperCAmelCase_) for ids in input_ids] return zip(*UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[Any] , UpperCAmelCase_ : list) ->Any: '''simple docstring''' lowerCamelCase__: Optional[Any] =[1 for _ in range(len(UpperCAmelCase_))] while len(UpperCAmelCase_) < self.max_length: input_ids.append(self.pad_id) attention_mask.append(0) return input_ids, attention_mask def lowerCAmelCase_ ( __a , __a , __a=None ) -> str: """simple docstring""" if seed is not None: lowerCamelCase__: Any =dataset.shuffle(seed=__a ) for i in range(len(__a ) // batch_size ): lowerCamelCase__: Any =dataset[i * batch_size : (i + 1) * batch_size] yield dict(__a ) @partial(jax.pmap , axis_name="batch" ) def lowerCAmelCase_ ( __a , __a , **__a ) -> List[str]: """simple docstring""" def loss_fn(__a ): lowerCamelCase__: Optional[int] =model_inputs.pop("start_labels" ) lowerCamelCase__: int =model_inputs.pop("end_labels" ) lowerCamelCase__: List[str] =model_inputs.pop("pooled_labels" ) lowerCamelCase__: Optional[int] =state.apply_fn(**__a , params=__a , dropout_rng=__a , train=__a ) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: List[Any] =outputs return state.loss_fn( __a , __a , __a , __a , __a , __a , ) lowerCamelCase__ , lowerCamelCase__: int =jax.random.split(__a ) lowerCamelCase__: Optional[Any] =jax.value_and_grad(__a ) lowerCamelCase__ , lowerCamelCase__: List[str] =grad_fn(state.params ) lowerCamelCase__: Optional[Any] =jax.lax.pmean({"loss": loss} , axis_name="batch" ) lowerCamelCase__: List[str] =jax.lax.pmean(__a , "batch" ) lowerCamelCase__: List[str] =state.apply_gradients(grads=__a ) return state, metrics, new_drp_rng @partial(jax.pmap , axis_name="batch" ) def lowerCAmelCase_ ( __a , **__a ) -> List[Any]: """simple docstring""" lowerCamelCase__: int =model_inputs.pop("start_labels" ) lowerCamelCase__: List[str] =model_inputs.pop("end_labels" ) lowerCamelCase__: int =model_inputs.pop("pooled_labels" ) lowerCamelCase__: Optional[Any] =state.apply_fn(**__a , params=state.params , train=__a ) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: List[str] =outputs lowerCamelCase__: Optional[int] =state.loss_fn(__a , __a , __a , __a , __a , __a ) lowerCamelCase__: Optional[Any] =jax.lax.pmean({"loss": loss} , axis_name="batch" ) return metrics class _SCREAMING_SNAKE_CASE ( train_state.TrainState ): '''simple docstring''' lowercase_ = struct.field(pytree_node=__SCREAMING_SNAKE_CASE ) @dataclass class _SCREAMING_SNAKE_CASE : '''simple docstring''' lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = None def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : int=None) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Dict =model.params lowerCamelCase__: Tuple =TrainState.create( apply_fn=model.__call__ , params=UpperCAmelCase_ , tx=UpperCAmelCase_ , loss_fn=UpperCAmelCase_ , ) if ckpt_dir is not None: lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Any =restore_checkpoint(UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: Tuple ={ "lr": args.lr, "init_lr": args.init_lr, "warmup_steps": args.warmup_steps, "num_train_steps": num_train_steps, "weight_decay": args.weight_decay, } lowerCamelCase__ , lowerCamelCase__: List[Any] =build_tx(**UpperCAmelCase_) lowerCamelCase__: str =train_state.TrainState( step=UpperCAmelCase_ , apply_fn=model.__call__ , params=UpperCAmelCase_ , tx=UpperCAmelCase_ , opt_state=UpperCAmelCase_ , ) lowerCamelCase__: Tuple =args lowerCamelCase__: Tuple =data_collator lowerCamelCase__: str =lr lowerCamelCase__: Dict =params lowerCamelCase__: List[str] =jax_utils.replicate(UpperCAmelCase_) return state def SCREAMING_SNAKE_CASE_ (self : List[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Tuple) ->Optional[Any]: '''simple docstring''' lowerCamelCase__: Tuple =self.args lowerCamelCase__: Any =len(UpperCAmelCase_) // args.batch_size lowerCamelCase__: List[str] =jax.random.PRNGKey(0) lowerCamelCase__: Optional[Any] =jax.random.split(UpperCAmelCase_ , jax.device_count()) for epoch in range(args.max_epochs): lowerCamelCase__: Union[str, Any] =jnp.array(0 , dtype=jnp.floataa) lowerCamelCase__: str =get_batched_dataset(UpperCAmelCase_ , args.batch_size , seed=UpperCAmelCase_) lowerCamelCase__: Dict =0 for batch in tqdm(UpperCAmelCase_ , total=UpperCAmelCase_ , desc=F"""Running EPOCH-{epoch}"""): lowerCamelCase__: List[str] =self.data_collator(UpperCAmelCase_) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Optional[int] =self.train_step_fn(UpperCAmelCase_ , UpperCAmelCase_ , **UpperCAmelCase_) running_loss += jax_utils.unreplicate(metrics["loss"]) i += 1 if i % args.logging_steps == 0: lowerCamelCase__: Optional[int] =jax_utils.unreplicate(state.step) lowerCamelCase__: List[Any] =running_loss.item() / i lowerCamelCase__: Tuple =self.scheduler_fn(state_step - 1) lowerCamelCase__: Union[str, Any] =self.evaluate(UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: Dict ={ "step": state_step.item(), "eval_loss": eval_loss.item(), "tr_loss": tr_loss, "lr": lr.item(), } tqdm.write(str(UpperCAmelCase_)) self.logger.log(UpperCAmelCase_ , commit=UpperCAmelCase_) if i % args.save_steps == 0: self.save_checkpoint(args.save_dir + F"""-e{epoch}-s{i}""" , state=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : str , UpperCAmelCase_ : str) ->Any: '''simple docstring''' lowerCamelCase__: List[Any] =get_batched_dataset(UpperCAmelCase_ , self.args.batch_size) lowerCamelCase__: List[str] =len(UpperCAmelCase_) // self.args.batch_size lowerCamelCase__: str =jnp.array(0 , dtype=jnp.floataa) lowerCamelCase__: Optional[Any] =0 for batch in tqdm(UpperCAmelCase_ , total=UpperCAmelCase_ , desc="Evaluating ... "): lowerCamelCase__: int =self.data_collator(UpperCAmelCase_) lowerCamelCase__: str =self.val_step_fn(UpperCAmelCase_ , **UpperCAmelCase_) running_loss += jax_utils.unreplicate(metrics["loss"]) i += 1 return running_loss / i def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[int]) ->int: '''simple docstring''' lowerCamelCase__: Any =jax_utils.unreplicate(UpperCAmelCase_) print(F"""SAVING CHECKPOINT IN {save_dir}""" , end=" ... ") self.model_save_fn(UpperCAmelCase_ , params=state.params) with open(os.path.join(UpperCAmelCase_ , "opt_state.msgpack") , "wb") as f: f.write(to_bytes(state.opt_state)) joblib.dump(self.args , os.path.join(UpperCAmelCase_ , "args.joblib")) joblib.dump(self.data_collator , os.path.join(UpperCAmelCase_ , "data_collator.joblib")) with open(os.path.join(UpperCAmelCase_ , "training_state.json") , "w") as f: json.dump({"step": state.step.item()} , UpperCAmelCase_) print("DONE") def lowerCAmelCase_ ( __a , __a ) -> str: """simple docstring""" print(F"""RESTORING CHECKPOINT FROM {save_dir}""" , end=" ... " ) with open(os.path.join(__a , "flax_model.msgpack" ) , "rb" ) as f: lowerCamelCase__: Tuple =from_bytes(state.params , f.read() ) with open(os.path.join(__a , "opt_state.msgpack" ) , "rb" ) as f: lowerCamelCase__: Optional[int] =from_bytes(state.opt_state , f.read() ) lowerCamelCase__: Any =joblib.load(os.path.join(__a , "args.joblib" ) ) lowerCamelCase__: Union[str, Any] =joblib.load(os.path.join(__a , "data_collator.joblib" ) ) with open(os.path.join(__a , "training_state.json" ) , "r" ) as f: lowerCamelCase__: Optional[Any] =json.load(__a ) lowerCamelCase__: Any =training_state["step"] print("DONE" ) return params, opt_state, step, args, data_collator def lowerCAmelCase_ ( __a , __a , __a , __a ) -> Optional[int]: """simple docstring""" lowerCamelCase__: int =num_train_steps - warmup_steps lowerCamelCase__: str =optax.linear_schedule(init_value=__a , end_value=__a , transition_steps=__a ) lowerCamelCase__: Optional[Any] =optax.linear_schedule(init_value=__a , end_value=1e-7 , transition_steps=__a ) lowerCamelCase__: List[Any] =optax.join_schedules(schedules=[warmup_fn, decay_fn] , boundaries=[warmup_steps] ) return lr def lowerCAmelCase_ ( __a , __a , __a , __a , __a ) -> str: """simple docstring""" def weight_decay_mask(__a ): lowerCamelCase__: List[str] =traverse_util.flatten_dict(__a ) lowerCamelCase__: List[str] ={k: (v[-1] != "bias" and v[-2:] != ("LayerNorm", "scale")) for k, v in params.items()} return traverse_util.unflatten_dict(__a ) lowerCamelCase__: Optional[Any] =scheduler_fn(__a , __a , __a , __a ) lowerCamelCase__: Tuple =optax.adamw(learning_rate=__a , weight_decay=__a , mask=__a ) return tx, lr
59
1
import unittest from transformers.models.xlm_prophetnet.tokenization_xlm_prophetnet import SPIECE_UNDERLINE, XLMProphetNetTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin __A = get_tests_dir("fixtures/test_sentencepiece.model") @require_sentencepiece class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowercase_ = XLMProphetNetTokenizer lowercase_ = False lowercase_ = True def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Optional[Any]: '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing lowerCamelCase__: Any =XLMProphetNetTokenizer(UpperCAmelCase_ , keep_accents=UpperCAmelCase_) tokenizer.save_pretrained(self.tmpdirname) def SCREAMING_SNAKE_CASE_ (self : str) ->str: '''simple docstring''' lowerCamelCase__: List[Any] ="[PAD]" lowerCamelCase__: Tuple =0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCAmelCase_) , UpperCAmelCase_) self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCAmelCase_) , UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Dict) ->int: '''simple docstring''' lowerCamelCase__: List[Any] =list(self.get_tokenizer().get_vocab().keys()) self.assertEqual(vocab_keys[0] , "[PAD]") self.assertEqual(vocab_keys[1] , "[CLS]") self.assertEqual(vocab_keys[-1] , "j") self.assertEqual(len(UpperCAmelCase_) , 1_012) def SCREAMING_SNAKE_CASE_ (self : Dict) ->Union[str, Any]: '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 1_012) def SCREAMING_SNAKE_CASE_ (self : Any) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Optional[Any] =XLMProphetNetTokenizer(UpperCAmelCase_ , keep_accents=UpperCAmelCase_) lowerCamelCase__: 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]] , ) lowerCamelCase__: Optional[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", "é", ".", ] , ) lowerCamelCase__: Any =tokenizer.convert_tokens_to_ids(UpperCAmelCase_) self.assertListEqual( UpperCAmelCase_ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, -9, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, -9, 4] ] , ) lowerCamelCase__: 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]", ".", ] , ) @cached_property def SCREAMING_SNAKE_CASE_ (self : Any) ->int: '''simple docstring''' return XLMProphetNetTokenizer.from_pretrained("microsoft/xprophetnet-large-wiki100-cased") @slow def SCREAMING_SNAKE_CASE_ (self : List[str]) ->List[str]: '''simple docstring''' lowerCamelCase__: Optional[int] ="Hello World!" lowerCamelCase__: Dict =[35_389, 6_672, 49, 2] self.assertListEqual(UpperCAmelCase_ , self.big_tokenizer.encode(UpperCAmelCase_)) @slow def SCREAMING_SNAKE_CASE_ (self : int) ->Union[str, Any]: '''simple docstring''' lowerCamelCase__: Any ={"input_ids": [[11_073, 82_783, 18, 26, 82_783, 549, 51_540, 248, 17_209, 1_301, 217, 20, 215_186, 1_325, 147, 17_209, 1_301, 217, 20, 56_370, 53, 122_020, 20, 16_477, 27, 87_355, 4_548, 20, 4_728, 78_392, 17, 159_969, 18, 26, 24_491, 629, 15, 538, 22_704, 5_439, 15, 2_788, 24_491, 9_885, 15, 43_534, 605, 15, 814, 18_403, 33_200, 29, 15, 43_534, 24_458, 12_410, 111, 24_966, 83_669, 9_637, 144_068, 26, 850, 22_346, 27, 147, 24_966, 83_669, 83_490, 26, 39_113, 735, 27, 689, 656, 2_800, 1_339, 4_600, 53, 122_020, 115_785, 34, 816, 1_339, 46_887, 18, 147, 53_905, 1_951, 42_238, 41_170, 17_732, 834, 436, 15, 27_523, 98_733, 217, 147, 5_542, 4_981, 930, 17_347, 16, 2], [20_091, 629, 94, 82_786, 58, 490, 20, 1_528, 84, 53_905, 344, 80_592, 110_128, 18_822, 5_267, 1_306, 62, 152_537, 308, 7_997, 401, 124_427, 549, 35_442, 225, 109, 15_055, 25_748, 147, 7_119, 43_712, 34, 767, 135_366, 18, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [592, 63_784, 119_466, 17, 147_808, 88_214, 18, 656, 81, 32, 3_296, 10_280, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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="microsoft/xprophetnet-large-wiki100-cased" , revision="1acad1643ddd54a44df6a1b797ada8373685d90e" , )
59
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = ["image_processor", "tokenizer"] lowercase_ = "ChineseCLIPImageProcessor" lowercase_ = ("BertTokenizer", "BertTokenizerFast") def __init__(self : Any , UpperCAmelCase_ : List[str]=None , UpperCAmelCase_ : Union[str, Any]=None , **UpperCAmelCase_ : str) ->Dict: '''simple docstring''' lowerCamelCase__: str =None if "feature_extractor" in kwargs: warnings.warn( "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`" " instead." , UpperCAmelCase_ , ) lowerCamelCase__: Tuple =kwargs.pop("feature_extractor") lowerCamelCase__: Optional[int] =image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("You need to specify an `image_processor`.") if tokenizer is None: raise ValueError("You need to specify a `tokenizer`.") super().__init__(UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: Optional[int] =self.image_processor def __call__(self : int , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : List[Any]=None , **UpperCAmelCase_ : Dict) ->Optional[int]: '''simple docstring''' if text is None and images is None: raise ValueError("You have to specify either text or images. Both cannot be none.") if text is not None: lowerCamelCase__: Dict =self.tokenizer(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_) if images is not None: lowerCamelCase__: List[str] =self.image_processor(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_) if text is not None and images is not None: lowerCamelCase__: Union[str, Any] =image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**UpperCAmelCase_) , tensor_type=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : int) ->str: '''simple docstring''' return self.tokenizer.batch_decode(*UpperCAmelCase_ , **UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Any , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : List[Any]) ->Dict: '''simple docstring''' return self.tokenizer.decode(*UpperCAmelCase_ , **UpperCAmelCase_) @property def SCREAMING_SNAKE_CASE_ (self : int) ->List[str]: '''simple docstring''' lowerCamelCase__: str =self.tokenizer.model_input_names lowerCamelCase__: Union[str, Any] =self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names)) @property def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->str: '''simple docstring''' warnings.warn( "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead." , UpperCAmelCase_ , ) return self.image_processor_class
59
1
import json import os import pickle import shutil import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np from datasets import Dataset from transformers import is_faiss_available from transformers.models.bart.configuration_bart import BartConfig from transformers.models.bart.tokenization_bart import BartTokenizer from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES as DPR_VOCAB_FILES_NAMES from transformers.models.dpr.configuration_dpr import DPRConfig from transformers.models.dpr.tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer from transformers.models.rag.configuration_rag import RagConfig from transformers.models.rag.retrieval_rag import CustomHFIndex, RagRetriever from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES as BART_VOCAB_FILES_NAMES from transformers.testing_utils import require_faiss, require_sentencepiece, require_tokenizers, require_torch if is_faiss_available(): import faiss @require_faiss class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ (self : int) ->Dict: '''simple docstring''' lowerCamelCase__: Any =tempfile.mkdtemp() lowerCamelCase__: Any =8 # DPR tok lowerCamelCase__: Tuple =[ "[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest", ] lowerCamelCase__: int =os.path.join(self.tmpdirname , "dpr_tokenizer") os.makedirs(UpperCAmelCase_ , exist_ok=UpperCAmelCase_) lowerCamelCase__: Any =os.path.join(UpperCAmelCase_ , DPR_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])) # BART tok lowerCamelCase__: str =[ "l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "\u0120", "\u0120l", "\u0120n", "\u0120lo", "\u0120low", "er", "\u0120lowest", "\u0120newer", "\u0120wider", "<unk>", ] lowerCamelCase__: Tuple =dict(zip(UpperCAmelCase_ , range(len(UpperCAmelCase_)))) lowerCamelCase__: Tuple =["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""] lowerCamelCase__: Any ={"unk_token": "<unk>"} lowerCamelCase__: str =os.path.join(self.tmpdirname , "bart_tokenizer") os.makedirs(UpperCAmelCase_ , exist_ok=UpperCAmelCase_) lowerCamelCase__: Dict =os.path.join(UpperCAmelCase_ , BART_VOCAB_FILES_NAMES["vocab_file"]) lowerCamelCase__: List[str] =os.path.join(UpperCAmelCase_ , BART_VOCAB_FILES_NAMES["merges_file"]) with open(self.vocab_file , "w" , encoding="utf-8") as fp: fp.write(json.dumps(UpperCAmelCase_) + "\n") with open(self.merges_file , "w" , encoding="utf-8") as fp: fp.write("\n".join(UpperCAmelCase_)) def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->DPRQuestionEncoderTokenizer: '''simple docstring''' return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname , "dpr_tokenizer")) def SCREAMING_SNAKE_CASE_ (self : Union[str, Any]) ->DPRContextEncoderTokenizer: '''simple docstring''' return DPRContextEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname , "dpr_tokenizer")) def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->BartTokenizer: '''simple docstring''' return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname , "bart_tokenizer")) def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->str: '''simple docstring''' shutil.rmtree(self.tmpdirname) def SCREAMING_SNAKE_CASE_ (self : int) ->Tuple: '''simple docstring''' lowerCamelCase__: Union[str, Any] =Dataset.from_dict( { "id": ["0", "1"], "text": ["foo", "bar"], "title": ["Foo", "Bar"], "embeddings": [np.ones(self.retrieval_vector_size), 2 * np.ones(self.retrieval_vector_size)], }) dataset.add_faiss_index("embeddings" , string_factory="Flat" , metric_type=faiss.METRIC_INNER_PRODUCT) return dataset def SCREAMING_SNAKE_CASE_ (self : Union[str, Any]) ->int: '''simple docstring''' lowerCamelCase__: Union[str, Any] =self.get_dummy_dataset() lowerCamelCase__: int =RagConfig( retrieval_vector_size=self.retrieval_vector_size , question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() , ) with patch("transformers.models.rag.retrieval_rag.load_dataset") as mock_load_dataset: lowerCamelCase__: int =dataset lowerCamelCase__: str =RagRetriever( UpperCAmelCase_ , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() , ) return retriever def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : bool) ->Union[str, Any]: '''simple docstring''' lowerCamelCase__: int =self.get_dummy_dataset() lowerCamelCase__: int =RagConfig( retrieval_vector_size=self.retrieval_vector_size , question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() , index_name="custom" , ) if from_disk: lowerCamelCase__: Optional[Any] =os.path.join(self.tmpdirname , "dataset") lowerCamelCase__: Tuple =os.path.join(self.tmpdirname , "index.faiss") dataset.get_index("embeddings").save(os.path.join(self.tmpdirname , "index.faiss")) dataset.drop_index("embeddings") dataset.save_to_disk(os.path.join(self.tmpdirname , "dataset")) del dataset lowerCamelCase__: Dict =RagRetriever( UpperCAmelCase_ , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() , ) else: lowerCamelCase__: Tuple =RagRetriever( UpperCAmelCase_ , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() , index=CustomHFIndex(config.retrieval_vector_size , UpperCAmelCase_) , ) return retriever def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Union[str, Any]: '''simple docstring''' lowerCamelCase__: List[Any] =Dataset.from_dict( { "id": ["0", "1"], "text": ["foo", "bar"], "title": ["Foo", "Bar"], "embeddings": [np.ones(self.retrieval_vector_size + 1), 2 * np.ones(self.retrieval_vector_size + 1)], }) dataset.add_faiss_index("embeddings" , string_factory="Flat" , metric_type=faiss.METRIC_INNER_PRODUCT) lowerCamelCase__: Dict =os.path.join(self.tmpdirname , "hf_bert_base.hnswSQ8_correct_phi_128.c_index") dataset.save_faiss_index("embeddings" , index_file_name + ".index.dpr") pickle.dump(dataset["id"] , open(index_file_name + ".index_meta.dpr" , "wb")) lowerCamelCase__: Dict =os.path.join(self.tmpdirname , "psgs_w100.tsv.pkl") lowerCamelCase__: str ={sample["id"]: [sample["text"], sample["title"]] for sample in dataset} pickle.dump(UpperCAmelCase_ , open(UpperCAmelCase_ , "wb")) lowerCamelCase__: Dict =RagConfig( retrieval_vector_size=self.retrieval_vector_size , question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() , index_name="legacy" , index_path=self.tmpdirname , ) lowerCamelCase__: Any =RagRetriever( UpperCAmelCase_ , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer()) return retriever def SCREAMING_SNAKE_CASE_ (self : int) ->List[str]: '''simple docstring''' lowerCamelCase__: Optional[Any] =1 lowerCamelCase__: List[Any] =self.get_dummy_canonical_hf_index_retriever() lowerCamelCase__: Union[str, Any] =np.array( [np.ones(self.retrieval_vector_size), -np.ones(self.retrieval_vector_size)] , dtype=np.floataa) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Optional[int] =retriever.retrieve(UpperCAmelCase_ , n_docs=UpperCAmelCase_) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size)) self.assertEqual(len(UpperCAmelCase_) , 2) self.assertEqual(sorted(doc_dicts[0]) , ["embeddings", "id", "text", "title"]) self.assertEqual(len(doc_dicts[0]["id"]) , UpperCAmelCase_) self.assertEqual(doc_dicts[0]["id"][0] , "1") # max inner product is reached with second doc self.assertEqual(doc_dicts[1]["id"][0] , "0") # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]]) def SCREAMING_SNAKE_CASE_ (self : List[str]) ->Any: '''simple docstring''' lowerCamelCase__: str =self.get_dummy_canonical_hf_index_retriever() with tempfile.TemporaryDirectory() as tmp_dirname: with patch("transformers.models.rag.retrieval_rag.load_dataset") as mock_load_dataset: lowerCamelCase__: List[Any] =self.get_dummy_dataset() retriever.save_pretrained(UpperCAmelCase_) lowerCamelCase__: List[str] =RagRetriever.from_pretrained(UpperCAmelCase_) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: Optional[Any] =np.array( [np.ones(self.retrieval_vector_size), -np.ones(self.retrieval_vector_size)] , dtype=np.floataa) lowerCamelCase__: Any =retriever.retrieve(UpperCAmelCase_ , n_docs=1) self.assertTrue(out is not None) def SCREAMING_SNAKE_CASE_ (self : Any) ->str: '''simple docstring''' lowerCamelCase__: Optional[int] =1 lowerCamelCase__: Optional[Any] =self.get_dummy_custom_hf_index_retriever(from_disk=UpperCAmelCase_) lowerCamelCase__: Any =np.array( [np.ones(self.retrieval_vector_size), -np.ones(self.retrieval_vector_size)] , dtype=np.floataa) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: str =retriever.retrieve(UpperCAmelCase_ , n_docs=UpperCAmelCase_) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size)) self.assertEqual(len(UpperCAmelCase_) , 2) self.assertEqual(sorted(doc_dicts[0]) , ["embeddings", "id", "text", "title"]) self.assertEqual(len(doc_dicts[0]["id"]) , UpperCAmelCase_) self.assertEqual(doc_dicts[0]["id"][0] , "1") # max inner product is reached with second doc self.assertEqual(doc_dicts[1]["id"][0] , "0") # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]]) def SCREAMING_SNAKE_CASE_ (self : str) ->List[Any]: '''simple docstring''' lowerCamelCase__: Tuple =self.get_dummy_custom_hf_index_retriever(from_disk=UpperCAmelCase_) with tempfile.TemporaryDirectory() as tmp_dirname: retriever.save_pretrained(UpperCAmelCase_) lowerCamelCase__: List[Any] =RagRetriever.from_pretrained(UpperCAmelCase_) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: Tuple =np.array( [np.ones(self.retrieval_vector_size), -np.ones(self.retrieval_vector_size)] , dtype=np.floataa) lowerCamelCase__: Any =retriever.retrieve(UpperCAmelCase_ , n_docs=1) self.assertTrue(out is not None) def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Any: '''simple docstring''' lowerCamelCase__: Tuple =1 lowerCamelCase__: Dict =self.get_dummy_custom_hf_index_retriever(from_disk=UpperCAmelCase_) lowerCamelCase__: str =np.array( [np.ones(self.retrieval_vector_size), -np.ones(self.retrieval_vector_size)] , dtype=np.floataa) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Optional[Any] =retriever.retrieve(UpperCAmelCase_ , n_docs=UpperCAmelCase_) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size)) self.assertEqual(len(UpperCAmelCase_) , 2) self.assertEqual(sorted(doc_dicts[0]) , ["embeddings", "id", "text", "title"]) self.assertEqual(len(doc_dicts[0]["id"]) , UpperCAmelCase_) self.assertEqual(doc_dicts[0]["id"][0] , "1") # max inner product is reached with second doc self.assertEqual(doc_dicts[1]["id"][0] , "0") # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]]) def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->Optional[int]: '''simple docstring''' lowerCamelCase__: List[str] =self.get_dummy_custom_hf_index_retriever(from_disk=UpperCAmelCase_) with tempfile.TemporaryDirectory() as tmp_dirname: retriever.save_pretrained(UpperCAmelCase_) lowerCamelCase__: Optional[Any] =RagRetriever.from_pretrained(UpperCAmelCase_) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: List[Any] =np.array( [np.ones(self.retrieval_vector_size), -np.ones(self.retrieval_vector_size)] , dtype=np.floataa) lowerCamelCase__: str =retriever.retrieve(UpperCAmelCase_ , n_docs=1) self.assertTrue(out is not None) def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->List[Any]: '''simple docstring''' lowerCamelCase__: Any =1 lowerCamelCase__: Optional[int] =self.get_dummy_legacy_index_retriever() lowerCamelCase__: Any =np.array( [np.ones(self.retrieval_vector_size), -np.ones(self.retrieval_vector_size)] , dtype=np.floataa) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Optional[int] =retriever.retrieve(UpperCAmelCase_ , n_docs=UpperCAmelCase_) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size)) self.assertEqual(len(UpperCAmelCase_) , 2) self.assertEqual(sorted(doc_dicts[0]) , ["text", "title"]) self.assertEqual(len(doc_dicts[0]["text"]) , UpperCAmelCase_) self.assertEqual(doc_dicts[0]["text"][0] , "bar") # max inner product is reached with second doc self.assertEqual(doc_dicts[1]["text"][0] , "foo") # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]]) def SCREAMING_SNAKE_CASE_ (self : Tuple) ->List[Any]: '''simple docstring''' lowerCamelCase__: str =self.get_dummy_legacy_index_retriever() with tempfile.TemporaryDirectory() as tmp_dirname: retriever.save_pretrained(UpperCAmelCase_) lowerCamelCase__: Optional[int] =RagRetriever.from_pretrained(UpperCAmelCase_) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: int =np.array( [np.ones(self.retrieval_vector_size), -np.ones(self.retrieval_vector_size)] , dtype=np.floataa) lowerCamelCase__: Tuple =retriever.retrieve(UpperCAmelCase_ , n_docs=1) self.assertTrue(out is not None) @require_torch @require_tokenizers @require_sentencepiece def SCREAMING_SNAKE_CASE_ (self : Dict) ->Union[str, Any]: '''simple docstring''' import torch lowerCamelCase__: Union[str, Any] =1 lowerCamelCase__: Optional[Any] =self.get_dummy_canonical_hf_index_retriever() lowerCamelCase__: str =[[5, 7], [10, 11]] lowerCamelCase__: List[str] =np.array( [np.ones(self.retrieval_vector_size), -np.ones(self.retrieval_vector_size)] , dtype=np.floataa) lowerCamelCase__: Optional[int] =retriever(UpperCAmelCase_ , UpperCAmelCase_ , prefix=retriever.config.generator.prefix , n_docs=UpperCAmelCase_) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Any =( out["context_input_ids"], out["context_attention_mask"], out["retrieved_doc_embeds"], ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size)) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_) self.assertIsInstance(UpperCAmelCase_ , np.ndarray) lowerCamelCase__: Optional[Any] =retriever( UpperCAmelCase_ , UpperCAmelCase_ , prefix=retriever.config.generator.prefix , n_docs=UpperCAmelCase_ , return_tensors="pt" , ) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Optional[Any] =( # noqa: F841 out["context_input_ids"], out["context_attention_mask"], out["retrieved_doc_embeds"], out["doc_ids"], ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size)) self.assertIsInstance(UpperCAmelCase_ , torch.Tensor) self.assertIsInstance(UpperCAmelCase_ , torch.Tensor) self.assertIsInstance(UpperCAmelCase_ , torch.Tensor) @require_torch @require_tokenizers @require_sentencepiece def SCREAMING_SNAKE_CASE_ (self : Any) ->Any: '''simple docstring''' lowerCamelCase__: Any =self.get_dpr_ctx_encoder_tokenizer() lowerCamelCase__: Dict =1 lowerCamelCase__: Tuple =self.get_dummy_custom_hf_index_retriever(from_disk=UpperCAmelCase_) retriever.set_ctx_encoder_tokenizer(UpperCAmelCase_) lowerCamelCase__: List[Any] =[[5, 7], [10, 11]] lowerCamelCase__: Any =np.array( [np.ones(self.retrieval_vector_size), -np.ones(self.retrieval_vector_size)] , dtype=np.floataa) lowerCamelCase__: List[Any] =retriever(UpperCAmelCase_ , UpperCAmelCase_ , prefix=retriever.config.generator.prefix , n_docs=UpperCAmelCase_) self.assertEqual( len(UpperCAmelCase_) , 6) # check whether the retriever output consist of 6 attributes including tokenized docs self.assertEqual( all(k in out for k in ("tokenized_doc_ids", "tokenized_doc_attention_mask")) , UpperCAmelCase_) # check for doc token related keys in dictionary.
59
from math import ceil, sqrt def lowerCAmelCase_ ( __a = 1000000 ) -> int: """simple docstring""" lowerCamelCase__: Any =0 for outer_width in range(3 , (limit // 4) + 2 ): if outer_width**2 > limit: lowerCamelCase__: Optional[int] =max(ceil(sqrt(outer_width**2 - limit ) ) , 1 ) else: lowerCamelCase__: Tuple =1 if (outer_width - hole_width_lower_bound) % 2: hole_width_lower_bound += 1 answer += (outer_width - hole_width_lower_bound - 2) // 2 + 1 return answer if __name__ == "__main__": print(f'{solution() = }')
59
1
import os import unittest from transformers.models.cpmant.tokenization_cpmant import VOCAB_FILES_NAMES, CpmAntTokenizer from transformers.testing_utils import require_jieba, tooslow from ...test_tokenization_common import TokenizerTesterMixin @require_jieba class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowercase_ = CpmAntTokenizer lowercase_ = False def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->List[str]: '''simple docstring''' super().setUp() lowerCamelCase__: Optional[int] =[ "<d>", "</d>", "<s>", "</s>", "</_>", "<unk>", "<pad>", "</n>", "我", "是", "C", "P", "M", "A", "n", "t", ] lowerCamelCase__: Any =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"]) with open(self.vocab_file , "w" , encoding="utf-8") as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens])) @tooslow def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->Optional[int]: '''simple docstring''' lowerCamelCase__: List[Any] =CpmAntTokenizer.from_pretrained("openbmb/cpm-ant-10b") lowerCamelCase__: Union[str, Any] ="今天天气真好!" lowerCamelCase__: int =["今天", "天气", "真", "好", "!"] lowerCamelCase__: List[str] =tokenizer.tokenize(UpperCAmelCase_) self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: Dict ="今天天气真好!" lowerCamelCase__: str =[tokenizer.bos_token] + tokens lowerCamelCase__: Union[str, Any] =[6, 9_802, 14_962, 2_082, 831, 244] self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase_) , UpperCAmelCase_) lowerCamelCase__: Tuple =tokenizer.decode(UpperCAmelCase_) self.assertEqual(UpperCAmelCase_ , UpperCAmelCase_)
59
def lowerCAmelCase_ ( __a = 50000000 ) -> int: """simple docstring""" lowerCamelCase__: Any =set() lowerCamelCase__: int =int((limit - 24) ** (1 / 2) ) lowerCamelCase__: Tuple =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 , __a ) ) ) for primea in primes: lowerCamelCase__: Optional[int] =primea * primea for primea in primes: lowerCamelCase__: List[str] =primea * primea * primea if square + cube >= limit - 16: break for primea in primes: lowerCamelCase__: int =primea * primea * primea * primea lowerCamelCase__: Optional[Any] =square + cube + tetr if total >= limit: break ret.add(__a ) return len(__a ) if __name__ == "__main__": print(f'{solution() = }')
59
1
def lowerCAmelCase_ ( __a ) -> "list[int]": """simple docstring""" if upper_limit < 0: raise ValueError("Limit for the Catalan sequence must be ≥ 0" ) lowerCamelCase__: List[str] =[0] * (upper_limit + 1) # Base case: C(0) = C(1) = 1 lowerCamelCase__: List[Any] =1 if upper_limit > 0: lowerCamelCase__: Tuple =1 # Recurrence relation: C(i) = sum(C(j).C(i-j-1)), from j = 0 to i for i in range(2 , upper_limit + 1 ): for j in range(__a ): catalan_list[i] += catalan_list[j] * catalan_list[i - j - 1] return catalan_list if __name__ == "__main__": print("\n********* Catalan Numbers Using Dynamic Programming ************\n") print("\n*** Enter -1 at any time to quit ***") print("\nEnter the upper limit (≥ 0) for the Catalan number sequence: ", end="") try: while True: __A = int(input().strip()) if N < 0: print("\n********* Goodbye!! ************") break else: print(f'The Catalan numbers from 0 through {N} are:') print(catalan_numbers(N)) print("Try another upper limit for the sequence: ", end="") except (NameError, ValueError): print("\n********* Invalid input, goodbye! ************\n") import doctest doctest.testmod()
59
from __future__ import annotations from decimal import Decimal from math import * # noqa: F403 from sympy import diff def lowerCAmelCase_ ( __a , __a , __a = 10**-10 ) -> float: """simple docstring""" lowerCamelCase__: List[str] =a while True: lowerCamelCase__: Optional[Any] =Decimal(__a ) - ( Decimal(eval(__a ) ) / Decimal(eval(str(diff(__a ) ) ) ) # noqa: S307 ) # This number dictates the accuracy of the answer if abs(eval(__a ) ) < precision: # noqa: S307 return float(__a ) # Let's Execute if __name__ == "__main__": # Find root of trigonometric function # Find value of pi print(f'The root of sin(x) = 0 is {newton_raphson("sin(x)", 2)}') # Find root of polynomial print(f'The root of x**2 - 5*x + 2 = 0 is {newton_raphson("x**2 - 5*x + 2", 0.4)}') # Find Square Root of 5 print(f'The root of log(x) - 1 = 0 is {newton_raphson("log(x) - 1", 2)}') # Exponential Roots print(f'The root of exp(x) - 1 = 0 is {newton_raphson("exp(x) - 1", 0)}')
59
1
import pytest from datasets.splits import SplitDict, SplitInfo from datasets.utils.py_utils import asdict @pytest.mark.parametrize( "split_dict" , [ SplitDict(), SplitDict({"train": SplitInfo(name="train" , num_bytes=1337 , num_examples=42 , dataset_name="my_dataset" )} ), SplitDict({"train": SplitInfo(name="train" , num_bytes=1337 , num_examples=42 )} ), SplitDict({"train": SplitInfo()} ), ] , ) def lowerCAmelCase_ ( __a ) -> Tuple: """simple docstring""" lowerCamelCase__: List[Any] =split_dict._to_yaml_list() assert len(__a ) == len(__a ) lowerCamelCase__: List[str] =SplitDict._from_yaml_list(__a ) for split_name, split_info in split_dict.items(): # dataset_name field is deprecated, and is therefore not part of the YAML dump lowerCamelCase__: Any =None # the split name of split_dict takes over the name of the split info object lowerCamelCase__: str =split_name assert split_dict == reloaded @pytest.mark.parametrize( "split_info" , [SplitInfo(), SplitInfo(dataset_name=__a ), SplitInfo(dataset_name="my_dataset" )] ) def lowerCAmelCase_ ( __a ) -> List[str]: """simple docstring""" lowerCamelCase__: List[str] =asdict(SplitDict({"train": split_info} ) ) assert "dataset_name" in split_dict_asdict["train"] assert split_dict_asdict["train"]["dataset_name"] == split_info.dataset_name
59
import numpy as np from numpy import ndarray from scipy.optimize import Bounds, LinearConstraint, minimize def lowerCAmelCase_ ( __a ) -> float: """simple docstring""" return np.dot(__a , __a ) class _SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__(self : List[str] , *, UpperCAmelCase_ : float = np.inf , UpperCAmelCase_ : str = "linear" , UpperCAmelCase_ : float = 0.0 , ) ->None: '''simple docstring''' lowerCamelCase__: Dict =regularization lowerCamelCase__: Any =gamma if kernel == "linear": lowerCamelCase__: Dict =self.__linear elif kernel == "rbf": if self.gamma == 0: raise ValueError("rbf kernel requires gamma") if not isinstance(self.gamma , (float, int)): raise ValueError("gamma must be float or int") if not self.gamma > 0: raise ValueError("gamma must be > 0") lowerCamelCase__: Tuple =self.__rbf # in the future, there could be a default value like in sklearn # sklear: def_gamma = 1/(n_features * X.var()) (wiki) # previously it was 1/(n_features) else: lowerCamelCase__: Optional[Any] =F"""Unknown kernel: {kernel}""" raise ValueError(UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : ndarray , UpperCAmelCase_ : ndarray) ->float: '''simple docstring''' return np.dot(UpperCAmelCase_ , UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : ndarray , UpperCAmelCase_ : ndarray) ->float: '''simple docstring''' return np.exp(-(self.gamma * norm_squared(vectora - vectora))) def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : list[ndarray] , UpperCAmelCase_ : ndarray) ->None: '''simple docstring''' lowerCamelCase__: Optional[Any] =observations lowerCamelCase__: Optional[int] =classes # using Wolfe's Dual to calculate w. # Primal problem: minimize 1/2*norm_squared(w) # constraint: yn(w . xn + b) >= 1 # # With l a vector # Dual problem: maximize sum_n(ln) - # 1/2 * sum_n(sum_m(ln*lm*yn*ym*xn . xm)) # constraint: self.C >= ln >= 0 # and sum_n(ln*yn) = 0 # Then we get w using w = sum_n(ln*yn*xn) # At the end we can get b ~= mean(yn - w . xn) # # Since we use kernels, we only need l_star to calculate b # and to classify observations ((lowerCamelCase__) , ): List[str] =np.shape(UpperCAmelCase_) def to_minimize(UpperCAmelCase_ : ndarray) -> float: lowerCamelCase__: int =0 ((lowerCamelCase__) , ): Optional[Any] =np.shape(UpperCAmelCase_) for i in range(UpperCAmelCase_): for j in range(UpperCAmelCase_): s += ( candidate[i] * candidate[j] * classes[i] * classes[j] * self.kernel(observations[i] , observations[j]) ) return 1 / 2 * s - sum(UpperCAmelCase_) lowerCamelCase__: List[Any] =LinearConstraint(UpperCAmelCase_ , 0 , 0) lowerCamelCase__: str =Bounds(0 , self.regularization) lowerCamelCase__: Union[str, Any] =minimize( UpperCAmelCase_ , np.ones(UpperCAmelCase_) , bounds=UpperCAmelCase_ , constraints=[ly_contraint]).x lowerCamelCase__: str =l_star # calculating mean offset of separation plane to points lowerCamelCase__: Tuple =0 for i in range(UpperCAmelCase_): for j in range(UpperCAmelCase_): s += classes[i] - classes[i] * self.optimum[i] * self.kernel( observations[i] , observations[j]) lowerCamelCase__: int =s / n def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : ndarray) ->int: '''simple docstring''' lowerCamelCase__: Optional[Any] =sum( self.optimum[n] * self.classes[n] * self.kernel(self.observations[n] , UpperCAmelCase_) for n in range(len(self.classes))) return 1 if s + self.offset >= 0 else -1 if __name__ == "__main__": import doctest doctest.testmod()
59
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available __A = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ["MLukeTokenizer"] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mluke import MLukeTokenizer else: import sys __A = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
59
import logging import os from typing import Dict, List, Optional, Union import torch import torch.nn as nn from accelerate.utils.imports import ( is_abit_bnb_available, is_abit_bnb_available, is_bnb_available, ) from ..big_modeling import dispatch_model, init_empty_weights from .dataclasses import BnbQuantizationConfig from .modeling import ( find_tied_parameters, get_balanced_memory, infer_auto_device_map, load_checkpoint_in_model, offload_weight, set_module_tensor_to_device, ) if is_bnb_available(): import bitsandbytes as bnb from copy import deepcopy __A = logging.getLogger(__name__) def lowerCAmelCase_ ( __a , __a , __a = None , __a = None , __a = None , __a = None , __a = None , __a = False , ) -> str: """simple docstring""" lowerCamelCase__: int =bnb_quantization_config.load_in_abit lowerCamelCase__: Any =bnb_quantization_config.load_in_abit if load_in_abit and not is_abit_bnb_available(): raise ImportError( "You have a version of `bitsandbytes` that is not compatible with 8bit quantization," " make sure you have the latest version of `bitsandbytes` installed." ) if load_in_abit and not is_abit_bnb_available(): raise ValueError( "You have a version of `bitsandbytes` that is not compatible with 4bit quantization," "make sure you have the latest version of `bitsandbytes` installed." ) lowerCamelCase__: List[Any] =[] # custom device map if isinstance(__a , __a ) and len(device_map.keys() ) > 1: lowerCamelCase__: Optional[int] =[key for key, value in device_map.items() if value in ["disk", "cpu"]] # We keep some modules such as the lm_head in their original dtype for numerical stability reasons if bnb_quantization_config.skip_modules is None: lowerCamelCase__: Any =get_keys_to_not_convert(__a ) # add cpu modules to skip modules only for 4-bit modules if load_in_abit: bnb_quantization_config.skip_modules.extend(__a ) lowerCamelCase__: List[str] =bnb_quantization_config.skip_modules # We add the modules we want to keep in full precision if bnb_quantization_config.keep_in_fpaa_modules is None: lowerCamelCase__: List[Any] =[] lowerCamelCase__: int =bnb_quantization_config.keep_in_fpaa_modules modules_to_not_convert.extend(__a ) # compatibility with peft lowerCamelCase__: List[str] =load_in_abit lowerCamelCase__: int =load_in_abit lowerCamelCase__: Tuple =get_parameter_device(__a ) if model_device.type != "meta": # quantization of an already loaded model logger.warning( "It is not recommended to quantize a loaded model. " "The model should be instantiated under the `init_empty_weights` context manager." ) lowerCamelCase__: Tuple =replace_with_bnb_layers(__a , __a , modules_to_not_convert=__a ) # convert param to the right dtype lowerCamelCase__: Dict =bnb_quantization_config.torch_dtype for name, param in model.state_dict().items(): if any(module_to_keep_in_fpaa in name for module_to_keep_in_fpaa in keep_in_fpaa_modules ): param.to(torch.floataa ) if param.dtype != torch.floataa: lowerCamelCase__: str =name.replace(".weight" , "" ).replace(".bias" , "" ) lowerCamelCase__: Optional[Any] =getattr(__a , __a , __a ) if param is not None: param.to(torch.floataa ) elif torch.is_floating_point(__a ): param.to(__a ) if model_device.type == "cuda": # move everything to cpu in the first place because we can't do quantization if the weights are already on cuda model.cuda(torch.cuda.current_device() ) torch.cuda.empty_cache() elif torch.cuda.is_available(): model.to(torch.cuda.current_device() ) else: raise RuntimeError("No GPU found. A GPU is needed for quantization." ) logger.info( F"""The model device type is {model_device.type}. However, cuda is needed for quantization.""" "We move the model to cuda." ) return model elif weights_location is None: raise RuntimeError( F"""`weights_location` needs to be the folder path containing the weights of the model, but we found {weights_location} """ ) else: with init_empty_weights(): lowerCamelCase__: str =replace_with_bnb_layers( __a , __a , modules_to_not_convert=__a ) lowerCamelCase__: Optional[Any] =get_quantized_model_device_map( __a , __a , __a , max_memory=__a , no_split_module_classes=__a , ) if offload_state_dict is None and device_map is not None and "disk" in device_map.values(): lowerCamelCase__: Any =True lowerCamelCase__: List[str] =any(x in list(device_map.values() ) for x in ["cpu", "disk"] ) load_checkpoint_in_model( __a , __a , __a , dtype=bnb_quantization_config.torch_dtype , offload_folder=__a , offload_state_dict=__a , keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules , offload_abit_bnb=load_in_abit and offload , ) return dispatch_model(__a , device_map=__a , offload_dir=__a ) def lowerCAmelCase_ ( __a , __a , __a=None , __a=None , __a=None ) -> str: """simple docstring""" if device_map is None: if torch.cuda.is_available(): lowerCamelCase__: str ={"": torch.cuda.current_device()} else: raise RuntimeError("No GPU found. A GPU is needed for quantization." ) logger.info("The device_map was not initialized." "Setting device_map to `{'':torch.cuda.current_device()}`." ) if isinstance(__a , __a ): if device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]: raise ValueError( "If passing a string for `device_map`, please choose 'auto', 'balanced', 'balanced_low_0' or " "'sequential'." ) lowerCamelCase__: Optional[int] ={} special_dtypes.update( { name: bnb_quantization_config.torch_dtype for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.skip_modules ) } ) special_dtypes.update( { name: torch.floataa for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.keep_in_fpaa_modules ) } ) lowerCamelCase__: Optional[Any] ={} lowerCamelCase__: str =special_dtypes lowerCamelCase__: List[str] =no_split_module_classes lowerCamelCase__: Dict =bnb_quantization_config.target_dtype # get max_memory for each device. if device_map != "sequential": lowerCamelCase__: Optional[Any] =get_balanced_memory( __a , low_zero=(device_map == "balanced_low_0") , max_memory=__a , **__a , ) lowerCamelCase__: Union[str, Any] =max_memory lowerCamelCase__: Dict =infer_auto_device_map(__a , **__a ) if isinstance(__a , __a ): # check if don't have any quantized module on the cpu lowerCamelCase__: Union[str, Any] =bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules lowerCamelCase__: List[Any] ={ key: device_map[key] for key in device_map.keys() if key not in modules_not_to_convert } for device in ["cpu", "disk"]: if device in device_map_without_some_modules.values(): if bnb_quantization_config.load_in_abit: raise ValueError( "\n Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit\n the quantized model. If you want to dispatch the model on the CPU or the disk while keeping\n these modules in `torch_dtype`, you need to pass a custom `device_map` to\n `load_and_quantize_model`. Check\n https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk\n for more details.\n " ) else: logger.info( "Some modules are are offloaded to the CPU or the disk. Note that these modules will be converted to 8-bit" ) del device_map_without_some_modules return device_map def lowerCAmelCase_ ( __a , __a , __a=None , __a=None ) -> Optional[Any]: """simple docstring""" if modules_to_not_convert is None: lowerCamelCase__: List[Any] =[] lowerCamelCase__ , lowerCamelCase__: Any =_replace_with_bnb_layers( __a , __a , __a , __a ) if not has_been_replaced: logger.warning( "You are loading your model in 8bit or 4bit but no linear modules were found in your model." " this can happen for some architectures such as gpt2 that uses Conv1D instead of Linear layers." " Please double check your model architecture, or submit an issue on github if you think this is" " a bug." ) return model def lowerCAmelCase_ ( __a , __a , __a=None , __a=None , ) -> List[Any]: """simple docstring""" lowerCamelCase__: Optional[int] =False for name, module in model.named_children(): if current_key_name is None: lowerCamelCase__: Optional[Any] =[] current_key_name.append(__a ) if isinstance(__a , nn.Linear ) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` lowerCamelCase__: List[str] =".".join(__a ) lowerCamelCase__: Optional[Any] =True for key in modules_to_not_convert: if ( (key in current_key_name_str) and (key + "." in current_key_name_str) ) or key == current_key_name_str: lowerCamelCase__: int =False break if proceed: # Load bnb module with empty weight and replace ``nn.Linear` module if bnb_quantization_config.load_in_abit: lowerCamelCase__: Optional[int] =bnb.nn.LinearabitLt( module.in_features , module.out_features , module.bias is not None , has_fpaa_weights=__a , threshold=bnb_quantization_config.llm_inta_threshold , ) elif bnb_quantization_config.load_in_abit: lowerCamelCase__: Dict =bnb.nn.Linearabit( module.in_features , module.out_features , module.bias is not None , bnb_quantization_config.bnb_abit_compute_dtype , compress_statistics=bnb_quantization_config.bnb_abit_use_double_quant , quant_type=bnb_quantization_config.bnb_abit_quant_type , ) else: raise ValueError("load_in_8bit and load_in_4bit can't be both False" ) lowerCamelCase__: Dict =module.weight.data if module.bias is not None: lowerCamelCase__: List[Any] =module.bias.data bnb_module.requires_grad_(__a ) setattr(__a , __a , __a ) lowerCamelCase__: int =True if len(list(module.children() ) ) > 0: lowerCamelCase__ , lowerCamelCase__: List[str] =_replace_with_bnb_layers( __a , __a , __a , __a ) lowerCamelCase__: Union[str, Any] =has_been_replaced | _has_been_replaced # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def lowerCAmelCase_ ( __a ) -> List[Any]: """simple docstring""" with init_empty_weights(): lowerCamelCase__: Any =deepcopy(__a ) # this has 0 cost since it is done inside `init_empty_weights` context manager` lowerCamelCase__: str =find_tied_parameters(__a ) # For compatibility with Accelerate < 0.18 if isinstance(__a , __a ): lowerCamelCase__: int =sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() ) else: lowerCamelCase__: str =sum(__a , [] ) lowerCamelCase__: str =len(__a ) > 0 # Check if it is a base model lowerCamelCase__: Optional[Any] =False if hasattr(__a , "base_model_prefix" ): lowerCamelCase__: Union[str, Any] =not hasattr(__a , model.base_model_prefix ) # Ignore this for base models (BertModel, GPT2Model, etc.) if (not has_tied_params) and is_base_model: return [] # otherwise they have an attached head lowerCamelCase__: Optional[int] =list(model.named_children() ) lowerCamelCase__: Optional[int] =[list_modules[-1][0]] # add last module together with tied weights lowerCamelCase__: Union[str, Any] =set(__a ) - set(__a ) lowerCamelCase__: List[str] =list(set(__a ) ) + list(__a ) # remove ".weight" from the keys lowerCamelCase__: List[Any] =[".weight", ".bias"] lowerCamelCase__: Tuple =[] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: lowerCamelCase__: Optional[Any] =name.replace(__a , "" ) filtered_module_names.append(__a ) return filtered_module_names def lowerCAmelCase_ ( __a ) -> Tuple: """simple docstring""" for m in model.modules(): if isinstance(__a , bnb.nn.Linearabit ): return True return False def lowerCAmelCase_ ( __a ) -> List[str]: """simple docstring""" return next(parameter.parameters() ).device def lowerCAmelCase_ ( __a , __a , __a , __a , __a , __a , __a ) -> Any: """simple docstring""" if fpaa_statistics is None: set_module_tensor_to_device(__a , __a , 0 , dtype=__a , value=__a ) lowerCamelCase__: Dict =param_name lowerCamelCase__: Tuple =model if "." in tensor_name: lowerCamelCase__: Any =tensor_name.split("." ) for split in splits[:-1]: lowerCamelCase__: Any =getattr(__a , __a ) if new_module is None: raise ValueError(F"""{module} has no attribute {split}.""" ) lowerCamelCase__: str =new_module lowerCamelCase__: int =splits[-1] # offload weights lowerCamelCase__: str =False offload_weight(module._parameters[tensor_name] , __a , __a , index=__a ) if hasattr(module._parameters[tensor_name] , "SCB" ): offload_weight( module._parameters[tensor_name].SCB , param_name.replace("weight" , "SCB" ) , __a , index=__a , ) else: offload_weight(__a , __a , __a , index=__a ) offload_weight(__a , param_name.replace("weight" , "SCB" ) , __a , index=__a ) set_module_tensor_to_device(__a , __a , "meta" , dtype=__a , value=torch.empty(*param.size() ) )
59
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) __A = { "configuration_blip": [ "BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP", "BlipConfig", "BlipTextConfig", "BlipVisionConfig", ], "processing_blip": ["BlipProcessor"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ["BlipImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ "BLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "BlipModel", "BlipPreTrainedModel", "BlipForConditionalGeneration", "BlipForQuestionAnswering", "BlipVisionModel", "BlipTextModel", "BlipForImageTextRetrieval", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ "TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "TFBlipModel", "TFBlipPreTrainedModel", "TFBlipForConditionalGeneration", "TFBlipForQuestionAnswering", "TFBlipVisionModel", "TFBlipTextModel", "TFBlipForImageTextRetrieval", ] if TYPE_CHECKING: from .configuration_blip import BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, BlipConfig, BlipTextConfig, BlipVisionConfig from .processing_blip import BlipProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_blip import BlipImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blip import ( BLIP_PRETRAINED_MODEL_ARCHIVE_LIST, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, BlipModel, BlipPreTrainedModel, BlipTextModel, BlipVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blip import ( TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST, TFBlipForConditionalGeneration, TFBlipForImageTextRetrieval, TFBlipForQuestionAnswering, TFBlipModel, TFBlipPreTrainedModel, TFBlipTextModel, TFBlipVisionModel, ) else: import sys __A = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
59
from __future__ import annotations from math import pi def lowerCAmelCase_ ( __a , __a , __a ) -> dict[str, float]: """simple docstring""" if (inductance, frequency, reactance).count(0 ) != 1: raise ValueError("One and only one argument must be 0" ) if inductance < 0: raise ValueError("Inductance cannot be negative" ) if frequency < 0: raise ValueError("Frequency cannot be negative" ) if reactance < 0: raise ValueError("Inductive reactance cannot be negative" ) if inductance == 0: return {"inductance": reactance / (2 * pi * frequency)} elif frequency == 0: return {"frequency": reactance / (2 * pi * inductance)} elif reactance == 0: return {"reactance": 2 * pi * frequency * inductance} else: raise ValueError("Exactly one argument must be 0" ) if __name__ == "__main__": import doctest doctest.testmod()
59
1
from queue import Queue from typing import TYPE_CHECKING, Optional if TYPE_CHECKING: from ..models.auto import AutoTokenizer class _SCREAMING_SNAKE_CASE : '''simple docstring''' def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : List[str]) ->Tuple: '''simple docstring''' raise NotImplementedError() def SCREAMING_SNAKE_CASE_ (self : List[str]) ->List[str]: '''simple docstring''' raise NotImplementedError() class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__(self : Union[str, Any] , UpperCAmelCase_ : "AutoTokenizer" , UpperCAmelCase_ : bool = False , **UpperCAmelCase_ : Optional[int]) ->Tuple: '''simple docstring''' lowerCamelCase__: str =tokenizer lowerCamelCase__: str =skip_prompt lowerCamelCase__: str =decode_kwargs # variables used in the streaming process lowerCamelCase__: Dict =[] lowerCamelCase__: int =0 lowerCamelCase__: Tuple =True def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : Any) ->List[str]: '''simple docstring''' if len(value.shape) > 1 and value.shape[0] > 1: raise ValueError("TextStreamer only supports batch size 1") elif len(value.shape) > 1: lowerCamelCase__: Tuple =value[0] if self.skip_prompt and self.next_tokens_are_prompt: lowerCamelCase__: List[str] =False return # Add the new token to the cache and decodes the entire thing. self.token_cache.extend(value.tolist()) lowerCamelCase__: Optional[Any] =self.tokenizer.decode(self.token_cache , **self.decode_kwargs) # After the symbol for a new line, we flush the cache. if text.endswith("\n"): lowerCamelCase__: Optional[Any] =text[self.print_len :] lowerCamelCase__: Union[str, Any] =[] lowerCamelCase__: List[str] =0 # If the last token is a CJK character, we print the characters. elif len(UpperCAmelCase_) > 0 and self._is_chinese_char(ord(text[-1])): lowerCamelCase__: Dict =text[self.print_len :] self.print_len += len(UpperCAmelCase_) # Otherwise, prints until the last space char (simple heuristic to avoid printing incomplete words, # which may change with the subsequent token -- there are probably smarter ways to do this!) else: lowerCamelCase__: Any =text[self.print_len : text.rfind(" ") + 1] self.print_len += len(UpperCAmelCase_) self.on_finalized_text(UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->Dict: '''simple docstring''' if len(self.token_cache) > 0: lowerCamelCase__: int =self.tokenizer.decode(self.token_cache , **self.decode_kwargs) lowerCamelCase__: Optional[int] =text[self.print_len :] lowerCamelCase__: int =[] lowerCamelCase__: str =0 else: lowerCamelCase__: Optional[int] ="" lowerCamelCase__: Optional[Any] =True self.on_finalized_text(UpperCAmelCase_ , stream_end=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : bool = False) ->Tuple: '''simple docstring''' print(UpperCAmelCase_ , flush=UpperCAmelCase_ , end="" if not stream_end else None) def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , UpperCAmelCase_ : Optional[Any]) ->Union[str, 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 class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__(self : Dict , UpperCAmelCase_ : "AutoTokenizer" , UpperCAmelCase_ : bool = False , UpperCAmelCase_ : Optional[float] = None , **UpperCAmelCase_ : List[str]) ->List[Any]: '''simple docstring''' super().__init__(UpperCAmelCase_ , UpperCAmelCase_ , **UpperCAmelCase_) lowerCamelCase__: int =Queue() lowerCamelCase__: List[Any] =None lowerCamelCase__: str =timeout def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : str , UpperCAmelCase_ : bool = False) ->Optional[int]: '''simple docstring''' self.text_queue.put(UpperCAmelCase_ , timeout=self.timeout) if stream_end: self.text_queue.put(self.stop_signal , timeout=self.timeout) def __iter__(self : Optional[int]) ->List[str]: '''simple docstring''' return self def SCREAMING_SNAKE_CASE_ (self : List[str]) ->List[str]: '''simple docstring''' lowerCamelCase__: str =self.text_queue.get(timeout=self.timeout) if value == self.stop_signal: raise StopIteration() else: return value
59
import pyarrow.parquet as pq import pytest from datasets import Audio, Dataset, DatasetDict, Features, NamedSplit, Sequence, Value, config from datasets.features.image import Image from datasets.io.parquet import ParquetDatasetReader, ParquetDatasetWriter, get_writer_batch_size from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def lowerCAmelCase_ ( __a , __a ) -> List[Any]: """simple docstring""" assert isinstance(__a , __a ) 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 lowerCAmelCase_ ( __a , __a , __a ) -> Any: """simple docstring""" lowerCamelCase__: Any =tmp_path / "cache" lowerCamelCase__: Optional[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(): lowerCamelCase__: Tuple =ParquetDatasetReader(__a , cache_dir=__a , keep_in_memory=__a ).read() _check_parquet_dataset(__a , __a ) @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 lowerCAmelCase_ ( __a , __a , __a ) -> List[str]: """simple docstring""" lowerCamelCase__: int =tmp_path / "cache" lowerCamelCase__: Tuple ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: Union[str, Any] =features.copy() if features else default_expected_features lowerCamelCase__: Optional[int] =( Features({feature: Value(__a ) for feature, dtype in features.items()} ) if features is not None else None ) lowerCamelCase__: int =ParquetDatasetReader(__a , features=__a , cache_dir=__a ).read() _check_parquet_dataset(__a , __a ) @pytest.mark.parametrize("split" , [None, NamedSplit("train" ), "train", "test"] ) def lowerCAmelCase_ ( __a , __a , __a ) -> Any: """simple docstring""" lowerCamelCase__: Any =tmp_path / "cache" lowerCamelCase__: Optional[Any] ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: Optional[Any] =ParquetDatasetReader(__a , cache_dir=__a , split=__a ).read() _check_parquet_dataset(__a , __a ) assert dataset.split == split if split else "train" @pytest.mark.parametrize("path_type" , [str, list] ) def lowerCAmelCase_ ( __a , __a , __a ) -> int: """simple docstring""" if issubclass(__a , __a ): lowerCamelCase__: List[Any] =parquet_path elif issubclass(__a , __a ): lowerCamelCase__: str =[parquet_path] lowerCamelCase__: Tuple =tmp_path / "cache" lowerCamelCase__: Optional[Any] ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: int =ParquetDatasetReader(__a , cache_dir=__a ).read() _check_parquet_dataset(__a , __a ) def lowerCAmelCase_ ( __a , __a , __a=("train",) ) -> Dict: """simple docstring""" assert isinstance(__a , __a ) for split in splits: lowerCamelCase__: Tuple =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 lowerCAmelCase_ ( __a , __a , __a ) -> Any: """simple docstring""" lowerCamelCase__: List[Any] =tmp_path / "cache" lowerCamelCase__: Optional[Any] ={"col_1": "string", "col_2": "int64", "col_3": "float64"} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): lowerCamelCase__: Tuple =ParquetDatasetReader( {"train": parquet_path} , cache_dir=__a , keep_in_memory=__a ).read() _check_parquet_datasetdict(__a , __a ) @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 lowerCAmelCase_ ( __a , __a , __a ) -> Optional[Any]: """simple docstring""" lowerCamelCase__: Tuple =tmp_path / "cache" lowerCamelCase__: Optional[int] ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: List[Any] =features.copy() if features else default_expected_features lowerCamelCase__: int =( Features({feature: Value(__a ) for feature, dtype in features.items()} ) if features is not None else None ) lowerCamelCase__: Optional[Any] =ParquetDatasetReader({"train": parquet_path} , features=__a , cache_dir=__a ).read() _check_parquet_datasetdict(__a , __a ) @pytest.mark.parametrize("split" , [None, NamedSplit("train" ), "train", "test"] ) def lowerCAmelCase_ ( __a , __a , __a ) -> Union[str, Any]: """simple docstring""" if split: lowerCamelCase__: Any ={split: parquet_path} else: lowerCamelCase__: int ="train" lowerCamelCase__: Any ={"train": parquet_path, "test": parquet_path} lowerCamelCase__: str =tmp_path / "cache" lowerCamelCase__: Any ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: int =ParquetDatasetReader(__a , cache_dir=__a ).read() _check_parquet_datasetdict(__a , __a , splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() ) def lowerCAmelCase_ ( __a , __a ) -> int: """simple docstring""" lowerCamelCase__: List[str] =ParquetDatasetWriter(__a , tmp_path / "foo.parquet" ) assert writer.write() > 0 lowerCamelCase__: List[str] =pq.ParquetFile(tmp_path / "foo.parquet" ) lowerCamelCase__: List[str] =pf.read() assert dataset.data.table == output_table def lowerCAmelCase_ ( __a , __a ) -> List[str]: """simple docstring""" lowerCamelCase__: List[str] =str(shared_datadir / "test_image_rgb.jpg" ) lowerCamelCase__: Union[str, Any] ={"image": [image_path]} lowerCamelCase__: Optional[Any] =Features({"image": Image()} ) lowerCamelCase__: Optional[int] =Dataset.from_dict(__a , features=__a ) lowerCamelCase__: Optional[int] =ParquetDatasetWriter(__a , tmp_path / "foo.parquet" ) assert writer.write() > 0 lowerCamelCase__: Dict =Dataset.from_parquet(str(tmp_path / "foo.parquet" ) ) assert dataset.features == reloaded_dataset.features lowerCamelCase__: Optional[Any] =ParquetDatasetReader(str(tmp_path / "foo.parquet" ) , streaming=__a ).read() assert dataset.features == reloaded_iterable_dataset.features @pytest.mark.parametrize( "feature, expected" , [ (Features({"foo": Value("int32" )} ), None), (Features({"image": Image(), "foo": Value("int32" )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS), (Features({"nested": Sequence(Audio() )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS), ] , ) def lowerCAmelCase_ ( __a , __a ) -> Optional[Any]: """simple docstring""" assert get_writer_batch_size(__a ) == expected
59
1
# Usage: # ./gen-card-facebook-wmt19.py import os from pathlib import Path def lowerCAmelCase_ ( __a , __a , __a ) -> Optional[Any]: """simple docstring""" lowerCamelCase__: Any ={ "en": "Machine learning is great, isn't it?", "ru": "Машинное обучение - это здорово, не так ли?", "de": "Maschinelles Lernen ist großartig, oder?", } # BLUE scores as follows: # "pair": [fairseq, transformers] lowerCamelCase__: Optional[Any] ={ "ru-en": ["[41.3](http://matrix.statmt.org/matrix/output/1907?run_id=6937)", "39.20"], "en-ru": ["[36.4](http://matrix.statmt.org/matrix/output/1914?run_id=6724)", "33.47"], "en-de": ["[43.1](http://matrix.statmt.org/matrix/output/1909?run_id=6862)", "42.83"], "de-en": ["[42.3](http://matrix.statmt.org/matrix/output/1902?run_id=6750)", "41.35"], } lowerCamelCase__: Union[str, Any] =F"""{src_lang}-{tgt_lang}""" lowerCamelCase__: Dict =F""" --- language: - {src_lang} - {tgt_lang} thumbnail: tags: - translation - wmt19 - facebook license: apache-2.0 datasets: - wmt19 metrics: - bleu --- # FSMT ## Model description This is a ported version of [fairseq wmt19 transformer](https://github.com/pytorch/fairseq/blob/master/examples/wmt19/README.md) for {src_lang}-{tgt_lang}. For more details, please see, [Facebook FAIR's WMT19 News Translation Task Submission](https://arxiv.org/abs/1907.06616). The abbreviation FSMT stands for FairSeqMachineTranslation All four models are available: * [wmt19-en-ru](https://huggingface.co/facebook/wmt19-en-ru) * [wmt19-ru-en](https://huggingface.co/facebook/wmt19-ru-en) * [wmt19-en-de](https://huggingface.co/facebook/wmt19-en-de) * [wmt19-de-en](https://huggingface.co/facebook/wmt19-de-en) ## Intended uses & limitations #### How to use ```python from transformers import FSMTForConditionalGeneration, FSMTTokenizer mname = \"facebook/wmt19-{src_lang}-{tgt_lang}\" tokenizer = FSMTTokenizer.from_pretrained(mname) model = FSMTForConditionalGeneration.from_pretrained(mname) input = \"{texts[src_lang]}\" input_ids = tokenizer.encode(input, return_tensors=\"pt\") outputs = model.generate(input_ids) decoded = tokenizer.decode(outputs[0], skip_special_tokens=True) print(decoded) # {texts[tgt_lang]} ``` #### Limitations and bias - The original (and this ported model) doesn't seem to handle well inputs with repeated sub-phrases, [content gets truncated](https://discuss.huggingface.co/t/issues-with-translating-inputs-containing-repeated-phrases/981) ## Training data Pretrained weights were left identical to the original model released by fairseq. For more details, please, see the [paper](https://arxiv.org/abs/1907.06616). ## Eval results pair | fairseq | transformers -------|---------|---------- {pair} | {scores[pair][0]} | {scores[pair][1]} The score is slightly below the score reported by `fairseq`, since `transformers`` currently doesn't support: - model ensemble, therefore the best performing checkpoint was ported (``model4.pt``). - re-ranking The score was calculated using this code: ```bash git clone https://github.com/huggingface/transformers cd transformers export PAIR={pair} export DATA_DIR=data/$PAIR export SAVE_DIR=data/$PAIR export BS=8 export NUM_BEAMS=15 mkdir -p $DATA_DIR sacrebleu -t wmt19 -l $PAIR --echo src > $DATA_DIR/val.source sacrebleu -t wmt19 -l $PAIR --echo ref > $DATA_DIR/val.target echo $PAIR PYTHONPATH=\"src:examples/seq2seq\" python examples/seq2seq/run_eval.py facebook/wmt19-$PAIR $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS ``` note: fairseq reports using a beam of 50, so you should get a slightly higher score if re-run with `--num_beams 50`. ## Data Sources - [training, etc.](http://www.statmt.org/wmt19/) - [test set](http://matrix.statmt.org/test_sets/newstest2019.tgz?1556572561) ### BibTeX entry and citation info ```bibtex @inproceedings{{..., year={{2020}}, title={{Facebook FAIR's WMT19 News Translation Task Submission}}, author={{Ng, Nathan and Yee, Kyra and Baevski, Alexei and Ott, Myle and Auli, Michael and Edunov, Sergey}}, booktitle={{Proc. of WMT}}, }} ``` ## TODO - port model ensemble (fairseq uses 4 model checkpoints) """ os.makedirs(__a , exist_ok=__a ) lowerCamelCase__: int =os.path.join(__a , "README.md" ) print(F"""Generating {path}""" ) with open(__a , "w" , encoding="utf-8" ) as f: f.write(__a ) # make sure we are under the root of the project __A = Path(__file__).resolve().parent.parent.parent __A = repo_dir / "model_cards" for model_name in ["wmt19-ru-en", "wmt19-en-ru", "wmt19-en-de", "wmt19-de-en"]: __A , __A , __A = model_name.split("-") __A = model_cards_dir / "facebook" / model_name write_model_card(model_card_dir, src_lang=src_lang, tgt_lang=tgt_lang)
59
import unittest from transformers.models.xlm_prophetnet.tokenization_xlm_prophetnet import SPIECE_UNDERLINE, XLMProphetNetTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin __A = get_tests_dir("fixtures/test_sentencepiece.model") @require_sentencepiece class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowercase_ = XLMProphetNetTokenizer lowercase_ = False lowercase_ = True def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Optional[Any]: '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing lowerCamelCase__: Any =XLMProphetNetTokenizer(UpperCAmelCase_ , keep_accents=UpperCAmelCase_) tokenizer.save_pretrained(self.tmpdirname) def SCREAMING_SNAKE_CASE_ (self : str) ->str: '''simple docstring''' lowerCamelCase__: List[Any] ="[PAD]" lowerCamelCase__: Tuple =0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCAmelCase_) , UpperCAmelCase_) self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCAmelCase_) , UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Dict) ->int: '''simple docstring''' lowerCamelCase__: List[Any] =list(self.get_tokenizer().get_vocab().keys()) self.assertEqual(vocab_keys[0] , "[PAD]") self.assertEqual(vocab_keys[1] , "[CLS]") self.assertEqual(vocab_keys[-1] , "j") self.assertEqual(len(UpperCAmelCase_) , 1_012) def SCREAMING_SNAKE_CASE_ (self : Dict) ->Union[str, Any]: '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 1_012) def SCREAMING_SNAKE_CASE_ (self : Any) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Optional[Any] =XLMProphetNetTokenizer(UpperCAmelCase_ , keep_accents=UpperCAmelCase_) lowerCamelCase__: 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]] , ) lowerCamelCase__: Optional[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", "é", ".", ] , ) lowerCamelCase__: Any =tokenizer.convert_tokens_to_ids(UpperCAmelCase_) self.assertListEqual( UpperCAmelCase_ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, -9, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, -9, 4] ] , ) lowerCamelCase__: 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]", ".", ] , ) @cached_property def SCREAMING_SNAKE_CASE_ (self : Any) ->int: '''simple docstring''' return XLMProphetNetTokenizer.from_pretrained("microsoft/xprophetnet-large-wiki100-cased") @slow def SCREAMING_SNAKE_CASE_ (self : List[str]) ->List[str]: '''simple docstring''' lowerCamelCase__: Optional[int] ="Hello World!" lowerCamelCase__: Dict =[35_389, 6_672, 49, 2] self.assertListEqual(UpperCAmelCase_ , self.big_tokenizer.encode(UpperCAmelCase_)) @slow def SCREAMING_SNAKE_CASE_ (self : int) ->Union[str, Any]: '''simple docstring''' lowerCamelCase__: Any ={"input_ids": [[11_073, 82_783, 18, 26, 82_783, 549, 51_540, 248, 17_209, 1_301, 217, 20, 215_186, 1_325, 147, 17_209, 1_301, 217, 20, 56_370, 53, 122_020, 20, 16_477, 27, 87_355, 4_548, 20, 4_728, 78_392, 17, 159_969, 18, 26, 24_491, 629, 15, 538, 22_704, 5_439, 15, 2_788, 24_491, 9_885, 15, 43_534, 605, 15, 814, 18_403, 33_200, 29, 15, 43_534, 24_458, 12_410, 111, 24_966, 83_669, 9_637, 144_068, 26, 850, 22_346, 27, 147, 24_966, 83_669, 83_490, 26, 39_113, 735, 27, 689, 656, 2_800, 1_339, 4_600, 53, 122_020, 115_785, 34, 816, 1_339, 46_887, 18, 147, 53_905, 1_951, 42_238, 41_170, 17_732, 834, 436, 15, 27_523, 98_733, 217, 147, 5_542, 4_981, 930, 17_347, 16, 2], [20_091, 629, 94, 82_786, 58, 490, 20, 1_528, 84, 53_905, 344, 80_592, 110_128, 18_822, 5_267, 1_306, 62, 152_537, 308, 7_997, 401, 124_427, 549, 35_442, 225, 109, 15_055, 25_748, 147, 7_119, 43_712, 34, 767, 135_366, 18, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [592, 63_784, 119_466, 17, 147_808, 88_214, 18, 656, 81, 32, 3_296, 10_280, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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="microsoft/xprophetnet-large-wiki100-cased" , revision="1acad1643ddd54a44df6a1b797ada8373685d90e" , )
59
1
import sys import turtle def lowerCAmelCase_ ( __a , __a ) -> tuple[float, float]: """simple docstring""" return (pa[0] + pa[0]) / 2, (pa[1] + pa[1]) / 2 def lowerCAmelCase_ ( __a , __a , __a , __a , ) -> None: """simple docstring""" my_pen.up() my_pen.goto(vertexa[0] , vertexa[1] ) my_pen.down() my_pen.goto(vertexa[0] , vertexa[1] ) my_pen.goto(vertexa[0] , vertexa[1] ) my_pen.goto(vertexa[0] , vertexa[1] ) if depth == 0: return triangle(__a , get_mid(__a , __a ) , get_mid(__a , __a ) , depth - 1 ) triangle(__a , get_mid(__a , __a ) , get_mid(__a , __a ) , depth - 1 ) triangle(__a , get_mid(__a , __a ) , get_mid(__a , __a ) , depth - 1 ) if __name__ == "__main__": if len(sys.argv) != 2: raise ValueError( "Correct format for using this script: " "python fractals.py <int:depth_for_fractal>" ) __A = turtle.Turtle() my_pen.ht() my_pen.speed(5) my_pen.pencolor("red") __A = [(-175, -125), (0, 175), (175, -125)] # vertices of triangle triangle(vertices[0], vertices[1], vertices[2], int(sys.argv[1]))
59
import os import shutil import tempfile import unittest import numpy as np from transformers import AutoTokenizer, BarkProcessor from transformers.testing_utils import require_torch, slow @require_torch class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ (self : List[str]) ->str: '''simple docstring''' lowerCamelCase__: Union[str, Any] ="ylacombe/bark-small" lowerCamelCase__: Tuple =tempfile.mkdtemp() lowerCamelCase__: Tuple ="en_speaker_1" lowerCamelCase__: Optional[int] ="This is a test string" lowerCamelCase__: List[str] ="speaker_embeddings_path.json" lowerCamelCase__: int ="speaker_embeddings" def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , **UpperCAmelCase_ : Any) ->Tuple: '''simple docstring''' return AutoTokenizer.from_pretrained(self.checkpoint , **UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[str]) ->Union[str, Any]: '''simple docstring''' shutil.rmtree(self.tmpdirname) def SCREAMING_SNAKE_CASE_ (self : int) ->Any: '''simple docstring''' lowerCamelCase__: List[Any] =self.get_tokenizer() lowerCamelCase__: List[str] =BarkProcessor(tokenizer=UpperCAmelCase_) processor.save_pretrained(self.tmpdirname) lowerCamelCase__: Dict =BarkProcessor.from_pretrained(self.tmpdirname) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab()) @slow def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Tuple: '''simple docstring''' lowerCamelCase__: Tuple =BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) processor.save_pretrained( self.tmpdirname , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , speaker_embeddings_directory=self.speaker_embeddings_directory , ) lowerCamelCase__: Dict =self.get_tokenizer(bos_token="(BOS)" , eos_token="(EOS)") lowerCamelCase__: Any =BarkProcessor.from_pretrained( self.tmpdirname , self.speaker_embeddings_dict_path , bos_token="(BOS)" , eos_token="(EOS)" , ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab()) def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->int: '''simple docstring''' lowerCamelCase__: Any =BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) lowerCamelCase__: List[str] =35 lowerCamelCase__: Optional[Any] =2 lowerCamelCase__: Optional[Any] =8 lowerCamelCase__: Optional[int] ={ "semantic_prompt": np.ones(UpperCAmelCase_), "coarse_prompt": np.ones((nb_codebooks_coarse, seq_len)), "fine_prompt": np.ones((nb_codebooks_total, seq_len)), } # test providing already loaded voice_preset lowerCamelCase__: Any =processor(text=self.input_string , voice_preset=UpperCAmelCase_) lowerCamelCase__: int =inputs["history_prompt"] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(UpperCAmelCase_ , np.array([])).tolist()) # test loading voice preset from npz file lowerCamelCase__: Union[str, Any] =os.path.join(self.tmpdirname , "file.npz") np.savez(UpperCAmelCase_ , **UpperCAmelCase_) lowerCamelCase__: Tuple =processor(text=self.input_string , voice_preset=UpperCAmelCase_) lowerCamelCase__: Optional[Any] =inputs["history_prompt"] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(UpperCAmelCase_ , np.array([])).tolist()) # test loading voice preset from the hub lowerCamelCase__: Any =processor(text=self.input_string , voice_preset=self.voice_preset) def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Union[str, Any]: '''simple docstring''' lowerCamelCase__: str =self.get_tokenizer() lowerCamelCase__: Dict =BarkProcessor(tokenizer=UpperCAmelCase_) lowerCamelCase__: List[Any] =processor(text=self.input_string) lowerCamelCase__: Optional[int] =tokenizer( self.input_string , padding="max_length" , max_length=256 , add_special_tokens=UpperCAmelCase_ , return_attention_mask=UpperCAmelCase_ , return_token_type_ids=UpperCAmelCase_ , ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key].squeeze().tolist())
59
1
__A = [ "Audio", "Array2D", "Array3D", "Array4D", "Array5D", "ClassLabel", "Features", "Sequence", "Value", "Image", "Translation", "TranslationVariableLanguages", ] from .audio import Audio from .features import ArrayaD, ArrayaD, ArrayaD, ArrayaD, ClassLabel, Features, Sequence, Value from .image import Image from .translation import Translation, TranslationVariableLanguages
59
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = ["image_processor", "tokenizer"] lowercase_ = "CLIPImageProcessor" lowercase_ = ("XLMRobertaTokenizer", "XLMRobertaTokenizerFast") def __init__(self : List[Any] , UpperCAmelCase_ : int=None , UpperCAmelCase_ : List[Any]=None , **UpperCAmelCase_ : List[str]) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Union[str, Any] =None if "feature_extractor" in kwargs: warnings.warn( "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`" " instead." , UpperCAmelCase_ , ) lowerCamelCase__: int =kwargs.pop("feature_extractor") lowerCamelCase__: int =image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("You need to specify an `image_processor`.") if tokenizer is None: raise ValueError("You need to specify a `tokenizer`.") super().__init__(UpperCAmelCase_ , UpperCAmelCase_) def __call__(self : List[Any] , UpperCAmelCase_ : str=None , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : int=None , **UpperCAmelCase_ : Any) ->Union[str, Any]: '''simple docstring''' if text is None and images is None: raise ValueError("You have to specify either text or images. Both cannot be none.") if text is not None: lowerCamelCase__: List[Any] =self.tokenizer(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_) if images is not None: lowerCamelCase__: int =self.image_processor(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_) if text is not None and images is not None: lowerCamelCase__: str =image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**UpperCAmelCase_) , tensor_type=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[str] , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : Optional[Any]) ->Dict: '''simple docstring''' return self.tokenizer.batch_decode(*UpperCAmelCase_ , **UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Optional[int] , *UpperCAmelCase_ : int , **UpperCAmelCase_ : Any) ->Optional[Any]: '''simple docstring''' return self.tokenizer.decode(*UpperCAmelCase_ , **UpperCAmelCase_) @property def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Optional[Any] =self.tokenizer.model_input_names lowerCamelCase__: str =self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
59
1
import itertools import string from collections.abc import Generator, Iterable def lowerCAmelCase_ ( __a , __a ) -> Generator[tuple[str, ...], None, None]: """simple docstring""" lowerCamelCase__: Optional[int] =iter(__a ) while True: lowerCamelCase__: Any =tuple(itertools.islice(__a , __a ) ) if not chunk: return yield chunk def lowerCAmelCase_ ( __a ) -> str: """simple docstring""" lowerCamelCase__: str ="".join([c.upper() for c in dirty if c in string.ascii_letters] ) lowerCamelCase__: Optional[Any] ="" if len(__a ) < 2: return dirty for i in range(len(__a ) - 1 ): clean += dirty[i] if dirty[i] == dirty[i + 1]: clean += "X" clean += dirty[-1] if len(__a ) & 1: clean += "X" return clean def lowerCAmelCase_ ( __a ) -> list[str]: """simple docstring""" lowerCamelCase__: List[str] ="ABCDEFGHIKLMNOPQRSTUVWXYZ" # we're using a list instead of a '2d' array because it makes the math # for setting up the table and doing the actual encoding/decoding simpler lowerCamelCase__: Tuple =[] # copy key chars into the table if they are in `alphabet` ignoring duplicates for char in key.upper(): if char not in table and char in alphabet: table.append(__a ) # fill the rest of the table in with the remaining alphabet chars for char in alphabet: if char not in table: table.append(__a ) return table def lowerCAmelCase_ ( __a , __a ) -> str: """simple docstring""" lowerCamelCase__: int =generate_table(__a ) lowerCamelCase__: Union[str, Any] =prepare_input(__a ) lowerCamelCase__: List[str] ="" # https://en.wikipedia.org/wiki/Playfair_cipher#Description for chara, chara in chunker(__a , 2 ): lowerCamelCase__ , lowerCamelCase__: Any =divmod(table.index(__a ) , 5 ) lowerCamelCase__ , lowerCamelCase__: Dict =divmod(table.index(__a ) , 5 ) if rowa == rowa: ciphertext += table[rowa * 5 + (cola + 1) % 5] ciphertext += table[rowa * 5 + (cola + 1) % 5] elif cola == cola: ciphertext += table[((rowa + 1) % 5) * 5 + cola] ciphertext += table[((rowa + 1) % 5) * 5 + cola] else: # rectangle ciphertext += table[rowa * 5 + cola] ciphertext += table[rowa * 5 + cola] return ciphertext def lowerCAmelCase_ ( __a , __a ) -> str: """simple docstring""" lowerCamelCase__: Any =generate_table(__a ) lowerCamelCase__: Optional[Any] ="" # https://en.wikipedia.org/wiki/Playfair_cipher#Description for chara, chara in chunker(__a , 2 ): lowerCamelCase__ , lowerCamelCase__: Any =divmod(table.index(__a ) , 5 ) lowerCamelCase__ , lowerCamelCase__: str =divmod(table.index(__a ) , 5 ) if rowa == rowa: plaintext += table[rowa * 5 + (cola - 1) % 5] plaintext += table[rowa * 5 + (cola - 1) % 5] elif cola == cola: plaintext += table[((rowa - 1) % 5) * 5 + cola] plaintext += table[((rowa - 1) % 5) * 5 + cola] else: # rectangle plaintext += table[rowa * 5 + cola] plaintext += table[rowa * 5 + cola] return plaintext
59
from datetime import datetime import matplotlib.pyplot as plt import torch def lowerCAmelCase_ ( __a ) -> Any: """simple docstring""" for param in module.parameters(): lowerCamelCase__: Tuple =False def lowerCAmelCase_ ( ) -> Optional[int]: """simple docstring""" lowerCamelCase__: List[str] ="cuda" if torch.cuda.is_available() else "cpu" if torch.backends.mps.is_available() and torch.backends.mps.is_built(): lowerCamelCase__: str ="mps" if device == "mps": print( "WARNING: MPS currently doesn't seem to work, and messes up backpropagation without any visible torch" " errors. I recommend using CUDA on a colab notebook or CPU instead if you're facing inexplicable issues" " with generations." ) return device def lowerCAmelCase_ ( __a ) -> List[str]: """simple docstring""" lowerCamelCase__: Union[str, Any] =plt.imshow(__a ) fig.axes.get_xaxis().set_visible(__a ) fig.axes.get_yaxis().set_visible(__a ) plt.show() def lowerCAmelCase_ ( ) -> Optional[Any]: """simple docstring""" lowerCamelCase__: List[str] =datetime.now() lowerCamelCase__: str =current_time.strftime("%H:%M:%S" ) return timestamp
59
1
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = ["image_processor", "tokenizer"] lowercase_ = "CLIPImageProcessor" lowercase_ = ("XLMRobertaTokenizer", "XLMRobertaTokenizerFast") def __init__(self : List[Any] , UpperCAmelCase_ : int=None , UpperCAmelCase_ : List[Any]=None , **UpperCAmelCase_ : List[str]) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Union[str, Any] =None if "feature_extractor" in kwargs: warnings.warn( "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`" " instead." , UpperCAmelCase_ , ) lowerCamelCase__: int =kwargs.pop("feature_extractor") lowerCamelCase__: int =image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("You need to specify an `image_processor`.") if tokenizer is None: raise ValueError("You need to specify a `tokenizer`.") super().__init__(UpperCAmelCase_ , UpperCAmelCase_) def __call__(self : List[Any] , UpperCAmelCase_ : str=None , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : int=None , **UpperCAmelCase_ : Any) ->Union[str, Any]: '''simple docstring''' if text is None and images is None: raise ValueError("You have to specify either text or images. Both cannot be none.") if text is not None: lowerCamelCase__: List[Any] =self.tokenizer(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_) if images is not None: lowerCamelCase__: int =self.image_processor(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_) if text is not None and images is not None: lowerCamelCase__: str =image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**UpperCAmelCase_) , tensor_type=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[str] , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : Optional[Any]) ->Dict: '''simple docstring''' return self.tokenizer.batch_decode(*UpperCAmelCase_ , **UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Optional[int] , *UpperCAmelCase_ : int , **UpperCAmelCase_ : Any) ->Optional[Any]: '''simple docstring''' return self.tokenizer.decode(*UpperCAmelCase_ , **UpperCAmelCase_) @property def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Optional[Any] =self.tokenizer.model_input_names lowerCamelCase__: str =self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
59
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __A = { "configuration_pix2struct": [ "PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP", "Pix2StructConfig", "Pix2StructTextConfig", "Pix2StructVisionConfig", ], "processing_pix2struct": ["Pix2StructProcessor"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ["Pix2StructImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ "PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST", "Pix2StructPreTrainedModel", "Pix2StructForConditionalGeneration", "Pix2StructVisionModel", "Pix2StructTextModel", ] if TYPE_CHECKING: from .configuration_pixastruct import ( PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP, PixaStructConfig, PixaStructTextConfig, PixaStructVisionConfig, ) from .processing_pixastruct import PixaStructProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_pixastruct import PixaStructImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_pixastruct import ( PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST, PixaStructForConditionalGeneration, PixaStructPreTrainedModel, PixaStructTextModel, PixaStructVisionModel, ) else: import sys __A = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
59
1
from typing import Optional import numpy as np import torch from torch import nn from transformers import GPTaConfig, GPTaLMHeadModel from transformers.modeling_utils import ModuleUtilsMixin from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = [R"h\.\d+\.attn\.bias", R"h\.\d+\.attn\.masked_bias"] @register_to_config def __init__(self : List[Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[int] = None , UpperCAmelCase_ : int = 50_257 , UpperCAmelCase_ : int = 1_024 , UpperCAmelCase_ : int = 768 , UpperCAmelCase_ : int = 12 , UpperCAmelCase_ : int = 12 , UpperCAmelCase_ : Optional[int] = None , UpperCAmelCase_ : str = "gelu_new" , UpperCAmelCase_ : float = 0.1 , UpperCAmelCase_ : float = 0.1 , UpperCAmelCase_ : float = 0.1 , UpperCAmelCase_ : float = 1E-5 , UpperCAmelCase_ : float = 0.02 , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : bool = False , UpperCAmelCase_ : bool = False , ) ->Any: '''simple docstring''' super().__init__() lowerCamelCase__: str =prefix_length if prefix_inner_dim != n_embd and prefix_hidden_dim is None: raise ValueError( F"""`prefix_hidden_dim` cannot be `None` when `prefix_inner_dim`: {prefix_hidden_dim} and""" F""" `n_embd`: {n_embd} are not equal.""") lowerCamelCase__: List[Any] =prefix_inner_dim lowerCamelCase__: str =prefix_hidden_dim lowerCamelCase__: Optional[Any] =( nn.Linear(self.prefix_inner_dim , self.prefix_hidden_dim) if self.prefix_hidden_dim is not None else nn.Identity() ) lowerCamelCase__: int =( nn.Linear(self.prefix_hidden_dim , UpperCAmelCase_) if self.prefix_hidden_dim is not None else nn.Identity() ) lowerCamelCase__: List[str] =GPTaConfig( vocab_size=UpperCAmelCase_ , n_positions=UpperCAmelCase_ , n_embd=UpperCAmelCase_ , n_layer=UpperCAmelCase_ , n_head=UpperCAmelCase_ , n_inner=UpperCAmelCase_ , activation_function=UpperCAmelCase_ , resid_pdrop=UpperCAmelCase_ , embd_pdrop=UpperCAmelCase_ , attn_pdrop=UpperCAmelCase_ , layer_norm_epsilon=UpperCAmelCase_ , initializer_range=UpperCAmelCase_ , scale_attn_weights=UpperCAmelCase_ , use_cache=UpperCAmelCase_ , scale_attn_by_inverse_layer_idx=UpperCAmelCase_ , reorder_and_upcast_attn=UpperCAmelCase_ , ) lowerCamelCase__: int =GPTaLMHeadModel(UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[Any] , UpperCAmelCase_ : torch.Tensor , UpperCAmelCase_ : torch.Tensor , UpperCAmelCase_ : Optional[torch.Tensor] = None , UpperCAmelCase_ : Optional[torch.Tensor] = None , ) ->int: '''simple docstring''' lowerCamelCase__: Optional[int] =self.transformer.transformer.wte(UpperCAmelCase_) lowerCamelCase__: str =self.encode_prefix(UpperCAmelCase_) lowerCamelCase__: Union[str, Any] =self.decode_prefix(UpperCAmelCase_) lowerCamelCase__: Tuple =torch.cat((prefix_embeds, embedding_text) , dim=1) if labels is not None: lowerCamelCase__: List[str] =self.get_dummy_token(input_ids.shape[0] , input_ids.device) lowerCamelCase__: Any =torch.cat((dummy_token, input_ids) , dim=1) lowerCamelCase__: Any =self.transformer(inputs_embeds=UpperCAmelCase_ , labels=UpperCAmelCase_ , attention_mask=UpperCAmelCase_) if self.prefix_hidden_dim is not None: return out, hidden else: return out def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : int , UpperCAmelCase_ : torch.device) ->torch.Tensor: '''simple docstring''' return torch.zeros(UpperCAmelCase_ , self.prefix_length , dtype=torch.intaa , device=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : List[str]) ->Union[str, Any]: '''simple docstring''' return self.encode_prefix(UpperCAmelCase_) @torch.no_grad() def SCREAMING_SNAKE_CASE_ (self : List[Any] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : str) ->Optional[Any]: '''simple docstring''' lowerCamelCase__: Union[str, Any] =torch.split(UpperCAmelCase_ , 1 , dim=0) lowerCamelCase__: List[str] =[] lowerCamelCase__: Any =[] for feature in features: lowerCamelCase__: Tuple =self.decode_prefix(feature.to(UpperCAmelCase_)) # back to the clip feature # Only support beam search for now lowerCamelCase__ , lowerCamelCase__: List[Any] =self.generate_beam( input_embeds=UpperCAmelCase_ , device=UpperCAmelCase_ , eos_token_id=UpperCAmelCase_) generated_tokens.append(output_tokens[0]) generated_seq_lengths.append(seq_lengths[0]) lowerCamelCase__: Union[str, Any] =torch.stack(UpperCAmelCase_) lowerCamelCase__: int =torch.stack(UpperCAmelCase_) return generated_tokens, generated_seq_lengths @torch.no_grad() def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : str=None , UpperCAmelCase_ : Union[str, Any]=None , UpperCAmelCase_ : str=None , UpperCAmelCase_ : int = 5 , UpperCAmelCase_ : int = 67 , UpperCAmelCase_ : float = 1.0 , UpperCAmelCase_ : Optional[int] = None , ) ->Tuple: '''simple docstring''' lowerCamelCase__: Optional[int] =eos_token_id lowerCamelCase__: Optional[int] =None lowerCamelCase__: Any =None lowerCamelCase__: Any =torch.ones(UpperCAmelCase_ , device=UpperCAmelCase_ , dtype=torch.int) lowerCamelCase__: List[Any] =torch.zeros(UpperCAmelCase_ , device=UpperCAmelCase_ , dtype=torch.bool) if input_embeds is not None: lowerCamelCase__: List[str] =input_embeds else: lowerCamelCase__: Any =self.transformer.transformer.wte(UpperCAmelCase_) for i in range(UpperCAmelCase_): lowerCamelCase__: int =self.transformer(inputs_embeds=UpperCAmelCase_) lowerCamelCase__: List[str] =outputs.logits lowerCamelCase__: Optional[Any] =logits[:, -1, :] / (temperature if temperature > 0 else 1.0) lowerCamelCase__: Union[str, Any] =logits.softmax(-1).log() if scores is None: lowerCamelCase__ , lowerCamelCase__: Any =logits.topk(UpperCAmelCase_ , -1) lowerCamelCase__: int =generated.expand(UpperCAmelCase_ , *generated.shape[1:]) lowerCamelCase__ , lowerCamelCase__: List[str] =next_tokens.permute(1 , 0), scores.squeeze(0) if tokens is None: lowerCamelCase__: Optional[int] =next_tokens else: lowerCamelCase__: str =tokens.expand(UpperCAmelCase_ , *tokens.shape[1:]) lowerCamelCase__: int =torch.cat((tokens, next_tokens) , dim=1) else: lowerCamelCase__: int =-float(np.inf) lowerCamelCase__: List[Any] =0 lowerCamelCase__: Tuple =scores[:, None] + logits seq_lengths[~is_stopped] += 1 lowerCamelCase__: Any =scores_sum / seq_lengths[:, None] lowerCamelCase__ , lowerCamelCase__: List[Any] =scores_sum_average.view(-1).topk(UpperCAmelCase_ , -1) lowerCamelCase__: List[str] =next_tokens // scores_sum.shape[1] lowerCamelCase__: Optional[Any] =seq_lengths[next_tokens_source] lowerCamelCase__: Optional[Any] =next_tokens % scores_sum.shape[1] lowerCamelCase__: List[str] =next_tokens.unsqueeze(1) lowerCamelCase__: Dict =tokens[next_tokens_source] lowerCamelCase__: Tuple =torch.cat((tokens, next_tokens) , dim=1) lowerCamelCase__: str =generated[next_tokens_source] lowerCamelCase__: List[Any] =scores_sum_average * seq_lengths lowerCamelCase__: str =is_stopped[next_tokens_source] lowerCamelCase__: Optional[int] =self.transformer.transformer.wte(next_tokens.squeeze()).view(generated.shape[0] , 1 , -1) lowerCamelCase__: List[str] =torch.cat((generated, next_token_embed) , dim=1) lowerCamelCase__: Union[str, Any] =is_stopped + next_tokens.eq(UpperCAmelCase_).squeeze() if is_stopped.all(): break lowerCamelCase__: str =scores / seq_lengths lowerCamelCase__: Any =scores.argsort(descending=UpperCAmelCase_) # tokens tensors are already padded to max_seq_length lowerCamelCase__: str =[tokens[i] for i in order] lowerCamelCase__: Optional[int] =torch.stack(UpperCAmelCase_ , dim=0) lowerCamelCase__: Dict =torch.tensor([seq_lengths[i] for i in order] , dtype=seq_lengths.dtype) return output_texts, seq_lengths
59
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_distilbert import DistilBertTokenizer __A = logging.get_logger(__name__) __A = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} __A = { "vocab_file": { "distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/vocab.txt", "distilbert-base-uncased-distilled-squad": ( "https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/vocab.txt" ), "distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/vocab.txt", "distilbert-base-cased-distilled-squad": ( "https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/vocab.txt" ), "distilbert-base-german-cased": "https://huggingface.co/distilbert-base-german-cased/resolve/main/vocab.txt", "distilbert-base-multilingual-cased": ( "https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/vocab.txt" ), }, "tokenizer_file": { "distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/tokenizer.json", "distilbert-base-uncased-distilled-squad": ( "https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/tokenizer.json" ), "distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/tokenizer.json", "distilbert-base-cased-distilled-squad": ( "https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/tokenizer.json" ), "distilbert-base-german-cased": ( "https://huggingface.co/distilbert-base-german-cased/resolve/main/tokenizer.json" ), "distilbert-base-multilingual-cased": ( "https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/tokenizer.json" ), }, } __A = { "distilbert-base-uncased": 512, "distilbert-base-uncased-distilled-squad": 512, "distilbert-base-cased": 512, "distilbert-base-cased-distilled-squad": 512, "distilbert-base-german-cased": 512, "distilbert-base-multilingual-cased": 512, } __A = { "distilbert-base-uncased": {"do_lower_case": True}, "distilbert-base-uncased-distilled-squad": {"do_lower_case": True}, "distilbert-base-cased": {"do_lower_case": False}, "distilbert-base-cased-distilled-squad": {"do_lower_case": False}, "distilbert-base-german-cased": {"do_lower_case": False}, "distilbert-base-multilingual-cased": {"do_lower_case": False}, } class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = VOCAB_FILES_NAMES lowercase_ = PRETRAINED_VOCAB_FILES_MAP lowercase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase_ = PRETRAINED_INIT_CONFIGURATION lowercase_ = ["input_ids", "attention_mask"] lowercase_ = DistilBertTokenizer def __init__(self : Tuple , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : int=None , UpperCAmelCase_ : Any=True , UpperCAmelCase_ : List[Any]="[UNK]" , UpperCAmelCase_ : Dict="[SEP]" , UpperCAmelCase_ : Dict="[PAD]" , UpperCAmelCase_ : Optional[int]="[CLS]" , UpperCAmelCase_ : str="[MASK]" , UpperCAmelCase_ : Any=True , UpperCAmelCase_ : List[str]=None , **UpperCAmelCase_ : List[str] , ) ->str: '''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_ , ) lowerCamelCase__: Union[str, Any] =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 ): lowerCamelCase__: List[str] =getattr(UpperCAmelCase_ , normalizer_state.pop("type")) lowerCamelCase__: Optional[int] =do_lower_case lowerCamelCase__: int =strip_accents lowerCamelCase__: Any =tokenize_chinese_chars lowerCamelCase__: Any =normalizer_class(**UpperCAmelCase_) lowerCamelCase__: str =do_lower_case def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : int , UpperCAmelCase_ : Union[str, Any]=None) ->Dict: '''simple docstring''' lowerCamelCase__: str =[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 SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None) ->List[int]: '''simple docstring''' lowerCamelCase__: str =[self.sep_token_id] lowerCamelCase__: str =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep) * [0] return len(cls + token_ids_a + sep) * [0] + len(token_ids_a + sep) * [1] def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] = None) ->Tuple[str]: '''simple docstring''' lowerCamelCase__: str =self._tokenizer.model.save(UpperCAmelCase_ , name=UpperCAmelCase_) return tuple(UpperCAmelCase_)
59
1
from __future__ import annotations from decimal import Decimal from math import * # noqa: F403 from sympy import diff def lowerCAmelCase_ ( __a , __a , __a = 10**-10 ) -> float: """simple docstring""" lowerCamelCase__: List[str] =a while True: lowerCamelCase__: Optional[Any] =Decimal(__a ) - ( Decimal(eval(__a ) ) / Decimal(eval(str(diff(__a ) ) ) ) # noqa: S307 ) # This number dictates the accuracy of the answer if abs(eval(__a ) ) < precision: # noqa: S307 return float(__a ) # Let's Execute if __name__ == "__main__": # Find root of trigonometric function # Find value of pi print(f'The root of sin(x) = 0 is {newton_raphson("sin(x)", 2)}') # Find root of polynomial print(f'The root of x**2 - 5*x + 2 = 0 is {newton_raphson("x**2 - 5*x + 2", 0.4)}') # Find Square Root of 5 print(f'The root of log(x) - 1 = 0 is {newton_raphson("log(x) - 1", 2)}') # Exponential Roots print(f'The root of exp(x) - 1 = 0 is {newton_raphson("exp(x) - 1", 0)}')
59
import operator as op def lowerCAmelCase_ ( __a ) -> Tuple: """simple docstring""" lowerCamelCase__: Optional[Any] =[] lowerCamelCase__: Tuple =lambda __a , __a : int(x / y ) # noqa: E731 integer division operation lowerCamelCase__: Tuple ={ "^": op.pow, "*": op.mul, "/": div, "+": op.add, "-": op.sub, } # operators & their respective operation # print table header print("Symbol".center(8 ) , "Action".center(12 ) , "Stack" , sep=" | " ) print("-" * (30 + len(__a )) ) for x in post_fix: if x.isdigit(): # if x in digit stack.append(__a ) # append x to stack # output in tabular format print(x.rjust(8 ) , ("push(" + x + ")").ljust(12 ) , ",".join(__a ) , sep=" | " ) else: lowerCamelCase__: List[Any] =stack.pop() # pop stack # output in tabular format print("".rjust(8 ) , ("pop(" + b + ")").ljust(12 ) , ",".join(__a ) , sep=" | " ) lowerCamelCase__: Optional[Any] =stack.pop() # pop stack # output in tabular format print("".rjust(8 ) , ("pop(" + a + ")").ljust(12 ) , ",".join(__a ) , sep=" | " ) stack.append( str(opr[x](int(__a ) , int(__a ) ) ) ) # evaluate the 2 values popped from stack & push result to stack # output in tabular format print( x.rjust(8 ) , ("push(" + a + x + b + ")").ljust(12 ) , ",".join(__a ) , sep=" | " , ) return int(stack[0] ) if __name__ == "__main__": __A = input("\n\nEnter a Postfix Equation (space separated) = ").split(" ") print("\n\tResult = ", solve(Postfix))
59
1
def lowerCAmelCase_ ( __a = 100 ) -> int: """simple docstring""" lowerCamelCase__: List[Any] =(n * (n + 1) // 2) ** 2 lowerCamelCase__: Dict =n * (n + 1) * (2 * n + 1) // 6 return sum_cubes - sum_squares if __name__ == "__main__": print(f'{solution() = }')
59
from collections import defaultdict from typing import Optional from ..image_utils import load_image from ..utils import ( add_end_docstrings, is_torch_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_MASK_GENERATION_MAPPING __A = logging.get_logger(__name__) @add_end_docstrings(__SCREAMING_SNAKE_CASE ) class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__(self : List[Any] , **UpperCAmelCase_ : Any) ->Any: '''simple docstring''' super().__init__(**UpperCAmelCase_) requires_backends(self , "vision") requires_backends(self , "torch") if self.framework != "pt": raise ValueError(F"""The {self.__class__} is only available in PyTorch.""") self.check_model_type(UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Tuple , **UpperCAmelCase_ : List[Any]) ->Tuple: '''simple docstring''' lowerCamelCase__: Optional[int] ={} lowerCamelCase__: Tuple ={} lowerCamelCase__: str ={} # preprocess args if "points_per_batch" in kwargs: lowerCamelCase__: Optional[Any] =kwargs["points_per_batch"] if "points_per_crop" in kwargs: lowerCamelCase__: int =kwargs["points_per_crop"] if "crops_n_layers" in kwargs: lowerCamelCase__: Any =kwargs["crops_n_layers"] if "crop_overlap_ratio" in kwargs: lowerCamelCase__: Tuple =kwargs["crop_overlap_ratio"] if "crop_n_points_downscale_factor" in kwargs: lowerCamelCase__: List[Any] =kwargs["crop_n_points_downscale_factor"] # postprocess args if "pred_iou_thresh" in kwargs: lowerCamelCase__: List[str] =kwargs["pred_iou_thresh"] if "stability_score_offset" in kwargs: lowerCamelCase__: int =kwargs["stability_score_offset"] if "mask_threshold" in kwargs: lowerCamelCase__: Optional[int] =kwargs["mask_threshold"] if "stability_score_thresh" in kwargs: lowerCamelCase__: str =kwargs["stability_score_thresh"] if "crops_nms_thresh" in kwargs: lowerCamelCase__: Any =kwargs["crops_nms_thresh"] if "output_rle_mask" in kwargs: lowerCamelCase__: List[Any] =kwargs["output_rle_mask"] if "output_bboxes_mask" in kwargs: lowerCamelCase__: List[str] =kwargs["output_bboxes_mask"] return preprocess_kwargs, forward_params, postprocess_kwargs def __call__(self : int , UpperCAmelCase_ : Dict , *UpperCAmelCase_ : Dict , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : Optional[Any]=None , **UpperCAmelCase_ : Dict) ->Optional[Any]: '''simple docstring''' return super().__call__(UpperCAmelCase_ , *UpperCAmelCase_ , num_workers=UpperCAmelCase_ , batch_size=UpperCAmelCase_ , **UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[Any]=64 , UpperCAmelCase_ : int = 0 , UpperCAmelCase_ : float = 512 / 1_500 , UpperCAmelCase_ : Optional[int] = 32 , UpperCAmelCase_ : Optional[int] = 1 , ) ->Dict: '''simple docstring''' lowerCamelCase__: Dict =load_image(UpperCAmelCase_) lowerCamelCase__: List[str] =self.image_processor.size["longest_edge"] lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Union[str, Any] =self.image_processor.generate_crop_boxes( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: str =self.image_processor(images=UpperCAmelCase_ , return_tensors="pt") with self.device_placement(): if self.framework == "pt": lowerCamelCase__: str =self.get_inference_context() with inference_context(): lowerCamelCase__: Union[str, Any] =self._ensure_tensor_on_device(UpperCAmelCase_ , device=self.device) lowerCamelCase__: Optional[Any] =self.model.get_image_embeddings(model_inputs.pop("pixel_values")) lowerCamelCase__: str =image_embeddings lowerCamelCase__: int =grid_points.shape[1] lowerCamelCase__: int =points_per_batch if points_per_batch is not None else n_points if points_per_batch <= 0: raise ValueError( "Cannot have points_per_batch<=0. Must be >=1 to returned batched outputs. " "To return all points at once, set points_per_batch to None") for i in range(0 , UpperCAmelCase_ , UpperCAmelCase_): lowerCamelCase__: int =grid_points[:, i : i + points_per_batch, :, :] lowerCamelCase__: Optional[Any] =input_labels[:, i : i + points_per_batch] lowerCamelCase__: Dict =i == n_points - points_per_batch yield { "input_points": batched_points, "input_labels": labels, "input_boxes": crop_boxes, "is_last": is_last, **model_inputs, } def SCREAMING_SNAKE_CASE_ (self : str , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Dict=0.88 , UpperCAmelCase_ : Optional[Any]=0.95 , UpperCAmelCase_ : Tuple=0 , UpperCAmelCase_ : Any=1 , ) ->Optional[Any]: '''simple docstring''' lowerCamelCase__: Any =model_inputs.pop("input_boxes") lowerCamelCase__: Dict =model_inputs.pop("is_last") lowerCamelCase__: int =model_inputs.pop("original_sizes").tolist() lowerCamelCase__: Union[str, Any] =model_inputs.pop("reshaped_input_sizes").tolist() lowerCamelCase__: Union[str, Any] =self.model(**UpperCAmelCase_) # post processing happens here in order to avoid CPU GPU copies of ALL the masks lowerCamelCase__: Optional[int] =model_outputs["pred_masks"] lowerCamelCase__: Union[str, Any] =self.image_processor.post_process_masks( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , binarize=UpperCAmelCase_) lowerCamelCase__: Optional[Any] =model_outputs["iou_scores"] lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Any =self.image_processor.filter_masks( masks[0] , iou_scores[0] , original_sizes[0] , input_boxes[0] , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , ) return { "masks": masks, "is_last": is_last, "boxes": boxes, "iou_scores": iou_scores, } def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : Any , UpperCAmelCase_ : Optional[int]=False , UpperCAmelCase_ : List[str]=False , UpperCAmelCase_ : Optional[int]=0.7 , ) ->Tuple: '''simple docstring''' lowerCamelCase__: Any =[] lowerCamelCase__: Optional[int] =[] lowerCamelCase__: List[str] =[] for model_output in model_outputs: all_scores.append(model_output.pop("iou_scores")) all_masks.extend(model_output.pop("masks")) all_boxes.append(model_output.pop("boxes")) lowerCamelCase__: str =torch.cat(UpperCAmelCase_) lowerCamelCase__: List[str] =torch.cat(UpperCAmelCase_) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Dict =self.image_processor.post_process_for_mask_generation( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: List[str] =defaultdict(UpperCAmelCase_) for output in model_outputs: for k, v in output.items(): extra[k].append(UpperCAmelCase_) lowerCamelCase__: Any ={} if output_rle_mask: lowerCamelCase__: Union[str, Any] =rle_mask if output_bboxes_mask: lowerCamelCase__: int =bounding_boxes return {"masks": output_masks, "scores": iou_scores, **optional, **extra}
59
1
import pyarrow.parquet as pq import pytest from datasets import Audio, Dataset, DatasetDict, Features, NamedSplit, Sequence, Value, config from datasets.features.image import Image from datasets.io.parquet import ParquetDatasetReader, ParquetDatasetWriter, get_writer_batch_size from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def lowerCAmelCase_ ( __a , __a ) -> List[Any]: """simple docstring""" assert isinstance(__a , __a ) 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 lowerCAmelCase_ ( __a , __a , __a ) -> Any: """simple docstring""" lowerCamelCase__: Any =tmp_path / "cache" lowerCamelCase__: Optional[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(): lowerCamelCase__: Tuple =ParquetDatasetReader(__a , cache_dir=__a , keep_in_memory=__a ).read() _check_parquet_dataset(__a , __a ) @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 lowerCAmelCase_ ( __a , __a , __a ) -> List[str]: """simple docstring""" lowerCamelCase__: int =tmp_path / "cache" lowerCamelCase__: Tuple ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: Union[str, Any] =features.copy() if features else default_expected_features lowerCamelCase__: Optional[int] =( Features({feature: Value(__a ) for feature, dtype in features.items()} ) if features is not None else None ) lowerCamelCase__: int =ParquetDatasetReader(__a , features=__a , cache_dir=__a ).read() _check_parquet_dataset(__a , __a ) @pytest.mark.parametrize("split" , [None, NamedSplit("train" ), "train", "test"] ) def lowerCAmelCase_ ( __a , __a , __a ) -> Any: """simple docstring""" lowerCamelCase__: Any =tmp_path / "cache" lowerCamelCase__: Optional[Any] ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: Optional[Any] =ParquetDatasetReader(__a , cache_dir=__a , split=__a ).read() _check_parquet_dataset(__a , __a ) assert dataset.split == split if split else "train" @pytest.mark.parametrize("path_type" , [str, list] ) def lowerCAmelCase_ ( __a , __a , __a ) -> int: """simple docstring""" if issubclass(__a , __a ): lowerCamelCase__: List[Any] =parquet_path elif issubclass(__a , __a ): lowerCamelCase__: str =[parquet_path] lowerCamelCase__: Tuple =tmp_path / "cache" lowerCamelCase__: Optional[Any] ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: int =ParquetDatasetReader(__a , cache_dir=__a ).read() _check_parquet_dataset(__a , __a ) def lowerCAmelCase_ ( __a , __a , __a=("train",) ) -> Dict: """simple docstring""" assert isinstance(__a , __a ) for split in splits: lowerCamelCase__: Tuple =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 lowerCAmelCase_ ( __a , __a , __a ) -> Any: """simple docstring""" lowerCamelCase__: List[Any] =tmp_path / "cache" lowerCamelCase__: Optional[Any] ={"col_1": "string", "col_2": "int64", "col_3": "float64"} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): lowerCamelCase__: Tuple =ParquetDatasetReader( {"train": parquet_path} , cache_dir=__a , keep_in_memory=__a ).read() _check_parquet_datasetdict(__a , __a ) @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 lowerCAmelCase_ ( __a , __a , __a ) -> Optional[Any]: """simple docstring""" lowerCamelCase__: Tuple =tmp_path / "cache" lowerCamelCase__: Optional[int] ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: List[Any] =features.copy() if features else default_expected_features lowerCamelCase__: int =( Features({feature: Value(__a ) for feature, dtype in features.items()} ) if features is not None else None ) lowerCamelCase__: Optional[Any] =ParquetDatasetReader({"train": parquet_path} , features=__a , cache_dir=__a ).read() _check_parquet_datasetdict(__a , __a ) @pytest.mark.parametrize("split" , [None, NamedSplit("train" ), "train", "test"] ) def lowerCAmelCase_ ( __a , __a , __a ) -> Union[str, Any]: """simple docstring""" if split: lowerCamelCase__: Any ={split: parquet_path} else: lowerCamelCase__: int ="train" lowerCamelCase__: Any ={"train": parquet_path, "test": parquet_path} lowerCamelCase__: str =tmp_path / "cache" lowerCamelCase__: Any ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: int =ParquetDatasetReader(__a , cache_dir=__a ).read() _check_parquet_datasetdict(__a , __a , splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() ) def lowerCAmelCase_ ( __a , __a ) -> int: """simple docstring""" lowerCamelCase__: List[str] =ParquetDatasetWriter(__a , tmp_path / "foo.parquet" ) assert writer.write() > 0 lowerCamelCase__: List[str] =pq.ParquetFile(tmp_path / "foo.parquet" ) lowerCamelCase__: List[str] =pf.read() assert dataset.data.table == output_table def lowerCAmelCase_ ( __a , __a ) -> List[str]: """simple docstring""" lowerCamelCase__: List[str] =str(shared_datadir / "test_image_rgb.jpg" ) lowerCamelCase__: Union[str, Any] ={"image": [image_path]} lowerCamelCase__: Optional[Any] =Features({"image": Image()} ) lowerCamelCase__: Optional[int] =Dataset.from_dict(__a , features=__a ) lowerCamelCase__: Optional[int] =ParquetDatasetWriter(__a , tmp_path / "foo.parquet" ) assert writer.write() > 0 lowerCamelCase__: Dict =Dataset.from_parquet(str(tmp_path / "foo.parquet" ) ) assert dataset.features == reloaded_dataset.features lowerCamelCase__: Optional[Any] =ParquetDatasetReader(str(tmp_path / "foo.parquet" ) , streaming=__a ).read() assert dataset.features == reloaded_iterable_dataset.features @pytest.mark.parametrize( "feature, expected" , [ (Features({"foo": Value("int32" )} ), None), (Features({"image": Image(), "foo": Value("int32" )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS), (Features({"nested": Sequence(Audio() )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS), ] , ) def lowerCAmelCase_ ( __a , __a ) -> Optional[Any]: """simple docstring""" assert get_writer_batch_size(__a ) == expected
59
from transformers import BertTokenizerFast from .custom_tokenization import CustomTokenizer class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = CustomTokenizer pass
59
1
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 __A = "▁" __A = {"vocab_file": "spiece.model"} __A = { "vocab_file": {"google/pegasus-xsum": "https://huggingface.co/google/pegasus-xsum/resolve/main/spiece.model"} } __A = { "google/pegasus-xsum": 512, } __A = logging.get_logger(__name__) class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = VOCAB_FILES_NAMES lowercase_ = VOCAB_FILES_NAMES lowercase_ = PRETRAINED_VOCAB_FILES_MAP lowercase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase_ = ["input_ids", "attention_mask"] def __init__(self : Optional[int] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : int="<pad>" , UpperCAmelCase_ : Optional[Any]="</s>" , UpperCAmelCase_ : Optional[int]="<unk>" , UpperCAmelCase_ : List[str]="<mask_2>" , UpperCAmelCase_ : Optional[Any]="<mask_1>" , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : Any=103 , UpperCAmelCase_ : Optional[Dict[str, Any]] = None , **UpperCAmelCase_ : List[Any] , ) ->None: '''simple docstring''' lowerCamelCase__: int =offset if additional_special_tokens is not None: if not isinstance(UpperCAmelCase_ , UpperCAmelCase_): raise TypeError( F"""additional_special_tokens should be of type {type(UpperCAmelCase_)}, but is""" F""" {type(UpperCAmelCase_)}""") lowerCamelCase__: Tuple =( ([mask_token_sent] + additional_special_tokens) if mask_token_sent not in additional_special_tokens and mask_token_sent is not None else additional_special_tokens ) # fill additional tokens with ..., <unk_token_102> in case not all additional tokens are already taken additional_special_tokens_extended += [ F"""<unk_{i}>""" for i in range(len(UpperCAmelCase_) , self.offset - 1) ] if len(set(UpperCAmelCase_)) != len(UpperCAmelCase_): raise ValueError( "Please make sure that the provided additional_special_tokens do not contain an incorrectly" F""" shifted list of <unk_x> tokens. Found {additional_special_tokens_extended}.""") lowerCamelCase__: str =additional_special_tokens_extended else: lowerCamelCase__: str =[mask_token_sent] if mask_token_sent is not None else [] additional_special_tokens += [F"""<unk_{i}>""" for i in range(2 , self.offset)] lowerCamelCase__: List[str] ={} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=UpperCAmelCase_ , unk_token=UpperCAmelCase_ , mask_token=UpperCAmelCase_ , pad_token=UpperCAmelCase_ , mask_token_sent=UpperCAmelCase_ , offset=UpperCAmelCase_ , additional_special_tokens=UpperCAmelCase_ , sp_model_kwargs=self.sp_model_kwargs , **UpperCAmelCase_ , ) lowerCamelCase__: Tuple =mask_token_sent lowerCamelCase__: Union[str, Any] =vocab_file lowerCamelCase__: Dict =spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(UpperCAmelCase_) # add special tokens to encoder dict lowerCamelCase__: Dict[int, str] ={ 0: self.pad_token, 1: self.eos_token, } if self.mask_token_sent is not None: self.encoder.update( { 2: self.mask_token_sent, 3: self.mask_token, }) if self.offset > 0: # entries 2-104 are only used for pretraining and called <mask_1>, <mask_2>, unk_2, ...unk_102 # mask_token_sent is already added to list -> so start at 1 self.encoder.update({i + 3: additional_special_tokens[i] for i in range(1 , self.offset - 1)}) lowerCamelCase__: Dict[str, int] ={v: k for k, v in self.encoder.items()} @property def SCREAMING_SNAKE_CASE_ (self : str) ->int: '''simple docstring''' return len(self.sp_model) + self.offset def SCREAMING_SNAKE_CASE_ (self : Union[str, Any]) ->Dict[str, int]: '''simple docstring''' lowerCamelCase__: Union[str, Any] ={self.convert_ids_to_tokens(UpperCAmelCase_): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def __getstate__(self : int) ->Tuple: '''simple docstring''' lowerCamelCase__: Optional[Any] =self.__dict__.copy() lowerCamelCase__: Optional[Any] =None return state def __setstate__(self : List[str] , UpperCAmelCase_ : List[Any]) ->Tuple: '''simple docstring''' lowerCamelCase__: str =d # for backward compatibility if not hasattr(self , "sp_model_kwargs"): lowerCamelCase__: List[str] ={} lowerCamelCase__: str =spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(self.vocab_file) def SCREAMING_SNAKE_CASE_ (self : Union[str, Any] , UpperCAmelCase_ : str) ->List[str]: '''simple docstring''' return self.sp_model.encode(UpperCAmelCase_ , out_type=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Union[str, Any] , UpperCAmelCase_ : str) ->int: '''simple docstring''' if token in self.decoder: return self.decoder[token] elif token in self.added_tokens_decoder: return self.added_tokens_decoder[token] lowerCamelCase__: List[str] =self.sp_model.piece_to_id(UpperCAmelCase_) return sp_id + self.offset def SCREAMING_SNAKE_CASE_ (self : Union[str, Any] , UpperCAmelCase_ : int) ->str: '''simple docstring''' if index in self.encoder: return self.encoder[index] elif index in self.added_tokens_encoder: return self.added_tokens_encoder[index] else: lowerCamelCase__: Tuple =self.sp_model.IdToPiece(index - self.offset) return token def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : List[str]) ->Tuple: '''simple docstring''' lowerCamelCase__: List[str] =[] lowerCamelCase__: Union[str, Any] ="" for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(UpperCAmelCase_) + token lowerCamelCase__: Tuple =[] else: current_sub_tokens.append(UpperCAmelCase_) out_string += self.sp_model.decode(UpperCAmelCase_) return out_string.strip() def SCREAMING_SNAKE_CASE_ (self : List[Any] , UpperCAmelCase_ : List[str]=False) ->int: '''simple docstring''' return 1 def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : Optional[int]) ->List[str]: '''simple docstring''' lowerCamelCase__: Optional[Any] =set(self.all_special_ids) # call it once instead of inside list comp all_special_ids.remove(self.unk_token_id) # <unk> is only sometimes special return [1 if x in all_special_ids else 0 for x in seq] def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : List , UpperCAmelCase_ : Optional[List] = None , UpperCAmelCase_ : bool = False) ->List[int]: '''simple docstring''' if already_has_special_tokens: return self._special_token_mask(UpperCAmelCase_) elif token_ids_a is None: return self._special_token_mask(UpperCAmelCase_) + [1] else: return self._special_token_mask(token_ids_a + token_ids_a) + [1] def SCREAMING_SNAKE_CASE_ (self : str , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Optional[Any]=None) ->List[int]: '''simple docstring''' if token_ids_a is None: return token_ids_a + [self.eos_token_id] # We don't expect to process pairs, but leave the pair logic for API consistency return token_ids_a + token_ids_a + [self.eos_token_id] def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] = None) ->Tuple[str]: '''simple docstring''' if not os.path.isdir(UpperCAmelCase_): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""") return lowerCamelCase__: int =os.path.join( UpperCAmelCase_ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]) if os.path.abspath(self.vocab_file) != os.path.abspath(UpperCAmelCase_) and os.path.isfile(self.vocab_file): copyfile(self.vocab_file , UpperCAmelCase_) elif not os.path.isfile(self.vocab_file): with open(UpperCAmelCase_ , "wb") as fi: lowerCamelCase__: List[str] =self.sp_model.serialized_model_proto() fi.write(UpperCAmelCase_) return (out_vocab_file,)
59
import inspect import os import unittest import torch import accelerate from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_multi_gpu from accelerate.utils import patch_environment class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ (self : Dict) ->Optional[int]: '''simple docstring''' lowerCamelCase__: List[Any] =inspect.getfile(accelerate.test_utils) lowerCamelCase__: List[Any] =os.path.sep.join(mod_file.split(os.path.sep)[:-1] + ["scripts", "test_script.py"]) lowerCamelCase__: Any =os.path.sep.join( mod_file.split(os.path.sep)[:-1] + ["scripts", "test_distributed_data_loop.py"]) lowerCamelCase__: Tuple =os.path.sep.join(mod_file.split(os.path.sep)[:-1] + ["scripts", "test_ops.py"]) @require_multi_gpu def SCREAMING_SNAKE_CASE_ (self : str) ->str: '''simple docstring''' print(F"""Found {torch.cuda.device_count()} devices.""") lowerCamelCase__: Union[str, Any] =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", self.test_file_path] with patch_environment(omp_num_threads=1): execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy()) @require_multi_gpu def SCREAMING_SNAKE_CASE_ (self : List[str]) ->List[Any]: '''simple docstring''' print(F"""Found {torch.cuda.device_count()} devices.""") lowerCamelCase__: Dict =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", self.operation_file_path] print(F"""Command: {cmd}""") with patch_environment(omp_num_threads=1): execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy()) @require_multi_gpu def SCREAMING_SNAKE_CASE_ (self : Dict) ->Tuple: '''simple docstring''' lowerCamelCase__: int =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", inspect.getfile(self.__class__)] with patch_environment(omp_num_threads=1): execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy()) @require_multi_gpu def SCREAMING_SNAKE_CASE_ (self : str) ->List[Any]: '''simple docstring''' print(F"""Found {torch.cuda.device_count()} devices, using 2 devices only""") lowerCamelCase__: int =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", self.data_loop_file_path] with patch_environment(omp_num_threads=1 , cuda_visible_devices="0,1"): execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy()) if __name__ == "__main__": __A = Accelerator() __A = (accelerator.state.process_index + 2, 10) __A = torch.randint(0, 10, shape).to(accelerator.device) __A = "" __A = accelerator.pad_across_processes(tensor) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += f"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." if not torch.equal(tensora[: accelerator.state.process_index + 2], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[accelerator.state.process_index + 2 :] == 0): error_msg += "Padding was not done with the right value (0)." __A = accelerator.pad_across_processes(tensor, pad_first=True) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += f"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." __A = accelerator.state.num_processes - accelerator.state.process_index - 1 if not torch.equal(tensora[index:], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[:index] == 0): error_msg += "Padding was not done with the right value (0)." # 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)
59
1
import argparse import shlex import runhouse as rh if __name__ == "__main__": # Refer to https://runhouse-docs.readthedocs-hosted.com/en/latest/api/python/cluster.html#hardware-setup for cloud access # setup instructions, if using on-demand hardware # If user passes --user <user> --host <host> --key_path <key_path> <example> <args>, fill them in as BYO cluster # If user passes --instance <instance> --provider <provider> <example> <args>, fill them in as on-demand cluster # Throw an error if user passes both BYO and on-demand cluster args # Otherwise, use default values __A = argparse.ArgumentParser() parser.add_argument("--user", type=str, default="ubuntu") parser.add_argument("--host", type=str, default="localhost") parser.add_argument("--key_path", type=str, default=None) parser.add_argument("--instance", type=str, default="V100:1") parser.add_argument("--provider", type=str, default="cheapest") parser.add_argument("--use_spot", type=bool, default=False) parser.add_argument("--example", type=str, default="pytorch/text-generation/run_generation.py") __A , __A = parser.parse_known_args() if args.host != "localhost": if args.instance != "V100:1" or args.provider != "cheapest": raise ValueError("Cannot specify both BYO and on-demand cluster args") __A = rh.cluster( name="rh-cluster", ips=[args.host], ssh_creds={"ssh_user": args.user, "ssh_private_key": args.key_path} ) else: __A = rh.cluster( name="rh-cluster", instance_type=args.instance, provider=args.provider, use_spot=args.use_spot ) __A = args.example.rsplit("/", 1)[0] # Set up remote environment cluster.install_packages(["pip:./"]) # Installs transformers from local source # Note transformers is copied into the home directory on the remote machine, so we can install from there cluster.run([f'pip install -r transformers/examples/{example_dir}/requirements.txt']) cluster.run(["pip install torch --upgrade --extra-index-url https://download.pytorch.org/whl/cu117"]) # Run example. You can bypass the CLI wrapper and paste your own code here. cluster.run([f'python transformers/examples/{args.example} {" ".join(shlex.quote(arg) for arg in unknown)}']) # Alternatively, we can just import and run a training function (especially if there's no wrapper CLI): # from my_script... import train # reqs = ['pip:./', 'torch', 'datasets', 'accelerate', 'evaluate', 'tqdm', 'scipy', 'scikit-learn', 'tensorboard'] # launch_train_gpu = rh.function(fn=train, # system=gpu, # reqs=reqs, # name='train_bert_glue') # # We can pass in arguments just like we would to a function: # launch_train_gpu(num_epochs = 3, lr = 2e-5, seed = 42, batch_size = 16 # stream_logs=True)
59
from typing import List, Optional, Tuple, Union import PIL import torch from torchvision import transforms from diffusers.pipeline_utils import DiffusionPipeline, ImagePipelineOutput from diffusers.schedulers import DDIMScheduler from diffusers.utils import randn_tensor __A = transforms.Compose( [ transforms.Resize((256, 256)), transforms.ToTensor(), transforms.Normalize([0.5], [0.5]), ] ) def lowerCAmelCase_ ( __a ) -> str: """simple docstring""" if isinstance(__a , torch.Tensor ): return image elif isinstance(__a , PIL.Image.Image ): lowerCamelCase__: Any =[image] lowerCamelCase__: Optional[Any] =[trans(img.convert("RGB" ) ) for img in image] lowerCamelCase__: Dict =torch.stack(__a ) return image class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__(self : Any , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Tuple) ->int: '''simple docstring''' super().__init__() # make sure scheduler can always be converted to DDIM lowerCamelCase__: Tuple =DDIMScheduler.from_config(scheduler.config) self.register_modules(unet=UpperCAmelCase_ , scheduler=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Union[str, Any]) ->Dict: '''simple docstring''' if strength < 0 or strength > 1: raise ValueError(F"""The value of strength should in [0.0, 1.0] but is {strength}""") def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Tuple) ->Tuple: '''simple docstring''' lowerCamelCase__: int =min(int(num_inference_steps * strength) , UpperCAmelCase_) lowerCamelCase__: str =max(num_inference_steps - init_timestep , 0) lowerCamelCase__: int =self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[int]=None) ->Optional[int]: '''simple docstring''' if not isinstance(UpperCAmelCase_ , (torch.Tensor, PIL.Image.Image, list)): raise ValueError( F"""`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(UpperCAmelCase_)}""") lowerCamelCase__: Optional[int] =image.to(device=UpperCAmelCase_ , dtype=UpperCAmelCase_) if isinstance(UpperCAmelCase_ , UpperCAmelCase_) and len(UpperCAmelCase_) != batch_size: raise ValueError( F"""You have passed a list of generators of length {len(UpperCAmelCase_)}, but requested an effective batch""" F""" size of {batch_size}. Make sure the batch size matches the length of the generators.""") lowerCamelCase__: Dict =init_latents.shape lowerCamelCase__: int =randn_tensor(UpperCAmelCase_ , generator=UpperCAmelCase_ , device=UpperCAmelCase_ , dtype=UpperCAmelCase_) # get latents print("add noise to latents at timestep" , UpperCAmelCase_) lowerCamelCase__: Union[str, Any] =self.scheduler.add_noise(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: int =init_latents return latents @torch.no_grad() def __call__(self : Tuple , UpperCAmelCase_ : Union[torch.FloatTensor, PIL.Image.Image] = None , UpperCAmelCase_ : float = 0.8 , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , UpperCAmelCase_ : float = 0.0 , UpperCAmelCase_ : int = 50 , UpperCAmelCase_ : Optional[bool] = None , UpperCAmelCase_ : Optional[str] = "pil" , UpperCAmelCase_ : bool = True , ) ->Union[ImagePipelineOutput, Tuple]: '''simple docstring''' self.check_inputs(UpperCAmelCase_) # 2. Preprocess image lowerCamelCase__: Dict =preprocess(UpperCAmelCase_) # 3. set timesteps self.scheduler.set_timesteps(UpperCAmelCase_ , device=self.device) lowerCamelCase__ , lowerCamelCase__: str =self.get_timesteps(UpperCAmelCase_ , UpperCAmelCase_ , self.device) lowerCamelCase__: Optional[int] =timesteps[:1].repeat(UpperCAmelCase_) # 4. Prepare latent variables lowerCamelCase__: int =self.prepare_latents(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , self.unet.dtype , self.device , UpperCAmelCase_) lowerCamelCase__: Tuple =latents # 5. Denoising loop for t in self.progress_bar(UpperCAmelCase_): # 1. predict noise model_output lowerCamelCase__: Dict =self.unet(UpperCAmelCase_ , UpperCAmelCase_).sample # 2. predict previous mean of image x_t-1 and add variance depending on eta # eta corresponds to η in paper and should be between [0, 1] # do x_t -> x_t-1 lowerCamelCase__: Optional[int] =self.scheduler.step( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , eta=UpperCAmelCase_ , use_clipped_model_output=UpperCAmelCase_ , generator=UpperCAmelCase_ , ).prev_sample lowerCamelCase__: str =(image / 2 + 0.5).clamp(0 , 1) lowerCamelCase__: Optional[Any] =image.cpu().permute(0 , 2 , 3 , 1).numpy() if output_type == "pil": lowerCamelCase__: Dict =self.numpy_to_pil(UpperCAmelCase_) if not return_dict: return (image, latent_timestep.item()) return ImagePipelineOutput(images=UpperCAmelCase_)
59
1
def lowerCAmelCase_ ( __a , __a , __a = 0 , __a = 0 ) -> int: """simple docstring""" lowerCamelCase__: Optional[Any] =right or len(__a ) - 1 if left > right: return -1 elif list_data[left] == key: return left elif list_data[right] == key: return right else: return search(__a , __a , left + 1 , right - 1 ) if __name__ == "__main__": import doctest doctest.testmod()
59
import argparse import os import pickle import sys import torch from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils from transformers.models.transfo_xl.tokenization_transfo_xl import CORPUS_NAME, VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() # We do this to be able to load python 2 datasets pickles # See e.g. https://stackoverflow.com/questions/2121874/python-pickling-after-changing-a-modules-directory/2121918#2121918 __A = data_utils.TransfoXLTokenizer __A = data_utils.TransfoXLCorpus __A = data_utils __A = data_utils def lowerCAmelCase_ ( __a , __a , __a , __a ) -> List[str]: """simple docstring""" if transfo_xl_dataset_file: # Convert a pre-processed corpus (see original TensorFlow repo) with open(__a , "rb" ) as fp: lowerCamelCase__: Optional[Any] =pickle.load(__a , encoding="latin1" ) # Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term) lowerCamelCase__: Union[str, Any] =pytorch_dump_folder_path + "/" + VOCAB_FILES_NAMES["pretrained_vocab_file"] print(F"""Save vocabulary to {pytorch_vocab_dump_path}""" ) lowerCamelCase__: Any =corpus.vocab.__dict__ torch.save(__a , __a ) lowerCamelCase__: Dict =corpus.__dict__ corpus_dict_no_vocab.pop("vocab" , __a ) lowerCamelCase__: List[str] =pytorch_dump_folder_path + "/" + CORPUS_NAME print(F"""Save dataset to {pytorch_dataset_dump_path}""" ) torch.save(__a , __a ) if tf_checkpoint_path: # Convert a pre-trained TensorFlow model lowerCamelCase__: Optional[Any] =os.path.abspath(__a ) lowerCamelCase__: Dict =os.path.abspath(__a ) print(F"""Converting Transformer XL checkpoint from {tf_path} with config at {config_path}.""" ) # Initialise PyTorch model if transfo_xl_config_file == "": lowerCamelCase__: int =TransfoXLConfig() else: lowerCamelCase__: Any =TransfoXLConfig.from_json_file(__a ) print(F"""Building PyTorch model from configuration: {config}""" ) lowerCamelCase__: List[Any] =TransfoXLLMHeadModel(__a ) lowerCamelCase__: List[str] =load_tf_weights_in_transfo_xl(__a , __a , __a ) # Save pytorch-model lowerCamelCase__: List[str] =os.path.join(__a , __a ) lowerCamelCase__: Tuple =os.path.join(__a , __a ) print(F"""Save PyTorch model to {os.path.abspath(__a )}""" ) torch.save(model.state_dict() , __a ) print(F"""Save configuration file to {os.path.abspath(__a )}""" ) with open(__a , "w" , encoding="utf-8" ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": __A = argparse.ArgumentParser() parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the folder to store the PyTorch model or dataset/vocab.", ) parser.add_argument( "--tf_checkpoint_path", default="", type=str, help="An optional path to a TensorFlow checkpoint path to be converted.", ) parser.add_argument( "--transfo_xl_config_file", default="", type=str, help=( "An optional config json file corresponding to the pre-trained BERT model. \n" "This specifies the model architecture." ), ) parser.add_argument( "--transfo_xl_dataset_file", default="", type=str, help="An optional dataset file to be converted in a vocabulary.", ) __A = parser.parse_args() convert_transfo_xl_checkpoint_to_pytorch( args.tf_checkpoint_path, args.transfo_xl_config_file, args.pytorch_dump_folder_path, args.transfo_xl_dataset_file, )
59
1
import json import os from dataclasses import dataclass from functools import partial from typing import Callable import flax.linen as nn import jax import jax.numpy as jnp import joblib import optax import wandb from flax import jax_utils, struct, traverse_util from flax.serialization import from_bytes, to_bytes from flax.training import train_state from flax.training.common_utils import shard from tqdm.auto import tqdm from transformers import BigBirdConfig, FlaxBigBirdForQuestionAnswering from transformers.models.big_bird.modeling_flax_big_bird import FlaxBigBirdForQuestionAnsweringModule class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = 42 lowercase_ = jnp.floataa lowercase_ = True def SCREAMING_SNAKE_CASE_ (self : Any) ->List[str]: '''simple docstring''' super().setup() lowerCamelCase__: int =nn.Dense(5 , dtype=self.dtype) def __call__(self : Dict , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : Any) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Optional[Any] =super().__call__(*UpperCAmelCase_ , **UpperCAmelCase_) lowerCamelCase__: int =self.cls(outputs[2]) return outputs[:2] + (cls_out,) class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = FlaxBigBirdForNaturalQuestionsModule def lowerCAmelCase_ ( __a , __a , __a , __a , __a , __a ) -> Tuple: """simple docstring""" def cross_entropy(__a , __a , __a=None ): lowerCamelCase__: Tuple =logits.shape[-1] lowerCamelCase__: Tuple =(labels[..., None] == jnp.arange(__a )[None]).astype("f4" ) lowerCamelCase__: str =jax.nn.log_softmax(__a , axis=-1 ) lowerCamelCase__: Optional[Any] =-jnp.sum(labels * logits , axis=-1 ) if reduction is not None: lowerCamelCase__: Optional[Any] =reduction(__a ) return loss lowerCamelCase__: str =partial(__a , reduction=jnp.mean ) lowerCamelCase__: str =cross_entropy(__a , __a ) lowerCamelCase__: Optional[int] =cross_entropy(__a , __a ) lowerCamelCase__: Optional[Any] =cross_entropy(__a , __a ) return (start_loss + end_loss + pooled_loss) / 3 @dataclass class _SCREAMING_SNAKE_CASE : '''simple docstring''' lowercase_ = "google/bigbird-roberta-base" lowercase_ = 3000 lowercase_ = 1_0500 lowercase_ = 128 lowercase_ = 3 lowercase_ = 1 lowercase_ = 5 # tx_args lowercase_ = 3E-5 lowercase_ = 0.0 lowercase_ = 2_0000 lowercase_ = 0.0095 lowercase_ = "bigbird-roberta-natural-questions" lowercase_ = "training-expt" lowercase_ = "data/nq-training.jsonl" lowercase_ = "data/nq-validation.jsonl" def SCREAMING_SNAKE_CASE_ (self : Tuple) ->List[str]: '''simple docstring''' os.makedirs(self.base_dir , exist_ok=UpperCAmelCase_) lowerCamelCase__: Optional[Any] =os.path.join(self.base_dir , self.save_dir) lowerCamelCase__: List[str] =self.batch_size_per_device * jax.device_count() @dataclass class _SCREAMING_SNAKE_CASE : '''simple docstring''' lowercase_ = 42 lowercase_ = 4096 # no dynamic padding on TPUs def __call__(self : List[Any] , UpperCAmelCase_ : Optional[Any]) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Optional[Any] =self.collate_fn(UpperCAmelCase_) lowerCamelCase__: List[Any] =jax.tree_util.tree_map(UpperCAmelCase_ , UpperCAmelCase_) return batch def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : List[str]) ->List[Any]: '''simple docstring''' lowerCamelCase__ , lowerCamelCase__: List[Any] =self.fetch_inputs(features["input_ids"]) lowerCamelCase__: Union[str, Any] ={ "input_ids": jnp.array(UpperCAmelCase_ , dtype=jnp.intaa), "attention_mask": jnp.array(UpperCAmelCase_ , dtype=jnp.intaa), "start_labels": jnp.array(features["start_token"] , dtype=jnp.intaa), "end_labels": jnp.array(features["end_token"] , dtype=jnp.intaa), "pooled_labels": jnp.array(features["category"] , dtype=jnp.intaa), } return batch def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : list) ->Optional[Any]: '''simple docstring''' lowerCamelCase__: Tuple =[self._fetch_inputs(UpperCAmelCase_) for ids in input_ids] return zip(*UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[Any] , UpperCAmelCase_ : list) ->Any: '''simple docstring''' lowerCamelCase__: Optional[Any] =[1 for _ in range(len(UpperCAmelCase_))] while len(UpperCAmelCase_) < self.max_length: input_ids.append(self.pad_id) attention_mask.append(0) return input_ids, attention_mask def lowerCAmelCase_ ( __a , __a , __a=None ) -> str: """simple docstring""" if seed is not None: lowerCamelCase__: Any =dataset.shuffle(seed=__a ) for i in range(len(__a ) // batch_size ): lowerCamelCase__: Any =dataset[i * batch_size : (i + 1) * batch_size] yield dict(__a ) @partial(jax.pmap , axis_name="batch" ) def lowerCAmelCase_ ( __a , __a , **__a ) -> List[str]: """simple docstring""" def loss_fn(__a ): lowerCamelCase__: Optional[int] =model_inputs.pop("start_labels" ) lowerCamelCase__: int =model_inputs.pop("end_labels" ) lowerCamelCase__: List[str] =model_inputs.pop("pooled_labels" ) lowerCamelCase__: Optional[int] =state.apply_fn(**__a , params=__a , dropout_rng=__a , train=__a ) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: List[Any] =outputs return state.loss_fn( __a , __a , __a , __a , __a , __a , ) lowerCamelCase__ , lowerCamelCase__: int =jax.random.split(__a ) lowerCamelCase__: Optional[Any] =jax.value_and_grad(__a ) lowerCamelCase__ , lowerCamelCase__: List[str] =grad_fn(state.params ) lowerCamelCase__: Optional[Any] =jax.lax.pmean({"loss": loss} , axis_name="batch" ) lowerCamelCase__: List[str] =jax.lax.pmean(__a , "batch" ) lowerCamelCase__: List[str] =state.apply_gradients(grads=__a ) return state, metrics, new_drp_rng @partial(jax.pmap , axis_name="batch" ) def lowerCAmelCase_ ( __a , **__a ) -> List[Any]: """simple docstring""" lowerCamelCase__: int =model_inputs.pop("start_labels" ) lowerCamelCase__: List[str] =model_inputs.pop("end_labels" ) lowerCamelCase__: int =model_inputs.pop("pooled_labels" ) lowerCamelCase__: Optional[Any] =state.apply_fn(**__a , params=state.params , train=__a ) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: List[str] =outputs lowerCamelCase__: Optional[int] =state.loss_fn(__a , __a , __a , __a , __a , __a ) lowerCamelCase__: Optional[Any] =jax.lax.pmean({"loss": loss} , axis_name="batch" ) return metrics class _SCREAMING_SNAKE_CASE ( train_state.TrainState ): '''simple docstring''' lowercase_ = struct.field(pytree_node=__SCREAMING_SNAKE_CASE ) @dataclass class _SCREAMING_SNAKE_CASE : '''simple docstring''' lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = None def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : int=None) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Dict =model.params lowerCamelCase__: Tuple =TrainState.create( apply_fn=model.__call__ , params=UpperCAmelCase_ , tx=UpperCAmelCase_ , loss_fn=UpperCAmelCase_ , ) if ckpt_dir is not None: lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Any =restore_checkpoint(UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: Tuple ={ "lr": args.lr, "init_lr": args.init_lr, "warmup_steps": args.warmup_steps, "num_train_steps": num_train_steps, "weight_decay": args.weight_decay, } lowerCamelCase__ , lowerCamelCase__: List[Any] =build_tx(**UpperCAmelCase_) lowerCamelCase__: str =train_state.TrainState( step=UpperCAmelCase_ , apply_fn=model.__call__ , params=UpperCAmelCase_ , tx=UpperCAmelCase_ , opt_state=UpperCAmelCase_ , ) lowerCamelCase__: Tuple =args lowerCamelCase__: Tuple =data_collator lowerCamelCase__: str =lr lowerCamelCase__: Dict =params lowerCamelCase__: List[str] =jax_utils.replicate(UpperCAmelCase_) return state def SCREAMING_SNAKE_CASE_ (self : List[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Tuple) ->Optional[Any]: '''simple docstring''' lowerCamelCase__: Tuple =self.args lowerCamelCase__: Any =len(UpperCAmelCase_) // args.batch_size lowerCamelCase__: List[str] =jax.random.PRNGKey(0) lowerCamelCase__: Optional[Any] =jax.random.split(UpperCAmelCase_ , jax.device_count()) for epoch in range(args.max_epochs): lowerCamelCase__: Union[str, Any] =jnp.array(0 , dtype=jnp.floataa) lowerCamelCase__: str =get_batched_dataset(UpperCAmelCase_ , args.batch_size , seed=UpperCAmelCase_) lowerCamelCase__: Dict =0 for batch in tqdm(UpperCAmelCase_ , total=UpperCAmelCase_ , desc=F"""Running EPOCH-{epoch}"""): lowerCamelCase__: List[str] =self.data_collator(UpperCAmelCase_) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Optional[int] =self.train_step_fn(UpperCAmelCase_ , UpperCAmelCase_ , **UpperCAmelCase_) running_loss += jax_utils.unreplicate(metrics["loss"]) i += 1 if i % args.logging_steps == 0: lowerCamelCase__: Optional[int] =jax_utils.unreplicate(state.step) lowerCamelCase__: List[Any] =running_loss.item() / i lowerCamelCase__: Tuple =self.scheduler_fn(state_step - 1) lowerCamelCase__: Union[str, Any] =self.evaluate(UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: Dict ={ "step": state_step.item(), "eval_loss": eval_loss.item(), "tr_loss": tr_loss, "lr": lr.item(), } tqdm.write(str(UpperCAmelCase_)) self.logger.log(UpperCAmelCase_ , commit=UpperCAmelCase_) if i % args.save_steps == 0: self.save_checkpoint(args.save_dir + F"""-e{epoch}-s{i}""" , state=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : str , UpperCAmelCase_ : str) ->Any: '''simple docstring''' lowerCamelCase__: List[Any] =get_batched_dataset(UpperCAmelCase_ , self.args.batch_size) lowerCamelCase__: List[str] =len(UpperCAmelCase_) // self.args.batch_size lowerCamelCase__: str =jnp.array(0 , dtype=jnp.floataa) lowerCamelCase__: Optional[Any] =0 for batch in tqdm(UpperCAmelCase_ , total=UpperCAmelCase_ , desc="Evaluating ... "): lowerCamelCase__: int =self.data_collator(UpperCAmelCase_) lowerCamelCase__: str =self.val_step_fn(UpperCAmelCase_ , **UpperCAmelCase_) running_loss += jax_utils.unreplicate(metrics["loss"]) i += 1 return running_loss / i def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[int]) ->int: '''simple docstring''' lowerCamelCase__: Any =jax_utils.unreplicate(UpperCAmelCase_) print(F"""SAVING CHECKPOINT IN {save_dir}""" , end=" ... ") self.model_save_fn(UpperCAmelCase_ , params=state.params) with open(os.path.join(UpperCAmelCase_ , "opt_state.msgpack") , "wb") as f: f.write(to_bytes(state.opt_state)) joblib.dump(self.args , os.path.join(UpperCAmelCase_ , "args.joblib")) joblib.dump(self.data_collator , os.path.join(UpperCAmelCase_ , "data_collator.joblib")) with open(os.path.join(UpperCAmelCase_ , "training_state.json") , "w") as f: json.dump({"step": state.step.item()} , UpperCAmelCase_) print("DONE") def lowerCAmelCase_ ( __a , __a ) -> str: """simple docstring""" print(F"""RESTORING CHECKPOINT FROM {save_dir}""" , end=" ... " ) with open(os.path.join(__a , "flax_model.msgpack" ) , "rb" ) as f: lowerCamelCase__: Tuple =from_bytes(state.params , f.read() ) with open(os.path.join(__a , "opt_state.msgpack" ) , "rb" ) as f: lowerCamelCase__: Optional[int] =from_bytes(state.opt_state , f.read() ) lowerCamelCase__: Any =joblib.load(os.path.join(__a , "args.joblib" ) ) lowerCamelCase__: Union[str, Any] =joblib.load(os.path.join(__a , "data_collator.joblib" ) ) with open(os.path.join(__a , "training_state.json" ) , "r" ) as f: lowerCamelCase__: Optional[Any] =json.load(__a ) lowerCamelCase__: Any =training_state["step"] print("DONE" ) return params, opt_state, step, args, data_collator def lowerCAmelCase_ ( __a , __a , __a , __a ) -> Optional[int]: """simple docstring""" lowerCamelCase__: int =num_train_steps - warmup_steps lowerCamelCase__: str =optax.linear_schedule(init_value=__a , end_value=__a , transition_steps=__a ) lowerCamelCase__: Optional[Any] =optax.linear_schedule(init_value=__a , end_value=1e-7 , transition_steps=__a ) lowerCamelCase__: List[Any] =optax.join_schedules(schedules=[warmup_fn, decay_fn] , boundaries=[warmup_steps] ) return lr def lowerCAmelCase_ ( __a , __a , __a , __a , __a ) -> str: """simple docstring""" def weight_decay_mask(__a ): lowerCamelCase__: List[str] =traverse_util.flatten_dict(__a ) lowerCamelCase__: List[str] ={k: (v[-1] != "bias" and v[-2:] != ("LayerNorm", "scale")) for k, v in params.items()} return traverse_util.unflatten_dict(__a ) lowerCamelCase__: Optional[Any] =scheduler_fn(__a , __a , __a , __a ) lowerCamelCase__: Tuple =optax.adamw(learning_rate=__a , weight_decay=__a , mask=__a ) return tx, lr
59
from collections import UserDict from typing import List, Union from ..utils import ( add_end_docstrings, is_tf_available, is_torch_available, is_vision_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING from ..tf_utils import stable_softmax __A = logging.get_logger(__name__) @add_end_docstrings(__SCREAMING_SNAKE_CASE ) class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__(self : Optional[int] , **UpperCAmelCase_ : List[Any]) ->List[str]: '''simple docstring''' super().__init__(**UpperCAmelCase_) requires_backends(self , "vision") self.check_model_type( TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING if self.framework == "tf" else MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING) def __call__(self : List[str] , UpperCAmelCase_ : Union[str, List[str], "Image", List["Image"]] , **UpperCAmelCase_ : List[Any]) ->Tuple: '''simple docstring''' return super().__call__(UpperCAmelCase_ , **UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[Any] , **UpperCAmelCase_ : Optional[int]) ->Any: '''simple docstring''' lowerCamelCase__: Optional[int] ={} if "candidate_labels" in kwargs: lowerCamelCase__: Tuple =kwargs["candidate_labels"] if "hypothesis_template" in kwargs: lowerCamelCase__: Tuple =kwargs["hypothesis_template"] return preprocess_params, {}, {} def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Dict=None , UpperCAmelCase_ : Optional[Any]="This is a photo of {}.") ->str: '''simple docstring''' lowerCamelCase__: int =load_image(UpperCAmelCase_) lowerCamelCase__: Any =self.image_processor(images=[image] , return_tensors=self.framework) lowerCamelCase__: Any =candidate_labels lowerCamelCase__: List[str] =[hypothesis_template.format(UpperCAmelCase_) for x in candidate_labels] lowerCamelCase__: int =self.tokenizer(UpperCAmelCase_ , return_tensors=self.framework , padding=UpperCAmelCase_) lowerCamelCase__: str =[text_inputs] return inputs def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Any) ->Tuple: '''simple docstring''' lowerCamelCase__: int =model_inputs.pop("candidate_labels") lowerCamelCase__: List[str] =model_inputs.pop("text_inputs") if isinstance(text_inputs[0] , UpperCAmelCase_): lowerCamelCase__: List[Any] =text_inputs[0] else: # Batching case. lowerCamelCase__: List[Any] =text_inputs[0][0] lowerCamelCase__: List[str] =self.model(**UpperCAmelCase_ , **UpperCAmelCase_) lowerCamelCase__: str ={ "candidate_labels": candidate_labels, "logits": outputs.logits_per_image, } return model_outputs def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , UpperCAmelCase_ : Union[str, Any]) ->int: '''simple docstring''' lowerCamelCase__: List[Any] =model_outputs.pop("candidate_labels") lowerCamelCase__: Optional[int] =model_outputs["logits"][0] if self.framework == "pt": lowerCamelCase__: Optional[Any] =logits.softmax(dim=-1).squeeze(-1) lowerCamelCase__: Optional[Any] =probs.tolist() if not isinstance(UpperCAmelCase_ , UpperCAmelCase_): lowerCamelCase__: Optional[int] =[scores] elif self.framework == "tf": lowerCamelCase__: List[str] =stable_softmax(UpperCAmelCase_ , axis=-1) lowerCamelCase__: Optional[int] =probs.numpy().tolist() else: raise ValueError(F"""Unsupported framework: {self.framework}""") lowerCamelCase__: Optional[int] =[ {"score": score, "label": candidate_label} for score, candidate_label in sorted(zip(UpperCAmelCase_ , UpperCAmelCase_) , key=lambda UpperCAmelCase_: -x[0]) ] return result
59
1
from collections import UserDict from typing import List, Union from ..utils import ( add_end_docstrings, is_tf_available, is_torch_available, is_vision_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING from ..tf_utils import stable_softmax __A = logging.get_logger(__name__) @add_end_docstrings(__SCREAMING_SNAKE_CASE ) class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__(self : Optional[int] , **UpperCAmelCase_ : List[Any]) ->List[str]: '''simple docstring''' super().__init__(**UpperCAmelCase_) requires_backends(self , "vision") self.check_model_type( TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING if self.framework == "tf" else MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING) def __call__(self : List[str] , UpperCAmelCase_ : Union[str, List[str], "Image", List["Image"]] , **UpperCAmelCase_ : List[Any]) ->Tuple: '''simple docstring''' return super().__call__(UpperCAmelCase_ , **UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[Any] , **UpperCAmelCase_ : Optional[int]) ->Any: '''simple docstring''' lowerCamelCase__: Optional[int] ={} if "candidate_labels" in kwargs: lowerCamelCase__: Tuple =kwargs["candidate_labels"] if "hypothesis_template" in kwargs: lowerCamelCase__: Tuple =kwargs["hypothesis_template"] return preprocess_params, {}, {} def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Dict=None , UpperCAmelCase_ : Optional[Any]="This is a photo of {}.") ->str: '''simple docstring''' lowerCamelCase__: int =load_image(UpperCAmelCase_) lowerCamelCase__: Any =self.image_processor(images=[image] , return_tensors=self.framework) lowerCamelCase__: Any =candidate_labels lowerCamelCase__: List[str] =[hypothesis_template.format(UpperCAmelCase_) for x in candidate_labels] lowerCamelCase__: int =self.tokenizer(UpperCAmelCase_ , return_tensors=self.framework , padding=UpperCAmelCase_) lowerCamelCase__: str =[text_inputs] return inputs def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Any) ->Tuple: '''simple docstring''' lowerCamelCase__: int =model_inputs.pop("candidate_labels") lowerCamelCase__: List[str] =model_inputs.pop("text_inputs") if isinstance(text_inputs[0] , UpperCAmelCase_): lowerCamelCase__: List[Any] =text_inputs[0] else: # Batching case. lowerCamelCase__: List[Any] =text_inputs[0][0] lowerCamelCase__: List[str] =self.model(**UpperCAmelCase_ , **UpperCAmelCase_) lowerCamelCase__: str ={ "candidate_labels": candidate_labels, "logits": outputs.logits_per_image, } return model_outputs def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , UpperCAmelCase_ : Union[str, Any]) ->int: '''simple docstring''' lowerCamelCase__: List[Any] =model_outputs.pop("candidate_labels") lowerCamelCase__: Optional[int] =model_outputs["logits"][0] if self.framework == "pt": lowerCamelCase__: Optional[Any] =logits.softmax(dim=-1).squeeze(-1) lowerCamelCase__: Optional[Any] =probs.tolist() if not isinstance(UpperCAmelCase_ , UpperCAmelCase_): lowerCamelCase__: Optional[int] =[scores] elif self.framework == "tf": lowerCamelCase__: List[str] =stable_softmax(UpperCAmelCase_ , axis=-1) lowerCamelCase__: Optional[int] =probs.numpy().tolist() else: raise ValueError(F"""Unsupported framework: {self.framework}""") lowerCamelCase__: Optional[int] =[ {"score": score, "label": candidate_label} for score, candidate_label in sorted(zip(UpperCAmelCase_ , UpperCAmelCase_) , key=lambda UpperCAmelCase_: -x[0]) ] return result
59
import json import os from dataclasses import dataclass from functools import partial from typing import Callable import flax.linen as nn import jax import jax.numpy as jnp import joblib import optax import wandb from flax import jax_utils, struct, traverse_util from flax.serialization import from_bytes, to_bytes from flax.training import train_state from flax.training.common_utils import shard from tqdm.auto import tqdm from transformers import BigBirdConfig, FlaxBigBirdForQuestionAnswering from transformers.models.big_bird.modeling_flax_big_bird import FlaxBigBirdForQuestionAnsweringModule class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = 42 lowercase_ = jnp.floataa lowercase_ = True def SCREAMING_SNAKE_CASE_ (self : Any) ->List[str]: '''simple docstring''' super().setup() lowerCamelCase__: int =nn.Dense(5 , dtype=self.dtype) def __call__(self : Dict , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : Any) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Optional[Any] =super().__call__(*UpperCAmelCase_ , **UpperCAmelCase_) lowerCamelCase__: int =self.cls(outputs[2]) return outputs[:2] + (cls_out,) class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = FlaxBigBirdForNaturalQuestionsModule def lowerCAmelCase_ ( __a , __a , __a , __a , __a , __a ) -> Tuple: """simple docstring""" def cross_entropy(__a , __a , __a=None ): lowerCamelCase__: Tuple =logits.shape[-1] lowerCamelCase__: Tuple =(labels[..., None] == jnp.arange(__a )[None]).astype("f4" ) lowerCamelCase__: str =jax.nn.log_softmax(__a , axis=-1 ) lowerCamelCase__: Optional[Any] =-jnp.sum(labels * logits , axis=-1 ) if reduction is not None: lowerCamelCase__: Optional[Any] =reduction(__a ) return loss lowerCamelCase__: str =partial(__a , reduction=jnp.mean ) lowerCamelCase__: str =cross_entropy(__a , __a ) lowerCamelCase__: Optional[int] =cross_entropy(__a , __a ) lowerCamelCase__: Optional[Any] =cross_entropy(__a , __a ) return (start_loss + end_loss + pooled_loss) / 3 @dataclass class _SCREAMING_SNAKE_CASE : '''simple docstring''' lowercase_ = "google/bigbird-roberta-base" lowercase_ = 3000 lowercase_ = 1_0500 lowercase_ = 128 lowercase_ = 3 lowercase_ = 1 lowercase_ = 5 # tx_args lowercase_ = 3E-5 lowercase_ = 0.0 lowercase_ = 2_0000 lowercase_ = 0.0095 lowercase_ = "bigbird-roberta-natural-questions" lowercase_ = "training-expt" lowercase_ = "data/nq-training.jsonl" lowercase_ = "data/nq-validation.jsonl" def SCREAMING_SNAKE_CASE_ (self : Tuple) ->List[str]: '''simple docstring''' os.makedirs(self.base_dir , exist_ok=UpperCAmelCase_) lowerCamelCase__: Optional[Any] =os.path.join(self.base_dir , self.save_dir) lowerCamelCase__: List[str] =self.batch_size_per_device * jax.device_count() @dataclass class _SCREAMING_SNAKE_CASE : '''simple docstring''' lowercase_ = 42 lowercase_ = 4096 # no dynamic padding on TPUs def __call__(self : List[Any] , UpperCAmelCase_ : Optional[Any]) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Optional[Any] =self.collate_fn(UpperCAmelCase_) lowerCamelCase__: List[Any] =jax.tree_util.tree_map(UpperCAmelCase_ , UpperCAmelCase_) return batch def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : List[str]) ->List[Any]: '''simple docstring''' lowerCamelCase__ , lowerCamelCase__: List[Any] =self.fetch_inputs(features["input_ids"]) lowerCamelCase__: Union[str, Any] ={ "input_ids": jnp.array(UpperCAmelCase_ , dtype=jnp.intaa), "attention_mask": jnp.array(UpperCAmelCase_ , dtype=jnp.intaa), "start_labels": jnp.array(features["start_token"] , dtype=jnp.intaa), "end_labels": jnp.array(features["end_token"] , dtype=jnp.intaa), "pooled_labels": jnp.array(features["category"] , dtype=jnp.intaa), } return batch def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : list) ->Optional[Any]: '''simple docstring''' lowerCamelCase__: Tuple =[self._fetch_inputs(UpperCAmelCase_) for ids in input_ids] return zip(*UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[Any] , UpperCAmelCase_ : list) ->Any: '''simple docstring''' lowerCamelCase__: Optional[Any] =[1 for _ in range(len(UpperCAmelCase_))] while len(UpperCAmelCase_) < self.max_length: input_ids.append(self.pad_id) attention_mask.append(0) return input_ids, attention_mask def lowerCAmelCase_ ( __a , __a , __a=None ) -> str: """simple docstring""" if seed is not None: lowerCamelCase__: Any =dataset.shuffle(seed=__a ) for i in range(len(__a ) // batch_size ): lowerCamelCase__: Any =dataset[i * batch_size : (i + 1) * batch_size] yield dict(__a ) @partial(jax.pmap , axis_name="batch" ) def lowerCAmelCase_ ( __a , __a , **__a ) -> List[str]: """simple docstring""" def loss_fn(__a ): lowerCamelCase__: Optional[int] =model_inputs.pop("start_labels" ) lowerCamelCase__: int =model_inputs.pop("end_labels" ) lowerCamelCase__: List[str] =model_inputs.pop("pooled_labels" ) lowerCamelCase__: Optional[int] =state.apply_fn(**__a , params=__a , dropout_rng=__a , train=__a ) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: List[Any] =outputs return state.loss_fn( __a , __a , __a , __a , __a , __a , ) lowerCamelCase__ , lowerCamelCase__: int =jax.random.split(__a ) lowerCamelCase__: Optional[Any] =jax.value_and_grad(__a ) lowerCamelCase__ , lowerCamelCase__: List[str] =grad_fn(state.params ) lowerCamelCase__: Optional[Any] =jax.lax.pmean({"loss": loss} , axis_name="batch" ) lowerCamelCase__: List[str] =jax.lax.pmean(__a , "batch" ) lowerCamelCase__: List[str] =state.apply_gradients(grads=__a ) return state, metrics, new_drp_rng @partial(jax.pmap , axis_name="batch" ) def lowerCAmelCase_ ( __a , **__a ) -> List[Any]: """simple docstring""" lowerCamelCase__: int =model_inputs.pop("start_labels" ) lowerCamelCase__: List[str] =model_inputs.pop("end_labels" ) lowerCamelCase__: int =model_inputs.pop("pooled_labels" ) lowerCamelCase__: Optional[Any] =state.apply_fn(**__a , params=state.params , train=__a ) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: List[str] =outputs lowerCamelCase__: Optional[int] =state.loss_fn(__a , __a , __a , __a , __a , __a ) lowerCamelCase__: Optional[Any] =jax.lax.pmean({"loss": loss} , axis_name="batch" ) return metrics class _SCREAMING_SNAKE_CASE ( train_state.TrainState ): '''simple docstring''' lowercase_ = struct.field(pytree_node=__SCREAMING_SNAKE_CASE ) @dataclass class _SCREAMING_SNAKE_CASE : '''simple docstring''' lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = None def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : int=None) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Dict =model.params lowerCamelCase__: Tuple =TrainState.create( apply_fn=model.__call__ , params=UpperCAmelCase_ , tx=UpperCAmelCase_ , loss_fn=UpperCAmelCase_ , ) if ckpt_dir is not None: lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Any =restore_checkpoint(UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: Tuple ={ "lr": args.lr, "init_lr": args.init_lr, "warmup_steps": args.warmup_steps, "num_train_steps": num_train_steps, "weight_decay": args.weight_decay, } lowerCamelCase__ , lowerCamelCase__: List[Any] =build_tx(**UpperCAmelCase_) lowerCamelCase__: str =train_state.TrainState( step=UpperCAmelCase_ , apply_fn=model.__call__ , params=UpperCAmelCase_ , tx=UpperCAmelCase_ , opt_state=UpperCAmelCase_ , ) lowerCamelCase__: Tuple =args lowerCamelCase__: Tuple =data_collator lowerCamelCase__: str =lr lowerCamelCase__: Dict =params lowerCamelCase__: List[str] =jax_utils.replicate(UpperCAmelCase_) return state def SCREAMING_SNAKE_CASE_ (self : List[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Tuple) ->Optional[Any]: '''simple docstring''' lowerCamelCase__: Tuple =self.args lowerCamelCase__: Any =len(UpperCAmelCase_) // args.batch_size lowerCamelCase__: List[str] =jax.random.PRNGKey(0) lowerCamelCase__: Optional[Any] =jax.random.split(UpperCAmelCase_ , jax.device_count()) for epoch in range(args.max_epochs): lowerCamelCase__: Union[str, Any] =jnp.array(0 , dtype=jnp.floataa) lowerCamelCase__: str =get_batched_dataset(UpperCAmelCase_ , args.batch_size , seed=UpperCAmelCase_) lowerCamelCase__: Dict =0 for batch in tqdm(UpperCAmelCase_ , total=UpperCAmelCase_ , desc=F"""Running EPOCH-{epoch}"""): lowerCamelCase__: List[str] =self.data_collator(UpperCAmelCase_) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Optional[int] =self.train_step_fn(UpperCAmelCase_ , UpperCAmelCase_ , **UpperCAmelCase_) running_loss += jax_utils.unreplicate(metrics["loss"]) i += 1 if i % args.logging_steps == 0: lowerCamelCase__: Optional[int] =jax_utils.unreplicate(state.step) lowerCamelCase__: List[Any] =running_loss.item() / i lowerCamelCase__: Tuple =self.scheduler_fn(state_step - 1) lowerCamelCase__: Union[str, Any] =self.evaluate(UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: Dict ={ "step": state_step.item(), "eval_loss": eval_loss.item(), "tr_loss": tr_loss, "lr": lr.item(), } tqdm.write(str(UpperCAmelCase_)) self.logger.log(UpperCAmelCase_ , commit=UpperCAmelCase_) if i % args.save_steps == 0: self.save_checkpoint(args.save_dir + F"""-e{epoch}-s{i}""" , state=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : str , UpperCAmelCase_ : str) ->Any: '''simple docstring''' lowerCamelCase__: List[Any] =get_batched_dataset(UpperCAmelCase_ , self.args.batch_size) lowerCamelCase__: List[str] =len(UpperCAmelCase_) // self.args.batch_size lowerCamelCase__: str =jnp.array(0 , dtype=jnp.floataa) lowerCamelCase__: Optional[Any] =0 for batch in tqdm(UpperCAmelCase_ , total=UpperCAmelCase_ , desc="Evaluating ... "): lowerCamelCase__: int =self.data_collator(UpperCAmelCase_) lowerCamelCase__: str =self.val_step_fn(UpperCAmelCase_ , **UpperCAmelCase_) running_loss += jax_utils.unreplicate(metrics["loss"]) i += 1 return running_loss / i def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[int]) ->int: '''simple docstring''' lowerCamelCase__: Any =jax_utils.unreplicate(UpperCAmelCase_) print(F"""SAVING CHECKPOINT IN {save_dir}""" , end=" ... ") self.model_save_fn(UpperCAmelCase_ , params=state.params) with open(os.path.join(UpperCAmelCase_ , "opt_state.msgpack") , "wb") as f: f.write(to_bytes(state.opt_state)) joblib.dump(self.args , os.path.join(UpperCAmelCase_ , "args.joblib")) joblib.dump(self.data_collator , os.path.join(UpperCAmelCase_ , "data_collator.joblib")) with open(os.path.join(UpperCAmelCase_ , "training_state.json") , "w") as f: json.dump({"step": state.step.item()} , UpperCAmelCase_) print("DONE") def lowerCAmelCase_ ( __a , __a ) -> str: """simple docstring""" print(F"""RESTORING CHECKPOINT FROM {save_dir}""" , end=" ... " ) with open(os.path.join(__a , "flax_model.msgpack" ) , "rb" ) as f: lowerCamelCase__: Tuple =from_bytes(state.params , f.read() ) with open(os.path.join(__a , "opt_state.msgpack" ) , "rb" ) as f: lowerCamelCase__: Optional[int] =from_bytes(state.opt_state , f.read() ) lowerCamelCase__: Any =joblib.load(os.path.join(__a , "args.joblib" ) ) lowerCamelCase__: Union[str, Any] =joblib.load(os.path.join(__a , "data_collator.joblib" ) ) with open(os.path.join(__a , "training_state.json" ) , "r" ) as f: lowerCamelCase__: Optional[Any] =json.load(__a ) lowerCamelCase__: Any =training_state["step"] print("DONE" ) return params, opt_state, step, args, data_collator def lowerCAmelCase_ ( __a , __a , __a , __a ) -> Optional[int]: """simple docstring""" lowerCamelCase__: int =num_train_steps - warmup_steps lowerCamelCase__: str =optax.linear_schedule(init_value=__a , end_value=__a , transition_steps=__a ) lowerCamelCase__: Optional[Any] =optax.linear_schedule(init_value=__a , end_value=1e-7 , transition_steps=__a ) lowerCamelCase__: List[Any] =optax.join_schedules(schedules=[warmup_fn, decay_fn] , boundaries=[warmup_steps] ) return lr def lowerCAmelCase_ ( __a , __a , __a , __a , __a ) -> str: """simple docstring""" def weight_decay_mask(__a ): lowerCamelCase__: List[str] =traverse_util.flatten_dict(__a ) lowerCamelCase__: List[str] ={k: (v[-1] != "bias" and v[-2:] != ("LayerNorm", "scale")) for k, v in params.items()} return traverse_util.unflatten_dict(__a ) lowerCamelCase__: Optional[Any] =scheduler_fn(__a , __a , __a , __a ) lowerCamelCase__: Tuple =optax.adamw(learning_rate=__a , weight_decay=__a , mask=__a ) return tx, lr
59
1
import tempfile import unittest import numpy as np import transformers from transformers import GPTaTokenizer, GPTJConfig, is_flax_available, is_torch_available from transformers.testing_utils import is_pt_flax_cross_test, require_flax, tooslow from ...generation.test_flax_utils import FlaxGenerationTesterMixin from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax import jax.numpy as jnp from transformers.modeling_flax_pytorch_utils import ( convert_pytorch_state_dict_to_flax, load_flax_weights_in_pytorch_model, ) from transformers.models.gptj.modeling_flax_gptj import FlaxGPTJForCausalLM, FlaxGPTJModel if is_torch_available(): import torch class _SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__(self : str , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Dict=14 , UpperCAmelCase_ : Tuple=7 , UpperCAmelCase_ : Dict=True , UpperCAmelCase_ : Optional[Any]=True , UpperCAmelCase_ : Optional[Any]=False , UpperCAmelCase_ : List[str]=True , UpperCAmelCase_ : Dict=99 , UpperCAmelCase_ : List[str]=32 , UpperCAmelCase_ : Optional[int]=4 , UpperCAmelCase_ : Any=4 , UpperCAmelCase_ : List[Any]=4 , UpperCAmelCase_ : Any=37 , UpperCAmelCase_ : List[str]="gelu" , UpperCAmelCase_ : Tuple=0.1 , UpperCAmelCase_ : Optional[Any]=0.1 , UpperCAmelCase_ : Dict=512 , UpperCAmelCase_ : Any=0.02 , ) ->Any: '''simple docstring''' lowerCamelCase__: Union[str, Any] =parent lowerCamelCase__: Dict =batch_size lowerCamelCase__: Tuple =seq_length lowerCamelCase__: Union[str, Any] =is_training lowerCamelCase__: Tuple =use_input_mask lowerCamelCase__: List[Any] =use_token_type_ids lowerCamelCase__: Union[str, Any] =use_labels lowerCamelCase__: Dict =vocab_size lowerCamelCase__: Optional[Any] =hidden_size lowerCamelCase__: str =rotary_dim lowerCamelCase__: Dict =num_hidden_layers lowerCamelCase__: List[str] =num_attention_heads lowerCamelCase__: List[str] =intermediate_size lowerCamelCase__: Optional[Any] =hidden_act lowerCamelCase__: int =hidden_dropout_prob lowerCamelCase__: Optional[Any] =attention_probs_dropout_prob lowerCamelCase__: Any =max_position_embeddings lowerCamelCase__: Optional[int] =initializer_range lowerCamelCase__: str =None lowerCamelCase__: str =vocab_size - 1 lowerCamelCase__: List[Any] =vocab_size - 1 lowerCamelCase__: int =vocab_size - 1 def SCREAMING_SNAKE_CASE_ (self : Dict) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Union[str, Any] =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) lowerCamelCase__: Optional[int] =None if self.use_input_mask: lowerCamelCase__: Any =random_attention_mask([self.batch_size, self.seq_length]) lowerCamelCase__: List[Any] =GPTJConfig( 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 , use_cache=UpperCAmelCase_ , bos_token_id=self.bos_token_id , eos_token_id=self.eos_token_id , pad_token_id=self.pad_token_id , rotary_dim=self.rotary_dim , ) return (config, input_ids, input_mask) def SCREAMING_SNAKE_CASE_ (self : Tuple) ->str: '''simple docstring''' lowerCamelCase__: List[str] =self.prepare_config_and_inputs() lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Union[str, Any] =config_and_inputs lowerCamelCase__: Optional[int] ={"input_ids": input_ids, "attention_mask": attention_mask} return config, inputs_dict def SCREAMING_SNAKE_CASE_ (self : Dict , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Any , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Dict) ->Optional[Any]: '''simple docstring''' lowerCamelCase__: Any =20 lowerCamelCase__: str =model_class_name(UpperCAmelCase_) lowerCamelCase__: Any =model.init_cache(input_ids.shape[0] , UpperCAmelCase_) lowerCamelCase__: Union[str, Any] =jnp.ones((input_ids.shape[0], max_decoder_length) , dtype="i4") lowerCamelCase__: Dict =jnp.broadcast_to( jnp.arange(input_ids.shape[-1] - 1)[None, :] , (input_ids.shape[0], input_ids.shape[-1] - 1)) lowerCamelCase__: Optional[Any] =model( input_ids[:, :-1] , attention_mask=UpperCAmelCase_ , past_key_values=UpperCAmelCase_ , position_ids=UpperCAmelCase_ , ) lowerCamelCase__: Any =jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] , dtype="i4") lowerCamelCase__: List[Any] =model( input_ids[:, -1:] , attention_mask=UpperCAmelCase_ , past_key_values=outputs_cache.past_key_values , position_ids=UpperCAmelCase_ , ) lowerCamelCase__: List[str] =model(UpperCAmelCase_) lowerCamelCase__: Dict =np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]))) self.parent.assertTrue(diff < 1E-3 , msg=F"""Max diff is {diff}""") def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : str , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[Any]) ->Union[str, Any]: '''simple docstring''' lowerCamelCase__: Any =20 lowerCamelCase__: int =model_class_name(UpperCAmelCase_) lowerCamelCase__: int =jnp.concatenate( [attention_mask, jnp.zeros((attention_mask.shape[0], max_decoder_length - attention_mask.shape[1]))] , axis=-1 , ) lowerCamelCase__: int =model.init_cache(input_ids.shape[0] , UpperCAmelCase_) lowerCamelCase__: Optional[Any] =jnp.broadcast_to( jnp.arange(input_ids.shape[-1] - 1)[None, :] , (input_ids.shape[0], input_ids.shape[-1] - 1)) lowerCamelCase__: List[str] =model( input_ids[:, :-1] , attention_mask=UpperCAmelCase_ , past_key_values=UpperCAmelCase_ , position_ids=UpperCAmelCase_ , ) lowerCamelCase__: Any =jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] , dtype="i4") lowerCamelCase__: int =model( input_ids[:, -1:] , past_key_values=outputs_cache.past_key_values , attention_mask=UpperCAmelCase_ , position_ids=UpperCAmelCase_ , ) lowerCamelCase__: List[str] =model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_) lowerCamelCase__: Tuple =np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]))) self.parent.assertTrue(diff < 1E-3 , msg=F"""Max diff is {diff}""") @require_flax class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowercase_ = (FlaxGPTJModel, FlaxGPTJForCausalLM) if is_flax_available() else () lowercase_ = (FlaxGPTJForCausalLM,) if is_flax_available() else () def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->Any: '''simple docstring''' lowerCamelCase__: Tuple =FlaxGPTJModelTester(self) def SCREAMING_SNAKE_CASE_ (self : Union[str, Any]) ->str: '''simple docstring''' for model_class_name in self.all_model_classes: lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Any =self.model_tester.prepare_config_and_inputs() self.model_tester.check_use_cache_forward(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Optional[int]: '''simple docstring''' for model_class_name in self.all_model_classes: lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: int =self.model_tester.prepare_config_and_inputs() self.model_tester.check_use_cache_forward_with_attn_mask( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_) @tooslow def SCREAMING_SNAKE_CASE_ (self : Any) ->Optional[Any]: '''simple docstring''' lowerCamelCase__: Union[str, Any] =GPTaTokenizer.from_pretrained("gpt2" , pad_token="<|endoftext|>" , padding_side="left") lowerCamelCase__: Any =tokenizer(["Hello this is a long string", "Hey"] , return_tensors="np" , padding=UpperCAmelCase_ , truncation=UpperCAmelCase_) lowerCamelCase__: str =FlaxGPTJForCausalLM.from_pretrained("EleutherAI/gpt-j-6B") lowerCamelCase__: Union[str, Any] =False lowerCamelCase__: List[str] =model.config.eos_token_id lowerCamelCase__: Optional[Any] =jax.jit(model.generate) lowerCamelCase__: List[str] =jit_generate( inputs["input_ids"] , attention_mask=inputs["attention_mask"] , pad_token_id=tokenizer.pad_token_id).sequences lowerCamelCase__: Tuple =tokenizer.batch_decode(UpperCAmelCase_ , skip_special_tokens=UpperCAmelCase_) lowerCamelCase__: Dict =[ "Hello this is a long string of text.\n\nI'm trying to get the text of the", "Hey, I'm a little late to the party. I'm going to", ] self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_) @is_pt_flax_cross_test def SCREAMING_SNAKE_CASE_ (self : int) ->List[Any]: '''simple docstring''' lowerCamelCase__ , lowerCamelCase__: List[Any] =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__): # prepare inputs lowerCamelCase__: List[Any] =self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: List[Any] ={k: torch.tensor(v.tolist()) for k, v in prepared_inputs_dict.items()} # load corresponding PyTorch class lowerCamelCase__: Optional[Any] =model_class.__name__[4:] # Skip the "Flax" at the beginning lowerCamelCase__: List[Any] =getattr(UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__ , lowerCamelCase__: List[Any] =pt_inputs["input_ids"].shape lowerCamelCase__: Optional[Any] =np.random.randint(0 , seq_length - 1 , size=(batch_size,)) for batch_idx, start_index in enumerate(UpperCAmelCase_): lowerCamelCase__: str =0 lowerCamelCase__: Optional[Any] =1 lowerCamelCase__: int =0 lowerCamelCase__: Union[str, Any] =1 lowerCamelCase__: Dict =pt_model_class(UpperCAmelCase_).eval() lowerCamelCase__: Any =model_class(UpperCAmelCase_ , dtype=jnp.floataa) lowerCamelCase__: str =convert_pytorch_state_dict_to_flax(pt_model.state_dict() , UpperCAmelCase_) lowerCamelCase__: List[str] =fx_state with torch.no_grad(): lowerCamelCase__: Optional[int] =pt_model(**UpperCAmelCase_).to_tuple() lowerCamelCase__: Dict =fx_model(**UpperCAmelCase_).to_tuple() self.assertEqual(len(UpperCAmelCase_) , len(UpperCAmelCase_) , "Output lengths differ between Flax and PyTorch") for fx_output, pt_output in zip(UpperCAmelCase_ , UpperCAmelCase_): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2) with tempfile.TemporaryDirectory() as tmpdirname: pt_model.save_pretrained(UpperCAmelCase_) lowerCamelCase__: Optional[int] =model_class.from_pretrained(UpperCAmelCase_ , from_pt=UpperCAmelCase_) lowerCamelCase__: str =fx_model_loaded(**UpperCAmelCase_).to_tuple() self.assertEqual( len(UpperCAmelCase_) , len(UpperCAmelCase_) , "Output lengths differ between Flax and PyTorch") for fx_output_loaded, pt_output in zip(UpperCAmelCase_ , UpperCAmelCase_): self.assert_almost_equals(fx_output_loaded[:, -1] , pt_output[:, -1].numpy() , 4E-2) @is_pt_flax_cross_test def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->Union[str, Any]: '''simple docstring''' lowerCamelCase__ , lowerCamelCase__: Optional[Any] =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__): # prepare inputs lowerCamelCase__: Union[str, Any] =self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: Dict ={k: torch.tensor(v.tolist()) for k, v in prepared_inputs_dict.items()} # load corresponding PyTorch class lowerCamelCase__: Optional[int] =model_class.__name__[4:] # Skip the "Flax" at the beginning lowerCamelCase__: List[Any] =getattr(UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: Optional[Any] =pt_model_class(UpperCAmelCase_).eval() lowerCamelCase__: str =model_class(UpperCAmelCase_ , dtype=jnp.floataa) lowerCamelCase__: Union[str, Any] =load_flax_weights_in_pytorch_model(UpperCAmelCase_ , fx_model.params) lowerCamelCase__ , lowerCamelCase__: Optional[Any] =pt_inputs["input_ids"].shape lowerCamelCase__: List[Any] =np.random.randint(0 , seq_length - 1 , size=(batch_size,)) for batch_idx, start_index in enumerate(UpperCAmelCase_): lowerCamelCase__: str =0 lowerCamelCase__: Union[str, Any] =1 lowerCamelCase__: Dict =0 lowerCamelCase__: int =1 # make sure weights are tied in PyTorch pt_model.tie_weights() with torch.no_grad(): lowerCamelCase__: List[Any] =pt_model(**UpperCAmelCase_).to_tuple() lowerCamelCase__: Optional[int] =fx_model(**UpperCAmelCase_).to_tuple() self.assertEqual(len(UpperCAmelCase_) , len(UpperCAmelCase_) , "Output lengths differ between Flax and PyTorch") for fx_output, pt_output in zip(UpperCAmelCase_ , UpperCAmelCase_): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2) with tempfile.TemporaryDirectory() as tmpdirname: fx_model.save_pretrained(UpperCAmelCase_) lowerCamelCase__: str =pt_model_class.from_pretrained(UpperCAmelCase_ , from_flax=UpperCAmelCase_) with torch.no_grad(): lowerCamelCase__: Optional[int] =pt_model_loaded(**UpperCAmelCase_).to_tuple() self.assertEqual( len(UpperCAmelCase_) , len(UpperCAmelCase_) , "Output lengths differ between Flax and PyTorch") for fx_output, pt_output in zip(UpperCAmelCase_ , UpperCAmelCase_): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2) @tooslow def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Optional[int]: '''simple docstring''' for model_class_name in self.all_model_classes: lowerCamelCase__: List[Any] =model_class_name.from_pretrained("EleutherAI/gpt-j-6B") lowerCamelCase__: List[str] =model(np.ones((1, 1))) self.assertIsNotNone(UpperCAmelCase_)
59
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = ["image_processor", "tokenizer"] lowercase_ = "ChineseCLIPImageProcessor" lowercase_ = ("BertTokenizer", "BertTokenizerFast") def __init__(self : Any , UpperCAmelCase_ : List[str]=None , UpperCAmelCase_ : Union[str, Any]=None , **UpperCAmelCase_ : str) ->Dict: '''simple docstring''' lowerCamelCase__: str =None if "feature_extractor" in kwargs: warnings.warn( "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`" " instead." , UpperCAmelCase_ , ) lowerCamelCase__: Tuple =kwargs.pop("feature_extractor") lowerCamelCase__: Optional[int] =image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("You need to specify an `image_processor`.") if tokenizer is None: raise ValueError("You need to specify a `tokenizer`.") super().__init__(UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: Optional[int] =self.image_processor def __call__(self : int , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : List[Any]=None , **UpperCAmelCase_ : Dict) ->Optional[int]: '''simple docstring''' if text is None and images is None: raise ValueError("You have to specify either text or images. Both cannot be none.") if text is not None: lowerCamelCase__: Dict =self.tokenizer(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_) if images is not None: lowerCamelCase__: List[str] =self.image_processor(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_) if text is not None and images is not None: lowerCamelCase__: Union[str, Any] =image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**UpperCAmelCase_) , tensor_type=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : int) ->str: '''simple docstring''' return self.tokenizer.batch_decode(*UpperCAmelCase_ , **UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Any , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : List[Any]) ->Dict: '''simple docstring''' return self.tokenizer.decode(*UpperCAmelCase_ , **UpperCAmelCase_) @property def SCREAMING_SNAKE_CASE_ (self : int) ->List[str]: '''simple docstring''' lowerCamelCase__: str =self.tokenizer.model_input_names lowerCamelCase__: Union[str, Any] =self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names)) @property def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->str: '''simple docstring''' warnings.warn( "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead." , UpperCAmelCase_ , ) return self.image_processor_class
59
1
def lowerCAmelCase_ ( ) -> str: """simple docstring""" lowerCamelCase__: str =[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] lowerCamelCase__: List[str] =6 lowerCamelCase__: int =1 lowerCamelCase__: int =1901 lowerCamelCase__: List[str] =0 while year < 2001: 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 lowerCamelCase__: int =day - days_per_month[month - 2] elif day > 29 and month == 2: month += 1 lowerCamelCase__: Dict =day - 29 else: if day > days_per_month[month - 1]: month += 1 lowerCamelCase__: Tuple =day - days_per_month[month - 2] if month > 12: year += 1 lowerCamelCase__: Union[str, Any] =1 if year < 2001 and day == 1: sundays += 1 return sundays if __name__ == "__main__": print(solution())
59
from math import ceil, sqrt def lowerCAmelCase_ ( __a = 1000000 ) -> int: """simple docstring""" lowerCamelCase__: Any =0 for outer_width in range(3 , (limit // 4) + 2 ): if outer_width**2 > limit: lowerCamelCase__: Optional[int] =max(ceil(sqrt(outer_width**2 - limit ) ) , 1 ) else: lowerCamelCase__: Tuple =1 if (outer_width - hole_width_lower_bound) % 2: hole_width_lower_bound += 1 answer += (outer_width - hole_width_lower_bound - 2) // 2 + 1 return answer if __name__ == "__main__": print(f'{solution() = }')
59
1
import inspect import os import unittest import torch import accelerate from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_multi_gpu from accelerate.utils import patch_environment class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ (self : Dict) ->Optional[int]: '''simple docstring''' lowerCamelCase__: List[Any] =inspect.getfile(accelerate.test_utils) lowerCamelCase__: List[Any] =os.path.sep.join(mod_file.split(os.path.sep)[:-1] + ["scripts", "test_script.py"]) lowerCamelCase__: Any =os.path.sep.join( mod_file.split(os.path.sep)[:-1] + ["scripts", "test_distributed_data_loop.py"]) lowerCamelCase__: Tuple =os.path.sep.join(mod_file.split(os.path.sep)[:-1] + ["scripts", "test_ops.py"]) @require_multi_gpu def SCREAMING_SNAKE_CASE_ (self : str) ->str: '''simple docstring''' print(F"""Found {torch.cuda.device_count()} devices.""") lowerCamelCase__: Union[str, Any] =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", self.test_file_path] with patch_environment(omp_num_threads=1): execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy()) @require_multi_gpu def SCREAMING_SNAKE_CASE_ (self : List[str]) ->List[Any]: '''simple docstring''' print(F"""Found {torch.cuda.device_count()} devices.""") lowerCamelCase__: Dict =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", self.operation_file_path] print(F"""Command: {cmd}""") with patch_environment(omp_num_threads=1): execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy()) @require_multi_gpu def SCREAMING_SNAKE_CASE_ (self : Dict) ->Tuple: '''simple docstring''' lowerCamelCase__: int =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", inspect.getfile(self.__class__)] with patch_environment(omp_num_threads=1): execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy()) @require_multi_gpu def SCREAMING_SNAKE_CASE_ (self : str) ->List[Any]: '''simple docstring''' print(F"""Found {torch.cuda.device_count()} devices, using 2 devices only""") lowerCamelCase__: int =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", self.data_loop_file_path] with patch_environment(omp_num_threads=1 , cuda_visible_devices="0,1"): execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy()) if __name__ == "__main__": __A = Accelerator() __A = (accelerator.state.process_index + 2, 10) __A = torch.randint(0, 10, shape).to(accelerator.device) __A = "" __A = accelerator.pad_across_processes(tensor) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += f"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." if not torch.equal(tensora[: accelerator.state.process_index + 2], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[accelerator.state.process_index + 2 :] == 0): error_msg += "Padding was not done with the right value (0)." __A = accelerator.pad_across_processes(tensor, pad_first=True) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += f"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." __A = accelerator.state.num_processes - accelerator.state.process_index - 1 if not torch.equal(tensora[index:], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[:index] == 0): error_msg += "Padding was not done with the right value (0)." # 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)
59
def lowerCAmelCase_ ( __a = 50000000 ) -> int: """simple docstring""" lowerCamelCase__: Any =set() lowerCamelCase__: int =int((limit - 24) ** (1 / 2) ) lowerCamelCase__: Tuple =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 , __a ) ) ) for primea in primes: lowerCamelCase__: Optional[int] =primea * primea for primea in primes: lowerCamelCase__: List[str] =primea * primea * primea if square + cube >= limit - 16: break for primea in primes: lowerCamelCase__: int =primea * primea * primea * primea lowerCamelCase__: Optional[Any] =square + cube + tetr if total >= limit: break ret.add(__a ) return len(__a ) if __name__ == "__main__": print(f'{solution() = }')
59
1
import warnings 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 __A = logging.get_logger(__name__) __A = { "nvidia/segformer-b0-finetuned-ade-512-512": ( "https://huggingface.co/nvidia/segformer-b0-finetuned-ade-512-512/resolve/main/config.json" ), # See all SegFormer models at https://huggingface.co/models?filter=segformer } class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = "segformer" def __init__(self : List[Any] , UpperCAmelCase_ : Optional[Any]=3 , UpperCAmelCase_ : int=4 , UpperCAmelCase_ : List[str]=[2, 2, 2, 2] , UpperCAmelCase_ : Optional[Any]=[8, 4, 2, 1] , UpperCAmelCase_ : Dict=[32, 64, 160, 256] , UpperCAmelCase_ : List[Any]=[7, 3, 3, 3] , UpperCAmelCase_ : int=[4, 2, 2, 2] , UpperCAmelCase_ : Dict=[1, 2, 5, 8] , UpperCAmelCase_ : Tuple=[4, 4, 4, 4] , UpperCAmelCase_ : int="gelu" , UpperCAmelCase_ : Union[str, Any]=0.0 , UpperCAmelCase_ : Any=0.0 , UpperCAmelCase_ : Any=0.1 , UpperCAmelCase_ : List[str]=0.02 , UpperCAmelCase_ : Optional[int]=0.1 , UpperCAmelCase_ : Optional[Any]=1E-6 , UpperCAmelCase_ : Union[str, Any]=256 , UpperCAmelCase_ : Tuple=255 , **UpperCAmelCase_ : Dict , ) ->Optional[Any]: '''simple docstring''' super().__init__(**UpperCAmelCase_) if "reshape_last_stage" in kwargs and kwargs["reshape_last_stage"] is False: warnings.warn( "Reshape_last_stage is set to False in this config. This argument is deprecated and will soon be" " removed, as the behaviour will default to that of reshape_last_stage = True." , UpperCAmelCase_ , ) lowerCamelCase__: Union[str, Any] =num_channels lowerCamelCase__: Optional[Any] =num_encoder_blocks lowerCamelCase__: List[Any] =depths lowerCamelCase__: str =sr_ratios lowerCamelCase__: Dict =hidden_sizes lowerCamelCase__: Dict =patch_sizes lowerCamelCase__: str =strides lowerCamelCase__: Dict =mlp_ratios lowerCamelCase__: Dict =num_attention_heads lowerCamelCase__: List[Any] =hidden_act lowerCamelCase__: int =hidden_dropout_prob lowerCamelCase__: Optional[Any] =attention_probs_dropout_prob lowerCamelCase__: Union[str, Any] =classifier_dropout_prob lowerCamelCase__: List[Any] =initializer_range lowerCamelCase__: Tuple =drop_path_rate lowerCamelCase__: Optional[int] =layer_norm_eps lowerCamelCase__: int =decoder_hidden_size lowerCamelCase__: Tuple =kwargs.get("reshape_last_stage" , UpperCAmelCase_) lowerCamelCase__: List[str] =semantic_loss_ignore_index class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = version.parse("1.11" ) @property def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Mapping[str, Mapping[int, str]]: '''simple docstring''' return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ]) @property def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->float: '''simple docstring''' return 1E-4 @property def SCREAMING_SNAKE_CASE_ (self : Any) ->int: '''simple docstring''' return 12
59
from __future__ import annotations from decimal import Decimal from math import * # noqa: F403 from sympy import diff def lowerCAmelCase_ ( __a , __a , __a = 10**-10 ) -> float: """simple docstring""" lowerCamelCase__: List[str] =a while True: lowerCamelCase__: Optional[Any] =Decimal(__a ) - ( Decimal(eval(__a ) ) / Decimal(eval(str(diff(__a ) ) ) ) # noqa: S307 ) # This number dictates the accuracy of the answer if abs(eval(__a ) ) < precision: # noqa: S307 return float(__a ) # Let's Execute if __name__ == "__main__": # Find root of trigonometric function # Find value of pi print(f'The root of sin(x) = 0 is {newton_raphson("sin(x)", 2)}') # Find root of polynomial print(f'The root of x**2 - 5*x + 2 = 0 is {newton_raphson("x**2 - 5*x + 2", 0.4)}') # Find Square Root of 5 print(f'The root of log(x) - 1 = 0 is {newton_raphson("log(x) - 1", 2)}') # Exponential Roots print(f'The root of exp(x) - 1 = 0 is {newton_raphson("exp(x) - 1", 0)}')
59
1
import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, FEATURE_EXTRACTOR_MAPPING, AutoConfig, AutoFeatureExtractor, WavaVecaConfig, WavaVecaFeatureExtractor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, get_tests_dir sys.path.append(str(Path(__file__).parent.parent.parent.parent / "utils")) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_feature_extraction import CustomFeatureExtractor # noqa E402 __A = get_tests_dir("fixtures") __A = get_tests_dir("fixtures/dummy_feature_extractor_config.json") __A = get_tests_dir("fixtures/dummy-config.json") class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Tuple: '''simple docstring''' lowerCamelCase__: Any =0 def SCREAMING_SNAKE_CASE_ (self : Tuple) ->int: '''simple docstring''' lowerCamelCase__: Any =AutoFeatureExtractor.from_pretrained("facebook/wav2vec2-base-960h") self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : int) ->List[str]: '''simple docstring''' lowerCamelCase__: List[Any] =AutoFeatureExtractor.from_pretrained(UpperCAmelCase_) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : int) ->List[Any]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: lowerCamelCase__: List[Any] =WavaVecaConfig() # remove feature_extractor_type to make sure config.json alone is enough to load feature processor locally lowerCamelCase__: Optional[int] =AutoFeatureExtractor.from_pretrained(UpperCAmelCase_).to_dict() config_dict.pop("feature_extractor_type") lowerCamelCase__: List[str] =WavaVecaFeatureExtractor(**UpperCAmelCase_) # save in new folder model_config.save_pretrained(UpperCAmelCase_) config.save_pretrained(UpperCAmelCase_) lowerCamelCase__: Dict =AutoFeatureExtractor.from_pretrained(UpperCAmelCase_) # make sure private variable is not incorrectly saved lowerCamelCase__: str =json.loads(config.to_json_string()) self.assertTrue("_processor_class" not in dict_as_saved) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->List[Any]: '''simple docstring''' lowerCamelCase__: List[str] =AutoFeatureExtractor.from_pretrained(UpperCAmelCase_) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Any) ->int: '''simple docstring''' with self.assertRaisesRegex( UpperCAmelCase_ , "bert-base is not a local folder and is not a valid model identifier"): lowerCamelCase__: Union[str, Any] =AutoFeatureExtractor.from_pretrained("bert-base") def SCREAMING_SNAKE_CASE_ (self : int) ->str: '''simple docstring''' with self.assertRaisesRegex( UpperCAmelCase_ , R"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)"): lowerCamelCase__: List[Any] =AutoFeatureExtractor.from_pretrained(UpperCAmelCase_ , revision="aaaaaa") def SCREAMING_SNAKE_CASE_ (self : Any) ->Optional[Any]: '''simple docstring''' with self.assertRaisesRegex( UpperCAmelCase_ , "hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json." , ): lowerCamelCase__: int =AutoFeatureExtractor.from_pretrained("hf-internal-testing/config-no-model") def SCREAMING_SNAKE_CASE_ (self : str) ->str: '''simple docstring''' with self.assertRaises(UpperCAmelCase_): lowerCamelCase__: List[str] =AutoFeatureExtractor.from_pretrained( "hf-internal-testing/test_dynamic_feature_extractor") # If remote code is disabled, we can't load this config. with self.assertRaises(UpperCAmelCase_): lowerCamelCase__: List[str] =AutoFeatureExtractor.from_pretrained( "hf-internal-testing/test_dynamic_feature_extractor" , trust_remote_code=UpperCAmelCase_) lowerCamelCase__: List[str] =AutoFeatureExtractor.from_pretrained( "hf-internal-testing/test_dynamic_feature_extractor" , trust_remote_code=UpperCAmelCase_) self.assertEqual(feature_extractor.__class__.__name__ , "NewFeatureExtractor") # Test feature extractor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: feature_extractor.save_pretrained(UpperCAmelCase_) lowerCamelCase__: int =AutoFeatureExtractor.from_pretrained(UpperCAmelCase_ , trust_remote_code=UpperCAmelCase_) self.assertEqual(reloaded_feature_extractor.__class__.__name__ , "NewFeatureExtractor") def SCREAMING_SNAKE_CASE_ (self : List[str]) ->Union[str, Any]: '''simple docstring''' try: AutoConfig.register("custom" , UpperCAmelCase_) AutoFeatureExtractor.register(UpperCAmelCase_ , UpperCAmelCase_) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(UpperCAmelCase_): AutoFeatureExtractor.register(UpperCAmelCase_ , UpperCAmelCase_) # Now that the config is registered, it can be used as any other config with the auto-API lowerCamelCase__: Dict =CustomFeatureExtractor.from_pretrained(UpperCAmelCase_) with tempfile.TemporaryDirectory() as tmp_dir: feature_extractor.save_pretrained(UpperCAmelCase_) lowerCamelCase__: Optional[Any] =AutoFeatureExtractor.from_pretrained(UpperCAmelCase_) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content: del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig] def SCREAMING_SNAKE_CASE_ (self : Any) ->Any: '''simple docstring''' class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = True try: AutoConfig.register("custom" , UpperCAmelCase_) AutoFeatureExtractor.register(UpperCAmelCase_ , UpperCAmelCase_) # If remote code is not set, the default is to use local lowerCamelCase__: Union[str, Any] =AutoFeatureExtractor.from_pretrained( "hf-internal-testing/test_dynamic_feature_extractor") self.assertEqual(feature_extractor.__class__.__name__ , "NewFeatureExtractor") self.assertTrue(feature_extractor.is_local) # If remote code is disabled, we load the local one. lowerCamelCase__: Dict =AutoFeatureExtractor.from_pretrained( "hf-internal-testing/test_dynamic_feature_extractor" , trust_remote_code=UpperCAmelCase_) self.assertEqual(feature_extractor.__class__.__name__ , "NewFeatureExtractor") self.assertTrue(feature_extractor.is_local) # If remote is enabled, we load from the Hub lowerCamelCase__: List[Any] =AutoFeatureExtractor.from_pretrained( "hf-internal-testing/test_dynamic_feature_extractor" , trust_remote_code=UpperCAmelCase_) self.assertEqual(feature_extractor.__class__.__name__ , "NewFeatureExtractor") self.assertTrue(not hasattr(UpperCAmelCase_ , "is_local")) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content: del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]
59
import numpy as np from numpy import ndarray from scipy.optimize import Bounds, LinearConstraint, minimize def lowerCAmelCase_ ( __a ) -> float: """simple docstring""" return np.dot(__a , __a ) class _SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__(self : List[str] , *, UpperCAmelCase_ : float = np.inf , UpperCAmelCase_ : str = "linear" , UpperCAmelCase_ : float = 0.0 , ) ->None: '''simple docstring''' lowerCamelCase__: Dict =regularization lowerCamelCase__: Any =gamma if kernel == "linear": lowerCamelCase__: Dict =self.__linear elif kernel == "rbf": if self.gamma == 0: raise ValueError("rbf kernel requires gamma") if not isinstance(self.gamma , (float, int)): raise ValueError("gamma must be float or int") if not self.gamma > 0: raise ValueError("gamma must be > 0") lowerCamelCase__: Tuple =self.__rbf # in the future, there could be a default value like in sklearn # sklear: def_gamma = 1/(n_features * X.var()) (wiki) # previously it was 1/(n_features) else: lowerCamelCase__: Optional[Any] =F"""Unknown kernel: {kernel}""" raise ValueError(UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : ndarray , UpperCAmelCase_ : ndarray) ->float: '''simple docstring''' return np.dot(UpperCAmelCase_ , UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : ndarray , UpperCAmelCase_ : ndarray) ->float: '''simple docstring''' return np.exp(-(self.gamma * norm_squared(vectora - vectora))) def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : list[ndarray] , UpperCAmelCase_ : ndarray) ->None: '''simple docstring''' lowerCamelCase__: Optional[Any] =observations lowerCamelCase__: Optional[int] =classes # using Wolfe's Dual to calculate w. # Primal problem: minimize 1/2*norm_squared(w) # constraint: yn(w . xn + b) >= 1 # # With l a vector # Dual problem: maximize sum_n(ln) - # 1/2 * sum_n(sum_m(ln*lm*yn*ym*xn . xm)) # constraint: self.C >= ln >= 0 # and sum_n(ln*yn) = 0 # Then we get w using w = sum_n(ln*yn*xn) # At the end we can get b ~= mean(yn - w . xn) # # Since we use kernels, we only need l_star to calculate b # and to classify observations ((lowerCamelCase__) , ): List[str] =np.shape(UpperCAmelCase_) def to_minimize(UpperCAmelCase_ : ndarray) -> float: lowerCamelCase__: int =0 ((lowerCamelCase__) , ): Optional[Any] =np.shape(UpperCAmelCase_) for i in range(UpperCAmelCase_): for j in range(UpperCAmelCase_): s += ( candidate[i] * candidate[j] * classes[i] * classes[j] * self.kernel(observations[i] , observations[j]) ) return 1 / 2 * s - sum(UpperCAmelCase_) lowerCamelCase__: List[Any] =LinearConstraint(UpperCAmelCase_ , 0 , 0) lowerCamelCase__: str =Bounds(0 , self.regularization) lowerCamelCase__: Union[str, Any] =minimize( UpperCAmelCase_ , np.ones(UpperCAmelCase_) , bounds=UpperCAmelCase_ , constraints=[ly_contraint]).x lowerCamelCase__: str =l_star # calculating mean offset of separation plane to points lowerCamelCase__: Tuple =0 for i in range(UpperCAmelCase_): for j in range(UpperCAmelCase_): s += classes[i] - classes[i] * self.optimum[i] * self.kernel( observations[i] , observations[j]) lowerCamelCase__: int =s / n def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : ndarray) ->int: '''simple docstring''' lowerCamelCase__: Optional[Any] =sum( self.optimum[n] * self.classes[n] * self.kernel(self.observations[n] , UpperCAmelCase_) for n in range(len(self.classes))) return 1 if s + self.offset >= 0 else -1 if __name__ == "__main__": import doctest doctest.testmod()
59
1
from collections import defaultdict from pathlib import Path import pandas as pd from rouge_cli import calculate_rouge_path from utils import calculate_rouge __A = [ "Prosecutor: \"No videos were used in the crash investigation\" German papers say they saw a cell phone video of the" " final seconds on board Flight 9525. The Germanwings co-pilot says he had a \"previous episode of severe" " depression\" German airline confirms it knew of Andreas Lubitz's depression years before he took control.", "The Palestinian Authority officially becomes the 123rd member of the International Criminal Court. The formal" " accession was marked with a ceremony at The Hague, in the Netherlands. The Palestinians signed the ICC's" " founding Rome Statute in January. Israel and the United States opposed the Palestinians' efforts to join the" " body.", "Amnesty International releases its annual report on the death penalty. The report catalogs the use of" " state-sanctioned killing as a punitive measure across the globe. At least 607 people were executed around the" " world in 2014, compared to 778 in 2013. The U.S. remains one of the worst offenders for imposing capital" " punishment.", ] __A = [ "Marseille prosecutor says \"so far no videos were used in the crash investigation\" despite media reports ." " Journalists at Bild and Paris Match are \"very confident\" the video clip is real, an editor says . Andreas Lubitz" " had informed his Lufthansa training school of an episode of severe depression, airline says .", "Membership gives the ICC jurisdiction over alleged crimes committed in Palestinian territories since last June ." " Israel and the United States opposed the move, which could open the door to war crimes investigations against" " Israelis .", "Amnesty's annual death penalty report catalogs encouraging signs, but setbacks in numbers of those sentenced to" " death . Organization claims that governments around the world are using the threat of terrorism to advance" " executions . The number of executions worldwide has gone down by almost 22% compared with 2013, but death" " sentences up by 28% .", ] def lowerCAmelCase_ ( ) -> int: """simple docstring""" lowerCamelCase__: Any =calculate_rouge(__a , __a , bootstrap_aggregation=__a , rouge_keys=["rouge2", "rougeL"] ) assert isinstance(__a , __a ) lowerCamelCase__: List[Any] =calculate_rouge(__a , __a , bootstrap_aggregation=__a , rouge_keys=["rouge2"] ) assert ( pd.DataFrame(no_aggregation["rouge2"] ).fmeasure.mean() == pd.DataFrame(no_aggregation_just_ra["rouge2"] ).fmeasure.mean() ) def lowerCAmelCase_ ( ) -> List[str]: """simple docstring""" lowerCamelCase__: Optional[int] ="rougeLsum" lowerCamelCase__: Tuple =calculate_rouge(__a , __a , newline_sep=__a , rouge_keys=[k] )[k] lowerCamelCase__: Optional[Any] =calculate_rouge(__a , __a , newline_sep=__a , rouge_keys=[k] )[k] assert score > score_no_sep def lowerCAmelCase_ ( ) -> Optional[Any]: """simple docstring""" lowerCamelCase__: List[Any] =["rouge1", "rouge2", "rougeL"] lowerCamelCase__: int =calculate_rouge(__a , __a , newline_sep=__a , rouge_keys=__a ) lowerCamelCase__: List[str] =calculate_rouge(__a , __a , newline_sep=__a , rouge_keys=__a ) assert score_sep == score_no_sep def lowerCAmelCase_ ( ) -> Dict: """simple docstring""" lowerCamelCase__: Dict =[ "Her older sister, Margot Frank, died in 1945, a month earlier than previously thought.", "Marseille prosecutor says \"so far no videos were used in the crash investigation\" despite media reports .", ] lowerCamelCase__: int =[ "Margot Frank, died in 1945, a month earlier than previously thought.", "Prosecutor: \"No videos were used in the crash investigation\" German papers say they saw a cell phone video of" " the final seconds on board Flight 9525.", ] assert calculate_rouge(__a , __a , newline_sep=__a ) == calculate_rouge(__a , __a , newline_sep=__a ) def lowerCAmelCase_ ( ) -> Tuple: """simple docstring""" lowerCamelCase__: List[str] =[ "\" \"a person who has such a video needs to immediately give it to the investigators,\" prosecutor says .<n> \"it is a very disturbing scene,\" editor-in-chief of bild online tells \"erin burnett: outfront\" " ] lowerCamelCase__: List[Any] =[ " Marseille prosecutor says \"so far no videos were used in the crash investigation\" despite media reports . Journalists at Bild and Paris Match are \"very confident\" the video clip is real, an editor says . Andreas Lubitz had informed his Lufthansa training school of an episode of severe depression, airline says ." ] lowerCamelCase__: Dict =calculate_rouge(__a , __a , rouge_keys=["rougeLsum"] , newline_sep=__a )["rougeLsum"] lowerCamelCase__: Tuple =calculate_rouge(__a , __a , rouge_keys=["rougeLsum"] )["rougeLsum"] assert new_score > prev_score def lowerCAmelCase_ ( ) -> Dict: """simple docstring""" lowerCamelCase__: Optional[Any] =Path("examples/seq2seq/test_data/wmt_en_ro" ) lowerCamelCase__: Union[str, Any] =calculate_rouge_path(data_dir.joinpath("test.source" ) , data_dir.joinpath("test.target" ) ) assert isinstance(__a , __a ) lowerCamelCase__: Dict =calculate_rouge_path( data_dir.joinpath("test.source" ) , data_dir.joinpath("test.target" ) , bootstrap_aggregation=__a ) assert isinstance(__a , __a )
59
import logging import os from typing import Dict, List, Optional, Union import torch import torch.nn as nn from accelerate.utils.imports import ( is_abit_bnb_available, is_abit_bnb_available, is_bnb_available, ) from ..big_modeling import dispatch_model, init_empty_weights from .dataclasses import BnbQuantizationConfig from .modeling import ( find_tied_parameters, get_balanced_memory, infer_auto_device_map, load_checkpoint_in_model, offload_weight, set_module_tensor_to_device, ) if is_bnb_available(): import bitsandbytes as bnb from copy import deepcopy __A = logging.getLogger(__name__) def lowerCAmelCase_ ( __a , __a , __a = None , __a = None , __a = None , __a = None , __a = None , __a = False , ) -> str: """simple docstring""" lowerCamelCase__: int =bnb_quantization_config.load_in_abit lowerCamelCase__: Any =bnb_quantization_config.load_in_abit if load_in_abit and not is_abit_bnb_available(): raise ImportError( "You have a version of `bitsandbytes` that is not compatible with 8bit quantization," " make sure you have the latest version of `bitsandbytes` installed." ) if load_in_abit and not is_abit_bnb_available(): raise ValueError( "You have a version of `bitsandbytes` that is not compatible with 4bit quantization," "make sure you have the latest version of `bitsandbytes` installed." ) lowerCamelCase__: List[Any] =[] # custom device map if isinstance(__a , __a ) and len(device_map.keys() ) > 1: lowerCamelCase__: Optional[int] =[key for key, value in device_map.items() if value in ["disk", "cpu"]] # We keep some modules such as the lm_head in their original dtype for numerical stability reasons if bnb_quantization_config.skip_modules is None: lowerCamelCase__: Any =get_keys_to_not_convert(__a ) # add cpu modules to skip modules only for 4-bit modules if load_in_abit: bnb_quantization_config.skip_modules.extend(__a ) lowerCamelCase__: List[str] =bnb_quantization_config.skip_modules # We add the modules we want to keep in full precision if bnb_quantization_config.keep_in_fpaa_modules is None: lowerCamelCase__: List[Any] =[] lowerCamelCase__: int =bnb_quantization_config.keep_in_fpaa_modules modules_to_not_convert.extend(__a ) # compatibility with peft lowerCamelCase__: List[str] =load_in_abit lowerCamelCase__: int =load_in_abit lowerCamelCase__: Tuple =get_parameter_device(__a ) if model_device.type != "meta": # quantization of an already loaded model logger.warning( "It is not recommended to quantize a loaded model. " "The model should be instantiated under the `init_empty_weights` context manager." ) lowerCamelCase__: Tuple =replace_with_bnb_layers(__a , __a , modules_to_not_convert=__a ) # convert param to the right dtype lowerCamelCase__: Dict =bnb_quantization_config.torch_dtype for name, param in model.state_dict().items(): if any(module_to_keep_in_fpaa in name for module_to_keep_in_fpaa in keep_in_fpaa_modules ): param.to(torch.floataa ) if param.dtype != torch.floataa: lowerCamelCase__: str =name.replace(".weight" , "" ).replace(".bias" , "" ) lowerCamelCase__: Optional[Any] =getattr(__a , __a , __a ) if param is not None: param.to(torch.floataa ) elif torch.is_floating_point(__a ): param.to(__a ) if model_device.type == "cuda": # move everything to cpu in the first place because we can't do quantization if the weights are already on cuda model.cuda(torch.cuda.current_device() ) torch.cuda.empty_cache() elif torch.cuda.is_available(): model.to(torch.cuda.current_device() ) else: raise RuntimeError("No GPU found. A GPU is needed for quantization." ) logger.info( F"""The model device type is {model_device.type}. However, cuda is needed for quantization.""" "We move the model to cuda." ) return model elif weights_location is None: raise RuntimeError( F"""`weights_location` needs to be the folder path containing the weights of the model, but we found {weights_location} """ ) else: with init_empty_weights(): lowerCamelCase__: str =replace_with_bnb_layers( __a , __a , modules_to_not_convert=__a ) lowerCamelCase__: Optional[Any] =get_quantized_model_device_map( __a , __a , __a , max_memory=__a , no_split_module_classes=__a , ) if offload_state_dict is None and device_map is not None and "disk" in device_map.values(): lowerCamelCase__: Any =True lowerCamelCase__: List[str] =any(x in list(device_map.values() ) for x in ["cpu", "disk"] ) load_checkpoint_in_model( __a , __a , __a , dtype=bnb_quantization_config.torch_dtype , offload_folder=__a , offload_state_dict=__a , keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules , offload_abit_bnb=load_in_abit and offload , ) return dispatch_model(__a , device_map=__a , offload_dir=__a ) def lowerCAmelCase_ ( __a , __a , __a=None , __a=None , __a=None ) -> str: """simple docstring""" if device_map is None: if torch.cuda.is_available(): lowerCamelCase__: str ={"": torch.cuda.current_device()} else: raise RuntimeError("No GPU found. A GPU is needed for quantization." ) logger.info("The device_map was not initialized." "Setting device_map to `{'':torch.cuda.current_device()}`." ) if isinstance(__a , __a ): if device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]: raise ValueError( "If passing a string for `device_map`, please choose 'auto', 'balanced', 'balanced_low_0' or " "'sequential'." ) lowerCamelCase__: Optional[int] ={} special_dtypes.update( { name: bnb_quantization_config.torch_dtype for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.skip_modules ) } ) special_dtypes.update( { name: torch.floataa for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.keep_in_fpaa_modules ) } ) lowerCamelCase__: Optional[Any] ={} lowerCamelCase__: str =special_dtypes lowerCamelCase__: List[str] =no_split_module_classes lowerCamelCase__: Dict =bnb_quantization_config.target_dtype # get max_memory for each device. if device_map != "sequential": lowerCamelCase__: Optional[Any] =get_balanced_memory( __a , low_zero=(device_map == "balanced_low_0") , max_memory=__a , **__a , ) lowerCamelCase__: Union[str, Any] =max_memory lowerCamelCase__: Dict =infer_auto_device_map(__a , **__a ) if isinstance(__a , __a ): # check if don't have any quantized module on the cpu lowerCamelCase__: Union[str, Any] =bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules lowerCamelCase__: List[Any] ={ key: device_map[key] for key in device_map.keys() if key not in modules_not_to_convert } for device in ["cpu", "disk"]: if device in device_map_without_some_modules.values(): if bnb_quantization_config.load_in_abit: raise ValueError( "\n Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit\n the quantized model. If you want to dispatch the model on the CPU or the disk while keeping\n these modules in `torch_dtype`, you need to pass a custom `device_map` to\n `load_and_quantize_model`. Check\n https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk\n for more details.\n " ) else: logger.info( "Some modules are are offloaded to the CPU or the disk. Note that these modules will be converted to 8-bit" ) del device_map_without_some_modules return device_map def lowerCAmelCase_ ( __a , __a , __a=None , __a=None ) -> Optional[Any]: """simple docstring""" if modules_to_not_convert is None: lowerCamelCase__: List[Any] =[] lowerCamelCase__ , lowerCamelCase__: Any =_replace_with_bnb_layers( __a , __a , __a , __a ) if not has_been_replaced: logger.warning( "You are loading your model in 8bit or 4bit but no linear modules were found in your model." " this can happen for some architectures such as gpt2 that uses Conv1D instead of Linear layers." " Please double check your model architecture, or submit an issue on github if you think this is" " a bug." ) return model def lowerCAmelCase_ ( __a , __a , __a=None , __a=None , ) -> List[Any]: """simple docstring""" lowerCamelCase__: Optional[int] =False for name, module in model.named_children(): if current_key_name is None: lowerCamelCase__: Optional[Any] =[] current_key_name.append(__a ) if isinstance(__a , nn.Linear ) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` lowerCamelCase__: List[str] =".".join(__a ) lowerCamelCase__: Optional[Any] =True for key in modules_to_not_convert: if ( (key in current_key_name_str) and (key + "." in current_key_name_str) ) or key == current_key_name_str: lowerCamelCase__: int =False break if proceed: # Load bnb module with empty weight and replace ``nn.Linear` module if bnb_quantization_config.load_in_abit: lowerCamelCase__: Optional[int] =bnb.nn.LinearabitLt( module.in_features , module.out_features , module.bias is not None , has_fpaa_weights=__a , threshold=bnb_quantization_config.llm_inta_threshold , ) elif bnb_quantization_config.load_in_abit: lowerCamelCase__: Dict =bnb.nn.Linearabit( module.in_features , module.out_features , module.bias is not None , bnb_quantization_config.bnb_abit_compute_dtype , compress_statistics=bnb_quantization_config.bnb_abit_use_double_quant , quant_type=bnb_quantization_config.bnb_abit_quant_type , ) else: raise ValueError("load_in_8bit and load_in_4bit can't be both False" ) lowerCamelCase__: Dict =module.weight.data if module.bias is not None: lowerCamelCase__: List[Any] =module.bias.data bnb_module.requires_grad_(__a ) setattr(__a , __a , __a ) lowerCamelCase__: int =True if len(list(module.children() ) ) > 0: lowerCamelCase__ , lowerCamelCase__: List[str] =_replace_with_bnb_layers( __a , __a , __a , __a ) lowerCamelCase__: Union[str, Any] =has_been_replaced | _has_been_replaced # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def lowerCAmelCase_ ( __a ) -> List[Any]: """simple docstring""" with init_empty_weights(): lowerCamelCase__: Any =deepcopy(__a ) # this has 0 cost since it is done inside `init_empty_weights` context manager` lowerCamelCase__: str =find_tied_parameters(__a ) # For compatibility with Accelerate < 0.18 if isinstance(__a , __a ): lowerCamelCase__: int =sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() ) else: lowerCamelCase__: str =sum(__a , [] ) lowerCamelCase__: str =len(__a ) > 0 # Check if it is a base model lowerCamelCase__: Optional[Any] =False if hasattr(__a , "base_model_prefix" ): lowerCamelCase__: Union[str, Any] =not hasattr(__a , model.base_model_prefix ) # Ignore this for base models (BertModel, GPT2Model, etc.) if (not has_tied_params) and is_base_model: return [] # otherwise they have an attached head lowerCamelCase__: Optional[int] =list(model.named_children() ) lowerCamelCase__: Optional[int] =[list_modules[-1][0]] # add last module together with tied weights lowerCamelCase__: Union[str, Any] =set(__a ) - set(__a ) lowerCamelCase__: List[str] =list(set(__a ) ) + list(__a ) # remove ".weight" from the keys lowerCamelCase__: List[Any] =[".weight", ".bias"] lowerCamelCase__: Tuple =[] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: lowerCamelCase__: Optional[Any] =name.replace(__a , "" ) filtered_module_names.append(__a ) return filtered_module_names def lowerCAmelCase_ ( __a ) -> Tuple: """simple docstring""" for m in model.modules(): if isinstance(__a , bnb.nn.Linearabit ): return True return False def lowerCAmelCase_ ( __a ) -> List[str]: """simple docstring""" return next(parameter.parameters() ).device def lowerCAmelCase_ ( __a , __a , __a , __a , __a , __a , __a ) -> Any: """simple docstring""" if fpaa_statistics is None: set_module_tensor_to_device(__a , __a , 0 , dtype=__a , value=__a ) lowerCamelCase__: Dict =param_name lowerCamelCase__: Tuple =model if "." in tensor_name: lowerCamelCase__: Any =tensor_name.split("." ) for split in splits[:-1]: lowerCamelCase__: Any =getattr(__a , __a ) if new_module is None: raise ValueError(F"""{module} has no attribute {split}.""" ) lowerCamelCase__: str =new_module lowerCamelCase__: int =splits[-1] # offload weights lowerCamelCase__: str =False offload_weight(module._parameters[tensor_name] , __a , __a , index=__a ) if hasattr(module._parameters[tensor_name] , "SCB" ): offload_weight( module._parameters[tensor_name].SCB , param_name.replace("weight" , "SCB" ) , __a , index=__a , ) else: offload_weight(__a , __a , __a , index=__a ) offload_weight(__a , param_name.replace("weight" , "SCB" ) , __a , index=__a ) set_module_tensor_to_device(__a , __a , "meta" , dtype=__a , value=torch.empty(*param.size() ) )
59
1
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 _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__(self : Optional[int] , UpperCAmelCase_ : NestedDataStructureLike[PathLike] , UpperCAmelCase_ : Optional[NamedSplit] = None , UpperCAmelCase_ : Optional[Features] = None , UpperCAmelCase_ : str = None , UpperCAmelCase_ : bool = False , UpperCAmelCase_ : bool = False , UpperCAmelCase_ : Optional[int] = None , **UpperCAmelCase_ : Optional[Any] , ) ->Any: '''simple docstring''' super().__init__( UpperCAmelCase_ , split=UpperCAmelCase_ , features=UpperCAmelCase_ , cache_dir=UpperCAmelCase_ , keep_in_memory=UpperCAmelCase_ , streaming=UpperCAmelCase_ , num_proc=UpperCAmelCase_ , **UpperCAmelCase_ , ) lowerCamelCase__: Tuple =path_or_paths if isinstance(UpperCAmelCase_ , UpperCAmelCase_) else {self.split: path_or_paths} lowerCamelCase__: Optional[int] =Text( cache_dir=UpperCAmelCase_ , data_files=UpperCAmelCase_ , features=UpperCAmelCase_ , **UpperCAmelCase_ , ) def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Tuple: '''simple docstring''' if self.streaming: lowerCamelCase__: int =self.builder.as_streaming_dataset(split=self.split) # Build regular (map-style) dataset else: lowerCamelCase__: Optional[int] =None lowerCamelCase__: Optional[Any] =None lowerCamelCase__: List[str] =None lowerCamelCase__: str =None self.builder.download_and_prepare( download_config=UpperCAmelCase_ , download_mode=UpperCAmelCase_ , verification_mode=UpperCAmelCase_ , base_path=UpperCAmelCase_ , num_proc=self.num_proc , ) lowerCamelCase__: Any =self.builder.as_dataset( split=self.split , verification_mode=UpperCAmelCase_ , in_memory=self.keep_in_memory) return dataset
59
from __future__ import annotations from math import pi def lowerCAmelCase_ ( __a , __a , __a ) -> dict[str, float]: """simple docstring""" if (inductance, frequency, reactance).count(0 ) != 1: raise ValueError("One and only one argument must be 0" ) if inductance < 0: raise ValueError("Inductance cannot be negative" ) if frequency < 0: raise ValueError("Frequency cannot be negative" ) if reactance < 0: raise ValueError("Inductive reactance cannot be negative" ) if inductance == 0: return {"inductance": reactance / (2 * pi * frequency)} elif frequency == 0: return {"frequency": reactance / (2 * pi * inductance)} elif reactance == 0: return {"reactance": 2 * pi * frequency * inductance} else: raise ValueError("Exactly one argument must be 0" ) if __name__ == "__main__": import doctest doctest.testmod()
59
1
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 _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = RobertaConfig lowercase_ = "roberta" def __init__(self : List[Any] , UpperCAmelCase_ : Union[str, Any]) ->Union[str, Any]: '''simple docstring''' super().__init__(UpperCAmelCase_) lowerCamelCase__: Any =RobertaEmbeddings(UpperCAmelCase_) self.init_weights() @add_start_docstrings( "RoBERTa Model (with early exiting - DeeRoBERTa) with a classifier on top,\n also takes care of multi-layer training. " , __SCREAMING_SNAKE_CASE , ) class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = RobertaConfig lowercase_ = "roberta" def __init__(self : Optional[Any] , UpperCAmelCase_ : List[str]) ->str: '''simple docstring''' super().__init__(UpperCAmelCase_) lowerCamelCase__: Union[str, Any] =config.num_labels lowerCamelCase__: Union[str, Any] =config.num_hidden_layers lowerCamelCase__: Dict =DeeRobertaModel(UpperCAmelCase_) lowerCamelCase__: Optional[Any] =nn.Dropout(config.hidden_dropout_prob) lowerCamelCase__: Tuple =nn.Linear(config.hidden_size , self.config.num_labels) @add_start_docstrings_to_model_forward(UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Dict , UpperCAmelCase_ : Dict=None , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : Dict=None , UpperCAmelCase_ : Optional[int]=None , UpperCAmelCase_ : Optional[int]=None , UpperCAmelCase_ : int=None , UpperCAmelCase_ : Any=None , UpperCAmelCase_ : Dict=-1 , UpperCAmelCase_ : List[Any]=False , ) ->Union[str, Any]: '''simple docstring''' lowerCamelCase__: List[Any] =self.num_layers try: lowerCamelCase__: Any =self.roberta( UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , position_ids=UpperCAmelCase_ , head_mask=UpperCAmelCase_ , inputs_embeds=UpperCAmelCase_ , ) lowerCamelCase__: int =outputs[1] lowerCamelCase__: int =self.dropout(UpperCAmelCase_) lowerCamelCase__: Optional[Any] =self.classifier(UpperCAmelCase_) lowerCamelCase__: List[Any] =(logits,) + outputs[2:] # add hidden states and attention if they are here except HighwayException as e: lowerCamelCase__: List[str] =e.message lowerCamelCase__: str =e.exit_layer lowerCamelCase__: Dict =outputs[0] if not self.training: lowerCamelCase__: Dict =entropy(UpperCAmelCase_) lowerCamelCase__: Tuple =[] lowerCamelCase__: Optional[int] =[] if labels is not None: if self.num_labels == 1: # We are doing regression lowerCamelCase__: Optional[int] =MSELoss() lowerCamelCase__: Tuple =loss_fct(logits.view(-1) , labels.view(-1)) else: lowerCamelCase__: str =CrossEntropyLoss() lowerCamelCase__: Optional[int] =loss_fct(logits.view(-1 , self.num_labels) , labels.view(-1)) # work with highway exits lowerCamelCase__: List[Any] =[] for highway_exit in outputs[-1]: lowerCamelCase__: List[Any] =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 lowerCamelCase__: Optional[Any] =MSELoss() lowerCamelCase__: Union[str, Any] =loss_fct(highway_logits.view(-1) , labels.view(-1)) else: lowerCamelCase__: List[str] =CrossEntropyLoss() lowerCamelCase__: List[str] =loss_fct(highway_logits.view(-1 , self.num_labels) , labels.view(-1)) highway_losses.append(UpperCAmelCase_) if train_highway: lowerCamelCase__: Optional[Any] =(sum(highway_losses[:-1]),) + outputs # exclude the final highway, of course else: lowerCamelCase__: Any =(loss,) + outputs if not self.training: lowerCamelCase__: Any =outputs + ((original_entropy, highway_entropy), exit_layer) if output_layer >= 0: lowerCamelCase__: Tuple =( (outputs[0],) + (highway_logits_all[output_layer],) + outputs[2:] ) # use the highway of the last layer return outputs # (loss), logits, (hidden_states), (attentions), entropy
59
import pyarrow.parquet as pq import pytest from datasets import Audio, Dataset, DatasetDict, Features, NamedSplit, Sequence, Value, config from datasets.features.image import Image from datasets.io.parquet import ParquetDatasetReader, ParquetDatasetWriter, get_writer_batch_size from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def lowerCAmelCase_ ( __a , __a ) -> List[Any]: """simple docstring""" assert isinstance(__a , __a ) 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 lowerCAmelCase_ ( __a , __a , __a ) -> Any: """simple docstring""" lowerCamelCase__: Any =tmp_path / "cache" lowerCamelCase__: Optional[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(): lowerCamelCase__: Tuple =ParquetDatasetReader(__a , cache_dir=__a , keep_in_memory=__a ).read() _check_parquet_dataset(__a , __a ) @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 lowerCAmelCase_ ( __a , __a , __a ) -> List[str]: """simple docstring""" lowerCamelCase__: int =tmp_path / "cache" lowerCamelCase__: Tuple ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: Union[str, Any] =features.copy() if features else default_expected_features lowerCamelCase__: Optional[int] =( Features({feature: Value(__a ) for feature, dtype in features.items()} ) if features is not None else None ) lowerCamelCase__: int =ParquetDatasetReader(__a , features=__a , cache_dir=__a ).read() _check_parquet_dataset(__a , __a ) @pytest.mark.parametrize("split" , [None, NamedSplit("train" ), "train", "test"] ) def lowerCAmelCase_ ( __a , __a , __a ) -> Any: """simple docstring""" lowerCamelCase__: Any =tmp_path / "cache" lowerCamelCase__: Optional[Any] ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: Optional[Any] =ParquetDatasetReader(__a , cache_dir=__a , split=__a ).read() _check_parquet_dataset(__a , __a ) assert dataset.split == split if split else "train" @pytest.mark.parametrize("path_type" , [str, list] ) def lowerCAmelCase_ ( __a , __a , __a ) -> int: """simple docstring""" if issubclass(__a , __a ): lowerCamelCase__: List[Any] =parquet_path elif issubclass(__a , __a ): lowerCamelCase__: str =[parquet_path] lowerCamelCase__: Tuple =tmp_path / "cache" lowerCamelCase__: Optional[Any] ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: int =ParquetDatasetReader(__a , cache_dir=__a ).read() _check_parquet_dataset(__a , __a ) def lowerCAmelCase_ ( __a , __a , __a=("train",) ) -> Dict: """simple docstring""" assert isinstance(__a , __a ) for split in splits: lowerCamelCase__: Tuple =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 lowerCAmelCase_ ( __a , __a , __a ) -> Any: """simple docstring""" lowerCamelCase__: List[Any] =tmp_path / "cache" lowerCamelCase__: Optional[Any] ={"col_1": "string", "col_2": "int64", "col_3": "float64"} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): lowerCamelCase__: Tuple =ParquetDatasetReader( {"train": parquet_path} , cache_dir=__a , keep_in_memory=__a ).read() _check_parquet_datasetdict(__a , __a ) @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 lowerCAmelCase_ ( __a , __a , __a ) -> Optional[Any]: """simple docstring""" lowerCamelCase__: Tuple =tmp_path / "cache" lowerCamelCase__: Optional[int] ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: List[Any] =features.copy() if features else default_expected_features lowerCamelCase__: int =( Features({feature: Value(__a ) for feature, dtype in features.items()} ) if features is not None else None ) lowerCamelCase__: Optional[Any] =ParquetDatasetReader({"train": parquet_path} , features=__a , cache_dir=__a ).read() _check_parquet_datasetdict(__a , __a ) @pytest.mark.parametrize("split" , [None, NamedSplit("train" ), "train", "test"] ) def lowerCAmelCase_ ( __a , __a , __a ) -> Union[str, Any]: """simple docstring""" if split: lowerCamelCase__: Any ={split: parquet_path} else: lowerCamelCase__: int ="train" lowerCamelCase__: Any ={"train": parquet_path, "test": parquet_path} lowerCamelCase__: str =tmp_path / "cache" lowerCamelCase__: Any ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: int =ParquetDatasetReader(__a , cache_dir=__a ).read() _check_parquet_datasetdict(__a , __a , splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() ) def lowerCAmelCase_ ( __a , __a ) -> int: """simple docstring""" lowerCamelCase__: List[str] =ParquetDatasetWriter(__a , tmp_path / "foo.parquet" ) assert writer.write() > 0 lowerCamelCase__: List[str] =pq.ParquetFile(tmp_path / "foo.parquet" ) lowerCamelCase__: List[str] =pf.read() assert dataset.data.table == output_table def lowerCAmelCase_ ( __a , __a ) -> List[str]: """simple docstring""" lowerCamelCase__: List[str] =str(shared_datadir / "test_image_rgb.jpg" ) lowerCamelCase__: Union[str, Any] ={"image": [image_path]} lowerCamelCase__: Optional[Any] =Features({"image": Image()} ) lowerCamelCase__: Optional[int] =Dataset.from_dict(__a , features=__a ) lowerCamelCase__: Optional[int] =ParquetDatasetWriter(__a , tmp_path / "foo.parquet" ) assert writer.write() > 0 lowerCamelCase__: Dict =Dataset.from_parquet(str(tmp_path / "foo.parquet" ) ) assert dataset.features == reloaded_dataset.features lowerCamelCase__: Optional[Any] =ParquetDatasetReader(str(tmp_path / "foo.parquet" ) , streaming=__a ).read() assert dataset.features == reloaded_iterable_dataset.features @pytest.mark.parametrize( "feature, expected" , [ (Features({"foo": Value("int32" )} ), None), (Features({"image": Image(), "foo": Value("int32" )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS), (Features({"nested": Sequence(Audio() )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS), ] , ) def lowerCAmelCase_ ( __a , __a ) -> Optional[Any]: """simple docstring""" assert get_writer_batch_size(__a ) == expected
59
1
import argparse import torch from torch import nn from transformers import MaMaaaConfig, MaMaaaForConditionalGeneration def lowerCAmelCase_ ( __a ) -> Any: """simple docstring""" lowerCamelCase__: List[Any] =[ "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 lowerCAmelCase_ ( __a ) -> List[str]: """simple docstring""" lowerCamelCase__ , lowerCamelCase__: str =emb.weight.shape lowerCamelCase__: Optional[Any] =nn.Linear(__a , __a , bias=__a ) lowerCamelCase__: str =emb.weight.data return lin_layer def lowerCAmelCase_ ( __a ) -> Any: """simple docstring""" lowerCamelCase__: str =torch.load(__a , map_location="cpu" ) lowerCamelCase__: List[Any] =mam_aaa["args"] or mam_aaa["cfg"]["model"] lowerCamelCase__: Dict =mam_aaa["model"] remove_ignore_keys_(__a ) lowerCamelCase__: Any =state_dict["encoder.embed_tokens.weight"].shape[0] lowerCamelCase__: Dict =MaMaaaConfig( vocab_size=__a , max_position_embeddings=1024 , encoder_layers=args.encoder_layers , decoder_layers=args.decoder_layers , encoder_attention_heads=args.encoder_attention_heads , decoder_attention_heads=args.decoder_attention_heads , encoder_ffn_dim=args.encoder_ffn_embed_dim , decoder_ffn_dim=args.decoder_ffn_embed_dim , d_model=args.encoder_embed_dim , encoder_layerdrop=args.encoder_layerdrop , decoder_layerdrop=args.decoder_layerdrop , dropout=args.dropout , attention_dropout=args.attention_dropout , activation_dropout=args.activation_dropout , activation_function="relu" , ) lowerCamelCase__: Tuple =state_dict["decoder.embed_tokens.weight"] lowerCamelCase__: Optional[Any] =MaMaaaForConditionalGeneration(__a ) model.model.load_state_dict(__a , strict=__a ) lowerCamelCase__: Optional[Any] =make_linear_from_emb(model.model.shared ) return model if __name__ == "__main__": __A = argparse.ArgumentParser() # Required parameters parser.add_argument("fairseq_path", type=str, help="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.") __A = parser.parse_args() __A = convert_fairseq_mamaaa_checkpoint_from_disk(args.fairseq_pathß) model.save_pretrained(args.pytorch_dump_folder_path)
59
import unittest from transformers.models.xlm_prophetnet.tokenization_xlm_prophetnet import SPIECE_UNDERLINE, XLMProphetNetTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin __A = get_tests_dir("fixtures/test_sentencepiece.model") @require_sentencepiece class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowercase_ = XLMProphetNetTokenizer lowercase_ = False lowercase_ = True def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Optional[Any]: '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing lowerCamelCase__: Any =XLMProphetNetTokenizer(UpperCAmelCase_ , keep_accents=UpperCAmelCase_) tokenizer.save_pretrained(self.tmpdirname) def SCREAMING_SNAKE_CASE_ (self : str) ->str: '''simple docstring''' lowerCamelCase__: List[Any] ="[PAD]" lowerCamelCase__: Tuple =0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCAmelCase_) , UpperCAmelCase_) self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCAmelCase_) , UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Dict) ->int: '''simple docstring''' lowerCamelCase__: List[Any] =list(self.get_tokenizer().get_vocab().keys()) self.assertEqual(vocab_keys[0] , "[PAD]") self.assertEqual(vocab_keys[1] , "[CLS]") self.assertEqual(vocab_keys[-1] , "j") self.assertEqual(len(UpperCAmelCase_) , 1_012) def SCREAMING_SNAKE_CASE_ (self : Dict) ->Union[str, Any]: '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 1_012) def SCREAMING_SNAKE_CASE_ (self : Any) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Optional[Any] =XLMProphetNetTokenizer(UpperCAmelCase_ , keep_accents=UpperCAmelCase_) lowerCamelCase__: 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]] , ) lowerCamelCase__: Optional[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", "é", ".", ] , ) lowerCamelCase__: Any =tokenizer.convert_tokens_to_ids(UpperCAmelCase_) self.assertListEqual( UpperCAmelCase_ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, -9, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, -9, 4] ] , ) lowerCamelCase__: 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]", ".", ] , ) @cached_property def SCREAMING_SNAKE_CASE_ (self : Any) ->int: '''simple docstring''' return XLMProphetNetTokenizer.from_pretrained("microsoft/xprophetnet-large-wiki100-cased") @slow def SCREAMING_SNAKE_CASE_ (self : List[str]) ->List[str]: '''simple docstring''' lowerCamelCase__: Optional[int] ="Hello World!" lowerCamelCase__: Dict =[35_389, 6_672, 49, 2] self.assertListEqual(UpperCAmelCase_ , self.big_tokenizer.encode(UpperCAmelCase_)) @slow def SCREAMING_SNAKE_CASE_ (self : int) ->Union[str, Any]: '''simple docstring''' lowerCamelCase__: Any ={"input_ids": [[11_073, 82_783, 18, 26, 82_783, 549, 51_540, 248, 17_209, 1_301, 217, 20, 215_186, 1_325, 147, 17_209, 1_301, 217, 20, 56_370, 53, 122_020, 20, 16_477, 27, 87_355, 4_548, 20, 4_728, 78_392, 17, 159_969, 18, 26, 24_491, 629, 15, 538, 22_704, 5_439, 15, 2_788, 24_491, 9_885, 15, 43_534, 605, 15, 814, 18_403, 33_200, 29, 15, 43_534, 24_458, 12_410, 111, 24_966, 83_669, 9_637, 144_068, 26, 850, 22_346, 27, 147, 24_966, 83_669, 83_490, 26, 39_113, 735, 27, 689, 656, 2_800, 1_339, 4_600, 53, 122_020, 115_785, 34, 816, 1_339, 46_887, 18, 147, 53_905, 1_951, 42_238, 41_170, 17_732, 834, 436, 15, 27_523, 98_733, 217, 147, 5_542, 4_981, 930, 17_347, 16, 2], [20_091, 629, 94, 82_786, 58, 490, 20, 1_528, 84, 53_905, 344, 80_592, 110_128, 18_822, 5_267, 1_306, 62, 152_537, 308, 7_997, 401, 124_427, 549, 35_442, 225, 109, 15_055, 25_748, 147, 7_119, 43_712, 34, 767, 135_366, 18, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [592, 63_784, 119_466, 17, 147_808, 88_214, 18, 656, 81, 32, 3_296, 10_280, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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="microsoft/xprophetnet-large-wiki100-cased" , revision="1acad1643ddd54a44df6a1b797ada8373685d90e" , )
59
1
import pytest __A = "__dummy_dataset1__" __A = "\nimport json\nimport os\n\nimport datasets\n\n\nREPO_URL = \"https://huggingface.co/datasets/albertvillanova/tests-raw-jsonl/resolve/main/\"\nURLS = {\"train\": REPO_URL + \"wikiann-bn-train.jsonl\", \"validation\": REPO_URL + \"wikiann-bn-validation.jsonl\"}\n\n\nclass __DummyDataset1__(datasets.GeneratorBasedBuilder):\n\n def _info(self):\n features = datasets.Features(\n {\n \"tokens\": datasets.Sequence(datasets.Value(\"string\")),\n \"ner_tags\": datasets.Sequence(\n datasets.features.ClassLabel(\n names=[\n \"O\",\n \"B-PER\",\n \"I-PER\",\n \"B-ORG\",\n \"I-ORG\",\n \"B-LOC\",\n \"I-LOC\",\n ]\n )\n ),\n \"langs\": datasets.Sequence(datasets.Value(\"string\")),\n \"spans\": datasets.Sequence(datasets.Value(\"string\")),\n }\n )\n return datasets.DatasetInfo(features=features)\n\n def _split_generators(self, dl_manager):\n dl_path = dl_manager.download(URLS)\n return [\n datasets.SplitGenerator(datasets.Split.TRAIN, gen_kwargs={\"filepath\": dl_path[\"train\"]}),\n datasets.SplitGenerator(datasets.Split.VALIDATION, gen_kwargs={\"filepath\": dl_path[\"validation\"]}),\n ]\n\n def _generate_examples(self, filepath):\n with open(filepath, \"r\", encoding=\"utf-8\") as f:\n for i, line in enumerate(f):\n yield i, json.loads(line)\n" @pytest.fixture def lowerCAmelCase_ ( ) -> str: """simple docstring""" return DATASET_LOADING_SCRIPT_NAME @pytest.fixture def lowerCAmelCase_ ( ) -> List[Any]: """simple docstring""" return DATASET_LOADING_SCRIPT_CODE @pytest.fixture def lowerCAmelCase_ ( __a , __a , __a ) -> Tuple: """simple docstring""" lowerCamelCase__: Union[str, Any] =dataset_loading_script_name lowerCamelCase__: List[str] =tmp_path / "datasets" / script_name script_dir.mkdir(parents=__a ) lowerCamelCase__: List[str] =script_dir / F"""{script_name}.py""" with open(__a , "w" ) as f: f.write(__a ) return str(__a )
59
import os import shutil import tempfile import unittest import numpy as np from transformers import AutoTokenizer, BarkProcessor from transformers.testing_utils import require_torch, slow @require_torch class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ (self : List[str]) ->str: '''simple docstring''' lowerCamelCase__: Union[str, Any] ="ylacombe/bark-small" lowerCamelCase__: Tuple =tempfile.mkdtemp() lowerCamelCase__: Tuple ="en_speaker_1" lowerCamelCase__: Optional[int] ="This is a test string" lowerCamelCase__: List[str] ="speaker_embeddings_path.json" lowerCamelCase__: int ="speaker_embeddings" def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , **UpperCAmelCase_ : Any) ->Tuple: '''simple docstring''' return AutoTokenizer.from_pretrained(self.checkpoint , **UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[str]) ->Union[str, Any]: '''simple docstring''' shutil.rmtree(self.tmpdirname) def SCREAMING_SNAKE_CASE_ (self : int) ->Any: '''simple docstring''' lowerCamelCase__: List[Any] =self.get_tokenizer() lowerCamelCase__: List[str] =BarkProcessor(tokenizer=UpperCAmelCase_) processor.save_pretrained(self.tmpdirname) lowerCamelCase__: Dict =BarkProcessor.from_pretrained(self.tmpdirname) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab()) @slow def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Tuple: '''simple docstring''' lowerCamelCase__: Tuple =BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) processor.save_pretrained( self.tmpdirname , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , speaker_embeddings_directory=self.speaker_embeddings_directory , ) lowerCamelCase__: Dict =self.get_tokenizer(bos_token="(BOS)" , eos_token="(EOS)") lowerCamelCase__: Any =BarkProcessor.from_pretrained( self.tmpdirname , self.speaker_embeddings_dict_path , bos_token="(BOS)" , eos_token="(EOS)" , ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab()) def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->int: '''simple docstring''' lowerCamelCase__: Any =BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) lowerCamelCase__: List[str] =35 lowerCamelCase__: Optional[Any] =2 lowerCamelCase__: Optional[Any] =8 lowerCamelCase__: Optional[int] ={ "semantic_prompt": np.ones(UpperCAmelCase_), "coarse_prompt": np.ones((nb_codebooks_coarse, seq_len)), "fine_prompt": np.ones((nb_codebooks_total, seq_len)), } # test providing already loaded voice_preset lowerCamelCase__: Any =processor(text=self.input_string , voice_preset=UpperCAmelCase_) lowerCamelCase__: int =inputs["history_prompt"] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(UpperCAmelCase_ , np.array([])).tolist()) # test loading voice preset from npz file lowerCamelCase__: Union[str, Any] =os.path.join(self.tmpdirname , "file.npz") np.savez(UpperCAmelCase_ , **UpperCAmelCase_) lowerCamelCase__: Tuple =processor(text=self.input_string , voice_preset=UpperCAmelCase_) lowerCamelCase__: Optional[Any] =inputs["history_prompt"] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(UpperCAmelCase_ , np.array([])).tolist()) # test loading voice preset from the hub lowerCamelCase__: Any =processor(text=self.input_string , voice_preset=self.voice_preset) def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Union[str, Any]: '''simple docstring''' lowerCamelCase__: str =self.get_tokenizer() lowerCamelCase__: Dict =BarkProcessor(tokenizer=UpperCAmelCase_) lowerCamelCase__: List[Any] =processor(text=self.input_string) lowerCamelCase__: Optional[int] =tokenizer( self.input_string , padding="max_length" , max_length=256 , add_special_tokens=UpperCAmelCase_ , return_attention_mask=UpperCAmelCase_ , return_token_type_ids=UpperCAmelCase_ , ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key].squeeze().tolist())
59
1
from __future__ import annotations __A = [] def lowerCAmelCase_ ( __a , __a , __a ) -> bool: """simple docstring""" for i in range(len(__a ) ): if board[row][i] == 1: return False for i in range(len(__a ) ): if board[i][column] == 1: return False for i, j in zip(range(__a , -1 , -1 ) , range(__a , -1 , -1 ) ): if board[i][j] == 1: return False for i, j in zip(range(__a , -1 , -1 ) , range(__a , len(__a ) ) ): if board[i][j] == 1: return False return True def lowerCAmelCase_ ( __a , __a ) -> bool: """simple docstring""" if row >= len(__a ): solution.append(__a ) printboard(__a ) print() return True for i in range(len(__a ) ): if is_safe(__a , __a , __a ): lowerCamelCase__: List[str] =1 solve(__a , row + 1 ) lowerCamelCase__: List[str] =0 return False def lowerCAmelCase_ ( __a ) -> None: """simple docstring""" for i in range(len(__a ) ): for j in range(len(__a ) ): if board[i][j] == 1: print("Q" , end=" " ) else: print("." , end=" " ) print() # n=int(input("The no. of queens")) __A = 8 __A = [[0 for i in range(n)] for j in range(n)] solve(board, 0) print("The total no. of solutions are :", len(solution))
59
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = ["image_processor", "tokenizer"] lowercase_ = "CLIPImageProcessor" lowercase_ = ("XLMRobertaTokenizer", "XLMRobertaTokenizerFast") def __init__(self : List[Any] , UpperCAmelCase_ : int=None , UpperCAmelCase_ : List[Any]=None , **UpperCAmelCase_ : List[str]) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Union[str, Any] =None if "feature_extractor" in kwargs: warnings.warn( "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`" " instead." , UpperCAmelCase_ , ) lowerCamelCase__: int =kwargs.pop("feature_extractor") lowerCamelCase__: int =image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("You need to specify an `image_processor`.") if tokenizer is None: raise ValueError("You need to specify a `tokenizer`.") super().__init__(UpperCAmelCase_ , UpperCAmelCase_) def __call__(self : List[Any] , UpperCAmelCase_ : str=None , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : int=None , **UpperCAmelCase_ : Any) ->Union[str, Any]: '''simple docstring''' if text is None and images is None: raise ValueError("You have to specify either text or images. Both cannot be none.") if text is not None: lowerCamelCase__: List[Any] =self.tokenizer(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_) if images is not None: lowerCamelCase__: int =self.image_processor(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_) if text is not None and images is not None: lowerCamelCase__: str =image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**UpperCAmelCase_) , tensor_type=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[str] , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : Optional[Any]) ->Dict: '''simple docstring''' return self.tokenizer.batch_decode(*UpperCAmelCase_ , **UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Optional[int] , *UpperCAmelCase_ : int , **UpperCAmelCase_ : Any) ->Optional[Any]: '''simple docstring''' return self.tokenizer.decode(*UpperCAmelCase_ , **UpperCAmelCase_) @property def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Optional[Any] =self.tokenizer.model_input_names lowerCamelCase__: str =self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
59
1
import argparse import collections import json from pathlib import Path import requests import torch import yaml from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( MobileViTImageProcessor, MobileViTVaConfig, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, ) from transformers.utils import logging logging.set_verbosity_info() __A = logging.get_logger(__name__) def lowerCAmelCase_ ( __a ) -> Tuple: """simple docstring""" print("Loading config file..." ) def flatten_yaml_as_dict(__a , __a="" , __a="." ): lowerCamelCase__: Union[str, Any] =[] for k, v in d.items(): lowerCamelCase__: Dict =parent_key + sep + k if parent_key else k if isinstance(__a , collections.abc.MutableMapping ): items.extend(flatten_yaml_as_dict(__a , __a , sep=__a ).items() ) else: items.append((new_key, v) ) return dict(__a ) lowerCamelCase__: Optional[Any] =argparse.Namespace() with open(__a , "r" ) as yaml_file: try: lowerCamelCase__: List[Any] =yaml.load(__a , Loader=yaml.FullLoader ) lowerCamelCase__: Dict =flatten_yaml_as_dict(__a ) for k, v in flat_cfg.items(): setattr(__a , __a , __a ) except yaml.YAMLError as exc: logger.error("Error while loading config file: {}. Error message: {}".format(__a , str(__a ) ) ) return config def lowerCAmelCase_ ( __a , __a ) -> Union[str, Any]: """simple docstring""" lowerCamelCase__: List[str] =MobileViTVaConfig() lowerCamelCase__: Union[str, Any] =False # dataset if task_name.startswith("imagenet1k_" ): lowerCamelCase__: Dict =1000 if int(task_name.strip().split("_" )[-1] ) == 384: lowerCamelCase__: Tuple =384 else: lowerCamelCase__: str =256 lowerCamelCase__: Optional[int] ="imagenet-1k-id2label.json" elif task_name.startswith("imagenet21k_to_1k_" ): lowerCamelCase__: Optional[int] =21000 if int(task_name.strip().split("_" )[-1] ) == 384: lowerCamelCase__: Dict =384 else: lowerCamelCase__: Any =256 lowerCamelCase__: int ="imagenet-22k-id2label.json" elif task_name.startswith("ade20k_" ): lowerCamelCase__: Optional[int] =151 lowerCamelCase__: Optional[int] =512 lowerCamelCase__: Optional[int] ="ade20k-id2label.json" lowerCamelCase__: Tuple =True elif task_name.startswith("voc_" ): lowerCamelCase__: List[Any] =21 lowerCamelCase__: List[str] =512 lowerCamelCase__: Any ="pascal-voc-id2label.json" lowerCamelCase__: str =True # orig_config lowerCamelCase__: Optional[Any] =load_orig_config_file(__a ) assert getattr(__a , "model.classification.name" , -1 ) == "mobilevit_v2", "Invalid model" lowerCamelCase__: Optional[Any] =getattr(__a , "model.classification.mitv2.width_multiplier" , 1.0 ) assert ( getattr(__a , "model.classification.mitv2.attn_norm_layer" , -1 ) == "layer_norm_2d" ), "Norm layers other than layer_norm_2d is not supported" lowerCamelCase__: Dict =getattr(__a , "model.classification.activation.name" , "swish" ) # config.image_size == getattr(orig_config, 'sampler.bs.crop_size_width', 256) if is_segmentation_model: lowerCamelCase__: Optional[int] =getattr(__a , "model.segmentation.output_stride" , 16 ) if "_deeplabv3" in task_name: lowerCamelCase__: Dict =getattr(__a , "model.segmentation.deeplabv3.aspp_rates" , [12, 24, 36] ) lowerCamelCase__: Optional[int] =getattr(__a , "model.segmentation.deeplabv3.aspp_out_channels" , 512 ) lowerCamelCase__: Dict =getattr(__a , "model.segmentation.deeplabv3.aspp_dropout" , 0.1 ) # id2label lowerCamelCase__: Dict ="huggingface/label-files" lowerCamelCase__: Tuple =json.load(open(hf_hub_download(__a , __a , repo_type="dataset" ) , "r" ) ) lowerCamelCase__: Tuple ={int(__a ): v for k, v in idalabel.items()} lowerCamelCase__: int =idalabel lowerCamelCase__: Optional[int] ={v: k for k, v in idalabel.items()} return config def lowerCAmelCase_ ( __a , __a , __a ) -> List[str]: """simple docstring""" lowerCamelCase__: Optional[Any] =dct.pop(__a ) lowerCamelCase__: Any =val def lowerCAmelCase_ ( __a , __a=False ) -> Optional[Any]: """simple docstring""" if base_model: lowerCamelCase__: List[Any] ="" else: lowerCamelCase__: int ="mobilevitv2." lowerCamelCase__: Optional[Any] =[] for k in state_dict.keys(): if k[:8] == "encoder.": lowerCamelCase__: Optional[Any] =k[8:] else: lowerCamelCase__: List[str] =k if ".block." in k: lowerCamelCase__: List[str] =k_new.replace(".block." , "." ) if ".conv." in k: lowerCamelCase__: Any =k_new.replace(".conv." , ".convolution." ) if ".norm." in k: lowerCamelCase__: List[Any] =k_new.replace(".norm." , ".normalization." ) if "conv_1." in k: lowerCamelCase__: Optional[Any] =k_new.replace("conv_1." , F"""{model_prefix}conv_stem.""" ) for i in [1, 2]: if F"""layer_{i}.""" in k: lowerCamelCase__: Union[str, Any] =k_new.replace(F"""layer_{i}.""" , F"""{model_prefix}encoder.layer.{i-1}.layer.""" ) if ".exp_1x1." in k: lowerCamelCase__: Dict =k_new.replace(".exp_1x1." , ".expand_1x1." ) if ".red_1x1." in k: lowerCamelCase__: List[str] =k_new.replace(".red_1x1." , ".reduce_1x1." ) for i in [3, 4, 5]: if F"""layer_{i}.0.""" in k: lowerCamelCase__: List[Any] =k_new.replace(F"""layer_{i}.0.""" , F"""{model_prefix}encoder.layer.{i-1}.downsampling_layer.""" ) if F"""layer_{i}.1.local_rep.0.""" in k: lowerCamelCase__: Optional[Any] =k_new.replace(F"""layer_{i}.1.local_rep.0.""" , F"""{model_prefix}encoder.layer.{i-1}.conv_kxk.""" ) if F"""layer_{i}.1.local_rep.1.""" in k: lowerCamelCase__: int =k_new.replace(F"""layer_{i}.1.local_rep.1.""" , F"""{model_prefix}encoder.layer.{i-1}.conv_1x1.""" ) for i in [3, 4, 5]: if i == 3: lowerCamelCase__: Optional[Any] =[0, 1] elif i == 4: lowerCamelCase__: Tuple =[0, 1, 2, 3] elif i == 5: lowerCamelCase__: Optional[int] =[0, 1, 2] for j in j_in: if F"""layer_{i}.1.global_rep.{j}.""" in k: lowerCamelCase__: List[str] =k_new.replace( F"""layer_{i}.1.global_rep.{j}.""" , F"""{model_prefix}encoder.layer.{i-1}.transformer.layer.{j}.""" ) if F"""layer_{i}.1.global_rep.{j+1}.""" in k: lowerCamelCase__: Optional[Any] =k_new.replace( F"""layer_{i}.1.global_rep.{j+1}.""" , F"""{model_prefix}encoder.layer.{i-1}.layernorm.""" ) if F"""layer_{i}.1.conv_proj.""" in k: lowerCamelCase__: Any =k_new.replace(F"""layer_{i}.1.conv_proj.""" , F"""{model_prefix}encoder.layer.{i-1}.conv_projection.""" ) if "pre_norm_attn.0." in k: lowerCamelCase__: int =k_new.replace("pre_norm_attn.0." , "layernorm_before." ) if "pre_norm_attn.1." in k: lowerCamelCase__: str =k_new.replace("pre_norm_attn.1." , "attention." ) if "pre_norm_ffn.0." in k: lowerCamelCase__: Tuple =k_new.replace("pre_norm_ffn.0." , "layernorm_after." ) if "pre_norm_ffn.1." in k: lowerCamelCase__: Optional[Any] =k_new.replace("pre_norm_ffn.1." , "ffn.conv1." ) if "pre_norm_ffn.3." in k: lowerCamelCase__: str =k_new.replace("pre_norm_ffn.3." , "ffn.conv2." ) if "classifier.1." in k: lowerCamelCase__: str =k_new.replace("classifier.1." , "classifier." ) if "seg_head." in k: lowerCamelCase__: int =k_new.replace("seg_head." , "segmentation_head." ) if ".aspp_layer." in k: lowerCamelCase__: str =k_new.replace(".aspp_layer." , "." ) if ".aspp_pool." in k: lowerCamelCase__: List[Any] =k_new.replace(".aspp_pool." , "." ) rename_keys.append((k, k_new) ) return rename_keys def lowerCAmelCase_ ( __a ) -> Any: """simple docstring""" lowerCamelCase__: Union[str, Any] =[] for k in state_dict.keys(): if k.startswith("seg_head.aux_head." ): keys_to_ignore.append(__a ) for k in keys_to_ignore: state_dict.pop(__a , __a ) def lowerCAmelCase_ ( ) -> Union[str, Any]: """simple docstring""" lowerCamelCase__: Union[str, Any] ="http://images.cocodataset.org/val2017/000000039769.jpg" # url = "https://cdn.britannica.com/86/141086-050-9D7C75EE/Gulfstream-G450-business-jet-passengers.jpg" lowerCamelCase__: Optional[int] =Image.open(requests.get(__a , stream=__a ).raw ) return im @torch.no_grad() def lowerCAmelCase_ ( __a , __a , __a , __a ) -> int: """simple docstring""" lowerCamelCase__: str =get_mobilevitva_config(__a , __a ) # load original state_dict lowerCamelCase__: str =torch.load(__a , map_location="cpu" ) # load huggingface model if task_name.startswith("ade20k_" ) or task_name.startswith("voc_" ): lowerCamelCase__: Union[str, Any] =MobileViTVaForSemanticSegmentation(__a ).eval() lowerCamelCase__: List[Any] =False else: lowerCamelCase__: List[Any] =MobileViTVaForImageClassification(__a ).eval() lowerCamelCase__: Optional[int] =False # remove and rename some keys of load the original model lowerCamelCase__: Optional[Any] =checkpoint remove_unused_keys(__a ) lowerCamelCase__: List[str] =create_rename_keys(__a , base_model=__a ) for rename_key_src, rename_key_dest in rename_keys: rename_key(__a , __a , __a ) # load modified state_dict model.load_state_dict(__a ) # Check outputs on an image, prepared by MobileViTImageProcessor lowerCamelCase__: Any =MobileViTImageProcessor(crop_size=config.image_size , size=config.image_size + 32 ) lowerCamelCase__: Tuple =image_processor(images=prepare_img() , return_tensors="pt" ) lowerCamelCase__: List[Any] =model(**__a ) # verify classification model if task_name.startswith("imagenet" ): lowerCamelCase__: Union[str, Any] =outputs.logits lowerCamelCase__: List[Any] =logits.argmax(-1 ).item() print("Predicted class:" , model.config.idalabel[predicted_class_idx] ) if task_name.startswith("imagenet1k_256" ) and config.width_multiplier == 1.0: # expected_logits for base variant lowerCamelCase__: Any =torch.tensor([-1.6_336e00, -7.3_204e-02, -5.1_883e-01] ) assert torch.allclose(logits[0, :3] , __a , atol=1e-4 ) Path(__a ).mkdir(exist_ok=__a ) print(F"""Saving model {task_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(__a ) print(F"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(__a ) if __name__ == "__main__": __A = argparse.ArgumentParser() # Required parameters parser.add_argument( "--task", default="imagenet1k_256", type=str, help=( "Name of the task for which the MobileViTV2 model you'd like to convert is trained on . " "\n Classification (ImageNet-1k)\n - MobileViTV2 (256x256) : imagenet1k_256\n - MobileViTV2 (Trained on 256x256 and Finetuned on 384x384) : imagenet1k_384\n - MobileViTV2 (Trained on ImageNet-21k and Finetuned on ImageNet-1k 256x256) :\n imagenet21k_to_1k_256\n - MobileViTV2 (Trained on ImageNet-21k, Finetuned on ImageNet-1k 256x256, and Finetuned on\n ImageNet-1k 384x384) : imagenet21k_to_1k_384\n Segmentation\n - ADE20K Dataset : ade20k_deeplabv3\n - Pascal VOC 2012 Dataset: voc_deeplabv3\n " ), choices=[ "imagenet1k_256", "imagenet1k_384", "imagenet21k_to_1k_256", "imagenet21k_to_1k_384", "ade20k_deeplabv3", "voc_deeplabv3", ], ) parser.add_argument( "--orig_checkpoint_path", required=True, type=str, help="Path to the original state dict (.pt file)." ) parser.add_argument("--orig_config_path", required=True, type=str, help="Path to the original config file.") parser.add_argument( "--pytorch_dump_folder_path", required=True, type=str, help="Path to the output PyTorch model directory." ) __A = parser.parse_args() convert_mobilevitva_checkpoint( args.task, args.orig_checkpoint_path, args.orig_config_path, args.pytorch_dump_folder_path )
59
from datetime import datetime import matplotlib.pyplot as plt import torch def lowerCAmelCase_ ( __a ) -> Any: """simple docstring""" for param in module.parameters(): lowerCamelCase__: Tuple =False def lowerCAmelCase_ ( ) -> Optional[int]: """simple docstring""" lowerCamelCase__: List[str] ="cuda" if torch.cuda.is_available() else "cpu" if torch.backends.mps.is_available() and torch.backends.mps.is_built(): lowerCamelCase__: str ="mps" if device == "mps": print( "WARNING: MPS currently doesn't seem to work, and messes up backpropagation without any visible torch" " errors. I recommend using CUDA on a colab notebook or CPU instead if you're facing inexplicable issues" " with generations." ) return device def lowerCAmelCase_ ( __a ) -> List[str]: """simple docstring""" lowerCamelCase__: Union[str, Any] =plt.imshow(__a ) fig.axes.get_xaxis().set_visible(__a ) fig.axes.get_yaxis().set_visible(__a ) plt.show() def lowerCAmelCase_ ( ) -> Optional[Any]: """simple docstring""" lowerCamelCase__: List[str] =datetime.now() lowerCamelCase__: str =current_time.strftime("%H:%M:%S" ) return timestamp
59
1
import argparse import os import pickle import sys import torch from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils from transformers.models.transfo_xl.tokenization_transfo_xl import CORPUS_NAME, VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() # We do this to be able to load python 2 datasets pickles # See e.g. https://stackoverflow.com/questions/2121874/python-pickling-after-changing-a-modules-directory/2121918#2121918 __A = data_utils.TransfoXLTokenizer __A = data_utils.TransfoXLCorpus __A = data_utils __A = data_utils def lowerCAmelCase_ ( __a , __a , __a , __a ) -> List[str]: """simple docstring""" if transfo_xl_dataset_file: # Convert a pre-processed corpus (see original TensorFlow repo) with open(__a , "rb" ) as fp: lowerCamelCase__: Optional[Any] =pickle.load(__a , encoding="latin1" ) # Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term) lowerCamelCase__: Union[str, Any] =pytorch_dump_folder_path + "/" + VOCAB_FILES_NAMES["pretrained_vocab_file"] print(F"""Save vocabulary to {pytorch_vocab_dump_path}""" ) lowerCamelCase__: Any =corpus.vocab.__dict__ torch.save(__a , __a ) lowerCamelCase__: Dict =corpus.__dict__ corpus_dict_no_vocab.pop("vocab" , __a ) lowerCamelCase__: List[str] =pytorch_dump_folder_path + "/" + CORPUS_NAME print(F"""Save dataset to {pytorch_dataset_dump_path}""" ) torch.save(__a , __a ) if tf_checkpoint_path: # Convert a pre-trained TensorFlow model lowerCamelCase__: Optional[Any] =os.path.abspath(__a ) lowerCamelCase__: Dict =os.path.abspath(__a ) print(F"""Converting Transformer XL checkpoint from {tf_path} with config at {config_path}.""" ) # Initialise PyTorch model if transfo_xl_config_file == "": lowerCamelCase__: int =TransfoXLConfig() else: lowerCamelCase__: Any =TransfoXLConfig.from_json_file(__a ) print(F"""Building PyTorch model from configuration: {config}""" ) lowerCamelCase__: List[Any] =TransfoXLLMHeadModel(__a ) lowerCamelCase__: List[str] =load_tf_weights_in_transfo_xl(__a , __a , __a ) # Save pytorch-model lowerCamelCase__: List[str] =os.path.join(__a , __a ) lowerCamelCase__: Tuple =os.path.join(__a , __a ) print(F"""Save PyTorch model to {os.path.abspath(__a )}""" ) torch.save(model.state_dict() , __a ) print(F"""Save configuration file to {os.path.abspath(__a )}""" ) with open(__a , "w" , encoding="utf-8" ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": __A = argparse.ArgumentParser() parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the folder to store the PyTorch model or dataset/vocab.", ) parser.add_argument( "--tf_checkpoint_path", default="", type=str, help="An optional path to a TensorFlow checkpoint path to be converted.", ) parser.add_argument( "--transfo_xl_config_file", default="", type=str, help=( "An optional config json file corresponding to the pre-trained BERT model. \n" "This specifies the model architecture." ), ) parser.add_argument( "--transfo_xl_dataset_file", default="", type=str, help="An optional dataset file to be converted in a vocabulary.", ) __A = parser.parse_args() convert_transfo_xl_checkpoint_to_pytorch( args.tf_checkpoint_path, args.transfo_xl_config_file, args.pytorch_dump_folder_path, args.transfo_xl_dataset_file, )
59
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __A = { "configuration_pix2struct": [ "PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP", "Pix2StructConfig", "Pix2StructTextConfig", "Pix2StructVisionConfig", ], "processing_pix2struct": ["Pix2StructProcessor"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ["Pix2StructImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ "PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST", "Pix2StructPreTrainedModel", "Pix2StructForConditionalGeneration", "Pix2StructVisionModel", "Pix2StructTextModel", ] if TYPE_CHECKING: from .configuration_pixastruct import ( PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP, PixaStructConfig, PixaStructTextConfig, PixaStructVisionConfig, ) from .processing_pixastruct import PixaStructProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_pixastruct import PixaStructImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_pixastruct import ( PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST, PixaStructForConditionalGeneration, PixaStructPreTrainedModel, PixaStructTextModel, PixaStructVisionModel, ) else: import sys __A = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
59
1
import unittest from transformers import SqueezeBertConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device 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 ( SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, SqueezeBertModel, ) class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__(self : Any , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : List[Any]=13 , UpperCAmelCase_ : Any=7 , UpperCAmelCase_ : str=True , UpperCAmelCase_ : List[str]=True , UpperCAmelCase_ : Union[str, Any]=False , UpperCAmelCase_ : Dict=True , UpperCAmelCase_ : Union[str, Any]=99 , UpperCAmelCase_ : Union[str, Any]=32 , UpperCAmelCase_ : Any=5 , UpperCAmelCase_ : Optional[Any]=4 , UpperCAmelCase_ : int=64 , UpperCAmelCase_ : Optional[Any]="gelu" , UpperCAmelCase_ : Union[str, Any]=0.1 , UpperCAmelCase_ : Union[str, Any]=0.1 , UpperCAmelCase_ : Any=512 , UpperCAmelCase_ : Optional[int]=16 , UpperCAmelCase_ : Tuple=2 , UpperCAmelCase_ : Union[str, Any]=0.02 , UpperCAmelCase_ : Dict=3 , UpperCAmelCase_ : Dict=4 , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : Dict=2 , UpperCAmelCase_ : Tuple=2 , UpperCAmelCase_ : Union[str, Any]=2 , UpperCAmelCase_ : Dict=2 , UpperCAmelCase_ : Dict=4 , UpperCAmelCase_ : Tuple=1 , ) ->Any: '''simple docstring''' lowerCamelCase__: Optional[Any] =parent lowerCamelCase__: Optional[int] =batch_size lowerCamelCase__: Dict =seq_length lowerCamelCase__: Union[str, Any] =is_training lowerCamelCase__: int =use_input_mask lowerCamelCase__: int =use_token_type_ids lowerCamelCase__: Dict =use_labels lowerCamelCase__: List[Any] =vocab_size lowerCamelCase__: Tuple =hidden_size lowerCamelCase__: List[Any] =num_hidden_layers lowerCamelCase__: str =num_attention_heads lowerCamelCase__: List[Any] =intermediate_size lowerCamelCase__: Optional[int] =hidden_act lowerCamelCase__: List[Any] =hidden_dropout_prob lowerCamelCase__: Optional[int] =attention_probs_dropout_prob lowerCamelCase__: List[Any] =max_position_embeddings lowerCamelCase__: List[str] =type_vocab_size lowerCamelCase__: Dict =type_sequence_label_size lowerCamelCase__: int =initializer_range lowerCamelCase__: Any =num_labels lowerCamelCase__: List[Any] =num_choices lowerCamelCase__: Optional[Any] =scope lowerCamelCase__: str =q_groups lowerCamelCase__: Optional[int] =k_groups lowerCamelCase__: List[Any] =v_groups lowerCamelCase__: Tuple =post_attention_groups lowerCamelCase__: Tuple =intermediate_groups lowerCamelCase__: str =output_groups def SCREAMING_SNAKE_CASE_ (self : int) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Optional[Any] =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) lowerCamelCase__: str =None if self.use_input_mask: lowerCamelCase__: Optional[int] =random_attention_mask([self.batch_size, self.seq_length]) lowerCamelCase__: int =None lowerCamelCase__: Optional[int] =None lowerCamelCase__: Optional[int] =None if self.use_labels: lowerCamelCase__: Optional[int] =ids_tensor([self.batch_size] , self.type_sequence_label_size) lowerCamelCase__: Optional[int] =ids_tensor([self.batch_size, self.seq_length] , self.num_labels) lowerCamelCase__: Any =ids_tensor([self.batch_size] , self.num_choices) lowerCamelCase__: List[str] =self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Dict: '''simple docstring''' return SqueezeBertConfig( embedding_size=self.hidden_size , 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 , attention_probs_dropout_prob=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , q_groups=self.q_groups , k_groups=self.k_groups , v_groups=self.v_groups , post_attention_groups=self.post_attention_groups , intermediate_groups=self.intermediate_groups , output_groups=self.output_groups , ) def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : List[str]) ->str: '''simple docstring''' lowerCamelCase__: Dict =SqueezeBertModel(config=UpperCAmelCase_) model.to(UpperCAmelCase_) model.eval() lowerCamelCase__: Optional[Any] =model(UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: Optional[Any] =model(UpperCAmelCase_) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def SCREAMING_SNAKE_CASE_ (self : List[Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : str) ->Dict: '''simple docstring''' lowerCamelCase__: Optional[int] =SqueezeBertForMaskedLM(config=UpperCAmelCase_) model.to(UpperCAmelCase_) model.eval() lowerCamelCase__: Union[str, Any] =model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , labels=UpperCAmelCase_) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size)) def SCREAMING_SNAKE_CASE_ (self : str , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : List[str]) ->Tuple: '''simple docstring''' lowerCamelCase__: Tuple =SqueezeBertForQuestionAnswering(config=UpperCAmelCase_) model.to(UpperCAmelCase_) model.eval() lowerCamelCase__: Tuple =model( UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , start_positions=UpperCAmelCase_ , end_positions=UpperCAmelCase_) 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 : str , UpperCAmelCase_ : Any , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : List[str]) ->str: '''simple docstring''' lowerCamelCase__: Optional[int] =self.num_labels lowerCamelCase__: Any =SqueezeBertForSequenceClassification(UpperCAmelCase_) model.to(UpperCAmelCase_) model.eval() lowerCamelCase__: List[str] =model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , labels=UpperCAmelCase_) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : int , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Any , UpperCAmelCase_ : int , UpperCAmelCase_ : Dict) ->Any: '''simple docstring''' lowerCamelCase__: Optional[Any] =self.num_labels lowerCamelCase__: List[Any] =SqueezeBertForTokenClassification(config=UpperCAmelCase_) model.to(UpperCAmelCase_) model.eval() lowerCamelCase__: Any =model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , labels=UpperCAmelCase_) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels)) def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : str , UpperCAmelCase_ : Dict , UpperCAmelCase_ : str , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : int) ->Tuple: '''simple docstring''' lowerCamelCase__: List[Any] =self.num_choices lowerCamelCase__: List[str] =SqueezeBertForMultipleChoice(config=UpperCAmelCase_) model.to(UpperCAmelCase_) model.eval() lowerCamelCase__: Optional[int] =input_ids.unsqueeze(1).expand(-1 , self.num_choices , -1).contiguous() lowerCamelCase__: int =input_mask.unsqueeze(1).expand(-1 , self.num_choices , -1).contiguous() lowerCamelCase__: List[str] =model( UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , labels=UpperCAmelCase_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices)) def SCREAMING_SNAKE_CASE_ (self : int) ->Tuple: '''simple docstring''' lowerCamelCase__: Dict =self.prepare_config_and_inputs() ((lowerCamelCase__) , (lowerCamelCase__) , (lowerCamelCase__) , (lowerCamelCase__) , (lowerCamelCase__) , (lowerCamelCase__)): List[str] =config_and_inputs lowerCamelCase__: str ={"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowercase_ = ( ( SqueezeBertModel, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, ) if is_torch_available() else None ) lowercase_ = ( { "feature-extraction": SqueezeBertModel, "fill-mask": SqueezeBertForMaskedLM, "question-answering": SqueezeBertForQuestionAnswering, "text-classification": SqueezeBertForSequenceClassification, "token-classification": SqueezeBertForTokenClassification, "zero-shot": SqueezeBertForSequenceClassification, } if is_torch_available() else {} ) lowercase_ = False lowercase_ = True lowercase_ = False def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Dict: '''simple docstring''' lowerCamelCase__: int =SqueezeBertModelTester(self) lowerCamelCase__: List[str] =ConfigTester(self , config_class=UpperCAmelCase_ , dim=37) def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->List[Any]: '''simple docstring''' self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE_ (self : Any) ->Optional[Any]: '''simple docstring''' lowerCamelCase__: int =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_model(*UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->str: '''simple docstring''' lowerCamelCase__: Tuple =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_masked_lm(*UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Any) ->Any: '''simple docstring''' lowerCamelCase__: List[Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_question_answering(*UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Optional[Any]: '''simple docstring''' lowerCamelCase__: List[str] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_sequence_classification(*UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Union[str, Any]) ->List[Any]: '''simple docstring''' lowerCamelCase__: List[str] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_token_classification(*UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->str: '''simple docstring''' lowerCamelCase__: str =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_multiple_choice(*UpperCAmelCase_) @slow def SCREAMING_SNAKE_CASE_ (self : Tuple) ->List[Any]: '''simple docstring''' for model_name in SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCamelCase__: List[Any] =SqueezeBertModel.from_pretrained(UpperCAmelCase_) self.assertIsNotNone(UpperCAmelCase_) @require_sentencepiece @require_tokenizers @require_torch class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @slow def SCREAMING_SNAKE_CASE_ (self : int) ->List[str]: '''simple docstring''' lowerCamelCase__: Optional[Any] =SqueezeBertForSequenceClassification.from_pretrained("squeezebert/squeezebert-mnli") lowerCamelCase__: Optional[Any] =torch.tensor([[1, 29_414, 232, 328, 740, 1_140, 12_695, 69, 13, 1_588, 2]]) lowerCamelCase__: List[str] =model(UpperCAmelCase_)[0] lowerCamelCase__: List[Any] =torch.Size((1, 3)) self.assertEqual(output.shape , UpperCAmelCase_) lowerCamelCase__: Optional[Any] =torch.tensor([[0.6401, -0.0349, -0.6041]]) self.assertTrue(torch.allclose(UpperCAmelCase_ , UpperCAmelCase_ , atol=1E-4))
59
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_distilbert import DistilBertTokenizer __A = logging.get_logger(__name__) __A = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} __A = { "vocab_file": { "distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/vocab.txt", "distilbert-base-uncased-distilled-squad": ( "https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/vocab.txt" ), "distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/vocab.txt", "distilbert-base-cased-distilled-squad": ( "https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/vocab.txt" ), "distilbert-base-german-cased": "https://huggingface.co/distilbert-base-german-cased/resolve/main/vocab.txt", "distilbert-base-multilingual-cased": ( "https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/vocab.txt" ), }, "tokenizer_file": { "distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/tokenizer.json", "distilbert-base-uncased-distilled-squad": ( "https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/tokenizer.json" ), "distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/tokenizer.json", "distilbert-base-cased-distilled-squad": ( "https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/tokenizer.json" ), "distilbert-base-german-cased": ( "https://huggingface.co/distilbert-base-german-cased/resolve/main/tokenizer.json" ), "distilbert-base-multilingual-cased": ( "https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/tokenizer.json" ), }, } __A = { "distilbert-base-uncased": 512, "distilbert-base-uncased-distilled-squad": 512, "distilbert-base-cased": 512, "distilbert-base-cased-distilled-squad": 512, "distilbert-base-german-cased": 512, "distilbert-base-multilingual-cased": 512, } __A = { "distilbert-base-uncased": {"do_lower_case": True}, "distilbert-base-uncased-distilled-squad": {"do_lower_case": True}, "distilbert-base-cased": {"do_lower_case": False}, "distilbert-base-cased-distilled-squad": {"do_lower_case": False}, "distilbert-base-german-cased": {"do_lower_case": False}, "distilbert-base-multilingual-cased": {"do_lower_case": False}, } class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = VOCAB_FILES_NAMES lowercase_ = PRETRAINED_VOCAB_FILES_MAP lowercase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase_ = PRETRAINED_INIT_CONFIGURATION lowercase_ = ["input_ids", "attention_mask"] lowercase_ = DistilBertTokenizer def __init__(self : Tuple , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : int=None , UpperCAmelCase_ : Any=True , UpperCAmelCase_ : List[Any]="[UNK]" , UpperCAmelCase_ : Dict="[SEP]" , UpperCAmelCase_ : Dict="[PAD]" , UpperCAmelCase_ : Optional[int]="[CLS]" , UpperCAmelCase_ : str="[MASK]" , UpperCAmelCase_ : Any=True , UpperCAmelCase_ : List[str]=None , **UpperCAmelCase_ : List[str] , ) ->str: '''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_ , ) lowerCamelCase__: Union[str, Any] =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 ): lowerCamelCase__: List[str] =getattr(UpperCAmelCase_ , normalizer_state.pop("type")) lowerCamelCase__: Optional[int] =do_lower_case lowerCamelCase__: int =strip_accents lowerCamelCase__: Any =tokenize_chinese_chars lowerCamelCase__: Any =normalizer_class(**UpperCAmelCase_) lowerCamelCase__: str =do_lower_case def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : int , UpperCAmelCase_ : Union[str, Any]=None) ->Dict: '''simple docstring''' lowerCamelCase__: str =[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 SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None) ->List[int]: '''simple docstring''' lowerCamelCase__: str =[self.sep_token_id] lowerCamelCase__: str =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep) * [0] return len(cls + token_ids_a + sep) * [0] + len(token_ids_a + sep) * [1] def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] = None) ->Tuple[str]: '''simple docstring''' lowerCamelCase__: str =self._tokenizer.model.save(UpperCAmelCase_ , name=UpperCAmelCase_) return tuple(UpperCAmelCase_)
59
1
from ...configuration_utils import PretrainedConfig from ...utils import logging __A = logging.get_logger(__name__) __A = { "weiweishi/roc-bert-base-zh": "https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json", } class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = "roc_bert" def __init__(self : Dict , UpperCAmelCase_ : Optional[int]=30_522 , UpperCAmelCase_ : Any=768 , UpperCAmelCase_ : Any=12 , UpperCAmelCase_ : Optional[Any]=12 , UpperCAmelCase_ : Union[str, Any]=3_072 , UpperCAmelCase_ : List[Any]="gelu" , UpperCAmelCase_ : str=0.1 , UpperCAmelCase_ : Dict=0.1 , UpperCAmelCase_ : str=512 , UpperCAmelCase_ : Any=2 , UpperCAmelCase_ : Optional[int]=0.02 , UpperCAmelCase_ : Tuple=1E-1_2 , UpperCAmelCase_ : Optional[Any]=True , UpperCAmelCase_ : Any=0 , UpperCAmelCase_ : int="absolute" , UpperCAmelCase_ : Union[str, Any]=None , UpperCAmelCase_ : List[Any]=True , UpperCAmelCase_ : List[Any]=True , UpperCAmelCase_ : List[Any]=768 , UpperCAmelCase_ : int=910 , UpperCAmelCase_ : Union[str, Any]=512 , UpperCAmelCase_ : Any=24_858 , UpperCAmelCase_ : List[str]=True , **UpperCAmelCase_ : str , ) ->int: '''simple docstring''' lowerCamelCase__: List[Any] =vocab_size lowerCamelCase__: Any =max_position_embeddings lowerCamelCase__: str =hidden_size lowerCamelCase__: int =num_hidden_layers lowerCamelCase__: Optional[int] =num_attention_heads lowerCamelCase__: Optional[Any] =intermediate_size lowerCamelCase__: int =hidden_act lowerCamelCase__: Optional[Any] =hidden_dropout_prob lowerCamelCase__: Optional[Any] =attention_probs_dropout_prob lowerCamelCase__: List[Any] =initializer_range lowerCamelCase__: Tuple =type_vocab_size lowerCamelCase__: Dict =layer_norm_eps lowerCamelCase__: Tuple =use_cache lowerCamelCase__: int =enable_pronunciation lowerCamelCase__: str =enable_shape lowerCamelCase__: List[Any] =pronunciation_embed_dim lowerCamelCase__: int =pronunciation_vocab_size lowerCamelCase__: Union[str, Any] =shape_embed_dim lowerCamelCase__: Union[str, Any] =shape_vocab_size lowerCamelCase__: int =concat_input lowerCamelCase__: str =position_embedding_type lowerCamelCase__: str =classifier_dropout super().__init__(pad_token_id=UpperCAmelCase_ , **UpperCAmelCase_)
59
import operator as op def lowerCAmelCase_ ( __a ) -> Tuple: """simple docstring""" lowerCamelCase__: Optional[Any] =[] lowerCamelCase__: Tuple =lambda __a , __a : int(x / y ) # noqa: E731 integer division operation lowerCamelCase__: Tuple ={ "^": op.pow, "*": op.mul, "/": div, "+": op.add, "-": op.sub, } # operators & their respective operation # print table header print("Symbol".center(8 ) , "Action".center(12 ) , "Stack" , sep=" | " ) print("-" * (30 + len(__a )) ) for x in post_fix: if x.isdigit(): # if x in digit stack.append(__a ) # append x to stack # output in tabular format print(x.rjust(8 ) , ("push(" + x + ")").ljust(12 ) , ",".join(__a ) , sep=" | " ) else: lowerCamelCase__: List[Any] =stack.pop() # pop stack # output in tabular format print("".rjust(8 ) , ("pop(" + b + ")").ljust(12 ) , ",".join(__a ) , sep=" | " ) lowerCamelCase__: Optional[Any] =stack.pop() # pop stack # output in tabular format print("".rjust(8 ) , ("pop(" + a + ")").ljust(12 ) , ",".join(__a ) , sep=" | " ) stack.append( str(opr[x](int(__a ) , int(__a ) ) ) ) # evaluate the 2 values popped from stack & push result to stack # output in tabular format print( x.rjust(8 ) , ("push(" + a + x + b + ")").ljust(12 ) , ",".join(__a ) , sep=" | " , ) return int(stack[0] ) if __name__ == "__main__": __A = input("\n\nEnter a Postfix Equation (space separated) = ").split(" ") print("\n\tResult = ", solve(Postfix))
59
1
from __future__ import annotations from typing import Dict from ...configuration_utils import PretrainedConfig __A = { "susnato/ernie-m-base_pytorch": "https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/config.json", "susnato/ernie-m-large_pytorch": "https://huggingface.co/susnato/ernie-m-large_pytorch/blob/main/config.json", } class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = "ernie_m" lowercase_ = {"dropout": "classifier_dropout", "num_classes": "num_labels"} def __init__(self : Any , UpperCAmelCase_ : int = 250_002 , UpperCAmelCase_ : int = 768 , UpperCAmelCase_ : int = 12 , UpperCAmelCase_ : int = 12 , UpperCAmelCase_ : int = 3_072 , UpperCAmelCase_ : str = "gelu" , UpperCAmelCase_ : float = 0.1 , UpperCAmelCase_ : float = 0.1 , UpperCAmelCase_ : int = 514 , UpperCAmelCase_ : float = 0.02 , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : float = 1E-0_5 , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : Optional[int]=False , UpperCAmelCase_ : List[Any]=0.0 , **UpperCAmelCase_ : str , ) ->List[str]: '''simple docstring''' super().__init__(pad_token_id=UpperCAmelCase_ , **UpperCAmelCase_) lowerCamelCase__: List[Any] =vocab_size lowerCamelCase__: Tuple =hidden_size lowerCamelCase__: Optional[Any] =num_hidden_layers lowerCamelCase__: Optional[Any] =num_attention_heads lowerCamelCase__: List[str] =intermediate_size lowerCamelCase__: Optional[int] =hidden_act lowerCamelCase__: Optional[Any] =hidden_dropout_prob lowerCamelCase__: Union[str, Any] =attention_probs_dropout_prob lowerCamelCase__: Optional[Any] =max_position_embeddings lowerCamelCase__: Union[str, Any] =initializer_range lowerCamelCase__: Dict =layer_norm_eps lowerCamelCase__: List[str] =classifier_dropout lowerCamelCase__: Union[str, Any] =is_decoder lowerCamelCase__: str =act_dropout
59
from collections import defaultdict from typing import Optional from ..image_utils import load_image from ..utils import ( add_end_docstrings, is_torch_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_MASK_GENERATION_MAPPING __A = logging.get_logger(__name__) @add_end_docstrings(__SCREAMING_SNAKE_CASE ) class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__(self : List[Any] , **UpperCAmelCase_ : Any) ->Any: '''simple docstring''' super().__init__(**UpperCAmelCase_) requires_backends(self , "vision") requires_backends(self , "torch") if self.framework != "pt": raise ValueError(F"""The {self.__class__} is only available in PyTorch.""") self.check_model_type(UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Tuple , **UpperCAmelCase_ : List[Any]) ->Tuple: '''simple docstring''' lowerCamelCase__: Optional[int] ={} lowerCamelCase__: Tuple ={} lowerCamelCase__: str ={} # preprocess args if "points_per_batch" in kwargs: lowerCamelCase__: Optional[Any] =kwargs["points_per_batch"] if "points_per_crop" in kwargs: lowerCamelCase__: int =kwargs["points_per_crop"] if "crops_n_layers" in kwargs: lowerCamelCase__: Any =kwargs["crops_n_layers"] if "crop_overlap_ratio" in kwargs: lowerCamelCase__: Tuple =kwargs["crop_overlap_ratio"] if "crop_n_points_downscale_factor" in kwargs: lowerCamelCase__: List[Any] =kwargs["crop_n_points_downscale_factor"] # postprocess args if "pred_iou_thresh" in kwargs: lowerCamelCase__: List[str] =kwargs["pred_iou_thresh"] if "stability_score_offset" in kwargs: lowerCamelCase__: int =kwargs["stability_score_offset"] if "mask_threshold" in kwargs: lowerCamelCase__: Optional[int] =kwargs["mask_threshold"] if "stability_score_thresh" in kwargs: lowerCamelCase__: str =kwargs["stability_score_thresh"] if "crops_nms_thresh" in kwargs: lowerCamelCase__: Any =kwargs["crops_nms_thresh"] if "output_rle_mask" in kwargs: lowerCamelCase__: List[Any] =kwargs["output_rle_mask"] if "output_bboxes_mask" in kwargs: lowerCamelCase__: List[str] =kwargs["output_bboxes_mask"] return preprocess_kwargs, forward_params, postprocess_kwargs def __call__(self : int , UpperCAmelCase_ : Dict , *UpperCAmelCase_ : Dict , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : Optional[Any]=None , **UpperCAmelCase_ : Dict) ->Optional[Any]: '''simple docstring''' return super().__call__(UpperCAmelCase_ , *UpperCAmelCase_ , num_workers=UpperCAmelCase_ , batch_size=UpperCAmelCase_ , **UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[Any]=64 , UpperCAmelCase_ : int = 0 , UpperCAmelCase_ : float = 512 / 1_500 , UpperCAmelCase_ : Optional[int] = 32 , UpperCAmelCase_ : Optional[int] = 1 , ) ->Dict: '''simple docstring''' lowerCamelCase__: Dict =load_image(UpperCAmelCase_) lowerCamelCase__: List[str] =self.image_processor.size["longest_edge"] lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Union[str, Any] =self.image_processor.generate_crop_boxes( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: str =self.image_processor(images=UpperCAmelCase_ , return_tensors="pt") with self.device_placement(): if self.framework == "pt": lowerCamelCase__: str =self.get_inference_context() with inference_context(): lowerCamelCase__: Union[str, Any] =self._ensure_tensor_on_device(UpperCAmelCase_ , device=self.device) lowerCamelCase__: Optional[Any] =self.model.get_image_embeddings(model_inputs.pop("pixel_values")) lowerCamelCase__: str =image_embeddings lowerCamelCase__: int =grid_points.shape[1] lowerCamelCase__: int =points_per_batch if points_per_batch is not None else n_points if points_per_batch <= 0: raise ValueError( "Cannot have points_per_batch<=0. Must be >=1 to returned batched outputs. " "To return all points at once, set points_per_batch to None") for i in range(0 , UpperCAmelCase_ , UpperCAmelCase_): lowerCamelCase__: int =grid_points[:, i : i + points_per_batch, :, :] lowerCamelCase__: Optional[Any] =input_labels[:, i : i + points_per_batch] lowerCamelCase__: Dict =i == n_points - points_per_batch yield { "input_points": batched_points, "input_labels": labels, "input_boxes": crop_boxes, "is_last": is_last, **model_inputs, } def SCREAMING_SNAKE_CASE_ (self : str , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Dict=0.88 , UpperCAmelCase_ : Optional[Any]=0.95 , UpperCAmelCase_ : Tuple=0 , UpperCAmelCase_ : Any=1 , ) ->Optional[Any]: '''simple docstring''' lowerCamelCase__: Any =model_inputs.pop("input_boxes") lowerCamelCase__: Dict =model_inputs.pop("is_last") lowerCamelCase__: int =model_inputs.pop("original_sizes").tolist() lowerCamelCase__: Union[str, Any] =model_inputs.pop("reshaped_input_sizes").tolist() lowerCamelCase__: Union[str, Any] =self.model(**UpperCAmelCase_) # post processing happens here in order to avoid CPU GPU copies of ALL the masks lowerCamelCase__: Optional[int] =model_outputs["pred_masks"] lowerCamelCase__: Union[str, Any] =self.image_processor.post_process_masks( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , binarize=UpperCAmelCase_) lowerCamelCase__: Optional[Any] =model_outputs["iou_scores"] lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Any =self.image_processor.filter_masks( masks[0] , iou_scores[0] , original_sizes[0] , input_boxes[0] , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , ) return { "masks": masks, "is_last": is_last, "boxes": boxes, "iou_scores": iou_scores, } def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : Any , UpperCAmelCase_ : Optional[int]=False , UpperCAmelCase_ : List[str]=False , UpperCAmelCase_ : Optional[int]=0.7 , ) ->Tuple: '''simple docstring''' lowerCamelCase__: Any =[] lowerCamelCase__: Optional[int] =[] lowerCamelCase__: List[str] =[] for model_output in model_outputs: all_scores.append(model_output.pop("iou_scores")) all_masks.extend(model_output.pop("masks")) all_boxes.append(model_output.pop("boxes")) lowerCamelCase__: str =torch.cat(UpperCAmelCase_) lowerCamelCase__: List[str] =torch.cat(UpperCAmelCase_) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Dict =self.image_processor.post_process_for_mask_generation( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: List[str] =defaultdict(UpperCAmelCase_) for output in model_outputs: for k, v in output.items(): extra[k].append(UpperCAmelCase_) lowerCamelCase__: Any ={} if output_rle_mask: lowerCamelCase__: Union[str, Any] =rle_mask if output_bboxes_mask: lowerCamelCase__: int =bounding_boxes return {"masks": output_masks, "scores": iou_scores, **optional, **extra}
59
1
def lowerCAmelCase_ ( __a ) -> list: """simple docstring""" for i in range(len(__a ) - 1 , 0 , -1 ): lowerCamelCase__: List[Any] =False for j in range(__a , 0 , -1 ): if unsorted[j] < unsorted[j - 1]: lowerCamelCase__ , lowerCamelCase__: Any =unsorted[j - 1], unsorted[j] lowerCamelCase__: Tuple =True for j in range(__a ): if unsorted[j] > unsorted[j + 1]: lowerCamelCase__ , lowerCamelCase__: Optional[int] =unsorted[j + 1], unsorted[j] lowerCamelCase__: Optional[int] =True if not swapped: break return unsorted if __name__ == "__main__": import doctest doctest.testmod() __A = input("Enter numbers separated by a comma:\n").strip() __A = [int(item) for item in user_input.split(",")] print(f'{cocktail_shaker_sort(unsorted) = }')
59
from transformers import BertTokenizerFast from .custom_tokenization import CustomTokenizer class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = CustomTokenizer pass
59
1
import inspect import unittest from transformers import MobileViTConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTModel from transformers.models.mobilevit.modeling_mobilevit import MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import MobileViTImageProcessor class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Union[str, Any]: '''simple docstring''' lowerCamelCase__: List[str] =self.config_class(**self.inputs_dict) self.parent.assertTrue(hasattr(UpperCAmelCase_ , "hidden_sizes")) self.parent.assertTrue(hasattr(UpperCAmelCase_ , "neck_hidden_sizes")) self.parent.assertTrue(hasattr(UpperCAmelCase_ , "num_attention_heads")) class _SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__(self : Dict , UpperCAmelCase_ : Any , UpperCAmelCase_ : List[Any]=13 , UpperCAmelCase_ : Optional[int]=32 , UpperCAmelCase_ : Optional[int]=2 , UpperCAmelCase_ : Any=3 , UpperCAmelCase_ : int=640 , UpperCAmelCase_ : str=4 , UpperCAmelCase_ : Dict="silu" , UpperCAmelCase_ : Dict=3 , UpperCAmelCase_ : Union[str, Any]=32 , UpperCAmelCase_ : int=0.1 , UpperCAmelCase_ : Tuple=0.1 , UpperCAmelCase_ : Any=0.1 , UpperCAmelCase_ : str=0.02 , UpperCAmelCase_ : List[str]=True , UpperCAmelCase_ : List[str]=True , UpperCAmelCase_ : Optional[Any]=10 , UpperCAmelCase_ : Union[str, Any]=None , ) ->Dict: '''simple docstring''' lowerCamelCase__: Optional[int] =parent lowerCamelCase__: int =batch_size lowerCamelCase__: int =image_size lowerCamelCase__: str =patch_size lowerCamelCase__: Optional[int] =num_channels lowerCamelCase__: Dict =last_hidden_size lowerCamelCase__: Dict =num_attention_heads lowerCamelCase__: Any =hidden_act lowerCamelCase__: Union[str, Any] =conv_kernel_size lowerCamelCase__: int =output_stride lowerCamelCase__: Optional[int] =hidden_dropout_prob lowerCamelCase__: int =attention_probs_dropout_prob lowerCamelCase__: List[Any] =classifier_dropout_prob lowerCamelCase__: List[Any] =use_labels lowerCamelCase__: int =is_training lowerCamelCase__: Any =num_labels lowerCamelCase__: Any =initializer_range lowerCamelCase__: Optional[int] =scope def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Dict =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) lowerCamelCase__: Optional[int] =None lowerCamelCase__: int =None if self.use_labels: lowerCamelCase__: str =ids_tensor([self.batch_size] , self.num_labels) lowerCamelCase__: Union[str, Any] =ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels) lowerCamelCase__: List[str] =self.get_config() return config, pixel_values, labels, pixel_labels def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Any: '''simple docstring''' return MobileViTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , num_attention_heads=self.num_attention_heads , hidden_act=self.hidden_act , conv_kernel_size=self.conv_kernel_size , output_stride=self.output_stride , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , ) def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : str) ->Tuple: '''simple docstring''' lowerCamelCase__: Union[str, Any] =MobileViTModel(config=UpperCAmelCase_) model.to(UpperCAmelCase_) model.eval() lowerCamelCase__: Optional[Any] =model(UpperCAmelCase_) self.parent.assertEqual( result.last_hidden_state.shape , ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def SCREAMING_SNAKE_CASE_ (self : str , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : int , UpperCAmelCase_ : str) ->Any: '''simple docstring''' lowerCamelCase__: Union[str, Any] =self.num_labels lowerCamelCase__: Optional[int] =MobileViTForImageClassification(UpperCAmelCase_) model.to(UpperCAmelCase_) model.eval() lowerCamelCase__: Union[str, Any] =model(UpperCAmelCase_ , labels=UpperCAmelCase_) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Any) ->Any: '''simple docstring''' lowerCamelCase__: Optional[int] =self.num_labels lowerCamelCase__: Union[str, Any] =MobileViTForSemanticSegmentation(UpperCAmelCase_) model.to(UpperCAmelCase_) model.eval() lowerCamelCase__: str =model(UpperCAmelCase_) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) lowerCamelCase__: Dict =model(UpperCAmelCase_ , labels=UpperCAmelCase_) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->List[Any]: '''simple docstring''' lowerCamelCase__: Optional[Any] =self.prepare_config_and_inputs() lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: str =config_and_inputs lowerCamelCase__: Union[str, Any] ={"pixel_values": pixel_values} return config, inputs_dict @require_torch class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowercase_ = ( (MobileViTModel, MobileViTForImageClassification, MobileViTForSemanticSegmentation) if is_torch_available() else () ) lowercase_ = ( { "feature-extraction": MobileViTModel, "image-classification": MobileViTForImageClassification, "image-segmentation": MobileViTForSemanticSegmentation, } if is_torch_available() else {} ) lowercase_ = False lowercase_ = False lowercase_ = False lowercase_ = False def SCREAMING_SNAKE_CASE_ (self : Any) ->List[str]: '''simple docstring''' lowerCamelCase__: Optional[Any] =MobileViTModelTester(self) lowerCamelCase__: Union[str, Any] =MobileViTConfigTester(self , config_class=UpperCAmelCase_ , has_text_modality=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->Optional[int]: '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason="MobileViT does not use inputs_embeds") def SCREAMING_SNAKE_CASE_ (self : List[str]) ->str: '''simple docstring''' pass @unittest.skip(reason="MobileViT does not support input and output embeddings") def SCREAMING_SNAKE_CASE_ (self : Any) ->List[Any]: '''simple docstring''' pass @unittest.skip(reason="MobileViT does not output attentions") def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->str: '''simple docstring''' pass def SCREAMING_SNAKE_CASE_ (self : Dict) ->List[Any]: '''simple docstring''' lowerCamelCase__ , lowerCamelCase__: int =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase__: Tuple =model_class(UpperCAmelCase_) lowerCamelCase__: int =inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCamelCase__: Tuple =[*signature.parameters.keys()] lowerCamelCase__: int =["pixel_values"] self.assertListEqual(arg_names[:1] , UpperCAmelCase_) @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests.") def SCREAMING_SNAKE_CASE_ (self : List[str]) ->Tuple: '''simple docstring''' pass def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->Dict: '''simple docstring''' lowerCamelCase__: List[Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[str]) ->List[Any]: '''simple docstring''' def check_hidden_states_output(UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Any , UpperCAmelCase_ : List[Any]): lowerCamelCase__: List[Any] =model_class(UpperCAmelCase_) model.to(UpperCAmelCase_) model.eval() with torch.no_grad(): lowerCamelCase__: List[Any] =model(**self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_)) lowerCamelCase__: List[str] =outputs.hidden_states lowerCamelCase__: List[str] =5 self.assertEqual(len(UpperCAmelCase_) , UpperCAmelCase_) # MobileViT's feature maps are of shape (batch_size, num_channels, height, width) # with the width and height being successively divided by 2. lowerCamelCase__: Optional[int] =2 for i in range(len(UpperCAmelCase_)): self.assertListEqual( list(hidden_states[i].shape[-2:]) , [self.model_tester.image_size // divisor, self.model_tester.image_size // divisor] , ) divisor *= 2 self.assertEqual(self.model_tester.output_stride , divisor // 2) lowerCamelCase__ , lowerCamelCase__: Dict =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase__: List[Any] =True check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCamelCase__: Optional[Any] =True check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[str]) ->Optional[int]: '''simple docstring''' lowerCamelCase__: List[Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->Optional[Any]: '''simple docstring''' lowerCamelCase__: Any =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*UpperCAmelCase_) @slow def SCREAMING_SNAKE_CASE_ (self : int) ->int: '''simple docstring''' for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCamelCase__: int =MobileViTModel.from_pretrained(UpperCAmelCase_) self.assertIsNotNone(UpperCAmelCase_) def lowerCAmelCase_ ( ) -> Optional[Any]: """simple docstring""" lowerCamelCase__: List[Any] =Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @cached_property def SCREAMING_SNAKE_CASE_ (self : Union[str, Any]) ->Any: '''simple docstring''' return MobileViTImageProcessor.from_pretrained("apple/mobilevit-xx-small") if is_vision_available() else None @slow def SCREAMING_SNAKE_CASE_ (self : Any) ->Any: '''simple docstring''' lowerCamelCase__: Optional[int] =MobileViTForImageClassification.from_pretrained("apple/mobilevit-xx-small").to(UpperCAmelCase_) lowerCamelCase__: Optional[int] =self.default_image_processor lowerCamelCase__: str =prepare_img() lowerCamelCase__: Dict =image_processor(images=UpperCAmelCase_ , return_tensors="pt").to(UpperCAmelCase_) # forward pass with torch.no_grad(): lowerCamelCase__: Union[str, Any] =model(**UpperCAmelCase_) # verify the logits lowerCamelCase__: Union[str, Any] =torch.Size((1, 1_000)) self.assertEqual(outputs.logits.shape , UpperCAmelCase_) lowerCamelCase__: Union[str, Any] =torch.tensor([-1.9364, -1.2327, -0.4653]).to(UpperCAmelCase_) self.assertTrue(torch.allclose(outputs.logits[0, :3] , UpperCAmelCase_ , atol=1E-4)) @slow def SCREAMING_SNAKE_CASE_ (self : str) ->List[Any]: '''simple docstring''' lowerCamelCase__: Union[str, Any] =MobileViTForSemanticSegmentation.from_pretrained("apple/deeplabv3-mobilevit-xx-small") lowerCamelCase__: str =model.to(UpperCAmelCase_) lowerCamelCase__: Optional[Any] =MobileViTImageProcessor.from_pretrained("apple/deeplabv3-mobilevit-xx-small") lowerCamelCase__: Optional[Any] =prepare_img() lowerCamelCase__: List[str] =image_processor(images=UpperCAmelCase_ , return_tensors="pt").to(UpperCAmelCase_) # forward pass with torch.no_grad(): lowerCamelCase__: List[str] =model(**UpperCAmelCase_) lowerCamelCase__: Tuple =outputs.logits # verify the logits lowerCamelCase__: int =torch.Size((1, 21, 32, 32)) self.assertEqual(logits.shape , UpperCAmelCase_) lowerCamelCase__: Any =torch.tensor( [ [[6.9713, 6.9786, 7.2422], [7.2893, 7.2825, 7.4446], [7.6580, 7.8797, 7.9420]], [[-10.6869, -10.3250, -10.3471], [-10.4228, -9.9868, -9.7132], [-11.0405, -11.0221, -10.7318]], [[-3.3089, -2.8539, -2.6740], [-3.2706, -2.5621, -2.5108], [-3.2534, -2.6615, -2.6651]], ] , device=UpperCAmelCase_ , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , UpperCAmelCase_ , atol=1E-4)) @slow def SCREAMING_SNAKE_CASE_ (self : Any) ->Union[str, Any]: '''simple docstring''' lowerCamelCase__: int =MobileViTForSemanticSegmentation.from_pretrained("apple/deeplabv3-mobilevit-xx-small") lowerCamelCase__: Dict =model.to(UpperCAmelCase_) lowerCamelCase__: Optional[Any] =MobileViTImageProcessor.from_pretrained("apple/deeplabv3-mobilevit-xx-small") lowerCamelCase__: str =prepare_img() lowerCamelCase__: List[Any] =image_processor(images=UpperCAmelCase_ , return_tensors="pt").to(UpperCAmelCase_) # forward pass with torch.no_grad(): lowerCamelCase__: Union[str, Any] =model(**UpperCAmelCase_) lowerCamelCase__: Optional[Any] =outputs.logits.detach().cpu() lowerCamelCase__: Any =image_processor.post_process_semantic_segmentation(outputs=UpperCAmelCase_ , target_sizes=[(50, 60)]) lowerCamelCase__: Union[str, Any] =torch.Size((50, 60)) self.assertEqual(segmentation[0].shape , UpperCAmelCase_) lowerCamelCase__: Optional[Any] =image_processor.post_process_semantic_segmentation(outputs=UpperCAmelCase_) lowerCamelCase__: int =torch.Size((32, 32)) self.assertEqual(segmentation[0].shape , UpperCAmelCase_)
59
import inspect import os import unittest import torch import accelerate from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_multi_gpu from accelerate.utils import patch_environment class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ (self : Dict) ->Optional[int]: '''simple docstring''' lowerCamelCase__: List[Any] =inspect.getfile(accelerate.test_utils) lowerCamelCase__: List[Any] =os.path.sep.join(mod_file.split(os.path.sep)[:-1] + ["scripts", "test_script.py"]) lowerCamelCase__: Any =os.path.sep.join( mod_file.split(os.path.sep)[:-1] + ["scripts", "test_distributed_data_loop.py"]) lowerCamelCase__: Tuple =os.path.sep.join(mod_file.split(os.path.sep)[:-1] + ["scripts", "test_ops.py"]) @require_multi_gpu def SCREAMING_SNAKE_CASE_ (self : str) ->str: '''simple docstring''' print(F"""Found {torch.cuda.device_count()} devices.""") lowerCamelCase__: Union[str, Any] =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", self.test_file_path] with patch_environment(omp_num_threads=1): execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy()) @require_multi_gpu def SCREAMING_SNAKE_CASE_ (self : List[str]) ->List[Any]: '''simple docstring''' print(F"""Found {torch.cuda.device_count()} devices.""") lowerCamelCase__: Dict =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", self.operation_file_path] print(F"""Command: {cmd}""") with patch_environment(omp_num_threads=1): execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy()) @require_multi_gpu def SCREAMING_SNAKE_CASE_ (self : Dict) ->Tuple: '''simple docstring''' lowerCamelCase__: int =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", inspect.getfile(self.__class__)] with patch_environment(omp_num_threads=1): execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy()) @require_multi_gpu def SCREAMING_SNAKE_CASE_ (self : str) ->List[Any]: '''simple docstring''' print(F"""Found {torch.cuda.device_count()} devices, using 2 devices only""") lowerCamelCase__: int =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", self.data_loop_file_path] with patch_environment(omp_num_threads=1 , cuda_visible_devices="0,1"): execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy()) if __name__ == "__main__": __A = Accelerator() __A = (accelerator.state.process_index + 2, 10) __A = torch.randint(0, 10, shape).to(accelerator.device) __A = "" __A = accelerator.pad_across_processes(tensor) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += f"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." if not torch.equal(tensora[: accelerator.state.process_index + 2], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[accelerator.state.process_index + 2 :] == 0): error_msg += "Padding was not done with the right value (0)." __A = accelerator.pad_across_processes(tensor, pad_first=True) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += f"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." __A = accelerator.state.num_processes - accelerator.state.process_index - 1 if not torch.equal(tensora[index:], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[:index] == 0): error_msg += "Padding was not done with the right value (0)." # 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)
59
1
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __A = { "configuration_vivit": ["VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "VivitConfig"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ["VivitImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ "VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST", "VivitModel", "VivitPreTrainedModel", "VivitForVideoClassification", ] if TYPE_CHECKING: from .configuration_vivit import VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, VivitConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_vivit import VivitImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vivit import ( VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST, VivitForVideoClassification, VivitModel, VivitPreTrainedModel, ) else: import sys __A = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
59
from typing import List, Optional, Tuple, Union import PIL import torch from torchvision import transforms from diffusers.pipeline_utils import DiffusionPipeline, ImagePipelineOutput from diffusers.schedulers import DDIMScheduler from diffusers.utils import randn_tensor __A = transforms.Compose( [ transforms.Resize((256, 256)), transforms.ToTensor(), transforms.Normalize([0.5], [0.5]), ] ) def lowerCAmelCase_ ( __a ) -> str: """simple docstring""" if isinstance(__a , torch.Tensor ): return image elif isinstance(__a , PIL.Image.Image ): lowerCamelCase__: Any =[image] lowerCamelCase__: Optional[Any] =[trans(img.convert("RGB" ) ) for img in image] lowerCamelCase__: Dict =torch.stack(__a ) return image class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__(self : Any , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Tuple) ->int: '''simple docstring''' super().__init__() # make sure scheduler can always be converted to DDIM lowerCamelCase__: Tuple =DDIMScheduler.from_config(scheduler.config) self.register_modules(unet=UpperCAmelCase_ , scheduler=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Union[str, Any]) ->Dict: '''simple docstring''' if strength < 0 or strength > 1: raise ValueError(F"""The value of strength should in [0.0, 1.0] but is {strength}""") def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Tuple) ->Tuple: '''simple docstring''' lowerCamelCase__: int =min(int(num_inference_steps * strength) , UpperCAmelCase_) lowerCamelCase__: str =max(num_inference_steps - init_timestep , 0) lowerCamelCase__: int =self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[int]=None) ->Optional[int]: '''simple docstring''' if not isinstance(UpperCAmelCase_ , (torch.Tensor, PIL.Image.Image, list)): raise ValueError( F"""`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(UpperCAmelCase_)}""") lowerCamelCase__: Optional[int] =image.to(device=UpperCAmelCase_ , dtype=UpperCAmelCase_) if isinstance(UpperCAmelCase_ , UpperCAmelCase_) and len(UpperCAmelCase_) != batch_size: raise ValueError( F"""You have passed a list of generators of length {len(UpperCAmelCase_)}, but requested an effective batch""" F""" size of {batch_size}. Make sure the batch size matches the length of the generators.""") lowerCamelCase__: Dict =init_latents.shape lowerCamelCase__: int =randn_tensor(UpperCAmelCase_ , generator=UpperCAmelCase_ , device=UpperCAmelCase_ , dtype=UpperCAmelCase_) # get latents print("add noise to latents at timestep" , UpperCAmelCase_) lowerCamelCase__: Union[str, Any] =self.scheduler.add_noise(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: int =init_latents return latents @torch.no_grad() def __call__(self : Tuple , UpperCAmelCase_ : Union[torch.FloatTensor, PIL.Image.Image] = None , UpperCAmelCase_ : float = 0.8 , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , UpperCAmelCase_ : float = 0.0 , UpperCAmelCase_ : int = 50 , UpperCAmelCase_ : Optional[bool] = None , UpperCAmelCase_ : Optional[str] = "pil" , UpperCAmelCase_ : bool = True , ) ->Union[ImagePipelineOutput, Tuple]: '''simple docstring''' self.check_inputs(UpperCAmelCase_) # 2. Preprocess image lowerCamelCase__: Dict =preprocess(UpperCAmelCase_) # 3. set timesteps self.scheduler.set_timesteps(UpperCAmelCase_ , device=self.device) lowerCamelCase__ , lowerCamelCase__: str =self.get_timesteps(UpperCAmelCase_ , UpperCAmelCase_ , self.device) lowerCamelCase__: Optional[int] =timesteps[:1].repeat(UpperCAmelCase_) # 4. Prepare latent variables lowerCamelCase__: int =self.prepare_latents(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , self.unet.dtype , self.device , UpperCAmelCase_) lowerCamelCase__: Tuple =latents # 5. Denoising loop for t in self.progress_bar(UpperCAmelCase_): # 1. predict noise model_output lowerCamelCase__: Dict =self.unet(UpperCAmelCase_ , UpperCAmelCase_).sample # 2. predict previous mean of image x_t-1 and add variance depending on eta # eta corresponds to η in paper and should be between [0, 1] # do x_t -> x_t-1 lowerCamelCase__: Optional[int] =self.scheduler.step( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , eta=UpperCAmelCase_ , use_clipped_model_output=UpperCAmelCase_ , generator=UpperCAmelCase_ , ).prev_sample lowerCamelCase__: str =(image / 2 + 0.5).clamp(0 , 1) lowerCamelCase__: Optional[Any] =image.cpu().permute(0 , 2 , 3 , 1).numpy() if output_type == "pil": lowerCamelCase__: Dict =self.numpy_to_pil(UpperCAmelCase_) if not return_dict: return (image, latent_timestep.item()) return ImagePipelineOutput(images=UpperCAmelCase_)
59
1
import argparse import os.path as osp import re import torch from safetensors.torch import load_file, save_file # =================# # UNet Conversion # # =================# __A = [ # (stable-diffusion, HF Diffusers) ("time_embed.0.weight", "time_embedding.linear_1.weight"), ("time_embed.0.bias", "time_embedding.linear_1.bias"), ("time_embed.2.weight", "time_embedding.linear_2.weight"), ("time_embed.2.bias", "time_embedding.linear_2.bias"), ("input_blocks.0.0.weight", "conv_in.weight"), ("input_blocks.0.0.bias", "conv_in.bias"), ("out.0.weight", "conv_norm_out.weight"), ("out.0.bias", "conv_norm_out.bias"), ("out.2.weight", "conv_out.weight"), ("out.2.bias", "conv_out.bias"), ] __A = [ # (stable-diffusion, HF Diffusers) ("in_layers.0", "norm1"), ("in_layers.2", "conv1"), ("out_layers.0", "norm2"), ("out_layers.3", "conv2"), ("emb_layers.1", "time_emb_proj"), ("skip_connection", "conv_shortcut"), ] __A = [] # hardcoded number of downblocks and resnets/attentions... # would need smarter logic for other networks. for i in range(4): # loop over downblocks/upblocks for j in range(2): # loop over resnets/attentions for downblocks __A = f'down_blocks.{i}.resnets.{j}.' __A = f'input_blocks.{3*i + j + 1}.0.' unet_conversion_map_layer.append((sd_down_res_prefix, hf_down_res_prefix)) if i < 3: # no attention layers in down_blocks.3 __A = f'down_blocks.{i}.attentions.{j}.' __A = f'input_blocks.{3*i + j + 1}.1.' unet_conversion_map_layer.append((sd_down_atn_prefix, hf_down_atn_prefix)) for j in range(3): # loop over resnets/attentions for upblocks __A = f'up_blocks.{i}.resnets.{j}.' __A = f'output_blocks.{3*i + j}.0.' unet_conversion_map_layer.append((sd_up_res_prefix, hf_up_res_prefix)) if i > 0: # no attention layers in up_blocks.0 __A = f'up_blocks.{i}.attentions.{j}.' __A = f'output_blocks.{3*i + j}.1.' unet_conversion_map_layer.append((sd_up_atn_prefix, hf_up_atn_prefix)) if i < 3: # no downsample in down_blocks.3 __A = f'down_blocks.{i}.downsamplers.0.conv.' __A = f'input_blocks.{3*(i+1)}.0.op.' unet_conversion_map_layer.append((sd_downsample_prefix, hf_downsample_prefix)) # no upsample in up_blocks.3 __A = f'up_blocks.{i}.upsamplers.0.' __A = f'output_blocks.{3*i + 2}.{1 if i == 0 else 2}.' unet_conversion_map_layer.append((sd_upsample_prefix, hf_upsample_prefix)) __A = "mid_block.attentions.0." __A = "middle_block.1." unet_conversion_map_layer.append((sd_mid_atn_prefix, hf_mid_atn_prefix)) for j in range(2): __A = f'mid_block.resnets.{j}.' __A = f'middle_block.{2*j}.' unet_conversion_map_layer.append((sd_mid_res_prefix, hf_mid_res_prefix)) def lowerCAmelCase_ ( __a ) -> Tuple: """simple docstring""" lowerCamelCase__: Any ={k: k for k in unet_state_dict.keys()} for sd_name, hf_name in unet_conversion_map: lowerCamelCase__: List[str] =sd_name for k, v in mapping.items(): if "resnets" in k: for sd_part, hf_part in unet_conversion_map_resnet: lowerCamelCase__: int =v.replace(__a , __a ) lowerCamelCase__: List[str] =v for k, v in mapping.items(): for sd_part, hf_part in unet_conversion_map_layer: lowerCamelCase__: Dict =v.replace(__a , __a ) lowerCamelCase__: List[str] =v lowerCamelCase__: List[str] ={v: unet_state_dict[k] for k, v in mapping.items()} return new_state_dict # ================# # VAE Conversion # # ================# __A = [ # (stable-diffusion, HF Diffusers) ("nin_shortcut", "conv_shortcut"), ("norm_out", "conv_norm_out"), ("mid.attn_1.", "mid_block.attentions.0."), ] for i in range(4): # down_blocks have two resnets for j in range(2): __A = f'encoder.down_blocks.{i}.resnets.{j}.' __A = f'encoder.down.{i}.block.{j}.' vae_conversion_map.append((sd_down_prefix, hf_down_prefix)) if i < 3: __A = f'down_blocks.{i}.downsamplers.0.' __A = f'down.{i}.downsample.' vae_conversion_map.append((sd_downsample_prefix, hf_downsample_prefix)) __A = f'up_blocks.{i}.upsamplers.0.' __A = f'up.{3-i}.upsample.' vae_conversion_map.append((sd_upsample_prefix, hf_upsample_prefix)) # up_blocks have three resnets # also, up blocks in hf are numbered in reverse from sd for j in range(3): __A = f'decoder.up_blocks.{i}.resnets.{j}.' __A = f'decoder.up.{3-i}.block.{j}.' vae_conversion_map.append((sd_up_prefix, hf_up_prefix)) # this part accounts for mid blocks in both the encoder and the decoder for i in range(2): __A = f'mid_block.resnets.{i}.' __A = f'mid.block_{i+1}.' vae_conversion_map.append((sd_mid_res_prefix, hf_mid_res_prefix)) __A = [ # (stable-diffusion, HF Diffusers) ("norm.", "group_norm."), ("q.", "query."), ("k.", "key."), ("v.", "value."), ("proj_out.", "proj_attn."), ] def lowerCAmelCase_ ( __a ) -> int: """simple docstring""" return w.reshape(*w.shape , 1 , 1 ) def lowerCAmelCase_ ( __a ) -> Any: """simple docstring""" lowerCamelCase__: Optional[Any] ={k: k for k in vae_state_dict.keys()} for k, v in mapping.items(): for sd_part, hf_part in vae_conversion_map: lowerCamelCase__: Dict =v.replace(__a , __a ) lowerCamelCase__: Dict =v for k, v in mapping.items(): if "attentions" in k: for sd_part, hf_part in vae_conversion_map_attn: lowerCamelCase__: Optional[int] =v.replace(__a , __a ) lowerCamelCase__: Dict =v lowerCamelCase__: Any ={v: vae_state_dict[k] for k, v in mapping.items()} lowerCamelCase__: List[Any] =["q", "k", "v", "proj_out"] for k, v in new_state_dict.items(): for weight_name in weights_to_convert: if F"""mid.attn_1.{weight_name}.weight""" in k: print(F"""Reshaping {k} for SD format""" ) lowerCamelCase__: Any =reshape_weight_for_sd(__a ) return new_state_dict # =========================# # Text Encoder Conversion # # =========================# __A = [ # (stable-diffusion, HF Diffusers) ("resblocks.", "text_model.encoder.layers."), ("ln_1", "layer_norm1"), ("ln_2", "layer_norm2"), (".c_fc.", ".fc1."), (".c_proj.", ".fc2."), (".attn", ".self_attn"), ("ln_final.", "transformer.text_model.final_layer_norm."), ("token_embedding.weight", "transformer.text_model.embeddings.token_embedding.weight"), ("positional_embedding", "transformer.text_model.embeddings.position_embedding.weight"), ] __A = {re.escape(x[1]): x[0] for x in textenc_conversion_lst} __A = re.compile("|".join(protected.keys())) # Ordering is from https://github.com/pytorch/pytorch/blob/master/test/cpp/api/modules.cpp __A = {"q": 0, "k": 1, "v": 2} def lowerCAmelCase_ ( __a ) -> Dict: """simple docstring""" lowerCamelCase__: List[str] ={} lowerCamelCase__: Tuple ={} lowerCamelCase__: List[str] ={} for k, v in text_enc_dict.items(): if ( k.endswith(".self_attn.q_proj.weight" ) or k.endswith(".self_attn.k_proj.weight" ) or k.endswith(".self_attn.v_proj.weight" ) ): lowerCamelCase__: int =k[: -len(".q_proj.weight" )] lowerCamelCase__: str =k[-len("q_proj.weight" )] if k_pre not in capture_qkv_weight: lowerCamelCase__: Union[str, Any] =[None, None, None] lowerCamelCase__: Optional[Any] =v continue if ( k.endswith(".self_attn.q_proj.bias" ) or k.endswith(".self_attn.k_proj.bias" ) or k.endswith(".self_attn.v_proj.bias" ) ): lowerCamelCase__: Dict =k[: -len(".q_proj.bias" )] lowerCamelCase__: Tuple =k[-len("q_proj.bias" )] if k_pre not in capture_qkv_bias: lowerCamelCase__: int =[None, None, None] lowerCamelCase__: str =v continue lowerCamelCase__: str =textenc_pattern.sub(lambda __a : protected[re.escape(m.group(0 ) )] , __a ) lowerCamelCase__: Union[str, Any] =v for k_pre, tensors in capture_qkv_weight.items(): if None in tensors: raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing" ) lowerCamelCase__: int =textenc_pattern.sub(lambda __a : protected[re.escape(m.group(0 ) )] , __a ) lowerCamelCase__: Any =torch.cat(__a ) for k_pre, tensors in capture_qkv_bias.items(): if None in tensors: raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing" ) lowerCamelCase__: Optional[Any] =textenc_pattern.sub(lambda __a : protected[re.escape(m.group(0 ) )] , __a ) lowerCamelCase__: str =torch.cat(__a ) return new_state_dict def lowerCAmelCase_ ( __a ) -> str: """simple docstring""" return text_enc_dict if __name__ == "__main__": __A = argparse.ArgumentParser() parser.add_argument("--model_path", default=None, type=str, required=True, help="Path to the model to convert.") parser.add_argument("--checkpoint_path", default=None, type=str, required=True, help="Path to the output model.") parser.add_argument("--half", action="store_true", help="Save weights in half precision.") parser.add_argument( "--use_safetensors", action="store_true", help="Save weights use safetensors, default is ckpt." ) __A = parser.parse_args() assert args.model_path is not None, "Must provide a model path!" assert args.checkpoint_path is not None, "Must provide a checkpoint path!" # Path for safetensors __A = osp.join(args.model_path, "unet", "diffusion_pytorch_model.safetensors") __A = osp.join(args.model_path, "vae", "diffusion_pytorch_model.safetensors") __A = osp.join(args.model_path, "text_encoder", "model.safetensors") # Load models from safetensors if it exists, if it doesn't pytorch if osp.exists(unet_path): __A = load_file(unet_path, device="cpu") else: __A = osp.join(args.model_path, "unet", "diffusion_pytorch_model.bin") __A = torch.load(unet_path, map_location="cpu") if osp.exists(vae_path): __A = load_file(vae_path, device="cpu") else: __A = osp.join(args.model_path, "vae", "diffusion_pytorch_model.bin") __A = torch.load(vae_path, map_location="cpu") if osp.exists(text_enc_path): __A = load_file(text_enc_path, device="cpu") else: __A = osp.join(args.model_path, "text_encoder", "pytorch_model.bin") __A = torch.load(text_enc_path, map_location="cpu") # Convert the UNet model __A = convert_unet_state_dict(unet_state_dict) __A = {"model.diffusion_model." + k: v for k, v in unet_state_dict.items()} # Convert the VAE model __A = convert_vae_state_dict(vae_state_dict) __A = {"first_stage_model." + k: v for k, v in vae_state_dict.items()} # Easiest way to identify v2.0 model seems to be that the text encoder (OpenCLIP) is deeper __A = "text_model.encoder.layers.22.layer_norm2.bias" in text_enc_dict if is_vaa_model: # Need to add the tag 'transformer' in advance so we can knock it out from the final layer-norm __A = {"transformer." + k: v for k, v in text_enc_dict.items()} __A = convert_text_enc_state_dict_vaa(text_enc_dict) __A = {"cond_stage_model.model." + k: v for k, v in text_enc_dict.items()} else: __A = convert_text_enc_state_dict(text_enc_dict) __A = {"cond_stage_model.transformer." + k: v for k, v in text_enc_dict.items()} # Put together new checkpoint __A = {**unet_state_dict, **vae_state_dict, **text_enc_dict} if args.half: __A = {k: v.half() for k, v in state_dict.items()} if args.use_safetensors: save_file(state_dict, args.checkpoint_path) else: __A = {"state_dict": state_dict} torch.save(state_dict, args.checkpoint_path)
59
import argparse import os import pickle import sys import torch from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils from transformers.models.transfo_xl.tokenization_transfo_xl import CORPUS_NAME, VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() # We do this to be able to load python 2 datasets pickles # See e.g. https://stackoverflow.com/questions/2121874/python-pickling-after-changing-a-modules-directory/2121918#2121918 __A = data_utils.TransfoXLTokenizer __A = data_utils.TransfoXLCorpus __A = data_utils __A = data_utils def lowerCAmelCase_ ( __a , __a , __a , __a ) -> List[str]: """simple docstring""" if transfo_xl_dataset_file: # Convert a pre-processed corpus (see original TensorFlow repo) with open(__a , "rb" ) as fp: lowerCamelCase__: Optional[Any] =pickle.load(__a , encoding="latin1" ) # Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term) lowerCamelCase__: Union[str, Any] =pytorch_dump_folder_path + "/" + VOCAB_FILES_NAMES["pretrained_vocab_file"] print(F"""Save vocabulary to {pytorch_vocab_dump_path}""" ) lowerCamelCase__: Any =corpus.vocab.__dict__ torch.save(__a , __a ) lowerCamelCase__: Dict =corpus.__dict__ corpus_dict_no_vocab.pop("vocab" , __a ) lowerCamelCase__: List[str] =pytorch_dump_folder_path + "/" + CORPUS_NAME print(F"""Save dataset to {pytorch_dataset_dump_path}""" ) torch.save(__a , __a ) if tf_checkpoint_path: # Convert a pre-trained TensorFlow model lowerCamelCase__: Optional[Any] =os.path.abspath(__a ) lowerCamelCase__: Dict =os.path.abspath(__a ) print(F"""Converting Transformer XL checkpoint from {tf_path} with config at {config_path}.""" ) # Initialise PyTorch model if transfo_xl_config_file == "": lowerCamelCase__: int =TransfoXLConfig() else: lowerCamelCase__: Any =TransfoXLConfig.from_json_file(__a ) print(F"""Building PyTorch model from configuration: {config}""" ) lowerCamelCase__: List[Any] =TransfoXLLMHeadModel(__a ) lowerCamelCase__: List[str] =load_tf_weights_in_transfo_xl(__a , __a , __a ) # Save pytorch-model lowerCamelCase__: List[str] =os.path.join(__a , __a ) lowerCamelCase__: Tuple =os.path.join(__a , __a ) print(F"""Save PyTorch model to {os.path.abspath(__a )}""" ) torch.save(model.state_dict() , __a ) print(F"""Save configuration file to {os.path.abspath(__a )}""" ) with open(__a , "w" , encoding="utf-8" ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": __A = argparse.ArgumentParser() parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the folder to store the PyTorch model or dataset/vocab.", ) parser.add_argument( "--tf_checkpoint_path", default="", type=str, help="An optional path to a TensorFlow checkpoint path to be converted.", ) parser.add_argument( "--transfo_xl_config_file", default="", type=str, help=( "An optional config json file corresponding to the pre-trained BERT model. \n" "This specifies the model architecture." ), ) parser.add_argument( "--transfo_xl_dataset_file", default="", type=str, help="An optional dataset file to be converted in a vocabulary.", ) __A = parser.parse_args() convert_transfo_xl_checkpoint_to_pytorch( args.tf_checkpoint_path, args.transfo_xl_config_file, args.pytorch_dump_folder_path, args.transfo_xl_dataset_file, )
59
1
import inspect import unittest from transformers import ViTMSNConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ViTMSNForImageClassification, ViTMSNModel from transformers.models.vit_msn.modeling_vit_msn import VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class lowerCamelCase_ : def __init__( self , __lowerCAmelCase , __lowerCAmelCase=1_3 , __lowerCAmelCase=3_0 , __lowerCAmelCase=2 , __lowerCAmelCase=3 , __lowerCAmelCase=True , __lowerCAmelCase=True , __lowerCAmelCase=3_2 , __lowerCAmelCase=5 , __lowerCAmelCase=4 , __lowerCAmelCase=3_7 , __lowerCAmelCase="gelu" , __lowerCAmelCase=0.1 , __lowerCAmelCase=0.1 , __lowerCAmelCase=1_0 , __lowerCAmelCase=0.02 , __lowerCAmelCase=None , ): """simple docstring""" __magic_name__ :Tuple = parent __magic_name__ :Dict = batch_size __magic_name__ :Optional[int] = image_size __magic_name__ :Optional[Any] = patch_size __magic_name__ :int = num_channels __magic_name__ :Union[str, Any] = is_training __magic_name__ :Optional[Any] = use_labels __magic_name__ :str = hidden_size __magic_name__ :Optional[int] = num_hidden_layers __magic_name__ :Optional[Any] = num_attention_heads __magic_name__ :Optional[Any] = intermediate_size __magic_name__ :str = hidden_act __magic_name__ :Tuple = hidden_dropout_prob __magic_name__ :Optional[int] = attention_probs_dropout_prob __magic_name__ :int = type_sequence_label_size __magic_name__ :Optional[int] = initializer_range __magic_name__ :Any = scope # in ViT MSN, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) __magic_name__ :Tuple = (image_size // patch_size) ** 2 __magic_name__ :int = num_patches + 1 def A ( self ): """simple docstring""" __magic_name__ :Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __magic_name__ :List[Any] = None if self.use_labels: __magic_name__ :Optional[int] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __magic_name__ :str = self.get_config() return config, pixel_values, labels def A ( self ): """simple docstring""" return ViTMSNConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , initializer_range=self.initializer_range , ) def A ( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ): """simple docstring""" __magic_name__ :Optional[Any] = ViTMSNModel(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() __magic_name__ :Union[str, Any] = model(__lowerCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def A ( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ): """simple docstring""" __magic_name__ :Tuple = self.type_sequence_label_size __magic_name__ :List[str] = ViTMSNForImageClassification(__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() __magic_name__ :Union[str, Any] = model(__lowerCAmelCase , labels=__lowerCAmelCase ) print('''Pixel and labels shape: {pixel_values.shape}, {labels.shape}''' ) print('''Labels: {labels}''' ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images __magic_name__ :Optional[int] = 1 __magic_name__ :Any = ViTMSNForImageClassification(__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() __magic_name__ :Optional[int] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __magic_name__ :Dict = model(__lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def A ( self ): """simple docstring""" __magic_name__ :int = self.prepare_config_and_inputs() __magic_name__ , __magic_name__ , __magic_name__ :Union[str, Any] = config_and_inputs __magic_name__ :int = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class lowerCamelCase_ ( lowerCamelCase , lowerCamelCase , unittest.TestCase ): a__ = (ViTMSNModel, ViTMSNForImageClassification) if is_torch_available() else () a__ = ( {'''feature-extraction''': ViTMSNModel, '''image-classification''': ViTMSNForImageClassification} if is_torch_available() else {} ) a__ = False a__ = False a__ = False a__ = False def A ( self ): """simple docstring""" __magic_name__ :Tuple = ViTMSNModelTester(self ) __magic_name__ :Any = ConfigTester(self , config_class=__lowerCAmelCase , has_text_modality=__lowerCAmelCase , hidden_size=3_7 ) def A ( self ): """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason='''ViTMSN does not use inputs_embeds''' ) def A ( self ): """simple docstring""" pass def A ( self ): """simple docstring""" __magic_name__ , __magic_name__ :Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __magic_name__ :int = model_class(__lowerCAmelCase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) __magic_name__ :Optional[Any] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__lowerCAmelCase , nn.Linear ) ) def A ( self ): """simple docstring""" __magic_name__ , __magic_name__ :Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __magic_name__ :Union[str, Any] = model_class(__lowerCAmelCase ) __magic_name__ :List[str] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __magic_name__ :List[str] = [*signature.parameters.keys()] __magic_name__ :str = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , __lowerCAmelCase ) def A ( self ): """simple docstring""" __magic_name__ :List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCAmelCase ) def A ( self ): """simple docstring""" __magic_name__ :Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__lowerCAmelCase ) @slow def A ( self ): """simple docstring""" for model_name in VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __magic_name__ :str = ViTMSNModel.from_pretrained(__lowerCAmelCase ) self.assertIsNotNone(__lowerCAmelCase ) def __lowercase ( ): """simple docstring""" __magic_name__ :Optional[int] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class lowerCamelCase_ ( unittest.TestCase ): @cached_property def A ( self ): """simple docstring""" return ViTImageProcessor.from_pretrained('''facebook/vit-msn-small''' ) if is_vision_available() else None @slow def A ( self ): """simple docstring""" torch.manual_seed(2 ) __magic_name__ :int = ViTMSNForImageClassification.from_pretrained('''facebook/vit-msn-small''' ).to(__lowerCAmelCase ) __magic_name__ :Any = self.default_image_processor __magic_name__ :Dict = prepare_img() __magic_name__ :Any = image_processor(images=__lowerCAmelCase , return_tensors='''pt''' ).to(__lowerCAmelCase ) # forward pass with torch.no_grad(): __magic_name__ :Tuple = model(**__lowerCAmelCase ) # verify the logits __magic_name__ :Union[str, Any] = torch.Size((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape , __lowerCAmelCase ) __magic_name__ :Tuple = torch.tensor([-0.0803, -0.4454, -0.2375] ).to(__lowerCAmelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __lowerCAmelCase , atol=1E-4 ) )
0
from collections import UserDict from typing import List, Union from ..utils import ( add_end_docstrings, is_tf_available, is_torch_available, is_vision_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING from ..tf_utils import stable_softmax __A = logging.get_logger(__name__) @add_end_docstrings(__SCREAMING_SNAKE_CASE ) class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__(self : Optional[int] , **UpperCAmelCase_ : List[Any]) ->List[str]: '''simple docstring''' super().__init__(**UpperCAmelCase_) requires_backends(self , "vision") self.check_model_type( TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING if self.framework == "tf" else MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING) def __call__(self : List[str] , UpperCAmelCase_ : Union[str, List[str], "Image", List["Image"]] , **UpperCAmelCase_ : List[Any]) ->Tuple: '''simple docstring''' return super().__call__(UpperCAmelCase_ , **UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[Any] , **UpperCAmelCase_ : Optional[int]) ->Any: '''simple docstring''' lowerCamelCase__: Optional[int] ={} if "candidate_labels" in kwargs: lowerCamelCase__: Tuple =kwargs["candidate_labels"] if "hypothesis_template" in kwargs: lowerCamelCase__: Tuple =kwargs["hypothesis_template"] return preprocess_params, {}, {} def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Dict=None , UpperCAmelCase_ : Optional[Any]="This is a photo of {}.") ->str: '''simple docstring''' lowerCamelCase__: int =load_image(UpperCAmelCase_) lowerCamelCase__: Any =self.image_processor(images=[image] , return_tensors=self.framework) lowerCamelCase__: Any =candidate_labels lowerCamelCase__: List[str] =[hypothesis_template.format(UpperCAmelCase_) for x in candidate_labels] lowerCamelCase__: int =self.tokenizer(UpperCAmelCase_ , return_tensors=self.framework , padding=UpperCAmelCase_) lowerCamelCase__: str =[text_inputs] return inputs def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Any) ->Tuple: '''simple docstring''' lowerCamelCase__: int =model_inputs.pop("candidate_labels") lowerCamelCase__: List[str] =model_inputs.pop("text_inputs") if isinstance(text_inputs[0] , UpperCAmelCase_): lowerCamelCase__: List[Any] =text_inputs[0] else: # Batching case. lowerCamelCase__: List[Any] =text_inputs[0][0] lowerCamelCase__: List[str] =self.model(**UpperCAmelCase_ , **UpperCAmelCase_) lowerCamelCase__: str ={ "candidate_labels": candidate_labels, "logits": outputs.logits_per_image, } return model_outputs def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , UpperCAmelCase_ : Union[str, Any]) ->int: '''simple docstring''' lowerCamelCase__: List[Any] =model_outputs.pop("candidate_labels") lowerCamelCase__: Optional[int] =model_outputs["logits"][0] if self.framework == "pt": lowerCamelCase__: Optional[Any] =logits.softmax(dim=-1).squeeze(-1) lowerCamelCase__: Optional[Any] =probs.tolist() if not isinstance(UpperCAmelCase_ , UpperCAmelCase_): lowerCamelCase__: Optional[int] =[scores] elif self.framework == "tf": lowerCamelCase__: List[str] =stable_softmax(UpperCAmelCase_ , axis=-1) lowerCamelCase__: Optional[int] =probs.numpy().tolist() else: raise ValueError(F"""Unsupported framework: {self.framework}""") lowerCamelCase__: Optional[int] =[ {"score": score, "label": candidate_label} for score, candidate_label in sorted(zip(UpperCAmelCase_ , UpperCAmelCase_) , key=lambda UpperCAmelCase_: -x[0]) ] return result
59
0
from dataclasses import dataclass from typing import Optional, Tuple import torch from torch import nn from transformers import RobertaPreTrainedModel, XLMRobertaConfig, XLMRobertaModel from transformers.utils import ModelOutput @dataclass class __lowerCamelCase (_a ): _lowercase = None _lowercase = None _lowercase = None _lowercase = None class __lowerCamelCase (_a ): def __init__( self: Optional[Any],A_: str=1,A_: int=0,A_: Tuple=2,A_: Optional[int]=512,A_: Tuple="cls",A_: Any=False,A_: int=True,**A_: Optional[Any],): '''simple docstring''' super().__init__(pad_token_id=A_,bos_token_id=A_,eos_token_id=A_,**A_ ) __UpperCamelCase = project_dim __UpperCamelCase = pooler_fn __UpperCamelCase = learn_encoder __UpperCamelCase = use_attention_mask class __lowerCamelCase (_a ): _lowercase = [R"""pooler""", R"""logit_scale"""] _lowercase = [R"""position_ids""", R"""predictions.decoder.bias"""] _lowercase = """roberta""" _lowercase = RobertaSeriesConfig def __init__( self: int,A_: List[str] ): '''simple docstring''' super().__init__(A_ ) __UpperCamelCase = XLMRobertaModel(A_ ) __UpperCamelCase = nn.Linear(config.hidden_size,config.project_dim ) __UpperCamelCase = getattr(A_,'has_pre_transformation',A_ ) if self.has_pre_transformation: __UpperCamelCase = nn.Linear(config.hidden_size,config.project_dim ) __UpperCamelCase = nn.LayerNorm(config.hidden_size,eps=config.layer_norm_eps ) self.post_init() def snake_case_ ( self: List[Any],A_: Optional[torch.Tensor] = None,A_: Optional[torch.Tensor] = None,A_: Optional[torch.Tensor] = None,A_: Optional[torch.Tensor] = None,A_: Optional[torch.Tensor] = None,A_: Optional[torch.Tensor] = None,A_: Optional[torch.Tensor] = None,A_: Optional[torch.Tensor] = None,A_: Optional[bool] = None,A_: Optional[bool] = None,A_: Optional[bool] = None,): '''simple docstring''' __UpperCamelCase = return_dict if return_dict is not None else self.config.use_return_dict __UpperCamelCase = self.base_model( input_ids=A_,attention_mask=A_,token_type_ids=A_,position_ids=A_,head_mask=A_,inputs_embeds=A_,encoder_hidden_states=A_,encoder_attention_mask=A_,output_attentions=A_,output_hidden_states=True if self.has_pre_transformation else output_hidden_states,return_dict=A_,) if self.has_pre_transformation: __UpperCamelCase = outputs['hidden_states'][-2] __UpperCamelCase = self.pre_LN(A_ ) __UpperCamelCase = self.transformation_pre(A_ ) return TransformationModelOutput( projection_state=A_,last_hidden_state=outputs.last_hidden_state,hidden_states=outputs.hidden_states,attentions=outputs.attentions,) else: __UpperCamelCase = self.transformation(outputs.last_hidden_state ) return TransformationModelOutput( projection_state=A_,last_hidden_state=outputs.last_hidden_state,hidden_states=outputs.hidden_states,attentions=outputs.attentions,)
1
import json import os from dataclasses import dataclass from functools import partial from typing import Callable import flax.linen as nn import jax import jax.numpy as jnp import joblib import optax import wandb from flax import jax_utils, struct, traverse_util from flax.serialization import from_bytes, to_bytes from flax.training import train_state from flax.training.common_utils import shard from tqdm.auto import tqdm from transformers import BigBirdConfig, FlaxBigBirdForQuestionAnswering from transformers.models.big_bird.modeling_flax_big_bird import FlaxBigBirdForQuestionAnsweringModule class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = 42 lowercase_ = jnp.floataa lowercase_ = True def SCREAMING_SNAKE_CASE_ (self : Any) ->List[str]: '''simple docstring''' super().setup() lowerCamelCase__: int =nn.Dense(5 , dtype=self.dtype) def __call__(self : Dict , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : Any) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Optional[Any] =super().__call__(*UpperCAmelCase_ , **UpperCAmelCase_) lowerCamelCase__: int =self.cls(outputs[2]) return outputs[:2] + (cls_out,) class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = FlaxBigBirdForNaturalQuestionsModule def lowerCAmelCase_ ( __a , __a , __a , __a , __a , __a ) -> Tuple: """simple docstring""" def cross_entropy(__a , __a , __a=None ): lowerCamelCase__: Tuple =logits.shape[-1] lowerCamelCase__: Tuple =(labels[..., None] == jnp.arange(__a )[None]).astype("f4" ) lowerCamelCase__: str =jax.nn.log_softmax(__a , axis=-1 ) lowerCamelCase__: Optional[Any] =-jnp.sum(labels * logits , axis=-1 ) if reduction is not None: lowerCamelCase__: Optional[Any] =reduction(__a ) return loss lowerCamelCase__: str =partial(__a , reduction=jnp.mean ) lowerCamelCase__: str =cross_entropy(__a , __a ) lowerCamelCase__: Optional[int] =cross_entropy(__a , __a ) lowerCamelCase__: Optional[Any] =cross_entropy(__a , __a ) return (start_loss + end_loss + pooled_loss) / 3 @dataclass class _SCREAMING_SNAKE_CASE : '''simple docstring''' lowercase_ = "google/bigbird-roberta-base" lowercase_ = 3000 lowercase_ = 1_0500 lowercase_ = 128 lowercase_ = 3 lowercase_ = 1 lowercase_ = 5 # tx_args lowercase_ = 3E-5 lowercase_ = 0.0 lowercase_ = 2_0000 lowercase_ = 0.0095 lowercase_ = "bigbird-roberta-natural-questions" lowercase_ = "training-expt" lowercase_ = "data/nq-training.jsonl" lowercase_ = "data/nq-validation.jsonl" def SCREAMING_SNAKE_CASE_ (self : Tuple) ->List[str]: '''simple docstring''' os.makedirs(self.base_dir , exist_ok=UpperCAmelCase_) lowerCamelCase__: Optional[Any] =os.path.join(self.base_dir , self.save_dir) lowerCamelCase__: List[str] =self.batch_size_per_device * jax.device_count() @dataclass class _SCREAMING_SNAKE_CASE : '''simple docstring''' lowercase_ = 42 lowercase_ = 4096 # no dynamic padding on TPUs def __call__(self : List[Any] , UpperCAmelCase_ : Optional[Any]) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Optional[Any] =self.collate_fn(UpperCAmelCase_) lowerCamelCase__: List[Any] =jax.tree_util.tree_map(UpperCAmelCase_ , UpperCAmelCase_) return batch def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : List[str]) ->List[Any]: '''simple docstring''' lowerCamelCase__ , lowerCamelCase__: List[Any] =self.fetch_inputs(features["input_ids"]) lowerCamelCase__: Union[str, Any] ={ "input_ids": jnp.array(UpperCAmelCase_ , dtype=jnp.intaa), "attention_mask": jnp.array(UpperCAmelCase_ , dtype=jnp.intaa), "start_labels": jnp.array(features["start_token"] , dtype=jnp.intaa), "end_labels": jnp.array(features["end_token"] , dtype=jnp.intaa), "pooled_labels": jnp.array(features["category"] , dtype=jnp.intaa), } return batch def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : list) ->Optional[Any]: '''simple docstring''' lowerCamelCase__: Tuple =[self._fetch_inputs(UpperCAmelCase_) for ids in input_ids] return zip(*UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[Any] , UpperCAmelCase_ : list) ->Any: '''simple docstring''' lowerCamelCase__: Optional[Any] =[1 for _ in range(len(UpperCAmelCase_))] while len(UpperCAmelCase_) < self.max_length: input_ids.append(self.pad_id) attention_mask.append(0) return input_ids, attention_mask def lowerCAmelCase_ ( __a , __a , __a=None ) -> str: """simple docstring""" if seed is not None: lowerCamelCase__: Any =dataset.shuffle(seed=__a ) for i in range(len(__a ) // batch_size ): lowerCamelCase__: Any =dataset[i * batch_size : (i + 1) * batch_size] yield dict(__a ) @partial(jax.pmap , axis_name="batch" ) def lowerCAmelCase_ ( __a , __a , **__a ) -> List[str]: """simple docstring""" def loss_fn(__a ): lowerCamelCase__: Optional[int] =model_inputs.pop("start_labels" ) lowerCamelCase__: int =model_inputs.pop("end_labels" ) lowerCamelCase__: List[str] =model_inputs.pop("pooled_labels" ) lowerCamelCase__: Optional[int] =state.apply_fn(**__a , params=__a , dropout_rng=__a , train=__a ) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: List[Any] =outputs return state.loss_fn( __a , __a , __a , __a , __a , __a , ) lowerCamelCase__ , lowerCamelCase__: int =jax.random.split(__a ) lowerCamelCase__: Optional[Any] =jax.value_and_grad(__a ) lowerCamelCase__ , lowerCamelCase__: List[str] =grad_fn(state.params ) lowerCamelCase__: Optional[Any] =jax.lax.pmean({"loss": loss} , axis_name="batch" ) lowerCamelCase__: List[str] =jax.lax.pmean(__a , "batch" ) lowerCamelCase__: List[str] =state.apply_gradients(grads=__a ) return state, metrics, new_drp_rng @partial(jax.pmap , axis_name="batch" ) def lowerCAmelCase_ ( __a , **__a ) -> List[Any]: """simple docstring""" lowerCamelCase__: int =model_inputs.pop("start_labels" ) lowerCamelCase__: List[str] =model_inputs.pop("end_labels" ) lowerCamelCase__: int =model_inputs.pop("pooled_labels" ) lowerCamelCase__: Optional[Any] =state.apply_fn(**__a , params=state.params , train=__a ) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: List[str] =outputs lowerCamelCase__: Optional[int] =state.loss_fn(__a , __a , __a , __a , __a , __a ) lowerCamelCase__: Optional[Any] =jax.lax.pmean({"loss": loss} , axis_name="batch" ) return metrics class _SCREAMING_SNAKE_CASE ( train_state.TrainState ): '''simple docstring''' lowercase_ = struct.field(pytree_node=__SCREAMING_SNAKE_CASE ) @dataclass class _SCREAMING_SNAKE_CASE : '''simple docstring''' lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = None def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : int=None) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Dict =model.params lowerCamelCase__: Tuple =TrainState.create( apply_fn=model.__call__ , params=UpperCAmelCase_ , tx=UpperCAmelCase_ , loss_fn=UpperCAmelCase_ , ) if ckpt_dir is not None: lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Any =restore_checkpoint(UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: Tuple ={ "lr": args.lr, "init_lr": args.init_lr, "warmup_steps": args.warmup_steps, "num_train_steps": num_train_steps, "weight_decay": args.weight_decay, } lowerCamelCase__ , lowerCamelCase__: List[Any] =build_tx(**UpperCAmelCase_) lowerCamelCase__: str =train_state.TrainState( step=UpperCAmelCase_ , apply_fn=model.__call__ , params=UpperCAmelCase_ , tx=UpperCAmelCase_ , opt_state=UpperCAmelCase_ , ) lowerCamelCase__: Tuple =args lowerCamelCase__: Tuple =data_collator lowerCamelCase__: str =lr lowerCamelCase__: Dict =params lowerCamelCase__: List[str] =jax_utils.replicate(UpperCAmelCase_) return state def SCREAMING_SNAKE_CASE_ (self : List[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Tuple) ->Optional[Any]: '''simple docstring''' lowerCamelCase__: Tuple =self.args lowerCamelCase__: Any =len(UpperCAmelCase_) // args.batch_size lowerCamelCase__: List[str] =jax.random.PRNGKey(0) lowerCamelCase__: Optional[Any] =jax.random.split(UpperCAmelCase_ , jax.device_count()) for epoch in range(args.max_epochs): lowerCamelCase__: Union[str, Any] =jnp.array(0 , dtype=jnp.floataa) lowerCamelCase__: str =get_batched_dataset(UpperCAmelCase_ , args.batch_size , seed=UpperCAmelCase_) lowerCamelCase__: Dict =0 for batch in tqdm(UpperCAmelCase_ , total=UpperCAmelCase_ , desc=F"""Running EPOCH-{epoch}"""): lowerCamelCase__: List[str] =self.data_collator(UpperCAmelCase_) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Optional[int] =self.train_step_fn(UpperCAmelCase_ , UpperCAmelCase_ , **UpperCAmelCase_) running_loss += jax_utils.unreplicate(metrics["loss"]) i += 1 if i % args.logging_steps == 0: lowerCamelCase__: Optional[int] =jax_utils.unreplicate(state.step) lowerCamelCase__: List[Any] =running_loss.item() / i lowerCamelCase__: Tuple =self.scheduler_fn(state_step - 1) lowerCamelCase__: Union[str, Any] =self.evaluate(UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: Dict ={ "step": state_step.item(), "eval_loss": eval_loss.item(), "tr_loss": tr_loss, "lr": lr.item(), } tqdm.write(str(UpperCAmelCase_)) self.logger.log(UpperCAmelCase_ , commit=UpperCAmelCase_) if i % args.save_steps == 0: self.save_checkpoint(args.save_dir + F"""-e{epoch}-s{i}""" , state=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : str , UpperCAmelCase_ : str) ->Any: '''simple docstring''' lowerCamelCase__: List[Any] =get_batched_dataset(UpperCAmelCase_ , self.args.batch_size) lowerCamelCase__: List[str] =len(UpperCAmelCase_) // self.args.batch_size lowerCamelCase__: str =jnp.array(0 , dtype=jnp.floataa) lowerCamelCase__: Optional[Any] =0 for batch in tqdm(UpperCAmelCase_ , total=UpperCAmelCase_ , desc="Evaluating ... "): lowerCamelCase__: int =self.data_collator(UpperCAmelCase_) lowerCamelCase__: str =self.val_step_fn(UpperCAmelCase_ , **UpperCAmelCase_) running_loss += jax_utils.unreplicate(metrics["loss"]) i += 1 return running_loss / i def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[int]) ->int: '''simple docstring''' lowerCamelCase__: Any =jax_utils.unreplicate(UpperCAmelCase_) print(F"""SAVING CHECKPOINT IN {save_dir}""" , end=" ... ") self.model_save_fn(UpperCAmelCase_ , params=state.params) with open(os.path.join(UpperCAmelCase_ , "opt_state.msgpack") , "wb") as f: f.write(to_bytes(state.opt_state)) joblib.dump(self.args , os.path.join(UpperCAmelCase_ , "args.joblib")) joblib.dump(self.data_collator , os.path.join(UpperCAmelCase_ , "data_collator.joblib")) with open(os.path.join(UpperCAmelCase_ , "training_state.json") , "w") as f: json.dump({"step": state.step.item()} , UpperCAmelCase_) print("DONE") def lowerCAmelCase_ ( __a , __a ) -> str: """simple docstring""" print(F"""RESTORING CHECKPOINT FROM {save_dir}""" , end=" ... " ) with open(os.path.join(__a , "flax_model.msgpack" ) , "rb" ) as f: lowerCamelCase__: Tuple =from_bytes(state.params , f.read() ) with open(os.path.join(__a , "opt_state.msgpack" ) , "rb" ) as f: lowerCamelCase__: Optional[int] =from_bytes(state.opt_state , f.read() ) lowerCamelCase__: Any =joblib.load(os.path.join(__a , "args.joblib" ) ) lowerCamelCase__: Union[str, Any] =joblib.load(os.path.join(__a , "data_collator.joblib" ) ) with open(os.path.join(__a , "training_state.json" ) , "r" ) as f: lowerCamelCase__: Optional[Any] =json.load(__a ) lowerCamelCase__: Any =training_state["step"] print("DONE" ) return params, opt_state, step, args, data_collator def lowerCAmelCase_ ( __a , __a , __a , __a ) -> Optional[int]: """simple docstring""" lowerCamelCase__: int =num_train_steps - warmup_steps lowerCamelCase__: str =optax.linear_schedule(init_value=__a , end_value=__a , transition_steps=__a ) lowerCamelCase__: Optional[Any] =optax.linear_schedule(init_value=__a , end_value=1e-7 , transition_steps=__a ) lowerCamelCase__: List[Any] =optax.join_schedules(schedules=[warmup_fn, decay_fn] , boundaries=[warmup_steps] ) return lr def lowerCAmelCase_ ( __a , __a , __a , __a , __a ) -> str: """simple docstring""" def weight_decay_mask(__a ): lowerCamelCase__: List[str] =traverse_util.flatten_dict(__a ) lowerCamelCase__: List[str] ={k: (v[-1] != "bias" and v[-2:] != ("LayerNorm", "scale")) for k, v in params.items()} return traverse_util.unflatten_dict(__a ) lowerCamelCase__: Optional[Any] =scheduler_fn(__a , __a , __a , __a ) lowerCamelCase__: Tuple =optax.adamw(learning_rate=__a , weight_decay=__a , mask=__a ) return tx, lr
59
0
import os from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import xopen, xsplitext from ..table import array_cast from ..utils.py_utils import no_op_if_value_is_null, string_to_dict if TYPE_CHECKING: from .features import FeatureType UpperCAmelCase_ ,UpperCAmelCase_ ,UpperCAmelCase_ = False, False, False @dataclass class lowerCamelCase__ : """simple docstring""" a__ : Optional[int] = None a__ : bool = True a__ : bool = True a__ : Optional[str] = None # Automatically constructed a__ : ClassVar[str] = "dict" a__ : ClassVar[Any] = pa.struct({"bytes": pa.binary(), "path": pa.string()}) a__ : str = field(default="Audio" , init=_A , repr=_A) def __call__( self : str ) -> List[str]: return self.pa_type def snake_case_ ( self : Any , __lowerCAmelCase : Union[str, bytes, dict] ) -> dict: try: import soundfile as sf # soundfile is a dependency of librosa, needed to decode audio files. except ImportError as err: raise ImportError('''To support encoding audio data, please install \'soundfile\'.''' ) from err if isinstance(__lowerCAmelCase , __lowerCAmelCase ): return {"bytes": None, "path": value} elif isinstance(__lowerCAmelCase , __lowerCAmelCase ): return {"bytes": value, "path": None} elif "array" in value: # convert the audio array to wav bytes _A = BytesIO() sf.write(__lowerCAmelCase , value['''array'''] , value['''sampling_rate'''] , format='''wav''' ) return {"bytes": buffer.getvalue(), "path": None} elif value.get('''path''' ) is not None and os.path.isfile(value['''path'''] ): # we set "bytes": None to not duplicate the data if they're already available locally if value["path"].endswith('''pcm''' ): # "PCM" only has raw audio bytes if value.get('''sampling_rate''' ) is None: # At least, If you want to convert "PCM-byte" to "WAV-byte", you have to know sampling rate raise KeyError('''To use PCM files, please specify a \'sampling_rate\' in Audio object''' ) if value.get('''bytes''' ): # If we already had PCM-byte, we don`t have to make "read file, make bytes" (just use it!) _A = np.frombuffer(value['''bytes'''] , dtype=np.intaa ).astype(np.floataa ) / 3_27_67 else: _A = np.memmap(value['''path'''] , dtype='''h''' , mode='''r''' ).astype(np.floataa ) / 3_27_67 _A = BytesIO(bytes() ) sf.write(__lowerCAmelCase , __lowerCAmelCase , value['''sampling_rate'''] , format='''wav''' ) return {"bytes": buffer.getvalue(), "path": None} else: return {"bytes": None, "path": value.get('''path''' )} elif value.get('''bytes''' ) is not None or value.get('''path''' ) is not None: # store the audio bytes, and path is used to infer the audio format using the file extension return {"bytes": value.get('''bytes''' ), "path": value.get('''path''' )} else: raise ValueError( f'''An audio sample should have one of \'path\' or \'bytes\' but they are missing or None in {value}.''' ) def snake_case_ ( self : Union[str, Any] , __lowerCAmelCase : dict , __lowerCAmelCase : Optional[Dict[str, Union[str, bool, None]]] = None ) -> dict: if not self.decode: raise RuntimeError('''Decoding is disabled for this feature. Please use Audio(decode=True) instead.''' ) _A , _A = (value['''path'''], BytesIO(value['''bytes'''] )) if value['''bytes'''] is not None else (value['''path'''], None) if path is None and file is None: raise ValueError(f'''An audio sample should have one of \'path\' or \'bytes\' but both are None in {value}.''' ) try: import librosa import soundfile as sf except ImportError as err: raise ImportError('''To support decoding audio files, please install \'librosa\' and \'soundfile\'.''' ) from err _A = xsplitext(__lowerCAmelCase )[1][1:].lower() if path is not None else None if not config.IS_OPUS_SUPPORTED and audio_format == "opus": raise RuntimeError( '''Decoding \'opus\' files requires system library \'libsndfile\'>=1.0.31, ''' '''You can try to update `soundfile` python library: `pip install "soundfile>=0.12.1"`. ''' ) elif not config.IS_MP3_SUPPORTED and audio_format == "mp3": raise RuntimeError( '''Decoding \'mp3\' files requires system library \'libsndfile\'>=1.1.0, ''' '''You can try to update `soundfile` python library: `pip install "soundfile>=0.12.1"`. ''' ) if file is None: _A = token_per_repo_id or {} _A = path.split('''::''' )[-1] try: _A = string_to_dict(__lowerCAmelCase , config.HUB_DATASETS_URL )['''repo_id'''] _A = token_per_repo_id[repo_id] except (ValueError, KeyError): _A = None with xopen(__lowerCAmelCase , '''rb''' , use_auth_token=__lowerCAmelCase ) as f: _A , _A = sf.read(__lowerCAmelCase ) else: _A , _A = sf.read(__lowerCAmelCase ) _A = array.T if self.mono: _A = librosa.to_mono(__lowerCAmelCase ) if self.sampling_rate and self.sampling_rate != sampling_rate: _A = librosa.resample(__lowerCAmelCase , orig_sr=__lowerCAmelCase , target_sr=self.sampling_rate ) _A = self.sampling_rate return {"path": path, "array": array, "sampling_rate": sampling_rate} def snake_case_ ( self : List[Any] ) -> Union["FeatureType", Dict[str, "FeatureType"]]: from .features import Value if self.decode: raise ValueError('''Cannot flatten a decoded Audio feature.''' ) return { "bytes": Value('''binary''' ), "path": Value('''string''' ), } def snake_case_ ( self : Union[str, Any] , __lowerCAmelCase : Union[pa.StringArray, pa.StructArray] ) -> pa.StructArray: if pa.types.is_string(storage.type ): _A = pa.array([None] * len(__lowerCAmelCase ) , type=pa.binary() ) _A = pa.StructArray.from_arrays([bytes_array, storage] , ['''bytes''', '''path'''] , mask=storage.is_null() ) elif pa.types.is_binary(storage.type ): _A = pa.array([None] * len(__lowerCAmelCase ) , type=pa.string() ) _A = pa.StructArray.from_arrays([storage, path_array] , ['''bytes''', '''path'''] , mask=storage.is_null() ) elif pa.types.is_struct(storage.type ) and storage.type.get_all_field_indices('''array''' ): _A = pa.array([Audio().encode_example(__lowerCAmelCase ) if x is not None else None for x in storage.to_pylist()] ) elif pa.types.is_struct(storage.type ): if storage.type.get_field_index('''bytes''' ) >= 0: _A = storage.field('''bytes''' ) else: _A = pa.array([None] * len(__lowerCAmelCase ) , type=pa.binary() ) if storage.type.get_field_index('''path''' ) >= 0: _A = storage.field('''path''' ) else: _A = pa.array([None] * len(__lowerCAmelCase ) , type=pa.string() ) _A = pa.StructArray.from_arrays([bytes_array, path_array] , ['''bytes''', '''path'''] , mask=storage.is_null() ) return array_cast(__lowerCAmelCase , self.pa_type ) def snake_case_ ( self : Optional[Any] , __lowerCAmelCase : pa.StructArray ) -> pa.StructArray: @no_op_if_value_is_null def path_to_bytes(__lowerCAmelCase : Union[str, Any] ): with xopen(__lowerCAmelCase , '''rb''' ) as f: _A = f.read() return bytes_ _A = pa.array( [ (path_to_bytes(x['''path'''] ) if x['''bytes'''] is None else x['''bytes''']) if x is not None else None for x in storage.to_pylist() ] , type=pa.binary() , ) _A = pa.array( [os.path.basename(__lowerCAmelCase ) if path is not None else None for path in storage.field('''path''' ).to_pylist()] , type=pa.string() , ) _A = pa.StructArray.from_arrays([bytes_array, path_array] , ['''bytes''', '''path'''] , mask=bytes_array.is_null() ) return array_cast(__lowerCAmelCase , self.pa_type )
2
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = ["image_processor", "tokenizer"] lowercase_ = "ChineseCLIPImageProcessor" lowercase_ = ("BertTokenizer", "BertTokenizerFast") def __init__(self : Any , UpperCAmelCase_ : List[str]=None , UpperCAmelCase_ : Union[str, Any]=None , **UpperCAmelCase_ : str) ->Dict: '''simple docstring''' lowerCamelCase__: str =None if "feature_extractor" in kwargs: warnings.warn( "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`" " instead." , UpperCAmelCase_ , ) lowerCamelCase__: Tuple =kwargs.pop("feature_extractor") lowerCamelCase__: Optional[int] =image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("You need to specify an `image_processor`.") if tokenizer is None: raise ValueError("You need to specify a `tokenizer`.") super().__init__(UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: Optional[int] =self.image_processor def __call__(self : int , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : List[Any]=None , **UpperCAmelCase_ : Dict) ->Optional[int]: '''simple docstring''' if text is None and images is None: raise ValueError("You have to specify either text or images. Both cannot be none.") if text is not None: lowerCamelCase__: Dict =self.tokenizer(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_) if images is not None: lowerCamelCase__: List[str] =self.image_processor(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_) if text is not None and images is not None: lowerCamelCase__: Union[str, Any] =image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**UpperCAmelCase_) , tensor_type=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : int) ->str: '''simple docstring''' return self.tokenizer.batch_decode(*UpperCAmelCase_ , **UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Any , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : List[Any]) ->Dict: '''simple docstring''' return self.tokenizer.decode(*UpperCAmelCase_ , **UpperCAmelCase_) @property def SCREAMING_SNAKE_CASE_ (self : int) ->List[str]: '''simple docstring''' lowerCamelCase__: str =self.tokenizer.model_input_names lowerCamelCase__: Union[str, Any] =self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names)) @property def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->str: '''simple docstring''' warnings.warn( "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead." , UpperCAmelCase_ , ) return self.image_processor_class
59
0
'''simple docstring''' from PIL import Image def A_( A : Image , A : float): def brightness(A : int) -> float: return 128 + level + (c - 128) if not -255.0 <= level <= 255.0: raise ValueError('level must be between -255.0 (black) and 255.0 (white)') return img.point(A) if __name__ == "__main__": # Load image with Image.open('image_data/lena.jpg') as img: # Change brightness to 100 lowerCAmelCase : Dict = change_brightness(img, 1_00) brigt_img.save('image_data/lena_brightness.png', format='png')
3
from math import ceil, sqrt def lowerCAmelCase_ ( __a = 1000000 ) -> int: """simple docstring""" lowerCamelCase__: Any =0 for outer_width in range(3 , (limit // 4) + 2 ): if outer_width**2 > limit: lowerCamelCase__: Optional[int] =max(ceil(sqrt(outer_width**2 - limit ) ) , 1 ) else: lowerCamelCase__: Tuple =1 if (outer_width - hole_width_lower_bound) % 2: hole_width_lower_bound += 1 answer += (outer_width - hole_width_lower_bound - 2) // 2 + 1 return answer if __name__ == "__main__": print(f'{solution() = }')
59
0
"""simple docstring""" import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..bit import BitConfig __UpperCamelCase : Any = logging.get_logger(__name__) __UpperCamelCase : Optional[Any] = { '''Intel/dpt-large''': '''https://huggingface.co/Intel/dpt-large/resolve/main/config.json''', # See all DPT models at https://huggingface.co/models?filter=dpt } class a ( a__ ): snake_case__ = '''dpt''' def __init__( self , _snake_case=7_68 , _snake_case=12 , _snake_case=12 , _snake_case=30_72 , _snake_case="gelu" , _snake_case=0.0 , _snake_case=0.0 , _snake_case=0.02 , _snake_case=1E-12 , _snake_case=3_84 , _snake_case=16 , _snake_case=3 , _snake_case=False , _snake_case=True , _snake_case=[2, 5, 8, 11] , _snake_case="project" , _snake_case=[4, 2, 1, 0.5] , _snake_case=[96, 1_92, 3_84, 7_68] , _snake_case=2_56 , _snake_case=-1 , _snake_case=False , _snake_case=True , _snake_case=0.4 , _snake_case=2_55 , _snake_case=0.1 , _snake_case=[1, 10_24, 24, 24] , _snake_case=[0, 1] , _snake_case=None , **_snake_case , ): """simple docstring""" super().__init__(**_snake_case ) lowerCAmelCase = hidden_size lowerCAmelCase = is_hybrid if self.is_hybrid: if backbone_config is None: logger.info('Initializing the config with a `BiT` backbone.' ) lowerCAmelCase = { 'global_padding': 'same', 'layer_type': 'bottleneck', 'depths': [3, 4, 9], 'out_features': ['stage1', 'stage2', 'stage3'], 'embedding_dynamic_padding': True, } lowerCAmelCase = BitConfig(**_snake_case ) elif isinstance(_snake_case , _snake_case ): logger.info('Initializing the config with a `BiT` backbone.' ) lowerCAmelCase = BitConfig(**_snake_case ) elif isinstance(_snake_case , _snake_case ): lowerCAmelCase = backbone_config else: raise ValueError( F'backbone_config must be a dictionary or a `PretrainedConfig`, got {backbone_config.__class__}.' ) lowerCAmelCase = backbone_featmap_shape lowerCAmelCase = neck_ignore_stages if readout_type != "project": raise ValueError('Readout type must be \'project\' when using `DPT-hybrid` mode.' ) else: lowerCAmelCase = None lowerCAmelCase = None lowerCAmelCase = [] lowerCAmelCase = num_hidden_layers lowerCAmelCase = num_attention_heads lowerCAmelCase = intermediate_size lowerCAmelCase = hidden_act lowerCAmelCase = hidden_dropout_prob lowerCAmelCase = attention_probs_dropout_prob lowerCAmelCase = initializer_range lowerCAmelCase = layer_norm_eps lowerCAmelCase = image_size lowerCAmelCase = patch_size lowerCAmelCase = num_channels lowerCAmelCase = qkv_bias lowerCAmelCase = backbone_out_indices if readout_type not in ["ignore", "add", "project"]: raise ValueError('Readout_type must be one of [\'ignore\', \'add\', \'project\']' ) lowerCAmelCase = readout_type lowerCAmelCase = reassemble_factors lowerCAmelCase = neck_hidden_sizes lowerCAmelCase = fusion_hidden_size lowerCAmelCase = head_in_index lowerCAmelCase = use_batch_norm_in_fusion_residual # auxiliary head attributes (semantic segmentation) lowerCAmelCase = use_auxiliary_head lowerCAmelCase = auxiliary_loss_weight lowerCAmelCase = semantic_loss_ignore_index lowerCAmelCase = semantic_classifier_dropout def UpperCamelCase__ ( self ): """simple docstring""" lowerCAmelCase = copy.deepcopy(self.__dict__ ) if output["backbone_config"] is not None: lowerCAmelCase = self.backbone_config.to_dict() lowerCAmelCase = self.__class__.model_type return output
4
def lowerCAmelCase_ ( __a = 50000000 ) -> int: """simple docstring""" lowerCamelCase__: Any =set() lowerCamelCase__: int =int((limit - 24) ** (1 / 2) ) lowerCamelCase__: Tuple =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 , __a ) ) ) for primea in primes: lowerCamelCase__: Optional[int] =primea * primea for primea in primes: lowerCamelCase__: List[str] =primea * primea * primea if square + cube >= limit - 16: break for primea in primes: lowerCamelCase__: int =primea * primea * primea * primea lowerCamelCase__: Optional[Any] =square + cube + tetr if total >= limit: break ret.add(__a ) return len(__a ) if __name__ == "__main__": print(f'{solution() = }')
59
0
'''simple docstring''' from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Features, Sequence, Value from .base import TaskTemplate @dataclass(frozen=_SCREAMING_SNAKE_CASE ) class UpperCAmelCase_ ( _SCREAMING_SNAKE_CASE ): '''simple docstring''' _lowercase : str = field(default='''question-answering-extractive''' , metadata={'''include_in_asdict_even_if_is_default''': True} ) _lowercase : ClassVar[Features] = Features({'''question''': Value('''string''' ), '''context''': Value('''string''' )} ) _lowercase : ClassVar[Features] = Features( { '''answers''': Sequence( { '''text''': Value('''string''' ), '''answer_start''': Value('''int32''' ), } ) } ) _lowercase : str = "question" _lowercase : str = "context" _lowercase : str = "answers" @property def _lowercase ( self ): """simple docstring""" return {self.question_column: "question", self.context_column: "context", self.answers_column: "answers"}
5
from __future__ import annotations from decimal import Decimal from math import * # noqa: F403 from sympy import diff def lowerCAmelCase_ ( __a , __a , __a = 10**-10 ) -> float: """simple docstring""" lowerCamelCase__: List[str] =a while True: lowerCamelCase__: Optional[Any] =Decimal(__a ) - ( Decimal(eval(__a ) ) / Decimal(eval(str(diff(__a ) ) ) ) # noqa: S307 ) # This number dictates the accuracy of the answer if abs(eval(__a ) ) < precision: # noqa: S307 return float(__a ) # Let's Execute if __name__ == "__main__": # Find root of trigonometric function # Find value of pi print(f'The root of sin(x) = 0 is {newton_raphson("sin(x)", 2)}') # Find root of polynomial print(f'The root of x**2 - 5*x + 2 = 0 is {newton_raphson("x**2 - 5*x + 2", 0.4)}') # Find Square Root of 5 print(f'The root of log(x) - 1 = 0 is {newton_raphson("log(x) - 1", 2)}') # Exponential Roots print(f'The root of exp(x) - 1 = 0 is {newton_raphson("exp(x) - 1", 0)}')
59
0
import collections import gzip import os import urllib import numpy from tensorflow.python.framework import dtypes, random_seed from tensorflow.python.platform import gfile from tensorflow.python.util.deprecation import deprecated _lowerCamelCase = collections.namedtuple('_Datasets', ['train', 'validation', 'test']) # CVDF mirror of http://yann.lecun.com/exdb/mnist/ _lowerCamelCase = 'https://storage.googleapis.com/cvdf-datasets/mnist/' def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[str, Any] ): SCREAMING_SNAKE_CASE__ = numpy.dtype(numpy.uintaa ).newbyteorder(""">""" ) return numpy.frombuffer(bytestream.read(4 ) , dtype=UpperCamelCase__ )[0] @deprecated(UpperCamelCase__ , """Please use tf.data to implement this functionality.""" ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] ): print("""Extracting""" , f.name ) with gzip.GzipFile(fileobj=UpperCamelCase__ ) as bytestream: SCREAMING_SNAKE_CASE__ = _readaa(UpperCamelCase__ ) if magic != 2_051: raise ValueError( """Invalid magic number %d in MNIST image file: %s""" % (magic, f.name) ) SCREAMING_SNAKE_CASE__ = _readaa(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = _readaa(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = _readaa(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = bytestream.read(rows * cols * num_images ) SCREAMING_SNAKE_CASE__ = numpy.frombuffer(UpperCamelCase__ , dtype=numpy.uinta ) SCREAMING_SNAKE_CASE__ = data.reshape(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , 1 ) return data @deprecated(UpperCamelCase__ , """Please use tf.one_hot on tensors.""" ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] , UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = labels_dense.shape[0] SCREAMING_SNAKE_CASE__ = numpy.arange(UpperCamelCase__ ) * num_classes SCREAMING_SNAKE_CASE__ = numpy.zeros((num_labels, num_classes) ) SCREAMING_SNAKE_CASE__ = 1 return labels_one_hot @deprecated(UpperCamelCase__ , """Please use tf.data to implement this functionality.""" ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[Any] , UpperCamelCase__: Union[str, Any]=False , UpperCamelCase__: List[Any]=10 ): print("""Extracting""" , f.name ) with gzip.GzipFile(fileobj=UpperCamelCase__ ) as bytestream: SCREAMING_SNAKE_CASE__ = _readaa(UpperCamelCase__ ) if magic != 2_049: raise ValueError( """Invalid magic number %d in MNIST label file: %s""" % (magic, f.name) ) SCREAMING_SNAKE_CASE__ = _readaa(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = bytestream.read(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = numpy.frombuffer(UpperCamelCase__ , dtype=numpy.uinta ) if one_hot: return _dense_to_one_hot(UpperCamelCase__ , UpperCamelCase__ ) return labels class UpperCamelCase_ : @deprecated( __A , """Please use alternatives such as official/mnist/_DataSet.py""" """ from tensorflow/models.""" , ) def __init__( self :Optional[Any] , __A :List[Any] , __A :Tuple , __A :Union[str, Any]=False , __A :int=False , __A :Optional[Any]=dtypes.floataa , __A :Any=True , __A :Optional[Any]=None , ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = random_seed.get_seed(__A ) # If op level seed is not set, use whatever graph level seed is returned numpy.random.seed(seeda if seed is None else seeda ) SCREAMING_SNAKE_CASE__ = dtypes.as_dtype(__A ).base_dtype if dtype not in (dtypes.uinta, dtypes.floataa): raise TypeError("""Invalid image dtype %r, expected uint8 or float32""" % dtype ) if fake_data: SCREAMING_SNAKE_CASE__ = 1_0000 SCREAMING_SNAKE_CASE__ = one_hot else: assert ( images.shape[0] == labels.shape[0] ), f'''images.shape: {images.shape} labels.shape: {labels.shape}''' SCREAMING_SNAKE_CASE__ = images.shape[0] # Convert shape from [num examples, rows, columns, depth] # to [num examples, rows*columns] (assuming depth == 1) if reshape: assert images.shape[3] == 1 SCREAMING_SNAKE_CASE__ = images.reshape( images.shape[0] , images.shape[1] * images.shape[2] ) if dtype == dtypes.floataa: # Convert from [0, 255] -> [0.0, 1.0]. SCREAMING_SNAKE_CASE__ = images.astype(numpy.floataa ) SCREAMING_SNAKE_CASE__ = numpy.multiply(__A , 1.0 / 2_5_5.0 ) SCREAMING_SNAKE_CASE__ = images SCREAMING_SNAKE_CASE__ = labels SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = 0 @property def _snake_case ( self :str ) -> List[str]: """simple docstring""" return self._images @property def _snake_case ( self :str ) -> List[str]: """simple docstring""" return self._labels @property def _snake_case ( self :List[str] ) -> str: """simple docstring""" return self._num_examples @property def _snake_case ( self :List[Any] ) -> Optional[Any]: """simple docstring""" return self._epochs_completed def _snake_case ( self :Union[str, Any] , __A :Union[str, Any] , __A :str=False , __A :str=True ) -> List[str]: """simple docstring""" if fake_data: SCREAMING_SNAKE_CASE__ = [1] * 784 SCREAMING_SNAKE_CASE__ = [1] + [0] * 9 if self.one_hot else 0 return ( [fake_image for _ in range(__A )], [fake_label for _ in range(__A )], ) SCREAMING_SNAKE_CASE__ = self._index_in_epoch # Shuffle for the first epoch if self._epochs_completed == 0 and start == 0 and shuffle: SCREAMING_SNAKE_CASE__ = numpy.arange(self._num_examples ) numpy.random.shuffle(__A ) SCREAMING_SNAKE_CASE__ = self.images[perma] SCREAMING_SNAKE_CASE__ = self.labels[perma] # Go to the next epoch if start + batch_size > self._num_examples: # Finished epoch self._epochs_completed += 1 # Get the rest examples in this epoch SCREAMING_SNAKE_CASE__ = self._num_examples - start SCREAMING_SNAKE_CASE__ = self._images[start : self._num_examples] SCREAMING_SNAKE_CASE__ = self._labels[start : self._num_examples] # Shuffle the data if shuffle: SCREAMING_SNAKE_CASE__ = numpy.arange(self._num_examples ) numpy.random.shuffle(__A ) SCREAMING_SNAKE_CASE__ = self.images[perm] SCREAMING_SNAKE_CASE__ = self.labels[perm] # Start next epoch SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = batch_size - rest_num_examples SCREAMING_SNAKE_CASE__ = self._index_in_epoch SCREAMING_SNAKE_CASE__ = self._images[start:end] SCREAMING_SNAKE_CASE__ = self._labels[start:end] return ( numpy.concatenate((images_rest_part, images_new_part) , axis=0 ), numpy.concatenate((labels_rest_part, labels_new_part) , axis=0 ), ) else: self._index_in_epoch += batch_size SCREAMING_SNAKE_CASE__ = self._index_in_epoch return self._images[start:end], self._labels[start:end] @deprecated(UpperCamelCase__ , """Please write your own downloading logic.""" ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: List[Any] ): if not gfile.Exists(UpperCamelCase__ ): gfile.MakeDirs(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = os.path.join(UpperCamelCase__ , UpperCamelCase__ ) if not gfile.Exists(UpperCamelCase__ ): urllib.request.urlretrieve(UpperCamelCase__ , UpperCamelCase__ ) # noqa: S310 with gfile.GFile(UpperCamelCase__ ) as f: SCREAMING_SNAKE_CASE__ = f.size() print("""Successfully downloaded""" , UpperCamelCase__ , UpperCamelCase__ , """bytes.""" ) return filepath @deprecated( UpperCamelCase__ , """Please use alternatives such as:""" """ tensorflow_datasets.load('mnist')""" ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[Any] , UpperCamelCase__: Optional[Any]=False , UpperCamelCase__: Dict=False , UpperCamelCase__: Union[str, Any]=dtypes.floataa , UpperCamelCase__: Any=True , UpperCamelCase__: List[Any]=5_000 , UpperCamelCase__: List[Any]=None , UpperCamelCase__: List[Any]=DEFAULT_SOURCE_URL , ): if fake_data: def fake(): return _DataSet( [] , [] , fake_data=UpperCamelCase__ , one_hot=UpperCamelCase__ , dtype=UpperCamelCase__ , seed=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = fake() SCREAMING_SNAKE_CASE__ = fake() SCREAMING_SNAKE_CASE__ = fake() return _Datasets(train=UpperCamelCase__ , validation=UpperCamelCase__ , test=UpperCamelCase__ ) if not source_url: # empty string check SCREAMING_SNAKE_CASE__ = DEFAULT_SOURCE_URL SCREAMING_SNAKE_CASE__ = """train-images-idx3-ubyte.gz""" SCREAMING_SNAKE_CASE__ = """train-labels-idx1-ubyte.gz""" SCREAMING_SNAKE_CASE__ = """t10k-images-idx3-ubyte.gz""" SCREAMING_SNAKE_CASE__ = """t10k-labels-idx1-ubyte.gz""" SCREAMING_SNAKE_CASE__ = _maybe_download( UpperCamelCase__ , UpperCamelCase__ , source_url + train_images_file ) with gfile.Open(UpperCamelCase__ , """rb""" ) as f: SCREAMING_SNAKE_CASE__ = _extract_images(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = _maybe_download( UpperCamelCase__ , UpperCamelCase__ , source_url + train_labels_file ) with gfile.Open(UpperCamelCase__ , """rb""" ) as f: SCREAMING_SNAKE_CASE__ = _extract_labels(UpperCamelCase__ , one_hot=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = _maybe_download( UpperCamelCase__ , UpperCamelCase__ , source_url + test_images_file ) with gfile.Open(UpperCamelCase__ , """rb""" ) as f: SCREAMING_SNAKE_CASE__ = _extract_images(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = _maybe_download( UpperCamelCase__ , UpperCamelCase__ , source_url + test_labels_file ) with gfile.Open(UpperCamelCase__ , """rb""" ) as f: SCREAMING_SNAKE_CASE__ = _extract_labels(UpperCamelCase__ , one_hot=UpperCamelCase__ ) if not 0 <= validation_size <= len(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = ( """Validation size should be between 0 and """ f'''{len(UpperCamelCase__ )}. Received: {validation_size}.''' ) raise ValueError(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = train_images[:validation_size] SCREAMING_SNAKE_CASE__ = train_labels[:validation_size] SCREAMING_SNAKE_CASE__ = train_images[validation_size:] SCREAMING_SNAKE_CASE__ = train_labels[validation_size:] SCREAMING_SNAKE_CASE__ = {"""dtype""": dtype, """reshape""": reshape, """seed""": seed} SCREAMING_SNAKE_CASE__ = _DataSet(UpperCamelCase__ , UpperCamelCase__ , **UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = _DataSet(UpperCamelCase__ , UpperCamelCase__ , **UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = _DataSet(UpperCamelCase__ , UpperCamelCase__ , **UpperCamelCase__ ) return _Datasets(train=UpperCamelCase__ , validation=UpperCamelCase__ , test=UpperCamelCase__ )
6
import numpy as np from numpy import ndarray from scipy.optimize import Bounds, LinearConstraint, minimize def lowerCAmelCase_ ( __a ) -> float: """simple docstring""" return np.dot(__a , __a ) class _SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__(self : List[str] , *, UpperCAmelCase_ : float = np.inf , UpperCAmelCase_ : str = "linear" , UpperCAmelCase_ : float = 0.0 , ) ->None: '''simple docstring''' lowerCamelCase__: Dict =regularization lowerCamelCase__: Any =gamma if kernel == "linear": lowerCamelCase__: Dict =self.__linear elif kernel == "rbf": if self.gamma == 0: raise ValueError("rbf kernel requires gamma") if not isinstance(self.gamma , (float, int)): raise ValueError("gamma must be float or int") if not self.gamma > 0: raise ValueError("gamma must be > 0") lowerCamelCase__: Tuple =self.__rbf # in the future, there could be a default value like in sklearn # sklear: def_gamma = 1/(n_features * X.var()) (wiki) # previously it was 1/(n_features) else: lowerCamelCase__: Optional[Any] =F"""Unknown kernel: {kernel}""" raise ValueError(UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : ndarray , UpperCAmelCase_ : ndarray) ->float: '''simple docstring''' return np.dot(UpperCAmelCase_ , UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : ndarray , UpperCAmelCase_ : ndarray) ->float: '''simple docstring''' return np.exp(-(self.gamma * norm_squared(vectora - vectora))) def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : list[ndarray] , UpperCAmelCase_ : ndarray) ->None: '''simple docstring''' lowerCamelCase__: Optional[Any] =observations lowerCamelCase__: Optional[int] =classes # using Wolfe's Dual to calculate w. # Primal problem: minimize 1/2*norm_squared(w) # constraint: yn(w . xn + b) >= 1 # # With l a vector # Dual problem: maximize sum_n(ln) - # 1/2 * sum_n(sum_m(ln*lm*yn*ym*xn . xm)) # constraint: self.C >= ln >= 0 # and sum_n(ln*yn) = 0 # Then we get w using w = sum_n(ln*yn*xn) # At the end we can get b ~= mean(yn - w . xn) # # Since we use kernels, we only need l_star to calculate b # and to classify observations ((lowerCamelCase__) , ): List[str] =np.shape(UpperCAmelCase_) def to_minimize(UpperCAmelCase_ : ndarray) -> float: lowerCamelCase__: int =0 ((lowerCamelCase__) , ): Optional[Any] =np.shape(UpperCAmelCase_) for i in range(UpperCAmelCase_): for j in range(UpperCAmelCase_): s += ( candidate[i] * candidate[j] * classes[i] * classes[j] * self.kernel(observations[i] , observations[j]) ) return 1 / 2 * s - sum(UpperCAmelCase_) lowerCamelCase__: List[Any] =LinearConstraint(UpperCAmelCase_ , 0 , 0) lowerCamelCase__: str =Bounds(0 , self.regularization) lowerCamelCase__: Union[str, Any] =minimize( UpperCAmelCase_ , np.ones(UpperCAmelCase_) , bounds=UpperCAmelCase_ , constraints=[ly_contraint]).x lowerCamelCase__: str =l_star # calculating mean offset of separation plane to points lowerCamelCase__: Tuple =0 for i in range(UpperCAmelCase_): for j in range(UpperCAmelCase_): s += classes[i] - classes[i] * self.optimum[i] * self.kernel( observations[i] , observations[j]) lowerCamelCase__: int =s / n def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : ndarray) ->int: '''simple docstring''' lowerCamelCase__: Optional[Any] =sum( self.optimum[n] * self.classes[n] * self.kernel(self.observations[n] , UpperCAmelCase_) for n in range(len(self.classes))) return 1 if s + self.offset >= 0 else -1 if __name__ == "__main__": import doctest doctest.testmod()
59
0
"""simple docstring""" def _snake_case ( _snake_case : list[list[float]] ) -> list[list[float]]: '''simple docstring''' _A = [] for data in source_data: for i, el in enumerate(_snake_case ): if len(_snake_case ) < i + 1: data_lists.append([] ) data_lists[i].append(float(_snake_case ) ) return data_lists def _snake_case ( _snake_case : list[list[float]] , _snake_case : list[int] ) -> list[list[float]]: '''simple docstring''' _A = [] for dlist, weight in zip(_snake_case , _snake_case ): _A = min(_snake_case ) _A = max(_snake_case ) _A = [] # for weight 0 score is 1 - actual score if weight == 0: for item in dlist: try: score.append(1 - ((item - mind) / (maxd - mind)) ) except ZeroDivisionError: score.append(1 ) elif weight == 1: for item in dlist: try: score.append((item - mind) / (maxd - mind) ) except ZeroDivisionError: score.append(0 ) # weight not 0 or 1 else: _A = F'''Invalid weight of {weight:f} provided''' raise ValueError(_snake_case ) score_lists.append(_snake_case ) return score_lists def _snake_case ( _snake_case : list[list[float]] ) -> list[float]: '''simple docstring''' _A = [0 for i in range(len(score_lists[0] ) )] for slist in score_lists: for j, ele in enumerate(_snake_case ): _A = final_scores[j] + ele return final_scores def _snake_case ( _snake_case : list[list[float]] , _snake_case : list[int] ) -> list[list[float]]: '''simple docstring''' _A = get_data(_snake_case ) _A = calculate_each_score(_snake_case , _snake_case ) _A = generate_final_scores(_snake_case ) # append scores to source data for i, ele in enumerate(_snake_case ): source_data[i].append(_snake_case ) return source_data
7
import logging import os from typing import Dict, List, Optional, Union import torch import torch.nn as nn from accelerate.utils.imports import ( is_abit_bnb_available, is_abit_bnb_available, is_bnb_available, ) from ..big_modeling import dispatch_model, init_empty_weights from .dataclasses import BnbQuantizationConfig from .modeling import ( find_tied_parameters, get_balanced_memory, infer_auto_device_map, load_checkpoint_in_model, offload_weight, set_module_tensor_to_device, ) if is_bnb_available(): import bitsandbytes as bnb from copy import deepcopy __A = logging.getLogger(__name__) def lowerCAmelCase_ ( __a , __a , __a = None , __a = None , __a = None , __a = None , __a = None , __a = False , ) -> str: """simple docstring""" lowerCamelCase__: int =bnb_quantization_config.load_in_abit lowerCamelCase__: Any =bnb_quantization_config.load_in_abit if load_in_abit and not is_abit_bnb_available(): raise ImportError( "You have a version of `bitsandbytes` that is not compatible with 8bit quantization," " make sure you have the latest version of `bitsandbytes` installed." ) if load_in_abit and not is_abit_bnb_available(): raise ValueError( "You have a version of `bitsandbytes` that is not compatible with 4bit quantization," "make sure you have the latest version of `bitsandbytes` installed." ) lowerCamelCase__: List[Any] =[] # custom device map if isinstance(__a , __a ) and len(device_map.keys() ) > 1: lowerCamelCase__: Optional[int] =[key for key, value in device_map.items() if value in ["disk", "cpu"]] # We keep some modules such as the lm_head in their original dtype for numerical stability reasons if bnb_quantization_config.skip_modules is None: lowerCamelCase__: Any =get_keys_to_not_convert(__a ) # add cpu modules to skip modules only for 4-bit modules if load_in_abit: bnb_quantization_config.skip_modules.extend(__a ) lowerCamelCase__: List[str] =bnb_quantization_config.skip_modules # We add the modules we want to keep in full precision if bnb_quantization_config.keep_in_fpaa_modules is None: lowerCamelCase__: List[Any] =[] lowerCamelCase__: int =bnb_quantization_config.keep_in_fpaa_modules modules_to_not_convert.extend(__a ) # compatibility with peft lowerCamelCase__: List[str] =load_in_abit lowerCamelCase__: int =load_in_abit lowerCamelCase__: Tuple =get_parameter_device(__a ) if model_device.type != "meta": # quantization of an already loaded model logger.warning( "It is not recommended to quantize a loaded model. " "The model should be instantiated under the `init_empty_weights` context manager." ) lowerCamelCase__: Tuple =replace_with_bnb_layers(__a , __a , modules_to_not_convert=__a ) # convert param to the right dtype lowerCamelCase__: Dict =bnb_quantization_config.torch_dtype for name, param in model.state_dict().items(): if any(module_to_keep_in_fpaa in name for module_to_keep_in_fpaa in keep_in_fpaa_modules ): param.to(torch.floataa ) if param.dtype != torch.floataa: lowerCamelCase__: str =name.replace(".weight" , "" ).replace(".bias" , "" ) lowerCamelCase__: Optional[Any] =getattr(__a , __a , __a ) if param is not None: param.to(torch.floataa ) elif torch.is_floating_point(__a ): param.to(__a ) if model_device.type == "cuda": # move everything to cpu in the first place because we can't do quantization if the weights are already on cuda model.cuda(torch.cuda.current_device() ) torch.cuda.empty_cache() elif torch.cuda.is_available(): model.to(torch.cuda.current_device() ) else: raise RuntimeError("No GPU found. A GPU is needed for quantization." ) logger.info( F"""The model device type is {model_device.type}. However, cuda is needed for quantization.""" "We move the model to cuda." ) return model elif weights_location is None: raise RuntimeError( F"""`weights_location` needs to be the folder path containing the weights of the model, but we found {weights_location} """ ) else: with init_empty_weights(): lowerCamelCase__: str =replace_with_bnb_layers( __a , __a , modules_to_not_convert=__a ) lowerCamelCase__: Optional[Any] =get_quantized_model_device_map( __a , __a , __a , max_memory=__a , no_split_module_classes=__a , ) if offload_state_dict is None and device_map is not None and "disk" in device_map.values(): lowerCamelCase__: Any =True lowerCamelCase__: List[str] =any(x in list(device_map.values() ) for x in ["cpu", "disk"] ) load_checkpoint_in_model( __a , __a , __a , dtype=bnb_quantization_config.torch_dtype , offload_folder=__a , offload_state_dict=__a , keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules , offload_abit_bnb=load_in_abit and offload , ) return dispatch_model(__a , device_map=__a , offload_dir=__a ) def lowerCAmelCase_ ( __a , __a , __a=None , __a=None , __a=None ) -> str: """simple docstring""" if device_map is None: if torch.cuda.is_available(): lowerCamelCase__: str ={"": torch.cuda.current_device()} else: raise RuntimeError("No GPU found. A GPU is needed for quantization." ) logger.info("The device_map was not initialized." "Setting device_map to `{'':torch.cuda.current_device()}`." ) if isinstance(__a , __a ): if device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]: raise ValueError( "If passing a string for `device_map`, please choose 'auto', 'balanced', 'balanced_low_0' or " "'sequential'." ) lowerCamelCase__: Optional[int] ={} special_dtypes.update( { name: bnb_quantization_config.torch_dtype for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.skip_modules ) } ) special_dtypes.update( { name: torch.floataa for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.keep_in_fpaa_modules ) } ) lowerCamelCase__: Optional[Any] ={} lowerCamelCase__: str =special_dtypes lowerCamelCase__: List[str] =no_split_module_classes lowerCamelCase__: Dict =bnb_quantization_config.target_dtype # get max_memory for each device. if device_map != "sequential": lowerCamelCase__: Optional[Any] =get_balanced_memory( __a , low_zero=(device_map == "balanced_low_0") , max_memory=__a , **__a , ) lowerCamelCase__: Union[str, Any] =max_memory lowerCamelCase__: Dict =infer_auto_device_map(__a , **__a ) if isinstance(__a , __a ): # check if don't have any quantized module on the cpu lowerCamelCase__: Union[str, Any] =bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules lowerCamelCase__: List[Any] ={ key: device_map[key] for key in device_map.keys() if key not in modules_not_to_convert } for device in ["cpu", "disk"]: if device in device_map_without_some_modules.values(): if bnb_quantization_config.load_in_abit: raise ValueError( "\n Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit\n the quantized model. If you want to dispatch the model on the CPU or the disk while keeping\n these modules in `torch_dtype`, you need to pass a custom `device_map` to\n `load_and_quantize_model`. Check\n https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk\n for more details.\n " ) else: logger.info( "Some modules are are offloaded to the CPU or the disk. Note that these modules will be converted to 8-bit" ) del device_map_without_some_modules return device_map def lowerCAmelCase_ ( __a , __a , __a=None , __a=None ) -> Optional[Any]: """simple docstring""" if modules_to_not_convert is None: lowerCamelCase__: List[Any] =[] lowerCamelCase__ , lowerCamelCase__: Any =_replace_with_bnb_layers( __a , __a , __a , __a ) if not has_been_replaced: logger.warning( "You are loading your model in 8bit or 4bit but no linear modules were found in your model." " this can happen for some architectures such as gpt2 that uses Conv1D instead of Linear layers." " Please double check your model architecture, or submit an issue on github if you think this is" " a bug." ) return model def lowerCAmelCase_ ( __a , __a , __a=None , __a=None , ) -> List[Any]: """simple docstring""" lowerCamelCase__: Optional[int] =False for name, module in model.named_children(): if current_key_name is None: lowerCamelCase__: Optional[Any] =[] current_key_name.append(__a ) if isinstance(__a , nn.Linear ) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` lowerCamelCase__: List[str] =".".join(__a ) lowerCamelCase__: Optional[Any] =True for key in modules_to_not_convert: if ( (key in current_key_name_str) and (key + "." in current_key_name_str) ) or key == current_key_name_str: lowerCamelCase__: int =False break if proceed: # Load bnb module with empty weight and replace ``nn.Linear` module if bnb_quantization_config.load_in_abit: lowerCamelCase__: Optional[int] =bnb.nn.LinearabitLt( module.in_features , module.out_features , module.bias is not None , has_fpaa_weights=__a , threshold=bnb_quantization_config.llm_inta_threshold , ) elif bnb_quantization_config.load_in_abit: lowerCamelCase__: Dict =bnb.nn.Linearabit( module.in_features , module.out_features , module.bias is not None , bnb_quantization_config.bnb_abit_compute_dtype , compress_statistics=bnb_quantization_config.bnb_abit_use_double_quant , quant_type=bnb_quantization_config.bnb_abit_quant_type , ) else: raise ValueError("load_in_8bit and load_in_4bit can't be both False" ) lowerCamelCase__: Dict =module.weight.data if module.bias is not None: lowerCamelCase__: List[Any] =module.bias.data bnb_module.requires_grad_(__a ) setattr(__a , __a , __a ) lowerCamelCase__: int =True if len(list(module.children() ) ) > 0: lowerCamelCase__ , lowerCamelCase__: List[str] =_replace_with_bnb_layers( __a , __a , __a , __a ) lowerCamelCase__: Union[str, Any] =has_been_replaced | _has_been_replaced # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def lowerCAmelCase_ ( __a ) -> List[Any]: """simple docstring""" with init_empty_weights(): lowerCamelCase__: Any =deepcopy(__a ) # this has 0 cost since it is done inside `init_empty_weights` context manager` lowerCamelCase__: str =find_tied_parameters(__a ) # For compatibility with Accelerate < 0.18 if isinstance(__a , __a ): lowerCamelCase__: int =sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() ) else: lowerCamelCase__: str =sum(__a , [] ) lowerCamelCase__: str =len(__a ) > 0 # Check if it is a base model lowerCamelCase__: Optional[Any] =False if hasattr(__a , "base_model_prefix" ): lowerCamelCase__: Union[str, Any] =not hasattr(__a , model.base_model_prefix ) # Ignore this for base models (BertModel, GPT2Model, etc.) if (not has_tied_params) and is_base_model: return [] # otherwise they have an attached head lowerCamelCase__: Optional[int] =list(model.named_children() ) lowerCamelCase__: Optional[int] =[list_modules[-1][0]] # add last module together with tied weights lowerCamelCase__: Union[str, Any] =set(__a ) - set(__a ) lowerCamelCase__: List[str] =list(set(__a ) ) + list(__a ) # remove ".weight" from the keys lowerCamelCase__: List[Any] =[".weight", ".bias"] lowerCamelCase__: Tuple =[] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: lowerCamelCase__: Optional[Any] =name.replace(__a , "" ) filtered_module_names.append(__a ) return filtered_module_names def lowerCAmelCase_ ( __a ) -> Tuple: """simple docstring""" for m in model.modules(): if isinstance(__a , bnb.nn.Linearabit ): return True return False def lowerCAmelCase_ ( __a ) -> List[str]: """simple docstring""" return next(parameter.parameters() ).device def lowerCAmelCase_ ( __a , __a , __a , __a , __a , __a , __a ) -> Any: """simple docstring""" if fpaa_statistics is None: set_module_tensor_to_device(__a , __a , 0 , dtype=__a , value=__a ) lowerCamelCase__: Dict =param_name lowerCamelCase__: Tuple =model if "." in tensor_name: lowerCamelCase__: Any =tensor_name.split("." ) for split in splits[:-1]: lowerCamelCase__: Any =getattr(__a , __a ) if new_module is None: raise ValueError(F"""{module} has no attribute {split}.""" ) lowerCamelCase__: str =new_module lowerCamelCase__: int =splits[-1] # offload weights lowerCamelCase__: str =False offload_weight(module._parameters[tensor_name] , __a , __a , index=__a ) if hasattr(module._parameters[tensor_name] , "SCB" ): offload_weight( module._parameters[tensor_name].SCB , param_name.replace("weight" , "SCB" ) , __a , index=__a , ) else: offload_weight(__a , __a , __a , index=__a ) offload_weight(__a , param_name.replace("weight" , "SCB" ) , __a , index=__a ) set_module_tensor_to_device(__a , __a , "meta" , dtype=__a , value=torch.empty(*param.size() ) )
59
0
'''simple docstring''' import argparse import glob import logging import os import time from argparse import Namespace import numpy as np import torch from lightning_base import BaseTransformer, add_generic_args, generic_train from torch.utils.data import DataLoader, TensorDataset from transformers import glue_compute_metrics as compute_metrics from transformers import glue_convert_examples_to_features as convert_examples_to_features from transformers import glue_output_modes, glue_tasks_num_labels from transformers import glue_processors as processors lowercase__ : Optional[Any] = logging.getLogger(__name__) class SCREAMING_SNAKE_CASE (a__ ): lowerCAmelCase = '''sequence-classification''' def __init__( self , _UpperCAmelCase): '''simple docstring''' if type(_UpperCAmelCase) == dict: __A : List[str] = Namespace(**_UpperCAmelCase) __A : str = glue_output_modes[hparams.task] __A : str = glue_tasks_num_labels[hparams.task] super().__init__(_UpperCAmelCase , _UpperCAmelCase , self.mode) def SCREAMING_SNAKE_CASE ( self , **_UpperCAmelCase): '''simple docstring''' return self.model(**_UpperCAmelCase) def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase , _UpperCAmelCase): '''simple docstring''' __A : int = {'input_ids': batch[0], 'attention_mask': batch[1], 'labels': batch[3]} if self.config.model_type not in ["distilbert", "bart"]: __A : Any = batch[2] if self.config.model_type in ['bert', 'xlnet', 'albert'] else None __A : str = self(**_UpperCAmelCase) __A : Optional[int] = outputs[0] __A : Optional[int] = self.trainer.lr_schedulers[0]['scheduler'] __A : Tuple = {'loss': loss, 'rate': lr_scheduler.get_last_lr()[-1]} return {"loss": loss, "log": tensorboard_logs} def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' __A : Any = self.hparams __A : str = processors[args.task]() __A : Tuple = processor.get_labels() for mode in ["train", "dev"]: __A : Optional[int] = self._feature_file(_UpperCAmelCase) if os.path.exists(_UpperCAmelCase) and not args.overwrite_cache: logger.info('Loading features from cached file %s' , _UpperCAmelCase) else: logger.info('Creating features from dataset file at %s' , args.data_dir) __A : Dict = ( processor.get_dev_examples(args.data_dir) if mode == 'dev' else processor.get_train_examples(args.data_dir) ) __A : List[str] = convert_examples_to_features( _UpperCAmelCase , self.tokenizer , max_length=args.max_seq_length , label_list=self.labels , output_mode=args.glue_output_mode , ) logger.info('Saving features into cached file %s' , _UpperCAmelCase) torch.save(_UpperCAmelCase , _UpperCAmelCase) def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = False): '''simple docstring''' __A : Dict = 'dev' if mode == 'test' else mode __A : Any = self._feature_file(_UpperCAmelCase) logger.info('Loading features from cached file %s' , _UpperCAmelCase) __A : Optional[int] = torch.load(_UpperCAmelCase) __A : Any = torch.tensor([f.input_ids for f in features] , dtype=torch.long) __A : List[Any] = torch.tensor([f.attention_mask for f in features] , dtype=torch.long) __A : Any = torch.tensor([f.token_type_ids for f in features] , dtype=torch.long) if self.hparams.glue_output_mode == "classification": __A : int = torch.tensor([f.label for f in features] , dtype=torch.long) elif self.hparams.glue_output_mode == "regression": __A : List[str] = torch.tensor([f.label for f in features] , dtype=torch.float) return DataLoader( TensorDataset(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) , batch_size=_UpperCAmelCase , shuffle=_UpperCAmelCase , ) def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase , _UpperCAmelCase): '''simple docstring''' __A : List[str] = {'input_ids': batch[0], 'attention_mask': batch[1], 'labels': batch[3]} if self.config.model_type not in ["distilbert", "bart"]: __A : Any = batch[2] if self.config.model_type in ['bert', 'xlnet', 'albert'] else None __A : str = self(**_UpperCAmelCase) __A ,__A : Optional[int] = outputs[:2] __A : Dict = logits.detach().cpu().numpy() __A : Union[str, Any] = inputs['labels'].detach().cpu().numpy() return {"val_loss": tmp_eval_loss.detach().cpu(), "pred": preds, "target": out_label_ids} def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase): '''simple docstring''' __A : List[str] = torch.stack([x['val_loss'] for x in outputs]).mean().detach().cpu().item() __A : Optional[Any] = np.concatenate([x['pred'] for x in outputs] , axis=0) if self.hparams.glue_output_mode == "classification": __A : str = np.argmax(_UpperCAmelCase , axis=1) elif self.hparams.glue_output_mode == "regression": __A : Any = np.squeeze(_UpperCAmelCase) __A : Union[str, Any] = np.concatenate([x['target'] for x in outputs] , axis=0) __A : List[Any] = [[] for _ in range(out_label_ids.shape[0])] __A : List[str] = [[] for _ in range(out_label_ids.shape[0])] __A : int = {**{'val_loss': val_loss_mean}, **compute_metrics(self.hparams.task , _UpperCAmelCase , _UpperCAmelCase)} __A : Optional[Any] = dict(results.items()) __A : Tuple = results return ret, preds_list, out_label_list def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase): '''simple docstring''' __A ,__A ,__A : str = self._eval_end(_UpperCAmelCase) __A : int = ret['log'] return {"val_loss": logs["val_loss"], "log": logs, "progress_bar": logs} def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase): '''simple docstring''' __A ,__A ,__A : List[str] = self._eval_end(_UpperCAmelCase) __A : Union[str, Any] = ret['log'] # `val_loss` is the key returned by `self._eval_end()` but actually refers to `test_loss` return {"avg_test_loss": logs["val_loss"], "log": logs, "progress_bar": logs} @staticmethod def SCREAMING_SNAKE_CASE ( _UpperCAmelCase , _UpperCAmelCase): '''simple docstring''' BaseTransformer.add_model_specific_args(_UpperCAmelCase , _UpperCAmelCase) parser.add_argument( '--max_seq_length' , default=128 , type=_UpperCAmelCase , help=( 'The maximum total input sequence length after tokenization. Sequences longer ' 'than this will be truncated, sequences shorter will be padded.' ) , ) parser.add_argument( '--task' , default='' , type=_UpperCAmelCase , required=_UpperCAmelCase , help='The GLUE task to run' , ) parser.add_argument( '--gpus' , default=0 , type=_UpperCAmelCase , help='The number of GPUs allocated for this, it is by default 0 meaning none' , ) parser.add_argument( '--overwrite_cache' , action='store_true' , help='Overwrite the cached training and evaluation sets') return parser def _lowerCAmelCase ( ) -> List[Any]: __A : str = argparse.ArgumentParser() add_generic_args(__snake_case , os.getcwd() ) __A : Union[str, Any] = GLUETransformer.add_model_specific_args(__snake_case , os.getcwd() ) __A : Any = parser.parse_args() # If output_dir not provided, a folder will be generated in pwd if args.output_dir is None: __A : Optional[int] = os.path.join( './results' , f'{args.task}_{time.strftime("%Y%m%d_%H%M%S" )}' , ) os.makedirs(args.output_dir ) __A : int = GLUETransformer(__snake_case ) __A : int = generic_train(__snake_case , __snake_case ) # Optionally, predict on dev set and write to output_dir if args.do_predict: __A : Union[str, Any] = sorted(glob.glob(os.path.join(args.output_dir , 'checkpoint-epoch=*.ckpt' ) , recursive=__snake_case ) ) __A : Tuple = model.load_from_checkpoint(checkpoints[-1] ) return trainer.test(__snake_case ) if __name__ == "__main__": main()
8
from __future__ import annotations from math import pi def lowerCAmelCase_ ( __a , __a , __a ) -> dict[str, float]: """simple docstring""" if (inductance, frequency, reactance).count(0 ) != 1: raise ValueError("One and only one argument must be 0" ) if inductance < 0: raise ValueError("Inductance cannot be negative" ) if frequency < 0: raise ValueError("Frequency cannot be negative" ) if reactance < 0: raise ValueError("Inductive reactance cannot be negative" ) if inductance == 0: return {"inductance": reactance / (2 * pi * frequency)} elif frequency == 0: return {"frequency": reactance / (2 * pi * inductance)} elif reactance == 0: return {"reactance": 2 * pi * frequency * inductance} else: raise ValueError("Exactly one argument must be 0" ) if __name__ == "__main__": import doctest doctest.testmod()
59
0
import warnings from .generation import TFGenerationMixin class __lowerCAmelCase ( UpperCAmelCase_ ): """simple docstring""" warnings.warn( "Importing `TFGenerationMixin` from `src/transformers/generation_tf_utils.py` is deprecated and will " "be removed in Transformers v5. Import as `from transformers import TFGenerationMixin` instead." , UpperCAmelCase_ , )
9
import pyarrow.parquet as pq import pytest from datasets import Audio, Dataset, DatasetDict, Features, NamedSplit, Sequence, Value, config from datasets.features.image import Image from datasets.io.parquet import ParquetDatasetReader, ParquetDatasetWriter, get_writer_batch_size from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def lowerCAmelCase_ ( __a , __a ) -> List[Any]: """simple docstring""" assert isinstance(__a , __a ) 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 lowerCAmelCase_ ( __a , __a , __a ) -> Any: """simple docstring""" lowerCamelCase__: Any =tmp_path / "cache" lowerCamelCase__: Optional[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(): lowerCamelCase__: Tuple =ParquetDatasetReader(__a , cache_dir=__a , keep_in_memory=__a ).read() _check_parquet_dataset(__a , __a ) @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 lowerCAmelCase_ ( __a , __a , __a ) -> List[str]: """simple docstring""" lowerCamelCase__: int =tmp_path / "cache" lowerCamelCase__: Tuple ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: Union[str, Any] =features.copy() if features else default_expected_features lowerCamelCase__: Optional[int] =( Features({feature: Value(__a ) for feature, dtype in features.items()} ) if features is not None else None ) lowerCamelCase__: int =ParquetDatasetReader(__a , features=__a , cache_dir=__a ).read() _check_parquet_dataset(__a , __a ) @pytest.mark.parametrize("split" , [None, NamedSplit("train" ), "train", "test"] ) def lowerCAmelCase_ ( __a , __a , __a ) -> Any: """simple docstring""" lowerCamelCase__: Any =tmp_path / "cache" lowerCamelCase__: Optional[Any] ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: Optional[Any] =ParquetDatasetReader(__a , cache_dir=__a , split=__a ).read() _check_parquet_dataset(__a , __a ) assert dataset.split == split if split else "train" @pytest.mark.parametrize("path_type" , [str, list] ) def lowerCAmelCase_ ( __a , __a , __a ) -> int: """simple docstring""" if issubclass(__a , __a ): lowerCamelCase__: List[Any] =parquet_path elif issubclass(__a , __a ): lowerCamelCase__: str =[parquet_path] lowerCamelCase__: Tuple =tmp_path / "cache" lowerCamelCase__: Optional[Any] ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: int =ParquetDatasetReader(__a , cache_dir=__a ).read() _check_parquet_dataset(__a , __a ) def lowerCAmelCase_ ( __a , __a , __a=("train",) ) -> Dict: """simple docstring""" assert isinstance(__a , __a ) for split in splits: lowerCamelCase__: Tuple =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 lowerCAmelCase_ ( __a , __a , __a ) -> Any: """simple docstring""" lowerCamelCase__: List[Any] =tmp_path / "cache" lowerCamelCase__: Optional[Any] ={"col_1": "string", "col_2": "int64", "col_3": "float64"} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): lowerCamelCase__: Tuple =ParquetDatasetReader( {"train": parquet_path} , cache_dir=__a , keep_in_memory=__a ).read() _check_parquet_datasetdict(__a , __a ) @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 lowerCAmelCase_ ( __a , __a , __a ) -> Optional[Any]: """simple docstring""" lowerCamelCase__: Tuple =tmp_path / "cache" lowerCamelCase__: Optional[int] ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: List[Any] =features.copy() if features else default_expected_features lowerCamelCase__: int =( Features({feature: Value(__a ) for feature, dtype in features.items()} ) if features is not None else None ) lowerCamelCase__: Optional[Any] =ParquetDatasetReader({"train": parquet_path} , features=__a , cache_dir=__a ).read() _check_parquet_datasetdict(__a , __a ) @pytest.mark.parametrize("split" , [None, NamedSplit("train" ), "train", "test"] ) def lowerCAmelCase_ ( __a , __a , __a ) -> Union[str, Any]: """simple docstring""" if split: lowerCamelCase__: Any ={split: parquet_path} else: lowerCamelCase__: int ="train" lowerCamelCase__: Any ={"train": parquet_path, "test": parquet_path} lowerCamelCase__: str =tmp_path / "cache" lowerCamelCase__: Any ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: int =ParquetDatasetReader(__a , cache_dir=__a ).read() _check_parquet_datasetdict(__a , __a , splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() ) def lowerCAmelCase_ ( __a , __a ) -> int: """simple docstring""" lowerCamelCase__: List[str] =ParquetDatasetWriter(__a , tmp_path / "foo.parquet" ) assert writer.write() > 0 lowerCamelCase__: List[str] =pq.ParquetFile(tmp_path / "foo.parquet" ) lowerCamelCase__: List[str] =pf.read() assert dataset.data.table == output_table def lowerCAmelCase_ ( __a , __a ) -> List[str]: """simple docstring""" lowerCamelCase__: List[str] =str(shared_datadir / "test_image_rgb.jpg" ) lowerCamelCase__: Union[str, Any] ={"image": [image_path]} lowerCamelCase__: Optional[Any] =Features({"image": Image()} ) lowerCamelCase__: Optional[int] =Dataset.from_dict(__a , features=__a ) lowerCamelCase__: Optional[int] =ParquetDatasetWriter(__a , tmp_path / "foo.parquet" ) assert writer.write() > 0 lowerCamelCase__: Dict =Dataset.from_parquet(str(tmp_path / "foo.parquet" ) ) assert dataset.features == reloaded_dataset.features lowerCamelCase__: Optional[Any] =ParquetDatasetReader(str(tmp_path / "foo.parquet" ) , streaming=__a ).read() assert dataset.features == reloaded_iterable_dataset.features @pytest.mark.parametrize( "feature, expected" , [ (Features({"foo": Value("int32" )} ), None), (Features({"image": Image(), "foo": Value("int32" )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS), (Features({"nested": Sequence(Audio() )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS), ] , ) def lowerCAmelCase_ ( __a , __a ) -> Optional[Any]: """simple docstring""" assert get_writer_batch_size(__a ) == expected
59
0
import logging import os from logging import ( CRITICAL, # NOQA DEBUG, # NOQA ERROR, # NOQA FATAL, # NOQA INFO, # NOQA NOTSET, # NOQA WARN, # NOQA WARNING, # NOQA ) from typing import Optional from tqdm import auto as tqdm_lib _lowerCAmelCase = { "debug": logging.DEBUG, "info": logging.INFO, "warning": logging.WARNING, "error": logging.ERROR, "critical": logging.CRITICAL, } _lowerCAmelCase = logging.WARNING def _snake_case ( ): _UpperCamelCase = os.getenv('''DATASETS_VERBOSITY''' , __snake_case ) if env_level_str: if env_level_str in log_levels: return log_levels[env_level_str] else: logging.getLogger().warning( f"""Unknown option DATASETS_VERBOSITY={env_level_str}, """ f"""has to be one of: { ", ".join(log_levels.keys() ) }""" ) return _default_log_level def _snake_case ( ): return __name__.split('''.''' )[0] def _snake_case ( ): return logging.getLogger(_get_library_name() ) def _snake_case ( ): # Apply our default configuration to the library root logger. _UpperCamelCase = _get_library_root_logger() library_root_logger.setLevel(_get_default_logging_level() ) def _snake_case ( ): _UpperCamelCase = _get_library_root_logger() library_root_logger.setLevel(logging.NOTSET ) def _snake_case ( __snake_case = None ): if name is None: _UpperCamelCase = _get_library_name() return logging.getLogger(__snake_case ) def _snake_case ( ): return _get_library_root_logger().getEffectiveLevel() def _snake_case ( __snake_case ): _get_library_root_logger().setLevel(__snake_case ) def _snake_case ( ): return set_verbosity(__snake_case ) def _snake_case ( ): return set_verbosity(__snake_case ) def _snake_case ( ): return set_verbosity(__snake_case ) def _snake_case ( ): return set_verbosity(__snake_case ) def _snake_case ( ): _UpperCamelCase = False def _snake_case ( ): _UpperCamelCase = True # Configure the library root logger at the module level (singleton-like) _configure_library_root_logger() class lowerCAmelCase_ : def __init__( self : Any , *_A : Union[str, Any] , **_A : str ): # pylint: disable=unused-argument _UpperCamelCase = args[0] if args else None def __iter__( self : Optional[Any] ): return iter(self._iterator ) def __getattr__( self : Any , _A : Optional[int] ): def empty_fn(*_A : List[Any] , **_A : List[str] ): # pylint: disable=unused-argument return return empty_fn def __enter__( self : str ): return self def __exit__( self : str , _A : List[str] , _A : Dict , _A : str ): return _lowerCAmelCase = True class lowerCAmelCase_ : def __call__( self : int , *_A : Union[str, Any] , _A : Optional[int]=False , **_A : Dict ): if _tqdm_active and not disable: return tqdm_lib.tqdm(*_A , **_A ) else: return EmptyTqdm(*_A , **_A ) def UpperCamelCase_ ( self : int , *_A : str , **_A : Optional[int] ): _UpperCamelCase = None if _tqdm_active: return tqdm_lib.tqdm.set_lock(*_A , **_A ) def UpperCamelCase_ ( self : Union[str, Any] ): if _tqdm_active: return tqdm_lib.tqdm.get_lock() _lowerCAmelCase = _tqdm_cls() def _snake_case ( ): global _tqdm_active return bool(_tqdm_active ) def _snake_case ( ): global _tqdm_active _UpperCamelCase = True def _snake_case ( ): global _tqdm_active _UpperCamelCase = False
10
import unittest from transformers.models.xlm_prophetnet.tokenization_xlm_prophetnet import SPIECE_UNDERLINE, XLMProphetNetTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin __A = get_tests_dir("fixtures/test_sentencepiece.model") @require_sentencepiece class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowercase_ = XLMProphetNetTokenizer lowercase_ = False lowercase_ = True def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Optional[Any]: '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing lowerCamelCase__: Any =XLMProphetNetTokenizer(UpperCAmelCase_ , keep_accents=UpperCAmelCase_) tokenizer.save_pretrained(self.tmpdirname) def SCREAMING_SNAKE_CASE_ (self : str) ->str: '''simple docstring''' lowerCamelCase__: List[Any] ="[PAD]" lowerCamelCase__: Tuple =0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCAmelCase_) , UpperCAmelCase_) self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCAmelCase_) , UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Dict) ->int: '''simple docstring''' lowerCamelCase__: List[Any] =list(self.get_tokenizer().get_vocab().keys()) self.assertEqual(vocab_keys[0] , "[PAD]") self.assertEqual(vocab_keys[1] , "[CLS]") self.assertEqual(vocab_keys[-1] , "j") self.assertEqual(len(UpperCAmelCase_) , 1_012) def SCREAMING_SNAKE_CASE_ (self : Dict) ->Union[str, Any]: '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 1_012) def SCREAMING_SNAKE_CASE_ (self : Any) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Optional[Any] =XLMProphetNetTokenizer(UpperCAmelCase_ , keep_accents=UpperCAmelCase_) lowerCamelCase__: 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]] , ) lowerCamelCase__: Optional[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", "é", ".", ] , ) lowerCamelCase__: Any =tokenizer.convert_tokens_to_ids(UpperCAmelCase_) self.assertListEqual( UpperCAmelCase_ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, -9, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, -9, 4] ] , ) lowerCamelCase__: 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]", ".", ] , ) @cached_property def SCREAMING_SNAKE_CASE_ (self : Any) ->int: '''simple docstring''' return XLMProphetNetTokenizer.from_pretrained("microsoft/xprophetnet-large-wiki100-cased") @slow def SCREAMING_SNAKE_CASE_ (self : List[str]) ->List[str]: '''simple docstring''' lowerCamelCase__: Optional[int] ="Hello World!" lowerCamelCase__: Dict =[35_389, 6_672, 49, 2] self.assertListEqual(UpperCAmelCase_ , self.big_tokenizer.encode(UpperCAmelCase_)) @slow def SCREAMING_SNAKE_CASE_ (self : int) ->Union[str, Any]: '''simple docstring''' lowerCamelCase__: Any ={"input_ids": [[11_073, 82_783, 18, 26, 82_783, 549, 51_540, 248, 17_209, 1_301, 217, 20, 215_186, 1_325, 147, 17_209, 1_301, 217, 20, 56_370, 53, 122_020, 20, 16_477, 27, 87_355, 4_548, 20, 4_728, 78_392, 17, 159_969, 18, 26, 24_491, 629, 15, 538, 22_704, 5_439, 15, 2_788, 24_491, 9_885, 15, 43_534, 605, 15, 814, 18_403, 33_200, 29, 15, 43_534, 24_458, 12_410, 111, 24_966, 83_669, 9_637, 144_068, 26, 850, 22_346, 27, 147, 24_966, 83_669, 83_490, 26, 39_113, 735, 27, 689, 656, 2_800, 1_339, 4_600, 53, 122_020, 115_785, 34, 816, 1_339, 46_887, 18, 147, 53_905, 1_951, 42_238, 41_170, 17_732, 834, 436, 15, 27_523, 98_733, 217, 147, 5_542, 4_981, 930, 17_347, 16, 2], [20_091, 629, 94, 82_786, 58, 490, 20, 1_528, 84, 53_905, 344, 80_592, 110_128, 18_822, 5_267, 1_306, 62, 152_537, 308, 7_997, 401, 124_427, 549, 35_442, 225, 109, 15_055, 25_748, 147, 7_119, 43_712, 34, 767, 135_366, 18, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [592, 63_784, 119_466, 17, 147_808, 88_214, 18, 656, 81, 32, 3_296, 10_280, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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="microsoft/xprophetnet-large-wiki100-cased" , revision="1acad1643ddd54a44df6a1b797ada8373685d90e" , )
59
0
'''simple docstring''' import math def lowerCAmelCase (__A): """simple docstring""" _a = [True] * n _a = False _a = False _a = True for i in range(3 , int(n**0.5 + 1) , 2): _a = i * 2 while index < n: _a = False _a = index + i _a = [2] for i in range(3 , __A , 2): if is_prime[i]: primes.append(__A) return primes def lowerCAmelCase (__A = 999_966_663_333): """simple docstring""" _a = math.floor(math.sqrt(__A)) + 100 _a = prime_sieve(__A) _a = 0 _a = 0 _a = primes[prime_index] while (last_prime**2) <= limit: _a = primes[prime_index + 1] _a = last_prime**2 _a = next_prime**2 # Get numbers divisible by lps(current) _a = lower_bound + last_prime while upper_bound > current <= limit: matches_sum += current current += last_prime # Reset the upper_bound while (upper_bound - next_prime) > limit: upper_bound -= next_prime # Add the numbers divisible by ups(current) _a = upper_bound - next_prime while current > lower_bound: matches_sum += current current -= next_prime # Remove the numbers divisible by both ups and lps _a = 0 while upper_bound > current <= limit: if current <= lower_bound: # Increment the current number current += last_prime * next_prime continue if current > limit: break # Remove twice since it was added by both ups and lps matches_sum -= current * 2 # Increment the current number current += last_prime * next_prime # Setup for next pair _a = next_prime prime_index += 1 return matches_sum if __name__ == "__main__": print(solution())
11
import os import shutil import tempfile import unittest import numpy as np from transformers import AutoTokenizer, BarkProcessor from transformers.testing_utils import require_torch, slow @require_torch class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ (self : List[str]) ->str: '''simple docstring''' lowerCamelCase__: Union[str, Any] ="ylacombe/bark-small" lowerCamelCase__: Tuple =tempfile.mkdtemp() lowerCamelCase__: Tuple ="en_speaker_1" lowerCamelCase__: Optional[int] ="This is a test string" lowerCamelCase__: List[str] ="speaker_embeddings_path.json" lowerCamelCase__: int ="speaker_embeddings" def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , **UpperCAmelCase_ : Any) ->Tuple: '''simple docstring''' return AutoTokenizer.from_pretrained(self.checkpoint , **UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[str]) ->Union[str, Any]: '''simple docstring''' shutil.rmtree(self.tmpdirname) def SCREAMING_SNAKE_CASE_ (self : int) ->Any: '''simple docstring''' lowerCamelCase__: List[Any] =self.get_tokenizer() lowerCamelCase__: List[str] =BarkProcessor(tokenizer=UpperCAmelCase_) processor.save_pretrained(self.tmpdirname) lowerCamelCase__: Dict =BarkProcessor.from_pretrained(self.tmpdirname) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab()) @slow def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Tuple: '''simple docstring''' lowerCamelCase__: Tuple =BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) processor.save_pretrained( self.tmpdirname , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , speaker_embeddings_directory=self.speaker_embeddings_directory , ) lowerCamelCase__: Dict =self.get_tokenizer(bos_token="(BOS)" , eos_token="(EOS)") lowerCamelCase__: Any =BarkProcessor.from_pretrained( self.tmpdirname , self.speaker_embeddings_dict_path , bos_token="(BOS)" , eos_token="(EOS)" , ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab()) def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->int: '''simple docstring''' lowerCamelCase__: Any =BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) lowerCamelCase__: List[str] =35 lowerCamelCase__: Optional[Any] =2 lowerCamelCase__: Optional[Any] =8 lowerCamelCase__: Optional[int] ={ "semantic_prompt": np.ones(UpperCAmelCase_), "coarse_prompt": np.ones((nb_codebooks_coarse, seq_len)), "fine_prompt": np.ones((nb_codebooks_total, seq_len)), } # test providing already loaded voice_preset lowerCamelCase__: Any =processor(text=self.input_string , voice_preset=UpperCAmelCase_) lowerCamelCase__: int =inputs["history_prompt"] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(UpperCAmelCase_ , np.array([])).tolist()) # test loading voice preset from npz file lowerCamelCase__: Union[str, Any] =os.path.join(self.tmpdirname , "file.npz") np.savez(UpperCAmelCase_ , **UpperCAmelCase_) lowerCamelCase__: Tuple =processor(text=self.input_string , voice_preset=UpperCAmelCase_) lowerCamelCase__: Optional[Any] =inputs["history_prompt"] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(UpperCAmelCase_ , np.array([])).tolist()) # test loading voice preset from the hub lowerCamelCase__: Any =processor(text=self.input_string , voice_preset=self.voice_preset) def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Union[str, Any]: '''simple docstring''' lowerCamelCase__: str =self.get_tokenizer() lowerCamelCase__: Dict =BarkProcessor(tokenizer=UpperCAmelCase_) lowerCamelCase__: List[Any] =processor(text=self.input_string) lowerCamelCase__: Optional[int] =tokenizer( self.input_string , padding="max_length" , max_length=256 , add_special_tokens=UpperCAmelCase_ , return_attention_mask=UpperCAmelCase_ , return_token_type_ids=UpperCAmelCase_ , ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key].squeeze().tolist())
59
0
from collections import defaultdict from math import ceil, sqrt def UpperCamelCase ( lowercase_ = 1_00_00_00 , lowercase_ = 10 ) -> int: '''simple docstring''' lowercase__ : defaultdict = defaultdict(lowercase_ ) for outer_width in range(3 , (t_limit // 4) + 2 ): if outer_width * outer_width > t_limit: lowercase__ : Any = max( ceil(sqrt(outer_width * outer_width - t_limit ) ) , 1 ) else: lowercase__ : List[str] = 1 hole_width_lower_bound += (outer_width - hole_width_lower_bound) % 2 for hole_width in range(lowercase_ , outer_width - 1 , 2 ): count[outer_width * outer_width - hole_width * hole_width] += 1 return sum(1 for n in count.values() if 1 <= n <= 10 ) if __name__ == "__main__": print(f'''{solution() = }''')
12
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = ["image_processor", "tokenizer"] lowercase_ = "CLIPImageProcessor" lowercase_ = ("XLMRobertaTokenizer", "XLMRobertaTokenizerFast") def __init__(self : List[Any] , UpperCAmelCase_ : int=None , UpperCAmelCase_ : List[Any]=None , **UpperCAmelCase_ : List[str]) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Union[str, Any] =None if "feature_extractor" in kwargs: warnings.warn( "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`" " instead." , UpperCAmelCase_ , ) lowerCamelCase__: int =kwargs.pop("feature_extractor") lowerCamelCase__: int =image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("You need to specify an `image_processor`.") if tokenizer is None: raise ValueError("You need to specify a `tokenizer`.") super().__init__(UpperCAmelCase_ , UpperCAmelCase_) def __call__(self : List[Any] , UpperCAmelCase_ : str=None , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : int=None , **UpperCAmelCase_ : Any) ->Union[str, Any]: '''simple docstring''' if text is None and images is None: raise ValueError("You have to specify either text or images. Both cannot be none.") if text is not None: lowerCamelCase__: List[Any] =self.tokenizer(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_) if images is not None: lowerCamelCase__: int =self.image_processor(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_) if text is not None and images is not None: lowerCamelCase__: str =image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**UpperCAmelCase_) , tensor_type=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[str] , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : Optional[Any]) ->Dict: '''simple docstring''' return self.tokenizer.batch_decode(*UpperCAmelCase_ , **UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Optional[int] , *UpperCAmelCase_ : int , **UpperCAmelCase_ : Any) ->Optional[Any]: '''simple docstring''' return self.tokenizer.decode(*UpperCAmelCase_ , **UpperCAmelCase_) @property def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Optional[Any] =self.tokenizer.model_input_names lowerCamelCase__: str =self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
59
0
'''simple docstring''' def UpperCAmelCase__ ( UpperCAmelCase_ : int ) -> bool: return str(UpperCAmelCase_ ) == str(UpperCAmelCase_ )[::-1] def UpperCAmelCase__ ( UpperCAmelCase_ : int ) -> int: return int(UpperCAmelCase_ ) + int(str(UpperCAmelCase_ )[::-1] ) def UpperCAmelCase__ ( UpperCAmelCase_ : int = 1_00_00 ) -> int: __lowerCamelCase : Tuple = [] for num in range(1 , UpperCAmelCase_ ): __lowerCamelCase : int = 0 __lowerCamelCase : Optional[int] = num while iterations < 50: __lowerCamelCase : Union[str, Any] = sum_reverse(UpperCAmelCase_ ) iterations += 1 if is_palindrome(UpperCAmelCase_ ): break else: lychrel_nums.append(UpperCAmelCase_ ) return len(UpperCAmelCase_ ) if __name__ == "__main__": print(f'''{solution() = }''')
13
from datetime import datetime import matplotlib.pyplot as plt import torch def lowerCAmelCase_ ( __a ) -> Any: """simple docstring""" for param in module.parameters(): lowerCamelCase__: Tuple =False def lowerCAmelCase_ ( ) -> Optional[int]: """simple docstring""" lowerCamelCase__: List[str] ="cuda" if torch.cuda.is_available() else "cpu" if torch.backends.mps.is_available() and torch.backends.mps.is_built(): lowerCamelCase__: str ="mps" if device == "mps": print( "WARNING: MPS currently doesn't seem to work, and messes up backpropagation without any visible torch" " errors. I recommend using CUDA on a colab notebook or CPU instead if you're facing inexplicable issues" " with generations." ) return device def lowerCAmelCase_ ( __a ) -> List[str]: """simple docstring""" lowerCamelCase__: Union[str, Any] =plt.imshow(__a ) fig.axes.get_xaxis().set_visible(__a ) fig.axes.get_yaxis().set_visible(__a ) plt.show() def lowerCAmelCase_ ( ) -> Optional[Any]: """simple docstring""" lowerCamelCase__: List[str] =datetime.now() lowerCamelCase__: str =current_time.strftime("%H:%M:%S" ) return timestamp
59
0
from __future__ import annotations import math def __UpperCAmelCase ( __a : int ,__a : int ,__a : bool ,__a : list[int] ,__a : float ) -> int: """simple docstring""" if depth < 0: raise ValueError('''Depth cannot be less than 0''' ) if len(__a ) == 0: raise ValueError('''Scores cannot be empty''' ) if depth == height: return scores[node_index] if is_max: return max( minimax(depth + 1 ,node_index * 2 ,__a ,__a ,__a ) ,minimax(depth + 1 ,node_index * 2 + 1 ,__a ,__a ,__a ) ,) return min( minimax(depth + 1 ,node_index * 2 ,__a ,__a ,__a ) ,minimax(depth + 1 ,node_index * 2 + 1 ,__a ,__a ,__a ) ,) def __UpperCAmelCase ( ) -> None: """simple docstring""" _a : List[Any] = [90, 23, 6, 33, 21, 65, 123, 34_423] _a : List[Any] = math.log(len(__a ) ,2 ) print('''Optimal value : ''' ,end='''''' ) print(minimax(0 ,0 ,__a ,__a ,__a ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
14
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __A = { "configuration_pix2struct": [ "PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP", "Pix2StructConfig", "Pix2StructTextConfig", "Pix2StructVisionConfig", ], "processing_pix2struct": ["Pix2StructProcessor"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ["Pix2StructImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ "PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST", "Pix2StructPreTrainedModel", "Pix2StructForConditionalGeneration", "Pix2StructVisionModel", "Pix2StructTextModel", ] if TYPE_CHECKING: from .configuration_pixastruct import ( PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP, PixaStructConfig, PixaStructTextConfig, PixaStructVisionConfig, ) from .processing_pixastruct import PixaStructProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_pixastruct import PixaStructImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_pixastruct import ( PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST, PixaStructForConditionalGeneration, PixaStructPreTrainedModel, PixaStructTextModel, PixaStructVisionModel, ) else: import sys __A = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
59
0
import argparse import os import re A : List[Any] = 'src/transformers/models/auto' # re pattern that matches mapping introductions: # SUPER_MODEL_MAPPING_NAMES = OrderedDict or SUPER_MODEL_MAPPING = OrderedDict A : Any = re.compile(r'[A-Z_]+_MAPPING(\s+|_[A-Z_]+\s+)=\s+OrderedDict') # re pattern that matches identifiers in mappings A : Optional[Any] = re.compile(r'\s*\(\s*"(\S[^"]+)"') def UpperCamelCase ( __magic_name__ : str , __magic_name__ : bool = False ) -> Optional[int]: """simple docstring""" with open(__magic_name__ , """r""" , encoding="""utf-8""" ) as f: lowercase__ = f.read() lowercase__ = content.split("""\n""" ) lowercase__ = [] lowercase__ = 0 while line_idx < len(__magic_name__ ): if _re_intro_mapping.search(lines[line_idx] ) is not None: lowercase__ = len(re.search(R"""^(\s*)\S""" , lines[line_idx] ).groups()[0] ) + 8 # Start of a new mapping! while not lines[line_idx].startswith(""" """ * indent + """(""" ): new_lines.append(lines[line_idx] ) line_idx += 1 lowercase__ = [] while lines[line_idx].strip() != "]": # Blocks either fit in one line or not if lines[line_idx].strip() == "(": lowercase__ = line_idx while not lines[line_idx].startswith(""" """ * indent + """)""" ): line_idx += 1 blocks.append("""\n""".join(lines[start_idx : line_idx + 1] ) ) else: blocks.append(lines[line_idx] ) line_idx += 1 # Sort blocks by their identifiers lowercase__ = sorted(__magic_name__ , key=lambda __magic_name__ : _re_identifier.search(__magic_name__ ).groups()[0] ) new_lines += blocks else: new_lines.append(lines[line_idx] ) line_idx += 1 if overwrite: with open(__magic_name__ , """w""" , encoding="""utf-8""" ) as f: f.write("""\n""".join(__magic_name__ ) ) elif "\n".join(__magic_name__ ) != content: return True def UpperCamelCase ( __magic_name__ : bool = False ) -> Dict: """simple docstring""" lowercase__ = [os.path.join(__magic_name__ , __magic_name__ ) for f in os.listdir(__magic_name__ ) if f.endswith(""".py""" )] lowercase__ = [sort_auto_mapping(__magic_name__ , overwrite=__magic_name__ ) for fname in fnames] if not overwrite and any(__magic_name__ ): lowercase__ = [f for f, d in zip(__magic_name__ , __magic_name__ ) if d] raise ValueError( f'''The following files have auto mappings that need sorting: {", ".join(__magic_name__ )}. Run `make style` to fix''' """ this.""" ) if __name__ == "__main__": A : Optional[Any] = argparse.ArgumentParser() parser.add_argument('--check_only', action='store_true', help='Whether to only check or fix style.') A : Tuple = parser.parse_args() sort_all_auto_mappings(not args.check_only)
15
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_distilbert import DistilBertTokenizer __A = logging.get_logger(__name__) __A = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} __A = { "vocab_file": { "distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/vocab.txt", "distilbert-base-uncased-distilled-squad": ( "https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/vocab.txt" ), "distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/vocab.txt", "distilbert-base-cased-distilled-squad": ( "https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/vocab.txt" ), "distilbert-base-german-cased": "https://huggingface.co/distilbert-base-german-cased/resolve/main/vocab.txt", "distilbert-base-multilingual-cased": ( "https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/vocab.txt" ), }, "tokenizer_file": { "distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/tokenizer.json", "distilbert-base-uncased-distilled-squad": ( "https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/tokenizer.json" ), "distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/tokenizer.json", "distilbert-base-cased-distilled-squad": ( "https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/tokenizer.json" ), "distilbert-base-german-cased": ( "https://huggingface.co/distilbert-base-german-cased/resolve/main/tokenizer.json" ), "distilbert-base-multilingual-cased": ( "https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/tokenizer.json" ), }, } __A = { "distilbert-base-uncased": 512, "distilbert-base-uncased-distilled-squad": 512, "distilbert-base-cased": 512, "distilbert-base-cased-distilled-squad": 512, "distilbert-base-german-cased": 512, "distilbert-base-multilingual-cased": 512, } __A = { "distilbert-base-uncased": {"do_lower_case": True}, "distilbert-base-uncased-distilled-squad": {"do_lower_case": True}, "distilbert-base-cased": {"do_lower_case": False}, "distilbert-base-cased-distilled-squad": {"do_lower_case": False}, "distilbert-base-german-cased": {"do_lower_case": False}, "distilbert-base-multilingual-cased": {"do_lower_case": False}, } class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = VOCAB_FILES_NAMES lowercase_ = PRETRAINED_VOCAB_FILES_MAP lowercase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase_ = PRETRAINED_INIT_CONFIGURATION lowercase_ = ["input_ids", "attention_mask"] lowercase_ = DistilBertTokenizer def __init__(self : Tuple , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : int=None , UpperCAmelCase_ : Any=True , UpperCAmelCase_ : List[Any]="[UNK]" , UpperCAmelCase_ : Dict="[SEP]" , UpperCAmelCase_ : Dict="[PAD]" , UpperCAmelCase_ : Optional[int]="[CLS]" , UpperCAmelCase_ : str="[MASK]" , UpperCAmelCase_ : Any=True , UpperCAmelCase_ : List[str]=None , **UpperCAmelCase_ : List[str] , ) ->str: '''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_ , ) lowerCamelCase__: Union[str, Any] =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 ): lowerCamelCase__: List[str] =getattr(UpperCAmelCase_ , normalizer_state.pop("type")) lowerCamelCase__: Optional[int] =do_lower_case lowerCamelCase__: int =strip_accents lowerCamelCase__: Any =tokenize_chinese_chars lowerCamelCase__: Any =normalizer_class(**UpperCAmelCase_) lowerCamelCase__: str =do_lower_case def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : int , UpperCAmelCase_ : Union[str, Any]=None) ->Dict: '''simple docstring''' lowerCamelCase__: str =[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 SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None) ->List[int]: '''simple docstring''' lowerCamelCase__: str =[self.sep_token_id] lowerCamelCase__: str =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep) * [0] return len(cls + token_ids_a + sep) * [0] + len(token_ids_a + sep) * [1] def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] = None) ->Tuple[str]: '''simple docstring''' lowerCamelCase__: str =self._tokenizer.model.save(UpperCAmelCase_ , name=UpperCAmelCase_) return tuple(UpperCAmelCase_)
59
0
import warnings from ...utils import logging from .image_processing_flava import FlavaImageProcessor __A : str = logging.get_logger(__name__) class _SCREAMING_SNAKE_CASE ( __snake_case ): '''simple docstring''' def __init__( self : List[str] , *__lowerCamelCase : Optional[Any] , **__lowerCamelCase : List[Any] ): warnings.warn( "The class FlavaFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please" " use FlavaImageProcessor instead." , __lowerCamelCase , ) super().__init__(*__lowerCamelCase , **__lowerCamelCase )
16
import operator as op def lowerCAmelCase_ ( __a ) -> Tuple: """simple docstring""" lowerCamelCase__: Optional[Any] =[] lowerCamelCase__: Tuple =lambda __a , __a : int(x / y ) # noqa: E731 integer division operation lowerCamelCase__: Tuple ={ "^": op.pow, "*": op.mul, "/": div, "+": op.add, "-": op.sub, } # operators & their respective operation # print table header print("Symbol".center(8 ) , "Action".center(12 ) , "Stack" , sep=" | " ) print("-" * (30 + len(__a )) ) for x in post_fix: if x.isdigit(): # if x in digit stack.append(__a ) # append x to stack # output in tabular format print(x.rjust(8 ) , ("push(" + x + ")").ljust(12 ) , ",".join(__a ) , sep=" | " ) else: lowerCamelCase__: List[Any] =stack.pop() # pop stack # output in tabular format print("".rjust(8 ) , ("pop(" + b + ")").ljust(12 ) , ",".join(__a ) , sep=" | " ) lowerCamelCase__: Optional[Any] =stack.pop() # pop stack # output in tabular format print("".rjust(8 ) , ("pop(" + a + ")").ljust(12 ) , ",".join(__a ) , sep=" | " ) stack.append( str(opr[x](int(__a ) , int(__a ) ) ) ) # evaluate the 2 values popped from stack & push result to stack # output in tabular format print( x.rjust(8 ) , ("push(" + a + x + b + ")").ljust(12 ) , ",".join(__a ) , sep=" | " , ) return int(stack[0] ) if __name__ == "__main__": __A = input("\n\nEnter a Postfix Equation (space separated) = ").split(" ") print("\n\tResult = ", solve(Postfix))
59
0
import unittest from transformers import is_tf_available from transformers.testing_utils import require_tf if is_tf_available(): import tensorflow as tf from tensorflow.python.eager import context from tensorflow.python.framework import ops from transformers import GradientAccumulator, create_optimizer @require_tf class lowerCamelCase_ ( unittest.TestCase ): def lowerCAmelCase_ ( self : Dict , __A : Any , __A : Union[str, Any] , __A : Union[str, Any] ): self.assertEqual(len(__A ) , len(__A ) ) for a, b in zip(__A , __A ): self.assertAlmostEqual(__A , __A , delta=__A ) def lowerCAmelCase_ ( self : Optional[Any] ): __A : int = GradientAccumulator() accumulator([tf.constant([1.0, 2.0] )] ) accumulator([tf.constant([-2.0, 1.0] )] ) accumulator([tf.constant([-1.0, 2.0] )] ) with self.assertRaises(__A ): accumulator([tf.constant([1.0, 1.0] ), tf.constant([2.0, 2.0] )] ) self.assertEqual(accumulator.step , 3 ) self.assertEqual(len(accumulator.gradients ) , 1 ) self.assertListAlmostEqual(accumulator.gradients[0].numpy().tolist() , [-2.0, 5.0] , tol=1e-2 ) accumulator.reset() self.assertEqual(accumulator.step , 0 ) self.assertListAlmostEqual(accumulator.gradients[0].numpy().tolist() , [0.0, 0.0] , tol=1e-2 ) def lowerCAmelCase_ ( self : List[Any] ): __A : List[Any] = None ops.enable_eager_execution_internal() __A : List[Any] = tf.config.list_physical_devices("""CPU""" ) if len(__A ) == 1: tf.config.set_logical_device_configuration( physical_devices[0] , [tf.config.LogicalDeviceConfiguration(), tf.config.LogicalDeviceConfiguration()] ) __A : int = tf.config.list_logical_devices(device_type="""CPU""" ) __A : str = tf.distribute.MirroredStrategy(devices=devices[:2] ) with strategy.scope(): __A : Union[str, Any] = GradientAccumulator() __A : List[str] = tf.Variable([4.0, 3.0] ) __A , __A : Any = create_optimizer(5e-5 , 10 , 5 ) __A : int = tf.Variable([0.0, 0.0] , trainable=__A ) def accumulate_on_replica(__A : Optional[Any] ): accumulator([gradient] ) def apply_on_replica(): optimizer.apply_gradients(list(zip(accumulator.gradients , [variable] ) ) ) @tf.function def accumulate(__A : Union[str, Any] , __A : List[str] ): with strategy.scope(): __A : List[Any] = strategy.experimental_local_results(__A ) local_variables[0].assign(__A ) local_variables[1].assign(__A ) strategy.run(__A , args=(gradient_placeholder,) ) @tf.function def apply_grad(): with strategy.scope(): strategy.run(__A ) def _check_local_values(__A : List[Any] , __A : Tuple ): __A : int = strategy.experimental_local_results(accumulator._gradients[0] ) self.assertListAlmostEqual(values[0].value() , __A , tol=1e-2 ) self.assertListAlmostEqual(values[1].value() , __A , tol=1e-2 ) accumulate([1.0, 2.0] , [-1.0, 1.0] ) accumulate([3.0, -1.0] , [-1.0, -1.0] ) accumulate([-2.0, 2.0] , [3.0, -2.0] ) self.assertEqual(accumulator.step , 3 ) _check_local_values([2.0, 3.0] , [1.0, -2.0] ) apply_grad() self.assertListAlmostEqual(variable.value() , [4.0, 3.0] , tol=1e-2 ) accumulator.reset() self.assertEqual(accumulator.step , 0 ) _check_local_values([0.0, 0.0] , [0.0, 0.0] )
17
from collections import defaultdict from typing import Optional from ..image_utils import load_image from ..utils import ( add_end_docstrings, is_torch_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_MASK_GENERATION_MAPPING __A = logging.get_logger(__name__) @add_end_docstrings(__SCREAMING_SNAKE_CASE ) class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__(self : List[Any] , **UpperCAmelCase_ : Any) ->Any: '''simple docstring''' super().__init__(**UpperCAmelCase_) requires_backends(self , "vision") requires_backends(self , "torch") if self.framework != "pt": raise ValueError(F"""The {self.__class__} is only available in PyTorch.""") self.check_model_type(UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Tuple , **UpperCAmelCase_ : List[Any]) ->Tuple: '''simple docstring''' lowerCamelCase__: Optional[int] ={} lowerCamelCase__: Tuple ={} lowerCamelCase__: str ={} # preprocess args if "points_per_batch" in kwargs: lowerCamelCase__: Optional[Any] =kwargs["points_per_batch"] if "points_per_crop" in kwargs: lowerCamelCase__: int =kwargs["points_per_crop"] if "crops_n_layers" in kwargs: lowerCamelCase__: Any =kwargs["crops_n_layers"] if "crop_overlap_ratio" in kwargs: lowerCamelCase__: Tuple =kwargs["crop_overlap_ratio"] if "crop_n_points_downscale_factor" in kwargs: lowerCamelCase__: List[Any] =kwargs["crop_n_points_downscale_factor"] # postprocess args if "pred_iou_thresh" in kwargs: lowerCamelCase__: List[str] =kwargs["pred_iou_thresh"] if "stability_score_offset" in kwargs: lowerCamelCase__: int =kwargs["stability_score_offset"] if "mask_threshold" in kwargs: lowerCamelCase__: Optional[int] =kwargs["mask_threshold"] if "stability_score_thresh" in kwargs: lowerCamelCase__: str =kwargs["stability_score_thresh"] if "crops_nms_thresh" in kwargs: lowerCamelCase__: Any =kwargs["crops_nms_thresh"] if "output_rle_mask" in kwargs: lowerCamelCase__: List[Any] =kwargs["output_rle_mask"] if "output_bboxes_mask" in kwargs: lowerCamelCase__: List[str] =kwargs["output_bboxes_mask"] return preprocess_kwargs, forward_params, postprocess_kwargs def __call__(self : int , UpperCAmelCase_ : Dict , *UpperCAmelCase_ : Dict , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : Optional[Any]=None , **UpperCAmelCase_ : Dict) ->Optional[Any]: '''simple docstring''' return super().__call__(UpperCAmelCase_ , *UpperCAmelCase_ , num_workers=UpperCAmelCase_ , batch_size=UpperCAmelCase_ , **UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[Any]=64 , UpperCAmelCase_ : int = 0 , UpperCAmelCase_ : float = 512 / 1_500 , UpperCAmelCase_ : Optional[int] = 32 , UpperCAmelCase_ : Optional[int] = 1 , ) ->Dict: '''simple docstring''' lowerCamelCase__: Dict =load_image(UpperCAmelCase_) lowerCamelCase__: List[str] =self.image_processor.size["longest_edge"] lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Union[str, Any] =self.image_processor.generate_crop_boxes( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: str =self.image_processor(images=UpperCAmelCase_ , return_tensors="pt") with self.device_placement(): if self.framework == "pt": lowerCamelCase__: str =self.get_inference_context() with inference_context(): lowerCamelCase__: Union[str, Any] =self._ensure_tensor_on_device(UpperCAmelCase_ , device=self.device) lowerCamelCase__: Optional[Any] =self.model.get_image_embeddings(model_inputs.pop("pixel_values")) lowerCamelCase__: str =image_embeddings lowerCamelCase__: int =grid_points.shape[1] lowerCamelCase__: int =points_per_batch if points_per_batch is not None else n_points if points_per_batch <= 0: raise ValueError( "Cannot have points_per_batch<=0. Must be >=1 to returned batched outputs. " "To return all points at once, set points_per_batch to None") for i in range(0 , UpperCAmelCase_ , UpperCAmelCase_): lowerCamelCase__: int =grid_points[:, i : i + points_per_batch, :, :] lowerCamelCase__: Optional[Any] =input_labels[:, i : i + points_per_batch] lowerCamelCase__: Dict =i == n_points - points_per_batch yield { "input_points": batched_points, "input_labels": labels, "input_boxes": crop_boxes, "is_last": is_last, **model_inputs, } def SCREAMING_SNAKE_CASE_ (self : str , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Dict=0.88 , UpperCAmelCase_ : Optional[Any]=0.95 , UpperCAmelCase_ : Tuple=0 , UpperCAmelCase_ : Any=1 , ) ->Optional[Any]: '''simple docstring''' lowerCamelCase__: Any =model_inputs.pop("input_boxes") lowerCamelCase__: Dict =model_inputs.pop("is_last") lowerCamelCase__: int =model_inputs.pop("original_sizes").tolist() lowerCamelCase__: Union[str, Any] =model_inputs.pop("reshaped_input_sizes").tolist() lowerCamelCase__: Union[str, Any] =self.model(**UpperCAmelCase_) # post processing happens here in order to avoid CPU GPU copies of ALL the masks lowerCamelCase__: Optional[int] =model_outputs["pred_masks"] lowerCamelCase__: Union[str, Any] =self.image_processor.post_process_masks( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , binarize=UpperCAmelCase_) lowerCamelCase__: Optional[Any] =model_outputs["iou_scores"] lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Any =self.image_processor.filter_masks( masks[0] , iou_scores[0] , original_sizes[0] , input_boxes[0] , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , ) return { "masks": masks, "is_last": is_last, "boxes": boxes, "iou_scores": iou_scores, } def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : Any , UpperCAmelCase_ : Optional[int]=False , UpperCAmelCase_ : List[str]=False , UpperCAmelCase_ : Optional[int]=0.7 , ) ->Tuple: '''simple docstring''' lowerCamelCase__: Any =[] lowerCamelCase__: Optional[int] =[] lowerCamelCase__: List[str] =[] for model_output in model_outputs: all_scores.append(model_output.pop("iou_scores")) all_masks.extend(model_output.pop("masks")) all_boxes.append(model_output.pop("boxes")) lowerCamelCase__: str =torch.cat(UpperCAmelCase_) lowerCamelCase__: List[str] =torch.cat(UpperCAmelCase_) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Dict =self.image_processor.post_process_for_mask_generation( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: List[str] =defaultdict(UpperCAmelCase_) for output in model_outputs: for k, v in output.items(): extra[k].append(UpperCAmelCase_) lowerCamelCase__: Any ={} if output_rle_mask: lowerCamelCase__: Union[str, Any] =rle_mask if output_bboxes_mask: lowerCamelCase__: int =bounding_boxes return {"masks": output_masks, "scores": iou_scores, **optional, **extra}
59
0
'''simple docstring''' import unittest from transformers import BigBirdTokenizer, BigBirdTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin _SCREAMING_SNAKE_CASE = "▁" _SCREAMING_SNAKE_CASE = get_tests_dir("fixtures/test_sentencepiece.model") @require_sentencepiece @require_tokenizers class lowerCAmelCase_ ( __magic_name__ ,unittest.TestCase ): __lowerCamelCase : Dict = BigBirdTokenizer __lowerCamelCase : Optional[Any] = BigBirdTokenizerFast __lowerCamelCase : Any = True __lowerCamelCase : Union[str, Any] = True def _snake_case ( self ) -> Any: super().setUp() _lowerCAmelCase = self.tokenizer_class(_lowerCAmelCase , keep_accents=_lowerCAmelCase ) tokenizer.save_pretrained(self.tmpdirname ) def _snake_case ( self ) -> List[Any]: _lowerCAmelCase = "<s>" _lowerCAmelCase = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_lowerCAmelCase ) , _lowerCAmelCase ) def _snake_case ( self ) -> Dict: _lowerCAmelCase = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<unk>" ) self.assertEqual(vocab_keys[1] , "<s>" ) self.assertEqual(vocab_keys[-1] , "[MASK]" ) self.assertEqual(len(_lowerCAmelCase ) , 1004 ) def _snake_case ( self ) -> Optional[int]: self.assertEqual(self.get_tokenizer().vocab_size , 1000 ) def _snake_case ( self ) -> Optional[int]: 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(_lowerCAmelCase ) _lowerCAmelCase = rust_tokenizer.tokenize(_lowerCAmelCase ) self.assertListEqual(_lowerCAmelCase , _lowerCAmelCase ) _lowerCAmelCase = tokenizer.encode(_lowerCAmelCase , add_special_tokens=_lowerCAmelCase ) _lowerCAmelCase = rust_tokenizer.encode(_lowerCAmelCase , add_special_tokens=_lowerCAmelCase ) self.assertListEqual(_lowerCAmelCase , _lowerCAmelCase ) _lowerCAmelCase = self.get_rust_tokenizer() _lowerCAmelCase = tokenizer.encode(_lowerCAmelCase ) _lowerCAmelCase = rust_tokenizer.encode(_lowerCAmelCase ) self.assertListEqual(_lowerCAmelCase , _lowerCAmelCase ) def _snake_case ( self ) -> int: _lowerCAmelCase = BigBirdTokenizer(_lowerCAmelCase , keep_accents=_lowerCAmelCase ) _lowerCAmelCase = tokenizer.tokenize("This is a test" ) self.assertListEqual(_lowerCAmelCase , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(_lowerCAmelCase ) , [285, 46, 10, 170, 382] , ) _lowerCAmelCase = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( _lowerCAmelCase , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "é", ".", ] , ) _lowerCAmelCase = tokenizer.convert_tokens_to_ids(_lowerCAmelCase ) self.assertListEqual( _lowerCAmelCase , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] , ) _lowerCAmelCase = tokenizer.convert_ids_to_tokens(_lowerCAmelCase ) self.assertListEqual( _lowerCAmelCase , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "<unk>", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "<unk>", ".", ] , ) @cached_property def _snake_case ( self ) -> Any: return BigBirdTokenizer.from_pretrained("google/bigbird-roberta-base" ) @slow def _snake_case ( self ) -> Tuple: _lowerCAmelCase = "Hello World!" _lowerCAmelCase = [65, 18536, 2260, 101, 66] self.assertListEqual(_lowerCAmelCase , self.big_tokenizer.encode(_lowerCAmelCase ) ) @slow def _snake_case ( self ) -> Union[str, Any]: _lowerCAmelCase = ( "This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) \" [ ] ! : - . Also we will" " add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth" ) # fmt: off _lowerCAmelCase = [65, 871, 419, 358, 946, 991, 2521, 452, 358, 1357, 387, 7751, 3536, 112, 985, 456, 126, 865, 938, 5400, 5734, 458, 1368, 467, 786, 2462, 5246, 1159, 633, 865, 4519, 457, 582, 852, 2557, 427, 916, 508, 405, 34324, 497, 391, 408, 11342, 1244, 385, 100, 938, 985, 456, 574, 362, 12597, 3200, 3129, 1172, 66] # noqa: E231 # fmt: on self.assertListEqual(_lowerCAmelCase , self.big_tokenizer.encode(_lowerCAmelCase ) ) @require_torch @slow def _snake_case ( self ) -> Any: import torch from transformers import BigBirdConfig, BigBirdModel # Build sequence _lowerCAmelCase = list(self.big_tokenizer.get_vocab().keys() )[:10] _lowerCAmelCase = " ".join(_lowerCAmelCase ) _lowerCAmelCase = self.big_tokenizer.encode_plus(_lowerCAmelCase , return_tensors="pt" , return_token_type_ids=_lowerCAmelCase ) _lowerCAmelCase = self.big_tokenizer.batch_encode_plus( [sequence + " " + sequence] , return_tensors="pt" , return_token_type_ids=_lowerCAmelCase ) _lowerCAmelCase = BigBirdConfig(attention_type="original_full" ) _lowerCAmelCase = BigBirdModel(_lowerCAmelCase ) assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size with torch.no_grad(): model(**_lowerCAmelCase ) model(**_lowerCAmelCase ) @slow def _snake_case ( self ) -> int: _lowerCAmelCase = BigBirdTokenizer.from_pretrained("google/bigbird-roberta-base" ) _lowerCAmelCase = tokenizer.decode(tokenizer("Paris is the [MASK]." ).input_ids ) self.assertTrue(decoded_text == "[CLS] Paris is the[MASK].[SEP]" ) @slow def _snake_case ( self ) -> Any: # fmt: off _lowerCAmelCase = {"input_ids": [[65, 39286, 458, 36335, 2001, 456, 13073, 13266, 455, 113, 7746, 1741, 11157, 391, 13073, 13266, 455, 113, 3967, 35412, 113, 4936, 109, 3870, 2377, 113, 30084, 45720, 458, 134, 17496, 112, 503, 11672, 113, 118, 112, 5665, 13347, 38687, 112, 1496, 31389, 112, 3268, 47264, 134, 962, 112, 16377, 8035, 23130, 430, 12169, 15518, 28592, 458, 146, 41697, 109, 391, 12169, 15518, 16689, 458, 146, 41358, 109, 452, 726, 4034, 111, 763, 35412, 5082, 388, 1903, 111, 9051, 391, 2870, 48918, 1900, 1123, 550, 998, 112, 9586, 15985, 455, 391, 410, 22955, 37636, 114, 66], [65, 448, 17496, 419, 3663, 385, 763, 113, 27533, 2870, 3283, 13043, 1639, 24713, 523, 656, 24013, 18550, 2521, 517, 27014, 21244, 420, 1212, 1465, 391, 927, 4833, 388, 578, 11786, 114, 66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [65, 484, 2169, 7687, 21932, 18146, 726, 363, 17032, 3391, 114, 66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=_lowerCAmelCase , model_name="google/bigbird-roberta-base" , revision="215c99f1600e06f83acce68422f2035b2b5c3510" , )
18
from transformers import BertTokenizerFast from .custom_tokenization import CustomTokenizer class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = CustomTokenizer pass
59
0
"""simple docstring""" from __future__ import annotations import unittest from transformers import RoFormerConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerModel, ) from transformers.models.roformer.modeling_tf_roformer import ( TFRoFormerSelfAttention, TFRoFormerSinusoidalPositionalEmbedding, ) class _UpperCAmelCase: 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=5_12 , __a=16 , __a=2 , __a=0.02 , __a=3 , __a=4 , __a=None , ) -> List[Any]: '''simple docstring''' _UpperCamelCase = parent _UpperCamelCase = 13 _UpperCamelCase = 7 _UpperCamelCase = True _UpperCamelCase = True _UpperCamelCase = True _UpperCamelCase = True _UpperCamelCase = 99 _UpperCamelCase = 32 _UpperCamelCase = 2 _UpperCamelCase = 4 _UpperCamelCase = 37 _UpperCamelCase = '''gelu''' _UpperCamelCase = 0.1 _UpperCamelCase = 0.1 _UpperCamelCase = 5_12 _UpperCamelCase = 16 _UpperCamelCase = 2 _UpperCamelCase = 0.02 _UpperCamelCase = 3 _UpperCamelCase = 4 _UpperCamelCase = None def UpperCAmelCase ( self) -> Optional[Any]: '''simple docstring''' _UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) _UpperCamelCase = None if self.use_input_mask: _UpperCamelCase = random_attention_mask([self.batch_size, self.seq_length]) _UpperCamelCase = None if self.use_token_type_ids: _UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size) _UpperCamelCase = None _UpperCamelCase = None _UpperCamelCase = None if self.use_labels: _UpperCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size) _UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels) _UpperCamelCase = ids_tensor([self.batch_size] , self.num_choices) _UpperCamelCase = RoFormerConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , return_dict=__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) -> List[str]: '''simple docstring''' _UpperCamelCase = TFRoFormerModel(config=__a) _UpperCamelCase = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} _UpperCamelCase = [input_ids, input_mask] _UpperCamelCase = model(__a) _UpperCamelCase = model(__a) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a) -> List[str]: '''simple docstring''' _UpperCamelCase = True _UpperCamelCase = TFRoFormerForCausalLM(config=__a) _UpperCamelCase = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } _UpperCamelCase = model(__a)['''logits'''] self.parent.assertListEqual( list(prediction_scores.numpy().shape) , [self.batch_size, self.seq_length, self.vocab_size]) def UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a) -> int: '''simple docstring''' _UpperCamelCase = TFRoFormerForMaskedLM(config=__a) _UpperCamelCase = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } _UpperCamelCase = model(__a) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size)) def UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a) -> Tuple: '''simple docstring''' _UpperCamelCase = self.num_labels _UpperCamelCase = TFRoFormerForSequenceClassification(config=__a) _UpperCamelCase = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } _UpperCamelCase = model(__a) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a) -> Optional[int]: '''simple docstring''' _UpperCamelCase = self.num_choices _UpperCamelCase = TFRoFormerForMultipleChoice(config=__a) _UpperCamelCase = tf.tile(tf.expand_dims(__a , 1) , (1, self.num_choices, 1)) _UpperCamelCase = tf.tile(tf.expand_dims(__a , 1) , (1, self.num_choices, 1)) _UpperCamelCase = tf.tile(tf.expand_dims(__a , 1) , (1, self.num_choices, 1)) _UpperCamelCase = { '''input_ids''': multiple_choice_inputs_ids, '''attention_mask''': multiple_choice_input_mask, '''token_type_ids''': multiple_choice_token_type_ids, } _UpperCamelCase = model(__a) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices)) def UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a) -> List[Any]: '''simple docstring''' _UpperCamelCase = self.num_labels _UpperCamelCase = TFRoFormerForTokenClassification(config=__a) _UpperCamelCase = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } _UpperCamelCase = model(__a) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels)) def UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a) -> str: '''simple docstring''' _UpperCamelCase = TFRoFormerForQuestionAnswering(config=__a) _UpperCamelCase = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } _UpperCamelCase = model(__a) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length)) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length)) def UpperCAmelCase ( self) -> Dict: '''simple docstring''' _UpperCamelCase = self.prepare_config_and_inputs() ( ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ) = config_and_inputs _UpperCamelCase = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_tf class _UpperCAmelCase( lowerCamelCase , lowerCamelCase , unittest.TestCase ): lowercase__ = ( ( TFRoFormerModel, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerForMultipleChoice, ) if is_tf_available() else () ) lowercase__ = ( { 'feature-extraction': TFRoFormerModel, 'fill-mask': TFRoFormerForMaskedLM, 'question-answering': TFRoFormerForQuestionAnswering, 'text-classification': TFRoFormerForSequenceClassification, 'text-generation': TFRoFormerForCausalLM, 'token-classification': TFRoFormerForTokenClassification, 'zero-shot': TFRoFormerForSequenceClassification, } if is_tf_available() else {} ) lowercase__ = False lowercase__ = False def UpperCAmelCase ( self , __a , __a , __a , __a , __a) -> List[str]: '''simple docstring''' if pipeline_test_casse_name == "TextGenerationPipelineTests": return True return False def UpperCAmelCase ( self) -> Union[str, Any]: '''simple docstring''' _UpperCamelCase = TFRoFormerModelTester(self) _UpperCamelCase = ConfigTester(self , config_class=__a , hidden_size=37) def UpperCAmelCase ( self) -> str: '''simple docstring''' self.config_tester.run_common_tests() def UpperCAmelCase ( self) -> Dict: '''simple docstring''' _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__a) def UpperCAmelCase ( self) -> Any: '''simple docstring''' _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*__a) def UpperCAmelCase ( self) -> List[Any]: '''simple docstring''' _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head(*__a) def UpperCAmelCase ( self) -> Optional[Any]: '''simple docstring''' _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*__a) def UpperCAmelCase ( self) -> List[str]: '''simple docstring''' _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__a) def UpperCAmelCase ( self) -> Tuple: '''simple docstring''' _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*__a) def UpperCAmelCase ( self) -> Optional[Any]: '''simple docstring''' _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__a) @slow def UpperCAmelCase ( self) -> List[Any]: '''simple docstring''' _UpperCamelCase = TFRoFormerModel.from_pretrained('''junnyu/roformer_chinese_base''') self.assertIsNotNone(__a) @require_tf class _UpperCAmelCase( unittest.TestCase ): @slow def UpperCAmelCase ( self) -> str: '''simple docstring''' _UpperCamelCase = TFRoFormerForMaskedLM.from_pretrained('''junnyu/roformer_chinese_base''') _UpperCamelCase = tf.constant([[0, 1, 2, 3, 4, 5]]) _UpperCamelCase = model(__a)[0] # TODO Replace vocab size _UpperCamelCase = 5_00_00 _UpperCamelCase = [1, 6, vocab_size] self.assertEqual(output.shape , __a) print(output[:, :3, :3]) # TODO Replace values below with what was printed above. _UpperCamelCase = tf.constant( [ [ [-0.1205_3341, -1.026_4901, 0.2922_1946], [-1.513_3783, 0.19_7433, 0.1519_0607], [-5.013_5403, -3.90_0256, -0.8403_8764], ] ]) tf.debugging.assert_near(output[:, :3, :3] , __a , atol=1e-4) @require_tf class _UpperCAmelCase( unittest.TestCase ): lowercase__ = 1E-4 def UpperCAmelCase ( self) -> List[str]: '''simple docstring''' _UpperCamelCase = tf.constant([[4, 10]]) _UpperCamelCase = TFRoFormerSinusoidalPositionalEmbedding(num_positions=6 , embedding_dim=6) _UpperCamelCase = emba(input_ids.shape) _UpperCamelCase = tf.constant( [[0.0000, 0.0000, 0.0000, 1.0000, 1.0000, 1.0000], [0.8415, 0.0464, 0.0022, 0.5403, 0.9989, 1.0000]]) tf.debugging.assert_near(__a , __a , atol=self.tolerance) def UpperCAmelCase ( self) -> Dict: '''simple docstring''' _UpperCamelCase = tf.constant( [ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000], [0.8415, 0.8219, 0.8020, 0.7819, 0.7617], [0.9093, 0.9364, 0.9581, 0.9749, 0.9870], ]) _UpperCamelCase = TFRoFormerSinusoidalPositionalEmbedding(num_positions=5_12 , embedding_dim=5_12) emba([2, 16, 5_12]) _UpperCamelCase = emba.weight[:3, :5] tf.debugging.assert_near(__a , __a , atol=self.tolerance) @require_tf class _UpperCAmelCase( unittest.TestCase ): lowercase__ = 1E-4 def UpperCAmelCase ( self) -> List[Any]: '''simple docstring''' # 2,12,16,64 _UpperCamelCase = tf.reshape(tf.range(2 * 12 * 16 * 64 , dtype=tf.floataa) , shape=(2, 12, 16, 64)) / 1_00 _UpperCamelCase = -tf.reshape(tf.range(2 * 12 * 16 * 64 , dtype=tf.floataa) , shape=(2, 12, 16, 64)) / 1_00 _UpperCamelCase = TFRoFormerSinusoidalPositionalEmbedding(num_positions=32 , embedding_dim=64) _UpperCamelCase = embed_positions([2, 16, 7_68])[None, None, :, :] _UpperCamelCase , _UpperCamelCase = TFRoFormerSelfAttention.apply_rotary_position_embeddings( __a , __a , __a) _UpperCamelCase = tf.constant( [ [0.0000, 0.0100, 0.0200, 0.0300, 0.0400, 0.0500, 0.0600, 0.0700], [-0.2012, 0.8897, 0.0263, 0.9401, 0.2074, 0.9463, 0.3481, 0.9343], [-1.7057, 0.6271, -1.2145, 1.3897, -0.6303, 1.7647, -0.1173, 1.8985], [-2.1731, -1.6397, -2.7358, 0.2854, -2.1840, 1.7183, -1.3018, 2.4871], [0.2717, -3.6173, -2.9206, -2.1988, -3.6638, 0.3858, -2.9155, 2.2980], [3.9859, -2.1580, -0.7984, -4.4904, -4.1181, -2.0252, -4.4782, 1.1253], ]) _UpperCamelCase = tf.constant( [ [0.0000, -0.0100, -0.0200, -0.0300, -0.0400, -0.0500, -0.0600, -0.0700], [0.2012, -0.8897, -0.0263, -0.9401, -0.2074, -0.9463, -0.3481, -0.9343], [1.7057, -0.6271, 1.2145, -1.3897, 0.6303, -1.7647, 0.1173, -1.8985], [2.1731, 1.6397, 2.7358, -0.2854, 2.1840, -1.7183, 1.3018, -2.4871], [-0.2717, 3.6173, 2.9206, 2.1988, 3.6638, -0.3858, 2.9155, -2.2980], [-3.9859, 2.1580, 0.7984, 4.4904, 4.1181, 2.0252, 4.4782, -1.1253], ]) tf.debugging.assert_near(query_layer[0, 0, :6, :8] , __a , atol=self.tolerance) tf.debugging.assert_near(key_layer[0, 0, :6, :8] , __a , atol=self.tolerance)
19
import inspect import os import unittest import torch import accelerate from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_multi_gpu from accelerate.utils import patch_environment class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ (self : Dict) ->Optional[int]: '''simple docstring''' lowerCamelCase__: List[Any] =inspect.getfile(accelerate.test_utils) lowerCamelCase__: List[Any] =os.path.sep.join(mod_file.split(os.path.sep)[:-1] + ["scripts", "test_script.py"]) lowerCamelCase__: Any =os.path.sep.join( mod_file.split(os.path.sep)[:-1] + ["scripts", "test_distributed_data_loop.py"]) lowerCamelCase__: Tuple =os.path.sep.join(mod_file.split(os.path.sep)[:-1] + ["scripts", "test_ops.py"]) @require_multi_gpu def SCREAMING_SNAKE_CASE_ (self : str) ->str: '''simple docstring''' print(F"""Found {torch.cuda.device_count()} devices.""") lowerCamelCase__: Union[str, Any] =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", self.test_file_path] with patch_environment(omp_num_threads=1): execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy()) @require_multi_gpu def SCREAMING_SNAKE_CASE_ (self : List[str]) ->List[Any]: '''simple docstring''' print(F"""Found {torch.cuda.device_count()} devices.""") lowerCamelCase__: Dict =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", self.operation_file_path] print(F"""Command: {cmd}""") with patch_environment(omp_num_threads=1): execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy()) @require_multi_gpu def SCREAMING_SNAKE_CASE_ (self : Dict) ->Tuple: '''simple docstring''' lowerCamelCase__: int =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", inspect.getfile(self.__class__)] with patch_environment(omp_num_threads=1): execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy()) @require_multi_gpu def SCREAMING_SNAKE_CASE_ (self : str) ->List[Any]: '''simple docstring''' print(F"""Found {torch.cuda.device_count()} devices, using 2 devices only""") lowerCamelCase__: int =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", self.data_loop_file_path] with patch_environment(omp_num_threads=1 , cuda_visible_devices="0,1"): execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy()) if __name__ == "__main__": __A = Accelerator() __A = (accelerator.state.process_index + 2, 10) __A = torch.randint(0, 10, shape).to(accelerator.device) __A = "" __A = accelerator.pad_across_processes(tensor) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += f"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." if not torch.equal(tensora[: accelerator.state.process_index + 2], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[accelerator.state.process_index + 2 :] == 0): error_msg += "Padding was not done with the right value (0)." __A = accelerator.pad_across_processes(tensor, pad_first=True) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += f"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." __A = accelerator.state.num_processes - accelerator.state.process_index - 1 if not torch.equal(tensora[index:], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[:index] == 0): error_msg += "Padding was not done with the right value (0)." # 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)
59
0