code
stringlengths
82
53.2k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
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 UpperCAmelCase_ ( _A ): '''simple docstring''' def _lowercase ( self : Union[str, Any] ) -> List[Any]: """simple docstring""" __magic_name__ = tempfile.mkdtemp() __magic_name__ = 8 # DPR tok __magic_name__ = [ """[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] __magic_name__ = os.path.join(self.tmpdirname , """dpr_tokenizer""" ) os.makedirs(UpperCamelCase__ , exist_ok=UpperCamelCase__ ) __magic_name__ = 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 __magic_name__ = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """\u0120""", """\u0120l""", """\u0120n""", """\u0120lo""", """\u0120low""", """er""", """\u0120lowest""", """\u0120newer""", """\u0120wider""", """<unk>""", ] __magic_name__ = dict(zip(UpperCamelCase__ , range(len(UpperCamelCase__ ) ) ) ) __magic_name__ = ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""] __magic_name__ = {"""unk_token""": """<unk>"""} __magic_name__ = os.path.join(self.tmpdirname , """bart_tokenizer""" ) os.makedirs(UpperCamelCase__ , exist_ok=UpperCamelCase__ ) __magic_name__ = os.path.join(UpperCamelCase__ , BART_VOCAB_FILES_NAMES["""vocab_file"""] ) __magic_name__ = 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 _lowercase ( self : List[str] ) -> DPRQuestionEncoderTokenizer: """simple docstring""" return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname , """dpr_tokenizer""" ) ) def _lowercase ( self : Tuple ) -> DPRContextEncoderTokenizer: """simple docstring""" return DPRContextEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname , """dpr_tokenizer""" ) ) def _lowercase ( self : Any ) -> BartTokenizer: """simple docstring""" return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname , """bart_tokenizer""" ) ) def _lowercase ( self : Optional[int] ) -> Union[str, Any]: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _lowercase ( self : List[Any] ) -> Any: """simple docstring""" __magic_name__ = 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 _lowercase ( self : Union[str, Any] ) -> str: """simple docstring""" __magic_name__ = self.get_dummy_dataset() __magic_name__ = 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: __magic_name__ = dataset __magic_name__ = RagRetriever( UpperCamelCase__ , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() , ) return retriever def _lowercase ( self : List[str] , UpperCamelCase__ : bool ) -> int: """simple docstring""" __magic_name__ = self.get_dummy_dataset() __magic_name__ = RagConfig( retrieval_vector_size=self.retrieval_vector_size , question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() , index_name="""custom""" , ) if from_disk: __magic_name__ = os.path.join(self.tmpdirname , """dataset""" ) __magic_name__ = 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 __magic_name__ = RagRetriever( UpperCamelCase__ , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() , ) else: __magic_name__ = 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 _lowercase ( self : List[str] ) -> int: """simple docstring""" __magic_name__ = 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 ) __magic_name__ = 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""" ) ) __magic_name__ = os.path.join(self.tmpdirname , """psgs_w100.tsv.pkl""" ) __magic_name__ = {sample["""id"""]: [sample["""text"""], sample["""title"""]] for sample in dataset} pickle.dump(UpperCamelCase__ , open(UpperCamelCase__ , """wb""" ) ) __magic_name__ = RagConfig( retrieval_vector_size=self.retrieval_vector_size , question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() , index_name="""legacy""" , index_path=self.tmpdirname , ) __magic_name__ = RagRetriever( UpperCamelCase__ , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() ) return retriever def _lowercase ( self : List[str] ) -> str: """simple docstring""" __magic_name__ = 1 __magic_name__ = self.get_dummy_canonical_hf_index_retriever() __magic_name__ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) __magic_name__ , __magic_name__ , __magic_name__ = 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 _lowercase ( self : Tuple ) -> Any: """simple docstring""" __magic_name__ = 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: __magic_name__ = self.get_dummy_dataset() retriever.save_pretrained(UpperCamelCase__ ) __magic_name__ = RagRetriever.from_pretrained(UpperCamelCase__ ) self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ ) __magic_name__ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) __magic_name__ = retriever.retrieve(UpperCamelCase__ , n_docs=1 ) self.assertTrue(out is not None ) def _lowercase ( self : List[str] ) -> str: """simple docstring""" __magic_name__ = 1 __magic_name__ = self.get_dummy_custom_hf_index_retriever(from_disk=UpperCamelCase__ ) __magic_name__ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) __magic_name__ , __magic_name__ , __magic_name__ = 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 _lowercase ( self : Any ) -> str: """simple docstring""" __magic_name__ = self.get_dummy_custom_hf_index_retriever(from_disk=UpperCamelCase__ ) with tempfile.TemporaryDirectory() as tmp_dirname: retriever.save_pretrained(UpperCamelCase__ ) __magic_name__ = RagRetriever.from_pretrained(UpperCamelCase__ ) self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ ) __magic_name__ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) __magic_name__ = retriever.retrieve(UpperCamelCase__ , n_docs=1 ) self.assertTrue(out is not None ) def _lowercase ( self : Optional[Any] ) -> int: """simple docstring""" __magic_name__ = 1 __magic_name__ = self.get_dummy_custom_hf_index_retriever(from_disk=UpperCamelCase__ ) __magic_name__ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) __magic_name__ , __magic_name__ , __magic_name__ = 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 _lowercase ( self : str ) -> List[Any]: """simple docstring""" __magic_name__ = self.get_dummy_custom_hf_index_retriever(from_disk=UpperCamelCase__ ) with tempfile.TemporaryDirectory() as tmp_dirname: retriever.save_pretrained(UpperCamelCase__ ) __magic_name__ = RagRetriever.from_pretrained(UpperCamelCase__ ) self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ ) __magic_name__ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) __magic_name__ = retriever.retrieve(UpperCamelCase__ , n_docs=1 ) self.assertTrue(out is not None ) def _lowercase ( self : List[Any] ) -> Optional[int]: """simple docstring""" __magic_name__ = 1 __magic_name__ = self.get_dummy_legacy_index_retriever() __magic_name__ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) __magic_name__ , __magic_name__ , __magic_name__ = 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 _lowercase ( self : Tuple ) -> List[Any]: """simple docstring""" __magic_name__ = self.get_dummy_legacy_index_retriever() with tempfile.TemporaryDirectory() as tmp_dirname: retriever.save_pretrained(UpperCamelCase__ ) __magic_name__ = RagRetriever.from_pretrained(UpperCamelCase__ ) self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ ) __magic_name__ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) __magic_name__ = retriever.retrieve(UpperCamelCase__ , n_docs=1 ) self.assertTrue(out is not None ) @require_torch @require_tokenizers @require_sentencepiece def _lowercase ( self : str ) -> List[Any]: """simple docstring""" import torch __magic_name__ = 1 __magic_name__ = self.get_dummy_canonical_hf_index_retriever() __magic_name__ = [[5, 7], [10, 11]] __magic_name__ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) __magic_name__ = retriever(UpperCamelCase__ , UpperCamelCase__ , prefix=retriever.config.generator.prefix , n_docs=UpperCamelCase__ ) __magic_name__ , __magic_name__ , __magic_name__ = ( 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 ) __magic_name__ = retriever( UpperCamelCase__ , UpperCamelCase__ , prefix=retriever.config.generator.prefix , n_docs=UpperCamelCase__ , return_tensors="""pt""" , ) __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ = ( # 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 _lowercase ( self : int ) -> List[Any]: """simple docstring""" __magic_name__ = self.get_dpr_ctx_encoder_tokenizer() __magic_name__ = 1 __magic_name__ = self.get_dummy_custom_hf_index_retriever(from_disk=UpperCamelCase__ ) retriever.set_ctx_encoder_tokenizer(UpperCamelCase__ ) __magic_name__ = [[5, 7], [10, 11]] __magic_name__ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) __magic_name__ = 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.
529
import warnings from ...utils import logging from .image_processing_beit import BeitImageProcessor __lowerCAmelCase : int = logging.get_logger(__name__) class UpperCAmelCase_ ( _A ): '''simple docstring''' def __init__( self : int , *UpperCamelCase__ : Optional[Any] , **UpperCamelCase__ : Optional[Any] ) -> None: """simple docstring""" warnings.warn( """The class BeitFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please""" """ use BeitImageProcessor instead.""" , UpperCamelCase__ , ) super().__init__(*UpperCamelCase__ , **UpperCamelCase__ )
529
1
'''simple docstring''' from __future__ import annotations def _UpperCAmelCase ( __A : list[int] ): # This function is recursive a_ : Any = len(__A ) # If the array contains only one element, we return it (it's the stop condition of # recursion) if array_length <= 1: return array # Else a_ : Optional[int] = array[0] a_ : Union[str, Any] = False a_ : List[Any] = 1 a_ : list[int] = [] while not is_found and i < array_length: if array[i] < pivot: a_ : Optional[int] = True a_ : Dict = [element for element in array[i:] if element >= array[i]] a_ : Any = longest_subsequence(__A ) if len(__A ) > len(__A ): a_ : Tuple = temp_array else: i += 1 a_ : str = [element for element in array[1:] if element >= pivot] a_ : Optional[int] = [pivot, *longest_subsequence(__A )] if len(__A ) > len(__A ): return temp_array else: return longest_subseq if __name__ == "__main__": import doctest doctest.testmod()
666
'''simple docstring''' from math import pi, sqrt, tan def _UpperCAmelCase ( __A : float ): if side_length < 0: raise ValueError('''surface_area_cube() only accepts non-negative values''' ) return 6 * side_length**2 def _UpperCAmelCase ( __A : float , __A : float , __A : float ): if length < 0 or breadth < 0 or height < 0: raise ValueError('''surface_area_cuboid() only accepts non-negative values''' ) return 2 * ((length * breadth) + (breadth * height) + (length * height)) def _UpperCAmelCase ( __A : float ): if radius < 0: raise ValueError('''surface_area_sphere() only accepts non-negative values''' ) return 4 * pi * radius**2 def _UpperCAmelCase ( __A : float ): if radius < 0: raise ValueError('''surface_area_hemisphere() only accepts non-negative values''' ) return 3 * pi * radius**2 def _UpperCAmelCase ( __A : float , __A : float ): if radius < 0 or height < 0: raise ValueError('''surface_area_cone() only accepts non-negative values''' ) return pi * radius * (radius + (height**2 + radius**2) ** 0.5) def _UpperCAmelCase ( __A : float , __A : float , __A : float ): if radius_a < 0 or radius_a < 0 or height < 0: raise ValueError( '''surface_area_conical_frustum() only accepts non-negative values''' ) a_ : Any = (height**2 + (radius_a - radius_a) ** 2) ** 0.5 return pi * ((slant_height * (radius_a + radius_a)) + radius_a**2 + radius_a**2) def _UpperCAmelCase ( __A : float , __A : float ): if radius < 0 or height < 0: raise ValueError('''surface_area_cylinder() only accepts non-negative values''' ) return 2 * pi * radius * (height + radius) def _UpperCAmelCase ( __A : float , __A : float ): if torus_radius < 0 or tube_radius < 0: raise ValueError('''surface_area_torus() only accepts non-negative values''' ) if torus_radius < tube_radius: raise ValueError( '''surface_area_torus() does not support spindle or self intersecting tori''' ) return 4 * pow(__A , 2 ) * torus_radius * tube_radius def _UpperCAmelCase ( __A : float , __A : float ): if length < 0 or width < 0: raise ValueError('''area_rectangle() only accepts non-negative values''' ) return length * width def _UpperCAmelCase ( __A : float ): if side_length < 0: raise ValueError('''area_square() only accepts non-negative values''' ) return side_length**2 def _UpperCAmelCase ( __A : float , __A : float ): if base < 0 or height < 0: raise ValueError('''area_triangle() only accepts non-negative values''' ) return (base * height) / 2 def _UpperCAmelCase ( __A : float , __A : float , __A : float ): if sidea < 0 or sidea < 0 or sidea < 0: raise ValueError('''area_triangle_three_sides() only accepts non-negative values''' ) elif sidea + sidea < sidea or sidea + sidea < sidea or sidea + sidea < sidea: raise ValueError('''Given three sides do not form a triangle''' ) a_ : int = (sidea + sidea + sidea) / 2 a_ : Optional[Any] = sqrt( semi_perimeter * (semi_perimeter - sidea) * (semi_perimeter - sidea) * (semi_perimeter - sidea) ) return area def _UpperCAmelCase ( __A : float , __A : float ): if base < 0 or height < 0: raise ValueError('''area_parallelogram() only accepts non-negative values''' ) return base * height def _UpperCAmelCase ( __A : float , __A : float , __A : float ): if basea < 0 or basea < 0 or height < 0: raise ValueError('''area_trapezium() only accepts non-negative values''' ) return 1 / 2 * (basea + basea) * height def _UpperCAmelCase ( __A : float ): if radius < 0: raise ValueError('''area_circle() only accepts non-negative values''' ) return pi * radius**2 def _UpperCAmelCase ( __A : float , __A : float ): if radius_x < 0 or radius_y < 0: raise ValueError('''area_ellipse() only accepts non-negative values''' ) return pi * radius_x * radius_y def _UpperCAmelCase ( __A : float , __A : float ): if diagonal_a < 0 or diagonal_a < 0: raise ValueError('''area_rhombus() only accepts non-negative values''' ) return 1 / 2 * diagonal_a * diagonal_a def _UpperCAmelCase ( __A : int , __A : float ): if not isinstance(__A , __A ) or sides < 3: raise ValueError( '''area_reg_polygon() only accepts integers greater than or \ equal to three as number of sides''' ) elif length < 0: raise ValueError( '''area_reg_polygon() only accepts non-negative values as \ length of a side''' ) return (sides * length**2) / (4 * tan(pi / sides )) return (sides * length**2) / (4 * tan(pi / sides )) if __name__ == "__main__": import doctest doctest.testmod(verbose=True) # verbose so we can see methods missing tests print('[DEMO] Areas of various geometric shapes: \n') print(F"""Rectangle: {area_rectangle(10, 20) = }""") print(F"""Square: {area_square(10) = }""") print(F"""Triangle: {area_triangle(10, 10) = }""") print(F"""Triangle: {area_triangle_three_sides(5, 12, 13) = }""") print(F"""Parallelogram: {area_parallelogram(10, 20) = }""") print(F"""Rhombus: {area_rhombus(10, 20) = }""") print(F"""Trapezium: {area_trapezium(10, 20, 30) = }""") print(F"""Circle: {area_circle(20) = }""") print(F"""Ellipse: {area_ellipse(10, 20) = }""") print('\nSurface Areas of various geometric shapes: \n') print(F"""Cube: {surface_area_cube(20) = }""") print(F"""Cuboid: {surface_area_cuboid(10, 20, 30) = }""") print(F"""Sphere: {surface_area_sphere(20) = }""") print(F"""Hemisphere: {surface_area_hemisphere(20) = }""") print(F"""Cone: {surface_area_cone(10, 20) = }""") print(F"""Conical Frustum: {surface_area_conical_frustum(10, 20, 30) = }""") print(F"""Cylinder: {surface_area_cylinder(10, 20) = }""") print(F"""Torus: {surface_area_torus(20, 10) = }""") print(F"""Equilateral Triangle: {area_reg_polygon(3, 10) = }""") print(F"""Square: {area_reg_polygon(4, 10) = }""") print(F"""Reqular Pentagon: {area_reg_polygon(5, 10) = }""")
666
1
'''simple docstring''' import argparse import collections import os import re from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_table.py lowerCamelCase :Optional[Any] = '''src/transformers''' lowerCamelCase :int = '''docs/source/en''' lowerCamelCase :Union[str, Any] = '''.''' def a ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ): '''simple docstring''' with open(__A , """r""" , encoding="""utf-8""" , newline="""\n""" ) as f: A_ : int = f.readlines() # Find the start prompt. A_ : Dict = 0 while not lines[start_index].startswith(__A ): start_index += 1 start_index += 1 A_ : Optional[Any] = start_index while not lines[end_index].startswith(__A ): end_index += 1 end_index -= 1 while len(lines[start_index] ) <= 1: start_index += 1 while len(lines[end_index] ) <= 1: end_index -= 1 end_index += 1 return "".join(lines[start_index:end_index] ), start_index, end_index, lines # Add here suffixes that are used to identify models, separated by | lowerCamelCase :str = '''Model|Encoder|Decoder|ForConditionalGeneration''' # Regexes that match TF/Flax/PT model names. lowerCamelCase :int = re.compile(R'''TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)''') lowerCamelCase :List[str] = re.compile(R'''Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)''') # Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes. lowerCamelCase :List[Any] = re.compile(R'''(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)''') # This is to make sure the transformers module imported is the one in the repo. lowerCamelCase :Optional[int] = direct_transformers_import(TRANSFORMERS_PATH) def a ( lowerCamelCase__ ): '''simple docstring''' A_ : int = re.finditer(""".+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)""" , __A ) return [m.group(0 ) for m in matches] def a ( lowerCamelCase__ , lowerCamelCase__ ): '''simple docstring''' A_ : List[str] = 2 if text == """✅""" or text == """❌""" else len(__A ) A_ : Dict = (width - text_length) // 2 A_ : Any = width - text_length - left_indent return " " * left_indent + text + " " * right_indent def a ( ): '''simple docstring''' A_ : Any = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES A_ : int = { name: config_maping_names[code] for code, name in transformers_module.MODEL_NAMES_MAPPING.items() if code in config_maping_names } A_ : List[Any] = {name: config.replace("""Config""" , """""" ) for name, config in model_name_to_config.items()} # Dictionaries flagging if each model prefix has a slow/fast tokenizer, backend in PT/TF/Flax. A_ : Tuple = collections.defaultdict(__A ) A_ : Optional[int] = collections.defaultdict(__A ) A_ : Union[str, Any] = collections.defaultdict(__A ) A_ : List[str] = collections.defaultdict(__A ) A_ : Tuple = collections.defaultdict(__A ) # Let's lookup through all transformers object (once). for attr_name in dir(__A ): A_ : List[str] = None if attr_name.endswith("""Tokenizer""" ): A_ : Dict = slow_tokenizers A_ : Optional[Any] = attr_name[:-9] elif attr_name.endswith("""TokenizerFast""" ): A_ : List[Any] = fast_tokenizers A_ : List[str] = attr_name[:-13] elif _re_tf_models.match(__A ) is not None: A_ : str = tf_models A_ : List[str] = _re_tf_models.match(__A ).groups()[0] elif _re_flax_models.match(__A ) is not None: A_ : List[Any] = flax_models A_ : str = _re_flax_models.match(__A ).groups()[0] elif _re_pt_models.match(__A ) is not None: A_ : List[str] = pt_models A_ : List[Any] = _re_pt_models.match(__A ).groups()[0] if lookup_dict is not None: while len(__A ) > 0: if attr_name in model_name_to_prefix.values(): A_ : Optional[Any] = True break # Try again after removing the last word in the name A_ : List[str] = """""".join(camel_case_split(__A )[:-1] ) # Let's build that table! A_ : Union[str, Any] = list(model_name_to_config.keys() ) model_names.sort(key=str.lower ) A_ : Any = ["""Model""", """Tokenizer slow""", """Tokenizer fast""", """PyTorch support""", """TensorFlow support""", """Flax Support"""] # We'll need widths to properly display everything in the center (+2 is to leave one extra space on each side). A_ : int = [len(__A ) + 2 for c in columns] A_ : int = max([len(__A ) for name in model_names] ) + 2 # Build the table per se A_ : List[Any] = """|""" + """|""".join([_center_text(__A , __A ) for c, w in zip(__A , __A )] ) + """|\n""" # Use ":-----:" format to center-aligned table cell texts table += "|" + "|".join([""":""" + """-""" * (w - 2) + """:""" for w in widths] ) + "|\n" A_ : List[str] = {True: """✅""", False: """❌"""} for name in model_names: A_ : Optional[int] = model_name_to_prefix[name] A_ : List[Any] = [ name, check[slow_tokenizers[prefix]], check[fast_tokenizers[prefix]], check[pt_models[prefix]], check[tf_models[prefix]], check[flax_models[prefix]], ] table += "|" + "|".join([_center_text(__A , __A ) for l, w in zip(__A , __A )] ) + "|\n" return table def a ( lowerCamelCase__=False ): '''simple docstring''' A_, A_, A_, A_ : int = _find_text_in_file( filename=os.path.join(__A , """index.md""" ) , start_prompt="""<!--This table is updated automatically from the auto modules""" , end_prompt="""<!-- End table-->""" , ) A_ : int = get_model_table_from_auto_modules() if current_table != new_table: if overwrite: with open(os.path.join(__A , """index.md""" ) , """w""" , encoding="""utf-8""" , newline="""\n""" ) as f: f.writelines(lines[:start_index] + [new_table] + lines[end_index:] ) else: raise ValueError( """The model table in the `index.md` has not been updated. Run `make fix-copies` to fix this.""" ) if __name__ == "__main__": lowerCamelCase :List[str] = argparse.ArgumentParser() parser.add_argument('''--fix_and_overwrite''', action='''store_true''', help='''Whether to fix inconsistencies.''') lowerCamelCase :List[str] = parser.parse_args() check_model_table(args.fix_and_overwrite)
667
def lowerCAmelCase_ ( __A, __A ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase__ = [1] for i in range(2, __A ): factorials.append(factorials[-1] * i ) assert 0 <= k < factorials[-1] * n, "k out of bounds" UpperCAmelCase__ = [] UpperCAmelCase__ = list(range(__A ) ) # Find permutation while factorials: UpperCAmelCase__ = factorials.pop() UpperCAmelCase__ , UpperCAmelCase__ = divmod(__A, __A ) permutation.append(elements[number] ) elements.remove(elements[number] ) permutation.append(elements[0] ) return permutation if __name__ == "__main__": import doctest doctest.testmod()
486
0
import argparse import pathlib import fairseq import torch from fairseq.models.roberta import RobertaModel as FairseqRobertaModel from fairseq.modules import TransformerSentenceEncoderLayer from packaging import version from transformers import XLMRobertaConfig, XLMRobertaXLForMaskedLM, XLMRobertaXLForSequenceClassification from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertSelfAttention, BertSelfOutput, ) from transformers.models.roberta.modeling_roberta import RobertaAttention from transformers.utils import logging if version.parse(fairseq.__version__) < version.parse('''1.0.0a'''): raise Exception('''requires fairseq >= 1.0.0a''') logging.set_verbosity_info() snake_case_ = logging.get_logger(__name__) snake_case_ = '''Hello world! cécé herlolip''' def A__ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Optional[int]: lowerCamelCase : Tuple =FairseqRobertaModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) roberta.eval() # disable dropout lowerCamelCase : Union[str, Any] =roberta.model.encoder.sentence_encoder lowerCamelCase : Union[str, Any] =XLMRobertaConfig( vocab_size=roberta_sent_encoder.embed_tokens.num_embeddings , hidden_size=roberta.cfg.model.encoder_embed_dim , num_hidden_layers=roberta.cfg.model.encoder_layers , num_attention_heads=roberta.cfg.model.encoder_attention_heads , intermediate_size=roberta.cfg.model.encoder_ffn_embed_dim , max_position_embeddings=5_1_4 , type_vocab_size=1 , layer_norm_eps=1E-5 , ) if classification_head: lowerCamelCase : List[str] =roberta.model.classification_heads['''mnli'''].out_proj.weight.shape[0] print('''Our RoBERTa config:''' , SCREAMING_SNAKE_CASE_ ) lowerCamelCase : Optional[int] =XLMRobertaXLForSequenceClassification(SCREAMING_SNAKE_CASE_ ) if classification_head else XLMRobertaXLForMaskedLM(SCREAMING_SNAKE_CASE_ ) model.eval() # Now let's copy all the weights. # Embeddings lowerCamelCase : List[str] =roberta_sent_encoder.embed_tokens.weight lowerCamelCase : List[str] =roberta_sent_encoder.embed_positions.weight lowerCamelCase : Tuple =torch.zeros_like( model.roberta.embeddings.token_type_embeddings.weight ) # just zero them out b/c RoBERTa doesn't use them. lowerCamelCase : List[str] =roberta_sent_encoder.layer_norm.weight lowerCamelCase : Tuple =roberta_sent_encoder.layer_norm.bias for i in range(config.num_hidden_layers ): # Encoder: start of layer lowerCamelCase : BertLayer =model.roberta.encoder.layer[i] lowerCamelCase : TransformerSentenceEncoderLayer =roberta_sent_encoder.layers[i] lowerCamelCase : RobertaAttention =layer.attention lowerCamelCase : List[Any] =roberta_layer.self_attn_layer_norm.weight lowerCamelCase : Tuple =roberta_layer.self_attn_layer_norm.bias # self attention lowerCamelCase : BertSelfAttention =layer.attention.self assert ( roberta_layer.self_attn.k_proj.weight.data.shape == roberta_layer.self_attn.q_proj.weight.data.shape == roberta_layer.self_attn.v_proj.weight.data.shape == torch.Size((config.hidden_size, config.hidden_size) ) ) lowerCamelCase : Optional[int] =roberta_layer.self_attn.q_proj.weight lowerCamelCase : str =roberta_layer.self_attn.q_proj.bias lowerCamelCase : str =roberta_layer.self_attn.k_proj.weight lowerCamelCase : Optional[Any] =roberta_layer.self_attn.k_proj.bias lowerCamelCase : Union[str, Any] =roberta_layer.self_attn.v_proj.weight lowerCamelCase : Dict =roberta_layer.self_attn.v_proj.bias # self-attention output lowerCamelCase : BertSelfOutput =layer.attention.output assert self_output.dense.weight.shape == roberta_layer.self_attn.out_proj.weight.shape lowerCamelCase : Any =roberta_layer.self_attn.out_proj.weight lowerCamelCase : List[Any] =roberta_layer.self_attn.out_proj.bias # this one is final layer norm lowerCamelCase : Any =roberta_layer.final_layer_norm.weight lowerCamelCase : Dict =roberta_layer.final_layer_norm.bias # intermediate lowerCamelCase : BertIntermediate =layer.intermediate assert intermediate.dense.weight.shape == roberta_layer.fca.weight.shape lowerCamelCase : Any =roberta_layer.fca.weight lowerCamelCase : Any =roberta_layer.fca.bias # output lowerCamelCase : BertOutput =layer.output assert bert_output.dense.weight.shape == roberta_layer.fca.weight.shape lowerCamelCase : Any =roberta_layer.fca.weight lowerCamelCase : Optional[int] =roberta_layer.fca.bias # end of layer if classification_head: lowerCamelCase : List[Any] =roberta.model.classification_heads['''mnli'''].dense.weight lowerCamelCase : Optional[Any] =roberta.model.classification_heads['''mnli'''].dense.bias lowerCamelCase : Dict =roberta.model.classification_heads['''mnli'''].out_proj.weight lowerCamelCase : List[Any] =roberta.model.classification_heads['''mnli'''].out_proj.bias else: # LM Head lowerCamelCase : List[Any] =roberta.model.encoder.lm_head.dense.weight lowerCamelCase : Optional[Any] =roberta.model.encoder.lm_head.dense.bias lowerCamelCase : Dict =roberta.model.encoder.lm_head.layer_norm.weight lowerCamelCase : List[str] =roberta.model.encoder.lm_head.layer_norm.bias lowerCamelCase : Tuple =roberta.model.encoder.lm_head.weight lowerCamelCase : int =roberta.model.encoder.lm_head.bias # Let's check that we get the same results. lowerCamelCase : torch.Tensor =roberta.encode(SCREAMING_SNAKE_CASE_ ).unsqueeze(0 ) # batch of size 1 lowerCamelCase : int =model(SCREAMING_SNAKE_CASE_ )[0] if classification_head: lowerCamelCase : Dict =roberta.model.classification_heads['''mnli'''](roberta.extract_features(SCREAMING_SNAKE_CASE_ ) ) else: lowerCamelCase : str =roberta.model(SCREAMING_SNAKE_CASE_ )[0] print(our_output.shape , their_output.shape ) lowerCamelCase : Dict =torch.max(torch.abs(our_output - their_output ) ).item() print(F"max_absolute_diff = {max_absolute_diff}" ) # ~ 1e-7 lowerCamelCase : Optional[Any] =torch.allclose(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=1E-3 ) print('''Do both models output the same tensors?''' , '''🔥''' if success else '''💩''' ) if not success: raise Exception('''Something went wRoNg''' ) pathlib.Path(SCREAMING_SNAKE_CASE_ ).mkdir(parents=SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) print(F"Saving model to {pytorch_dump_folder_path}" ) model.save_pretrained(SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": snake_case_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--roberta_checkpoint_path''', default=None, type=str, required=True, help='''Path the official PyTorch dump.''' ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) parser.add_argument( '''--classification_head''', action='''store_true''', help='''Whether to convert a final classification head.''' ) snake_case_ = parser.parse_args() convert_xlm_roberta_xl_checkpoint_to_pytorch( args.roberta_checkpoint_path, args.pytorch_dump_folder_path, args.classification_head )
262
import argparse import re from flax.traverse_util import flatten_dict, unflatten_dict from tax import checkpoints from transformers import SwitchTransformersConfig, SwitchTransformersForConditionalGeneration from transformers.modeling_flax_pytorch_utils import load_flax_weights_in_pytorch_model from transformers.utils import logging logging.set_verbosity_info() # should not include what is already done by the `from_pt` argument snake_case_ = { '''/attention/''': '''/0/SelfAttention/''', '''/self_attention/''': '''/0/SelfAttention/''', '''/encoder_decoder_attention/''': '''/1/EncDecAttention/''', '''value''': '''v''', '''query''': '''q''', '''key''': '''k''', '''out''': '''o''', '''pre_self_attention_layer_norm''': '''0/layer_norm''', '''pre_cross_attention_layer_norm''': '''1/layer_norm''', '''pre_attention_layer_norm''': '''0/layer_norm''', # previously 1, but seems wrong '''token_embedder''': '''shared''', '''encoder_norm''': '''final_layer_norm''', '''decoder_norm''': '''final_layer_norm''', '''relpos_bias/rel_embedding''': '''block/0/layer/0/SelfAttention/relative_attention_bias/weight''', '''router/router_weights/w/''': '''router/classifier/''', '''roer/roer_weights/w/''': '''router/classifier/''', '''logits_dense''': '''lm_head''', } def A__ ( SCREAMING_SNAKE_CASE_ ) -> int: # 1. in HF T5, we have block.{x}.layer.{y}. which corresponds to layer.{x} in # the original model lowerCamelCase : List[Any] =list(s_dict.keys() ) for key in keys: lowerCamelCase : Dict =R'''.*/layers_(\d+)''' lowerCamelCase : Optional[int] =key if re.match(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): lowerCamelCase : Optional[Any] =re.sub(R'''layers_(\d+)''' , R'''block/\1/layer''' , SCREAMING_SNAKE_CASE_ ) lowerCamelCase : Dict =R'''(encoder|decoder)\/''' if re.match(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): lowerCamelCase : Dict =re.match(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).groups() if groups[0] == "encoder": lowerCamelCase : Dict =re.sub(R'''/mlp/''' , R'''/1/mlp/''' , SCREAMING_SNAKE_CASE_ ) lowerCamelCase : Optional[int] =re.sub(R'''/pre_mlp_layer_norm/''' , R'''/1/layer_norm/''' , SCREAMING_SNAKE_CASE_ ) elif groups[0] == "decoder": lowerCamelCase : List[str] =re.sub(R'''/mlp/''' , R'''/2/mlp/''' , SCREAMING_SNAKE_CASE_ ) lowerCamelCase : str =re.sub(R'''/pre_mlp_layer_norm/''' , R'''/2/layer_norm/''' , SCREAMING_SNAKE_CASE_ ) # 2. Convert other classic mappings for old_key, temp_key in MOE_LAYER_NAME_MAPPING.items(): if old_key in new_key: lowerCamelCase : Dict =new_key.replace(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) print(F"{key} -> {new_key}" ) lowerCamelCase : Optional[Any] =s_dict.pop(SCREAMING_SNAKE_CASE_ ) if "encoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight" in s_dict: lowerCamelCase : Dict =s_dict[ '''encoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight''' ].T if "decoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight" in s_dict: lowerCamelCase : Union[str, Any] =s_dict[ '''decoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight''' ].T # 3. Take extra care of the EXPERTS layer for key in list(s_dict.keys() ): if "expert" in key: lowerCamelCase : List[Any] =s_dict[key].shape[0] lowerCamelCase : int =s_dict[key] for idx in range(SCREAMING_SNAKE_CASE_ ): lowerCamelCase : Tuple =expert_weihts[idx] print(F"{key} -> {key.replace('expert/' , 'nested fstring' )}" ) s_dict.pop(SCREAMING_SNAKE_CASE_ ) return s_dict snake_case_ = { '''NUM_ENCODER_LAYERS''': '''num_layers''', '''NUM_DECODER_LAYERS''': '''num_decoder_layers''', '''NUM_HEADS''': '''num_heads''', '''HEAD_DIM''': '''d_kv''', '''EMBED_DIM''': '''d_model''', '''MLP_DIM''': '''d_ff''', '''NUM_SELECTED_EXPERTS''': '''num_selected_experts''', '''NUM_ENCODER_SPARSE_LAYERS''': '''num_sparse_encoder_layers''', '''NUM_DECODER_SPARSE_LAYERS''': '''num_sparse_decoder_layers''', '''dense.MlpBlock.activations''': '''feed_forward_proj''', } def A__ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]: # Convert a google style config to the hugging face fromat import regex as re with open(SCREAMING_SNAKE_CASE_ , '''r''' ) as f: lowerCamelCase : str =f.read() lowerCamelCase : Union[str, Any] =re.findall(R'''(.*) = ([0-9.]*)''' , SCREAMING_SNAKE_CASE_ ) lowerCamelCase : str ={} for param, value in regex_match: if param in GIN_TO_CONFIG_MAPPING and value != "": lowerCamelCase : str =float(SCREAMING_SNAKE_CASE_ ) if '''.''' in value else int(SCREAMING_SNAKE_CASE_ ) lowerCamelCase : int =re.findall(R'''(.*activations) = \(\'(.*)\',\)''' , SCREAMING_SNAKE_CASE_ )[0] lowerCamelCase : Any =str(activation[1] ) lowerCamelCase : Tuple =num_experts lowerCamelCase : Any =SwitchTransformersConfig(**SCREAMING_SNAKE_CASE_ ) return config def A__ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_="./" , SCREAMING_SNAKE_CASE_=8 ) -> Dict: # Initialise PyTorch model print(F"Loading flax weights from : {flax_checkpoint_path}" ) lowerCamelCase : List[Any] =checkpoints.load_tax_checkpoint(SCREAMING_SNAKE_CASE_ ) if gin_file is not None: lowerCamelCase : Dict =convert_gin_to_config(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else: lowerCamelCase : Optional[int] =SwitchTransformersConfig.from_pretrained(SCREAMING_SNAKE_CASE_ ) lowerCamelCase : Any =SwitchTransformersForConditionalGeneration(SCREAMING_SNAKE_CASE_ ) lowerCamelCase : int =flax_params['''target'''] lowerCamelCase : Optional[int] =flatten_dict(SCREAMING_SNAKE_CASE_ , sep='''/''' ) lowerCamelCase : str =rename_keys(SCREAMING_SNAKE_CASE_ ) lowerCamelCase : List[str] =unflatten_dict(SCREAMING_SNAKE_CASE_ , sep='''/''' ) # Load the flax params in the PT model load_flax_weights_in_pytorch_model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) print(F"Save PyTorch model to {pytorch_dump_path}" ) pt_model.save_pretrained(SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": snake_case_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--switch_t5x_checkpoint_path''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained SwitchTransformers model. \nThis specifies the''' ''' model architecture. If not provided, a `gin_file` has to be provided.''' ), ) parser.add_argument( '''--gin_file''', default=None, type=str, required=False, help='''Path to the gin config file. If not provided, a `config_file` has to be passed ''', ) parser.add_argument( '''--config_name''', default=None, type=str, required=False, help='''Config name of SwitchTransformers model.''' ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output pytorch model.''' ) parser.add_argument('''--num_experts''', default=8, type=int, required=False, help='''Number of experts''') snake_case_ = parser.parse_args() convert_flax_checkpoint_to_pytorch( args.switch_tax_checkpoint_path, args.config_name, args.gin_file, args.pytorch_dump_folder_path, args.num_experts, )
262
1
'''simple docstring''' import argparse import torch from transformers import BertForMaskedLM if __name__ == "__main__": lowerCAmelCase : Optional[Any] = argparse.ArgumentParser( description=( """Extraction some layers of the full BertForMaskedLM or RObertaForMaskedLM for Transfer Learned""" """ Distillation""" ) ) parser.add_argument("""--model_type""", default="""bert""", choices=["""bert"""]) parser.add_argument("""--model_name""", default="""bert-base-uncased""", type=str) parser.add_argument("""--dump_checkpoint""", default="""serialization_dir/tf_bert-base-uncased_0247911.pth""", type=str) parser.add_argument("""--vocab_transform""", action="""store_true""") lowerCAmelCase : Optional[int] = parser.parse_args() if args.model_type == "bert": lowerCAmelCase : Any = BertForMaskedLM.from_pretrained(args.model_name) lowerCAmelCase : Optional[int] = """bert""" else: raise ValueError("""args.model_type should be \"bert\".""") lowerCAmelCase : str = model.state_dict() lowerCAmelCase : str = {} for w in ["word_embeddings", "position_embeddings"]: lowerCAmelCase : Optional[int] = state_dict[F'''{prefix}.embeddings.{w}.weight'''] for w in ["weight", "bias"]: lowerCAmelCase : Optional[int] = state_dict[F'''{prefix}.embeddings.LayerNorm.{w}'''] lowerCAmelCase : Union[str, Any] = 0 for teacher_idx in [0, 2, 4, 7, 9, 1_1]: for w in ["weight", "bias"]: lowerCAmelCase : str = state_dict[ F'''{prefix}.encoder.layer.{teacher_idx}.attention.self.query.{w}''' ] lowerCAmelCase : List[Any] = state_dict[ F'''{prefix}.encoder.layer.{teacher_idx}.attention.self.key.{w}''' ] lowerCAmelCase : str = state_dict[ F'''{prefix}.encoder.layer.{teacher_idx}.attention.self.value.{w}''' ] lowerCAmelCase : Dict = state_dict[ F'''{prefix}.encoder.layer.{teacher_idx}.attention.output.dense.{w}''' ] lowerCAmelCase : Union[str, Any] = state_dict[ F'''{prefix}.encoder.layer.{teacher_idx}.attention.output.LayerNorm.{w}''' ] lowerCAmelCase : Union[str, Any] = state_dict[ F'''{prefix}.encoder.layer.{teacher_idx}.intermediate.dense.{w}''' ] lowerCAmelCase : Union[str, Any] = state_dict[ F'''{prefix}.encoder.layer.{teacher_idx}.output.dense.{w}''' ] lowerCAmelCase : Optional[Any] = state_dict[ F'''{prefix}.encoder.layer.{teacher_idx}.output.LayerNorm.{w}''' ] std_idx += 1 lowerCAmelCase : Optional[Any] = state_dict["""cls.predictions.decoder.weight"""] lowerCAmelCase : Tuple = state_dict["""cls.predictions.bias"""] if args.vocab_transform: for w in ["weight", "bias"]: lowerCAmelCase : int = state_dict[F'''cls.predictions.transform.dense.{w}'''] lowerCAmelCase : Optional[int] = state_dict[F'''cls.predictions.transform.LayerNorm.{w}'''] print(F'''N layers selected for distillation: {std_idx}''') print(F'''Number of params transferred for distillation: {len(compressed_sd.keys())}''') print(F'''Save transferred checkpoint to {args.dump_checkpoint}.''') torch.save(compressed_sd, args.dump_checkpoint)
372
'''simple docstring''' import copy import inspect import unittest from transformers import PretrainedConfig, SwiftFormerConfig 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 SwiftFormerForImageClassification, SwiftFormerModel from transformers.models.swiftformer.modeling_swiftformer import SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class _UpperCamelCase : '''simple docstring''' def __init__( self , a_ , a_=1_3 , a_=3 , a_=True , a_=True , a_=0.1 , a_=0.1 , a_=2_2_4 , a_=1_0_0_0 , a_=[3, 3, 6, 4] , a_=[4_8, 5_6, 1_1_2, 2_2_0] , ) -> Union[str, Any]: lowercase : Optional[Any] = parent lowercase : List[Any] = batch_size lowercase : Union[str, Any] = num_channels lowercase : str = is_training lowercase : Any = use_labels lowercase : Optional[Any] = hidden_dropout_prob lowercase : List[str] = attention_probs_dropout_prob lowercase : Optional[Any] = num_labels lowercase : str = image_size lowercase : Dict = layer_depths lowercase : List[str] = embed_dims def a__ ( self ) -> Optional[Any]: lowercase : int = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowercase : int = None if self.use_labels: lowercase : Optional[Any] = ids_tensor([self.batch_size] , self.num_labels ) lowercase : List[Any] = self.get_config() return config, pixel_values, labels def a__ ( self ) -> List[Any]: return SwiftFormerConfig( depths=self.layer_depths , embed_dims=self.embed_dims , mlp_ratio=4 , downsamples=[True, True, True, True] , hidden_act="gelu" , num_labels=self.num_labels , down_patch_size=3 , down_stride=2 , down_pad=1 , drop_rate=0.0 , drop_path_rate=0.0 , use_layer_scale=a_ , layer_scale_init_value=1e-5 , ) def a__ ( self , a_ , a_ , a_ ) -> Optional[Any]: lowercase : Tuple = SwiftFormerModel(config=a_ ) model.to(a_ ) model.eval() lowercase : Union[str, Any] = model(a_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.embed_dims[-1], 7, 7) ) def a__ ( self , a_ , a_ , a_ ) -> Any: lowercase : Dict = self.num_labels lowercase : Optional[int] = SwiftFormerForImageClassification(a_ ) model.to(a_ ) model.eval() lowercase : Tuple = model(a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) lowercase : Tuple = SwiftFormerForImageClassification(a_ ) model.to(a_ ) model.eval() lowercase : List[str] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowercase : str = model(a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def a__ ( self ) -> Dict: ((lowercase) , (lowercase) , (lowercase)) : Dict = self.prepare_config_and_inputs() lowercase : Dict = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class _UpperCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , unittest.TestCase): '''simple docstring''' _snake_case = (SwiftFormerModel, SwiftFormerForImageClassification) if is_torch_available() else () _snake_case = ( {'''feature-extraction''': SwiftFormerModel, '''image-classification''': SwiftFormerForImageClassification} if is_torch_available() else {} ) _snake_case = False _snake_case = False _snake_case = False _snake_case = False _snake_case = False def a__ ( self ) -> str: lowercase : Optional[int] = SwiftFormerModelTester(self ) lowercase : int = ConfigTester( self , config_class=a_ , has_text_modality=a_ , hidden_size=3_7 , num_attention_heads=1_2 , num_hidden_layers=1_2 , ) def a__ ( self ) -> Any: self.config_tester.run_common_tests() @unittest.skip(reason="SwiftFormer does not use inputs_embeds" ) def a__ ( self ) -> int: pass def a__ ( self ) -> Optional[int]: lowercase , lowercase : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase : Optional[int] = model_class(a_ ) lowercase : Tuple = model.get_output_embeddings() self.assertTrue(x is None or isinstance(a_ , nn.Linear ) ) def a__ ( self ) -> List[Any]: lowercase , lowercase : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase : str = model_class(a_ ) lowercase : int = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowercase : Union[str, Any] = [*signature.parameters.keys()] lowercase : int = ["pixel_values"] self.assertListEqual(arg_names[:1] , a_ ) def a__ ( self ) -> int: lowercase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def a__ ( self ) -> Optional[int]: lowercase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a_ ) @slow def a__ ( self ) -> Dict: for model_name in SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowercase : Optional[int] = SwiftFormerModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) @unittest.skip(reason="SwiftFormer does not output attentions" ) def a__ ( self ) -> Optional[Any]: pass def a__ ( self ) -> str: def check_hidden_states_output(a_ , a_ , a_ ): lowercase : Union[str, Any] = model_class(a_ ) model.to(a_ ) model.eval() with torch.no_grad(): lowercase : List[str] = model(**self._prepare_for_class(a_ , a_ ) ) lowercase : str = outputs.hidden_states lowercase : str = 8 self.assertEqual(len(a_ ) , a_ ) # TODO # SwiftFormer's feature maps are of shape (batch_size, embed_dims, height, width) # with the width and height being successively divided by 2, after every 2 blocks for i in range(len(a_ ) ): self.assertEqual( hidden_states[i].shape , torch.Size( [ self.model_tester.batch_size, self.model_tester.embed_dims[i // 2], (self.model_tester.image_size // 4) // 2 ** (i // 2), (self.model_tester.image_size // 4) // 2 ** (i // 2), ] ) , ) lowercase , lowercase : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase : Dict = True check_hidden_states_output(a_ , a_ , a_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowercase : str = True check_hidden_states_output(a_ , a_ , a_ ) def a__ ( self ) -> Optional[Any]: def _config_zero_init(a_ ): lowercase : str = copy.deepcopy(a_ ) for key in configs_no_init.__dict__.keys(): if "_range" in key or "_std" in key or "initializer_factor" in key or "layer_scale" in key: setattr(a_ , a_ , 1e-1_0 ) if isinstance(getattr(a_ , a_ , a_ ) , a_ ): lowercase : List[Any] = _config_zero_init(getattr(a_ , a_ ) ) setattr(a_ , a_ , a_ ) return configs_no_init lowercase , lowercase : Any = self.model_tester.prepare_config_and_inputs_for_common() lowercase : List[str] = _config_zero_init(a_ ) for model_class in self.all_model_classes: lowercase : Tuple = model_class(config=a_ ) for name, param in model.named_parameters(): if param.requires_grad: self.assertIn( ((param.data.mean() * 1e9) / 1e9).round().item() , [0.0, 1.0] , msg=F'''Parameter {name} of model {model_class} seems not properly initialized''' , ) @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." ) def a__ ( self ) -> Tuple: pass def _A ( ) -> List[str]: lowercase : Optional[int] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class _UpperCamelCase ( unittest.TestCase): '''simple docstring''' @cached_property def a__ ( self ) -> List[Any]: return ViTImageProcessor.from_pretrained("MBZUAI/swiftformer-xs" ) if is_vision_available() else None @slow def a__ ( self ) -> List[str]: lowercase : Tuple = SwiftFormerForImageClassification.from_pretrained("MBZUAI/swiftformer-xs" ).to(a_ ) lowercase : Any = self.default_image_processor lowercase : Optional[int] = prepare_img() lowercase : Any = image_processor(images=a_ , return_tensors="pt" ).to(a_ ) # forward pass with torch.no_grad(): lowercase : List[str] = model(**a_ ) # verify the logits lowercase : str = torch.Size((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape , a_ ) lowercase : List[Any] = torch.tensor([[-2.1_7_0_3e0_0, 2.1_1_0_7e0_0, -2.0_8_1_1e0_0]] ).to(a_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , a_ , atol=1e-4 ) )
372
1
'''simple docstring''' import argparse import csv import logging import os import random import numpy as np import torch from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset from tqdm import tqdm, trange from transformers import ( CONFIG_NAME, WEIGHTS_NAME, AdamW, OpenAIGPTDoubleHeadsModel, OpenAIGPTTokenizer, get_linear_schedule_with_warmup, ) logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO ) lowerCAmelCase : Union[str, Any] = logging.getLogger(__name__) def A_( A : List[Any] , A : List[str]) -> str: UpperCamelCase = np.argmax(__UpperCamelCase , axis=1) return np.sum(outputs == labels) def A_( A : Optional[Any]) -> Optional[Any]: with open(__UpperCamelCase , encoding='utf_8') as f: UpperCamelCase = csv.reader(__UpperCamelCase) UpperCamelCase = [] next(__UpperCamelCase) # skip the first line for line in tqdm(__UpperCamelCase): output.append((' '.join(line[1:5]), line[5], line[6], int(line[-1]) - 1)) return output def A_( A : List[str] , A : List[Any] , A : Union[str, Any] , A : Union[str, Any] , A : Dict , A : Dict) -> Optional[int]: UpperCamelCase = [] for dataset in encoded_datasets: UpperCamelCase = len(__UpperCamelCase) UpperCamelCase = np.zeros((n_batch, 2, input_len) , dtype=np.intaa) UpperCamelCase = np.zeros((n_batch, 2) , dtype=np.intaa) UpperCamelCase = np.full((n_batch, 2, input_len) , fill_value=-100 , dtype=np.intaa) UpperCamelCase = np.zeros((n_batch,) , dtype=np.intaa) for ( i, (story, conta, conta, mc_label), ) in enumerate(__UpperCamelCase): UpperCamelCase = [start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token] UpperCamelCase = [start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token] UpperCamelCase = with_conta UpperCamelCase = with_conta UpperCamelCase = len(__UpperCamelCase) - 1 UpperCamelCase = len(__UpperCamelCase) - 1 UpperCamelCase = with_conta UpperCamelCase = with_conta UpperCamelCase = mc_label UpperCamelCase = (input_ids, mc_token_ids, lm_labels, mc_labels) tensor_datasets.append(tuple(torch.tensor(__UpperCamelCase) for t in all_inputs)) return tensor_datasets def A_( ) -> List[Any]: UpperCamelCase = argparse.ArgumentParser() parser.add_argument('--model_name' , type=__UpperCamelCase , default='openai-gpt' , help='pretrained model name') parser.add_argument('--do_train' , action='store_true' , help='Whether to run training.') parser.add_argument('--do_eval' , action='store_true' , help='Whether to run eval on the dev set.') parser.add_argument( '--output_dir' , default=__UpperCamelCase , type=__UpperCamelCase , required=__UpperCamelCase , help='The output directory where the model predictions and checkpoints will be written.' , ) parser.add_argument('--train_dataset' , type=__UpperCamelCase , default='') parser.add_argument('--eval_dataset' , type=__UpperCamelCase , default='') parser.add_argument('--seed' , type=__UpperCamelCase , default=42) parser.add_argument('--num_train_epochs' , type=__UpperCamelCase , default=3) parser.add_argument('--train_batch_size' , type=__UpperCamelCase , default=8) parser.add_argument('--eval_batch_size' , type=__UpperCamelCase , default=16) parser.add_argument('--adam_epsilon' , default=1E-8 , type=__UpperCamelCase , help='Epsilon for Adam optimizer.') parser.add_argument('--max_grad_norm' , type=__UpperCamelCase , default=1) parser.add_argument( '--max_steps' , default=-1 , type=__UpperCamelCase , help=( 'If > 0: set total number of training steps to perform. Override num_train_epochs.' ) , ) parser.add_argument( '--gradient_accumulation_steps' , type=__UpperCamelCase , default=1 , help='Number of updates steps to accumulate before performing a backward/update pass.' , ) parser.add_argument('--learning_rate' , type=__UpperCamelCase , default=6.25E-5) parser.add_argument('--warmup_steps' , default=0 , type=__UpperCamelCase , help='Linear warmup over warmup_steps.') parser.add_argument('--lr_schedule' , type=__UpperCamelCase , default='warmup_linear') parser.add_argument('--weight_decay' , type=__UpperCamelCase , default=0.01) parser.add_argument('--lm_coef' , type=__UpperCamelCase , default=0.9) parser.add_argument('--n_valid' , type=__UpperCamelCase , default=374) parser.add_argument('--server_ip' , type=__UpperCamelCase , default='' , help='Can be used for distant debugging.') parser.add_argument('--server_port' , type=__UpperCamelCase , default='' , help='Can be used for distant debugging.') UpperCamelCase = parser.parse_args() print(__UpperCamelCase) if args.server_ip and args.server_port: # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd print('Waiting for debugger attach') ptvsd.enable_attach(address=(args.server_ip, args.server_port) , redirect_output=__UpperCamelCase) ptvsd.wait_for_attach() random.seed(args.seed) np.random.seed(args.seed) torch.manual_seed(args.seed) torch.cuda.manual_seed_all(args.seed) UpperCamelCase = torch.device('cuda' if torch.cuda.is_available() else 'cpu') UpperCamelCase = torch.cuda.device_count() logger.info('device: {}, n_gpu {}'.format(__UpperCamelCase , __UpperCamelCase)) if not args.do_train and not args.do_eval: raise ValueError('At least one of `do_train` or `do_eval` must be True.') if not os.path.exists(args.output_dir): os.makedirs(args.output_dir) # Load tokenizer and model # This loading functions also add new tokens and embeddings called `special tokens` # These new embeddings will be fine-tuned on the RocStories dataset UpperCamelCase = ['_start_', '_delimiter_', '_classify_'] UpperCamelCase = OpenAIGPTTokenizer.from_pretrained(args.model_name) tokenizer.add_tokens(__UpperCamelCase) UpperCamelCase = tokenizer.convert_tokens_to_ids(__UpperCamelCase) UpperCamelCase = OpenAIGPTDoubleHeadsModel.from_pretrained(args.model_name) model.resize_token_embeddings(len(__UpperCamelCase)) model.to(__UpperCamelCase) # Load and encode the datasets def tokenize_and_encode(A : List[str]): if isinstance(__UpperCamelCase , __UpperCamelCase): return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(__UpperCamelCase)) elif isinstance(__UpperCamelCase , __UpperCamelCase): return obj return [tokenize_and_encode(__UpperCamelCase) for o in obj] logger.info('Encoding dataset...') UpperCamelCase = load_rocstories_dataset(args.train_dataset) UpperCamelCase = load_rocstories_dataset(args.eval_dataset) UpperCamelCase = (train_dataset, eval_dataset) UpperCamelCase = tokenize_and_encode(__UpperCamelCase) # Compute the max input length for the Transformer UpperCamelCase = model.config.n_positions // 2 - 2 UpperCamelCase = max( len(story[:max_length]) + max(len(conta[:max_length]) , len(conta[:max_length])) + 3 for dataset in encoded_datasets for story, conta, conta, _ in dataset) UpperCamelCase = min(__UpperCamelCase , model.config.n_positions) # Max size of input for the pre-trained model # Prepare inputs tensors and dataloaders UpperCamelCase = pre_process_datasets(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , *__UpperCamelCase) UpperCamelCase , UpperCamelCase = tensor_datasets[0], tensor_datasets[1] UpperCamelCase = TensorDataset(*__UpperCamelCase) UpperCamelCase = RandomSampler(__UpperCamelCase) UpperCamelCase = DataLoader(__UpperCamelCase , sampler=__UpperCamelCase , batch_size=args.train_batch_size) UpperCamelCase = TensorDataset(*__UpperCamelCase) UpperCamelCase = SequentialSampler(__UpperCamelCase) UpperCamelCase = DataLoader(__UpperCamelCase , sampler=__UpperCamelCase , batch_size=args.eval_batch_size) # Prepare optimizer if args.do_train: if args.max_steps > 0: UpperCamelCase = args.max_steps UpperCamelCase = args.max_steps // (len(__UpperCamelCase) // args.gradient_accumulation_steps) + 1 else: UpperCamelCase = len(__UpperCamelCase) // args.gradient_accumulation_steps * args.num_train_epochs UpperCamelCase = list(model.named_parameters()) UpperCamelCase = ['bias', 'LayerNorm.bias', 'LayerNorm.weight'] UpperCamelCase = [ { 'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], 'weight_decay': args.weight_decay, }, {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}, ] UpperCamelCase = AdamW(__UpperCamelCase , lr=args.learning_rate , eps=args.adam_epsilon) UpperCamelCase = get_linear_schedule_with_warmup( __UpperCamelCase , num_warmup_steps=args.warmup_steps , num_training_steps=__UpperCamelCase) if args.do_train: UpperCamelCase , UpperCamelCase , UpperCamelCase = 0, 0, None model.train() for _ in trange(int(args.num_train_epochs) , desc='Epoch'): UpperCamelCase = 0 UpperCamelCase = 0 UpperCamelCase = tqdm(__UpperCamelCase , desc='Training') for step, batch in enumerate(__UpperCamelCase): UpperCamelCase = tuple(t.to(__UpperCamelCase) for t in batch) UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = batch UpperCamelCase = model(__UpperCamelCase , mc_token_ids=__UpperCamelCase , lm_labels=__UpperCamelCase , mc_labels=__UpperCamelCase) UpperCamelCase = args.lm_coef * losses[0] + losses[1] loss.backward() optimizer.step() scheduler.step() optimizer.zero_grad() tr_loss += loss.item() UpperCamelCase = ( loss.item() if exp_average_loss is None else 0.7 * exp_average_loss + 0.3 * loss.item() ) nb_tr_steps += 1 UpperCamelCase = 'Training loss: {:.2e} lr: {:.2e}'.format(__UpperCamelCase , scheduler.get_lr()[0]) # Save a trained model if args.do_train: # Save a trained model, configuration and tokenizer UpperCamelCase = model.module if hasattr(__UpperCamelCase , 'module') else model # Only save the model itself # If we save using the predefined names, we can load using `from_pretrained` UpperCamelCase = os.path.join(args.output_dir , __UpperCamelCase) UpperCamelCase = os.path.join(args.output_dir , __UpperCamelCase) torch.save(model_to_save.state_dict() , __UpperCamelCase) model_to_save.config.to_json_file(__UpperCamelCase) tokenizer.save_vocabulary(args.output_dir) # Load a trained model and vocabulary that you have fine-tuned UpperCamelCase = OpenAIGPTDoubleHeadsModel.from_pretrained(args.output_dir) UpperCamelCase = OpenAIGPTTokenizer.from_pretrained(args.output_dir) model.to(__UpperCamelCase) if args.do_eval: model.eval() UpperCamelCase , UpperCamelCase = 0, 0 UpperCamelCase , UpperCamelCase = 0, 0 for batch in tqdm(__UpperCamelCase , desc='Evaluating'): UpperCamelCase = tuple(t.to(__UpperCamelCase) for t in batch) UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = batch with torch.no_grad(): UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = model( __UpperCamelCase , mc_token_ids=__UpperCamelCase , lm_labels=__UpperCamelCase , mc_labels=__UpperCamelCase) UpperCamelCase = mc_logits.detach().cpu().numpy() UpperCamelCase = mc_labels.to('cpu').numpy() UpperCamelCase = accuracy(__UpperCamelCase , __UpperCamelCase) eval_loss += mc_loss.mean().item() eval_accuracy += tmp_eval_accuracy nb_eval_examples += input_ids.size(0) nb_eval_steps += 1 UpperCamelCase = eval_loss / nb_eval_steps UpperCamelCase = eval_accuracy / nb_eval_examples UpperCamelCase = tr_loss / nb_tr_steps if args.do_train else None UpperCamelCase = {'eval_loss': eval_loss, 'eval_accuracy': eval_accuracy, 'train_loss': train_loss} UpperCamelCase = os.path.join(args.output_dir , 'eval_results.txt') with open(__UpperCamelCase , 'w') as writer: logger.info('***** Eval results *****') for key in sorted(result.keys()): logger.info(' %s = %s' , __UpperCamelCase , str(result[key])) writer.write('%s = %s\n' % (key, str(result[key]))) if __name__ == "__main__": main()
708
'''simple docstring''' import torch from torch import nn from transformers import CLIPPreTrainedModel, CLIPVisionModel from ...models.attention import BasicTransformerBlock from ...utils import logging lowerCAmelCase : str = logging.get_logger(__name__) # pylint: disable=invalid-name class SCREAMING_SNAKE_CASE__ ( snake_case_): def __init__( self , A_ , A_=768 )-> Any: '''simple docstring''' super().__init__(A_ ) UpperCamelCase = proj_size UpperCamelCase = CLIPVisionModel(A_ ) UpperCamelCase = PaintByExampleMapper(A_ ) UpperCamelCase = nn.LayerNorm(config.hidden_size ) UpperCamelCase = nn.Linear(config.hidden_size , self.proj_size ) # uncondition for scaling UpperCamelCase = nn.Parameter(torch.randn((1, 1, self.proj_size) ) ) def UpperCAmelCase_ ( self , A_ , A_=False )-> Dict: '''simple docstring''' UpperCamelCase = self.model(pixel_values=A_ ) UpperCamelCase = clip_output.pooler_output UpperCamelCase = self.mapper(latent_states[:, None] ) UpperCamelCase = self.final_layer_norm(A_ ) UpperCamelCase = self.proj_out(A_ ) if return_uncond_vector: return latent_states, self.uncond_vector return latent_states class SCREAMING_SNAKE_CASE__ ( nn.Module): def __init__( self , A_ )-> Tuple: '''simple docstring''' super().__init__() UpperCamelCase = (config.num_hidden_layers + 1) // 5 UpperCamelCase = config.hidden_size UpperCamelCase = 1 UpperCamelCase = nn.ModuleList( [ BasicTransformerBlock(A_ , A_ , A_ , activation_fn='gelu' , attention_bias=A_ ) for _ in range(A_ ) ] ) def UpperCAmelCase_ ( self , A_ )-> Dict: '''simple docstring''' for block in self.blocks: UpperCamelCase = block(A_ ) return hidden_states
432
0
from ..utils import DummyObject, requires_backends class SCREAMING_SNAKE_CASE__ ( metaclass=SCREAMING_SNAKE_CASE__ ): '''simple docstring''' __lowerCamelCase : Any = ["torch", "scipy"] def __init__( self, *lowerCamelCase__, **lowerCamelCase__ ): requires_backends(self, ["""torch""", """scipy"""] ) @classmethod def _lowerCAmelCase ( cls, *lowerCamelCase__, **lowerCamelCase__ ): requires_backends(cls, ["""torch""", """scipy"""] ) @classmethod def _lowerCAmelCase ( cls, *lowerCamelCase__, **lowerCamelCase__ ): requires_backends(cls, ["""torch""", """scipy"""] )
662
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) SCREAMING_SNAKE_CASE_:int = { """configuration_blenderbot""": [ """BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """BlenderbotConfig""", """BlenderbotOnnxConfig""", ], """tokenization_blenderbot""": ["""BlenderbotTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_:Union[str, Any] = ["""BlenderbotTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_:Optional[int] = [ """BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST""", """BlenderbotForCausalLM""", """BlenderbotForConditionalGeneration""", """BlenderbotModel""", """BlenderbotPreTrainedModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_:Union[str, Any] = [ """TFBlenderbotForConditionalGeneration""", """TFBlenderbotModel""", """TFBlenderbotPreTrainedModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_:Any = [ """FlaxBlenderbotForConditionalGeneration""", """FlaxBlenderbotModel""", """FlaxBlenderbotPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_blenderbot import ( BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP, BlenderbotConfig, BlenderbotOnnxConfig, ) from .tokenization_blenderbot import BlenderbotTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_blenderbot_fast import BlenderbotTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blenderbot import ( BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST, BlenderbotForCausalLM, BlenderbotForConditionalGeneration, BlenderbotModel, BlenderbotPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blenderbot import ( TFBlenderbotForConditionalGeneration, TFBlenderbotModel, TFBlenderbotPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_blenderbot import ( FlaxBlenderbotForConditionalGeneration, FlaxBlenderbotModel, FlaxBlenderbotPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE_:Optional[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
662
1
'''simple docstring''' from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging UpperCamelCase : Tuple = logging.get_logger(__name__) UpperCamelCase : Optional[int] = { """google/umt5-small""": """https://huggingface.co/google/umt5-small/resolve/main/config.json""", # See all umt5 models at https://huggingface.co/models?filter=umt5 } class UpperCamelCase ( __UpperCAmelCase ): """simple docstring""" A : Any = "umt5" A : Union[str, Any] = ["past_key_values"] def __init__( self : Dict , UpperCAmelCase_ : Dict=2_5_0_1_1_2 , UpperCAmelCase_ : Any=5_1_2 , UpperCAmelCase_ : List[str]=6_4 , UpperCAmelCase_ : Optional[int]=1_0_2_4 , UpperCAmelCase_ : List[str]=8 , UpperCAmelCase_ : str=None , UpperCAmelCase_ : int=6 , UpperCAmelCase_ : int=3_2 , UpperCAmelCase_ : Optional[Any]=1_2_8 , UpperCAmelCase_ : int=0.1 , UpperCAmelCase_ : str=1e-6 , UpperCAmelCase_ : Tuple=1.0 , UpperCAmelCase_ : List[Any]="gated-gelu" , UpperCAmelCase_ : Tuple=True , UpperCAmelCase_ : int=True , UpperCAmelCase_ : Dict="T5Tokenizer" , UpperCAmelCase_ : int=True , UpperCAmelCase_ : List[str]=0 , UpperCAmelCase_ : Dict=1 , UpperCAmelCase_ : Tuple=0 , **UpperCAmelCase_ : List[Any] , ): """simple docstring""" super().__init__( is_encoder_decoder=UpperCAmelCase_ , tokenizer_class=UpperCAmelCase_ , tie_word_embeddings=UpperCAmelCase_ , pad_token_id=UpperCAmelCase_ , eos_token_id=UpperCAmelCase_ , decoder_start_token_id=UpperCAmelCase_ , **UpperCAmelCase_ , ) a : Union[str, Any] = vocab_size a : List[Any] = d_model a : Optional[int] = d_kv a : str = d_ff a : Dict = num_layers a : Tuple = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry a : Union[str, Any] = num_heads a : str = relative_attention_num_buckets a : List[Any] = relative_attention_max_distance a : str = dropout_rate a : List[str] = layer_norm_epsilon a : List[Any] = initializer_factor a : int = feed_forward_proj a : Union[str, Any] = use_cache a : int = self.feed_forward_proj.split('-') a : Optional[int] = act_info[-1] a : Any = act_info[0] == 'gated' if len(UpperCAmelCase_) > 1 and act_info[0] != "gated" or len(UpperCAmelCase_) > 2: raise ValueError( f"""`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.""" 'Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. ' '\'gated-gelu\' or \'relu\'') if feed_forward_proj == "gated-gelu": a : str = 'gelu_new' @property def SCREAMING_SNAKE_CASE_ ( self : Tuple): """simple docstring""" return self.d_model @property def SCREAMING_SNAKE_CASE_ ( self : str): """simple docstring""" return self.num_heads @property def SCREAMING_SNAKE_CASE_ ( self : List[Any]): """simple docstring""" return self.num_layers class UpperCamelCase ( __UpperCAmelCase ): """simple docstring""" @property # Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.inputs def SCREAMING_SNAKE_CASE_ ( self : int): """simple docstring""" a : Dict = { 'input_ids': {0: 'batch', 1: 'encoder_sequence'}, 'attention_mask': {0: 'batch', 1: 'encoder_sequence'}, } if self.use_past: a : str = 'past_encoder_sequence + sequence' a : int = {0: 'batch'} a : Union[str, Any] = {0: 'batch', 1: 'past_decoder_sequence + sequence'} else: a : Optional[int] = {0: 'batch', 1: 'decoder_sequence'} a : Dict = {0: 'batch', 1: 'decoder_sequence'} if self.use_past: self.fill_with_past_key_values_(UpperCAmelCase_ , direction='inputs') return common_inputs @property # Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.default_onnx_opset def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any]): """simple docstring""" return 1_3 @property def SCREAMING_SNAKE_CASE_ ( self : Optional[int]): """simple docstring""" return 5e-4
717
'''simple docstring''' import importlib import os import sys # This is required to make the module import works (when the python process is running from the root of the repo) sys.path.append(""".""") def SCREAMING_SNAKE_CASE__ ( snake_case : Dict ) -> Optional[Any]: """simple docstring""" a : Union[str, Any] = test_file.split(os.path.sep ) if components[0:2] != ["tests", "models"]: raise ValueError( '`test_file` should start with `tests/models/` (with `/` being the OS specific path separator). Got ' F"""{test_file} instead.""" ) a : int = components[-1] if not test_fn.endswith('py' ): raise ValueError(F"""`test_file` should be a python file. Got {test_fn} instead.""" ) if not test_fn.startswith('test_modeling_' ): raise ValueError( F"""`test_file` should point to a file name of the form `test_modeling_*.py`. Got {test_fn} instead.""" ) a : Tuple = components[:-1] + [test_fn.replace('.py' , '' )] a : Union[str, Any] = '.'.join(snake_case ) return test_module_path def SCREAMING_SNAKE_CASE__ ( snake_case : List[Any] ) -> Tuple: """simple docstring""" a : List[str] = get_module_path(snake_case ) a : Tuple = importlib.import_module(snake_case ) return test_module def SCREAMING_SNAKE_CASE__ ( snake_case : Union[str, Any] ) -> Optional[Any]: """simple docstring""" a : Optional[int] = [] a : str = get_test_module(snake_case ) for attr in dir(snake_case ): if attr.endswith('ModelTester' ): tester_classes.append(getattr(snake_case , snake_case ) ) # sort with class names return sorted(snake_case , key=lambda snake_case : x.__name__ ) def SCREAMING_SNAKE_CASE__ ( snake_case : Tuple ) -> str: """simple docstring""" a : Dict = [] a : List[str] = get_test_module(snake_case ) for attr in dir(snake_case ): a : int = getattr(snake_case , snake_case ) # (TF/Flax)ModelTesterMixin is also an attribute in specific model test module. Let's exclude them by checking # `all_model_classes` is not empty (which also excludes other special classes). a : Optional[Any] = getattr(snake_case , 'all_model_classes' , [] ) if len(snake_case ) > 0: test_classes.append(snake_case ) # sort with class names return sorted(snake_case , key=lambda snake_case : x.__name__ ) def SCREAMING_SNAKE_CASE__ ( snake_case : Any ) -> Union[str, Any]: """simple docstring""" a : Dict = get_test_classes(snake_case ) a : List[str] = set() for test_class in test_classes: model_classes.update(test_class.all_model_classes ) # sort with class names return sorted(snake_case , key=lambda snake_case : x.__name__ ) def SCREAMING_SNAKE_CASE__ ( snake_case : Optional[Any] ) -> str: """simple docstring""" a : Dict = test_class() if hasattr(snake_case , 'setUp' ): test.setUp() a : Union[str, Any] = None if hasattr(snake_case , 'model_tester' ): # `(TF/Flax)ModelTesterMixin` has this attribute default to `None`. Let's skip this case. if test.model_tester is not None: a : Tuple = test.model_tester.__class__ return model_tester def SCREAMING_SNAKE_CASE__ ( snake_case : Dict , snake_case : Optional[Any] ) -> Optional[Any]: """simple docstring""" a : Optional[int] = get_test_classes(snake_case ) a : str = [] for test_class in test_classes: if model_class in test_class.all_model_classes: target_test_classes.append(snake_case ) # sort with class names return sorted(snake_case , key=lambda snake_case : x.__name__ ) def SCREAMING_SNAKE_CASE__ ( snake_case : Optional[Any] , snake_case : int ) -> Optional[int]: """simple docstring""" a : Any = get_test_classes_for_model(snake_case , snake_case ) a : Tuple = [] for test_class in test_classes: a : Any = get_model_tester_from_test_class(snake_case ) if tester_class is not None: tester_classes.append(snake_case ) # sort with class names return sorted(snake_case , key=lambda snake_case : x.__name__ ) def SCREAMING_SNAKE_CASE__ ( snake_case : Optional[int] ) -> str: """simple docstring""" a : Dict = get_test_classes(snake_case ) a : Optional[Any] = {test_class: get_model_tester_from_test_class(snake_case ) for test_class in test_classes} return test_tester_mapping def SCREAMING_SNAKE_CASE__ ( snake_case : Optional[int] ) -> Union[str, Any]: """simple docstring""" a : Dict = get_model_classes(snake_case ) a : Optional[Any] = { model_class: get_test_classes_for_model(snake_case , snake_case ) for model_class in model_classes } return model_test_mapping def SCREAMING_SNAKE_CASE__ ( snake_case : str ) -> Optional[Any]: """simple docstring""" a : str = get_model_classes(snake_case ) a : List[Any] = { model_class: get_tester_classes_for_model(snake_case , snake_case ) for model_class in model_classes } return model_to_tester_mapping def SCREAMING_SNAKE_CASE__ ( snake_case : Any ) -> Union[str, Any]: """simple docstring""" if isinstance(snake_case , snake_case ): return o elif isinstance(snake_case , snake_case ): return o.__name__ elif isinstance(snake_case , (list, tuple) ): return [to_json(snake_case ) for x in o] elif isinstance(snake_case , snake_case ): return {to_json(snake_case ): to_json(snake_case ) for k, v in o.items()} else: return o
610
0
'''simple docstring''' import math from typing import Any, Callable, List, Optional, Tuple, Union import numpy as np import torch from ...models import TaFilmDecoder from ...schedulers import DDPMScheduler from ...utils import is_onnx_available, logging, randn_tensor if is_onnx_available(): from ..onnx_utils import OnnxRuntimeModel from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline from .continous_encoder import SpectrogramContEncoder from .notes_encoder import SpectrogramNotesEncoder _UpperCAmelCase : Dict = logging.get_logger(__name__) # pylint: disable=invalid-name _UpperCAmelCase : Any = 2_56 class lowercase_ ( UpperCamelCase_ ): """simple docstring""" __lowerCAmelCase = ['melgan'] def __init__( self : str, UpperCamelCase__ : SpectrogramNotesEncoder, UpperCamelCase__ : SpectrogramContEncoder, UpperCamelCase__ : TaFilmDecoder, UpperCamelCase__ : DDPMScheduler, UpperCamelCase__ : OnnxRuntimeModel if is_onnx_available() else Any, ) -> None: super().__init__() # From MELGAN _A = math.log(1e-5 ) # Matches MelGAN training. _A = 4.0 # Largest value for most examples _A = 1_28 self.register_modules( notes_encoder=lowercase_, continuous_encoder=lowercase_, decoder=lowercase_, scheduler=lowercase_, melgan=lowercase_, ) def __UpperCAmelCase ( self : Optional[Any], UpperCamelCase__ : List[str], UpperCamelCase__ : List[Any]=(-1.0, 1.0), UpperCamelCase__ : Any=False ) -> List[str]: _A = output_range if clip: _A = torch.clip(lowercase_, self.min_value, self.max_value ) # Scale to [0, 1]. _A = (features - self.min_value) / (self.max_value - self.min_value) # Scale to [min_out, max_out]. return zero_one * (max_out - min_out) + min_out def __UpperCAmelCase ( self : List[str], UpperCamelCase__ : str, UpperCamelCase__ : int=(-1.0, 1.0), UpperCamelCase__ : List[str]=False ) -> Union[str, Any]: _A = input_range _A = torch.clip(lowercase_, lowercase_, lowercase_ ) if clip else outputs # Scale to [0, 1]. _A = (outputs - min_out) / (max_out - min_out) # Scale to [self.min_value, self.max_value]. return zero_one * (self.max_value - self.min_value) + self.min_value def __UpperCAmelCase ( self : Union[str, Any], UpperCamelCase__ : Optional[Any], UpperCamelCase__ : Tuple, UpperCamelCase__ : Union[str, Any] ) -> List[str]: _A = input_tokens > 0 _A = self.notes_encoder( encoder_input_tokens=lowercase_, encoder_inputs_mask=lowercase_ ) _A = self.continuous_encoder( encoder_inputs=lowercase_, encoder_inputs_mask=lowercase_ ) return [(tokens_encoded, tokens_mask), (continuous_encoded, continuous_mask)] def __UpperCAmelCase ( self : List[str], UpperCamelCase__ : Optional[Any], UpperCamelCase__ : str, UpperCamelCase__ : List[Any] ) -> Dict: _A = noise_time if not torch.is_tensor(lowercase_ ): _A = torch.tensor([timesteps], dtype=torch.long, device=input_tokens.device ) elif torch.is_tensor(lowercase_ ) and len(timesteps.shape ) == 0: _A = timesteps[None].to(input_tokens.device ) # broadcast to batch dimension in a way that's compatible with ONNX/Core ML _A = timesteps * torch.ones(input_tokens.shape[0], dtype=timesteps.dtype, device=timesteps.device ) _A = self.decoder( encodings_and_masks=lowercase_, decoder_input_tokens=lowercase_, decoder_noise_time=lowercase_ ) return logits @torch.no_grad() def __call__( self : Dict, UpperCamelCase__ : List[List[int]], UpperCamelCase__ : Optional[torch.Generator] = None, UpperCamelCase__ : int = 1_00, UpperCamelCase__ : bool = True, UpperCamelCase__ : str = "numpy", UpperCamelCase__ : Optional[Callable[[int, int, torch.FloatTensor], None]] = None, UpperCamelCase__ : int = 1, ) -> Union[AudioPipelineOutput, Tuple]: if (callback_steps is None) or ( callback_steps is not None and (not isinstance(lowercase_, lowercase_ ) or callback_steps <= 0) ): raise ValueError( f'`callback_steps` has to be a positive integer but is {callback_steps} of type' f' {type(lowercase_ )}.' ) _A = np.zeros([1, TARGET_FEATURE_LENGTH, self.n_dims], dtype=np.floataa ) _A = np.zeros([1, 0, self.n_dims], np.floataa ) _A = torch.ones((1, TARGET_FEATURE_LENGTH), dtype=lowercase_, device=self.device ) for i, encoder_input_tokens in enumerate(lowercase_ ): if i == 0: _A = torch.from_numpy(pred_mel[:1].copy() ).to( device=self.device, dtype=self.decoder.dtype ) # The first chunk has no previous context. _A = torch.zeros((1, TARGET_FEATURE_LENGTH), dtype=lowercase_, device=self.device ) else: # The full song pipeline does not feed in a context feature, so the mask # will be all 0s after the feature converter. Because we know we're # feeding in a full context chunk from the previous prediction, set it # to all 1s. _A = ones _A = self.scale_features( lowercase_, output_range=[-1.0, 1.0], clip=lowercase_ ) _A = self.encode( input_tokens=torch.IntTensor([encoder_input_tokens] ).to(device=self.device ), continuous_inputs=lowercase_, continuous_mask=lowercase_, ) # Sample encoder_continuous_inputs shaped gaussian noise to begin loop _A = randn_tensor( shape=encoder_continuous_inputs.shape, generator=lowercase_, device=self.device, dtype=self.decoder.dtype, ) # set step values self.scheduler.set_timesteps(lowercase_ ) # Denoising diffusion loop for j, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): _A = self.decode( encodings_and_masks=lowercase_, input_tokens=lowercase_, noise_time=t / self.scheduler.config.num_train_timesteps, ) # Compute previous output: x_t -> x_t-1 _A = self.scheduler.step(lowercase_, lowercase_, lowercase_, generator=lowercase_ ).prev_sample _A = self.scale_to_features(lowercase_, input_range=[-1.0, 1.0] ) _A = mel[:1] _A = mel.cpu().float().numpy() _A = np.concatenate([full_pred_mel, pred_mel[:1]], axis=1 ) # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(lowercase_, lowercase_ ) logger.info('Generated segment', lowercase_ ) if output_type == "numpy" and not is_onnx_available(): raise ValueError( 'Cannot return output in \'np\' format if ONNX is not available. Make sure to have ONNX installed or set \'output_type\' to \'mel\'.' ) elif output_type == "numpy" and self.melgan is None: raise ValueError( 'Cannot return output in \'np\' format if melgan component is not defined. Make sure to define `self.melgan` or set \'output_type\' to \'mel\'.' ) if output_type == "numpy": _A = self.melgan(input_features=full_pred_mel.astype(np.floataa ) ) else: _A = full_pred_mel if not return_dict: return (output,) return AudioPipelineOutput(audios=lowercase_ )
107
import json import os import sys import tempfile import unittest from pathlib import Path from shutil import copyfile from huggingface_hub import HfFolder, Repository, create_repo, delete_repo from requests.exceptions import HTTPError import transformers from transformers import ( CONFIG_MAPPING, FEATURE_EXTRACTOR_MAPPING, PROCESSOR_MAPPING, TOKENIZER_MAPPING, AutoConfig, AutoFeatureExtractor, AutoProcessor, AutoTokenizer, BertTokenizer, ProcessorMixin, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaProcessor, ) from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test from transformers.tokenization_utils import TOKENIZER_CONFIG_FILE from transformers.utils import FEATURE_EXTRACTOR_NAME, is_tokenizers_available 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 from test_module.custom_processing import CustomProcessor # noqa E402 from test_module.custom_tokenization import CustomTokenizer # noqa E402 lowerCamelCase = get_tests_dir('fixtures/dummy_feature_extractor_config.json') lowerCamelCase = get_tests_dir('fixtures/vocab.json') lowerCamelCase = get_tests_dir('fixtures') class A ( unittest.TestCase ): UpperCamelCase__ : Dict =['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'bla', 'blou'] def lowerCamelCase ( self : str ) -> Optional[Any]: """simple docstring""" _lowerCamelCase : Dict =0 def lowerCamelCase ( self : str ) -> List[str]: """simple docstring""" _lowerCamelCase : List[Any] =AutoProcessor.from_pretrained('facebook/wav2vec2-base-960h' ) self.assertIsInstance(lowercase_ , lowercase_ ) def lowerCamelCase ( self : int ) -> Tuple: """simple docstring""" with tempfile.TemporaryDirectory() as tmpdirname: _lowerCamelCase : int =WavaVecaConfig() _lowerCamelCase : Dict =AutoProcessor.from_pretrained('facebook/wav2vec2-base-960h' ) # save in new folder model_config.save_pretrained(lowercase_ ) processor.save_pretrained(lowercase_ ) _lowerCamelCase : Any =AutoProcessor.from_pretrained(lowercase_ ) self.assertIsInstance(lowercase_ , lowercase_ ) def lowerCamelCase ( self : str ) -> Union[str, Any]: """simple docstring""" with tempfile.TemporaryDirectory() as tmpdirname: # copy relevant files copyfile(lowercase_ , os.path.join(lowercase_ , lowercase_ ) ) copyfile(lowercase_ , os.path.join(lowercase_ , 'vocab.json' ) ) _lowerCamelCase : Union[str, Any] =AutoProcessor.from_pretrained(lowercase_ ) self.assertIsInstance(lowercase_ , lowercase_ ) def lowerCamelCase ( self : Any ) -> Optional[Any]: """simple docstring""" with tempfile.TemporaryDirectory() as tmpdirname: _lowerCamelCase : List[Any] =WavaVecaFeatureExtractor() _lowerCamelCase : List[str] =AutoTokenizer.from_pretrained('facebook/wav2vec2-base-960h' ) _lowerCamelCase : str =WavaVecaProcessor(lowercase_ , lowercase_ ) # save in new folder processor.save_pretrained(lowercase_ ) # drop `processor_class` in tokenizer with open(os.path.join(lowercase_ , lowercase_ ) , 'r' ) as f: _lowerCamelCase : Optional[int] =json.load(lowercase_ ) config_dict.pop('processor_class' ) with open(os.path.join(lowercase_ , lowercase_ ) , 'w' ) as f: f.write(json.dumps(lowercase_ ) ) _lowerCamelCase : Optional[int] =AutoProcessor.from_pretrained(lowercase_ ) self.assertIsInstance(lowercase_ , lowercase_ ) def lowerCamelCase ( self : Dict ) -> Optional[int]: """simple docstring""" with tempfile.TemporaryDirectory() as tmpdirname: _lowerCamelCase : Optional[Any] =WavaVecaFeatureExtractor() _lowerCamelCase : Tuple =AutoTokenizer.from_pretrained('facebook/wav2vec2-base-960h' ) _lowerCamelCase : Dict =WavaVecaProcessor(lowercase_ , lowercase_ ) # save in new folder processor.save_pretrained(lowercase_ ) # drop `processor_class` in feature extractor with open(os.path.join(lowercase_ , lowercase_ ) , 'r' ) as f: _lowerCamelCase : Union[str, Any] =json.load(lowercase_ ) config_dict.pop('processor_class' ) with open(os.path.join(lowercase_ , lowercase_ ) , 'w' ) as f: f.write(json.dumps(lowercase_ ) ) _lowerCamelCase : Optional[int] =AutoProcessor.from_pretrained(lowercase_ ) self.assertIsInstance(lowercase_ , lowercase_ ) def lowerCamelCase ( self : List[str] ) -> List[str]: """simple docstring""" with tempfile.TemporaryDirectory() as tmpdirname: _lowerCamelCase : Optional[Any] =WavaVecaConfig(processor_class='Wav2Vec2Processor' ) model_config.save_pretrained(lowercase_ ) # copy relevant files copyfile(lowercase_ , os.path.join(lowercase_ , 'vocab.json' ) ) # create emtpy sample processor with open(os.path.join(lowercase_ , lowercase_ ) , 'w' ) as f: f.write('{}' ) _lowerCamelCase : int =AutoProcessor.from_pretrained(lowercase_ ) self.assertIsInstance(lowercase_ , lowercase_ ) def lowerCamelCase ( self : str ) -> Optional[int]: """simple docstring""" with self.assertRaises(lowercase_ ): _lowerCamelCase : int =AutoProcessor.from_pretrained('hf-internal-testing/test_dynamic_processor' ) # If remote code is disabled, we can't load this config. with self.assertRaises(lowercase_ ): _lowerCamelCase : Union[str, Any] =AutoProcessor.from_pretrained( 'hf-internal-testing/test_dynamic_processor' , trust_remote_code=lowercase_ ) _lowerCamelCase : List[str] =AutoProcessor.from_pretrained('hf-internal-testing/test_dynamic_processor' , trust_remote_code=lowercase_ ) self.assertTrue(processor.special_attribute_present ) self.assertEqual(processor.__class__.__name__ , 'NewProcessor' ) _lowerCamelCase : int =processor.feature_extractor self.assertTrue(feature_extractor.special_attribute_present ) self.assertEqual(feature_extractor.__class__.__name__ , 'NewFeatureExtractor' ) _lowerCamelCase : Optional[int] =processor.tokenizer self.assertTrue(tokenizer.special_attribute_present ) if is_tokenizers_available(): self.assertEqual(tokenizer.__class__.__name__ , 'NewTokenizerFast' ) # Test we can also load the slow version _lowerCamelCase : int =AutoProcessor.from_pretrained( 'hf-internal-testing/test_dynamic_processor' , trust_remote_code=lowercase_ , use_fast=lowercase_ ) _lowerCamelCase : Optional[int] =new_processor.tokenizer self.assertTrue(new_tokenizer.special_attribute_present ) self.assertEqual(new_tokenizer.__class__.__name__ , 'NewTokenizer' ) else: self.assertEqual(tokenizer.__class__.__name__ , 'NewTokenizer' ) def lowerCamelCase ( self : Optional[int] ) -> Optional[int]: """simple docstring""" try: AutoConfig.register('custom' , lowercase_ ) AutoFeatureExtractor.register(lowercase_ , lowercase_ ) AutoTokenizer.register(lowercase_ , slow_tokenizer_class=lowercase_ ) AutoProcessor.register(lowercase_ , lowercase_ ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(lowercase_ ): AutoProcessor.register(lowercase_ , lowercase_ ) # Now that the config is registered, it can be used as any other config with the auto-API _lowerCamelCase : str =CustomFeatureExtractor.from_pretrained(lowercase_ ) with tempfile.TemporaryDirectory() as tmp_dir: _lowerCamelCase : str =os.path.join(lowercase_ , 'vocab.txt' ) with open(lowercase_ , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) _lowerCamelCase : List[Any] =CustomTokenizer(lowercase_ ) _lowerCamelCase : Optional[int] =CustomProcessor(lowercase_ , lowercase_ ) with tempfile.TemporaryDirectory() as tmp_dir: processor.save_pretrained(lowercase_ ) _lowerCamelCase : List[Any] =AutoProcessor.from_pretrained(lowercase_ ) self.assertIsInstance(lowercase_ , lowercase_ ) 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] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] if CustomConfig in PROCESSOR_MAPPING._extra_content: del PROCESSOR_MAPPING._extra_content[CustomConfig] def lowerCamelCase ( self : Union[str, Any] ) -> List[str]: """simple docstring""" class A ( UpperCamelCase_ ): UpperCamelCase__ : Optional[Any] =False class A ( UpperCamelCase_ ): UpperCamelCase__ : int =False class A ( UpperCamelCase_ ): UpperCamelCase__ : Union[str, Any] ='AutoFeatureExtractor' UpperCamelCase__ : str ='AutoTokenizer' UpperCamelCase__ : List[Any] =False try: AutoConfig.register('custom' , lowercase_ ) AutoFeatureExtractor.register(lowercase_ , lowercase_ ) AutoTokenizer.register(lowercase_ , slow_tokenizer_class=lowercase_ ) AutoProcessor.register(lowercase_ , lowercase_ ) # If remote code is not set, the default is to use local classes. _lowerCamelCase : int =AutoProcessor.from_pretrained('hf-internal-testing/test_dynamic_processor' ) self.assertEqual(processor.__class__.__name__ , 'NewProcessor' ) self.assertFalse(processor.special_attribute_present ) self.assertFalse(processor.feature_extractor.special_attribute_present ) self.assertFalse(processor.tokenizer.special_attribute_present ) # If remote code is disabled, we load the local ones. _lowerCamelCase : int =AutoProcessor.from_pretrained( 'hf-internal-testing/test_dynamic_processor' , trust_remote_code=lowercase_ ) self.assertEqual(processor.__class__.__name__ , 'NewProcessor' ) self.assertFalse(processor.special_attribute_present ) self.assertFalse(processor.feature_extractor.special_attribute_present ) self.assertFalse(processor.tokenizer.special_attribute_present ) # If remote is enabled, we load from the Hub. _lowerCamelCase : str =AutoProcessor.from_pretrained( 'hf-internal-testing/test_dynamic_processor' , trust_remote_code=lowercase_ ) self.assertEqual(processor.__class__.__name__ , 'NewProcessor' ) self.assertTrue(processor.special_attribute_present ) self.assertTrue(processor.feature_extractor.special_attribute_present ) self.assertTrue(processor.tokenizer.special_attribute_present ) 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] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] if CustomConfig in PROCESSOR_MAPPING._extra_content: del PROCESSOR_MAPPING._extra_content[CustomConfig] def lowerCamelCase ( self : Optional[int] ) -> str: """simple docstring""" _lowerCamelCase : List[Any] =AutoProcessor.from_pretrained('hf-internal-testing/tiny-random-bert' ) self.assertEqual(processor.__class__.__name__ , 'BertTokenizerFast' ) def lowerCamelCase ( self : Any ) -> Dict: """simple docstring""" _lowerCamelCase : Any =AutoProcessor.from_pretrained('hf-internal-testing/tiny-random-convnext' ) self.assertEqual(processor.__class__.__name__ , 'ConvNextImageProcessor' ) @is_staging_test class A ( unittest.TestCase ): UpperCamelCase__ : List[Any] =['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'bla', 'blou'] @classmethod def lowerCamelCase ( cls : int ) -> Optional[Any]: """simple docstring""" _lowerCamelCase : Union[str, Any] =TOKEN HfFolder.save_token(lowercase_ ) @classmethod def lowerCamelCase ( cls : Optional[int] ) -> Union[str, Any]: """simple docstring""" try: delete_repo(token=cls._token , repo_id='test-processor' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='valid_org/test-processor-org' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='test-dynamic-processor' ) except HTTPError: pass def lowerCamelCase ( self : str ) -> int: """simple docstring""" _lowerCamelCase : Tuple =WavaVecaProcessor.from_pretrained(lowercase_ ) with tempfile.TemporaryDirectory() as tmp_dir: processor.save_pretrained( os.path.join(lowercase_ , 'test-processor' ) , push_to_hub=lowercase_ , use_auth_token=self._token ) _lowerCamelCase : Union[str, Any] =WavaVecaProcessor.from_pretrained(F'''{USER}/test-processor''' ) for k, v in processor.feature_extractor.__dict__.items(): self.assertEqual(lowercase_ , getattr(new_processor.feature_extractor , lowercase_ ) ) self.assertDictEqual(new_processor.tokenizer.get_vocab() , processor.tokenizer.get_vocab() ) def lowerCamelCase ( self : str ) -> Tuple: """simple docstring""" _lowerCamelCase : int =WavaVecaProcessor.from_pretrained(lowercase_ ) with tempfile.TemporaryDirectory() as tmp_dir: processor.save_pretrained( os.path.join(lowercase_ , 'test-processor-org' ) , push_to_hub=lowercase_ , use_auth_token=self._token , organization='valid_org' , ) _lowerCamelCase : str =WavaVecaProcessor.from_pretrained('valid_org/test-processor-org' ) for k, v in processor.feature_extractor.__dict__.items(): self.assertEqual(lowercase_ , getattr(new_processor.feature_extractor , lowercase_ ) ) self.assertDictEqual(new_processor.tokenizer.get_vocab() , processor.tokenizer.get_vocab() ) def lowerCamelCase ( self : List[Any] ) -> str: """simple docstring""" CustomFeatureExtractor.register_for_auto_class() CustomTokenizer.register_for_auto_class() CustomProcessor.register_for_auto_class() _lowerCamelCase : Optional[Any] =CustomFeatureExtractor.from_pretrained(lowercase_ ) with tempfile.TemporaryDirectory() as tmp_dir: _lowerCamelCase : Dict =os.path.join(lowercase_ , 'vocab.txt' ) with open(lowercase_ , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) _lowerCamelCase : Any =CustomTokenizer(lowercase_ ) _lowerCamelCase : List[Any] =CustomProcessor(lowercase_ , lowercase_ ) with tempfile.TemporaryDirectory() as tmp_dir: create_repo(F'''{USER}/test-dynamic-processor''' , token=self._token ) _lowerCamelCase : List[str] =Repository(lowercase_ , clone_from=F'''{USER}/test-dynamic-processor''' , token=self._token ) processor.save_pretrained(lowercase_ ) # This has added the proper auto_map field to the feature extractor config self.assertDictEqual( processor.feature_extractor.auto_map , { 'AutoFeatureExtractor': 'custom_feature_extraction.CustomFeatureExtractor', 'AutoProcessor': 'custom_processing.CustomProcessor', } , ) # This has added the proper auto_map field to the tokenizer config with open(os.path.join(lowercase_ , 'tokenizer_config.json' ) ) as f: _lowerCamelCase : Union[str, Any] =json.load(lowercase_ ) self.assertDictEqual( tokenizer_config['auto_map'] , { 'AutoTokenizer': ['custom_tokenization.CustomTokenizer', None], 'AutoProcessor': 'custom_processing.CustomProcessor', } , ) # The code has been copied from fixtures self.assertTrue(os.path.isfile(os.path.join(lowercase_ , 'custom_feature_extraction.py' ) ) ) self.assertTrue(os.path.isfile(os.path.join(lowercase_ , 'custom_tokenization.py' ) ) ) self.assertTrue(os.path.isfile(os.path.join(lowercase_ , 'custom_processing.py' ) ) ) repo.push_to_hub() _lowerCamelCase : Tuple =AutoProcessor.from_pretrained(F'''{USER}/test-dynamic-processor''' , trust_remote_code=lowercase_ ) # Can't make an isinstance check because the new_processor is from the CustomProcessor class of a dynamic module self.assertEqual(new_processor.__class__.__name__ , 'CustomProcessor' )
464
0
def _A( UpperCamelCase__ : int ) -> bool: '''simple docstring''' if num < 0: return False __lowercase = num __lowercase = 0 while num > 0: __lowercase = rev_num * 10 + (num % 10) num //= 10 return num_copy == rev_num if __name__ == "__main__": import doctest doctest.testmod()
362
import unittest import numpy as np import timeout_decorator # noqa from transformers import BlenderbotConfig, is_flax_available from transformers.testing_utils import jax_device, require_flax, slow from ...generation.test_flax_utils import FlaxGenerationTesterMixin from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor if is_flax_available(): import os # The slow tests are often failing with OOM error on GPU # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html UpperCAmelCase__ = "platform" import jax import jax.numpy as jnp from transformers import BlenderbotTokenizer from transformers.models.blenderbot.modeling_flax_blenderbot import ( FlaxBlenderbotForConditionalGeneration, FlaxBlenderbotModel, shift_tokens_right, ) def _A( UpperCamelCase__ : Tuple , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Dict=None , UpperCamelCase__ : Optional[int]=None , UpperCamelCase__ : int=None , UpperCamelCase__ : Union[str, Any]=None , UpperCamelCase__ : Optional[Any]=None , UpperCamelCase__ : List[str]=None , ) -> int: '''simple docstring''' if attention_mask is None: __lowercase = np.where(input_ids != config.pad_token_id , 1 , 0 ) if decoder_attention_mask is None: __lowercase = np.where(decoder_input_ids != config.pad_token_id , 1 , 0 ) if head_mask is None: __lowercase = np.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: __lowercase = np.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: __lowercase = np.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": attention_mask, } class a : """simple docstring""" def __init__( self : Dict , lowerCamelCase__ : Dict , lowerCamelCase__ : Union[str, Any]=13 , lowerCamelCase__ : Union[str, Any]=7 , lowerCamelCase__ : Dict=True , lowerCamelCase__ : int=False , lowerCamelCase__ : Any=99 , lowerCamelCase__ : str=16 , lowerCamelCase__ : Union[str, Any]=2 , lowerCamelCase__ : Union[str, Any]=4 , lowerCamelCase__ : Tuple=4 , lowerCamelCase__ : Optional[Any]="gelu" , lowerCamelCase__ : int=0.1 , lowerCamelCase__ : Tuple=0.1 , lowerCamelCase__ : Any=32 , lowerCamelCase__ : List[str]=2 , lowerCamelCase__ : Optional[Any]=1 , lowerCamelCase__ : List[Any]=0 , lowerCamelCase__ : int=0.0_2 , ) -> Optional[int]: """simple docstring""" __lowercase = parent __lowercase = batch_size __lowercase = seq_length __lowercase = is_training __lowercase = use_labels __lowercase = vocab_size __lowercase = hidden_size __lowercase = num_hidden_layers __lowercase = num_attention_heads __lowercase = intermediate_size __lowercase = hidden_act __lowercase = hidden_dropout_prob __lowercase = attention_probs_dropout_prob __lowercase = max_position_embeddings __lowercase = eos_token_id __lowercase = pad_token_id __lowercase = bos_token_id __lowercase = initializer_range def UpperCAmelCase_ ( self : int ) -> Any: """simple docstring""" __lowercase = np.clip(ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) , 3 , self.vocab_size ) __lowercase = np.concatenate((input_ids, 2 * np.ones((self.batch_size, 1) , dtype=np.intaa )) , -1 ) __lowercase = shift_tokens_right(lowerCamelCase__ , 1 , 2 ) __lowercase = BlenderbotConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , initializer_range=self.initializer_range , use_cache=lowerCamelCase__ , ) __lowercase = prepare_blenderbot_inputs_dict(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) return config, inputs_dict def UpperCAmelCase_ ( self : Dict ) -> Optional[int]: """simple docstring""" __lowercase , __lowercase = self.prepare_config_and_inputs() return config, inputs_dict def UpperCAmelCase_ ( self : Optional[Any] , lowerCamelCase__ : str , lowerCamelCase__ : List[str] , lowerCamelCase__ : Tuple ) -> Any: """simple docstring""" __lowercase = 20 __lowercase = model_class_name(lowerCamelCase__ ) __lowercase = model.encode(inputs_dict['''input_ids'''] ) __lowercase , __lowercase = ( inputs_dict['''decoder_input_ids'''], inputs_dict['''decoder_attention_mask'''], ) __lowercase = model.init_cache(decoder_input_ids.shape[0] , lowerCamelCase__ , lowerCamelCase__ ) __lowercase = jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype='''i4''' ) __lowercase = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) __lowercase = model.decode( decoder_input_ids[:, :-1] , lowerCamelCase__ , decoder_attention_mask=lowerCamelCase__ , past_key_values=lowerCamelCase__ , decoder_position_ids=lowerCamelCase__ , ) __lowercase = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype='''i4''' ) __lowercase = model.decode( decoder_input_ids[:, -1:] , lowerCamelCase__ , decoder_attention_mask=lowerCamelCase__ , past_key_values=outputs_cache.past_key_values , decoder_position_ids=lowerCamelCase__ , ) __lowercase = model.decode(lowerCamelCase__ , lowerCamelCase__ ) __lowercase = 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 UpperCAmelCase_ ( self : int , lowerCamelCase__ : Optional[Any] , lowerCamelCase__ : str , lowerCamelCase__ : List[Any] ) -> Optional[Any]: """simple docstring""" __lowercase = 20 __lowercase = model_class_name(lowerCamelCase__ ) __lowercase = model.encode(inputs_dict['''input_ids'''] ) __lowercase , __lowercase = ( inputs_dict['''decoder_input_ids'''], inputs_dict['''decoder_attention_mask'''], ) __lowercase = jnp.concatenate( [ decoder_attention_mask, jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1]) ), ] , axis=-1 , ) __lowercase = model.init_cache(decoder_input_ids.shape[0] , lowerCamelCase__ , lowerCamelCase__ ) __lowercase = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) __lowercase = model.decode( decoder_input_ids[:, :-1] , lowerCamelCase__ , decoder_attention_mask=lowerCamelCase__ , past_key_values=lowerCamelCase__ , decoder_position_ids=lowerCamelCase__ , ) __lowercase = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype='''i4''' ) __lowercase = model.decode( decoder_input_ids[:, -1:] , lowerCamelCase__ , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=lowerCamelCase__ , decoder_position_ids=lowerCamelCase__ , ) __lowercase = model.decode(lowerCamelCase__ , lowerCamelCase__ , decoder_attention_mask=lowerCamelCase__ ) __lowercase = 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 a ( unittest.TestCase ): """simple docstring""" UpperCamelCase_ : List[Any] = 99 def UpperCAmelCase_ ( self : List[Any] ) -> Dict: """simple docstring""" __lowercase = np.array( [ [71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 82, 2], [5, 97, 17, 39, 94, 40, 2], [76, 83, 94, 25, 70, 78, 2], [87, 59, 41, 35, 48, 66, 2], [55, 13, 16, 58, 5, 2, 1], # note padding [64, 27, 31, 51, 12, 75, 2], [52, 64, 86, 17, 83, 39, 2], [48, 61, 9, 24, 71, 82, 2], [26, 1, 60, 48, 22, 13, 2], [21, 5, 62, 28, 14, 76, 2], [45, 98, 37, 86, 59, 48, 2], [70, 70, 50, 9, 28, 0, 2], ] , dtype=np.intaa , ) __lowercase = input_ids.shape[0] __lowercase = BlenderbotConfig( vocab_size=self.vocab_size , d_model=24 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=32 , decoder_ffn_dim=32 , max_position_embeddings=48 , eos_token_id=2 , pad_token_id=1 , bos_token_id=0 , ) return config, input_ids, batch_size def UpperCAmelCase_ ( self : Tuple ) -> Optional[int]: """simple docstring""" __lowercase , __lowercase , __lowercase = self._get_config_and_data() __lowercase = FlaxBlenderbotForConditionalGeneration(lowerCamelCase__ ) __lowercase = lm_model(input_ids=lowerCamelCase__ ) __lowercase = (batch_size, input_ids.shape[1], config.vocab_size) self.assertEqual(outputs['''logits'''].shape , lowerCamelCase__ ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> List[Any]: """simple docstring""" __lowercase = BlenderbotConfig( vocab_size=self.vocab_size , d_model=14 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=8 , decoder_ffn_dim=8 , max_position_embeddings=48 , ) __lowercase = FlaxBlenderbotForConditionalGeneration(lowerCamelCase__ ) __lowercase = np.array([[71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 2, 1]] , dtype=np.intaa ) __lowercase = np.array([[82, 71, 82, 18, 2], [58, 68, 2, 1, 1]] , dtype=np.intaa ) __lowercase = lm_model(input_ids=lowerCamelCase__ , decoder_input_ids=lowerCamelCase__ ) __lowercase = (*summary.shape, config.vocab_size) self.assertEqual(outputs['''logits'''].shape , lowerCamelCase__ ) def UpperCAmelCase_ ( self : List[str] ) -> List[Any]: """simple docstring""" __lowercase = np.array([[71, 82, 18, 33, 2, 1, 1], [68, 34, 26, 58, 30, 82, 2]] , dtype=np.intaa ) __lowercase = shift_tokens_right(lowerCamelCase__ , 1 , 2 ) __lowercase = np.equal(lowerCamelCase__ , 1 ).astype(np.floataa ).sum() __lowercase = np.equal(lowerCamelCase__ , 1 ).astype(np.floataa ).sum() self.assertEqual(shifted.shape , input_ids.shape ) self.assertEqual(lowerCamelCase__ , n_pad_before - 1 ) self.assertTrue(np.equal(shifted[:, 0] , 2 ).all() ) @require_flax class a ( __SCREAMING_SNAKE_CASE , unittest.TestCase , __SCREAMING_SNAKE_CASE ): """simple docstring""" UpperCamelCase_ : Optional[Any] = True UpperCamelCase_ : List[str] = ( ( FlaxBlenderbotModel, FlaxBlenderbotForConditionalGeneration, ) if is_flax_available() else () ) UpperCamelCase_ : Union[str, Any] = (FlaxBlenderbotForConditionalGeneration,) if is_flax_available() else () def UpperCAmelCase_ ( self : Optional[int] ) -> List[str]: """simple docstring""" __lowercase = FlaxBlenderbotModelTester(self ) def UpperCAmelCase_ ( self : Any ) -> List[str]: """simple docstring""" __lowercase , __lowercase = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Optional[Any]: """simple docstring""" __lowercase , __lowercase = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward_with_attn_mask(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) def UpperCAmelCase_ ( self : List[str] ) -> int: """simple docstring""" __lowercase , __lowercase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __lowercase = self._prepare_for_class(lowerCamelCase__ , lowerCamelCase__ ) __lowercase = model_class(lowerCamelCase__ ) @jax.jit def encode_jitted(lowerCamelCase__ : List[str] , lowerCamelCase__ : Any=None , **lowerCamelCase__ : Dict ): return model.encode(input_ids=lowerCamelCase__ , attention_mask=lowerCamelCase__ ) with self.subTest('''JIT Enabled''' ): __lowercase = encode_jitted(**lowerCamelCase__ ).to_tuple() with self.subTest('''JIT Disabled''' ): with jax.disable_jit(): __lowercase = encode_jitted(**lowerCamelCase__ ).to_tuple() self.assertEqual(len(lowerCamelCase__ ) , len(lowerCamelCase__ ) ) for jitted_output, output in zip(lowerCamelCase__ , lowerCamelCase__ ): self.assertEqual(jitted_output.shape , output.shape ) def UpperCAmelCase_ ( self : Dict ) -> Optional[Any]: """simple docstring""" __lowercase , __lowercase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __lowercase = model_class(lowerCamelCase__ ) __lowercase = model.encode(inputs_dict['''input_ids'''] , inputs_dict['''attention_mask'''] ) __lowercase = { '''decoder_input_ids''': inputs_dict['''decoder_input_ids'''], '''decoder_attention_mask''': inputs_dict['''decoder_attention_mask'''], '''encoder_outputs''': encoder_outputs, } @jax.jit def decode_jitted(lowerCamelCase__ : List[str] , lowerCamelCase__ : List[str] , lowerCamelCase__ : Tuple ): return model.decode( decoder_input_ids=lowerCamelCase__ , decoder_attention_mask=lowerCamelCase__ , encoder_outputs=lowerCamelCase__ , ) with self.subTest('''JIT Enabled''' ): __lowercase = decode_jitted(**lowerCamelCase__ ).to_tuple() with self.subTest('''JIT Disabled''' ): with jax.disable_jit(): __lowercase = decode_jitted(**lowerCamelCase__ ).to_tuple() self.assertEqual(len(lowerCamelCase__ ) , len(lowerCamelCase__ ) ) for jitted_output, output in zip(lowerCamelCase__ , lowerCamelCase__ ): self.assertEqual(jitted_output.shape , output.shape ) @slow def UpperCAmelCase_ ( self : int ) -> Union[str, Any]: """simple docstring""" for model_class_name in self.all_model_classes: __lowercase = model_class_name.from_pretrained('''facebook/blenderbot-400M-distill''' ) # FlaxBlenderbotForSequenceClassification expects eos token in input_ids __lowercase = np.ones((1, 1) ) * model.config.eos_token_id __lowercase = model(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) @unittest.skipUnless(jax_device != '''cpu''' , '''3B test too slow on CPU.''' ) @slow def UpperCAmelCase_ ( self : Tuple ) -> List[str]: """simple docstring""" __lowercase = {'''num_beams''': 1, '''early_stopping''': True, '''min_length''': 15, '''max_length''': 25} __lowercase = {'''skip_special_tokens''': True, '''clean_up_tokenization_spaces''': True} __lowercase = FlaxBlenderbotForConditionalGeneration.from_pretrained('''facebook/blenderbot-3B''' , from_pt=lowerCamelCase__ ) __lowercase = BlenderbotTokenizer.from_pretrained('''facebook/blenderbot-3B''' ) __lowercase = ['''Sam'''] __lowercase = tokenizer(lowerCamelCase__ , return_tensors='''jax''' ) __lowercase = model.generate(**lowerCamelCase__ , **lowerCamelCase__ ) __lowercase = '''Sam is a great name. It means "sun" in Gaelic.''' __lowercase = tokenizer.batch_decode(lowerCamelCase__ , **lowerCamelCase__ ) assert generated_txt[0].strip() == tgt_text
362
1
import argparse import collections import os import re from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_table.py _lowerCamelCase : Tuple = """src/transformers""" _lowerCamelCase : Any = """docs/source/en""" _lowerCamelCase : Dict = """.""" def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ ) -> Any: """simple docstring""" with open(lowercase_ , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: A__ = f.readlines() # Find the start prompt. A__ = 0 while not lines[start_index].startswith(lowercase_ ): start_index += 1 start_index += 1 A__ = start_index while not lines[end_index].startswith(lowercase_ ): end_index += 1 end_index -= 1 while len(lines[start_index] ) <= 1: start_index += 1 while len(lines[end_index] ) <= 1: end_index -= 1 end_index += 1 return "".join(lines[start_index:end_index] ), start_index, end_index, lines # Add here suffixes that are used to identify models, separated by | _lowerCamelCase : Optional[Any] = """Model|Encoder|Decoder|ForConditionalGeneration""" # Regexes that match TF/Flax/PT model names. _lowerCamelCase : Optional[Any] = re.compile(r"""TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)""") _lowerCamelCase : Union[str, Any] = re.compile(r"""Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)""") # Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes. _lowerCamelCase : str = re.compile(r"""(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)""") # This is to make sure the transformers module imported is the one in the repo. _lowerCamelCase : str = direct_transformers_import(TRANSFORMERS_PATH) def SCREAMING_SNAKE_CASE ( lowercase_ ) -> Union[str, Any]: """simple docstring""" A__ = re.finditer('''.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)''' , lowercase_ ) return [m.group(0 ) for m in matches] def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ ) -> Optional[int]: """simple docstring""" A__ = 2 if text == '''✅''' or text == '''❌''' else len(lowercase_ ) A__ = (width - text_length) // 2 A__ = width - text_length - left_indent return " " * left_indent + text + " " * right_indent def SCREAMING_SNAKE_CASE ( ) -> str: """simple docstring""" A__ = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES A__ = { name: config_maping_names[code] for code, name in transformers_module.MODEL_NAMES_MAPPING.items() if code in config_maping_names } A__ = {name: config.replace('''Config''' , '''''' ) for name, config in model_name_to_config.items()} # Dictionaries flagging if each model prefix has a slow/fast tokenizer, backend in PT/TF/Flax. A__ = collections.defaultdict(lowercase_ ) A__ = collections.defaultdict(lowercase_ ) A__ = collections.defaultdict(lowercase_ ) A__ = collections.defaultdict(lowercase_ ) A__ = collections.defaultdict(lowercase_ ) # Let's lookup through all transformers object (once). for attr_name in dir(lowercase_ ): A__ = None if attr_name.endswith('''Tokenizer''' ): A__ = slow_tokenizers A__ = attr_name[:-9] elif attr_name.endswith('''TokenizerFast''' ): A__ = fast_tokenizers A__ = attr_name[:-13] elif _re_tf_models.match(lowercase_ ) is not None: A__ = tf_models A__ = _re_tf_models.match(lowercase_ ).groups()[0] elif _re_flax_models.match(lowercase_ ) is not None: A__ = flax_models A__ = _re_flax_models.match(lowercase_ ).groups()[0] elif _re_pt_models.match(lowercase_ ) is not None: A__ = pt_models A__ = _re_pt_models.match(lowercase_ ).groups()[0] if lookup_dict is not None: while len(lowercase_ ) > 0: if attr_name in model_name_to_prefix.values(): A__ = True break # Try again after removing the last word in the name A__ = ''''''.join(camel_case_split(lowercase_ )[:-1] ) # Let's build that table! A__ = list(model_name_to_config.keys() ) model_names.sort(key=str.lower ) A__ = ['''Model''', '''Tokenizer slow''', '''Tokenizer fast''', '''PyTorch support''', '''TensorFlow support''', '''Flax Support'''] # We'll need widths to properly display everything in the center (+2 is to leave one extra space on each side). A__ = [len(lowercase_ ) + 2 for c in columns] A__ = max([len(lowercase_ ) for name in model_names] ) + 2 # Build the table per se A__ = '''|''' + '''|'''.join([_center_text(lowercase_ , lowercase_ ) for c, w in zip(lowercase_ , lowercase_ )] ) + '''|\n''' # Use ":-----:" format to center-aligned table cell texts table += "|" + "|".join([''':''' + '''-''' * (w - 2) + ''':''' for w in widths] ) + "|\n" A__ = {True: '''✅''', False: '''❌'''} for name in model_names: A__ = model_name_to_prefix[name] A__ = [ name, check[slow_tokenizers[prefix]], check[fast_tokenizers[prefix]], check[pt_models[prefix]], check[tf_models[prefix]], check[flax_models[prefix]], ] table += "|" + "|".join([_center_text(lowercase_ , lowercase_ ) for l, w in zip(lowercase_ , lowercase_ )] ) + "|\n" return table def SCREAMING_SNAKE_CASE ( lowercase_=False ) -> Optional[int]: """simple docstring""" A__ , A__ , A__ , A__ = _find_text_in_file( filename=os.path.join(lowercase_ , '''index.md''' ) , start_prompt='''<!--This table is updated automatically from the auto modules''' , end_prompt='''<!-- End table-->''' , ) A__ = get_model_table_from_auto_modules() if current_table != new_table: if overwrite: with open(os.path.join(lowercase_ , '''index.md''' ) , '''w''' , encoding='''utf-8''' , newline='''\n''' ) as f: f.writelines(lines[:start_index] + [new_table] + lines[end_index:] ) else: raise ValueError( '''The model table in the `index.md` has not been updated. Run `make fix-copies` to fix this.''' ) if __name__ == "__main__": _lowerCamelCase : Optional[Any] = argparse.ArgumentParser() parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""") _lowerCamelCase : Optional[Any] = parser.parse_args() check_model_table(args.fix_and_overwrite)
87
"""simple docstring""" import argparse import re import torch from CLAP import create_model from transformers import AutoFeatureExtractor, ClapConfig, ClapModel __magic_name__ = { "text_branch": "text_model", "audio_branch": "audio_model.audio_encoder", "attn": "attention.self", "self.proj": "output.dense", "attention.self_mask": "attn_mask", "mlp.fc1": "intermediate.dense", "mlp.fc2": "output.dense", "norm1": "layernorm_before", "norm2": "layernorm_after", "bn0": "batch_norm", } __magic_name__ = AutoFeatureExtractor.from_pretrained("laion/clap-htsat-unfused", truncation="rand_trunc") def _lowerCamelCase ( UpperCAmelCase__,UpperCAmelCase__=False ) -> Union[str, Any]: '''simple docstring''' a__ , a__ = create_model( 'HTSAT-tiny','roberta',UpperCAmelCase__,precision='fp32',device='cuda:0' if torch.cuda.is_available() else 'cpu',enable_fusion=UpperCAmelCase__,fusion_type='aff_2d' if enable_fusion else None,) return model, model_cfg def _lowerCamelCase ( UpperCAmelCase__ ) -> Optional[int]: '''simple docstring''' a__ = {} a__ = R'.*sequential.(\d+).*' a__ = R'.*_projection.(\d+).*' for key, value in state_dict.items(): # check if any key needs to be modified for key_to_modify, new_key in KEYS_TO_MODIFY_MAPPING.items(): if key_to_modify in key: a__ = key.replace(UpperCAmelCase__,UpperCAmelCase__ ) if re.match(UpperCAmelCase__,UpperCAmelCase__ ): # replace sequential layers with list a__ = re.match(UpperCAmelCase__,UpperCAmelCase__ ).group(1 ) a__ = key.replace(f'''sequential.{sequential_layer}.''',f'''layers.{int(UpperCAmelCase__ )//3}.linear.''' ) elif re.match(UpperCAmelCase__,UpperCAmelCase__ ): a__ = int(re.match(UpperCAmelCase__,UpperCAmelCase__ ).group(1 ) ) # Because in CLAP they use `nn.Sequential`... a__ = 1 if projecton_layer == 0 else 2 a__ = key.replace(f'''_projection.{projecton_layer}.''',f'''_projection.linear{transformers_projection_layer}.''' ) if "audio" and "qkv" in key: # split qkv into query key and value a__ = value a__ = mixed_qkv.size(0 ) // 3 a__ = mixed_qkv[:qkv_dim] a__ = mixed_qkv[qkv_dim : qkv_dim * 2] a__ = mixed_qkv[qkv_dim * 2 :] a__ = query_layer a__ = key_layer a__ = value_layer else: a__ = value return model_state_dict def _lowerCamelCase ( UpperCAmelCase__,UpperCAmelCase__,UpperCAmelCase__,UpperCAmelCase__=False ) -> Any: '''simple docstring''' a__ , a__ = init_clap(UpperCAmelCase__,enable_fusion=UpperCAmelCase__ ) clap_model.eval() a__ = clap_model.state_dict() a__ = rename_state_dict(UpperCAmelCase__ ) a__ = ClapConfig() a__ = enable_fusion a__ = ClapModel(UpperCAmelCase__ ) # ignore the spectrogram embedding layer model.load_state_dict(UpperCAmelCase__,strict=UpperCAmelCase__ ) model.save_pretrained(UpperCAmelCase__ ) transformers_config.save_pretrained(UpperCAmelCase__ ) if __name__ == "__main__": __magic_name__ = argparse.ArgumentParser() parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to fairseq checkpoint") parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert") parser.add_argument("--enable_fusion", action="store_true", help="Whether to enable fusion or not") __magic_name__ = parser.parse_args() convert_clap_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.enable_fusion)
232
0
import math def _UpperCamelCase ( lowerCAmelCase_ ) ->bool: assert isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) and ( number >= 0 ), "'number' must been an int and positive" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or not number % 2: # Negatives, 0, 1 and all even numbers are not primes return False UpperCAmelCase = range(3 , int(math.sqrt(lowerCAmelCase_ ) + 1 ) , 2 ) return not any(not number % i for i in odd_numbers ) def _UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_=1 , **lowerCAmelCase_ ) ->str: UpperCAmelCase = factor * value UpperCAmelCase = value while not is_prime(lowerCAmelCase_ ): value += 1 if not ("desc" in kwargs and kwargs["desc"] is True) else -1 if value == first_value_val: return next_prime(value + 1 , **lowerCAmelCase_ ) return value
627
from sklearn.metrics import fa_score, matthews_corrcoef import datasets from .record_evaluation import evaluate as evaluate_record __a = """\ @article{wang2019superglue, title={SuperGLUE: A Stickier Benchmark for General-Purpose Language Understanding Systems}, author={Wang, Alex and Pruksachatkun, Yada and Nangia, Nikita and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R}, journal={arXiv preprint arXiv:1905.00537}, year={2019} } """ __a = """\ SuperGLUE (https://super.gluebenchmark.com/) is a new benchmark styled after GLUE with a new set of more difficult language understanding tasks, improved resources, and a new public leaderboard. """ __a = """ Compute SuperGLUE evaluation metric associated to each SuperGLUE dataset. Args: predictions: list of predictions to score. Depending on the SuperGlUE subset: - for 'record': list of question-answer dictionaries with the following keys: - 'idx': index of the question as specified by the dataset - 'prediction_text': the predicted answer text - for 'multirc': list of question-answer dictionaries with the following keys: - 'idx': index of the question-answer pair as specified by the dataset - 'prediction': the predicted answer label - otherwise: list of predicted labels references: list of reference labels. Depending on the SuperGLUE subset: - for 'record': list of question-answers dictionaries with the following keys: - 'idx': index of the question as specified by the dataset - 'answers': list of possible answers - otherwise: list of reference labels Returns: depending on the SuperGLUE subset: - for 'record': - 'exact_match': Exact match between answer and gold answer - 'f1': F1 score - for 'multirc': - 'exact_match': Exact match between answer and gold answer - 'f1_m': Per-question macro-F1 score - 'f1_a': Average F1 score over all answers - for 'axb': 'matthews_correlation': Matthew Correlation - for 'cb': - 'accuracy': Accuracy - 'f1': F1 score - for all others: - 'accuracy': Accuracy Examples: >>> super_glue_metric = datasets.load_metric('super_glue', 'copa') # any of [\"copa\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"boolq\", \"axg\"] >>> predictions = [0, 1] >>> references = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'accuracy': 1.0} >>> super_glue_metric = datasets.load_metric('super_glue', 'cb') >>> predictions = [0, 1] >>> references = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'accuracy': 1.0, 'f1': 1.0} >>> super_glue_metric = datasets.load_metric('super_glue', 'record') >>> predictions = [{'idx': {'passage': 0, 'query': 0}, 'prediction_text': 'answer'}] >>> references = [{'idx': {'passage': 0, 'query': 0}, 'answers': ['answer', 'another_answer']}] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'exact_match': 1.0, 'f1': 1.0} >>> super_glue_metric = datasets.load_metric('super_glue', 'multirc') >>> predictions = [{'idx': {'answer': 0, 'paragraph': 0, 'question': 0}, 'prediction': 0}, {'idx': {'answer': 1, 'paragraph': 2, 'question': 3}, 'prediction': 1}] >>> references = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'exact_match': 1.0, 'f1_m': 1.0, 'f1_a': 1.0} >>> super_glue_metric = datasets.load_metric('super_glue', 'axb') >>> references = [0, 1] >>> predictions = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'matthews_correlation': 1.0} """ def _UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) ->List[str]: return float((preds == labels).mean() ) def _UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_="binary" ) ->Union[str, Any]: UpperCAmelCase = simple_accuracy(lowerCAmelCase_ , lowerCAmelCase_ ) UpperCAmelCase = float(fa_score(y_true=lowerCAmelCase_ , y_pred=lowerCAmelCase_ , average=lowerCAmelCase_ ) ) return { "accuracy": acc, "f1": fa, } def _UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) ->List[Any]: UpperCAmelCase = {} for id_pred, label in zip(lowerCAmelCase_ , lowerCAmelCase_ ): UpperCAmelCase = F"""{id_pred['idx']['paragraph']}-{id_pred['idx']['question']}""" UpperCAmelCase = id_pred["""prediction"""] if question_id in question_map: question_map[question_id].append((pred, label) ) else: UpperCAmelCase = [(pred, label)] UpperCAmelCase , UpperCAmelCase = [], [] for question, preds_labels in question_map.items(): UpperCAmelCase , UpperCAmelCase = zip(*lowerCAmelCase_ ) UpperCAmelCase = fa_score(y_true=lowerCAmelCase_ , y_pred=lowerCAmelCase_ , average="""macro""" ) fas.append(lowerCAmelCase_ ) UpperCAmelCase = int(sum(pred == label for pred, label in preds_labels ) == len(lowerCAmelCase_ ) ) ems.append(lowerCAmelCase_ ) UpperCAmelCase = float(sum(lowerCAmelCase_ ) / len(lowerCAmelCase_ ) ) UpperCAmelCase = sum(lowerCAmelCase_ ) / len(lowerCAmelCase_ ) UpperCAmelCase = float(fa_score(y_true=lowerCAmelCase_ , y_pred=[id_pred["""prediction"""] for id_pred in ids_preds] ) ) return {"exact_match": em, "f1_m": fa_m, "f1_a": fa_a} @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __lowercase ( datasets.Metric ): def _lowercase ( self : int ) -> Any: """simple docstring""" if self.config_name not in [ "boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg", ]: raise KeyError( """You should supply a configuration name selected in """ """[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]""" ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , codebase_urls=[] , reference_urls=[] , format="""numpy""" if not self.config_name == """record""" and not self.config_name == """multirc""" else None , ) def _lowercase ( self : Optional[Any] ) -> Any: """simple docstring""" if self.config_name == "record": return { "predictions": { "idx": { "passage": datasets.Value("""int64""" ), "query": datasets.Value("""int64""" ), }, "prediction_text": datasets.Value("""string""" ), }, "references": { "idx": { "passage": datasets.Value("""int64""" ), "query": datasets.Value("""int64""" ), }, "answers": datasets.Sequence(datasets.Value("""string""" ) ), }, } elif self.config_name == "multirc": return { "predictions": { "idx": { "answer": datasets.Value("""int64""" ), "paragraph": datasets.Value("""int64""" ), "question": datasets.Value("""int64""" ), }, "prediction": datasets.Value("""int64""" ), }, "references": datasets.Value("""int64""" ), } else: return { "predictions": datasets.Value("""int64""" ), "references": datasets.Value("""int64""" ), } def _lowercase ( self : Dict , __lowerCamelCase : int , __lowerCamelCase : Optional[int] ) -> List[Any]: """simple docstring""" if self.config_name == "axb": return {"matthews_correlation": matthews_corrcoef(__lowerCamelCase , __lowerCamelCase )} elif self.config_name == "cb": return acc_and_fa(__lowerCamelCase , __lowerCamelCase , fa_avg="""macro""" ) elif self.config_name == "record": UpperCAmelCase = [ { """qas""": [ {"""id""": ref["""idx"""]["""query"""], """answers""": [{"""text""": ans} for ans in ref["""answers"""]]} for ref in references ] } ] UpperCAmelCase = {pred["""idx"""]["""query"""]: pred["""prediction_text"""] for pred in predictions} return evaluate_record(__lowerCamelCase , __lowerCamelCase )[0] elif self.config_name == "multirc": return evaluate_multirc(__lowerCamelCase , __lowerCamelCase ) elif self.config_name in ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]: return {"accuracy": simple_accuracy(__lowerCamelCase , __lowerCamelCase )} else: raise KeyError( """You should supply a configuration name selected in """ """[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]""" )
627
1
'''simple docstring''' import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import MaskaFormerConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskaFormerForUniversalSegmentation, MaskaFormerModel if is_vision_available(): from transformers import MaskaFormerImageProcessor if is_vision_available(): from PIL import Image class SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : List[str] , __lowerCAmelCase : Dict , __lowerCAmelCase : Tuple=2 , __lowerCAmelCase : List[Any]=True , __lowerCAmelCase : Optional[int]=False , __lowerCAmelCase : int=10 , __lowerCAmelCase : Optional[Any]=3 , __lowerCAmelCase : Any=32 * 8 , __lowerCAmelCase : Optional[Any]=32 * 8 , __lowerCAmelCase : List[Any]=4 , __lowerCAmelCase : Dict=64 , ): """simple docstring""" _lowerCAmelCase = parent _lowerCAmelCase = batch_size _lowerCAmelCase = is_training _lowerCAmelCase = use_auxiliary_loss _lowerCAmelCase = num_queries _lowerCAmelCase = num_channels _lowerCAmelCase = min_size _lowerCAmelCase = max_size _lowerCAmelCase = num_labels _lowerCAmelCase = hidden_dim _lowerCAmelCase = hidden_dim def a ( self : Tuple ): """simple docstring""" _lowerCAmelCase = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( __lowerCAmelCase ) _lowerCAmelCase = torch.ones([self.batch_size, self.min_size, self.max_size] , device=__lowerCAmelCase ) _lowerCAmelCase = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=__lowerCAmelCase ) > 0.5 ).float() _lowerCAmelCase = (torch.rand((self.batch_size, self.num_labels) , device=__lowerCAmelCase ) > 0.5).long() _lowerCAmelCase = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def a ( self : int ): """simple docstring""" _lowerCAmelCase = MaskaFormerConfig( hidden_size=self.hidden_dim , ) _lowerCAmelCase = self.num_queries _lowerCAmelCase = self.num_labels _lowerCAmelCase = [1, 1, 1, 1] _lowerCAmelCase = self.num_channels _lowerCAmelCase = 64 _lowerCAmelCase = 128 _lowerCAmelCase = self.hidden_dim _lowerCAmelCase = self.hidden_dim _lowerCAmelCase = self.hidden_dim return config def a ( self : Union[str, Any] ): """simple docstring""" _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase = self.prepare_config_and_inputs() _lowerCAmelCase = {'pixel_values': pixel_values, 'pixel_mask': pixel_mask} return config, inputs_dict def a ( self : Dict , __lowerCAmelCase : int , __lowerCAmelCase : Union[str, Any] ): """simple docstring""" _lowerCAmelCase = output.encoder_hidden_states _lowerCAmelCase = output.pixel_decoder_hidden_states _lowerCAmelCase = output.transformer_decoder_hidden_states self.parent.assertTrue(len(__lowerCAmelCase ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(__lowerCAmelCase ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(__lowerCAmelCase ) , config.decoder_layers ) def a ( self : Any , __lowerCAmelCase : Tuple , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Optional[int]=False ): """simple docstring""" with torch.no_grad(): _lowerCAmelCase = MaskaFormerModel(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCAmelCase = model(pixel_values=__lowerCAmelCase , pixel_mask=__lowerCAmelCase ) _lowerCAmelCase = model(__lowerCAmelCase , output_hidden_states=__lowerCAmelCase ) self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.hidden_dim) , ) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(output.encoder_last_hidden_state is not None ) if output_hidden_states: self.check_output_hidden_state(__lowerCAmelCase , __lowerCAmelCase ) def a ( self : Any , __lowerCAmelCase : List[str] , __lowerCAmelCase : Dict , __lowerCAmelCase : str , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : int ): """simple docstring""" _lowerCAmelCase = MaskaFormerForUniversalSegmentation(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() def comm_check_on_output(__lowerCAmelCase : List[str] ): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.encoder_last_hidden_state is not None ) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , ) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1) ) with torch.no_grad(): _lowerCAmelCase = model(pixel_values=__lowerCAmelCase , pixel_mask=__lowerCAmelCase ) _lowerCAmelCase = model(__lowerCAmelCase ) comm_check_on_output(__lowerCAmelCase ) _lowerCAmelCase = model( pixel_values=__lowerCAmelCase , pixel_mask=__lowerCAmelCase , mask_labels=__lowerCAmelCase , class_labels=__lowerCAmelCase ) comm_check_on_output(__lowerCAmelCase ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape , torch.Size([1] ) ) @require_torch class SCREAMING_SNAKE_CASE ( __a , __a , unittest.TestCase ): """simple docstring""" __A = (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else () __A = {"feature-extraction": MaskaFormerModel} if is_torch_available() else {} __A = False __A = False __A = False __A = False def a ( self : Tuple ): """simple docstring""" _lowerCAmelCase = MaskaFormerModelTester(self ) _lowerCAmelCase = ConfigTester(self , config_class=__lowerCAmelCase , has_text_modality=__lowerCAmelCase ) def a ( self : Optional[int] ): """simple docstring""" self.config_tester.run_common_tests() def a ( self : Any ): """simple docstring""" _lowerCAmelCase , _lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(__lowerCAmelCase , **__lowerCAmelCase , output_hidden_states=__lowerCAmelCase ) def a ( self : Dict ): """simple docstring""" _lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*__lowerCAmelCase ) @unittest.skip(reason='Mask2Former does not use inputs_embeds' ) def a ( self : List[Any] ): """simple docstring""" pass @unittest.skip(reason='Mask2Former does not have a get_input_embeddings method' ) def a ( self : Union[str, Any] ): """simple docstring""" pass @unittest.skip(reason='Mask2Former is not a generative model' ) def a ( self : Any ): """simple docstring""" pass @unittest.skip(reason='Mask2Former does not use token embeddings' ) def a ( self : int ): """simple docstring""" pass @require_torch_multi_gpu @unittest.skip( reason='Mask2Former has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`' ) def a ( self : Union[str, Any] ): """simple docstring""" pass @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def a ( self : Tuple ): """simple docstring""" pass def a ( self : Tuple ): """simple docstring""" _lowerCAmelCase , _lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCAmelCase = model_class(__lowerCAmelCase ) _lowerCAmelCase = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _lowerCAmelCase = [*signature.parameters.keys()] _lowerCAmelCase = ['pixel_values'] self.assertListEqual(arg_names[:1] , __lowerCAmelCase ) @slow def a ( self : Union[str, Any] ): """simple docstring""" for model_name in ["facebook/mask2former-swin-small-coco-instance"]: _lowerCAmelCase = MaskaFormerModel.from_pretrained(__lowerCAmelCase ) self.assertIsNotNone(__lowerCAmelCase ) def a ( self : List[str] ): """simple docstring""" _lowerCAmelCase = (self.model_tester.min_size,) * 2 _lowerCAmelCase = { 'pixel_values': torch.randn((2, 3, *size) , device=__lowerCAmelCase ), 'mask_labels': torch.randn((2, 10, *size) , device=__lowerCAmelCase ), 'class_labels': torch.zeros(2 , 10 , device=__lowerCAmelCase ).long(), } _lowerCAmelCase = self.model_tester.get_config() _lowerCAmelCase = MaskaFormerForUniversalSegmentation(__lowerCAmelCase ).to(__lowerCAmelCase ) _lowerCAmelCase = model(**__lowerCAmelCase ) self.assertTrue(outputs.loss is not None ) def a ( self : Union[str, Any] ): """simple docstring""" _lowerCAmelCase , _lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(__lowerCAmelCase , **__lowerCAmelCase , output_hidden_states=__lowerCAmelCase ) def a ( self : List[str] ): """simple docstring""" _lowerCAmelCase , _lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCAmelCase = model_class(__lowerCAmelCase ).to(__lowerCAmelCase ) _lowerCAmelCase = model(**__lowerCAmelCase , output_attentions=__lowerCAmelCase ) self.assertTrue(outputs.attentions is not None ) def a ( self : int ): """simple docstring""" if not self.model_tester.is_training: return _lowerCAmelCase = self.all_model_classes[1] _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase = self.model_tester.prepare_config_and_inputs() _lowerCAmelCase = model_class(__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.train() _lowerCAmelCase = model(__lowerCAmelCase , mask_labels=__lowerCAmelCase , class_labels=__lowerCAmelCase ).loss loss.backward() def a ( self : Dict ): """simple docstring""" _lowerCAmelCase = self.all_model_classes[1] _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase = self.model_tester.prepare_config_and_inputs() _lowerCAmelCase = True _lowerCAmelCase = True _lowerCAmelCase = model_class(__lowerCAmelCase ).to(__lowerCAmelCase ) model.train() _lowerCAmelCase = model(__lowerCAmelCase , mask_labels=__lowerCAmelCase , class_labels=__lowerCAmelCase ) _lowerCAmelCase = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() _lowerCAmelCase = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() _lowerCAmelCase = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() _lowerCAmelCase = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=__lowerCAmelCase ) self.assertIsNotNone(encoder_hidden_states.grad ) self.assertIsNotNone(pixel_decoder_hidden_states.grad ) self.assertIsNotNone(transformer_decoder_hidden_states.grad ) self.assertIsNotNone(attentions.grad ) snake_case = 1e-4 def A_ ( ): _lowerCAmelCase = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_vision @slow class SCREAMING_SNAKE_CASE ( unittest.TestCase ): """simple docstring""" @cached_property def a ( self : List[Any] ): """simple docstring""" return "facebook/mask2former-swin-small-coco-instance" @cached_property def a ( self : Tuple ): """simple docstring""" return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints ) if is_vision_available() else None def a ( self : Dict ): """simple docstring""" _lowerCAmelCase = MaskaFormerModel.from_pretrained(self.model_checkpoints ).to(__lowerCAmelCase ) _lowerCAmelCase = self.default_image_processor _lowerCAmelCase = prepare_img() _lowerCAmelCase = image_processor(__lowerCAmelCase , return_tensors='pt' ).to(__lowerCAmelCase ) _lowerCAmelCase = inputs['pixel_values'].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(__lowerCAmelCase , (1, 3, 384, 384) ) with torch.no_grad(): _lowerCAmelCase = model(**__lowerCAmelCase ) _lowerCAmelCase = torch.tensor( [[-0.2_7_9_0, -1.0_7_1_7, -1.1_6_6_8], [-0.5_1_2_8, -0.3_1_2_8, -0.4_9_8_7], [-0.5_8_3_2, 0.1_9_7_1, -0.0_1_9_7]] ).to(__lowerCAmelCase ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] , __lowerCAmelCase , atol=__lowerCAmelCase ) ) _lowerCAmelCase = torch.tensor( [[0.8_9_7_3, 1.1_8_4_7, 1.1_7_7_6], [1.1_9_3_4, 1.5_0_4_0, 1.5_1_2_8], [1.1_1_5_3, 1.4_4_8_6, 1.4_9_5_1]] ).to(__lowerCAmelCase ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , __lowerCAmelCase , atol=__lowerCAmelCase ) ) _lowerCAmelCase = torch.tensor( [[2.1_1_5_2, 1.7_0_0_0, -0.8_6_0_3], [1.5_8_0_8, 1.8_0_0_4, -0.9_3_5_3], [1.6_0_4_3, 1.7_4_9_5, -0.5_9_9_9]] ).to(__lowerCAmelCase ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] , __lowerCAmelCase , atol=__lowerCAmelCase ) ) def a ( self : Dict ): """simple docstring""" _lowerCAmelCase = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(__lowerCAmelCase ).eval() _lowerCAmelCase = self.default_image_processor _lowerCAmelCase = prepare_img() _lowerCAmelCase = image_processor(__lowerCAmelCase , return_tensors='pt' ).to(__lowerCAmelCase ) _lowerCAmelCase = inputs['pixel_values'].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(__lowerCAmelCase , (1, 3, 384, 384) ) with torch.no_grad(): _lowerCAmelCase = model(**__lowerCAmelCase ) # masks_queries_logits _lowerCAmelCase = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) ) _lowerCAmelCase = [ [-8.7_8_3_9, -9.0_0_5_6, -8.8_1_2_1], [-7.4_1_0_4, -7.0_3_1_3, -6.5_4_0_1], [-6.6_1_0_5, -6.3_4_2_7, -6.4_6_7_5], ] _lowerCAmelCase = torch.tensor(__lowerCAmelCase ).to(__lowerCAmelCase ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , __lowerCAmelCase , atol=__lowerCAmelCase ) ) # class_queries_logits _lowerCAmelCase = outputs.class_queries_logits self.assertEqual(class_queries_logits.shape , (1, model.config.num_queries, model.config.num_labels + 1) ) _lowerCAmelCase = torch.tensor( [ [1.8_3_2_4, -8.0_8_3_5, -4.1_9_2_2], [0.8_4_5_0, -9.0_0_5_0, -3.6_0_5_3], [0.3_0_4_5, -7.7_2_9_3, -3.0_2_7_5], ] ).to(__lowerCAmelCase ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , __lowerCAmelCase , atol=__lowerCAmelCase ) ) def a ( self : Optional[int] ): """simple docstring""" _lowerCAmelCase = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(__lowerCAmelCase ).eval() _lowerCAmelCase = self.default_image_processor _lowerCAmelCase = image_processor( [np.zeros((3, 800, 1333) ), np.zeros((3, 800, 1333) )] , segmentation_maps=[np.zeros((384, 384) ).astype(np.floataa ), np.zeros((384, 384) ).astype(np.floataa )] , return_tensors='pt' , ) _lowerCAmelCase = inputs['pixel_values'].to(__lowerCAmelCase ) _lowerCAmelCase = [el.to(__lowerCAmelCase ) for el in inputs['mask_labels']] _lowerCAmelCase = [el.to(__lowerCAmelCase ) for el in inputs['class_labels']] with torch.no_grad(): _lowerCAmelCase = model(**__lowerCAmelCase ) self.assertTrue(outputs.loss is not None )
309
'''simple docstring''' import warnings from typing import List, Optional, Union from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class SCREAMING_SNAKE_CASE ( __a ): """simple docstring""" __A = ["image_processor", "tokenizer"] __A = "FlavaImageProcessor" __A = ("BertTokenizer", "BertTokenizerFast") def __init__( self : Dict , __lowerCAmelCase : int=None , __lowerCAmelCase : Optional[Any]=None , **__lowerCAmelCase : int ): """simple docstring""" _lowerCAmelCase = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , __lowerCAmelCase , ) _lowerCAmelCase = kwargs.pop('feature_extractor' ) _lowerCAmelCase = 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__(__lowerCAmelCase , __lowerCAmelCase ) _lowerCAmelCase = self.image_processor def __call__( self : Union[str, Any] , __lowerCAmelCase : Optional[ImageInput] = None , __lowerCAmelCase : Optional[Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]]] = None , __lowerCAmelCase : bool = True , __lowerCAmelCase : Union[bool, str, PaddingStrategy] = False , __lowerCAmelCase : Union[bool, str, TruncationStrategy] = False , __lowerCAmelCase : Optional[int] = None , __lowerCAmelCase : int = 0 , __lowerCAmelCase : Optional[int] = None , __lowerCAmelCase : Optional[bool] = None , __lowerCAmelCase : Optional[bool] = None , __lowerCAmelCase : Optional[bool] = None , __lowerCAmelCase : Optional[bool] = None , __lowerCAmelCase : bool = False , __lowerCAmelCase : bool = False , __lowerCAmelCase : bool = False , __lowerCAmelCase : bool = False , __lowerCAmelCase : bool = True , __lowerCAmelCase : Optional[Union[str, TensorType]] = None , **__lowerCAmelCase : 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 = self.tokenizer( text=__lowerCAmelCase , add_special_tokens=__lowerCAmelCase , padding=__lowerCAmelCase , truncation=__lowerCAmelCase , max_length=__lowerCAmelCase , stride=__lowerCAmelCase , pad_to_multiple_of=__lowerCAmelCase , return_token_type_ids=__lowerCAmelCase , return_attention_mask=__lowerCAmelCase , return_overflowing_tokens=__lowerCAmelCase , return_special_tokens_mask=__lowerCAmelCase , return_offsets_mapping=__lowerCAmelCase , return_length=__lowerCAmelCase , verbose=__lowerCAmelCase , return_tensors=__lowerCAmelCase , **__lowerCAmelCase , ) if images is not None: _lowerCAmelCase = self.image_processor( __lowerCAmelCase , return_image_mask=__lowerCAmelCase , return_codebook_pixels=__lowerCAmelCase , return_tensors=__lowerCAmelCase , **__lowerCAmelCase , ) if text is not None and images is not None: encoding.update(__lowerCAmelCase ) return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**__lowerCAmelCase ) , tensor_type=__lowerCAmelCase ) def a ( self : Any , *__lowerCAmelCase : str , **__lowerCAmelCase : List[Any] ): """simple docstring""" return self.tokenizer.batch_decode(*__lowerCAmelCase , **__lowerCAmelCase ) def a ( self : List[str] , *__lowerCAmelCase : List[str] , **__lowerCAmelCase : Optional[int] ): """simple docstring""" return self.tokenizer.decode(*__lowerCAmelCase , **__lowerCAmelCase ) @property def a ( self : List[str] ): """simple docstring""" _lowerCAmelCase = self.tokenizer.model_input_names _lowerCAmelCase = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def a ( self : Optional[int] ): """simple docstring""" warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' , __lowerCAmelCase , ) return self.image_processor_class @property def a ( self : Any ): """simple docstring""" warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , __lowerCAmelCase , ) return self.image_processor
309
1
"""simple docstring""" from collections.abc import Iterator, MutableMapping from dataclasses import dataclass from typing import Generic, TypeVar A : Tuple = TypeVar("KEY") A : Optional[Any] = TypeVar("VAL") @dataclass(frozen=lowerCAmelCase__ ,slots=lowerCAmelCase__ ) class _UpperCamelCase ( Generic[KEY, VAL] ): '''simple docstring''' __UpperCAmelCase : KEY __UpperCAmelCase : VAL class _UpperCamelCase ( _Item ): '''simple docstring''' def __init__( self ): super().__init__(__a , __a ) def __bool__( self ): return False A : Tuple = _DeletedItem() class _UpperCamelCase ( MutableMapping[KEY, VAL] ): '''simple docstring''' def __init__( self , __a = 8 , __a = 0.7_5 ): __lowerCAmelCase = initial_block_size __lowerCAmelCase = [None] * initial_block_size assert 0.0 < capacity_factor < 1.0 __lowerCAmelCase = capacity_factor __lowerCAmelCase = 0 def snake_case ( self , __a ): return hash(__a ) % len(self._buckets ) def snake_case ( self , __a ): return (ind + 1) % len(self._buckets ) def snake_case ( self , __a , __a , __a ): __lowerCAmelCase = self._buckets[ind] if not stored: __lowerCAmelCase = _Item(__a , __a ) self._len += 1 return True elif stored.key == key: __lowerCAmelCase = _Item(__a , __a ) return True else: return False def snake_case ( self ): __lowerCAmelCase = len(self._buckets ) * self._capacity_factor return len(self ) >= int(__a ) def snake_case ( self ): if len(self._buckets ) <= self._initial_block_size: return False __lowerCAmelCase = len(self._buckets ) * self._capacity_factor / 2 return len(self ) < limit def snake_case ( self , __a ): __lowerCAmelCase = self._buckets __lowerCAmelCase = [None] * new_size __lowerCAmelCase = 0 for item in old_buckets: if item: self._add_item(item.key , item.val ) def snake_case ( self ): self._resize(len(self._buckets ) * 2 ) def snake_case ( self ): self._resize(len(self._buckets ) // 2 ) def snake_case ( self , __a ): __lowerCAmelCase = self._get_bucket_index(__a ) for _ in range(len(self._buckets ) ): yield ind __lowerCAmelCase = self._get_next_ind(__a ) def snake_case ( self , __a , __a ): for ind in self._iterate_buckets(__a ): if self._try_set(__a , __a , __a ): break def __setitem__( self , __a , __a ): if self._is_full(): self._size_up() self._add_item(__a , __a ) def __delitem__( self , __a ): for ind in self._iterate_buckets(__a ): __lowerCAmelCase = self._buckets[ind] if item is None: raise KeyError(__a ) if item is _deleted: continue if item.key == key: __lowerCAmelCase = _deleted self._len -= 1 break if self._is_sparse(): self._size_down() def __getitem__( self , __a ): for ind in self._iterate_buckets(__a ): __lowerCAmelCase = self._buckets[ind] if item is None: break if item is _deleted: continue if item.key == key: return item.val raise KeyError(__a ) def __len__( self ): return self._len def __iter__( self ): yield from (item.key for item in self._buckets if item) def __repr__( self ): __lowerCAmelCase = " ,".join( f"{item.key}: {item.val}" for item in self._buckets if item ) return f"HashMap({val_string})"
282
"""simple docstring""" import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import SegformerImageProcessor, SwinConfig, UperNetConfig, UperNetForSemanticSegmentation def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = 384 __lowerCAmelCase = 7 if "tiny" in model_name: __lowerCAmelCase = 96 __lowerCAmelCase = (2, 2, 6, 2) __lowerCAmelCase = (3, 6, 12, 24) elif "small" in model_name: __lowerCAmelCase = 96 __lowerCAmelCase = (2, 2, 18, 2) __lowerCAmelCase = (3, 6, 12, 24) elif "base" in model_name: __lowerCAmelCase = 128 __lowerCAmelCase = (2, 2, 18, 2) __lowerCAmelCase = (4, 8, 16, 32) __lowerCAmelCase = 12 __lowerCAmelCase = 512 elif "large" in model_name: __lowerCAmelCase = 192 __lowerCAmelCase = (2, 2, 18, 2) __lowerCAmelCase = (6, 12, 24, 48) __lowerCAmelCase = 12 __lowerCAmelCase = 768 # set label information __lowerCAmelCase = 150 __lowerCAmelCase = "huggingface/label-files" __lowerCAmelCase = "ade20k-id2label.json" __lowerCAmelCase = json.load(open(hf_hub_download(_UpperCamelCase , _UpperCamelCase , repo_type="dataset" ) , "r" ) ) __lowerCAmelCase = {int(_UpperCamelCase ): v for k, v in idalabel.items()} __lowerCAmelCase = {v: k for k, v in idalabel.items()} __lowerCAmelCase = SwinConfig( embed_dim=_UpperCamelCase , depths=_UpperCamelCase , num_heads=_UpperCamelCase , window_size=_UpperCamelCase , out_features=["stage1", "stage2", "stage3", "stage4"] , ) __lowerCAmelCase = UperNetConfig( backbone_config=_UpperCamelCase , auxiliary_in_channels=_UpperCamelCase , num_labels=_UpperCamelCase , idalabel=_UpperCamelCase , labelaid=_UpperCamelCase , ) return config def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = [] # fmt: off # stem rename_keys.append(("backbone.patch_embed.projection.weight", "backbone.embeddings.patch_embeddings.projection.weight") ) rename_keys.append(("backbone.patch_embed.projection.bias", "backbone.embeddings.patch_embeddings.projection.bias") ) rename_keys.append(("backbone.patch_embed.norm.weight", "backbone.embeddings.norm.weight") ) rename_keys.append(("backbone.patch_embed.norm.bias", "backbone.embeddings.norm.bias") ) # stages for i in range(len(config.backbone_config.depths ) ): for j in range(config.backbone_config.depths[i] ): rename_keys.append((f"backbone.stages.{i}.blocks.{j}.norm1.weight", f"backbone.encoder.layers.{i}.blocks.{j}.layernorm_before.weight") ) rename_keys.append((f"backbone.stages.{i}.blocks.{j}.norm1.bias", f"backbone.encoder.layers.{i}.blocks.{j}.layernorm_before.bias") ) rename_keys.append((f"backbone.stages.{i}.blocks.{j}.attn.w_msa.relative_position_bias_table", f"backbone.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_bias_table") ) rename_keys.append((f"backbone.stages.{i}.blocks.{j}.attn.w_msa.relative_position_index", f"backbone.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_index") ) rename_keys.append((f"backbone.stages.{i}.blocks.{j}.attn.w_msa.proj.weight", f"backbone.encoder.layers.{i}.blocks.{j}.attention.output.dense.weight") ) rename_keys.append((f"backbone.stages.{i}.blocks.{j}.attn.w_msa.proj.bias", f"backbone.encoder.layers.{i}.blocks.{j}.attention.output.dense.bias") ) rename_keys.append((f"backbone.stages.{i}.blocks.{j}.norm2.weight", f"backbone.encoder.layers.{i}.blocks.{j}.layernorm_after.weight") ) rename_keys.append((f"backbone.stages.{i}.blocks.{j}.norm2.bias", f"backbone.encoder.layers.{i}.blocks.{j}.layernorm_after.bias") ) rename_keys.append((f"backbone.stages.{i}.blocks.{j}.ffn.layers.0.0.weight", f"backbone.encoder.layers.{i}.blocks.{j}.intermediate.dense.weight") ) rename_keys.append((f"backbone.stages.{i}.blocks.{j}.ffn.layers.0.0.bias", f"backbone.encoder.layers.{i}.blocks.{j}.intermediate.dense.bias") ) rename_keys.append((f"backbone.stages.{i}.blocks.{j}.ffn.layers.1.weight", f"backbone.encoder.layers.{i}.blocks.{j}.output.dense.weight") ) rename_keys.append((f"backbone.stages.{i}.blocks.{j}.ffn.layers.1.bias", f"backbone.encoder.layers.{i}.blocks.{j}.output.dense.bias") ) if i < 3: rename_keys.append((f"backbone.stages.{i}.downsample.reduction.weight", f"backbone.encoder.layers.{i}.downsample.reduction.weight") ) rename_keys.append((f"backbone.stages.{i}.downsample.norm.weight", f"backbone.encoder.layers.{i}.downsample.norm.weight") ) rename_keys.append((f"backbone.stages.{i}.downsample.norm.bias", f"backbone.encoder.layers.{i}.downsample.norm.bias") ) rename_keys.append((f"backbone.norm{i}.weight", f"backbone.hidden_states_norms.stage{i+1}.weight") ) rename_keys.append((f"backbone.norm{i}.bias", f"backbone.hidden_states_norms.stage{i+1}.bias") ) # decode head rename_keys.extend( [ ("decode_head.conv_seg.weight", "decode_head.classifier.weight"), ("decode_head.conv_seg.bias", "decode_head.classifier.bias"), ("auxiliary_head.conv_seg.weight", "auxiliary_head.classifier.weight"), ("auxiliary_head.conv_seg.bias", "auxiliary_head.classifier.bias"), ] ) # fmt: on return rename_keys def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = dct.pop(_UpperCamelCase ) __lowerCAmelCase = val def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = [int(backbone_config.embed_dim * 2**i ) for i in range(len(backbone_config.depths ) )] for i in range(len(backbone_config.depths ) ): __lowerCAmelCase = num_features[i] for j in range(backbone_config.depths[i] ): # fmt: off # read in weights + bias of input projection layer (in original implementation, this is a single matrix + bias) __lowerCAmelCase = state_dict.pop(f"backbone.stages.{i}.blocks.{j}.attn.w_msa.qkv.weight" ) __lowerCAmelCase = state_dict.pop(f"backbone.stages.{i}.blocks.{j}.attn.w_msa.qkv.bias" ) # next, add query, keys and values (in that order) to the state dict __lowerCAmelCase = in_proj_weight[:dim, :] __lowerCAmelCase = in_proj_bias[: dim] __lowerCAmelCase = in_proj_weight[ dim : dim * 2, : ] __lowerCAmelCase = in_proj_bias[ dim : dim * 2 ] __lowerCAmelCase = in_proj_weight[ -dim :, : ] __lowerCAmelCase = in_proj_bias[-dim :] # fmt: on def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase , __lowerCAmelCase = x.shape __lowerCAmelCase = x.reshape(_UpperCamelCase , 4 , in_channel // 4 ) __lowerCAmelCase = x[:, [0, 2, 1, 3], :].transpose(1 , 2 ).reshape(_UpperCamelCase , _UpperCamelCase ) return x def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase , __lowerCAmelCase = x.shape __lowerCAmelCase = x.reshape(_UpperCamelCase , in_channel // 4 , 4 ) __lowerCAmelCase = x[:, :, [0, 2, 1, 3]].transpose(1 , 2 ).reshape(_UpperCamelCase , _UpperCamelCase ) return x def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = x.shape[0] __lowerCAmelCase = x.reshape(4 , in_channel // 4 ) __lowerCAmelCase = x[[0, 2, 1, 3], :].transpose(0 , 1 ).reshape(_UpperCamelCase ) return x def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = x.shape[0] __lowerCAmelCase = x.reshape(in_channel // 4 , 4 ) __lowerCAmelCase = x[:, [0, 2, 1, 3]].transpose(0 , 1 ).reshape(_UpperCamelCase ) return x def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = { "upernet-swin-tiny": "https://download.openmmlab.com/mmsegmentation/v0.5/swin/upernet_swin_tiny_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K/upernet_swin_tiny_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K_20210531_112542-e380ad3e.pth", "upernet-swin-small": "https://download.openmmlab.com/mmsegmentation/v0.5/swin/upernet_swin_small_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K/upernet_swin_small_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K_20210526_192015-ee2fff1c.pth", "upernet-swin-base": "https://download.openmmlab.com/mmsegmentation/v0.5/swin/upernet_swin_base_patch4_window12_512x512_160k_ade20k_pretrain_384x384_22K/upernet_swin_base_patch4_window12_512x512_160k_ade20k_pretrain_384x384_22K_20210531_125459-429057bf.pth", "upernet-swin-large": "https://download.openmmlab.com/mmsegmentation/v0.5/swin/upernet_swin_large_patch4_window12_512x512_pretrain_384x384_22K_160k_ade20k/upernet_swin_large_patch4_window12_512x512_pretrain_384x384_22K_160k_ade20k_20220318_091743-9ba68901.pth", } __lowerCAmelCase = model_name_to_url[model_name] __lowerCAmelCase = torch.hub.load_state_dict_from_url(_UpperCamelCase , map_location="cpu" , file_name=_UpperCamelCase )[ "state_dict" ] for name, param in state_dict.items(): print(_UpperCamelCase , param.shape ) __lowerCAmelCase = get_upernet_config(_UpperCamelCase ) __lowerCAmelCase = UperNetForSemanticSegmentation(_UpperCamelCase ) model.eval() # replace "bn" => "batch_norm" for key in state_dict.copy().keys(): __lowerCAmelCase = state_dict.pop(_UpperCamelCase ) if "bn" in key: __lowerCAmelCase = key.replace("bn" , "batch_norm" ) __lowerCAmelCase = val # rename keys __lowerCAmelCase = create_rename_keys(_UpperCamelCase ) for src, dest in rename_keys: rename_key(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) read_in_q_k_v(_UpperCamelCase , config.backbone_config ) # fix downsample parameters for key, value in state_dict.items(): if "downsample" in key: if "reduction" in key: __lowerCAmelCase = reverse_correct_unfold_reduction_order(_UpperCamelCase ) if "norm" in key: __lowerCAmelCase = reverse_correct_unfold_norm_order(_UpperCamelCase ) model.load_state_dict(_UpperCamelCase ) # verify on image __lowerCAmelCase = "https://huggingface.co/datasets/hf-internal-testing/fixtures_ade20k/resolve/main/ADE_val_00000001.jpg" __lowerCAmelCase = Image.open(requests.get(_UpperCamelCase , stream=_UpperCamelCase ).raw ).convert("RGB" ) __lowerCAmelCase = SegformerImageProcessor() __lowerCAmelCase = processor(_UpperCamelCase , return_tensors="pt" ).pixel_values with torch.no_grad(): __lowerCAmelCase = model(_UpperCamelCase ) __lowerCAmelCase = outputs.logits print(logits.shape ) print("First values of logits:" , logits[0, 0, :3, :3] ) # assert values if model_name == "upernet-swin-tiny": __lowerCAmelCase = torch.tensor( [[-7.59_58, -7.59_58, -7.43_02], [-7.59_58, -7.59_58, -7.43_02], [-7.47_97, -7.47_97, -7.30_68]] ) elif model_name == "upernet-swin-small": __lowerCAmelCase = torch.tensor( [[-7.19_21, -7.19_21, -6.95_32], [-7.19_21, -7.19_21, -6.95_32], [-7.09_08, -7.09_08, -6.85_34]] ) elif model_name == "upernet-swin-base": __lowerCAmelCase = torch.tensor( [[-6.58_51, -6.58_51, -6.43_30], [-6.58_51, -6.58_51, -6.43_30], [-6.47_63, -6.47_63, -6.32_54]] ) elif model_name == "upernet-swin-large": __lowerCAmelCase = torch.tensor( [[-7.52_97, -7.52_97, -7.38_02], [-7.52_97, -7.52_97, -7.38_02], [-7.40_44, -7.40_44, -7.25_86]] ) print("Logits:" , outputs.logits[0, 0, :3, :3] ) assert torch.allclose(outputs.logits[0, 0, :3, :3] , _UpperCamelCase , atol=1e-4 ) print("Looks ok!" ) if pytorch_dump_folder_path is not None: print(f"Saving model {model_name} to {pytorch_dump_folder_path}" ) model.save_pretrained(_UpperCamelCase ) print(f"Saving processor to {pytorch_dump_folder_path}" ) processor.save_pretrained(_UpperCamelCase ) if push_to_hub: print(f"Pushing model and processor for {model_name} to hub" ) model.push_to_hub(f"openmmlab/{model_name}" ) processor.push_to_hub(f"openmmlab/{model_name}" ) if __name__ == "__main__": A : int = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default="upernet-swin-tiny", type=str, choices=[f'''upernet-swin-{size}''' for size in ["tiny", "small", "base", "large"]], help="Name of the Swin + UperNet model you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether or not to push the converted model to the 🤗 hub." ) A : List[Any] = parser.parse_args() convert_upernet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
282
1
import unittest from transformers import load_tool from .test_tools_common import ToolTesterMixin class _lowercase ( unittest.TestCase , snake_case_ ): def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> Dict: """simple docstring""" UpperCamelCase_ : Optional[Any] = load_tool('text-classification' ) self.tool.setup() UpperCamelCase_ : Union[str, Any] = load_tool('text-classification' , remote=snake_case ) def SCREAMING_SNAKE_CASE__ ( self : str ) -> Union[str, Any]: """simple docstring""" UpperCamelCase_ : Union[str, Any] = self.tool('That\'s quite cool' , ['positive', 'negative'] ) self.assertEqual(snake_case , 'positive' ) def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> str: """simple docstring""" UpperCamelCase_ : Optional[Any] = self.remote_tool('That\'s quite cool' , ['positive', 'negative'] ) self.assertEqual(snake_case , 'positive' ) def SCREAMING_SNAKE_CASE__ ( self : str ) -> str: """simple docstring""" UpperCamelCase_ : int = self.tool(text='That\'s quite cool' , labels=['positive', 'negative'] ) self.assertEqual(snake_case , 'positive' ) def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> Optional[int]: """simple docstring""" UpperCamelCase_ : List[Any] = self.remote_tool(text='That\'s quite cool' , labels=['positive', 'negative'] ) self.assertEqual(snake_case , 'positive' )
417
import argparse import requests import torch from PIL import Image from torchvision.transforms import Compose, Normalize, Resize, ToTensor from transformers import SwinaSRConfig, SwinaSRForImageSuperResolution, SwinaSRImageProcessor def __lowercase ( lowerCamelCase : str ): UpperCamelCase_ : Any = SwinaSRConfig() if "Swin2SR_ClassicalSR_X4_64" in checkpoint_url: UpperCamelCase_ : Union[str, Any] = 4 elif "Swin2SR_CompressedSR_X4_48" in checkpoint_url: UpperCamelCase_ : Union[str, Any] = 4 UpperCamelCase_ : Union[str, Any] = 48 UpperCamelCase_ : List[Any] = 'pixelshuffle_aux' elif "Swin2SR_Lightweight_X2_64" in checkpoint_url: UpperCamelCase_ : Union[str, Any] = [6, 6, 6, 6] UpperCamelCase_ : Union[str, Any] = 60 UpperCamelCase_ : List[str] = [6, 6, 6, 6] UpperCamelCase_ : Tuple = 'pixelshuffledirect' elif "Swin2SR_RealworldSR_X4_64_BSRGAN_PSNR" in checkpoint_url: UpperCamelCase_ : Optional[int] = 4 UpperCamelCase_ : Dict = 'nearest+conv' elif "Swin2SR_Jpeg_dynamic" in checkpoint_url: UpperCamelCase_ : Any = 1 UpperCamelCase_ : List[Any] = 1 UpperCamelCase_ : List[str] = 126 UpperCamelCase_ : Dict = 7 UpperCamelCase_ : int = 2_5_5.0 UpperCamelCase_ : str = '' return config def __lowercase ( lowerCamelCase : Optional[int] , lowerCamelCase : Optional[Any] ): if "patch_embed.proj" in name and "layers" not in name: UpperCamelCase_ : Any = name.replace('patch_embed.proj' , 'embeddings.patch_embeddings.projection' ) if "patch_embed.norm" in name: UpperCamelCase_ : Tuple = name.replace('patch_embed.norm' , 'embeddings.patch_embeddings.layernorm' ) if "layers" in name: UpperCamelCase_ : List[str] = name.replace('layers' , 'encoder.stages' ) if "residual_group.blocks" in name: UpperCamelCase_ : Optional[Any] = name.replace('residual_group.blocks' , 'layers' ) if "attn.proj" in name: UpperCamelCase_ : List[Any] = name.replace('attn.proj' , 'attention.output.dense' ) if "attn" in name: UpperCamelCase_ : Dict = name.replace('attn' , 'attention.self' ) if "norm1" in name: UpperCamelCase_ : List[str] = name.replace('norm1' , 'layernorm_before' ) if "norm2" in name: UpperCamelCase_ : Optional[Any] = name.replace('norm2' , 'layernorm_after' ) if "mlp.fc1" in name: UpperCamelCase_ : List[str] = name.replace('mlp.fc1' , 'intermediate.dense' ) if "mlp.fc2" in name: UpperCamelCase_ : Optional[Any] = name.replace('mlp.fc2' , 'output.dense' ) if "q_bias" in name: UpperCamelCase_ : List[str] = name.replace('q_bias' , 'query.bias' ) if "k_bias" in name: UpperCamelCase_ : str = name.replace('k_bias' , 'key.bias' ) if "v_bias" in name: UpperCamelCase_ : Tuple = name.replace('v_bias' , 'value.bias' ) if "cpb_mlp" in name: UpperCamelCase_ : Optional[int] = name.replace('cpb_mlp' , 'continuous_position_bias_mlp' ) if "patch_embed.proj" in name: UpperCamelCase_ : Union[str, Any] = name.replace('patch_embed.proj' , 'patch_embed.projection' ) if name == "norm.weight": UpperCamelCase_ : Dict = 'layernorm.weight' if name == "norm.bias": UpperCamelCase_ : List[str] = 'layernorm.bias' if "conv_first" in name: UpperCamelCase_ : Any = name.replace('conv_first' , 'first_convolution' ) if ( "upsample" in name or "conv_before_upsample" in name or "conv_bicubic" in name or "conv_up" in name or "conv_hr" in name or "conv_last" in name or "aux" in name ): # heads if "conv_last" in name: UpperCamelCase_ : int = name.replace('conv_last' , 'final_convolution' ) if config.upsampler in ["pixelshuffle", "pixelshuffle_aux", "nearest+conv"]: if "conv_before_upsample.0" in name: UpperCamelCase_ : Union[str, Any] = name.replace('conv_before_upsample.0' , 'conv_before_upsample' ) if "upsample.0" in name: UpperCamelCase_ : Optional[Any] = name.replace('upsample.0' , 'upsample.convolution_0' ) if "upsample.2" in name: UpperCamelCase_ : Optional[Any] = name.replace('upsample.2' , 'upsample.convolution_1' ) UpperCamelCase_ : Dict = 'upsample.' + name elif config.upsampler == "pixelshuffledirect": UpperCamelCase_ : List[Any] = name.replace('upsample.0.weight' , 'upsample.conv.weight' ) UpperCamelCase_ : List[Any] = name.replace('upsample.0.bias' , 'upsample.conv.bias' ) else: pass else: UpperCamelCase_ : Union[str, Any] = 'swin2sr.' + name return name def __lowercase ( lowerCamelCase : Dict , lowerCamelCase : str ): for key in orig_state_dict.copy().keys(): UpperCamelCase_ : Any = orig_state_dict.pop(lowerCamelCase ) if "qkv" in key: UpperCamelCase_ : List[str] = key.split('.' ) UpperCamelCase_ : Any = int(key_split[1] ) UpperCamelCase_ : Union[str, Any] = int(key_split[4] ) UpperCamelCase_ : str = config.embed_dim if "weight" in key: UpperCamelCase_ : str = val[:dim, :] UpperCamelCase_ : Optional[int] = val[dim : dim * 2, :] UpperCamelCase_ : Union[str, Any] = val[-dim:, :] else: UpperCamelCase_ : Dict = val[:dim] UpperCamelCase_ : Tuple = val[dim : dim * 2] UpperCamelCase_ : str = val[-dim:] pass else: UpperCamelCase_ : Tuple = val return orig_state_dict def __lowercase ( lowerCamelCase : int , lowerCamelCase : int , lowerCamelCase : str ): UpperCamelCase_ : int = get_config(lowerCamelCase ) UpperCamelCase_ : Dict = SwinaSRForImageSuperResolution(lowerCamelCase ) model.eval() UpperCamelCase_ : Any = torch.hub.load_state_dict_from_url(lowerCamelCase , map_location='cpu' ) UpperCamelCase_ : str = convert_state_dict(lowerCamelCase , lowerCamelCase ) UpperCamelCase_, UpperCamelCase_ : List[Any] = model.load_state_dict(lowerCamelCase , strict=lowerCamelCase ) if len(lowerCamelCase ) > 0: raise ValueError('Missing keys when converting: {}'.format(lowerCamelCase ) ) for key in unexpected_keys: if not ("relative_position_index" in key or "relative_coords_table" in key or "self_mask" in key): raise ValueError(F"Unexpected key {key} in state_dict" ) # verify values UpperCamelCase_ : Tuple = 'https://github.com/mv-lab/swin2sr/blob/main/testsets/real-inputs/shanghai.jpg?raw=true' UpperCamelCase_ : List[Any] = Image.open(requests.get(lowerCamelCase , stream=lowerCamelCase ).raw ).convert('RGB' ) UpperCamelCase_ : Dict = SwinaSRImageProcessor() # pixel_values = processor(image, return_tensors="pt").pixel_values UpperCamelCase_ : Union[str, Any] = 126 if 'Jpeg' in checkpoint_url else 256 UpperCamelCase_ : str = Compose( [ Resize((image_size, image_size) ), ToTensor(), Normalize(mean=[0.4_8_5, 0.4_5_6, 0.4_0_6] , std=[0.2_2_9, 0.2_2_4, 0.2_2_5] ), ] ) UpperCamelCase_ : Union[str, Any] = transforms(lowerCamelCase ).unsqueeze(0 ) if config.num_channels == 1: UpperCamelCase_ : List[str] = pixel_values[:, 0, :, :].unsqueeze(1 ) UpperCamelCase_ : Optional[Any] = model(lowerCamelCase ) # assert values if "Swin2SR_ClassicalSR_X2_64" in checkpoint_url: UpperCamelCase_ : int = torch.Size([1, 3, 512, 512] ) UpperCamelCase_ : List[str] = torch.tensor( [[-0.7_0_8_7, -0.7_1_3_8, -0.6_7_2_1], [-0.8_3_4_0, -0.8_0_9_5, -0.7_2_9_8], [-0.9_1_4_9, -0.8_4_1_4, -0.7_9_4_0]] ) elif "Swin2SR_ClassicalSR_X4_64" in checkpoint_url: UpperCamelCase_ : str = torch.Size([1, 3, 1024, 1024] ) UpperCamelCase_ : Optional[Any] = torch.tensor( [[-0.7_7_7_5, -0.8_1_0_5, -0.8_9_3_3], [-0.7_7_6_4, -0.8_3_5_6, -0.9_2_2_5], [-0.7_9_7_6, -0.8_6_8_6, -0.9_5_7_9]] ) elif "Swin2SR_CompressedSR_X4_48" in checkpoint_url: # TODO values didn't match exactly here UpperCamelCase_ : List[str] = torch.Size([1, 3, 1024, 1024] ) UpperCamelCase_ : Tuple = torch.tensor( [[-0.8_0_3_5, -0.7_5_0_4, -0.7_4_9_1], [-0.8_5_3_8, -0.8_1_2_4, -0.7_7_8_2], [-0.8_8_0_4, -0.8_6_5_1, -0.8_4_9_3]] ) elif "Swin2SR_Lightweight_X2_64" in checkpoint_url: UpperCamelCase_ : Any = torch.Size([1, 3, 512, 512] ) UpperCamelCase_ : Tuple = torch.tensor( [[-0.7_6_6_9, -0.8_6_6_2, -0.8_7_6_7], [-0.8_8_1_0, -0.9_9_6_2, -0.9_8_2_0], [-0.9_3_4_0, -1.0_3_2_2, -1.1_1_4_9]] ) elif "Swin2SR_RealworldSR_X4_64_BSRGAN_PSNR" in checkpoint_url: UpperCamelCase_ : Optional[Any] = torch.Size([1, 3, 1024, 1024] ) UpperCamelCase_ : Tuple = torch.tensor( [[-0.5_2_3_8, -0.5_5_5_7, -0.6_3_2_1], [-0.6_0_1_6, -0.5_9_0_3, -0.6_3_9_1], [-0.6_2_4_4, -0.6_3_3_4, -0.6_8_8_9]] ) assert ( outputs.reconstruction.shape == expected_shape ), F"Shape of reconstruction should be {expected_shape}, but is {outputs.reconstruction.shape}" assert torch.allclose(outputs.reconstruction[0, 0, :3, :3] , lowerCamelCase , atol=1e-3 ) print('Looks ok!' ) UpperCamelCase_ : List[Any] = { 'https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_ClassicalSR_X2_64.pth': ( 'swin2SR-classical-sr-x2-64' ), 'https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_ClassicalSR_X4_64.pth': ( 'swin2SR-classical-sr-x4-64' ), 'https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_CompressedSR_X4_48.pth': ( 'swin2SR-compressed-sr-x4-48' ), 'https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_Lightweight_X2_64.pth': ( 'swin2SR-lightweight-x2-64' ), 'https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_RealworldSR_X4_64_BSRGAN_PSNR.pth': ( 'swin2SR-realworld-sr-x4-64-bsrgan-psnr' ), } UpperCamelCase_ : List[str] = url_to_name[checkpoint_url] if pytorch_dump_folder_path is not None: print(F"Saving model {model_name} to {pytorch_dump_folder_path}" ) model.save_pretrained(lowerCamelCase ) print(F"Saving image processor to {pytorch_dump_folder_path}" ) processor.save_pretrained(lowerCamelCase ) if push_to_hub: model.push_to_hub(F"caidas/{model_name}" ) processor.push_to_hub(F"caidas/{model_name}" ) if __name__ == "__main__": a_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--checkpoint_url', default='https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_ClassicalSR_X2_64.pth', type=str, help='URL of the original Swin2SR checkpoint you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) parser.add_argument('--push_to_hub', action='store_true', help='Whether to push the converted model to the hub.') a_ = parser.parse_args() convert_swinasr_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
417
1
'''simple docstring''' def __lowerCamelCase ( A__ = 1_000 ) -> int: """simple docstring""" UpperCamelCase , UpperCamelCase = 1, 1 UpperCamelCase = [] for i in range(1 , n + 1 ): UpperCamelCase = prev_numerator + 2 * prev_denominator UpperCamelCase = prev_numerator + prev_denominator if len(str(A__ ) ) > len(str(A__ ) ): result.append(A__ ) UpperCamelCase = numerator UpperCamelCase = denominator return len(A__ ) if __name__ == "__main__": print(f'''{solution() = }''')
714
'''simple docstring''' import io import math from typing import Dict, Optional, Union import numpy as np from huggingface_hub import hf_hub_download from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import convert_to_rgb, normalize, to_channel_dimension_format, to_pil_image from ...image_utils import ( ChannelDimension, ImageInput, get_image_size, infer_channel_dimension_format, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_torch_available, is_vision_available, logging from ...utils.import_utils import requires_backends if is_vision_available(): import textwrap from PIL import Image, ImageDraw, ImageFont if is_torch_available(): import torch from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11 else: _lowerCamelCase : Dict = False _lowerCamelCase : int = logging.get_logger(__name__) _lowerCamelCase : Dict = "ybelkada/fonts" def __lowerCamelCase ( ) -> Optional[int]: """simple docstring""" if is_torch_available() and not is_torch_greater_or_equal_than_1_11: raise ImportError( F"""You are using torch=={torch.__version__}, but torch>=1.11.0 is required to use """ 'Pix2StructImageProcessor. Please upgrade torch.' ) def __lowerCamelCase ( A__ , A__ , A__ ) -> str: """simple docstring""" requires_backends(A__ , ['torch'] ) _check_torch_version() UpperCamelCase = image_tensor.unsqueeze(0 ) UpperCamelCase = torch.nn.functional.unfold(A__ , (patch_height, patch_width) , stride=(patch_height, patch_width) ) UpperCamelCase = patches.reshape(image_tensor.size(0 ) , image_tensor.size(1 ) , A__ , A__ , -1 ) UpperCamelCase = patches.permute(0 , 4 , 2 , 3 , 1 ).reshape( image_tensor.size(2 ) // patch_height , image_tensor.size(3 ) // patch_width , image_tensor.size(1 ) * patch_height * patch_width , ) return patches.unsqueeze(0 ) def __lowerCamelCase ( A__ , A__ = 36 , A__ = "black" , A__ = "white" , A__ = 5 , A__ = 5 , A__ = 5 , A__ = 5 , A__ = None , A__ = None , ) -> Image.Image: """simple docstring""" requires_backends(A__ , 'vision' ) # Add new lines so that each line is no more than 80 characters. UpperCamelCase = textwrap.TextWrapper(width=80 ) UpperCamelCase = wrapper.wrap(text=A__ ) UpperCamelCase = '\n'.join(A__ ) if font_bytes is not None and font_path is None: UpperCamelCase = io.BytesIO(A__ ) elif font_path is not None: UpperCamelCase = font_path else: UpperCamelCase = hf_hub_download(A__ , 'Arial.TTF' ) UpperCamelCase = ImageFont.truetype(A__ , encoding='UTF-8' , size=A__ ) # Use a temporary canvas to determine the width and height in pixels when # rendering the text. UpperCamelCase = ImageDraw.Draw(Image.new('RGB' , (1, 1) , A__ ) ) UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = temp_draw.textbbox((0, 0) , A__ , A__ ) # Create the actual image with a bit of padding around the text. UpperCamelCase = text_width + left_padding + right_padding UpperCamelCase = text_height + top_padding + bottom_padding UpperCamelCase = Image.new('RGB' , (image_width, image_height) , A__ ) UpperCamelCase = ImageDraw.Draw(A__ ) draw.text(xy=(left_padding, top_padding) , text=A__ , fill=A__ , font=A__ ) return image def __lowerCamelCase ( A__ , A__ , **A__ ) -> Optional[Any]: """simple docstring""" requires_backends(A__ , 'vision' ) # Convert to PIL image if necessary UpperCamelCase = to_pil_image(A__ ) UpperCamelCase = render_text(A__ , **A__ ) UpperCamelCase = max(header_image.width , image.width ) UpperCamelCase = int(image.height * (new_width / image.width) ) UpperCamelCase = int(header_image.height * (new_width / header_image.width) ) UpperCamelCase = Image.new('RGB' , (new_width, new_height + new_header_height) , 'white' ) new_image.paste(header_image.resize((new_width, new_header_height) ) , (0, 0) ) new_image.paste(image.resize((new_width, new_height) ) , (0, new_header_height) ) # Convert back to the original framework if necessary UpperCamelCase = to_numpy_array(A__ ) if infer_channel_dimension_format(A__ ) == ChannelDimension.LAST: UpperCamelCase = to_channel_dimension_format(A__ , ChannelDimension.LAST ) return new_image class SCREAMING_SNAKE_CASE ( _a ): """simple docstring""" _SCREAMING_SNAKE_CASE = ["""flattened_patches"""] def __init__( self : Any , UpperCamelCase__ : bool = True , UpperCamelCase__ : bool = True , UpperCamelCase__ : Dict[str, int] = None , UpperCamelCase__ : int = 2_0_4_8 , UpperCamelCase__ : bool = False , **UpperCamelCase__ : Any , ): """simple docstring""" super().__init__(**UpperCamelCase__ ) UpperCamelCase = patch_size if patch_size is not None else {'height': 1_6, 'width': 1_6} UpperCamelCase = do_normalize UpperCamelCase = do_convert_rgb UpperCamelCase = max_patches UpperCamelCase = is_vqa def A ( self : int , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : int , UpperCamelCase__ : dict , **UpperCamelCase__ : Union[str, Any] ): """simple docstring""" requires_backends(self.extract_flattened_patches , 'torch' ) _check_torch_version() # convert to torch UpperCamelCase = to_channel_dimension_format(UpperCamelCase__ , ChannelDimension.FIRST ) UpperCamelCase = torch.from_numpy(UpperCamelCase__ ) UpperCamelCase , UpperCamelCase = patch_size['height'], patch_size['width'] UpperCamelCase , UpperCamelCase = get_image_size(UpperCamelCase__ ) # maximize scale s.t. UpperCamelCase = math.sqrt(max_patches * (patch_height / image_height) * (patch_width / image_width) ) UpperCamelCase = max(min(math.floor(scale * image_height / patch_height ) , UpperCamelCase__ ) , 1 ) UpperCamelCase = max(min(math.floor(scale * image_width / patch_width ) , UpperCamelCase__ ) , 1 ) UpperCamelCase = max(num_feasible_rows * patch_height , 1 ) UpperCamelCase = max(num_feasible_cols * patch_width , 1 ) UpperCamelCase = torch.nn.functional.interpolate( image.unsqueeze(0 ) , size=(resized_height, resized_width) , mode='bilinear' , align_corners=UpperCamelCase__ , antialias=UpperCamelCase__ , ).squeeze(0 ) # [1, rows, columns, patch_height * patch_width * image_channels] UpperCamelCase = torch_extract_patches(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) UpperCamelCase = patches.shape UpperCamelCase = patches_shape[1] UpperCamelCase = patches_shape[2] UpperCamelCase = patches_shape[3] # [rows * columns, patch_height * patch_width * image_channels] UpperCamelCase = patches.reshape([rows * columns, depth] ) # [rows * columns, 1] UpperCamelCase = torch.arange(UpperCamelCase__ ).reshape([rows, 1] ).repeat(1 , UpperCamelCase__ ).reshape([rows * columns, 1] ) UpperCamelCase = torch.arange(UpperCamelCase__ ).reshape([1, columns] ).repeat(UpperCamelCase__ , 1 ).reshape([rows * columns, 1] ) # Offset by 1 so the ids do not contain zeros, which represent padding. row_ids += 1 col_ids += 1 # Prepare additional patch features. # [rows * columns, 1] UpperCamelCase = row_ids.to(torch.floataa ) UpperCamelCase = col_ids.to(torch.floataa ) # [rows * columns, 2 + patch_height * patch_width * image_channels] UpperCamelCase = torch.cat([row_ids, col_ids, patches] , -1 ) # [max_patches, 2 + patch_height * patch_width * image_channels] UpperCamelCase = torch.nn.functional.pad(UpperCamelCase__ , [0, 0, 0, max_patches - (rows * columns)] ).float() UpperCamelCase = to_numpy_array(UpperCamelCase__ ) return result def A ( self : List[Any] , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : Tuple ): """simple docstring""" if image.dtype == np.uinta: UpperCamelCase = image.astype(np.floataa ) # take mean across the whole `image` UpperCamelCase = np.mean(UpperCamelCase__ ) UpperCamelCase = np.std(UpperCamelCase__ ) UpperCamelCase = max(UpperCamelCase__ , 1.0 / math.sqrt(np.prod(image.shape ) ) ) return normalize(UpperCamelCase__ , mean=UpperCamelCase__ , std=UpperCamelCase__ , **UpperCamelCase__ ) def A ( self : Union[str, Any] , UpperCamelCase__ : ImageInput , UpperCamelCase__ : Optional[str] = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : Optional[bool] = None , UpperCamelCase__ : Optional[int] = None , UpperCamelCase__ : Optional[Dict[str, int]] = None , UpperCamelCase__ : Optional[Union[str, TensorType]] = None , UpperCamelCase__ : ChannelDimension = ChannelDimension.FIRST , **UpperCamelCase__ : Any , ): """simple docstring""" UpperCamelCase = do_normalize if do_normalize is not None else self.do_normalize UpperCamelCase = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb UpperCamelCase = patch_size if patch_size is not None else self.patch_size UpperCamelCase = max_patches if max_patches is not None else self.max_patches UpperCamelCase = self.is_vqa if kwargs.get('data_format' , UpperCamelCase__ ) is not None: raise ValueError('data_format is not an accepted input as the outputs are ' ) UpperCamelCase = make_list_of_images(UpperCamelCase__ ) if not valid_images(UpperCamelCase__ ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) # PIL RGBA images are converted to RGB if do_convert_rgb: UpperCamelCase = [convert_to_rgb(UpperCamelCase__ ) for image in images] # All transformations expect numpy arrays. UpperCamelCase = [to_numpy_array(UpperCamelCase__ ) for image in images] if is_vqa: if header_text is None: raise ValueError('A header text must be provided for VQA models.' ) UpperCamelCase = kwargs.pop('font_bytes' , UpperCamelCase__ ) UpperCamelCase = kwargs.pop('font_path' , UpperCamelCase__ ) if isinstance(UpperCamelCase__ , UpperCamelCase__ ): UpperCamelCase = [header_text] * len(UpperCamelCase__ ) UpperCamelCase = [ render_header(UpperCamelCase__ , header_text[i] , font_bytes=UpperCamelCase__ , font_path=UpperCamelCase__ ) for i, image in enumerate(UpperCamelCase__ ) ] if do_normalize: UpperCamelCase = [self.normalize(image=UpperCamelCase__ ) for image in images] # convert to torch tensor and permute UpperCamelCase = [ self.extract_flattened_patches(image=UpperCamelCase__ , max_patches=UpperCamelCase__ , patch_size=UpperCamelCase__ ) for image in images ] # create attention mask in numpy UpperCamelCase = [(image.sum(axis=-1 ) != 0).astype(np.floataa ) for image in images] UpperCamelCase = BatchFeature( data={'flattened_patches': images, 'attention_mask': attention_masks} , tensor_type=UpperCamelCase__ ) return encoded_outputs
324
0
import os # Precomputes a list of the 100 first triangular numbers UpperCamelCase = [int(0.5 * n * (n + 1)) for n in range(1, 101)] def A ( ) -> Optional[Any]: UpperCamelCase__ :Optional[int] = os.path.dirname(os.path.realpath(lowercase__ ) ) UpperCamelCase__ :Optional[Any] = os.path.join(lowercase__ , """words.txt""" ) UpperCamelCase__ :Optional[Any] = """""" with open(lowercase__ ) as f: UpperCamelCase__ :int = f.readline() UpperCamelCase__ :Optional[int] = [word.strip("""\"""" ) for word in words.strip("""\r\n""" ).split(""",""" )] UpperCamelCase__ :Union[str, Any] = [ word for word in [sum(ord(lowercase__ ) - 64 for x in word ) for word in words] if word in TRIANGULAR_NUMBERS ] return len(lowercase__ ) if __name__ == "__main__": print(solution())
45
import io import itertools import json from dataclasses import dataclass from typing import Optional import pyarrow as pa import pyarrow.json as paj import datasets from datasets.table import table_cast from datasets.utils.file_utils import readline __lowercase = datasets.utils.logging.get_logger(__name__) @dataclass class lowerCamelCase_ ( datasets.BuilderConfig ): '''simple docstring''' a__ : Optional[datasets.Features] = None a__ : str = "utf-8" a__ : Optional[str] = None a__ : Optional[str] = None a__ : bool = True # deprecated a__ : Optional[int] = None # deprecated a__ : int = 1_0 << 2_0 # 10MB a__ : Optional[bool] = None class lowerCamelCase_ ( datasets.ArrowBasedBuilder ): '''simple docstring''' a__ : Optional[int] = JsonConfig def UpperCamelCase__ ( self) -> int: if self.config.block_size is not None: logger.warning('''The JSON loader parameter `block_size` is deprecated. Please use `chunksize` instead''') __UpperCamelCase :int = self.config.block_size if self.config.use_threads is not True: logger.warning( '''The JSON loader parameter `use_threads` is deprecated and doesn\'t have any effect anymore.''') if self.config.newlines_in_values is not None: raise ValueError('''The JSON loader parameter `newlines_in_values` is no longer supported''') return datasets.DatasetInfo(features=self.config.features) def UpperCamelCase__ ( self , __lowercase) -> Optional[Any]: if not self.config.data_files: raise ValueError(f"""At least one data file must be specified, but got data_files={self.config.data_files}""") __UpperCamelCase :Optional[Any] = dl_manager.download_and_extract(self.config.data_files) if isinstance(__lowercase , (str, list, tuple)): __UpperCamelCase :List[str] = data_files if isinstance(__lowercase , __lowercase): __UpperCamelCase :Optional[int] = [files] __UpperCamelCase :Dict = [dl_manager.iter_files(__lowercase) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'''files''': files})] __UpperCamelCase :str = [] for split_name, files in data_files.items(): if isinstance(__lowercase , __lowercase): __UpperCamelCase :str = [files] __UpperCamelCase :Tuple = [dl_manager.iter_files(__lowercase) for file in files] splits.append(datasets.SplitGenerator(name=__lowercase , gen_kwargs={'''files''': files})) return splits def UpperCamelCase__ ( self , __lowercase) -> pa.Table: if self.config.features is not None: # adding missing columns for column_name in set(self.config.features) - set(pa_table.column_names): __UpperCamelCase :int = self.config.features.arrow_schema.field(__lowercase).type __UpperCamelCase :Tuple = pa_table.append_column(__lowercase , pa.array([None] * len(__lowercase) , type=__lowercase)) # more expensive cast to support nested structures with keys in a different order # allows str <-> int/float or str to Audio for example __UpperCamelCase :List[str] = table_cast(__lowercase , self.config.features.arrow_schema) return pa_table def UpperCamelCase__ ( self , __lowercase) -> str: for file_idx, file in enumerate(itertools.chain.from_iterable(__lowercase)): # If the file is one json object and if we need to look at the list of items in one specific field if self.config.field is not None: with open(__lowercase , encoding=self.config.encoding , errors=self.config.encoding_errors) as f: __UpperCamelCase :Optional[Any] = json.load(__lowercase) # We keep only the field we are interested in __UpperCamelCase :Union[str, Any] = dataset[self.config.field] # We accept two format: a list of dicts or a dict of lists if isinstance(__lowercase , (list, tuple)): __UpperCamelCase :int = set().union(*[row.keys() for row in dataset]) __UpperCamelCase :Union[str, Any] = {col: [row.get(__lowercase) for row in dataset] for col in keys} else: __UpperCamelCase :List[Any] = dataset __UpperCamelCase :Optional[int] = pa.Table.from_pydict(__lowercase) yield file_idx, self._cast_table(__lowercase) # If the file has one json object per line else: with open(__lowercase , '''rb''') as f: __UpperCamelCase :List[str] = 0 # Use block_size equal to the chunk size divided by 32 to leverage multithreading # Set a default minimum value of 16kB if the chunk size is really small __UpperCamelCase :Optional[int] = max(self.config.chunksize // 32 , 16 << 10) __UpperCamelCase :List[str] = ( self.config.encoding_errors if self.config.encoding_errors is not None else '''strict''' ) while True: __UpperCamelCase :List[str] = f.read(self.config.chunksize) if not batch: break # Finish current line try: batch += f.readline() except (AttributeError, io.UnsupportedOperation): batch += readline(__lowercase) # PyArrow only accepts utf-8 encoded bytes if self.config.encoding != "utf-8": __UpperCamelCase :Union[str, Any] = batch.decode(self.config.encoding , errors=__lowercase).encode('''utf-8''') try: while True: try: __UpperCamelCase :Optional[int] = paj.read_json( io.BytesIO(__lowercase) , read_options=paj.ReadOptions(block_size=__lowercase)) break except (pa.ArrowInvalid, pa.ArrowNotImplementedError) as e: if ( isinstance(__lowercase , pa.ArrowInvalid) and "straddling" not in str(__lowercase) or block_size > len(__lowercase) ): raise else: # Increase the block size in case it was too small. # The block size will be reset for the next file. logger.debug( f"""Batch of {len(__lowercase)} bytes couldn't be parsed with block_size={block_size}. Retrying with block_size={block_size * 2}.""") block_size *= 2 except pa.ArrowInvalid as e: try: with open( __lowercase , encoding=self.config.encoding , errors=self.config.encoding_errors) as f: __UpperCamelCase :Tuple = json.load(__lowercase) except json.JSONDecodeError: logger.error(f"""Failed to read file '{file}' with error {type(__lowercase)}: {e}""") raise e # If possible, parse the file as a list of json objects and exit the loop if isinstance(__lowercase , __lowercase): # list is the only sequence type supported in JSON try: __UpperCamelCase :Optional[int] = set().union(*[row.keys() for row in dataset]) __UpperCamelCase :Optional[int] = {col: [row.get(__lowercase) for row in dataset] for col in keys} __UpperCamelCase :int = pa.Table.from_pydict(__lowercase) except (pa.ArrowInvalid, AttributeError) as e: logger.error(f"""Failed to read file '{file}' with error {type(__lowercase)}: {e}""") raise ValueError(f"""Not able to read records in the JSON file at {file}.""") from None yield file_idx, self._cast_table(__lowercase) break else: logger.error(f"""Failed to read file '{file}' with error {type(__lowercase)}: {e}""") raise ValueError( f"""Not able to read records in the JSON file at {file}. """ f"""You should probably indicate the field of the JSON file containing your records. """ f"""This JSON file contain the following fields: {str(list(dataset.keys()))}. """ f"""Select the correct one and provide it as `field='XXX'` to the dataset loading method. """) from None # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield (file_idx, batch_idx), self._cast_table(__lowercase) batch_idx += 1
167
0
"""simple docstring""" import math import unittest from transformers import BioGptConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptTokenizer, ) from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCamelCase__ : def __init__( self ,A ,A=13 ,A=7 ,A=True ,A=True ,A=False ,A=True ,A=99 ,A=32 ,A=5 ,A=4 ,A=37 ,A="gelu" ,A=0.1 ,A=0.1 ,A=512 ,A=16 ,A=2 ,A=0.02 ,A=3 ,A=4 ,A=None ,): UpperCAmelCase = parent UpperCAmelCase = batch_size UpperCAmelCase = seq_length UpperCAmelCase = is_training UpperCAmelCase = use_input_mask UpperCAmelCase = use_token_type_ids UpperCAmelCase = use_labels UpperCAmelCase = vocab_size UpperCAmelCase = hidden_size UpperCAmelCase = num_hidden_layers UpperCAmelCase = num_attention_heads UpperCAmelCase = intermediate_size UpperCAmelCase = hidden_act UpperCAmelCase = hidden_dropout_prob UpperCAmelCase = attention_probs_dropout_prob UpperCAmelCase = max_position_embeddings UpperCAmelCase = type_vocab_size UpperCAmelCase = type_sequence_label_size UpperCAmelCase = initializer_range UpperCAmelCase = num_labels UpperCAmelCase = num_choices UpperCAmelCase = scope def _UpperCamelCase ( self ): 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 = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _UpperCamelCase ( self ): return BioGptConfig( vocab_size=self.vocab_size ,hidden_size=self.hidden_size ,num_hidden_layers=self.num_hidden_layers ,num_attention_heads=self.num_attention_heads ,intermediate_size=self.intermediate_size ,hidden_act=self.hidden_act ,hidden_dropout_prob=self.hidden_dropout_prob ,attention_probs_dropout_prob=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,type_vocab_size=self.type_vocab_size ,is_decoder=A ,initializer_range=self.initializer_range ,) def _UpperCamelCase ( self ,A ,A ,A ,A ,A ,A ,A ): UpperCAmelCase = BioGptModel(config=A ) model.to(A ) model.eval() UpperCAmelCase = model(A ,attention_mask=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 ,A ,A ,): UpperCAmelCase = BioGptForCausalLM(config=A ) model.to(A ) model.eval() UpperCAmelCase = model(A ,attention_mask=A ,token_type_ids=A ,labels=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 ): UpperCAmelCase = BioGptModel(config=A ) model.to(A ) model.eval() # create attention mask UpperCAmelCase = torch.ones(input_ids.shape ,dtype=torch.long ,device=A ) UpperCAmelCase = self.seq_length // 2 UpperCAmelCase = 0 # first forward pass UpperCAmelCase , UpperCAmelCase = model(A ,attention_mask=A ).to_tuple() # create hypothetical next token and extent to next_input_ids UpperCAmelCase = ids_tensor((self.batch_size, 1) ,config.vocab_size ) # change a random masked slice from input_ids UpperCAmelCase = ids_tensor((1,) ,A ).item() + 1 UpperCAmelCase = ids_tensor((self.batch_size, 1) ,config.vocab_size ).squeeze(-1 ) UpperCAmelCase = random_other_next_tokens # append to next input_ids and attn_mask UpperCAmelCase = torch.cat([input_ids, next_tokens] ,dim=-1 ) UpperCAmelCase = torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1) ,dtype=torch.long ,device=A )] ,dim=1 ,) # get two different outputs UpperCAmelCase = model(A ,attention_mask=A )["""last_hidden_state"""] UpperCAmelCase = model(A ,past_key_values=A ,attention_mask=A )["""last_hidden_state"""] # select random slice UpperCAmelCase = ids_tensor((1,) ,output_from_past.shape[-1] ).item() UpperCAmelCase = output_from_no_past[:, -1, random_slice_idx].detach() UpperCAmelCase = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(A ,A ,atol=1e-3 ) ) def _UpperCamelCase ( self ,A ,A ,A ,A ,A ,*A ): UpperCAmelCase = BioGptModel(config=A ).to(A ).eval() UpperCAmelCase = torch.ones(input_ids.shape ,dtype=torch.long ,device=A ) # first forward pass UpperCAmelCase = model(A ,attention_mask=A ,use_cache=A ) UpperCAmelCase , UpperCAmelCase = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids UpperCAmelCase = ids_tensor((self.batch_size, 3) ,config.vocab_size ) UpperCAmelCase = ids_tensor((self.batch_size, 3) ,2 ) # append to next input_ids and UpperCAmelCase = torch.cat([input_ids, next_tokens] ,dim=-1 ) UpperCAmelCase = torch.cat([attention_mask, next_attn_mask] ,dim=-1 ) UpperCAmelCase = model(A ,attention_mask=A )["""last_hidden_state"""] UpperCAmelCase = model(A ,attention_mask=A ,past_key_values=A )[ """last_hidden_state""" ] # select random slice UpperCAmelCase = ids_tensor((1,) ,output_from_past.shape[-1] ).item() UpperCAmelCase = output_from_no_past[:, -3:, random_slice_idx].detach() UpperCAmelCase = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(A ,A ,atol=1e-3 ) ) def _UpperCamelCase ( self ,A ,A ,A ,A ,A ,*A ,A=False ): UpperCAmelCase = BioGptForCausalLM(A ) model.to(A ) if gradient_checkpointing: model.gradient_checkpointing_enable() UpperCAmelCase = model(A ,labels=A ) self.parent.assertEqual(result.loss.shape ,() ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) result.loss.backward() def _UpperCamelCase ( self ,A ,*A ): UpperCAmelCase = BioGptModel(A ) UpperCAmelCase = model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers ) for key in model.state_dict().keys(): if "c_proj" in key and "weight" in key: self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key] ) - model_std ) ,0.001 ) self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key] ) - 0.0 ) ,0.01 ) def _UpperCamelCase ( self ,A ,A ,A ,A ,A ,*A ): UpperCAmelCase = self.num_labels UpperCAmelCase = BioGptForTokenClassification(A ) model.to(A ) model.eval() UpperCAmelCase = model(A ,attention_mask=A ,token_type_ids=A ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.num_labels) ) def _UpperCamelCase ( self ): UpperCAmelCase = self.prepare_config_and_inputs() ( ( UpperCAmelCase ) , ( UpperCAmelCase ) , ( UpperCAmelCase ) , ( UpperCAmelCase ) , ( UpperCAmelCase ) , ( UpperCAmelCase ) , ( UpperCAmelCase ) , ) = config_and_inputs UpperCAmelCase = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class lowerCamelCase__ ( snake_case , snake_case , snake_case , unittest.TestCase ): SCREAMING_SNAKE_CASE = ( (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification) if is_torch_available() else () ) SCREAMING_SNAKE_CASE = (BioGptForCausalLM,) if is_torch_available() else () SCREAMING_SNAKE_CASE = ( { '''feature-extraction''': BioGptModel, '''text-classification''': BioGptForSequenceClassification, '''text-generation''': BioGptForCausalLM, '''token-classification''': BioGptForTokenClassification, '''zero-shot''': BioGptForSequenceClassification, } if is_torch_available() else {} ) SCREAMING_SNAKE_CASE = False def _UpperCamelCase ( self ): UpperCAmelCase = BioGptModelTester(self ) UpperCAmelCase = ConfigTester(self ,config_class=A ,hidden_size=37 ) def _UpperCamelCase ( self ): self.config_tester.run_common_tests() def _UpperCamelCase ( self ): UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A ) def _UpperCamelCase ( self ): UpperCAmelCase = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: UpperCAmelCase = type self.model_tester.create_and_check_model(*A ) def _UpperCamelCase ( self ): UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_attention_mask_past(*A ) def _UpperCamelCase ( self ): UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_forward_and_backwards(*A ,gradient_checkpointing=A ) def _UpperCamelCase ( self ): UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_past_large_inputs(*A ) def _UpperCamelCase ( self ): UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_weight_initialization(*A ) def _UpperCamelCase ( self ): UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_for_token_classification(*A ) @slow def _UpperCamelCase ( self ): UpperCAmelCase = BioGptForCausalLM.from_pretrained("""microsoft/biogpt""" ) model.to(A ) UpperCAmelCase = BioGptTokenizer.from_pretrained("""microsoft/biogpt""" ) UpperCAmelCase = """left""" # Define PAD Token = EOS Token = 50256 UpperCAmelCase = tokenizer.eos_token UpperCAmelCase = model.config.eos_token_id # use different length sentences to test batching UpperCAmelCase = [ """Hello, my dog is a little""", """Today, I""", ] UpperCAmelCase = tokenizer(A ,return_tensors="""pt""" ,padding=A ) UpperCAmelCase = inputs["""input_ids"""].to(A ) UpperCAmelCase = model.generate( input_ids=A ,attention_mask=inputs["""attention_mask"""].to(A ) ,) UpperCAmelCase = tokenizer(sentences[0] ,return_tensors="""pt""" ).input_ids.to(A ) UpperCAmelCase = model.generate(input_ids=A ) UpperCAmelCase = inputs_non_padded.shape[-1] - inputs["""attention_mask"""][-1].long().sum().cpu().item() UpperCAmelCase = tokenizer(sentences[1] ,return_tensors="""pt""" ).input_ids.to(A ) UpperCAmelCase = model.generate(input_ids=A ,max_length=model.config.max_length - num_paddings ) UpperCAmelCase = tokenizer.batch_decode(A ,skip_special_tokens=A ) UpperCAmelCase = tokenizer.decode(output_non_padded[0] ,skip_special_tokens=A ) UpperCAmelCase = tokenizer.decode(output_padded[0] ,skip_special_tokens=A ) UpperCAmelCase = [ """Hello, my dog is a little bit bigger than a little bit.""", """Today, I have a good idea of how to use the information""", ] self.assertListEqual(A ,A ) self.assertListEqual(A ,[non_padded_sentence, padded_sentence] ) @slow def _UpperCamelCase ( self ): for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase = BioGptModel.from_pretrained(A ) self.assertIsNotNone(A ) def _UpperCamelCase ( self ): UpperCAmelCase , UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() UpperCAmelCase = 3 UpperCAmelCase = input_dict["""input_ids"""] UpperCAmelCase = input_ids.ne(1 ).to(A ) UpperCAmelCase = ids_tensor([self.model_tester.batch_size] ,self.model_tester.type_sequence_label_size ) UpperCAmelCase = BioGptForSequenceClassification(A ) model.to(A ) model.eval() UpperCAmelCase = model(A ,attention_mask=A ,labels=A ) self.assertEqual(result.logits.shape ,(self.model_tester.batch_size, self.model_tester.num_labels) ) def _UpperCamelCase ( self ): UpperCAmelCase , UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() UpperCAmelCase = 3 UpperCAmelCase = """multi_label_classification""" UpperCAmelCase = input_dict["""input_ids"""] UpperCAmelCase = input_ids.ne(1 ).to(A ) UpperCAmelCase = ids_tensor( [self.model_tester.batch_size, config.num_labels] ,self.model_tester.type_sequence_label_size ).to(torch.float ) UpperCAmelCase = BioGptForSequenceClassification(A ) model.to(A ) model.eval() UpperCAmelCase = model(A ,attention_mask=A ,labels=A ) self.assertEqual(result.logits.shape ,(self.model_tester.batch_size, self.model_tester.num_labels) ) @require_torch class lowerCamelCase__ ( unittest.TestCase ): @slow def _UpperCamelCase ( self ): UpperCAmelCase = BioGptForCausalLM.from_pretrained("""microsoft/biogpt""" ) UpperCAmelCase = torch.tensor([[2, 4_805, 9, 656, 21]] ) UpperCAmelCase = model(A )[0] UpperCAmelCase = 42_384 UpperCAmelCase = torch.Size((1, 5, vocab_size) ) self.assertEqual(output.shape ,A ) UpperCAmelCase = torch.tensor( [[[-9.5236, -9.8918, 10.4557], [-11.0469, -9.6423, 8.1022], [-8.8664, -7.8826, 5.5325]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] ,A ,atol=1e-4 ) ) @slow def _UpperCamelCase ( self ): UpperCAmelCase = BioGptTokenizer.from_pretrained("""microsoft/biogpt""" ) UpperCAmelCase = BioGptForCausalLM.from_pretrained("""microsoft/biogpt""" ) model.to(A ) torch.manual_seed(0 ) UpperCAmelCase = tokenizer("""COVID-19 is""" ,return_tensors="""pt""" ).to(A ) UpperCAmelCase = model.generate( **A ,min_length=100 ,max_length=1_024 ,num_beams=5 ,early_stopping=A ,) UpperCAmelCase = tokenizer.decode(output_ids[0] ,skip_special_tokens=A ) UpperCAmelCase = ( """COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the""" """ causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and""" """ territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK),""" """ and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and""" """ more than 800,000 deaths.""" ) self.assertEqual(A ,A )
74
"""simple docstring""" from __future__ import annotations from collections.abc import Generator import requests from bsa import BeautifulSoup _UpperCamelCase = """https://www.indeed.co.in/jobs?q=mobile+app+development&l=""" def _a ( _snake_case = "mumbai" ): """simple docstring""" UpperCAmelCase = BeautifulSoup(requests.get(url + location ).content , """html.parser""" ) # This attribute finds out all the specifics listed in a job for job in soup.find_all("""div""" , attrs={"""data-tn-component""": """organicJob"""} ): UpperCAmelCase = job.find("""a""" , attrs={"""data-tn-element""": """jobTitle"""} ).text.strip() UpperCAmelCase = job.find("""span""" , {"""class""": """company"""} ).text.strip() yield job_title, company_name if __name__ == "__main__": for i, job in enumerate(fetch_jobs("""Bangalore"""), 1): print(F"""Job {i:>2} is {job[0]} at {job[1]}""")
74
1
"""simple docstring""" from __future__ import annotations def A__ ( __lowerCamelCase, __lowerCamelCase ): """simple docstring""" _lowerCAmelCase = get_failure_array(__lowerCamelCase ) # 2) Step through text searching for pattern _lowerCAmelCase = 0, 0 # index into text, pattern while i < len(__lowerCamelCase ): if pattern[j] == text[i]: if j == (len(__lowerCamelCase ) - 1): return True j += 1 # if this is a prefix in our pattern # just go back far enough to continue elif j > 0: _lowerCAmelCase = failure[j - 1] continue i += 1 return False def A__ ( __lowerCamelCase ): """simple docstring""" _lowerCAmelCase = [0] _lowerCAmelCase = 0 _lowerCAmelCase = 1 while j < len(__lowerCamelCase ): if pattern[i] == pattern[j]: i += 1 elif i > 0: _lowerCAmelCase = failure[i - 1] continue j += 1 failure.append(__lowerCamelCase ) return failure if __name__ == "__main__": # Test 1) a__ : Optional[int] = """abc1abc12""" a__ : Any = """alskfjaldsabc1abc1abc12k23adsfabcabc""" a__ : Any = """alskfjaldsk23adsfabcabc""" assert kmp(pattern, texta) and not kmp(pattern, texta) # Test 2) a__ : List[Any] = """ABABX""" a__ : Tuple = """ABABZABABYABABX""" assert kmp(pattern, text) # Test 3) a__ : List[Any] = """AAAB""" a__ : str = """ABAAAAAB""" assert kmp(pattern, text) # Test 4) a__ : List[str] = """abcdabcy""" a__ : List[str] = """abcxabcdabxabcdabcdabcy""" assert kmp(pattern, text) # Test 5) a__ : Tuple = """aabaabaaa""" assert get_failure_array(pattern) == [0, 1, 0, 1, 2, 3, 4, 5, 2]
589
'''simple docstring''' from sklearn.metrics import fa_score import datasets lowerCAmelCase_ : int = """ The F1 score is the harmonic mean of the precision and recall. It can be computed with the equation: F1 = 2 * (precision * recall) / (precision + recall) """ lowerCAmelCase_ : Optional[int] = """ Args: predictions (`list` of `int`): Predicted labels. references (`list` of `int`): Ground truth labels. labels (`list` of `int`): The set of labels to include when `average` is not set to `'binary'`, and the order of the labels if `average` is `None`. Labels present in the data can be excluded, for example to calculate a multiclass average ignoring a majority negative class. Labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in `predictions` and `references` are used in sorted order. Defaults to None. pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1. average (`string`): This parameter is required for multiclass/multilabel targets. If set to `None`, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `'binary'`. - 'binary': Only report results for the class specified by `pos_label`. This is applicable only if the classes found in `predictions` and `references` are binary. - 'micro': Calculate metrics globally by counting the total true positives, false negatives and false positives. - 'macro': Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account. - 'weighted': Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `'macro'` to account for label imbalance. This option can result in an F-score that is not between precision and recall. - 'samples': Calculate metrics for each instance, and find their average (only meaningful for multilabel classification). sample_weight (`list` of `float`): Sample weights Defaults to None. Returns: f1 (`float` or `array` of `float`): F1 score or list of f1 scores, depending on the value passed to `average`. Minimum possible value is 0. Maximum possible value is 1. Higher f1 scores are better. Examples: Example 1-A simple binary example >>> f1_metric = datasets.load_metric(\"f1\") >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0]) >>> print(results) {'f1': 0.5} Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`. >>> f1_metric = datasets.load_metric(\"f1\") >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0) >>> print(round(results['f1'], 2)) 0.67 Example 3-The same simple binary example as in Example 1, but with `sample_weight` included. >>> f1_metric = datasets.load_metric(\"f1\") >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], sample_weight=[0.9, 0.5, 3.9, 1.2, 0.3]) >>> print(round(results['f1'], 2)) 0.35 Example 4-A multiclass example, with different values for the `average` input. >>> predictions = [0, 2, 1, 0, 0, 1] >>> references = [0, 1, 2, 0, 1, 2] >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"macro\") >>> print(round(results['f1'], 2)) 0.27 >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"micro\") >>> print(round(results['f1'], 2)) 0.33 >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"weighted\") >>> print(round(results['f1'], 2)) 0.27 >>> results = f1_metric.compute(predictions=predictions, references=references, average=None) >>> print(results) {'f1': array([0.8, 0. , 0. ])} """ lowerCAmelCase_ : Any = """ @article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011} } """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class SCREAMING_SNAKE_CASE ( datasets.Metric ): '''simple docstring''' def snake_case__ ( self : str ) ->Union[str, Any]: '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Sequence(datasets.Value("int32" ) ), "references": datasets.Sequence(datasets.Value("int32" ) ), } if self.config_name == "multilabel" else { "predictions": datasets.Value("int32" ), "references": datasets.Value("int32" ), } ) , reference_urls=["https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html"] , ) def snake_case__ ( self : Optional[int] , lowercase__ : Any , lowercase__ : Tuple , lowercase__ : Optional[Any]=None , lowercase__ : List[str]=1 , lowercase__ : Optional[int]="binary" , lowercase__ : int=None ) ->int: '''simple docstring''' _UpperCamelCase : List[str] = fa_score( lowercase__ , lowercase__ , labels=lowercase__ , pos_label=lowercase__ , average=lowercase__ , sample_weight=lowercase__ ) return {"f1": float(lowercase__ ) if score.size == 1 else score}
435
0
"""simple docstring""" def lowerCamelCase_ ( __lowerCAmelCase = 100_0000 ) -> List[str]: '''simple docstring''' lowerCamelCase__ =1 lowerCamelCase__ =1 lowerCamelCase__ ={1: 1} for inputa in range(2 , _lowerCAmelCase ): lowerCamelCase__ =0 lowerCamelCase__ =inputa while True: if number in counters: counter += counters[number] break if number % 2 == 0: number //= 2 counter += 1 else: lowerCamelCase__ =(3 * number) + 1 counter += 1 if inputa not in counters: lowerCamelCase__ =counter if counter > pre_counter: lowerCamelCase__ =inputa lowerCamelCase__ =counter return largest_number if __name__ == "__main__": print(solution(int(input().strip())))
701
"""simple docstring""" from collections.abc import Sequence from queue import Queue class __UpperCAmelCase : def __init__( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase=None , _lowerCamelCase=None ): lowerCamelCase__ =start lowerCamelCase__ =end lowerCamelCase__ =val lowerCamelCase__ =(start + end) // 2 lowerCamelCase__ =left lowerCamelCase__ =right def __repr__( self ): return F'''SegmentTreeNode(start={self.start}, end={self.end}, val={self.val})''' class __UpperCAmelCase : def __init__( self , _lowerCamelCase , _lowerCamelCase ): lowerCamelCase__ =collection lowerCamelCase__ =function if self.collection: lowerCamelCase__ =self._build_tree(0 , len(_lowerCamelCase ) - 1 ) def _a ( self , _lowerCamelCase , _lowerCamelCase ): self._update_tree(self.root , _lowerCamelCase , _lowerCamelCase ) def _a ( self , _lowerCamelCase , _lowerCamelCase ): return self._query_range(self.root , _lowerCamelCase , _lowerCamelCase ) def _a ( self , _lowerCamelCase , _lowerCamelCase ): if start == end: return SegmentTreeNode(_lowerCamelCase , _lowerCamelCase , self.collection[start] ) lowerCamelCase__ =(start + end) // 2 lowerCamelCase__ =self._build_tree(_lowerCamelCase , _lowerCamelCase ) lowerCamelCase__ =self._build_tree(mid + 1 , _lowerCamelCase ) return SegmentTreeNode(_lowerCamelCase , _lowerCamelCase , self.fn(left.val , right.val ) , _lowerCamelCase , _lowerCamelCase ) def _a ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): if node.start == i and node.end == i: lowerCamelCase__ =val return if i <= node.mid: self._update_tree(node.left , _lowerCamelCase , _lowerCamelCase ) else: self._update_tree(node.right , _lowerCamelCase , _lowerCamelCase ) lowerCamelCase__ =self.fn(node.left.val , node.right.val ) def _a ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): if node.start == i and node.end == j: return node.val if i <= node.mid: if j <= node.mid: # range in left child tree return self._query_range(node.left , _lowerCamelCase , _lowerCamelCase ) else: # range in left child tree and right child tree return self.fn( self._query_range(node.left , _lowerCamelCase , node.mid ) , self._query_range(node.right , node.mid + 1 , _lowerCamelCase ) , ) else: # range in right child tree return self._query_range(node.right , _lowerCamelCase , _lowerCamelCase ) def _a ( self ): if self.root is not None: lowerCamelCase__ =Queue() queue.put(self.root ) while not queue.empty(): lowerCamelCase__ =queue.get() yield node if node.left is not None: queue.put(node.left ) if node.right is not None: queue.put(node.right ) if __name__ == "__main__": import operator for fn in [operator.add, max, min]: print('*' * 50) a =SegmentTree([2, 1, 5, 3, 4], fn) for node in arr.traverse(): print(node) print() arr.update(1, 5) for node in arr.traverse(): print(node) print() print(arr.query_range(3, 4)) # 7 print(arr.query_range(2, 2)) # 5 print(arr.query_range(1, 3)) # 13 print()
132
0
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 lowerCamelCase = '▁' lowerCamelCase = get_tests_dir('fixtures/test_sentencepiece.model') @require_sentencepiece @require_tokenizers class A ( UpperCamelCase_ , unittest.TestCase ): UpperCamelCase__ : Optional[int] =BigBirdTokenizer UpperCamelCase__ : str =BigBirdTokenizerFast UpperCamelCase__ : Tuple =True UpperCamelCase__ : Optional[Any] =True def lowerCamelCase ( self : List[Any] ) -> Tuple: """simple docstring""" super().setUp() _lowerCamelCase : str =self.tokenizer_class(__A , keep_accents=__A ) tokenizer.save_pretrained(self.tmpdirname ) def lowerCamelCase ( self : List[Any] ) -> List[Any]: """simple docstring""" _lowerCamelCase : str ='''<s>''' _lowerCamelCase : Union[str, Any] =1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__A ) , __A ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__A ) , __A ) def lowerCamelCase ( self : Union[str, Any] ) -> Any: """simple docstring""" _lowerCamelCase : str =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(__A ) , 1004 ) def lowerCamelCase ( self : Any ) -> Optional[Any]: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1000 ) def lowerCamelCase ( self : List[str] ) -> str: """simple docstring""" if not self.test_rust_tokenizer: return _lowerCamelCase : Dict =self.get_tokenizer() _lowerCamelCase : List[Any] =self.get_rust_tokenizer() _lowerCamelCase : Union[str, Any] ='''I was born in 92000, and this is falsé.''' _lowerCamelCase : List[Any] =tokenizer.tokenize(__A ) _lowerCamelCase : Optional[int] =rust_tokenizer.tokenize(__A ) self.assertListEqual(__A , __A ) _lowerCamelCase : Union[str, Any] =tokenizer.encode(__A , add_special_tokens=__A ) _lowerCamelCase : List[Any] =rust_tokenizer.encode(__A , add_special_tokens=__A ) self.assertListEqual(__A , __A ) _lowerCamelCase : Dict =self.get_rust_tokenizer() _lowerCamelCase : int =tokenizer.encode(__A ) _lowerCamelCase : Dict =rust_tokenizer.encode(__A ) self.assertListEqual(__A , __A ) def lowerCamelCase ( self : List[str] ) -> str: """simple docstring""" _lowerCamelCase : Optional[Any] =BigBirdTokenizer(__A , keep_accents=__A ) _lowerCamelCase : str =tokenizer.tokenize('This is a test' ) self.assertListEqual(__A , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__A ) , [285, 46, 10, 170, 382] , ) _lowerCamelCase : List[Any] =tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( __A , [ 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 : Dict =tokenizer.convert_tokens_to_ids(__A ) self.assertListEqual( __A , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] , ) _lowerCamelCase : Optional[Any] =tokenizer.convert_ids_to_tokens(__A ) self.assertListEqual( __A , [ 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 lowerCamelCase ( self : Optional[Any] ) -> Union[str, Any]: """simple docstring""" return BigBirdTokenizer.from_pretrained('google/bigbird-roberta-base' ) @slow def lowerCamelCase ( self : str ) -> Any: """simple docstring""" _lowerCamelCase : str ='''Hello World!''' _lowerCamelCase : Dict =[65, 1_8536, 2260, 101, 66] self.assertListEqual(__A , self.big_tokenizer.encode(__A ) ) @slow def lowerCamelCase ( self : List[str] ) -> Optional[int]: """simple docstring""" _lowerCamelCase : Union[str, Any] =( '''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 : List[Any] =[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, 3_4324, 497, 391, 408, 1_1342, 1244, 385, 100, 938, 985, 456, 574, 362, 1_2597, 3200, 3129, 1172, 66] # noqa: E231 # fmt: on self.assertListEqual(__A , self.big_tokenizer.encode(__A ) ) @require_torch @slow def lowerCamelCase ( self : str ) -> int: """simple docstring""" import torch from transformers import BigBirdConfig, BigBirdModel # Build sequence _lowerCamelCase : Optional[int] =list(self.big_tokenizer.get_vocab().keys() )[:10] _lowerCamelCase : Any =''' '''.join(__A ) _lowerCamelCase : int =self.big_tokenizer.encode_plus(__A , return_tensors='pt' , return_token_type_ids=__A ) _lowerCamelCase : Tuple =self.big_tokenizer.batch_encode_plus( [sequence + ' ' + sequence] , return_tensors='pt' , return_token_type_ids=__A ) _lowerCamelCase : Union[str, Any] =BigBirdConfig(attention_type='original_full' ) _lowerCamelCase : Tuple =BigBirdModel(__A ) assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size with torch.no_grad(): model(**__A ) model(**__A ) @slow def lowerCamelCase ( self : Optional[int] ) -> Tuple: """simple docstring""" _lowerCamelCase : Any =BigBirdTokenizer.from_pretrained('google/bigbird-roberta-base' ) _lowerCamelCase : List[Any] =tokenizer.decode(tokenizer('Paris is the [MASK].' ).input_ids ) self.assertTrue(decoded_text == '[CLS] Paris is the[MASK].[SEP]' ) @slow def lowerCamelCase ( self : Optional[int] ) -> Any: """simple docstring""" _lowerCamelCase : Optional[int] ={'''input_ids''': [[65, 3_9286, 458, 3_6335, 2001, 456, 1_3073, 1_3266, 455, 113, 7746, 1741, 1_1157, 391, 1_3073, 1_3266, 455, 113, 3967, 3_5412, 113, 4936, 109, 3870, 2377, 113, 3_0084, 4_5720, 458, 134, 1_7496, 112, 503, 1_1672, 113, 118, 112, 5665, 1_3347, 3_8687, 112, 1496, 3_1389, 112, 3268, 4_7264, 134, 962, 112, 1_6377, 8035, 2_3130, 430, 1_2169, 1_5518, 2_8592, 458, 146, 4_1697, 109, 391, 1_2169, 1_5518, 1_6689, 458, 146, 4_1358, 109, 452, 726, 4034, 111, 763, 3_5412, 5082, 388, 1903, 111, 9051, 391, 2870, 4_8918, 1900, 1123, 550, 998, 112, 9586, 1_5985, 455, 391, 410, 2_2955, 3_7636, 114, 66], [65, 448, 1_7496, 419, 3663, 385, 763, 113, 2_7533, 2870, 3283, 1_3043, 1639, 2_4713, 523, 656, 2_4013, 1_8550, 2521, 517, 2_7014, 2_1244, 420, 1212, 1465, 391, 927, 4833, 388, 578, 1_1786, 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, 2_1932, 1_8146, 726, 363, 1_7032, 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=__A , model_name='google/bigbird-roberta-base' , revision='215c99f1600e06f83acce68422f2035b2b5c3510' , )
464
from collections.abc import Sequence def SCREAMING_SNAKE_CASE_ ( UpperCAmelCase_ : Sequence[int] | None = None ) -> int: if nums is None or not nums: raise ValueError('''Input sequence should not be empty''' ) SCREAMING_SNAKE_CASE_ : Tuple =nums[0] for i in range(1 , len(UpperCAmelCase_ ) ): SCREAMING_SNAKE_CASE_ : Any =nums[i] SCREAMING_SNAKE_CASE_ : Optional[int] =max(UpperCAmelCase_ , ans + num , UpperCAmelCase_ ) return ans if __name__ == "__main__": import doctest doctest.testmod() # Try on a sample input from the user _lowercase = int(input("""Enter number of elements : """).strip()) _lowercase = list(map(int, input("""\nEnter the numbers : """).strip().split()))[:n] print(max_subsequence_sum(array))
443
0
'''simple docstring''' import numpy as np from cva import COLOR_BGR2GRAY, CV_8UC3, cvtColor, filteraD, imread, imshow, waitKey def SCREAMING_SNAKE_CASE ( lowercase_ : int , lowercase_ : int , lowercase_ : int , lowercase_ : int , lowercase_ : int , lowercase_ : int ): # prepare kernel # the kernel size have to be odd if (ksize % 2) == 0: lowercase = ksize + 1 lowercase = np.zeros((ksize, ksize) , dtype=np.floataa ) # each value for y in range(lowercase_ ): for x in range(lowercase_ ): # distance from center lowercase = x - ksize // 2 lowercase = y - ksize // 2 # degree to radiant lowercase = theta / 180 * np.pi lowercase = np.cos(_theta ) lowercase = np.sin(_theta ) # get kernel x lowercase = cos_theta * px + sin_theta * py # get kernel y lowercase = -sin_theta * px + cos_theta * py # fill kernel lowercase = np.exp( -(_x**2 + gamma**2 * _y**2) / (2 * sigma**2) ) * np.cos(2 * np.pi * _x / lambd + psi ) return gabor if __name__ == "__main__": import doctest doctest.testmod() # read original image lowercase_ : List[Any] = imread('''../image_data/lena.jpg''') # turn image in gray scale value lowercase_ : str = cvtColor(img, COLOR_BGR2GRAY) # Apply multiple Kernel to detect edges lowercase_ : Union[str, Any] = np.zeros(gray.shape[:2]) for theta in [0, 30, 60, 90, 120, 150]: lowercase_ : Dict = gabor_filter_kernel(10, 8, theta, 10, 0, 0) out += filteraD(gray, CV_8UC3, kernel_aa) lowercase_ : Tuple = out / out.max() * 255 lowercase_ : Dict = out.astype(np.uinta) imshow('''Original''', gray) imshow('''Gabor filter with 20x20 mask and 6 directions''', out) waitKey(0)
703
'''simple docstring''' import json import logging import os import socket import git import numpy as np import torch logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - PID: %(process)d - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO, ) lowercase_ : Tuple = logging.getLogger(__name__) def SCREAMING_SNAKE_CASE ( lowercase_ : str ): lowercase = git.Repo(search_parent_directories=lowercase_ ) lowercase = { """repo_id""": str(lowercase_ ), """repo_sha""": str(repo.head.object.hexsha ), """repo_branch""": str(repo.active_branch ), } with open(os.path.join(lowercase_ , """git_log.json""" ) , """w""" ) as f: json.dump(lowercase_ , lowercase_ , indent=4 ) def SCREAMING_SNAKE_CASE ( lowercase_ : str ): if params.n_gpu <= 0: lowercase = 0 lowercase = -1 lowercase = True lowercase = False return assert torch.cuda.is_available() logger.info("""Initializing GPUs""" ) if params.n_gpu > 1: assert params.local_rank != -1 lowercase = int(os.environ["""WORLD_SIZE"""] ) lowercase = int(os.environ["""N_GPU_NODE"""] ) lowercase = int(os.environ["""RANK"""] ) # number of nodes / node ID lowercase = params.world_size // params.n_gpu_per_node lowercase = params.global_rank // params.n_gpu_per_node lowercase = True assert params.n_nodes == int(os.environ["""N_NODES"""] ) assert params.node_id == int(os.environ["""NODE_RANK"""] ) # local job (single GPU) else: assert params.local_rank == -1 lowercase = 1 lowercase = 0 lowercase = 0 lowercase = 0 lowercase = 1 lowercase = 1 lowercase = False # sanity checks assert params.n_nodes >= 1 assert 0 <= params.node_id < params.n_nodes assert 0 <= params.local_rank <= params.global_rank < params.world_size assert params.world_size == params.n_nodes * params.n_gpu_per_node # define whether this is the master process / if we are in multi-node distributed mode lowercase = params.node_id == 0 and params.local_rank == 0 lowercase = params.n_nodes > 1 # summary lowercase = F"""--- Global rank: {params.global_rank} - """ logger.info(PREFIX + """Number of nodes: %i""" % params.n_nodes ) logger.info(PREFIX + """Node ID : %i""" % params.node_id ) logger.info(PREFIX + """Local rank : %i""" % params.local_rank ) logger.info(PREFIX + """World size : %i""" % params.world_size ) logger.info(PREFIX + """GPUs per node : %i""" % params.n_gpu_per_node ) logger.info(PREFIX + """Master : %s""" % str(params.is_master ) ) logger.info(PREFIX + """Multi-node : %s""" % str(params.multi_node ) ) logger.info(PREFIX + """Multi-GPU : %s""" % str(params.multi_gpu ) ) logger.info(PREFIX + """Hostname : %s""" % socket.gethostname() ) # set GPU device torch.cuda.set_device(params.local_rank ) # initialize multi-GPU if params.multi_gpu: logger.info("""Initializing PyTorch distributed""" ) torch.distributed.init_process_group( init_method="""env://""" , backend="""nccl""" , ) def SCREAMING_SNAKE_CASE ( lowercase_ : Optional[Any] ): np.random.seed(args.seed ) torch.manual_seed(args.seed ) if args.n_gpu > 0: torch.cuda.manual_seed_all(args.seed )
653
0
import doctest import glob import importlib import inspect import os import re from contextlib import contextmanager from functools import wraps from unittest.mock import patch import numpy as np import pytest from absl.testing import parameterized import datasets from datasets import load_metric from .utils import for_all_test_methods, local, slow # mark all tests as integration snake_case_ = pytest.mark.integration snake_case_ = {'''comet'''} snake_case_ = importlib.util.find_spec('''fairseq''') is not None snake_case_ = {'''code_eval'''} snake_case_ = os.name == '''nt''' snake_case_ = {'''bertscore''', '''frugalscore''', '''perplexity'''} snake_case_ = importlib.util.find_spec('''transformers''') is not None def snake_case__ ( SCREAMING_SNAKE_CASE_ : Union[str, Any] ): '''simple docstring''' @wraps(SCREAMING_SNAKE_CASE_ ) def wrapper(self : Union[str, Any] , SCREAMING_SNAKE_CASE_ : List[str] ): if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ: self.skipTest('"test requires Fairseq"' ) else: test_case(self , SCREAMING_SNAKE_CASE_ ) return wrapper def snake_case__ ( SCREAMING_SNAKE_CASE_ : List[Any] ): '''simple docstring''' @wraps(SCREAMING_SNAKE_CASE_ ) def wrapper(self : Optional[Any] , SCREAMING_SNAKE_CASE_ : Tuple ): if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS: self.skipTest('"test requires transformers"' ) else: test_case(self , SCREAMING_SNAKE_CASE_ ) return wrapper def snake_case__ ( SCREAMING_SNAKE_CASE_ : int ): '''simple docstring''' @wraps(SCREAMING_SNAKE_CASE_ ) def wrapper(self : Dict , SCREAMING_SNAKE_CASE_ : List[str] ): if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS: self.skipTest('"test not supported on Windows"' ) else: test_case(self , SCREAMING_SNAKE_CASE_ ) return wrapper def snake_case__ ( ): '''simple docstring''' lowercase__ : Optional[Any] = [metric_dir.split(os.sep )[-2] for metric_dir in glob.glob('./metrics/*/' )] return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"] # gleu is unfinished @parameterized.named_parameters(get_local_metric_names() ) @for_all_test_methods( __snake_case , __snake_case , __snake_case ) @local class SCREAMING_SNAKE_CASE__ (parameterized.TestCase ): __lowerCamelCase : List[str] = {} __lowerCamelCase : Tuple = None @pytest.mark.filterwarnings('ignore:metric_module_factory is deprecated:FutureWarning') @pytest.mark.filterwarnings('ignore:load_metric is deprecated:FutureWarning') def snake_case_ ( self , a): lowercase__ : str = '[...]' lowercase__ : List[str] = importlib.import_module( datasets.load.metric_module_factory(os.path.join('metrics' , a)).module_path) lowercase__ : Dict = datasets.load.import_main_class(metric_module.__name__ , dataset=a) # check parameters lowercase__ : Union[str, Any] = inspect.signature(metric._compute).parameters self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values())) # no **kwargs # run doctest with self.patch_intensive_calls(a , metric_module.__name__): with self.use_local_metrics(): try: lowercase__ : str = doctest.testmod(a , verbose=a , raise_on_error=a) except doctest.UnexpectedException as e: raise e.exc_info[1] # raise the exception that doctest caught self.assertEqual(results.failed , 0) self.assertGreater(results.attempted , 1) @slow def snake_case_ ( self , a): lowercase__ : List[Any] = '[...]' lowercase__ : Optional[int] = importlib.import_module( datasets.load.metric_module_factory(os.path.join('metrics' , a)).module_path) # run doctest with self.use_local_metrics(): lowercase__ : Union[str, Any] = doctest.testmod(a , verbose=a , raise_on_error=a) self.assertEqual(results.failed , 0) self.assertGreater(results.attempted , 1) @contextmanager def snake_case_ ( self , a , a): if metric_name in self.INTENSIVE_CALLS_PATCHER: with self.INTENSIVE_CALLS_PATCHER[metric_name](a): yield else: yield @contextmanager def snake_case_ ( self): def load_local_metric(a , *a , **a): return load_metric(os.path.join('metrics' , a) , *a , **a) with patch('datasets.load_metric') as mock_load_metric: lowercase__ : Tuple = load_local_metric yield @classmethod def snake_case_ ( cls , a): def wrapper(a): lowercase__ : Optional[int] = contextmanager(a) lowercase__ : Tuple = patcher return patcher return wrapper @LocalMetricTest.register_intensive_calls_patcher('bleurt' ) def snake_case__ ( SCREAMING_SNAKE_CASE_ : Tuple ): '''simple docstring''' import tensorflow.compat.va as tf from bleurt.score import Predictor tf.flags.DEFINE_string('sv' , '' , '' ) # handle pytest cli flags class SCREAMING_SNAKE_CASE__ (__snake_case ): def snake_case_ ( self , a): assert len(input_dict['input_ids']) == 2 return np.array([1.03, 1.04]) # mock predict_fn which is supposed to do a forward pass with a bleurt model with patch('bleurt.score._create_predictor' ) as mock_create_predictor: lowercase__ : Optional[Any] = MockedPredictor() yield @LocalMetricTest.register_intensive_calls_patcher('bertscore' ) def snake_case__ ( SCREAMING_SNAKE_CASE_ : Optional[Any] ): '''simple docstring''' import torch def bert_cos_score_idf(SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Optional[int] , *SCREAMING_SNAKE_CASE_ : List[str] , **SCREAMING_SNAKE_CASE_ : List[Any] ): return torch.tensor([[1.0, 1.0, 1.0]] * len(SCREAMING_SNAKE_CASE_ ) ) # mock get_model which is supposed to do download a bert model # mock bert_cos_score_idf which is supposed to do a forward pass with a bert model with patch('bert_score.scorer.get_model' ), patch( 'bert_score.scorer.bert_cos_score_idf' ) as mock_bert_cos_score_idf: lowercase__ : Any = bert_cos_score_idf yield @LocalMetricTest.register_intensive_calls_patcher('comet' ) def snake_case__ ( SCREAMING_SNAKE_CASE_ : str ): '''simple docstring''' def load_from_checkpoint(SCREAMING_SNAKE_CASE_ : Any ): class SCREAMING_SNAKE_CASE__ : def snake_case_ ( self , a , *a , **a): assert len(a) == 2 lowercase__ : Any = [0.19, 0.92] return scores, sum(a) / len(a) return Model() # mock load_from_checkpoint which is supposed to do download a bert model # mock load_from_checkpoint which is supposed to do download a bert model with patch('comet.download_model' ) as mock_download_model: lowercase__ : Union[str, Any] = None with patch('comet.load_from_checkpoint' ) as mock_load_from_checkpoint: lowercase__ : int = load_from_checkpoint yield def snake_case__ ( ): '''simple docstring''' lowercase__ : Optional[Any] = load_metric(os.path.join('metrics' , 'seqeval' ) ) lowercase__ : List[str] = 'ERROR' lowercase__ : Optional[Any] = f"""Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}""" with pytest.raises(SCREAMING_SNAKE_CASE_ , match=re.escape(SCREAMING_SNAKE_CASE_ ) ): metric.compute(predictions=[] , references=[] , scheme=SCREAMING_SNAKE_CASE_ )
164
def snake_case__ ( SCREAMING_SNAKE_CASE_ : int ): '''simple docstring''' lowercase__ : int = (1 + 24 * n) ** 0.5 return ((1 + root) / 6) % 1 == 0 def snake_case__ ( SCREAMING_SNAKE_CASE_ : int = 5_000 ): '''simple docstring''' lowercase__ : int = [(i * (3 * i - 1)) // 2 for i in range(1 , SCREAMING_SNAKE_CASE_ )] for i, pentagonal_i in enumerate(SCREAMING_SNAKE_CASE_ ): for j in range(SCREAMING_SNAKE_CASE_ , len(SCREAMING_SNAKE_CASE_ ) ): lowercase__ : Tuple = pentagonal_nums[j] lowercase__ : Union[str, Any] = pentagonal_i + pentagonal_j lowercase__ : int = pentagonal_j - pentagonal_i if is_pentagonal(SCREAMING_SNAKE_CASE_ ) and is_pentagonal(SCREAMING_SNAKE_CASE_ ): return b return -1 if __name__ == "__main__": print(F'''{solution() = }''')
164
1
import os from glob import glob import imageio import torch import torchvision import wandb from img_processing import custom_to_pil, loop_post_process, preprocess, preprocess_vqgan from loaders import load_vqgan from PIL import Image from torch import nn from transformers import CLIPModel, CLIPTokenizerFast from utils import get_device, get_timestamp, show_pil class UpperCamelCase : '''simple docstring''' def __init__( self , A_ = "cpu" , A_ = "openai/clip-vit-large-patch14" ) -> None: """simple docstring""" _lowerCamelCase = device _lowerCamelCase = CLIPTokenizerFast.from_pretrained(A_ ) _lowerCamelCase = [0.48145466, 0.4578275, 0.40821073] _lowerCamelCase = [0.26862954, 0.26130258, 0.27577711] _lowerCamelCase = torchvision.transforms.Normalize(self.image_mean , self.image_std ) _lowerCamelCase = torchvision.transforms.Resize(2_24 ) _lowerCamelCase = torchvision.transforms.CenterCrop(2_24 ) def UpperCamelCase_ ( self , A_ ) -> int: """simple docstring""" _lowerCamelCase = self.resize(A_ ) _lowerCamelCase = self.center_crop(A_ ) _lowerCamelCase = self.normalize(A_ ) return images def __call__( self , A_=None , A_=None , **A_ ) -> Optional[Any]: """simple docstring""" _lowerCamelCase = self.tokenizer(text=A_ , **A_ ) _lowerCamelCase = self.preprocess_img(A_ ) _lowerCamelCase = {key: value.to(self.device ) for (key, value) in encoding.items()} return encoding class UpperCamelCase ( nn.Module ): '''simple docstring''' def __init__( self , A_=10 , A_=0.01 , A_=None , A_=None , A_=None , A_=None , A_=None , A_=None , A_=False , A_=True , A_="image" , A_=True , A_=False , A_=False , A_=False , ) -> None: """simple docstring""" super().__init__() _lowerCamelCase = None _lowerCamelCase = device if device else get_device() if vqgan: _lowerCamelCase = vqgan else: _lowerCamelCase = load_vqgan(self.device , conf_path=A_ , ckpt_path=A_ ) self.vqgan.eval() if clip: _lowerCamelCase = clip else: _lowerCamelCase = CLIPModel.from_pretrained('''openai/clip-vit-base-patch32''' ) self.clip.to(self.device ) _lowerCamelCase = ProcessorGradientFlow(device=self.device ) _lowerCamelCase = iterations _lowerCamelCase = lr _lowerCamelCase = log _lowerCamelCase = make_grid _lowerCamelCase = return_val _lowerCamelCase = quantize _lowerCamelCase = self.vqgan.decoder.z_shape def UpperCamelCase_ ( self , A_=None , A_=None , A_=5 , A_=True ) -> Any: """simple docstring""" _lowerCamelCase = [] if output_path is None: _lowerCamelCase = '''./animation.gif''' if input_path is None: _lowerCamelCase = self.save_path _lowerCamelCase = sorted(glob(input_path + '''/*''' ) ) if not len(A_ ): raise ValueError( '''No images found in save path, aborting (did you pass save_intermediate=True to the generate''' ''' function?)''' ) if len(A_ ) == 1: print('''Only one image found in save path, (did you pass save_intermediate=True to the generate function?)''' ) _lowerCamelCase = total_duration / len(A_ ) _lowerCamelCase = [frame_duration] * len(A_ ) if extend_frames: _lowerCamelCase = 1.5 _lowerCamelCase = 3 for file_name in paths: if file_name.endswith('''.png''' ): images.append(imageio.imread(A_ ) ) imageio.mimsave(A_ , A_ , duration=A_ ) print(F'gif saved to {output_path}' ) def UpperCamelCase_ ( self , A_=None , A_=None ) -> Union[str, Any]: """simple docstring""" if not (path or img): raise ValueError('''Input either path or tensor''' ) if img is not None: raise NotImplementedError _lowerCamelCase = preprocess(Image.open(A_ ) , target_image_size=2_56 ).to(self.device ) _lowerCamelCase = preprocess_vqgan(A_ ) _lowerCamelCase , *_lowerCamelCase = self.vqgan.encode(A_ ) return z def UpperCamelCase_ ( self , A_ ) -> Optional[int]: """simple docstring""" _lowerCamelCase = self.latent.detach().requires_grad_() _lowerCamelCase = base_latent + transform_vector if self.quantize: _lowerCamelCase , *_lowerCamelCase = self.vqgan.quantize(A_ ) else: _lowerCamelCase = trans_latent return self.vqgan.decode(A_ ) def UpperCamelCase_ ( self , A_ , A_ , A_=None ) -> Any: """simple docstring""" _lowerCamelCase = self.clip_preprocessor(text=A_ , images=A_ , return_tensors='''pt''' , padding=A_ ) _lowerCamelCase = self.clip(**A_ ) _lowerCamelCase = clip_outputs.logits_per_image if weights is not None: _lowerCamelCase = similarity_logits * weights return similarity_logits.sum() def UpperCamelCase_ ( self , A_ , A_ , A_ ) -> Dict: """simple docstring""" _lowerCamelCase = self._get_clip_similarity(pos_prompts['''prompts'''] , A_ , weights=(1 / pos_prompts['''weights''']) ) if neg_prompts: _lowerCamelCase = self._get_clip_similarity(neg_prompts['''prompts'''] , A_ , weights=neg_prompts['''weights'''] ) else: _lowerCamelCase = torch.tensor([1] , device=self.device ) _lowerCamelCase = -torch.log(A_ ) + torch.log(A_ ) return loss def UpperCamelCase_ ( self , A_ , A_ , A_ ) -> str: """simple docstring""" _lowerCamelCase = torch.randn_like(self.latent , requires_grad=A_ , device=self.device ) _lowerCamelCase = torch.optim.Adam([vector] , lr=self.lr ) for i in range(self.iterations ): optim.zero_grad() _lowerCamelCase = self._add_vector(A_ ) _lowerCamelCase = loop_post_process(A_ ) _lowerCamelCase = self._get_CLIP_loss(A_ , A_ , A_ ) print('''CLIP loss''' , A_ ) if self.log: wandb.log({'''CLIP Loss''': clip_loss} ) clip_loss.backward(retain_graph=A_ ) optim.step() if self.return_val == "image": yield custom_to_pil(transformed_img[0] ) else: yield vector def UpperCamelCase_ ( self , A_ , A_ , A_ ) -> Any: """simple docstring""" wandb.init(reinit=A_ , project='''face-editor''' ) wandb.config.update({'''Positive Prompts''': positive_prompts} ) wandb.config.update({'''Negative Prompts''': negative_prompts} ) wandb.config.update({'''lr''': self.lr, '''iterations''': self.iterations} ) if image_path: _lowerCamelCase = Image.open(A_ ) _lowerCamelCase = image.resize((2_56, 2_56) ) wandb.log('''Original Image''' , wandb.Image(A_ ) ) def UpperCamelCase_ ( self , A_ ) -> int: """simple docstring""" if not prompts: return [] _lowerCamelCase = [] _lowerCamelCase = [] if isinstance(A_ , A_ ): _lowerCamelCase = [prompt.strip() for prompt in prompts.split('''|''' )] for prompt in prompts: if isinstance(A_ , (tuple, list) ): _lowerCamelCase = prompt[0] _lowerCamelCase = float(prompt[1] ) elif ":" in prompt: _lowerCamelCase , _lowerCamelCase = prompt.split(''':''' ) _lowerCamelCase = float(A_ ) else: _lowerCamelCase = prompt _lowerCamelCase = 1.0 processed_prompts.append(A_ ) weights.append(A_ ) return { "prompts": processed_prompts, "weights": torch.tensor(A_ , device=self.device ), } def UpperCamelCase_ ( self , A_ , A_=None , A_=None , A_=True , A_=False , A_=True , A_=True , A_=None , ) -> str: """simple docstring""" if image_path: _lowerCamelCase = self._get_latent(A_ ) else: _lowerCamelCase = torch.randn(self.latent_dim , device=self.device ) if self.log: self._init_logging(A_ , A_ , A_ ) assert pos_prompts, "You must provide at least one positive prompt." _lowerCamelCase = self.process_prompts(A_ ) _lowerCamelCase = self.process_prompts(A_ ) if save_final and save_path is None: _lowerCamelCase = os.path.join('''./outputs/''' , '''_'''.join(pos_prompts['''prompts'''] ) ) if not os.path.exists(A_ ): os.makedirs(A_ ) else: _lowerCamelCase = save_path + '''_''' + get_timestamp() os.makedirs(A_ ) _lowerCamelCase = save_path _lowerCamelCase = self.vqgan.decode(self.latent )[0] if show_intermediate: print('''Original Image''' ) show_pil(custom_to_pil(A_ ) ) _lowerCamelCase = loop_post_process(A_ ) for iter, transformed_img in enumerate(self._optimize_CLIP(A_ , A_ , A_ ) ): if show_intermediate: show_pil(A_ ) if save_intermediate: transformed_img.save(os.path.join(self.save_path , F'iter_{iter:03d}.png' ) ) if self.log: wandb.log({'''Image''': wandb.Image(A_ )} ) if show_final: show_pil(A_ ) if save_final: transformed_img.save(os.path.join(self.save_path , F'iter_{iter:03d}_final.png' ) )
714
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) snake_case__ = { 'configuration_whisper': ['WHISPER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'WhisperConfig', 'WhisperOnnxConfig'], 'feature_extraction_whisper': ['WhisperFeatureExtractor'], 'processing_whisper': ['WhisperProcessor'], 'tokenization_whisper': ['WhisperTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case__ = ['WhisperTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case__ = [ 'WHISPER_PRETRAINED_MODEL_ARCHIVE_LIST', 'WhisperForConditionalGeneration', 'WhisperModel', 'WhisperPreTrainedModel', 'WhisperForAudioClassification', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case__ = [ 'TF_WHISPER_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFWhisperForConditionalGeneration', 'TFWhisperModel', 'TFWhisperPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case__ = [ 'FlaxWhisperForConditionalGeneration', 'FlaxWhisperModel', 'FlaxWhisperPreTrainedModel', 'FlaxWhisperForAudioClassification', ] if TYPE_CHECKING: from .configuration_whisper import WHISPER_PRETRAINED_CONFIG_ARCHIVE_MAP, WhisperConfig, WhisperOnnxConfig from .feature_extraction_whisper import WhisperFeatureExtractor from .processing_whisper import WhisperProcessor from .tokenization_whisper import WhisperTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_whisper_fast import WhisperTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_whisper import ( WHISPER_PRETRAINED_MODEL_ARCHIVE_LIST, WhisperForAudioClassification, WhisperForConditionalGeneration, WhisperModel, WhisperPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_whisper import ( TF_WHISPER_PRETRAINED_MODEL_ARCHIVE_LIST, TFWhisperForConditionalGeneration, TFWhisperModel, TFWhisperPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_whisper import ( FlaxWhisperForAudioClassification, FlaxWhisperForConditionalGeneration, FlaxWhisperModel, FlaxWhisperPreTrainedModel, ) else: import sys snake_case__ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
638
0
import os import sys import tempfile import torch from .state import AcceleratorState from .utils import PrecisionType, PrepareForLaunch, is_mps_available, patch_environment def UpperCamelCase_ ( __a , __a=() , __a=None , __a="no" , __a="29500" ) -> Any: a__ : Union[str, Any] = False a__ : List[str] = False if any(key.startswith("KAGGLE" ) for key in os.environ.keys() ): a__ : Optional[int] = True elif "IPython" in sys.modules: a__ : Union[str, Any] = '''google.colab''' in str(sys.modules["IPython"].get_ipython() ) try: a__ : int = PrecisionType(mixed_precision.lower() ) except ValueError: raise ValueError( f'''Unknown mixed_precision mode: {args.mixed_precision.lower()}. Choose between {PrecisionType.list()}.''' ) if (in_colab or in_kaggle) and (os.environ.get("TPU_NAME" , __A ) is not None): # TPU launch import torch_xla.distributed.xla_multiprocessing as xmp if len(AcceleratorState._shared_state ) > 0: raise ValueError( "To train on TPU in Colab or Kaggle Kernel, the `Accelerator` should only be initialized inside " "your training function. Restart your notebook and make sure no cells initializes an " "`Accelerator`." ) if num_processes is None: a__ : List[Any] = 8 a__ : List[Any] = PrepareForLaunch(__A , distributed_type="TPU" ) print(f'''Launching a training on {num_processes} TPU cores.''' ) xmp.spawn(__A , args=__A , nprocs=__A , start_method="fork" ) elif in_colab: # No need for a distributed launch otherwise as it's either CPU or one GPU. if torch.cuda.is_available(): print("Launching training on one GPU." ) else: print("Launching training on one CPU." ) function(*__A ) else: if num_processes is None: raise ValueError( "You have to specify the number of GPUs you would like to use, add `num_processes=...` to your call." ) if num_processes > 1: # Multi-GPU launch from torch.multiprocessing import start_processes from torch.multiprocessing.spawn import ProcessRaisedException if len(AcceleratorState._shared_state ) > 0: raise ValueError( "To launch a multi-GPU training from your notebook, the `Accelerator` should only be initialized " "inside your training function. Restart your notebook and make sure no cells initializes an " "`Accelerator`." ) if torch.cuda.is_initialized(): raise ValueError( "To launch a multi-GPU training from your notebook, you need to avoid running any instruction " "using `torch.cuda` in any cell. Restart your notebook and make sure no cells use any CUDA " "function." ) # torch.distributed will expect a few environment variable to be here. We set the ones common to each # process here (the other ones will be set be the launcher). with patch_environment( world_size=__A , master_addr="127.0.01" , master_port=__A , mixed_precision=__A ): a__ : str = PrepareForLaunch(__A , distributed_type="MULTI_GPU" ) print(f'''Launching training on {num_processes} GPUs.''' ) try: start_processes(__A , args=__A , nprocs=__A , start_method="fork" ) except ProcessRaisedException as e: if "Cannot re-initialize CUDA in forked subprocess" in e.args[0]: raise RuntimeError( "CUDA has been initialized before the `notebook_launcher` could create a forked subprocess. " "This likely stems from an outside import causing issues once the `notebook_launcher()` is called. " "Please review your imports and test them when running the `notebook_launcher()` to identify " "which one is problematic." ) from e else: # No need for a distributed launch otherwise as it's either CPU, GPU or MPS. if is_mps_available(): a__ : Dict = '''1''' print("Launching training on MPS." ) elif torch.cuda.is_available(): print("Launching training on one GPU." ) else: print("Launching training on CPU." ) function(*__A ) def UpperCamelCase_ ( __a , __a=() , __a=2 ) -> Any: from torch.multiprocessing import start_processes with tempfile.NamedTemporaryFile() as tmp_file: # torch.distributed will expect a few environment variable to be here. We set the ones common to each # process here (the other ones will be set be the launcher). with patch_environment( world_size=__A , master_addr="127.0.01" , master_port="29500" , accelerate_mixed_precision="no" , accelerate_debug_rdv_file=tmp_file.name , accelerate_use_cpu="yes" , ): a__ : List[str] = PrepareForLaunch(__A , debug=__A ) start_processes(__A , args=__A , nprocs=__A , start_method="fork" )
37
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging SCREAMING_SNAKE_CASE = logging.get_logger(__name__) SCREAMING_SNAKE_CASE = { 'junnyu/roformer_chinese_small': 'https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/config.json', 'junnyu/roformer_chinese_base': 'https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/config.json', 'junnyu/roformer_chinese_char_small': ( 'https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/config.json' ), 'junnyu/roformer_chinese_char_base': ( 'https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/config.json' ), 'junnyu/roformer_small_discriminator': ( 'https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/config.json' ), 'junnyu/roformer_small_generator': ( 'https://huggingface.co/junnyu/roformer_small_generator/resolve/main/config.json' ), # See all RoFormer models at https://huggingface.co/models?filter=roformer } class A_ ( __lowercase ): '''simple docstring''' _SCREAMING_SNAKE_CASE : List[Any] = "roformer" def __init__( self , _A=50000 , _A=None , _A=768 , _A=12 , _A=12 , _A=3072 , _A="gelu" , _A=0.1 , _A=0.1 , _A=1536 , _A=2 , _A=0.02 , _A=1e-12 , _A=0 , _A=False , _A=True , **_A , ) -> Optional[Any]: """simple docstring""" super().__init__(pad_token_id=_A , **_A) _UpperCAmelCase : Tuple = vocab_size _UpperCAmelCase : Any = hidden_size if embedding_size is None else embedding_size _UpperCAmelCase : Any = hidden_size _UpperCAmelCase : int = num_hidden_layers _UpperCAmelCase : Dict = num_attention_heads _UpperCAmelCase : int = hidden_act _UpperCAmelCase : Optional[Any] = intermediate_size _UpperCAmelCase : str = hidden_dropout_prob _UpperCAmelCase : List[Any] = attention_probs_dropout_prob _UpperCAmelCase : Tuple = max_position_embeddings _UpperCAmelCase : List[Any] = type_vocab_size _UpperCAmelCase : Any = initializer_range _UpperCAmelCase : Any = layer_norm_eps _UpperCAmelCase : Optional[Any] = rotary_value _UpperCAmelCase : int = use_cache class A_ ( __lowercase ): '''simple docstring''' @property def snake_case__ ( self) -> Mapping[str, Mapping[int, str]]: """simple docstring""" if self.task == "multiple-choice": _UpperCAmelCase : Optional[int] = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: _UpperCAmelCase : Optional[Any] = {0: '''batch''', 1: '''sequence'''} _UpperCAmelCase : Dict = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ('''token_type_ids''', dynamic_axis), ])
485
0
'''simple docstring''' from __future__ import annotations SCREAMING_SNAKE_CASE : Dict = [-10, -5, 0, 5, 5.1, 11, 13, 21, 3, 4, -21, -10, -5, -1, 0] SCREAMING_SNAKE_CASE : Any = [-5, 0, 5, 5.1, 11, 13, 21, -1, 4, -1, -10, -5, -1, 0, -1] def _UpperCamelCase ( lowerCAmelCase__: list[float] ) -> list[float]: SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = len(lowerCAmelCase__ ) for i in range(lowerCAmelCase__ ): SCREAMING_SNAKE_CASE_ = -1 for j in range(i + 1 ,lowerCAmelCase__ ): if arr[i] < arr[j]: SCREAMING_SNAKE_CASE_ = arr[j] break result.append(lowerCAmelCase__ ) return result def _UpperCamelCase ( lowerCAmelCase__: list[float] ) -> list[float]: SCREAMING_SNAKE_CASE_ = [] for i, outer in enumerate(lowerCAmelCase__ ): SCREAMING_SNAKE_CASE_ = -1 for inner in arr[i + 1 :]: if outer < inner: SCREAMING_SNAKE_CASE_ = inner break result.append(lowerCAmelCase__ ) return result def _UpperCamelCase ( lowerCAmelCase__: list[float] ) -> list[float]: SCREAMING_SNAKE_CASE_ = len(lowerCAmelCase__ ) SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = [-1] * arr_size for index in reversed(range(lowerCAmelCase__ ) ): if stack: while stack[-1] <= arr[index]: stack.pop() if not stack: break if stack: SCREAMING_SNAKE_CASE_ = stack[-1] stack.append(arr[index] ) return result if __name__ == "__main__": from doctest import testmod from timeit import timeit testmod() print(next_greatest_element_slow(arr)) print(next_greatest_element_fast(arr)) print(next_greatest_element(arr)) SCREAMING_SNAKE_CASE : Any = ( "from __main__ import arr, next_greatest_element_slow, " "next_greatest_element_fast, next_greatest_element" ) print( "next_greatest_element_slow():", timeit("next_greatest_element_slow(arr)", setup=setup), ) print( "next_greatest_element_fast():", timeit("next_greatest_element_fast(arr)", setup=setup), ) print( " next_greatest_element():", timeit("next_greatest_element(arr)", setup=setup), )
238
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging SCREAMING_SNAKE_CASE : Tuple = logging.get_logger(__name__) SCREAMING_SNAKE_CASE : Optional[int] = { "facebook/xmod-base": "https://huggingface.co/facebook/xmod-base/resolve/main/config.json", "facebook/xmod-large-prenorm": "https://huggingface.co/facebook/xmod-large-prenorm/resolve/main/config.json", "facebook/xmod-base-13-125k": "https://huggingface.co/facebook/xmod-base-13-125k/resolve/main/config.json", "facebook/xmod-base-30-125k": "https://huggingface.co/facebook/xmod-base-30-125k/resolve/main/config.json", "facebook/xmod-base-30-195k": "https://huggingface.co/facebook/xmod-base-30-195k/resolve/main/config.json", "facebook/xmod-base-60-125k": "https://huggingface.co/facebook/xmod-base-60-125k/resolve/main/config.json", "facebook/xmod-base-60-265k": "https://huggingface.co/facebook/xmod-base-60-265k/resolve/main/config.json", "facebook/xmod-base-75-125k": "https://huggingface.co/facebook/xmod-base-75-125k/resolve/main/config.json", "facebook/xmod-base-75-269k": "https://huggingface.co/facebook/xmod-base-75-269k/resolve/main/config.json", } class snake_case ( lowercase_ ): """simple docstring""" _a = """xmod""" def __init__( self, _lowercase=30522, _lowercase=768, _lowercase=12, _lowercase=12, _lowercase=3072, _lowercase="gelu", _lowercase=0.1, _lowercase=0.1, _lowercase=512, _lowercase=2, _lowercase=0.02, _lowercase=1E-12, _lowercase=1, _lowercase=0, _lowercase=2, _lowercase="absolute", _lowercase=True, _lowercase=None, _lowercase=False, _lowercase=2, _lowercase=False, _lowercase=True, _lowercase=True, _lowercase=("en_XX",), _lowercase=None, **_lowercase, ) -> Optional[Any]: super().__init__(pad_token_id=_lowercase, bos_token_id=_lowercase, eos_token_id=_lowercase, **_lowercase ) SCREAMING_SNAKE_CASE_ = vocab_size SCREAMING_SNAKE_CASE_ = hidden_size SCREAMING_SNAKE_CASE_ = num_hidden_layers SCREAMING_SNAKE_CASE_ = num_attention_heads SCREAMING_SNAKE_CASE_ = hidden_act SCREAMING_SNAKE_CASE_ = intermediate_size SCREAMING_SNAKE_CASE_ = hidden_dropout_prob SCREAMING_SNAKE_CASE_ = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ = max_position_embeddings SCREAMING_SNAKE_CASE_ = type_vocab_size SCREAMING_SNAKE_CASE_ = initializer_range SCREAMING_SNAKE_CASE_ = layer_norm_eps SCREAMING_SNAKE_CASE_ = position_embedding_type SCREAMING_SNAKE_CASE_ = use_cache SCREAMING_SNAKE_CASE_ = classifier_dropout SCREAMING_SNAKE_CASE_ = pre_norm SCREAMING_SNAKE_CASE_ = adapter_reduction_factor SCREAMING_SNAKE_CASE_ = adapter_layer_norm SCREAMING_SNAKE_CASE_ = adapter_reuse_layer_norm SCREAMING_SNAKE_CASE_ = ln_before_adapter SCREAMING_SNAKE_CASE_ = list(_lowercase ) SCREAMING_SNAKE_CASE_ = default_language class snake_case ( lowercase_ ): """simple docstring""" @property def a__ ( self ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": SCREAMING_SNAKE_CASE_ = {0: 'batch', 1: 'choice', 2: 'sequence'} else: SCREAMING_SNAKE_CASE_ = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
238
1
'''simple docstring''' def lowercase__( _UpperCamelCase : list )-> list: """simple docstring""" if len(__lowercase ) < 2: return collection def circle_sort_util(_UpperCamelCase : list , _UpperCamelCase : int , _UpperCamelCase : int ) -> bool: _UpperCamelCase = False if low == high: return swapped _UpperCamelCase = low _UpperCamelCase = high while left < right: if collection[left] > collection[right]: _UpperCamelCase = ( collection[right], collection[left], ) _UpperCamelCase = True left += 1 right -= 1 if left == right and collection[left] > collection[right + 1]: _UpperCamelCase = ( collection[right + 1], collection[left], ) _UpperCamelCase = True _UpperCamelCase = low + int((high - low) / 2 ) _UpperCamelCase = circle_sort_util(__lowercase , __lowercase , __lowercase ) _UpperCamelCase = circle_sort_util(__lowercase , mid + 1 , __lowercase ) return swapped or left_swap or right_swap _UpperCamelCase = True while is_not_sorted is True: _UpperCamelCase = circle_sort_util(__lowercase , 0 , len(__lowercase ) - 1 ) return collection if __name__ == "__main__": snake_case_ : Any = input('''Enter numbers separated by a comma:\n''').strip() snake_case_ : List[str] = [int(item) for item in user_input.split(''',''')] print(circle_sort(unsorted))
138
def a__ (__lowercase :str , __lowercase :str ) -> float: def get_matched_characters(__lowercase :str , __lowercase :str ) -> str: _A : Union[str, Any] = [] _A : Dict = min(len(_stra ) , len(_stra ) ) // 2 for i, l in enumerate(_stra ): _A : Tuple = int(max(0 , i - limit ) ) _A : Union[str, Any] = int(min(i + limit + 1 , len(_stra ) ) ) if l in _stra[left:right]: matched.append(__lowercase ) _A : List[Any] = f"""{_stra[0:_stra.index(__lowercase )]} {_stra[_stra.index(__lowercase ) + 1:]}""" return "".join(__lowercase ) # matching characters _A : str = get_matched_characters(__lowercase , __lowercase ) _A : Optional[Any] = get_matched_characters(__lowercase , __lowercase ) _A : Any = len(__lowercase ) # transposition _A : str = ( len([(ca, ca) for ca, ca in zip(__lowercase , __lowercase ) if ca != ca] ) // 2 ) if not match_count: _A : Optional[int] = 0.0 else: _A : str = ( 1 / 3 * ( match_count / len(__lowercase ) + match_count / len(__lowercase ) + (match_count - transpositions) / match_count ) ) # common prefix up to 4 characters _A : Any = 0 for ca, ca in zip(stra[:4] , stra[:4] ): if ca == ca: prefix_len += 1 else: break return jaro + 0.1 * prefix_len * (1 - jaro) if __name__ == "__main__": import doctest doctest.testmod() print(jaro_winkler('hello', 'world'))
206
0
from __future__ import annotations def a_ ( lowerCAmelCase_ : dict, lowerCAmelCase_ : str ): __lowerCAmelCase , __lowerCAmelCase = set(lowerCAmelCase_ ), [start] while stack: __lowerCAmelCase = stack.pop() explored.add(lowerCAmelCase_ ) # Differences from BFS: # 1) pop last element instead of first one # 2) add adjacent elements to stack without exploring them for adj in reversed(graph[v] ): if adj not in explored: stack.append(lowerCAmelCase_ ) return explored _snake_case : Union[str, Any] = { 'A': ['B', 'C', 'D'], 'B': ['A', 'D', 'E'], 'C': ['A', 'F'], 'D': ['B', 'D'], 'E': ['B', 'F'], 'F': ['C', 'E', 'G'], 'G': ['F'], } if __name__ == "__main__": import doctest doctest.testmod() print(depth_first_search(G, 'A'))
711
from __future__ import annotations def a_ ( lowerCAmelCase_ : int | str ): __lowerCAmelCase = str(lowerCAmelCase_ ) return n == n[::-1] def a_ ( lowerCAmelCase_ : int = 100_0000 ): __lowerCAmelCase = 0 for i in range(1, lowerCAmelCase_ ): if is_palindrome(lowerCAmelCase_ ) and is_palindrome(bin(lowerCAmelCase_ ).split('b' )[1] ): total += i return total if __name__ == "__main__": print(solution(int(str(input().strip()))))
421
0
from typing import List import datasets from datasets.tasks import AudioClassification from ..folder_based_builder import folder_based_builder UpperCAmelCase__ : List[str] = datasets.utils.logging.get_logger(__name__) class UpperCamelCase_ ( folder_based_builder.FolderBasedBuilderConfig ): '''simple docstring''' UpperCamelCase_ = None UpperCamelCase_ = None class UpperCamelCase_ ( folder_based_builder.FolderBasedBuilder ): '''simple docstring''' UpperCamelCase_ = datasets.Audio() UpperCamelCase_ = """audio""" UpperCamelCase_ = AudioFolderConfig UpperCamelCase_ = 42 # definition at the bottom of the script UpperCamelCase_ = AudioClassification(audio_column="""audio""" , label_column="""label""" ) UpperCAmelCase__ : List[Any] = [ '''.aiff''', '''.au''', '''.avr''', '''.caf''', '''.flac''', '''.htk''', '''.svx''', '''.mat4''', '''.mat5''', '''.mpc2k''', '''.ogg''', '''.paf''', '''.pvf''', '''.raw''', '''.rf64''', '''.sd2''', '''.sds''', '''.ircam''', '''.voc''', '''.w64''', '''.wav''', '''.nist''', '''.wavex''', '''.wve''', '''.xi''', '''.mp3''', '''.opus''', ] UpperCAmelCase__ : List[Any] = AUDIO_EXTENSIONS
410
import math def _lowercase ( __SCREAMING_SNAKE_CASE ) -> list[int]: UpperCamelCase__ : Tuple = [] UpperCamelCase__ : int = 2 UpperCamelCase__ : str = int(math.sqrt(__SCREAMING_SNAKE_CASE ) ) # Size of every segment UpperCamelCase__ : Optional[int] = [True] * (end + 1) UpperCamelCase__ : Dict = [] while start <= end: if temp[start] is True: in_prime.append(__SCREAMING_SNAKE_CASE ) for i in range(start * start , end + 1 , __SCREAMING_SNAKE_CASE ): UpperCamelCase__ : List[Any] = False start += 1 prime += in_prime UpperCamelCase__ : Union[str, Any] = end + 1 UpperCamelCase__ : Optional[Any] = min(2 * end , __SCREAMING_SNAKE_CASE ) while low <= n: UpperCamelCase__ : Dict = [True] * (high - low + 1) for each in in_prime: UpperCamelCase__ : Any = math.floor(low / each ) * each if t < low: t += each for j in range(__SCREAMING_SNAKE_CASE , high + 1 , __SCREAMING_SNAKE_CASE ): UpperCamelCase__ : Optional[int] = False for j in range(len(__SCREAMING_SNAKE_CASE ) ): if temp[j] is True: prime.append(j + low ) UpperCamelCase__ : Optional[int] = high + 1 UpperCamelCase__ : List[Any] = min(high + end , __SCREAMING_SNAKE_CASE ) return prime print(sieve(10**6))
410
1
'''simple docstring''' import unittest import numpy as np from transformers import is_flax_available from transformers.testing_utils import require_flax from ..test_modeling_flax_common import ids_tensor if is_flax_available(): import jax import jax.numpy as jnp from transformers.generation import ( FlaxForcedBOSTokenLogitsProcessor, FlaxForcedEOSTokenLogitsProcessor, FlaxLogitsProcessorList, FlaxMinLengthLogitsProcessor, FlaxTemperatureLogitsWarper, FlaxTopKLogitsWarper, FlaxTopPLogitsWarper, ) @require_flax class lowerCAmelCase_( unittest.TestCase ): '''simple docstring''' def UpperCAmelCase_ ( self ,__UpperCAmelCase ,__UpperCAmelCase ) -> Any: lowerCAmelCase__ : Union[str, Any] = jnp.ones((batch_size, length) ) / length return scores def UpperCAmelCase_ ( self ) -> Tuple: lowerCAmelCase__ : Union[str, Any] = None lowerCAmelCase__ : List[str] = 20 lowerCAmelCase__ : List[Any] = self._get_uniform_logits(batch_size=2 ,length=lowerCAmelCase_ ) # tweak scores to not be uniform anymore lowerCAmelCase__ : Any = scores.at[1, 5].set((1 / length) + 0.1 ) # peak, 1st batch lowerCAmelCase__ : Optional[Any] = scores.at[1, 10].set((1 / length) - 0.4 ) # valley, 1st batch # compute softmax lowerCAmelCase__ : int = jax.nn.softmax(lowerCAmelCase_ ,axis=-1 ) lowerCAmelCase__ : Optional[Any] = FlaxTemperatureLogitsWarper(temperature=0.5 ) lowerCAmelCase__ : Union[str, Any] = FlaxTemperatureLogitsWarper(temperature=1.3 ) lowerCAmelCase__ : Dict = jax.nn.softmax(temp_dist_warper_sharper(lowerCAmelCase_ ,scores.copy() ,cur_len=lowerCAmelCase_ ) ,axis=-1 ) lowerCAmelCase__ : List[Any] = jax.nn.softmax(temp_dist_warper_smoother(lowerCAmelCase_ ,scores.copy() ,cur_len=lowerCAmelCase_ ) ,axis=-1 ) # uniform distribution stays uniform self.assertTrue(jnp.allclose(probs[0, :] ,warped_prob_sharp[0, :] ,atol=1E-3 ) ) self.assertTrue(jnp.allclose(probs[0, :] ,warped_prob_smooth[0, :] ,atol=1E-3 ) ) # sharp peaks get higher, valleys get lower self.assertLess(probs[1, :].max() ,warped_prob_sharp[1, :].max() ) self.assertGreater(probs[1, :].min() ,warped_prob_sharp[1, :].min() ) # smooth peaks get lower, valleys get higher self.assertGreater(probs[1, :].max() ,warped_prob_smooth[1, :].max() ) self.assertLess(probs[1, :].min() ,warped_prob_smooth[1, :].min() ) def UpperCAmelCase_ ( self ) -> str: lowerCAmelCase__ : int = None lowerCAmelCase__ : Tuple = 10 lowerCAmelCase__ : Union[str, Any] = 2 # create ramp distribution lowerCAmelCase__ : Dict = np.broadcast_to(np.arange(lowerCAmelCase_ )[None, :] ,(batch_size, vocab_size) ).copy() lowerCAmelCase__ : List[str] = ramp_logits[1:, : vocab_size // 2] + vocab_size lowerCAmelCase__ : str = FlaxTopKLogitsWarper(3 ) lowerCAmelCase__ : Dict = top_k_warp(lowerCAmelCase_ ,lowerCAmelCase_ ,cur_len=lowerCAmelCase_ ) # check that correct tokens are filtered self.assertListEqual(jnp.isinf(scores[0] ).tolist() ,7 * [True] + 3 * [False] ) self.assertListEqual(jnp.isinf(scores[1] ).tolist() ,2 * [True] + 3 * [False] + 5 * [True] ) # check special case lowerCAmelCase__ : int = 5 lowerCAmelCase__ : Tuple = FlaxTopKLogitsWarper(top_k=1 ,filter_value=0.0 ,min_tokens_to_keep=3 ) lowerCAmelCase__ : Any = np.broadcast_to(np.arange(lowerCAmelCase_ )[None, :] ,(batch_size, length) ).copy() lowerCAmelCase__ : Any = top_k_warp_safety_check(lowerCAmelCase_ ,lowerCAmelCase_ ,cur_len=lowerCAmelCase_ ) # min_tokens overwrites k: 3 tokens are kept => 2 tokens are nullified self.assertListEqual((scores == 0.0).sum(axis=-1 ).tolist() ,[2, 2] ) def UpperCAmelCase_ ( self ) -> int: lowerCAmelCase__ : List[Any] = None lowerCAmelCase__ : str = 10 lowerCAmelCase__ : Dict = 2 # create distribution and take log (inverse to Softmax as taken in TopPLogitsWarper) lowerCAmelCase__ : List[Any] = np.log(np.array([[0.3, 0.1, 0.1, 0.5], [0.1_5, 0.3, 0.3, 0.2_5]] ) ) lowerCAmelCase__ : List[str] = FlaxTopPLogitsWarper(0.8 ) lowerCAmelCase__ : Union[str, Any] = np.exp(top_p_warp(lowerCAmelCase_ ,lowerCAmelCase_ ,cur_len=lowerCAmelCase_ ) ) # dist should be filtered to keep min num values so that sum is >= top_p # exp (-inf) => 0 lowerCAmelCase__ : Union[str, Any] = np.array([[0.3, 0.0, 0.0, 0.5], [0.0, 0.3, 0.3, 0.2_5]] ) self.assertTrue(np.allclose(lowerCAmelCase_ ,lowerCAmelCase_ ,atol=1E-3 ) ) # check edge cases with negative and extreme logits lowerCAmelCase__ : Optional[int] = np.broadcast_to(np.arange(lowerCAmelCase_ )[None, :] ,(batch_size, vocab_size) ).copy() - ( vocab_size // 2 ) # make ramp_logits more extreme lowerCAmelCase__ : List[Any] = ramp_logits[1] * 1_0_0.0 # make sure at least 2 tokens are kept lowerCAmelCase__ : List[str] = FlaxTopPLogitsWarper(0.9 ,min_tokens_to_keep=2 ,filter_value=0.0 ) lowerCAmelCase__ : str = top_p_warp(lowerCAmelCase_ ,lowerCAmelCase_ ,cur_len=lowerCAmelCase_ ) # first batch should keep three tokens, second batch would keep only 1, but due to `min_tokens_to_keep=2` keeps 2. self.assertListEqual((filtered_dist != 0.0).sum(axis=-1 ).tolist() ,[3, 2] ) def UpperCAmelCase_ ( self ) -> Optional[int]: lowerCAmelCase__ : Optional[Any] = 20 lowerCAmelCase__ : Union[str, Any] = 4 lowerCAmelCase__ : List[Any] = 0 lowerCAmelCase__ : int = FlaxMinLengthLogitsProcessor(min_length=10 ,eos_token_id=lowerCAmelCase_ ) # check that min length is applied at length 5 lowerCAmelCase__ : Union[str, Any] = ids_tensor((batch_size, 20) ,vocab_size=20 ) lowerCAmelCase__ : Any = 5 lowerCAmelCase__ : int = self._get_uniform_logits(lowerCAmelCase_ ,lowerCAmelCase_ ) lowerCAmelCase__ : Optional[int] = min_dist_processor(lowerCAmelCase_ ,lowerCAmelCase_ ,cur_len=lowerCAmelCase_ ) self.assertListEqual(scores_before_min_length[:, eos_token_id].tolist() ,4 * [-float("""inf""" )] ) # check that min length is not applied anymore at length 15 lowerCAmelCase__ : Dict = self._get_uniform_logits(lowerCAmelCase_ ,lowerCAmelCase_ ) lowerCAmelCase__ : Any = 15 lowerCAmelCase__ : int = min_dist_processor(lowerCAmelCase_ ,lowerCAmelCase_ ,cur_len=lowerCAmelCase_ ) self.assertFalse(jnp.isinf(lowerCAmelCase_ ).any() ) def UpperCAmelCase_ ( self ) -> List[str]: lowerCAmelCase__ : Any = 20 lowerCAmelCase__ : List[Any] = 4 lowerCAmelCase__ : Dict = 0 lowerCAmelCase__ : Dict = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=lowerCAmelCase_ ) # check that all scores are -inf except the bos_token_id score lowerCAmelCase__ : List[Any] = ids_tensor((batch_size, 1) ,vocab_size=20 ) lowerCAmelCase__ : Dict = 1 lowerCAmelCase__ : str = self._get_uniform_logits(lowerCAmelCase_ ,lowerCAmelCase_ ) lowerCAmelCase__ : List[str] = logits_processor(lowerCAmelCase_ ,lowerCAmelCase_ ,cur_len=lowerCAmelCase_ ) self.assertTrue(jnp.isneginf(scores[:, bos_token_id + 1 :] ).all() ) self.assertListEqual(scores[:, bos_token_id].tolist() ,4 * [0] ) # score for bos_token_id shold be zero # check that bos_token_id is not forced if current length is greater than 1 lowerCAmelCase__ : List[Any] = 3 lowerCAmelCase__ : List[str] = self._get_uniform_logits(lowerCAmelCase_ ,lowerCAmelCase_ ) lowerCAmelCase__ : Optional[Any] = logits_processor(lowerCAmelCase_ ,lowerCAmelCase_ ,cur_len=lowerCAmelCase_ ) self.assertFalse(jnp.isinf(lowerCAmelCase_ ).any() ) def UpperCAmelCase_ ( self ) -> str: lowerCAmelCase__ : str = 20 lowerCAmelCase__ : str = 4 lowerCAmelCase__ : Union[str, Any] = 0 lowerCAmelCase__ : Dict = 5 lowerCAmelCase__ : int = FlaxForcedEOSTokenLogitsProcessor(max_length=lowerCAmelCase_ ,eos_token_id=lowerCAmelCase_ ) # check that all scores are -inf except the eos_token_id when max_length is reached lowerCAmelCase__ : Any = ids_tensor((batch_size, 4) ,vocab_size=20 ) lowerCAmelCase__ : Optional[Any] = 4 lowerCAmelCase__ : Any = self._get_uniform_logits(lowerCAmelCase_ ,lowerCAmelCase_ ) lowerCAmelCase__ : Tuple = logits_processor(lowerCAmelCase_ ,lowerCAmelCase_ ,cur_len=lowerCAmelCase_ ) self.assertTrue(jnp.isneginf(scores[:, eos_token_id + 1 :] ).all() ) self.assertListEqual(scores[:, eos_token_id].tolist() ,4 * [0] ) # score for eos_token_id should be zero # check that eos_token_id is not forced if max_length is not reached lowerCAmelCase__ : Dict = 3 lowerCAmelCase__ : Tuple = self._get_uniform_logits(lowerCAmelCase_ ,lowerCAmelCase_ ) lowerCAmelCase__ : Any = logits_processor(lowerCAmelCase_ ,lowerCAmelCase_ ,cur_len=lowerCAmelCase_ ) self.assertFalse(jnp.isinf(lowerCAmelCase_ ).any() ) def UpperCAmelCase_ ( self ) -> Tuple: lowerCAmelCase__ : Tuple = 4 lowerCAmelCase__ : Any = 10 lowerCAmelCase__ : Tuple = 15 lowerCAmelCase__ : List[str] = 2 lowerCAmelCase__ : Any = 1 lowerCAmelCase__ : int = 15 # dummy input_ids and scores lowerCAmelCase__ : Tuple = ids_tensor((batch_size, sequence_length) ,lowerCAmelCase_ ) lowerCAmelCase__ : Optional[int] = input_ids.copy() lowerCAmelCase__ : Dict = self._get_uniform_logits(lowerCAmelCase_ ,lowerCAmelCase_ ) lowerCAmelCase__ : Tuple = scores.copy() # instantiate all dist processors lowerCAmelCase__ : Optional[int] = FlaxTemperatureLogitsWarper(temperature=0.5 ) lowerCAmelCase__ : Optional[int] = FlaxTopKLogitsWarper(3 ) lowerCAmelCase__ : List[str] = FlaxTopPLogitsWarper(0.8 ) # instantiate all logits processors lowerCAmelCase__ : Any = FlaxMinLengthLogitsProcessor(min_length=10 ,eos_token_id=lowerCAmelCase_ ) lowerCAmelCase__ : List[str] = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=lowerCAmelCase_ ) lowerCAmelCase__ : Dict = FlaxForcedEOSTokenLogitsProcessor(max_length=lowerCAmelCase_ ,eos_token_id=lowerCAmelCase_ ) lowerCAmelCase__ : Tuple = 10 # no processor list lowerCAmelCase__ : List[Any] = temp_dist_warp(lowerCAmelCase_ ,lowerCAmelCase_ ,cur_len=lowerCAmelCase_ ) lowerCAmelCase__ : List[Any] = top_k_warp(lowerCAmelCase_ ,lowerCAmelCase_ ,cur_len=lowerCAmelCase_ ) lowerCAmelCase__ : Any = top_p_warp(lowerCAmelCase_ ,lowerCAmelCase_ ,cur_len=lowerCAmelCase_ ) lowerCAmelCase__ : int = min_dist_proc(lowerCAmelCase_ ,lowerCAmelCase_ ,cur_len=lowerCAmelCase_ ) lowerCAmelCase__ : Optional[Any] = bos_dist_proc(lowerCAmelCase_ ,lowerCAmelCase_ ,cur_len=lowerCAmelCase_ ) lowerCAmelCase__ : Tuple = eos_dist_proc(lowerCAmelCase_ ,lowerCAmelCase_ ,cur_len=lowerCAmelCase_ ) # with processor list lowerCAmelCase__ : Any = FlaxLogitsProcessorList( [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc] ) lowerCAmelCase__ : Dict = processor(lowerCAmelCase_ ,lowerCAmelCase_ ,cur_len=lowerCAmelCase_ ) # scores should be equal self.assertTrue(jnp.allclose(lowerCAmelCase_ ,lowerCAmelCase_ ,atol=1E-3 ) ) # input_ids should never be changed self.assertListEqual(input_ids.tolist() ,input_ids_comp.tolist() ) def UpperCAmelCase_ ( self ) -> List[Any]: lowerCAmelCase__ : Optional[Any] = 4 lowerCAmelCase__ : Optional[int] = 10 lowerCAmelCase__ : Any = 15 lowerCAmelCase__ : Optional[Any] = 2 lowerCAmelCase__ : Union[str, Any] = 1 lowerCAmelCase__ : List[Any] = 15 # dummy input_ids and scores lowerCAmelCase__ : Any = ids_tensor((batch_size, sequence_length) ,lowerCAmelCase_ ) lowerCAmelCase__ : List[str] = input_ids.copy() lowerCAmelCase__ : List[Any] = self._get_uniform_logits(lowerCAmelCase_ ,lowerCAmelCase_ ) lowerCAmelCase__ : Union[str, Any] = scores.copy() # instantiate all dist processors lowerCAmelCase__ : Any = FlaxTemperatureLogitsWarper(temperature=0.5 ) lowerCAmelCase__ : Any = FlaxTopKLogitsWarper(3 ) lowerCAmelCase__ : Optional[int] = FlaxTopPLogitsWarper(0.8 ) # instantiate all logits processors lowerCAmelCase__ : Dict = FlaxMinLengthLogitsProcessor(min_length=10 ,eos_token_id=lowerCAmelCase_ ) lowerCAmelCase__ : Dict = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=lowerCAmelCase_ ) lowerCAmelCase__ : Optional[int] = FlaxForcedEOSTokenLogitsProcessor(max_length=lowerCAmelCase_ ,eos_token_id=lowerCAmelCase_ ) lowerCAmelCase__ : Optional[int] = 10 # no processor list def run_no_processor_list(__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ): lowerCAmelCase__ : List[str] = temp_dist_warp(lowerCAmelCase_ ,lowerCAmelCase_ ,cur_len=lowerCAmelCase_ ) lowerCAmelCase__ : Union[str, Any] = top_k_warp(lowerCAmelCase_ ,lowerCAmelCase_ ,cur_len=lowerCAmelCase_ ) lowerCAmelCase__ : str = top_p_warp(lowerCAmelCase_ ,lowerCAmelCase_ ,cur_len=lowerCAmelCase_ ) lowerCAmelCase__ : str = min_dist_proc(lowerCAmelCase_ ,lowerCAmelCase_ ,cur_len=lowerCAmelCase_ ) lowerCAmelCase__ : Optional[Any] = bos_dist_proc(lowerCAmelCase_ ,lowerCAmelCase_ ,cur_len=lowerCAmelCase_ ) lowerCAmelCase__ : List[Any] = eos_dist_proc(lowerCAmelCase_ ,lowerCAmelCase_ ,cur_len=lowerCAmelCase_ ) return scores # with processor list def run_processor_list(__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ): lowerCAmelCase__ : Any = FlaxLogitsProcessorList( [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc] ) lowerCAmelCase__ : Union[str, Any] = processor(lowerCAmelCase_ ,lowerCAmelCase_ ,cur_len=lowerCAmelCase_ ) return scores lowerCAmelCase__ : Dict = jax.jit(lowerCAmelCase_ ) lowerCAmelCase__ : int = jax.jit(lowerCAmelCase_ ) lowerCAmelCase__ : str = jitted_run_no_processor_list(lowerCAmelCase_ ,lowerCAmelCase_ ,lowerCAmelCase_ ) lowerCAmelCase__ : str = jitted_run_processor_list(lowerCAmelCase_ ,lowerCAmelCase_ ,lowerCAmelCase_ ) # scores should be equal self.assertTrue(jnp.allclose(lowerCAmelCase_ ,lowerCAmelCase_ ,atol=1E-3 ) ) # input_ids should never be changed self.assertListEqual(input_ids.tolist() ,input_ids_comp.tolist() )
712
'''simple docstring''' import unittest import numpy as np import torch from diffusers import PNDMPipeline, PNDMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class lowerCAmelCase_( unittest.TestCase ): '''simple docstring''' @property def UpperCAmelCase_ ( self ) -> List[str]: torch.manual_seed(0 ) lowerCAmelCase__ : Any = UNetaDModel( block_out_channels=(32, 64) ,layers_per_block=2 ,sample_size=32 ,in_channels=3 ,out_channels=3 ,down_block_types=("""DownBlock2D""", """AttnDownBlock2D""") ,up_block_types=("""AttnUpBlock2D""", """UpBlock2D""") ,) return model def UpperCAmelCase_ ( self ) -> Any: lowerCAmelCase__ : List[str] = self.dummy_uncond_unet lowerCAmelCase__ : Optional[Any] = PNDMScheduler() lowerCAmelCase__ : List[Any] = PNDMPipeline(unet=__UpperCAmelCase ,scheduler=__UpperCAmelCase ) pndm.to(__UpperCAmelCase ) pndm.set_progress_bar_config(disable=__UpperCAmelCase ) lowerCAmelCase__ : Optional[int] = torch.manual_seed(0 ) lowerCAmelCase__ : int = pndm(generator=__UpperCAmelCase ,num_inference_steps=20 ,output_type="""numpy""" ).images lowerCAmelCase__ : List[str] = torch.manual_seed(0 ) lowerCAmelCase__ : Any = pndm(generator=__UpperCAmelCase ,num_inference_steps=20 ,output_type="""numpy""" ,return_dict=__UpperCAmelCase )[0] lowerCAmelCase__ : Dict = image[0, -3:, -3:, -1] lowerCAmelCase__ : Union[str, Any] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) lowerCAmelCase__ : Union[str, Any] = np.array([1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch class lowerCAmelCase_( unittest.TestCase ): '''simple docstring''' def UpperCAmelCase_ ( self ) -> str: lowerCAmelCase__ : Any = """google/ddpm-cifar10-32""" lowerCAmelCase__ : str = UNetaDModel.from_pretrained(__UpperCAmelCase ) lowerCAmelCase__ : Tuple = PNDMScheduler() lowerCAmelCase__ : Dict = PNDMPipeline(unet=__UpperCAmelCase ,scheduler=__UpperCAmelCase ) pndm.to(__UpperCAmelCase ) pndm.set_progress_bar_config(disable=__UpperCAmelCase ) lowerCAmelCase__ : Optional[Any] = torch.manual_seed(0 ) lowerCAmelCase__ : int = pndm(generator=__UpperCAmelCase ,output_type="""numpy""" ).images lowerCAmelCase__ : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) lowerCAmelCase__ : Optional[int] = np.array([0.1_5_6_4, 0.1_4_6_4_5, 0.1_4_0_6, 0.1_4_7_1_5, 0.1_2_4_2_5, 0.1_4_0_4_5, 0.1_3_1_1_5, 0.1_2_1_7_5, 0.1_2_5] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
160
0
import glob import os import random from string import ascii_lowercase, digits import cva import numpy as np # Parrameters __lowerCamelCase : int = (7_20, 12_80) # Height, Width __lowerCamelCase : Optional[Any] = (0.4, 0.6) # if height or width lower than this scale, drop it. __lowerCamelCase : Optional[Any] = 1 / 1_00 __lowerCamelCase : Any = """""" __lowerCamelCase : Dict = """""" __lowerCamelCase : str = """""" __lowerCamelCase : Optional[int] = 2_50 def A__ ( ): '''simple docstring''' snake_case__ , snake_case__ : List[Any] =get_dataset(_a , _a ) for index in range(_a ): snake_case__ : Tuple =random.sample(range(len(_a ) ) , 4 ) snake_case__ , snake_case__ , snake_case__ : Any =update_image_and_anno( _a , _a , _a , _a , _a , filter_scale=_a , ) # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' snake_case__ : int =random_chars(32 ) snake_case__ : List[str] =path.split(os.sep )[-1].rsplit(""".""" , 1 )[0] snake_case__ : List[Any] =f"{OUTPUT_DIR}/{file_name}_MOSAIC_{letter_code}" cva.imwrite(f"{file_root}.jpg" , _a , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(f"Succeeded {index+1}/{NUMBER_IMAGES} with {file_name}" ) snake_case__ : int =[] for anno in new_annos: snake_case__ : Any =anno[3] - anno[1] snake_case__ : Optional[int] =anno[4] - anno[2] snake_case__ : int =anno[1] + width / 2 snake_case__ : Tuple =anno[2] + height / 2 snake_case__ : List[Any] =f"{anno[0]} {x_center} {y_center} {width} {height}" annos_list.append(_a ) with open(f"{file_root}.txt" , """w""" ) as outfile: outfile.write("""\n""".join(line for line in annos_list ) ) def A__ ( _a : str , _a : str ): '''simple docstring''' snake_case__ : Tuple =[] snake_case__ : Dict =[] for label_file in glob.glob(os.path.join(_a , """*.txt""" ) ): snake_case__ : Optional[int] =label_file.split(os.sep )[-1].rsplit(""".""" , 1 )[0] with open(_a ) as in_file: snake_case__ : int =in_file.readlines() snake_case__ : Optional[int] =os.path.join(_a , f"{label_name}.jpg" ) snake_case__ : List[str] =[] for obj_list in obj_lists: snake_case__ : int =obj_list.rstrip("""\n""" ).split(""" """ ) snake_case__ : Any =float(obj[1] ) - float(obj[3] ) / 2 snake_case__ : int =float(obj[2] ) - float(obj[4] ) / 2 snake_case__ : Dict =float(obj[1] ) + float(obj[3] ) / 2 snake_case__ : Union[str, Any] =float(obj[2] ) + float(obj[4] ) / 2 boxes.append([int(obj[0] ), xmin, ymin, xmax, ymax] ) if not boxes: continue img_paths.append(_a ) labels.append(_a ) return img_paths, labels def A__ ( _a : list , _a : list , _a : list[int] , _a : tuple[int, int] , _a : tuple[float, float] , _a : float = 0.0 , ): '''simple docstring''' snake_case__ : Optional[int] =np.zeros([output_size[0], output_size[1], 3] , dtype=np.uinta ) snake_case__ : List[Any] =scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) snake_case__ : Optional[int] =scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) snake_case__ : str =int(scale_x * output_size[1] ) snake_case__ : Tuple =int(scale_y * output_size[0] ) snake_case__ : Optional[int] =[] snake_case__ : List[str] =[] for i, index in enumerate(_a ): snake_case__ : Union[str, Any] =all_img_list[index] path_list.append(_a ) snake_case__ : int =all_annos[index] snake_case__ : Tuple =cva.imread(_a ) if i == 0: # top-left snake_case__ : Tuple =cva.resize(_a , (divid_point_x, divid_point_y) ) snake_case__ : int =img for bbox in img_annos: snake_case__ : Dict =bbox[1] * scale_x snake_case__ : str =bbox[2] * scale_y snake_case__ : Tuple =bbox[3] * scale_x snake_case__ : List[Any] =bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 1: # top-right snake_case__ : Optional[Any] =cva.resize(_a , (output_size[1] - divid_point_x, divid_point_y) ) snake_case__ : str =img for bbox in img_annos: snake_case__ : Any =scale_x + bbox[1] * (1 - scale_x) snake_case__ : Dict =bbox[2] * scale_y snake_case__ : List[Any] =scale_x + bbox[3] * (1 - scale_x) snake_case__ : Optional[int] =bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 2: # bottom-left snake_case__ : List[Any] =cva.resize(_a , (divid_point_x, output_size[0] - divid_point_y) ) snake_case__ : Optional[Any] =img for bbox in img_annos: snake_case__ : int =bbox[1] * scale_x snake_case__ : Optional[Any] =scale_y + bbox[2] * (1 - scale_y) snake_case__ : Tuple =bbox[3] * scale_x snake_case__ : Dict =scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) else: # bottom-right snake_case__ : str =cva.resize( _a , (output_size[1] - divid_point_x, output_size[0] - divid_point_y) ) snake_case__ : Optional[int] =img for bbox in img_annos: snake_case__ : List[Any] =scale_x + bbox[1] * (1 - scale_x) snake_case__ : List[Any] =scale_y + bbox[2] * (1 - scale_y) snake_case__ : Optional[int] =scale_x + bbox[3] * (1 - scale_x) snake_case__ : List[str] =scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) # Remove bounding box small than scale of filter if filter_scale > 0: snake_case__ : Optional[Any] =[ anno for anno in new_anno if filter_scale < (anno[3] - anno[1]) and filter_scale < (anno[4] - anno[2]) ] return output_img, new_anno, path_list[0] def A__ ( _a : int ): '''simple docstring''' assert number_char > 1, "The number of character should greater than 1" snake_case__ : Union[str, Any] =ascii_lowercase + digits return "".join(random.choice(_a ) for _ in range(_a ) ) if __name__ == "__main__": main() print("""DONE ✅""")
385
from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import numpy as np import tensorflow as tf from transformers import TFCamembertModel @require_tf @require_sentencepiece @require_tokenizers class _lowercase ( unittest.TestCase ): @slow def lowercase__ ( self ): snake_case__ : Union[str, Any] =TFCamembertModel.from_pretrained("""jplu/tf-camembert-base""" ) snake_case__ : List[str] =tf.convert_to_tensor( [[5, 1_2_1, 1_1, 6_6_0, 1_6, 7_3_0, 2_5_5_4_3, 1_1_0, 8_3, 6]] , dtype=tf.intaa , ) # J'aime le camembert !" snake_case__ : Dict =model(a )["""last_hidden_state"""] snake_case__ : Any =tf.TensorShape((1, 1_0, 7_6_8) ) self.assertEqual(output.shape , a ) # compare the actual values for a slice. snake_case__ : str =tf.convert_to_tensor( [[[-0.0254, 0.0235, 0.1027], [0.0606, -0.1811, -0.0418], [-0.1561, -0.1127, 0.2687]]] , dtype=tf.floataa , ) # camembert = torch.hub.load('pytorch/fairseq', 'camembert.v0') # camembert.eval() # expected_slice = roberta.model.forward(input_ids)[0][:, :3, :3].detach() self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1e-4 ) )
385
1
"""simple docstring""" from math import sqrt def A__ ( UpperCamelCase ): if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(sqrt(lowerCAmelCase_ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def A__ ( UpperCamelCase = 10_001 ): A = 0 A = 1 while count != nth and number < 3: number += 1 if is_prime(lowerCAmelCase_ ): count += 1 while count != nth: number += 2 if is_prime(lowerCAmelCase_ ): count += 1 return number if __name__ == "__main__": print(F"""{solution() = }""")
707
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _snake_case : Dict = {'configuration_mbart': ['MBART_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MBartConfig', 'MBartOnnxConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case : Any = ['MBartTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case : Dict = ['MBartTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case : str = [ 'MBART_PRETRAINED_MODEL_ARCHIVE_LIST', 'MBartForCausalLM', 'MBartForConditionalGeneration', 'MBartForQuestionAnswering', 'MBartForSequenceClassification', 'MBartModel', 'MBartPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case : List[Any] = [ 'TFMBartForConditionalGeneration', 'TFMBartModel', 'TFMBartPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case : str = [ 'FlaxMBartForConditionalGeneration', 'FlaxMBartForQuestionAnswering', 'FlaxMBartForSequenceClassification', 'FlaxMBartModel', 'FlaxMBartPreTrainedModel', ] if TYPE_CHECKING: from .configuration_mbart import MBART_PRETRAINED_CONFIG_ARCHIVE_MAP, MBartConfig, MBartOnnxConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart import MBartTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart_fast import MBartTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mbart import ( MBART_PRETRAINED_MODEL_ARCHIVE_LIST, MBartForCausalLM, MBartForConditionalGeneration, MBartForQuestionAnswering, MBartForSequenceClassification, MBartModel, MBartPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mbart import TFMBartForConditionalGeneration, TFMBartModel, TFMBartPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_mbart import ( FlaxMBartForConditionalGeneration, FlaxMBartForQuestionAnswering, FlaxMBartForSequenceClassification, FlaxMBartModel, FlaxMBartPreTrainedModel, ) else: import sys _snake_case : str = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
524
0
'''simple docstring''' A__ : Optional[int] =[ 9_99, 8_00, 7_99, 6_00, 5_99, 5_00, 4_00, 3_99, 3_77, 3_55, 3_33, 3_11, 2_88, 2_66, 2_44, 2_22, 2_00, 1_99, 1_77, 1_55, 1_33, 1_11, 88, 66, 44, 22, 0, ] A__ : Any =[ 9_99, 9_76, 9_52, 9_28, 9_05, 8_82, 8_58, 8_57, 8_10, 7_62, 7_15, 7_14, 5_72, 4_29, 4_28, 2_86, 2_85, 2_38, 1_90, 1_43, 1_42, 1_18, 95, 71, 47, 24, 0, ] A__ : Dict =[ 9_99, 9_88, 9_77, 9_66, 9_55, 9_44, 9_33, 9_22, 9_11, 9_00, 8_99, 8_79, 8_59, 8_40, 8_20, 8_00, 7_99, 7_66, 7_33, 7_00, 6_99, 6_50, 6_00, 5_99, 5_00, 4_99, 4_00, 3_99, 3_50, 3_00, 2_99, 2_66, 2_33, 2_00, 1_99, 1_79, 1_59, 1_40, 1_20, 1_00, 99, 88, 77, 66, 55, 44, 33, 22, 11, 0, ] A__ : Optional[Any] =[ 9_99, 9_95, 9_92, 9_89, 9_85, 9_81, 9_78, 9_75, 9_71, 9_67, 9_64, 9_61, 9_57, 9_56, 9_51, 9_47, 9_42, 9_37, 9_33, 9_28, 9_23, 9_19, 9_14, 9_13, 9_08, 9_03, 8_97, 8_92, 8_87, 8_81, 8_76, 8_71, 8_70, 8_64, 8_58, 8_52, 8_46, 8_40, 8_34, 8_28, 8_27, 8_20, 8_13, 8_06, 7_99, 7_92, 7_85, 7_84, 7_77, 7_70, 7_63, 7_56, 7_49, 7_42, 7_41, 7_33, 7_24, 7_16, 7_07, 6_99, 6_98, 6_88, 6_77, 6_66, 6_56, 6_55, 6_45, 6_34, 6_23, 6_13, 6_12, 5_98, 5_84, 5_70, 5_69, 5_55, 5_41, 5_27, 5_26, 5_05, 4_84, 4_83, 4_62, 4_40, 4_39, 3_96, 3_95, 3_52, 3_51, 3_08, 3_07, 2_64, 2_63, 2_20, 2_19, 1_76, 1_32, 88, 44, 0, ] A__ : Optional[int] =[ 9_99, 9_97, 9_95, 9_92, 9_90, 9_88, 9_86, 9_84, 9_81, 9_79, 9_77, 9_75, 9_72, 9_70, 9_68, 9_66, 9_64, 9_61, 9_59, 9_57, 9_56, 9_54, 9_51, 9_49, 9_46, 9_44, 9_41, 9_39, 9_36, 9_34, 9_31, 9_29, 9_26, 9_24, 9_21, 9_19, 9_16, 9_14, 9_13, 9_10, 9_07, 9_05, 9_02, 8_99, 8_96, 8_93, 8_91, 8_88, 8_85, 8_82, 8_79, 8_77, 8_74, 8_71, 8_70, 8_67, 8_64, 8_61, 8_58, 8_55, 8_52, 8_49, 8_46, 8_43, 8_40, 8_37, 8_34, 8_31, 8_28, 8_27, 8_24, 8_21, 8_17, 8_14, 8_11, 8_08, 8_04, 8_01, 7_98, 7_95, 7_91, 7_88, 7_85, 7_84, 7_80, 7_77, 7_74, 7_70, 7_66, 7_63, 7_60, 7_56, 7_52, 7_49, 7_46, 7_42, 7_41, 7_37, 7_33, 7_30, 7_26, 7_22, 7_18, 7_14, 7_10, 7_07, 7_03, 6_99, 6_98, 6_94, 6_90, 6_85, 6_81, 6_77, 6_73, 6_69, 6_64, 6_60, 6_56, 6_55, 6_50, 6_46, 6_41, 6_36, 6_32, 6_27, 6_22, 6_18, 6_13, 6_12, 6_07, 6_02, 5_96, 5_91, 5_86, 5_80, 5_75, 5_70, 5_69, 5_63, 5_57, 5_51, 5_45, 5_39, 5_33, 5_27, 5_26, 5_19, 5_12, 5_05, 4_98, 4_91, 4_84, 4_83, 4_74, 4_66, 4_57, 4_49, 4_40, 4_39, 4_28, 4_18, 4_07, 3_96, 3_95, 3_81, 3_66, 3_52, 3_51, 3_30, 3_08, 3_07, 2_86, 2_64, 2_63, 2_42, 2_20, 2_19, 1_76, 1_75, 1_32, 1_31, 88, 44, 0, ] A__ : List[Any] =[ 9_99, 9_91, 9_82, 9_74, 9_66, 9_58, 9_50, 9_41, 9_33, 9_25, 9_16, 9_08, 9_00, 8_99, 8_74, 8_50, 8_25, 8_00, 7_99, 7_00, 6_00, 5_00, 4_00, 3_00, 2_00, 1_00, 0, ] A__ : List[str] =[ 9_99, 9_92, 9_85, 9_78, 9_71, 9_64, 9_57, 9_49, 9_42, 9_35, 9_28, 9_21, 9_14, 9_07, 9_00, 8_99, 8_79, 8_59, 8_40, 8_20, 8_00, 7_99, 7_66, 7_33, 7_00, 6_99, 6_50, 6_00, 5_99, 5_00, 4_99, 4_00, 3_99, 3_00, 2_99, 2_00, 1_99, 1_00, 99, 0, ] A__ : Dict =[ 9_99, 9_96, 9_92, 9_89, 9_85, 9_82, 9_79, 9_75, 9_72, 9_68, 9_65, 9_61, 9_58, 9_55, 9_51, 9_48, 9_44, 9_41, 9_38, 9_34, 9_31, 9_27, 9_24, 9_20, 9_17, 9_14, 9_10, 9_07, 9_03, 9_00, 8_99, 8_91, 8_84, 8_76, 8_69, 8_61, 8_53, 8_46, 8_38, 8_30, 8_23, 8_15, 8_08, 8_00, 7_99, 7_88, 7_77, 7_66, 7_55, 7_44, 7_33, 7_22, 7_11, 7_00, 6_99, 6_88, 6_77, 6_66, 6_55, 6_44, 6_33, 6_22, 6_11, 6_00, 5_99, 5_85, 5_71, 5_57, 5_42, 5_28, 5_14, 5_00, 4_99, 4_85, 4_71, 4_57, 4_42, 4_28, 4_14, 4_00, 3_99, 3_79, 3_59, 3_40, 3_20, 3_00, 2_99, 2_79, 2_59, 2_40, 2_20, 2_00, 1_99, 1_66, 1_33, 1_00, 99, 66, 33, 0, ]
207
'''simple docstring''' import argparse import ast import logging import os import sys import pandas as pd import torch from tqdm import tqdm from transformers import BartForConditionalGeneration, RagRetriever, RagSequenceForGeneration, RagTokenForGeneration from transformers import logging as transformers_logging sys.path.append(os.path.join(os.getcwd())) # noqa: E402 # isort:skip from utils_rag import exact_match_score, fa_score # noqa: E402 # isort:skip A__ : Union[str, Any] =logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) transformers_logging.set_verbosity_info() def UpperCamelCase__ ( lowerCAmelCase ): """simple docstring""" if "token" in model_name_or_path: return "rag_token" if "sequence" in model_name_or_path: return "rag_sequence" if "bart" in model_name_or_path: return "bart" return None def UpperCamelCase__ ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ): """simple docstring""" return max(metric_fn(lowerCAmelCase , lowerCAmelCase ) for gt in ground_truths ) def UpperCamelCase__ ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ): """simple docstring""" _lowerCAmelCase = [line.strip() for line in open(lowerCAmelCase , """r""" ).readlines()] _lowerCAmelCase = [] if args.gold_data_mode == "qa": _lowerCAmelCase = pd.read_csv(lowerCAmelCase , sep="""\t""" , header=lowerCAmelCase ) for answer_list in data[1]: _lowerCAmelCase = ast.literal_eval(lowerCAmelCase ) answers.append(lowerCAmelCase ) else: _lowerCAmelCase = [line.strip() for line in open(lowerCAmelCase , """r""" ).readlines()] _lowerCAmelCase = [[reference] for reference in references] _lowerCAmelCase = _lowerCAmelCase = _lowerCAmelCase = 0 for prediction, ground_truths in zip(lowerCAmelCase , lowerCAmelCase ): total += 1 em += metric_max_over_ground_truths(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) fa += metric_max_over_ground_truths(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) _lowerCAmelCase = 100.0 * em / total _lowerCAmelCase = 100.0 * fa / total logger.info(f"F1: {fa:.2f}" ) logger.info(f"EM: {em:.2f}" ) def UpperCamelCase__ ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ): """simple docstring""" _lowerCAmelCase = args.k _lowerCAmelCase = [line.strip() for line in open(lowerCAmelCase , """r""" ).readlines()] _lowerCAmelCase = [line.strip() for line in open(lowerCAmelCase , """r""" ).readlines()] _lowerCAmelCase = _lowerCAmelCase = 0 for hypo, reference in zip(lowerCAmelCase , lowerCAmelCase ): _lowerCAmelCase = set(hypo.split("""\t""" )[:k] ) _lowerCAmelCase = set(reference.split("""\t""" ) ) total += 1 em += len(hypo_provenance & ref_provenance ) / k _lowerCAmelCase = 100.0 * em / total logger.info(f"Precision@{k}: {em: .2f}" ) def UpperCamelCase__ ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ): """simple docstring""" def strip_title(lowerCAmelCase ): if title.startswith("""\"""" ): _lowerCAmelCase = title[1:] if title.endswith("""\"""" ): _lowerCAmelCase = title[:-1] return title _lowerCAmelCase = rag_model.retriever.question_encoder_tokenizer.batch_encode_plus( lowerCAmelCase , return_tensors="""pt""" , padding=lowerCAmelCase , truncation=lowerCAmelCase , )["""input_ids"""].to(args.device ) _lowerCAmelCase = rag_model.rag.question_encoder(lowerCAmelCase ) _lowerCAmelCase = question_enc_outputs[0] _lowerCAmelCase = rag_model.retriever( lowerCAmelCase , question_enc_pool_output.cpu().detach().to(torch.floataa ).numpy() , prefix=rag_model.rag.generator.config.prefix , n_docs=rag_model.config.n_docs , return_tensors="""pt""" , ) _lowerCAmelCase = rag_model.retriever.index.get_doc_dicts(result.doc_ids ) _lowerCAmelCase = [] for docs in all_docs: _lowerCAmelCase = [strip_title(lowerCAmelCase ) for title in docs["""title"""]] provenance_strings.append("""\t""".join(lowerCAmelCase ) ) return provenance_strings def UpperCamelCase__ ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ): """simple docstring""" with torch.no_grad(): _lowerCAmelCase = rag_model.retriever.question_encoder_tokenizer.batch_encode_plus( lowerCAmelCase , return_tensors="""pt""" , padding=lowerCAmelCase , truncation=lowerCAmelCase ) _lowerCAmelCase = inputs_dict.input_ids.to(args.device ) _lowerCAmelCase = inputs_dict.attention_mask.to(args.device ) _lowerCAmelCase = rag_model.generate( # rag_model overwrites generate lowerCAmelCase , attention_mask=lowerCAmelCase , num_beams=args.num_beams , min_length=args.min_length , max_length=args.max_length , early_stopping=lowerCAmelCase , num_return_sequences=1 , bad_words_ids=[[0, 0]] , ) _lowerCAmelCase = rag_model.retriever.generator_tokenizer.batch_decode(lowerCAmelCase , skip_special_tokens=lowerCAmelCase ) if args.print_predictions: for q, a in zip(lowerCAmelCase , lowerCAmelCase ): logger.info("""Q: {} - A: {}""".format(lowerCAmelCase , lowerCAmelCase ) ) return answers def UpperCamelCase__ ( ): """simple docstring""" _lowerCAmelCase = argparse.ArgumentParser() parser.add_argument( """--model_type""" , choices=["""rag_sequence""", """rag_token""", """bart"""] , type=lowerCAmelCase , help=( """RAG model type: rag_sequence, rag_token or bart, if none specified, the type is inferred from the""" """ model_name_or_path""" ) , ) parser.add_argument( """--index_name""" , default=lowerCAmelCase , choices=["""exact""", """compressed""", """legacy"""] , type=lowerCAmelCase , help="""RAG model retriever type""" , ) parser.add_argument( """--index_path""" , default=lowerCAmelCase , type=lowerCAmelCase , help="""Path to the retrieval index""" , ) parser.add_argument("""--n_docs""" , default=5 , type=lowerCAmelCase , help="""Number of retrieved docs""" ) parser.add_argument( """--model_name_or_path""" , default=lowerCAmelCase , type=lowerCAmelCase , required=lowerCAmelCase , help="""Path to pretrained checkpoints or model identifier from huggingface.co/models""" , ) parser.add_argument( """--eval_mode""" , choices=["""e2e""", """retrieval"""] , default="""e2e""" , type=lowerCAmelCase , help=( """Evaluation mode, e2e calculates exact match and F1 of the downstream task, retrieval calculates""" """ precision@k.""" ) , ) parser.add_argument("""--k""" , default=1 , type=lowerCAmelCase , help="""k for the precision@k calculation""" ) parser.add_argument( """--evaluation_set""" , default=lowerCAmelCase , type=lowerCAmelCase , required=lowerCAmelCase , help="""Path to a file containing evaluation samples""" , ) parser.add_argument( """--gold_data_path""" , default=lowerCAmelCase , type=lowerCAmelCase , required=lowerCAmelCase , help="""Path to a tab-separated file with gold samples""" , ) parser.add_argument( """--gold_data_mode""" , default="""qa""" , type=lowerCAmelCase , choices=["""qa""", """ans"""] , help=( """Format of the gold data file""" """qa - a single line in the following format: question [tab] answer_list""" """ans - a single line of the gold file contains the expected answer string""" ) , ) parser.add_argument( """--predictions_path""" , type=lowerCAmelCase , default="""predictions.txt""" , help="""Name of the predictions file, to be stored in the checkpoints directory""" , ) parser.add_argument( """--eval_all_checkpoints""" , action="""store_true""" , help="""Evaluate all checkpoints starting with the same prefix as model_name ending and ending with step number""" , ) parser.add_argument( """--eval_batch_size""" , default=8 , type=lowerCAmelCase , help="""Batch size per GPU/CPU for evaluation.""" , ) parser.add_argument( """--recalculate""" , help="""Recalculate predictions even if the prediction file exists""" , action="""store_true""" , ) parser.add_argument( """--num_beams""" , default=4 , type=lowerCAmelCase , help="""Number of beams to be used when generating answers""" , ) parser.add_argument("""--min_length""" , default=1 , type=lowerCAmelCase , help="""Min length of the generated answers""" ) parser.add_argument("""--max_length""" , default=50 , type=lowerCAmelCase , help="""Max length of the generated answers""" ) parser.add_argument( """--print_predictions""" , action="""store_true""" , help="""If True, prints predictions while evaluating.""" , ) parser.add_argument( """--print_docs""" , action="""store_true""" , help="""If True, prints docs retried while generating.""" , ) _lowerCAmelCase = parser.parse_args() _lowerCAmelCase = torch.device("""cuda""" if torch.cuda.is_available() else """cpu""" ) return args def UpperCamelCase__ ( lowerCAmelCase ): """simple docstring""" _lowerCAmelCase = {} if args.model_type is None: _lowerCAmelCase = infer_model_type(args.model_name_or_path ) assert args.model_type is not None if args.model_type.startswith("""rag""" ): _lowerCAmelCase = RagTokenForGeneration if args.model_type == """rag_token""" else RagSequenceForGeneration _lowerCAmelCase = args.n_docs if args.index_name is not None: _lowerCAmelCase = args.index_name if args.index_path is not None: _lowerCAmelCase = args.index_path else: _lowerCAmelCase = BartForConditionalGeneration _lowerCAmelCase = ( [f.path for f in os.scandir(args.model_name_or_path ) if f.is_dir()] if args.eval_all_checkpoints else [args.model_name_or_path] ) logger.info("""Evaluate the following checkpoints: %s""" , lowerCAmelCase ) _lowerCAmelCase = get_scores if args.eval_mode == """e2e""" else get_precision_at_k _lowerCAmelCase = evaluate_batch_eae if args.eval_mode == """e2e""" else evaluate_batch_retrieval for checkpoint in checkpoints: if os.path.exists(args.predictions_path ) and (not args.recalculate): logger.info("""Calculating metrics based on an existing predictions file: {}""".format(args.predictions_path ) ) score_fn(lowerCAmelCase , args.predictions_path , args.gold_data_path ) continue logger.info("""***** Running evaluation for {} *****""".format(lowerCAmelCase ) ) logger.info(""" Batch size = %d""" , args.eval_batch_size ) logger.info(""" Predictions will be stored under {}""".format(args.predictions_path ) ) if args.model_type.startswith("""rag""" ): _lowerCAmelCase = RagRetriever.from_pretrained(lowerCAmelCase , **lowerCAmelCase ) _lowerCAmelCase = model_class.from_pretrained(lowerCAmelCase , retriever=lowerCAmelCase , **lowerCAmelCase ) model.retriever.init_retrieval() else: _lowerCAmelCase = model_class.from_pretrained(lowerCAmelCase , **lowerCAmelCase ) model.to(args.device ) with open(args.evaluation_set , """r""" ) as eval_file, open(args.predictions_path , """w""" ) as preds_file: _lowerCAmelCase = [] for line in tqdm(lowerCAmelCase ): questions.append(line.strip() ) if len(lowerCAmelCase ) == args.eval_batch_size: _lowerCAmelCase = evaluate_batch_fn(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) preds_file.write("""\n""".join(lowerCAmelCase ) + """\n""" ) preds_file.flush() _lowerCAmelCase = [] if len(lowerCAmelCase ) > 0: _lowerCAmelCase = evaluate_batch_fn(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) preds_file.write("""\n""".join(lowerCAmelCase ) ) preds_file.flush() score_fn(lowerCAmelCase , args.predictions_path , args.gold_data_path ) if __name__ == "__main__": A__ : Tuple =get_args() main(args)
207
1
"""simple docstring""" import argparse import json import os 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.deepspeed import DummyOptim, DummyScheduler A: List[str] = 1_6 A: Dict = 3_2 def _snake_case ( UpperCamelCase : Accelerator , UpperCamelCase : int = 16 , UpperCamelCase : str = "bert-base-cased" ): UpperCAmelCase : Dict = AutoTokenizer.from_pretrained(UpperCamelCase ) UpperCAmelCase : str = load_dataset("""glue""" , """mrpc""" ) def tokenize_function(UpperCamelCase : List[Any] ): # max_length=None => use the model max length (it's actually the default) UpperCAmelCase : Tuple = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=UpperCamelCase , max_length=UpperCamelCase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset UpperCAmelCase : Dict = datasets.map( UpperCamelCase , batched=UpperCamelCase , remove_columns=["""idx""", """sentence1""", """sentence2"""] , load_from_cache_file=UpperCamelCase ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library UpperCAmelCase : Any = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(UpperCamelCase : Union[str, Any] ): # 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(UpperCamelCase , padding="""max_length""" , max_length=128 , return_tensors="""pt""" ) return tokenizer.pad(UpperCamelCase , padding="""longest""" , return_tensors="""pt""" ) # Instantiate dataloaders. UpperCAmelCase : List[str] = DataLoader( tokenized_datasets["""train"""] , shuffle=UpperCamelCase , collate_fn=UpperCamelCase , batch_size=UpperCamelCase ) UpperCAmelCase : List[Any] = DataLoader( tokenized_datasets["""validation"""] , shuffle=UpperCamelCase , collate_fn=UpperCamelCase , batch_size=UpperCamelCase ) return train_dataloader, eval_dataloader def _snake_case ( UpperCamelCase : int , UpperCamelCase : List[str] ): # Initialize accelerator UpperCAmelCase : Any = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs UpperCAmelCase : Any = config["""lr"""] UpperCAmelCase : Tuple = int(config["""num_epochs"""] ) UpperCAmelCase : Optional[Any] = int(config["""seed"""] ) UpperCAmelCase : List[str] = int(config["""batch_size"""] ) UpperCAmelCase : List[Any] = args.model_name_or_path set_seed(UpperCamelCase ) UpperCAmelCase , UpperCAmelCase : Optional[int] = get_dataloaders(UpperCamelCase , UpperCamelCase , UpperCamelCase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) UpperCAmelCase : Optional[int] = AutoModelForSequenceClassification.from_pretrained(UpperCamelCase , return_dict=UpperCamelCase ) # Instantiate optimizer UpperCAmelCase : str = ( AdamW if accelerator.state.deepspeed_plugin is None or """optimizer""" not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) UpperCAmelCase : int = optimizer_cls(params=model.parameters() , lr=UpperCamelCase ) if accelerator.state.deepspeed_plugin is not None: UpperCAmelCase : Optional[int] = accelerator.state.deepspeed_plugin.deepspeed_config[ """gradient_accumulation_steps""" ] else: UpperCAmelCase : List[str] = 1 UpperCAmelCase : str = (len(UpperCamelCase ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): UpperCAmelCase : str = get_linear_schedule_with_warmup( optimizer=UpperCamelCase , num_warmup_steps=0 , num_training_steps=UpperCamelCase , ) else: UpperCAmelCase : Any = DummyScheduler(UpperCamelCase , total_num_steps=UpperCamelCase , 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. UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase : Optional[int] = accelerator.prepare( UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) # We need to keep track of how many total steps we have iterated over UpperCAmelCase : Any = 0 # We also need to keep track of the stating epoch so files are named properly UpperCAmelCase : Dict = 0 # Now we train the model UpperCAmelCase : Tuple = evaluate.load("""glue""" , """mrpc""" ) UpperCAmelCase : Any = 0 UpperCAmelCase : Optional[int] = {} for epoch in range(UpperCamelCase , UpperCamelCase ): model.train() for step, batch in enumerate(UpperCamelCase ): UpperCAmelCase : Union[str, Any] = model(**UpperCamelCase ) UpperCAmelCase : Dict = outputs.loss UpperCAmelCase : Tuple = loss / gradient_accumulation_steps accelerator.backward(UpperCamelCase ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 model.eval() UpperCAmelCase : Optional[int] = 0 for step, batch in enumerate(UpperCamelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): UpperCAmelCase : Optional[int] = model(**UpperCamelCase ) UpperCAmelCase : Any = outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times UpperCAmelCase , UpperCAmelCase : Optional[Any] = accelerator.gather( (predictions, batch["""labels"""]) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(UpperCamelCase ) - 1: UpperCAmelCase : Union[str, Any] = predictions[: len(eval_dataloader.dataset ) - samples_seen] UpperCAmelCase : Any = references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=UpperCamelCase , references=UpperCamelCase , ) UpperCAmelCase : Tuple = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F"epoch {epoch}:" , UpperCamelCase ) UpperCAmelCase : List[str] = eval_metric["""accuracy"""] if best_performance < eval_metric["accuracy"]: UpperCAmelCase : Any = eval_metric["""accuracy"""] if args.performance_lower_bound is not None: assert ( args.performance_lower_bound <= best_performance ), F"Best performance metric {best_performance} is lower than the lower bound {args.performance_lower_bound}" accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir , """all_results.json""" ) , """w""" ) as f: json.dump(UpperCamelCase , UpperCamelCase ) def _snake_case ( ): UpperCAmelCase : int = argparse.ArgumentParser(description="""Simple example of training script tracking peak GPU memory usage.""" ) parser.add_argument( """--model_name_or_path""" , type=UpperCamelCase , default="""bert-base-cased""" , help="""Path to pretrained model or model identifier from huggingface.co/models.""" , required=UpperCamelCase , ) parser.add_argument( """--output_dir""" , type=UpperCamelCase , default=""".""" , help="""Optional save directory where all checkpoint folders will be stored. Default is the current working directory.""" , ) parser.add_argument( """--performance_lower_bound""" , type=UpperCamelCase , default=UpperCamelCase , help="""Optional lower bound for the performance metric. If set, the training will throw error when the performance metric drops below this value.""" , ) parser.add_argument( """--num_epochs""" , type=UpperCamelCase , default=3 , help="""Number of train epochs.""" , ) UpperCAmelCase : List[str] = parser.parse_args() UpperCAmelCase : Optional[Any] = {"""lr""": 2e-5, """num_epochs""": args.num_epochs, """seed""": 42, """batch_size""": 16} training_function(UpperCamelCase , UpperCamelCase ) if __name__ == "__main__": main()
359
"""simple docstring""" def _snake_case ( UpperCamelCase : int , UpperCamelCase : int ): return 1 if input_a == input_a else 0 def _snake_case ( ): assert xnor_gate(0 , 0 ) == 1 assert xnor_gate(0 , 1 ) == 0 assert xnor_gate(1 , 0 ) == 0 assert xnor_gate(1 , 1 ) == 1 if __name__ == "__main__": print(xnor_gate(0, 0)) print(xnor_gate(0, 1)) print(xnor_gate(1, 0)) print(xnor_gate(1, 1))
359
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __SCREAMING_SNAKE_CASE : Optional[int] ={ '''configuration_megatron_bert''': ['''MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MegatronBertConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE : int =[ '''MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MegatronBertForCausalLM''', '''MegatronBertForMaskedLM''', '''MegatronBertForMultipleChoice''', '''MegatronBertForNextSentencePrediction''', '''MegatronBertForPreTraining''', '''MegatronBertForQuestionAnswering''', '''MegatronBertForSequenceClassification''', '''MegatronBertForTokenClassification''', '''MegatronBertModel''', '''MegatronBertPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_megatron_bert import MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, MegatronBertConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_megatron_bert import ( MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, MegatronBertForCausalLM, MegatronBertForMaskedLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, MegatronBertModel, MegatronBertPreTrainedModel, ) else: import sys __SCREAMING_SNAKE_CASE : List[Any] =_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
428
__SCREAMING_SNAKE_CASE : Optional[Any] ='''Tobias Carryer''' from time import time class A_ : def __init__( self : int , snake_case__ : List[Any] , snake_case__ : List[str] , snake_case__ : int , snake_case__ : int=int(time() ) ): # noqa: B008 lowercase = multiplier lowercase = increment lowercase = modulo lowercase = seed def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): lowercase = (self.multiplier * self.seed + self.increment) % self.modulo return self.seed if __name__ == "__main__": # Show the LCG in action. __SCREAMING_SNAKE_CASE : Union[str, Any] =LinearCongruentialGenerator(1_664_525, 1_013_904_223, 2 << 31) while True: print(lcg.next_number())
428
1
import numpy as np # Importing the Keras libraries and packages import tensorflow as tf from tensorflow.keras import layers, models if __name__ == "__main__": # Initialising the CNN # (Sequential- Building the model layer by layer) _SCREAMING_SNAKE_CASE : str = models.Sequential() # Step 1 - Convolution # Here 64,64 is the length & breadth of dataset images and 3 is for the RGB channel # (3,3) is the kernel size (filter matrix) classifier.add( layers.ConvaD(32, (3, 3), input_shape=(64, 64, 3), activation='''relu''') ) # Step 2 - Pooling classifier.add(layers.MaxPoolingaD(pool_size=(2, 2))) # Adding a second convolutional layer classifier.add(layers.ConvaD(32, (3, 3), activation='''relu''')) classifier.add(layers.MaxPoolingaD(pool_size=(2, 2))) # Step 3 - Flattening classifier.add(layers.Flatten()) # Step 4 - Full connection classifier.add(layers.Dense(units=128, activation='''relu''')) classifier.add(layers.Dense(units=1, activation='''sigmoid''')) # Compiling the CNN classifier.compile( optimizer='''adam''', loss='''binary_crossentropy''', metrics=['''accuracy'''] ) # Part 2 - Fitting the CNN to the images # Load Trained model weights # from keras.models import load_model # regressor=load_model('cnn.h5') _SCREAMING_SNAKE_CASE : Optional[int] = tf.keras.preprocessing.image.ImageDataGenerator( rescale=1.0 / 255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True ) _SCREAMING_SNAKE_CASE : Dict = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1.0 / 255) _SCREAMING_SNAKE_CASE : Union[str, Any] = train_datagen.flow_from_directory( '''dataset/training_set''', target_size=(64, 64), batch_size=32, class_mode='''binary''' ) _SCREAMING_SNAKE_CASE : Dict = test_datagen.flow_from_directory( '''dataset/test_set''', target_size=(64, 64), batch_size=32, class_mode='''binary''' ) classifier.fit_generator( training_set, steps_per_epoch=5, epochs=30, validation_data=test_set ) classifier.save('''cnn.h5''') # Part 3 - Making new predictions _SCREAMING_SNAKE_CASE : Tuple = tf.keras.preprocessing.image.load_img( '''dataset/single_prediction/image.png''', target_size=(64, 64) ) _SCREAMING_SNAKE_CASE : int = tf.keras.preprocessing.image.img_to_array(test_image) _SCREAMING_SNAKE_CASE : Any = np.expand_dims(test_image, axis=0) _SCREAMING_SNAKE_CASE : str = classifier.predict(test_image) # training_set.class_indices if result[0][0] == 0: _SCREAMING_SNAKE_CASE : Optional[Any] = '''Normal''' if result[0][0] == 1: _SCREAMING_SNAKE_CASE : Tuple = '''Abnormality detected'''
708
from collections import OrderedDict from typing import TYPE_CHECKING, Any, List, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import TensorType, logging if TYPE_CHECKING: from ...onnx.config import PatchingSpec from ...tokenization_utils_base import PreTrainedTokenizerBase _SCREAMING_SNAKE_CASE : Any = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE : List[str] = { '''allenai/longformer-base-4096''': '''https://huggingface.co/allenai/longformer-base-4096/resolve/main/config.json''', '''allenai/longformer-large-4096''': '''https://huggingface.co/allenai/longformer-large-4096/resolve/main/config.json''', '''allenai/longformer-large-4096-finetuned-triviaqa''': ( '''https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/config.json''' ), '''allenai/longformer-base-4096-extra.pos.embd.only''': ( '''https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/config.json''' ), '''allenai/longformer-large-4096-extra.pos.embd.only''': ( '''https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/config.json''' ), } class UpperCAmelCase__ ( A__ ): """simple docstring""" a = "longformer" def __init__( self : int , __lowerCamelCase : Union[List[int], int] = 512 , __lowerCamelCase : int = 2 , __lowerCamelCase : int = 1 , __lowerCamelCase : int = 0 , __lowerCamelCase : int = 2 , __lowerCamelCase : int = 3_0522 , __lowerCamelCase : int = 768 , __lowerCamelCase : int = 12 , __lowerCamelCase : int = 12 , __lowerCamelCase : int = 3072 , __lowerCamelCase : str = "gelu" , __lowerCamelCase : float = 0.1 , __lowerCamelCase : float = 0.1 , __lowerCamelCase : int = 512 , __lowerCamelCase : int = 2 , __lowerCamelCase : float = 0.02 , __lowerCamelCase : float = 1e-12 , __lowerCamelCase : bool = False , **__lowerCamelCase : Tuple , ) -> List[Any]: super().__init__(pad_token_id=__lowerCamelCase , **__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = attention_window SCREAMING_SNAKE_CASE__ = sep_token_id SCREAMING_SNAKE_CASE__ = bos_token_id SCREAMING_SNAKE_CASE__ = eos_token_id SCREAMING_SNAKE_CASE__ = vocab_size SCREAMING_SNAKE_CASE__ = hidden_size SCREAMING_SNAKE_CASE__ = num_hidden_layers SCREAMING_SNAKE_CASE__ = num_attention_heads SCREAMING_SNAKE_CASE__ = hidden_act SCREAMING_SNAKE_CASE__ = intermediate_size SCREAMING_SNAKE_CASE__ = hidden_dropout_prob SCREAMING_SNAKE_CASE__ = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ = max_position_embeddings SCREAMING_SNAKE_CASE__ = type_vocab_size SCREAMING_SNAKE_CASE__ = initializer_range SCREAMING_SNAKE_CASE__ = layer_norm_eps SCREAMING_SNAKE_CASE__ = onnx_export class UpperCAmelCase__ ( A__ ): """simple docstring""" def __init__( self : Dict , __lowerCamelCase : "PretrainedConfig" , __lowerCamelCase : str = "default" , __lowerCamelCase : "List[PatchingSpec]" = None ) -> List[str]: super().__init__(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) SCREAMING_SNAKE_CASE__ = True @property def lowercase_ ( self : Optional[Any] ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": SCREAMING_SNAKE_CASE__ = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: SCREAMING_SNAKE_CASE__ = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ('''global_attention_mask''', dynamic_axis), ] ) @property def lowercase_ ( self : Optional[int] ) -> Mapping[str, Mapping[int, str]]: SCREAMING_SNAKE_CASE__ = super().outputs if self.task == "default": SCREAMING_SNAKE_CASE__ = {0: '''batch'''} return outputs @property def lowercase_ ( self : Optional[int] ) -> float: return 1e-4 @property def lowercase_ ( self : Union[str, Any] ) -> int: # needs to be >= 14 to support tril operator return max(super().default_onnx_opset , 14 ) def lowercase_ ( self : Dict , __lowerCamelCase : "PreTrainedTokenizerBase" , __lowerCamelCase : int = -1 , __lowerCamelCase : int = -1 , __lowerCamelCase : bool = False , __lowerCamelCase : Optional[TensorType] = None , ) -> Mapping[str, Any]: SCREAMING_SNAKE_CASE__ = super().generate_dummy_inputs( preprocessor=__lowerCamelCase , batch_size=__lowerCamelCase , seq_length=__lowerCamelCase , is_pair=__lowerCamelCase , framework=__lowerCamelCase ) import torch # for some reason, replacing this code by inputs["global_attention_mask"] = torch.randint(2, inputs["input_ids"].shape, dtype=torch.int64) # makes the export fail randomly SCREAMING_SNAKE_CASE__ = torch.zeros_like(inputs['''input_ids'''] ) # make every second token global SCREAMING_SNAKE_CASE__ = 1 return inputs
472
0
import inspect import re from hashlib import shaaaa from typing import Dict, List from .arrow import arrow from .audiofolder import audiofolder from .csv import csv from .imagefolder import imagefolder from .json import json from .pandas import pandas from .parquet import parquet from .sql import sql # noqa F401 from .text import text def a__ ( lowercase__ ): '''simple docstring''' UpperCAmelCase_ =[] for line in lines: UpperCAmelCase_ =re.sub(R"#.*" , "" , lowercase__ ) # remove comments if line: filtered_lines.append(lowercase__ ) UpperCAmelCase_ ="\n".join(lowercase__ ) # Make a hash from all this code UpperCAmelCase_ =full_str.encode("utf-8" ) return shaaaa(lowercase__ ).hexdigest() # get importable module names and hash for caching __lowercase : Tuple ={ """csv""": (csv.__name__, _hash_python_lines(inspect.getsource(csv).splitlines())), """json""": (json.__name__, _hash_python_lines(inspect.getsource(json).splitlines())), """pandas""": (pandas.__name__, _hash_python_lines(inspect.getsource(pandas).splitlines())), """parquet""": (parquet.__name__, _hash_python_lines(inspect.getsource(parquet).splitlines())), """arrow""": (arrow.__name__, _hash_python_lines(inspect.getsource(arrow).splitlines())), """text""": (text.__name__, _hash_python_lines(inspect.getsource(text).splitlines())), """imagefolder""": (imagefolder.__name__, _hash_python_lines(inspect.getsource(imagefolder).splitlines())), """audiofolder""": (audiofolder.__name__, _hash_python_lines(inspect.getsource(audiofolder).splitlines())), } # Used to infer the module to use based on the data files extensions __lowercase : Optional[int] ={ """.csv""": ("""csv""", {}), """.tsv""": ("""csv""", {"""sep""": """\t"""}), """.json""": ("""json""", {}), """.jsonl""": ("""json""", {}), """.parquet""": ("""parquet""", {}), """.arrow""": ("""arrow""", {}), """.txt""": ("""text""", {}), } _EXTENSION_TO_MODULE.update({ext: ("""imagefolder""", {}) for ext in imagefolder.ImageFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext.upper(): ("""imagefolder""", {}) for ext in imagefolder.ImageFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext: ("""audiofolder""", {}) for ext in audiofolder.AudioFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext.upper(): ("""audiofolder""", {}) for ext in audiofolder.AudioFolder.EXTENSIONS}) __lowercase : Dict ={"""imagefolder""", """audiofolder"""} # Used to filter data files based on extensions given a module name __lowercase : Dict[str, List[str]] ={} for _ext, (_module, _) in _EXTENSION_TO_MODULE.items(): _MODULE_TO_EXTENSIONS.setdefault(_module, []).append(_ext) _MODULE_TO_EXTENSIONS["imagefolder"].append(""".zip""") _MODULE_TO_EXTENSIONS["audiofolder"].append(""".zip""")
54
import fire from torch.utils.data import DataLoader from tqdm import tqdm from transformers import AutoTokenizer from utils import SeqaSeqDataset, pickle_save def a__ ( lowercase__ , lowercase__ , lowercase__=1_0_2_4 , lowercase__=1_0_2_4 , lowercase__=False , **lowercase__ ): '''simple docstring''' UpperCAmelCase_ =AutoTokenizer.from_pretrained(lowercase__ ) UpperCAmelCase_ =SeqaSeqDataset(lowercase__ , lowercase__ , lowercase__ , lowercase__ , type_path="train" , **lowercase__ ) UpperCAmelCase_ =tok.pad_token_id def get_lens(lowercase__ ): UpperCAmelCase_ =tqdm( DataLoader(lowercase__ , batch_size=5_1_2 , num_workers=8 , shuffle=lowercase__ , collate_fn=ds.collate_fn ) , desc=str(ds.len_file ) , ) UpperCAmelCase_ =[] for batch in dl: UpperCAmelCase_ =batch["input_ids"].ne(lowercase__ ).sum(1 ).tolist() UpperCAmelCase_ =batch["labels"].ne(lowercase__ ).sum(1 ).tolist() if consider_target: for src, tgt in zip(lowercase__ , lowercase__ ): max_lens.append(max(lowercase__ , lowercase__ ) ) else: max_lens.extend(lowercase__ ) return max_lens UpperCAmelCase_ =get_lens(lowercase__ ) UpperCAmelCase_ =SeqaSeqDataset(lowercase__ , lowercase__ , lowercase__ , lowercase__ , type_path="val" , **lowercase__ ) UpperCAmelCase_ =get_lens(lowercase__ ) pickle_save(lowercase__ , train_ds.len_file ) pickle_save(lowercase__ , val_ds.len_file ) if __name__ == "__main__": fire.Fire(save_len_file)
54
1
def __lowerCAmelCase ( lowercase : int , lowercase : int ) -> int: """simple docstring""" while second != 0: snake_case : str = first & second first ^= second snake_case : str = c << 1 return first if __name__ == "__main__": import doctest doctest.testmod() __snake_case = int(input("""Enter the first number: """).strip()) __snake_case = int(input("""Enter the second number: """).strip()) print(F'''{add(first, second) = }''')
715
"""simple docstring""" import os import unittest from transformers import LayoutLMTokenizer, LayoutLMTokenizerFast from transformers.models.layoutlm.tokenization_layoutlm import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class _lowerCAmelCase ( snake_case_ , unittest.TestCase ): __UpperCAmelCase : List[Any] = LayoutLMTokenizer __UpperCAmelCase : List[Any] = LayoutLMTokenizerFast __UpperCAmelCase : List[Any] = True __UpperCAmelCase : Dict = True def lowerCamelCase ( self ) -> str: '''simple docstring''' super().setUp() snake_case : Dict = [ "[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest", ] snake_case : List[str] = 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] ) ) def lowerCamelCase ( self , **UpperCamelCase__ ) -> Dict: '''simple docstring''' return LayoutLMTokenizer.from_pretrained(self.tmpdirname , **UpperCamelCase__ ) def lowerCamelCase ( self , UpperCamelCase__ ) -> Tuple: '''simple docstring''' snake_case : str = "UNwant\u00E9d,running" snake_case : Optional[int] = "unwanted, running" return input_text, output_text def lowerCamelCase ( self ) -> Any: '''simple docstring''' snake_case : List[str] = self.tokenizer_class(self.vocab_file ) snake_case : Optional[Any] = tokenizer.tokenize("UNwant\u00E9d,running" ) self.assertListEqual(UpperCamelCase__ , ["un", "##want", "##ed", ",", "runn", "##ing"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCamelCase__ ) , [7, 4, 5, 10, 8, 9] ) def lowerCamelCase ( self ) -> Dict: '''simple docstring''' pass
117
0
from __future__ import annotations import unittest from transformers import AutoTokenizer, PegasusConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFPegasusForConditionalGeneration, TFPegasusModel @require_tf class a__ : _A = PegasusConfig _A = {} _A = "gelu" def __init__( self : int , A_ : int , A_ : List[str]=13 , A_ : Optional[Any]=7 , A_ : Optional[Any]=True , A_ : Optional[int]=False , A_ : int=99 , A_ : List[Any]=32 , A_ : Optional[int]=2 , A_ : Tuple=4 , A_ : Optional[Any]=37 , A_ : List[Any]=0.1 , A_ : Any=0.1 , A_ : Optional[Any]=40 , A_ : str=2 , A_ : Optional[Any]=1 , A_ : Tuple=0 , ) -> Optional[int]: """simple docstring""" lowerCamelCase_: str = parent lowerCamelCase_: int = batch_size lowerCamelCase_: Any = seq_length lowerCamelCase_: Optional[int] = is_training lowerCamelCase_: Union[str, Any] = use_labels lowerCamelCase_: List[Any] = vocab_size lowerCamelCase_: Dict = hidden_size lowerCamelCase_: str = num_hidden_layers lowerCamelCase_: List[str] = num_attention_heads lowerCamelCase_: List[Any] = intermediate_size lowerCamelCase_: List[Any] = hidden_dropout_prob lowerCamelCase_: Any = attention_probs_dropout_prob lowerCamelCase_: int = max_position_embeddings lowerCamelCase_: int = eos_token_id lowerCamelCase_: Optional[int] = pad_token_id lowerCamelCase_: str = bos_token_id def lowerCAmelCase ( self : List[Any] ) -> Any: """simple docstring""" lowerCamelCase_: List[Any] = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) lowerCamelCase_: Optional[int] = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) lowerCamelCase_: str = tf.concat([input_ids, eos_tensor] , axis=1 ) lowerCamelCase_: Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCamelCase_: List[Any] = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) lowerCamelCase_: List[Any] = prepare_pegasus_inputs_dict(A_ , A_ , A_ ) return config, inputs_dict def lowerCAmelCase ( self : List[str] , A_ : Optional[Any] , A_ : str ) -> List[Any]: """simple docstring""" lowerCamelCase_: Tuple = TFPegasusModel(config=A_ ).get_decoder() lowerCamelCase_: Union[str, Any] = inputs_dict["""input_ids"""] lowerCamelCase_: int = input_ids[:1, :] lowerCamelCase_: List[Any] = inputs_dict["""attention_mask"""][:1, :] lowerCamelCase_: Union[str, Any] = inputs_dict["""head_mask"""] lowerCamelCase_: Tuple = 1 # first forward pass lowerCamelCase_: Optional[int] = model(A_ , attention_mask=A_ , head_mask=A_ , use_cache=A_ ) lowerCamelCase_ , lowerCamelCase_: Optional[int] = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids lowerCamelCase_: Optional[Any] = ids_tensor((self.batch_size, 3) , config.vocab_size ) lowerCamelCase_: Optional[int] = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and lowerCamelCase_: Optional[Any] = tf.concat([input_ids, next_tokens] , axis=-1 ) lowerCamelCase_: Tuple = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) lowerCamelCase_: int = model(A_ , attention_mask=A_ )[0] lowerCamelCase_: Optional[int] = model(A_ , attention_mask=A_ , past_key_values=A_ )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice lowerCamelCase_: Optional[int] = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) lowerCamelCase_: Union[str, Any] = output_from_no_past[:, -3:, random_slice_idx] lowerCamelCase_: Optional[int] = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(A_ , A_ , rtol=1e-3 ) def UpperCAmelCase_ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=None , _UpperCAmelCase=None , _UpperCAmelCase=None , _UpperCAmelCase=None , _UpperCAmelCase=None , ): if attention_mask is None: lowerCamelCase_: Optional[int] = tf.cast(tf.math.not_equal(_UpperCAmelCase , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: lowerCamelCase_: List[str] = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: lowerCamelCase_: int = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: lowerCamelCase_: List[Any] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: lowerCamelCase_: List[Any] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class a__ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): _A = (TFPegasusForConditionalGeneration, TFPegasusModel) if is_tf_available() else () _A = (TFPegasusForConditionalGeneration,) if is_tf_available() else () _A = ( { "conversational": TFPegasusForConditionalGeneration, "feature-extraction": TFPegasusModel, "summarization": TFPegasusForConditionalGeneration, "text2text-generation": TFPegasusForConditionalGeneration, "translation": TFPegasusForConditionalGeneration, } if is_tf_available() else {} ) _A = True _A = False _A = False def lowerCAmelCase ( self : Union[str, Any] ) -> Any: """simple docstring""" lowerCamelCase_: Tuple = TFPegasusModelTester(self ) lowerCamelCase_: Optional[int] = ConfigTester(self , config_class=A_ ) def lowerCAmelCase ( self : Optional[Any] ) -> List[Any]: """simple docstring""" self.config_tester.run_common_tests() def lowerCAmelCase ( self : Dict ) -> Tuple: """simple docstring""" lowerCamelCase_: List[str] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*A_ ) @require_sentencepiece @require_tokenizers @require_tf class a__ ( unittest.TestCase ): _A = [ " PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.", " The London trio are up for best UK act and best album, as well as getting two nominations in the best song category.\"We got told like this morning 'Oh I think you're nominated'\", said Dappy.\"And I was like 'Oh yeah, which one?' And now we've got nominated for four awards. I mean, wow!\"Bandmate Fazer added: \"We thought it's best of us to come down and mingle with everyone and say hello to the cameras. And now we find we've got four nominations.\"The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn't be too disappointed if they didn't win this time around.\"At the end of the day we're grateful to be where we are in our careers.\"If it don't happen then it don't happen - live to fight another day and keep on making albums and hits for the fans.\"Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a re-working of The Killers' All These Things That I've Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year's Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border.\"We just done Edinburgh the other day,\" said Dappy.\"We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!\" ", ] _A = [ "California's largest electricity provider has cut power to hundreds of thousands of customers in an effort to" " reduce the risk of wildfires.", "N-Dubz have revealed they\'re \"grateful\" to have been nominated for four Mobo Awards.", ] # differs slightly from pytorch, likely due to numerical differences in linear layers _A = "google/pegasus-xsum" @cached_property def lowerCAmelCase ( self : Optional[int] ) -> Optional[int]: """simple docstring""" return AutoTokenizer.from_pretrained(self.model_name ) @cached_property def lowerCAmelCase ( self : Any ) -> Union[str, Any]: """simple docstring""" lowerCamelCase_: Any = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model def lowerCAmelCase ( self : str , **A_ : Optional[int] ) -> int: """simple docstring""" lowerCamelCase_: Union[str, Any] = self.translate_src_text(**A_ ) assert self.expected_text == generated_words def lowerCAmelCase ( self : str , **A_ : int ) -> Optional[Any]: """simple docstring""" lowerCamelCase_: List[Any] = self.tokenizer(self.src_text , **A_ , padding=A_ , return_tensors="""tf""" ) lowerCamelCase_: str = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 , use_cache=A_ , ) lowerCamelCase_: Tuple = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=A_ ) return generated_words @slow def lowerCAmelCase ( self : Optional[int] ) -> List[str]: """simple docstring""" self._assert_generated_batch_equal_expected()
423
import math from collections import defaultdict from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput def UpperCAmelCase_ ( _UpperCAmelCase , _UpperCAmelCase=0.9_9_9 , _UpperCAmelCase="cosine" , ): if alpha_transform_type == "cosine": def alpha_bar_fn(_UpperCAmelCase ): return math.cos((t + 0.0_0_8) / 1.0_0_8 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(_UpperCAmelCase ): return math.exp(t * -1_2.0 ) else: raise ValueError(f"""Unsupported alpha_tranform_type: {alpha_transform_type}""" ) lowerCamelCase_: Union[str, Any] = [] for i in range(_UpperCAmelCase ): lowerCamelCase_: Tuple = i / num_diffusion_timesteps lowerCamelCase_: Optional[Any] = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(_UpperCAmelCase ) / alpha_bar_fn(_UpperCAmelCase ) , _UpperCAmelCase ) ) return torch.tensor(_UpperCAmelCase , dtype=torch.floataa ) class a__ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): _A = [e.name for e in KarrasDiffusionSchedulers] _A = 2 @register_to_config def __init__( self : int , A_ : int = 10_00 , A_ : float = 0.00085 , A_ : float = 0.012 , A_ : str = "linear" , A_ : Optional[Union[np.ndarray, List[float]]] = None , A_ : str = "epsilon" , A_ : str = "linspace" , A_ : int = 0 , ) -> Any: """simple docstring""" if trained_betas is not None: lowerCamelCase_: Dict = torch.tensor(A_ , dtype=torch.floataa ) elif beta_schedule == "linear": lowerCamelCase_: Tuple = torch.linspace(A_ , A_ , A_ , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. lowerCamelCase_: List[Any] = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , A_ , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule lowerCamelCase_: Tuple = betas_for_alpha_bar(A_ ) else: raise NotImplementedError(f"""{beta_schedule} does is not implemented for {self.__class__}""" ) lowerCamelCase_: str = 1.0 - self.betas lowerCamelCase_: Any = torch.cumprod(self.alphas , dim=0 ) # set all values self.set_timesteps(A_ , A_ , A_ ) def lowerCAmelCase ( self : List[Any] , A_ : str , A_ : Union[str, Any]=None ) -> int: """simple docstring""" if schedule_timesteps is None: lowerCamelCase_: Union[str, Any] = self.timesteps lowerCamelCase_: Tuple = (schedule_timesteps == timestep).nonzero() # The sigma index that is taken for the **very** first `step` # is always the second index (or the last index if there is only 1) # This way we can ensure we don't accidentally skip a sigma in # case we start in the middle of the denoising schedule (e.g. for image-to-image) if len(self._index_counter ) == 0: lowerCamelCase_: List[str] = 1 if len(A_ ) > 1 else 0 else: lowerCamelCase_: int = timestep.cpu().item() if torch.is_tensor(A_ ) else timestep lowerCamelCase_: List[Any] = self._index_counter[timestep_int] return indices[pos].item() @property def lowerCAmelCase ( self : Any ) -> int: """simple docstring""" # standard deviation of the initial noise distribution if self.config.timestep_spacing in ["linspace", "trailing"]: return self.sigmas.max() return (self.sigmas.max() ** 2 + 1) ** 0.5 def lowerCAmelCase ( self : int , A_ : torch.FloatTensor , A_ : Union[float, torch.FloatTensor] , ) -> torch.FloatTensor: """simple docstring""" lowerCamelCase_: List[Any] = self.index_for_timestep(A_ ) if self.state_in_first_order: lowerCamelCase_: List[Any] = self.sigmas[step_index] else: lowerCamelCase_: Optional[Any] = self.sigmas_interpol[step_index] lowerCamelCase_: Optional[int] = sample / ((sigma**2 + 1) ** 0.5) return sample def lowerCAmelCase ( self : Any , A_ : int , A_ : Union[str, torch.device] = None , A_ : Optional[int] = None , ) -> List[Any]: """simple docstring""" lowerCamelCase_: List[str] = num_inference_steps lowerCamelCase_: int = num_train_timesteps or self.config.num_train_timesteps # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891 if self.config.timestep_spacing == "linspace": lowerCamelCase_: int = np.linspace(0 , num_train_timesteps - 1 , A_ , dtype=A_ )[::-1].copy() elif self.config.timestep_spacing == "leading": lowerCamelCase_: Dict = num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 lowerCamelCase_: List[Any] = (np.arange(0 , A_ ) * step_ratio).round()[::-1].copy().astype(A_ ) timesteps += self.config.steps_offset elif self.config.timestep_spacing == "trailing": lowerCamelCase_: Optional[int] = num_train_timesteps / self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 lowerCamelCase_: Any = (np.arange(A_ , 0 , -step_ratio )).round().copy().astype(A_ ) timesteps -= 1 else: raise ValueError( f"""{self.config.timestep_spacing} is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'.""" ) lowerCamelCase_: Dict = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5 ) lowerCamelCase_: Any = torch.from_numpy(np.log(A_ ) ).to(A_ ) lowerCamelCase_: Union[str, Any] = np.interp(A_ , np.arange(0 , len(A_ ) ) , A_ ) lowerCamelCase_: List[str] = np.concatenate([sigmas, [0.0]] ).astype(np.floataa ) lowerCamelCase_: Tuple = torch.from_numpy(A_ ).to(device=A_ ) # interpolate sigmas lowerCamelCase_: List[Any] = sigmas.log().lerp(sigmas.roll(1 ).log() , 0.5 ).exp() lowerCamelCase_: List[Any] = torch.cat([sigmas[:1], sigmas[1:].repeat_interleave(2 ), sigmas[-1:]] ) lowerCamelCase_: int = torch.cat( [sigmas_interpol[:1], sigmas_interpol[1:].repeat_interleave(2 ), sigmas_interpol[-1:]] ) if str(A_ ).startswith("""mps""" ): # mps does not support float64 lowerCamelCase_: List[Any] = torch.from_numpy(A_ ).to(A_ , dtype=torch.floataa ) else: lowerCamelCase_: Union[str, Any] = torch.from_numpy(A_ ).to(A_ ) # interpolate timesteps lowerCamelCase_: Optional[int] = self.sigma_to_t(A_ ).to(A_ , dtype=timesteps.dtype ) lowerCamelCase_: Optional[int] = torch.stack((timesteps_interpol[1:-1, None], timesteps[1:, None]) , dim=-1 ).flatten() lowerCamelCase_: str = torch.cat([timesteps[:1], interleaved_timesteps] ) lowerCamelCase_: Tuple = None # for exp beta schedules, such as the one for `pipeline_shap_e.py` # we need an index counter lowerCamelCase_: List[str] = defaultdict(A_ ) def lowerCAmelCase ( self : Tuple , A_ : List[Any] ) -> Optional[Any]: """simple docstring""" # get log sigma lowerCamelCase_: List[Any] = sigma.log() # get distribution lowerCamelCase_: Union[str, Any] = log_sigma - self.log_sigmas[:, None] # get sigmas range lowerCamelCase_: Any = dists.ge(0 ).cumsum(dim=0 ).argmax(dim=0 ).clamp(max=self.log_sigmas.shape[0] - 2 ) lowerCamelCase_: int = low_idx + 1 lowerCamelCase_: Optional[Any] = self.log_sigmas[low_idx] lowerCamelCase_: Dict = self.log_sigmas[high_idx] # interpolate sigmas lowerCamelCase_: int = (low - log_sigma) / (low - high) lowerCamelCase_: Optional[int] = w.clamp(0 , 1 ) # transform interpolation to time range lowerCamelCase_: Any = (1 - w) * low_idx + w * high_idx lowerCamelCase_: Dict = t.view(sigma.shape ) return t @property def lowerCAmelCase ( self : Optional[Any] ) -> Union[str, Any]: """simple docstring""" return self.sample is None def lowerCAmelCase ( self : List[Any] , A_ : Union[torch.FloatTensor, np.ndarray] , A_ : Union[float, torch.FloatTensor] , A_ : Union[torch.FloatTensor, np.ndarray] , A_ : bool = True , ) -> Union[SchedulerOutput, Tuple]: """simple docstring""" lowerCamelCase_: int = self.index_for_timestep(A_ ) # advance index counter by 1 lowerCamelCase_: List[str] = timestep.cpu().item() if torch.is_tensor(A_ ) else timestep self._index_counter[timestep_int] += 1 if self.state_in_first_order: lowerCamelCase_: List[str] = self.sigmas[step_index] lowerCamelCase_: int = self.sigmas_interpol[step_index + 1] lowerCamelCase_: int = self.sigmas[step_index + 1] else: # 2nd order / KDPM2's method lowerCamelCase_: Union[str, Any] = self.sigmas[step_index - 1] lowerCamelCase_: List[Any] = self.sigmas_interpol[step_index] lowerCamelCase_: str = self.sigmas[step_index] # currently only gamma=0 is supported. This usually works best anyways. # We can support gamma in the future but then need to scale the timestep before # passing it to the model which requires a change in API lowerCamelCase_: List[str] = 0 lowerCamelCase_: int = sigma * (gamma + 1) # Note: sigma_hat == sigma for now # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise if self.config.prediction_type == "epsilon": lowerCamelCase_: str = sigma_hat if self.state_in_first_order else sigma_interpol lowerCamelCase_: int = sample - sigma_input * model_output elif self.config.prediction_type == "v_prediction": lowerCamelCase_: Tuple = sigma_hat if self.state_in_first_order else sigma_interpol lowerCamelCase_: Union[str, Any] = model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + ( sample / (sigma_input**2 + 1) ) elif self.config.prediction_type == "sample": raise NotImplementedError("""prediction_type not implemented yet: sample""" ) else: raise ValueError( f"""prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`""" ) if self.state_in_first_order: # 2. Convert to an ODE derivative for 1st order lowerCamelCase_: Optional[int] = (sample - pred_original_sample) / sigma_hat # 3. delta timestep lowerCamelCase_: Any = sigma_interpol - sigma_hat # store for 2nd order step lowerCamelCase_: str = sample else: # DPM-Solver-2 # 2. Convert to an ODE derivative for 2nd order lowerCamelCase_: Dict = (sample - pred_original_sample) / sigma_interpol # 3. delta timestep lowerCamelCase_: List[Any] = sigma_next - sigma_hat lowerCamelCase_: str = self.sample lowerCamelCase_: Tuple = None lowerCamelCase_: str = sample + derivative * dt if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=A_ ) def lowerCAmelCase ( self : Tuple , A_ : torch.FloatTensor , A_ : torch.FloatTensor , A_ : torch.FloatTensor , ) -> torch.FloatTensor: """simple docstring""" # Make sure sigmas and timesteps have the same device and dtype as original_samples lowerCamelCase_: List[str] = self.sigmas.to(device=original_samples.device , dtype=original_samples.dtype ) if original_samples.device.type == "mps" and torch.is_floating_point(A_ ): # mps does not support float64 lowerCamelCase_: int = self.timesteps.to(original_samples.device , dtype=torch.floataa ) lowerCamelCase_: Dict = timesteps.to(original_samples.device , dtype=torch.floataa ) else: lowerCamelCase_: int = self.timesteps.to(original_samples.device ) lowerCamelCase_: Dict = timesteps.to(original_samples.device ) lowerCamelCase_: Optional[Any] = [self.index_for_timestep(A_ , A_ ) for t in timesteps] lowerCamelCase_: Tuple = sigmas[step_indices].flatten() while len(sigma.shape ) < len(original_samples.shape ): lowerCamelCase_: List[Any] = sigma.unsqueeze(-1 ) lowerCamelCase_: List[Any] = original_samples + noise * sigma return noisy_samples def __len__( self : Union[str, Any] ) -> Optional[Any]: """simple docstring""" return self.config.num_train_timesteps
423
1
import unittest import numpy as np import torch from diffusers import DDIMPipeline, DDIMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow, torch_device from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class A__ ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): lowerCamelCase__ : Tuple =DDIMPipeline lowerCamelCase__ : List[Any] =UNCONDITIONAL_IMAGE_GENERATION_PARAMS lowerCamelCase__ : List[Any] =PipelineTesterMixin.required_optional_params - { "num_images_per_prompt", "latents", "callback", "callback_steps", } lowerCamelCase__ : List[Any] =UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS lowerCamelCase__ : List[Any] =False def lowercase ( self ) -> List[Any]: """simple docstring""" torch.manual_seed(0 ) __magic_name__ : Tuple = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=('''DownBlock2D''', '''AttnDownBlock2D''') , up_block_types=('''AttnUpBlock2D''', '''UpBlock2D''') , ) __magic_name__ : List[Any] = DDIMScheduler() __magic_name__ : Any = {'''unet''': unet, '''scheduler''': scheduler} return components def lowercase ( self , lowerCamelCase , lowerCamelCase=0 ) -> Tuple: """simple docstring""" if str(lowerCamelCase ).startswith('''mps''' ): __magic_name__ : List[str] = torch.manual_seed(lowerCamelCase ) else: __magic_name__ : Union[str, Any] = torch.Generator(device=lowerCamelCase ).manual_seed(lowerCamelCase ) __magic_name__ : List[Any] = { '''batch_size''': 1, '''generator''': generator, '''num_inference_steps''': 2, '''output_type''': '''numpy''', } return inputs def lowercase ( self ) -> Optional[int]: """simple docstring""" __magic_name__ : Optional[Any] = '''cpu''' __magic_name__ : str = self.get_dummy_components() __magic_name__ : Optional[Any] = self.pipeline_class(**lowerCamelCase ) pipe.to(lowerCamelCase ) pipe.set_progress_bar_config(disable=lowerCamelCase ) __magic_name__ : Optional[Any] = self.get_dummy_inputs(lowerCamelCase ) __magic_name__ : str = pipe(**lowerCamelCase ).images __magic_name__ : List[Any] = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 32, 32, 3) ) __magic_name__ : Optional[int] = np.array( [1.0_00e00, 5.7_17e-01, 4.7_17e-01, 1.0_00e00, 0.0_00e00, 1.0_00e00, 3.0_00e-04, 0.0_00e00, 9.0_00e-04] ) __magic_name__ : List[Any] = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(lowerCamelCase , 1e-3 ) def lowercase ( self ) -> Dict: """simple docstring""" super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3 ) def lowercase ( self ) -> int: """simple docstring""" super().test_save_load_local(expected_max_difference=3e-3 ) def lowercase ( self ) -> Any: """simple docstring""" super().test_save_load_optional_components(expected_max_difference=3e-3 ) def lowercase ( self ) -> Union[str, Any]: """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class A__ ( unittest.TestCase ): def lowercase ( self ) -> List[Any]: """simple docstring""" __magic_name__ : Union[str, Any] = '''google/ddpm-cifar10-32''' __magic_name__ : str = UNetaDModel.from_pretrained(lowerCamelCase ) __magic_name__ : Optional[Any] = DDIMScheduler() __magic_name__ : str = DDIMPipeline(unet=lowerCamelCase , scheduler=lowerCamelCase ) ddim.to(lowerCamelCase ) ddim.set_progress_bar_config(disable=lowerCamelCase ) __magic_name__ : Tuple = torch.manual_seed(0 ) __magic_name__ : List[str] = ddim(generator=lowerCamelCase , eta=0.0 , output_type='''numpy''' ).images __magic_name__ : Optional[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __magic_name__ : int = np.array([0.1_7_2_3, 0.1_6_1_7, 0.1_6_0_0, 0.1_6_2_6, 0.1_4_9_7, 0.1_5_1_3, 0.1_5_0_5, 0.1_4_4_2, 0.1_4_5_3] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def lowercase ( self ) -> Optional[Any]: """simple docstring""" __magic_name__ : List[str] = '''google/ddpm-ema-bedroom-256''' __magic_name__ : Any = UNetaDModel.from_pretrained(lowerCamelCase ) __magic_name__ : List[Any] = DDIMScheduler.from_pretrained(lowerCamelCase ) __magic_name__ : Dict = DDIMPipeline(unet=lowerCamelCase , scheduler=lowerCamelCase ) ddpm.to(lowerCamelCase ) ddpm.set_progress_bar_config(disable=lowerCamelCase ) __magic_name__ : Dict = torch.manual_seed(0 ) __magic_name__ : List[str] = ddpm(generator=lowerCamelCase , output_type='''numpy''' ).images __magic_name__ : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) __magic_name__ : Dict = np.array([0.0_0_6_0, 0.0_2_0_1, 0.0_3_4_4, 0.0_0_2_4, 0.0_0_1_8, 0.0_0_0_2, 0.0_0_2_2, 0.0_0_0_0, 0.0_0_6_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
336
from io import BytesIO from typing import List, Union import requests from ..utils import add_end_docstrings, is_decord_available, is_torch_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_decord_available(): import numpy as np from decord import VideoReader if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING lowercase_ = logging.get_logger(__name__) @add_end_docstrings(__SCREAMING_SNAKE_CASE ) class A__ ( __SCREAMING_SNAKE_CASE ): def __init__( self , *lowerCamelCase , **lowerCamelCase ) -> Dict: """simple docstring""" super().__init__(*lowerCamelCase , **lowerCamelCase ) requires_backends(self , '''decord''' ) self.check_model_type(lowerCamelCase ) def lowercase ( self , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase=None ) -> List[Any]: """simple docstring""" __magic_name__ : List[str] = {} if frame_sampling_rate is not None: __magic_name__ : Optional[int] = frame_sampling_rate if num_frames is not None: __magic_name__ : Optional[Any] = num_frames __magic_name__ : Union[str, Any] = {} if top_k is not None: __magic_name__ : Union[str, Any] = top_k return preprocess_params, {}, postprocess_params def __call__( self , lowerCamelCase , **lowerCamelCase ) -> List[Any]: """simple docstring""" return super().__call__(lowerCamelCase , **lowerCamelCase ) def lowercase ( self , lowerCamelCase , lowerCamelCase=None , lowerCamelCase=1 ) -> int: """simple docstring""" if num_frames is None: __magic_name__ : Any = self.model.config.num_frames if video.startswith('''http://''' ) or video.startswith('''https://''' ): __magic_name__ : str = BytesIO(requests.get(lowerCamelCase ).content ) __magic_name__ : Optional[int] = VideoReader(lowerCamelCase ) videoreader.seek(0 ) __magic_name__ : Union[str, Any] = 0 __magic_name__ : Tuple = num_frames * frame_sampling_rate - 1 __magic_name__ : Tuple = np.linspace(lowerCamelCase , lowerCamelCase , num=lowerCamelCase , dtype=np.intaa ) __magic_name__ : Union[str, Any] = videoreader.get_batch(lowerCamelCase ).asnumpy() __magic_name__ : List[str] = list(lowerCamelCase ) __magic_name__ : Tuple = self.image_processor(lowerCamelCase , return_tensors=self.framework ) return model_inputs def lowercase ( self , lowerCamelCase ) -> str: """simple docstring""" __magic_name__ : Union[str, Any] = self.model(**lowerCamelCase ) return model_outputs def lowercase ( self , lowerCamelCase , lowerCamelCase=5 ) -> Optional[Any]: """simple docstring""" if top_k > self.model.config.num_labels: __magic_name__ : Dict = self.model.config.num_labels if self.framework == "pt": __magic_name__ : Tuple = model_outputs.logits.softmax(-1 )[0] __magic_name__ , __magic_name__ : str = probs.topk(lowerCamelCase ) else: raise ValueError(F'''Unsupported framework: {self.framework}''' ) __magic_name__ : List[str] = scores.tolist() __magic_name__ : Tuple = ids.tolist() return [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(lowerCamelCase , lowerCamelCase )]
336
1
import gc import random import unittest import numpy as np import torch from PIL import Image from diffusers import ( DDIMScheduler, KandinskyVaaInpaintPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class _a ( A__ , unittest.TestCase ): """simple docstring""" snake_case =KandinskyVaaInpaintPipeline snake_case =["""image_embeds""", """negative_image_embeds""", """image""", """mask_image"""] snake_case =[ """image_embeds""", """negative_image_embeds""", """image""", """mask_image""", ] snake_case =[ """generator""", """height""", """width""", """latents""", """guidance_scale""", """num_inference_steps""", """return_dict""", """guidance_scale""", """num_images_per_prompt""", """output_type""", """return_dict""", ] snake_case =False @property def SCREAMING_SNAKE_CASE ( self ): return 32 @property def SCREAMING_SNAKE_CASE ( self ): return 32 @property def SCREAMING_SNAKE_CASE ( self ): return self.time_input_dim @property def SCREAMING_SNAKE_CASE ( self ): return self.time_input_dim * 4 @property def SCREAMING_SNAKE_CASE ( self ): return 100 @property def SCREAMING_SNAKE_CASE ( self ): torch.manual_seed(0 ) _UpperCAmelCase ={ "in_channels": 9, # Out channels is double in channels because predicts mean and variance "out_channels": 8, "addition_embed_type": "image", "down_block_types": ("ResnetDownsampleBlock2D", "SimpleCrossAttnDownBlock2D"), "up_block_types": ("SimpleCrossAttnUpBlock2D", "ResnetUpsampleBlock2D"), "mid_block_type": "UNetMidBlock2DSimpleCrossAttn", "block_out_channels": (self.block_out_channels_a, self.block_out_channels_a * 2), "layers_per_block": 1, "encoder_hid_dim": self.text_embedder_hidden_size, "encoder_hid_dim_type": "image_proj", "cross_attention_dim": self.cross_attention_dim, "attention_head_dim": 4, "resnet_time_scale_shift": "scale_shift", "class_embed_type": None, } _UpperCAmelCase =UNetaDConditionModel(**_snake_case ) return model @property def SCREAMING_SNAKE_CASE ( self ): return { "block_out_channels": [32, 64], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def SCREAMING_SNAKE_CASE ( self ): torch.manual_seed(0 ) _UpperCAmelCase =VQModel(**self.dummy_movq_kwargs ) return model def SCREAMING_SNAKE_CASE ( self ): _UpperCAmelCase =self.dummy_unet _UpperCAmelCase =self.dummy_movq _UpperCAmelCase =DDIMScheduler( num_train_timesteps=1000 , beta_schedule="linear" , beta_start=0.00_085 , beta_end=0.012 , clip_sample=_snake_case , set_alpha_to_one=_snake_case , steps_offset=1 , prediction_type="epsilon" , thresholding=_snake_case , ) _UpperCAmelCase ={ "unet": unet, "scheduler": scheduler, "movq": movq, } return components def SCREAMING_SNAKE_CASE ( self , _snake_case , _snake_case=0 ): _UpperCAmelCase =floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(_snake_case ) ).to(_snake_case ) _UpperCAmelCase =floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( _snake_case ) # create init_image _UpperCAmelCase =floats_tensor((1, 3, 64, 64) , rng=random.Random(_snake_case ) ).to(_snake_case ) _UpperCAmelCase =image.cpu().permute(0 , 2 , 3 , 1 )[0] _UpperCAmelCase =Image.fromarray(np.uinta(_snake_case ) ).convert("RGB" ).resize((256, 256) ) # create mask _UpperCAmelCase =np.ones((64, 64) , dtype=np.floataa ) _UpperCAmelCase =0 if str(_snake_case ).startswith("mps" ): _UpperCAmelCase =torch.manual_seed(_snake_case ) else: _UpperCAmelCase =torch.Generator(device=_snake_case ).manual_seed(_snake_case ) _UpperCAmelCase ={ "image": init_image, "mask_image": mask, "image_embeds": image_embeds, "negative_image_embeds": negative_image_embeds, "generator": generator, "height": 64, "width": 64, "num_inference_steps": 2, "guidance_scale": 4.0, "output_type": "np", } return inputs def SCREAMING_SNAKE_CASE ( self ): _UpperCAmelCase ="cpu" _UpperCAmelCase =self.get_dummy_components() _UpperCAmelCase =self.pipeline_class(**_snake_case ) _UpperCAmelCase =pipe.to(_snake_case ) pipe.set_progress_bar_config(disable=_snake_case ) _UpperCAmelCase =pipe(**self.get_dummy_inputs(_snake_case ) ) _UpperCAmelCase =output.images _UpperCAmelCase =pipe( **self.get_dummy_inputs(_snake_case ) , return_dict=_snake_case , )[0] _UpperCAmelCase =image[0, -3:, -3:, -1] _UpperCAmelCase =image_from_tuple[0, -3:, -3:, -1] print(F"image.shape {image.shape}" ) assert image.shape == (1, 64, 64, 3) _UpperCAmelCase =np.array( [0.50_775_903, 0.49_527_195, 0.48_824_543, 0.50_192_237, 0.48_644_906, 0.49_373_814, 0.4_780_598, 0.47_234_827, 0.48_327_848] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 ), F" expected_slice {expected_slice}, but got {image_slice.flatten()}" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 ), F" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}" def SCREAMING_SNAKE_CASE ( self ): super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class _a ( unittest.TestCase ): """simple docstring""" def SCREAMING_SNAKE_CASE ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE ( self ): _UpperCAmelCase =load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/kandinskyv22/kandinskyv22_inpaint_cat_with_hat_fp16.npy" ) _UpperCAmelCase =load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/kandinsky/cat.png" ) _UpperCAmelCase =np.ones((768, 768) , dtype=np.floataa ) _UpperCAmelCase =0 _UpperCAmelCase ="a hat" _UpperCAmelCase =KandinskyVaaPriorPipeline.from_pretrained( "kandinsky-community/kandinsky-2-2-prior" , torch_dtype=torch.floataa ) pipe_prior.to(_snake_case ) _UpperCAmelCase =KandinskyVaaInpaintPipeline.from_pretrained( "kandinsky-community/kandinsky-2-2-decoder-inpaint" , torch_dtype=torch.floataa ) _UpperCAmelCase =pipeline.to(_snake_case ) pipeline.set_progress_bar_config(disable=_snake_case ) _UpperCAmelCase =torch.Generator(device="cpu" ).manual_seed(0 ) _UpperCAmelCase , _UpperCAmelCase =pipe_prior( _snake_case , generator=_snake_case , num_inference_steps=5 , negative_prompt="" , ).to_tuple() _UpperCAmelCase =pipeline( image=_snake_case , mask_image=_snake_case , image_embeds=_snake_case , negative_image_embeds=_snake_case , generator=_snake_case , num_inference_steps=100 , height=768 , width=768 , output_type="np" , ) _UpperCAmelCase =output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(_snake_case , _snake_case )
408
from ....configuration_utils import PretrainedConfig from ....utils import logging snake_case__ : List[str] = logging.get_logger(__name__) # TODO: upload to AWS snake_case__ : str = { 'yjernite/retribert-base-uncased': ( 'https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/config.json' ), } class _a ( A__ ): """simple docstring""" snake_case ="""retribert""" def __init__( self , _snake_case=3_0522 , _snake_case=768 , _snake_case=8 , _snake_case=12 , _snake_case=3072 , _snake_case="gelu" , _snake_case=0.1 , _snake_case=0.1 , _snake_case=512 , _snake_case=2 , _snake_case=0.02 , _snake_case=1E-1_2 , _snake_case=True , _snake_case=128 , _snake_case=0 , **_snake_case , ): super().__init__(pad_token_id=_snake_case , **_snake_case ) _UpperCAmelCase =vocab_size _UpperCAmelCase =hidden_size _UpperCAmelCase =num_hidden_layers _UpperCAmelCase =num_attention_heads _UpperCAmelCase =hidden_act _UpperCAmelCase =intermediate_size _UpperCAmelCase =hidden_dropout_prob _UpperCAmelCase =attention_probs_dropout_prob _UpperCAmelCase =max_position_embeddings _UpperCAmelCase =type_vocab_size _UpperCAmelCase =initializer_range _UpperCAmelCase =layer_norm_eps _UpperCAmelCase =share_encoders _UpperCAmelCase =projection_dim
408
1
'''simple docstring''' import importlib import json import os from collections import OrderedDict from typing import Dict, Optional, Union # Build the list of all feature extractors from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code from ...feature_extraction_utils import FeatureExtractionMixin from ...utils import CONFIG_NAME, FEATURE_EXTRACTOR_NAME, get_file_from_repo, logging from .auto_factory import _LazyAutoMapping from .configuration_auto import ( CONFIG_MAPPING_NAMES, AutoConfig, model_type_to_module_name, replace_list_option_in_docstrings, ) A__ = logging.get_logger(__name__) A__ = OrderedDict( [ ("audio-spectrogram-transformer", "ASTFeatureExtractor"), ("beit", "BeitFeatureExtractor"), ("chinese_clip", "ChineseCLIPFeatureExtractor"), ("clap", "ClapFeatureExtractor"), ("clip", "CLIPFeatureExtractor"), ("clipseg", "ViTFeatureExtractor"), ("conditional_detr", "ConditionalDetrFeatureExtractor"), ("convnext", "ConvNextFeatureExtractor"), ("cvt", "ConvNextFeatureExtractor"), ("data2vec-audio", "Wav2Vec2FeatureExtractor"), ("data2vec-vision", "BeitFeatureExtractor"), ("deformable_detr", "DeformableDetrFeatureExtractor"), ("deit", "DeiTFeatureExtractor"), ("detr", "DetrFeatureExtractor"), ("dinat", "ViTFeatureExtractor"), ("donut-swin", "DonutFeatureExtractor"), ("dpt", "DPTFeatureExtractor"), ("encodec", "EncodecFeatureExtractor"), ("flava", "FlavaFeatureExtractor"), ("glpn", "GLPNFeatureExtractor"), ("groupvit", "CLIPFeatureExtractor"), ("hubert", "Wav2Vec2FeatureExtractor"), ("imagegpt", "ImageGPTFeatureExtractor"), ("layoutlmv2", "LayoutLMv2FeatureExtractor"), ("layoutlmv3", "LayoutLMv3FeatureExtractor"), ("levit", "LevitFeatureExtractor"), ("maskformer", "MaskFormerFeatureExtractor"), ("mctct", "MCTCTFeatureExtractor"), ("mobilenet_v1", "MobileNetV1FeatureExtractor"), ("mobilenet_v2", "MobileNetV2FeatureExtractor"), ("mobilevit", "MobileViTFeatureExtractor"), ("nat", "ViTFeatureExtractor"), ("owlvit", "OwlViTFeatureExtractor"), ("perceiver", "PerceiverFeatureExtractor"), ("poolformer", "PoolFormerFeatureExtractor"), ("regnet", "ConvNextFeatureExtractor"), ("resnet", "ConvNextFeatureExtractor"), ("segformer", "SegformerFeatureExtractor"), ("sew", "Wav2Vec2FeatureExtractor"), ("sew-d", "Wav2Vec2FeatureExtractor"), ("speech_to_text", "Speech2TextFeatureExtractor"), ("speecht5", "SpeechT5FeatureExtractor"), ("swiftformer", "ViTFeatureExtractor"), ("swin", "ViTFeatureExtractor"), ("swinv2", "ViTFeatureExtractor"), ("table-transformer", "DetrFeatureExtractor"), ("timesformer", "VideoMAEFeatureExtractor"), ("tvlt", "TvltFeatureExtractor"), ("unispeech", "Wav2Vec2FeatureExtractor"), ("unispeech-sat", "Wav2Vec2FeatureExtractor"), ("van", "ConvNextFeatureExtractor"), ("videomae", "VideoMAEFeatureExtractor"), ("vilt", "ViltFeatureExtractor"), ("vit", "ViTFeatureExtractor"), ("vit_mae", "ViTFeatureExtractor"), ("vit_msn", "ViTFeatureExtractor"), ("wav2vec2", "Wav2Vec2FeatureExtractor"), ("wav2vec2-conformer", "Wav2Vec2FeatureExtractor"), ("wavlm", "Wav2Vec2FeatureExtractor"), ("whisper", "WhisperFeatureExtractor"), ("xclip", "CLIPFeatureExtractor"), ("yolos", "YolosFeatureExtractor"), ] ) A__ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FEATURE_EXTRACTOR_MAPPING_NAMES) def _lowercase ( a_ : str ) -> Tuple: '''simple docstring''' for module_name, extractors in FEATURE_EXTRACTOR_MAPPING_NAMES.items(): if class_name in extractors: __magic_name__ = model_type_to_module_name(a_ ) __magic_name__ = importlib.import_module(F'.{module_name}' ,'transformers.models' ) try: return getattr(a_ ,a_ ) except AttributeError: continue for _, extractor in FEATURE_EXTRACTOR_MAPPING._extra_content.items(): if getattr(a_ ,'__name__' ,a_ ) == class_name: return extractor # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main # init and we return the proper dummy to get an appropriate error message. __magic_name__ = importlib.import_module('transformers' ) if hasattr(a_ ,a_ ): return getattr(a_ ,a_ ) return None def _lowercase ( a_ : Union[str, os.PathLike] ,a_ : Optional[Union[str, os.PathLike]] = None ,a_ : bool = False ,a_ : bool = False ,a_ : Optional[Dict[str, str]] = None ,a_ : Optional[Union[bool, str]] = None ,a_ : Optional[str] = None ,a_ : bool = False ,**a_ : Tuple ,) -> List[str]: '''simple docstring''' __magic_name__ = get_file_from_repo( a_ ,a_ ,cache_dir=a_ ,force_download=a_ ,resume_download=a_ ,proxies=a_ ,use_auth_token=a_ ,revision=a_ ,local_files_only=a_ ,) if resolved_config_file is None: logger.info( 'Could not locate the feature extractor configuration file, will try to use the model config instead.' ) return {} with open(a_ ,encoding='utf-8' ) as reader: return json.load(a_ ) class __UpperCamelCase : def __init__( self: int ): '''simple docstring''' raise EnvironmentError( 'AutoFeatureExtractor is designed to be instantiated ' 'using the `AutoFeatureExtractor.from_pretrained(pretrained_model_name_or_path)` method.' ) @classmethod @replace_list_option_in_docstrings(__UpperCamelCase ) def _SCREAMING_SNAKE_CASE ( cls: str , __UpperCamelCase: int , **__UpperCamelCase: List[str] ): '''simple docstring''' __magic_name__ = kwargs.pop('config' , __UpperCamelCase ) __magic_name__ = kwargs.pop('trust_remote_code' , __UpperCamelCase ) __magic_name__ = True __magic_name__, __magic_name__ = FeatureExtractionMixin.get_feature_extractor_dict(__UpperCamelCase , **__UpperCamelCase ) __magic_name__ = config_dict.get('feature_extractor_type' , __UpperCamelCase ) __magic_name__ = None if "AutoFeatureExtractor" in config_dict.get('auto_map' , {} ): __magic_name__ = config_dict['auto_map']['AutoFeatureExtractor'] # If we don't find the feature extractor class in the feature extractor config, let's try the model config. if feature_extractor_class is None and feature_extractor_auto_map is None: if not isinstance(__UpperCamelCase , __UpperCamelCase ): __magic_name__ = AutoConfig.from_pretrained(__UpperCamelCase , **__UpperCamelCase ) # It could be in `config.feature_extractor_type`` __magic_name__ = getattr(__UpperCamelCase , 'feature_extractor_type' , __UpperCamelCase ) if hasattr(__UpperCamelCase , 'auto_map' ) and "AutoFeatureExtractor" in config.auto_map: __magic_name__ = config.auto_map['AutoFeatureExtractor'] if feature_extractor_class is not None: __magic_name__ = feature_extractor_class_from_name(__UpperCamelCase ) __magic_name__ = feature_extractor_auto_map is not None __magic_name__ = feature_extractor_class is not None or type(__UpperCamelCase ) in FEATURE_EXTRACTOR_MAPPING __magic_name__ = resolve_trust_remote_code( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) if has_remote_code and trust_remote_code: __magic_name__ = get_class_from_dynamic_module( __UpperCamelCase , __UpperCamelCase , **__UpperCamelCase ) __magic_name__ = kwargs.pop('code_revision' , __UpperCamelCase ) if os.path.isdir(__UpperCamelCase ): feature_extractor_class.register_for_auto_class() return feature_extractor_class.from_dict(__UpperCamelCase , **__UpperCamelCase ) elif feature_extractor_class is not None: return feature_extractor_class.from_dict(__UpperCamelCase , **__UpperCamelCase ) # Last try: we use the FEATURE_EXTRACTOR_MAPPING. elif type(__UpperCamelCase ) in FEATURE_EXTRACTOR_MAPPING: __magic_name__ = FEATURE_EXTRACTOR_MAPPING[type(__UpperCamelCase )] return feature_extractor_class.from_dict(__UpperCamelCase , **__UpperCamelCase ) raise ValueError( F'Unrecognized feature extractor in {pretrained_model_name_or_path}. Should have a ' F'`feature_extractor_type` key in its {FEATURE_EXTRACTOR_NAME} of {CONFIG_NAME}, or one of the following ' F'`model_type` keys in its {CONFIG_NAME}: {", ".join(c for c in FEATURE_EXTRACTOR_MAPPING_NAMES.keys() )}' ) @staticmethod def _SCREAMING_SNAKE_CASE ( __UpperCamelCase: int , __UpperCamelCase: Optional[Any] ): '''simple docstring''' FEATURE_EXTRACTOR_MAPPING.register(__UpperCamelCase , __UpperCamelCase )
710
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__ = { "camembert-base": "https://huggingface.co/camembert-base/resolve/main/config.json", "umberto-commoncrawl-cased-v1": ( "https://huggingface.co/Musixmatch/umberto-commoncrawl-cased-v1/resolve/main/config.json" ), "umberto-wikipedia-uncased-v1": ( "https://huggingface.co/Musixmatch/umberto-wikipedia-uncased-v1/resolve/main/config.json" ), } class __UpperCamelCase ( SCREAMING_SNAKE_CASE ): _lowercase : Optional[int] = "camembert" def __init__( self: Optional[Any] , __UpperCamelCase: Any=3_05_22 , __UpperCamelCase: Tuple=7_68 , __UpperCamelCase: str=12 , __UpperCamelCase: Optional[int]=12 , __UpperCamelCase: List[str]=30_72 , __UpperCamelCase: Any="gelu" , __UpperCamelCase: Optional[int]=0.1 , __UpperCamelCase: Any=0.1 , __UpperCamelCase: str=5_12 , __UpperCamelCase: Dict=2 , __UpperCamelCase: str=0.02 , __UpperCamelCase: List[Any]=1E-12 , __UpperCamelCase: List[Any]=1 , __UpperCamelCase: Any=0 , __UpperCamelCase: Union[str, Any]=2 , __UpperCamelCase: Dict="absolute" , __UpperCamelCase: Any=True , __UpperCamelCase: Any=None , **__UpperCamelCase: Union[str, Any] , ): '''simple docstring''' super().__init__(pad_token_id=__UpperCamelCase , bos_token_id=__UpperCamelCase , eos_token_id=__UpperCamelCase , **__UpperCamelCase ) __magic_name__ = vocab_size __magic_name__ = hidden_size __magic_name__ = num_hidden_layers __magic_name__ = num_attention_heads __magic_name__ = hidden_act __magic_name__ = intermediate_size __magic_name__ = hidden_dropout_prob __magic_name__ = attention_probs_dropout_prob __magic_name__ = max_position_embeddings __magic_name__ = type_vocab_size __magic_name__ = initializer_range __magic_name__ = layer_norm_eps __magic_name__ = position_embedding_type __magic_name__ = use_cache __magic_name__ = classifier_dropout class __UpperCamelCase ( SCREAMING_SNAKE_CASE ): @property def _SCREAMING_SNAKE_CASE ( self: Dict ): '''simple docstring''' if self.task == "multiple-choice": __magic_name__ = {0: 'batch', 1: 'choice', 2: 'sequence'} else: __magic_name__ = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
184
0
from argparse import ArgumentParser from ..pipelines import Pipeline, PipelineDataFormat, get_supported_tasks, pipeline from ..utils import logging from . import BaseTransformersCLICommand __lowerCamelCase : Any = logging.get_logger(__name__) # pylint: disable=invalid-name def SCREAMING_SNAKE_CASE ( snake_case_ : str ): if not path: return "pipe" for ext in PipelineDataFormat.SUPPORTED_FORMATS: if path.endswith(lowerCAmelCase__ ): return ext raise Exception( F'''Unable to determine file format from file extension {path}. ''' F'''Please provide the format through --format {PipelineDataFormat.SUPPORTED_FORMATS}''' ) def SCREAMING_SNAKE_CASE ( snake_case_ : Optional[Any] ): snake_case__ : List[Any] = pipeline( task=args.task , model=args.model if args.model else None , config=args.config , tokenizer=args.tokenizer , device=args.device , ) snake_case__ : Union[str, Any] = try_infer_format_from_ext(args.input ) if args.format == "infer" else args.format snake_case__ : Any = PipelineDataFormat.from_str( format=lowerCAmelCase__ , output_path=args.output , input_path=args.input , column=args.column if args.column else nlp.default_input_names , overwrite=args.overwrite , ) return RunCommand(lowerCAmelCase__ , lowerCAmelCase__ ) class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ): """simple docstring""" def __init__( self : int , __A : Pipeline , __A : PipelineDataFormat ): snake_case__ : List[Any] = nlp snake_case__ : str = reader @staticmethod def _lowercase ( __A : ArgumentParser ): snake_case__ : List[str] = parser.add_parser("run" , help="Run a pipeline through the CLI" ) run_parser.add_argument("--task" , choices=get_supported_tasks() , help="Task to run" ) run_parser.add_argument("--input" , type=a_ , help="Path to the file to use for inference" ) run_parser.add_argument("--output" , type=a_ , help="Path to the file that will be used post to write results." ) run_parser.add_argument("--model" , type=a_ , help="Name or path to the model to instantiate." ) run_parser.add_argument("--config" , type=a_ , help="Name or path to the model's config to instantiate." ) run_parser.add_argument( "--tokenizer" , type=a_ , help="Name of the tokenizer to use. (default: same as the model name)" ) run_parser.add_argument( "--column" , type=a_ , help="Name of the column to use as input. (For multi columns input as QA use column1,columns2)" , ) run_parser.add_argument( "--format" , type=a_ , default="infer" , choices=PipelineDataFormat.SUPPORTED_FORMATS , help="Input format to read from" , ) run_parser.add_argument( "--device" , type=a_ , default=-1 , help="Indicate the device to run onto, -1 indicates CPU, >= 0 indicates GPU (default: -1)" , ) run_parser.add_argument("--overwrite" , action="store_true" , help="Allow overwriting the output file." ) run_parser.set_defaults(func=a_ ) def _lowercase ( self : int ): snake_case__ : Tuple = self._nlp, [] for entry in self._reader: snake_case__ : str = nlp(**a_ ) if self._reader.is_multi_columns else nlp(a_ ) if isinstance(a_ , a_ ): outputs.append(a_ ) else: outputs += output # Saving data if self._nlp.binary_output: snake_case__ : Tuple = self._reader.save_binary(a_ ) logger.warning(f'''Current pipeline requires output to be in binary format, saving at {binary_path}''' ) else: self._reader.save(a_ )
297
"""simple docstring""" __UpperCAmelCase = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0], ] def lowercase__ ( lowerCAmelCase__ : Dict , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : List[str] , lowerCAmelCase__ : Tuple ) -> Dict: '''simple docstring''' # Return True if there is node that has not iterated. a__ : int = [False] * len(lowerCAmelCase__ ) a__ : Optional[Any] = [s] a__ : Optional[int] = True while queue: a__ : Any = queue.pop(0 ) for ind in range(len(graph[u] ) ): if visited[ind] is False and graph[u][ind] > 0: queue.append(lowerCAmelCase__ ) a__ : Any = True a__ : Union[str, Any] = u return visited[t] def lowercase__ ( lowerCAmelCase__ : List[str] , lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : Optional[Any] ) -> Any: '''simple docstring''' a__ : Any = [-1] * (len(lowerCAmelCase__ )) a__ : Any = 0 a__ : List[str] = [] a__ : Tuple = [i[:] for i in graph] # Record original cut, copy. while bfs(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ): a__ : Any = float("Inf" ) a__ : Optional[int] = sink while s != source: # Find the minimum value in select path a__ : Union[str, Any] = min(lowerCAmelCase__ , graph[parent[s]][s] ) a__ : List[str] = parent[s] max_flow += path_flow a__ : List[str] = sink while v != source: a__ : int = parent[v] graph[u][v] -= path_flow graph[v][u] += path_flow a__ : List[str] = parent[v] for i in range(len(lowerCAmelCase__ ) ): for j in range(len(graph[0] ) ): if graph[i][j] == 0 and temp[i][j] > 0: res.append((i, j) ) return res if __name__ == "__main__": print(mincut(test_graph, source=0, sink=5))
642
0
"""simple docstring""" import argparse import json from collections import OrderedDict import torch from huggingface_hub import cached_download, hf_hub_url from transformers import AutoImageProcessor, CvtConfig, CvtForImageClassification def _snake_case ( lowerCamelCase__ : Optional[int] ) -> List[str]: lowerCamelCase_ : Dict =[] embed.append( ( F"""cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.weight""", F"""stage{idx}.patch_embed.proj.weight""", ) ) embed.append( ( F"""cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.bias""", F"""stage{idx}.patch_embed.proj.bias""", ) ) embed.append( ( F"""cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.weight""", F"""stage{idx}.patch_embed.norm.weight""", ) ) embed.append( ( F"""cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.bias""", F"""stage{idx}.patch_embed.norm.bias""", ) ) return embed def _snake_case ( lowerCamelCase__ : Tuple , lowerCamelCase__ : Dict ) -> List[str]: lowerCamelCase_ : str =[] attention_weights.append( ( F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.convolution.weight""", F"""stage{idx}.blocks.{cnt}.attn.conv_proj_q.conv.weight""", ) ) attention_weights.append( ( F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.weight""", F"""stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.weight""", ) ) attention_weights.append( ( F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.bias""", F"""stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.bias""", ) ) attention_weights.append( ( F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_mean""", F"""stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_mean""", ) ) attention_weights.append( ( F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_var""", F"""stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_var""", ) ) attention_weights.append( ( F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.num_batches_tracked""", F"""stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.num_batches_tracked""", ) ) attention_weights.append( ( F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.convolution.weight""", F"""stage{idx}.blocks.{cnt}.attn.conv_proj_k.conv.weight""", ) ) attention_weights.append( ( F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.weight""", F"""stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.weight""", ) ) attention_weights.append( ( F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.bias""", F"""stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.bias""", ) ) attention_weights.append( ( F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_mean""", F"""stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_mean""", ) ) attention_weights.append( ( F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_var""", F"""stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_var""", ) ) attention_weights.append( ( F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.num_batches_tracked""", F"""stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.num_batches_tracked""", ) ) attention_weights.append( ( F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.convolution.weight""", F"""stage{idx}.blocks.{cnt}.attn.conv_proj_v.conv.weight""", ) ) attention_weights.append( ( F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.weight""", F"""stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.weight""", ) ) attention_weights.append( ( F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.bias""", F"""stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.bias""", ) ) attention_weights.append( ( F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_mean""", F"""stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_mean""", ) ) attention_weights.append( ( F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_var""", F"""stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_var""", ) ) attention_weights.append( ( F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.num_batches_tracked""", F"""stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.num_batches_tracked""", ) ) attention_weights.append( ( F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.weight""", F"""stage{idx}.blocks.{cnt}.attn.proj_q.weight""", ) ) attention_weights.append( ( F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.bias""", F"""stage{idx}.blocks.{cnt}.attn.proj_q.bias""", ) ) attention_weights.append( ( F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.weight""", F"""stage{idx}.blocks.{cnt}.attn.proj_k.weight""", ) ) attention_weights.append( ( F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.bias""", F"""stage{idx}.blocks.{cnt}.attn.proj_k.bias""", ) ) attention_weights.append( ( F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.weight""", F"""stage{idx}.blocks.{cnt}.attn.proj_v.weight""", ) ) attention_weights.append( ( F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.bias""", F"""stage{idx}.blocks.{cnt}.attn.proj_v.bias""", ) ) attention_weights.append( ( F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.weight""", F"""stage{idx}.blocks.{cnt}.attn.proj.weight""", ) ) attention_weights.append( ( F"""cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.bias""", F"""stage{idx}.blocks.{cnt}.attn.proj.bias""", ) ) attention_weights.append( (F"""cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.weight""", F"""stage{idx}.blocks.{cnt}.mlp.fc1.weight""") ) attention_weights.append( (F"""cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.bias""", F"""stage{idx}.blocks.{cnt}.mlp.fc1.bias""") ) attention_weights.append( (F"""cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.weight""", F"""stage{idx}.blocks.{cnt}.mlp.fc2.weight""") ) attention_weights.append( (F"""cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.bias""", F"""stage{idx}.blocks.{cnt}.mlp.fc2.bias""") ) attention_weights.append( (F"""cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.weight""", F"""stage{idx}.blocks.{cnt}.norm1.weight""") ) attention_weights.append( (F"""cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.bias""", F"""stage{idx}.blocks.{cnt}.norm1.bias""") ) attention_weights.append( (F"""cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.weight""", F"""stage{idx}.blocks.{cnt}.norm2.weight""") ) attention_weights.append( (F"""cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.bias""", F"""stage{idx}.blocks.{cnt}.norm2.bias""") ) return attention_weights def _snake_case ( lowerCamelCase__ : Union[str, Any] ) -> Optional[Any]: lowerCamelCase_ : int =[] token.append((F"""cvt.encoder.stages.{idx}.cls_token""", "stage2.cls_token") ) return token def _snake_case ( ) -> Optional[int]: lowerCamelCase_ : int =[] head.append(("layernorm.weight", "norm.weight") ) head.append(("layernorm.bias", "norm.bias") ) head.append(("classifier.weight", "head.weight") ) head.append(("classifier.bias", "head.bias") ) return head def _snake_case ( lowerCamelCase__ : Optional[int] , lowerCamelCase__ : int , lowerCamelCase__ : List[Any] , lowerCamelCase__ : Dict ) -> Tuple: lowerCamelCase_ : Tuple ='imagenet-1k-id2label.json' lowerCamelCase_ : str =1_000 lowerCamelCase_ : Optional[int] ='huggingface/label-files' lowerCamelCase_ : List[str] =num_labels lowerCamelCase_ : List[Any] =json.load(open(cached_download(hf_hub_url(__lowercase , __lowercase , repo_type="dataset" ) ) , "r" ) ) lowerCamelCase_ : Union[str, Any] ={int(__lowercase ): v for k, v in idalabel.items()} lowerCamelCase_ : str =idalabel lowerCamelCase_ : List[Any] ={v: k for k, v in idalabel.items()} lowerCamelCase_ : Tuple =CvtConfig(num_labels=__lowercase , idalabel=__lowercase , labelaid=__lowercase ) # For depth size 13 (13 = 1+2+10) if cvt_model.rsplit("/" , 1 )[-1][4:6] == "13": lowerCamelCase_ : str =[1, 2, 10] # For depth size 21 (21 = 1+4+16) elif cvt_model.rsplit("/" , 1 )[-1][4:6] == "21": lowerCamelCase_ : Dict =[1, 4, 16] # For wide cvt (similar to wide-resnet) depth size 24 (w24 = 2 + 2 20) else: lowerCamelCase_ : Tuple =[2, 2, 20] lowerCamelCase_ : Optional[Any] =[3, 12, 16] lowerCamelCase_ : Dict =[192, 768, 1_024] lowerCamelCase_ : Dict =CvtForImageClassification(__lowercase ) lowerCamelCase_ : List[Any] =AutoImageProcessor.from_pretrained("facebook/convnext-base-224-22k-1k" ) lowerCamelCase_ : Dict =image_size lowerCamelCase_ : Tuple =torch.load(__lowercase , map_location=torch.device("cpu" ) ) lowerCamelCase_ : List[Any] =OrderedDict() lowerCamelCase_ : Optional[Any] =[] for idx in range(len(config.depth ) ): if config.cls_token[idx]: lowerCamelCase_ : str =list_of_state_dict + cls_token(__lowercase ) lowerCamelCase_ : Optional[int] =list_of_state_dict + embeddings(__lowercase ) for cnt in range(config.depth[idx] ): lowerCamelCase_ : Dict =list_of_state_dict + attention(__lowercase , __lowercase ) lowerCamelCase_ : str =list_of_state_dict + final() for gg in list_of_state_dict: print(__lowercase ) for i in range(len(__lowercase ) ): lowerCamelCase_ : List[str] =original_weights[list_of_state_dict[i][1]] model.load_state_dict(__lowercase ) model.save_pretrained(__lowercase ) image_processor.save_pretrained(__lowercase ) # Download the weights from zoo: https://1drv.ms/u/s!AhIXJn_J-blW9RzF3rMW7SsLHa8h?e=blQ0Al if __name__ == "__main__": A__ : str = argparse.ArgumentParser() parser.add_argument( '--cvt_model', default='cvt-w24', type=str, help='Name of the cvt model you\'d like to convert.', ) parser.add_argument( '--image_size', default=384, type=int, help='Input Image Size', ) parser.add_argument( '--cvt_file_name', default=r'cvtmodels\CvT-w24-384x384-IN-22k.pth', type=str, help='Input Image Size', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) A__ : List[Any] = parser.parse_args() convert_cvt_checkpoint(args.cvt_model, args.image_size, args.cvt_file_name, args.pytorch_dump_folder_path)
704
"""simple docstring""" def _snake_case ( lowerCamelCase__ : str ) -> list: lowerCamelCase_ : Union[str, Any] =[0] * len(lowerCamelCase__ ) for i in range(1 , len(lowerCamelCase__ ) ): # use last results for better performance - dynamic programming lowerCamelCase_ : List[str] =prefix_result[i - 1] while j > 0 and input_string[i] != input_string[j]: lowerCamelCase_ : List[str] =prefix_result[j - 1] if input_string[i] == input_string[j]: j += 1 lowerCamelCase_ : str =j return prefix_result def _snake_case ( lowerCamelCase__ : str ) -> int: return max(prefix_function(lowerCamelCase__ ) ) if __name__ == "__main__": import doctest doctest.testmod()
244
0
'''simple docstring''' def lowerCamelCase ( ): '''simple docstring''' return [list(range(1_000 - i ,-1_000 - i ,-1 ) ) for i in range(1_000 )] SCREAMING_SNAKE_CASE__ = generate_large_matrix() SCREAMING_SNAKE_CASE__ = ( [[4, 3, 2, -1], [3, 2, 1, -1], [1, 1, -1, -2], [-1, -1, -2, -3]], [[3, 2], [1, 0]], [[7, 7, 6]], [[7, 7, 6], [-1, -2, -3]], grid, ) def lowerCamelCase ( _snake_case : list[list[int]] ): '''simple docstring''' assert all(row == sorted(_snake_case ,reverse=_snake_case ) for row in grid ) assert all(list(_snake_case ) == sorted(_snake_case ,reverse=_snake_case ) for col in zip(*_snake_case ) ) def lowerCamelCase ( _snake_case : list[int] ): '''simple docstring''' lowercase__ = 0 lowercase__ = len(_snake_case ) - 1 # Edge cases such as no values or all numbers are negative. if not array or array[0] < 0: return 0 while right + 1 > left: lowercase__ = (left + right) // 2 lowercase__ = array[mid] # Num must be negative and the index must be greater than or equal to 0. if num < 0 and array[mid - 1] >= 0: return mid if num >= 0: lowercase__ = mid + 1 else: lowercase__ = mid - 1 # No negative numbers so return the last index of the array + 1 which is the length. return len(_snake_case ) def lowerCamelCase ( _snake_case : list[list[int]] ): '''simple docstring''' lowercase__ = 0 lowercase__ = len(grid[0] ) for i in range(len(_snake_case ) ): lowercase__ = find_negative_index(grid[i][:bound] ) total += bound return (len(_snake_case ) * len(grid[0] )) - total def lowerCamelCase ( _snake_case : list[list[int]] ): '''simple docstring''' return len([number for row in grid for number in row if number < 0] ) def lowerCamelCase ( _snake_case : list[list[int]] ): '''simple docstring''' lowercase__ = 0 for row in grid: for i, number in enumerate(_snake_case ): if number < 0: total += len(_snake_case ) - i break return total def lowerCamelCase ( ): '''simple docstring''' from timeit import timeit print("Running benchmarks" ) lowercase__ = ( "from __main__ import count_negatives_binary_search, " "count_negatives_brute_force, count_negatives_brute_force_with_break, grid" ) for func in ( "count_negatives_binary_search", # took 0.7727 seconds "count_negatives_brute_force_with_break", # took 4.6505 seconds "count_negatives_brute_force", # took 12.8160 seconds ): lowercase__ = timeit(f'''{func}(grid=grid)''' ,setup=_snake_case ,number=500 ) print(f'''{func}() took {time:0.4f} seconds''' ) if __name__ == "__main__": import doctest doctest.testmod() benchmark()
267
'''simple docstring''' import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XGLMTokenizer, XGLMTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin SCREAMING_SNAKE_CASE__ = get_tests_dir("fixtures/test_sentencepiece.model") @require_sentencepiece @require_tokenizers class snake_case (UpperCamelCase , unittest.TestCase ): lowerCAmelCase__ :List[Any] = XGLMTokenizer lowerCAmelCase__ :Tuple = XGLMTokenizerFast lowerCAmelCase__ :Any = True lowerCAmelCase__ :List[Any] = True def _a ( self ) -> Tuple: super().setUp() # We have a SentencePiece fixture for testing lowercase__ = XGLMTokenizer(UpperCAmelCase_ ,keep_accents=UpperCAmelCase_ ) tokenizer.save_pretrained(self.tmpdirname ) def _a ( self ) -> Tuple: lowercase__ = "<pad>" lowercase__ = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCAmelCase_ ) ,UpperCAmelCase_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCAmelCase_ ) ,UpperCAmelCase_ ) def _a ( self ) -> Dict: lowercase__ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] ,"<s>" ) self.assertEqual(vocab_keys[1] ,"<pad>" ) self.assertEqual(len(UpperCAmelCase_ ) ,1_008 ) def _a ( self ) -> Union[str, Any]: self.assertEqual(self.get_tokenizer().vocab_size ,1_008 ) def _a ( self ) -> Dict: lowercase__ = XGLMTokenizer(UpperCAmelCase_ ,keep_accents=UpperCAmelCase_ ) lowercase__ = 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]] ,) lowercase__ = 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", "é", ".", ] ,) lowercase__ = 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] ] ,) lowercase__ = 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 _a ( self ) -> Optional[int]: return XGLMTokenizer.from_pretrained("facebook/xglm-564M" ) def _a ( self ) -> int: with tempfile.NamedTemporaryFile() as f: shutil.copyfile(UpperCAmelCase_ ,f.name ) lowercase__ = XGLMTokenizer(f.name ,keep_accents=UpperCAmelCase_ ) lowercase__ = pickle.dumps(UpperCAmelCase_ ) pickle.loads(UpperCAmelCase_ ) def _a ( self ) -> Optional[int]: if not self.test_rust_tokenizer: return lowercase__ = self.get_tokenizer() lowercase__ = self.get_rust_tokenizer() lowercase__ = "I was born in 92000, and this is falsé." lowercase__ = tokenizer.tokenize(UpperCAmelCase_ ) lowercase__ = rust_tokenizer.tokenize(UpperCAmelCase_ ) self.assertListEqual(UpperCAmelCase_ ,UpperCAmelCase_ ) lowercase__ = tokenizer.encode(UpperCAmelCase_ ,add_special_tokens=UpperCAmelCase_ ) lowercase__ = rust_tokenizer.encode(UpperCAmelCase_ ,add_special_tokens=UpperCAmelCase_ ) self.assertListEqual(UpperCAmelCase_ ,UpperCAmelCase_ ) lowercase__ = self.get_rust_tokenizer() lowercase__ = tokenizer.encode(UpperCAmelCase_ ) lowercase__ = rust_tokenizer.encode(UpperCAmelCase_ ) self.assertListEqual(UpperCAmelCase_ ,UpperCAmelCase_ ) @slow def _a ( self ) -> List[str]: lowercase__ = "Hello World!" lowercase__ = [2, 31_227, 4_447, 35] self.assertListEqual(UpperCAmelCase_ ,self.big_tokenizer.encode(UpperCAmelCase_ ) ) @slow def _a ( self ) -> str: lowercase__ = ( "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 lowercase__ = [2, 1_018, 67, 11, 1_988, 2_617, 5_631, 278, 11, 3_407, 48, 71_630, 28_085, 4, 3_234, 157, 13, 6, 5, 6, 4, 3_526, 768, 15, 659, 57, 298, 3_983, 864, 129, 21, 6, 5, 13_675, 377, 652, 7_580, 10_341, 155, 2_817, 422, 1_666, 7, 1_674, 53, 113, 202_277, 17_892, 33, 60, 87, 4, 3_234, 157, 61, 2_667, 52_376, 19, 88, 23, 735] # fmt: on self.assertListEqual(UpperCAmelCase_ ,self.big_tokenizer.encode(UpperCAmelCase_ ) ) @slow def _a ( self ) -> str: # fmt: off lowercase__ = { "input_ids": [[2, 108_825, 1_163, 15, 88_010, 473, 15_898, 157, 13_672, 1_857, 312, 8, 238_021, 1_163, 53, 13_672, 1_857, 312, 8, 53_283, 182_396, 8, 18_566, 16, 36_733, 4_101, 8, 230, 244_017, 122_553, 7, 15, 132_597, 4, 293, 12_511, 7_610, 4, 3_414, 132_597, 9, 4, 32_361, 362, 4, 734, 28_512, 32_569, 18, 4, 32_361, 26_096, 14_982, 73, 18_715, 21_433, 235_261, 15, 492, 12_427, 16, 53, 18_715, 21_433, 65_454, 15, 23_659, 563, 16, 278, 597, 2_843, 595, 7_931, 182_396, 64_186, 22, 886, 595, 132_981, 53, 25_540, 3_449, 43_982, 39_901, 5_951, 878, 330, 4, 27_694, 80_269, 312, 53, 6_517, 11_780, 611, 20_408, 5], [2, 6, 132_597, 67, 42_897, 33, 592, 8, 163_729, 25_540, 361, 136_997, 109_514, 173_230, 7, 501, 60, 102_913, 196, 5_631, 235, 63_243, 473, 6, 231_757, 74, 5_277, 7_905, 53, 3_095, 37_317, 22, 454, 183_874, 5], [2, 268, 31_298, 46_530, 6, 132_935, 43_831, 7, 597, 32, 24, 3_688, 9_865, 5]], "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, 1, 1, 1]] } # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=UpperCAmelCase_ ,model_name="facebook/xglm-564M" ,padding=UpperCAmelCase_ ,)
267
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 lowercase_ (_UpperCAmelCase ): A__ : torch.FloatTensor class lowercase_ (_UpperCAmelCase, _UpperCAmelCase ): @register_to_config def __init__( self , a_ = 1_6 , a_ = 8_8 , a_ = None , a_ = None , a_ = 1 , a_ = 0.0 , a_ = 3_2 , a_ = None , a_ = False , a_ = None , a_ = "geglu" , a_ = True , a_ = True , ) ->int: '''simple docstring''' super().__init__() _a = num_attention_heads _a = attention_head_dim _a = num_attention_heads * attention_head_dim _a = in_channels _a = torch.nn.GroupNorm(num_groups=a_ , num_channels=a_ , eps=1E-6 , affine=a_ ) _a = nn.Linear(a_ , a_ ) # 3. Define transformers blocks _a = nn.ModuleList( [ BasicTransformerBlock( a_ , a_ , a_ , dropout=a_ , cross_attention_dim=a_ , activation_fn=a_ , attention_bias=a_ , double_self_attention=a_ , norm_elementwise_affine=a_ , ) for d in range(a_ ) ] ) _a = nn.Linear(a_ , a_ ) def lowerCamelCase__ ( self , a_ , a_=None , a_=None , a_=None , a_=1 , a_=None , a_ = True , ) ->List[Any]: '''simple docstring''' _a , _a , _a , _a = hidden_states.shape _a = batch_frames // num_frames _a = hidden_states _a = hidden_states[None, :].reshape(a_ , a_ , a_ , a_ , a_ ) _a = hidden_states.permute(0 , 2 , 1 , 3 , 4 ) _a = self.norm(a_ ) _a = hidden_states.permute(0 , 3 , 4 , 2 , 1 ).reshape(batch_size * height * width , a_ , a_ ) _a = self.proj_in(a_ ) # 2. Blocks for block in self.transformer_blocks: _a = block( a_ , encoder_hidden_states=a_ , timestep=a_ , cross_attention_kwargs=a_ , class_labels=a_ , ) # 3. Output _a = self.proj_out(a_ ) _a = ( hidden_states[None, None, :] .reshape(a_ , a_ , a_ , a_ , a_ ) .permute(0 , 3 , 4 , 1 , 2 ) .contiguous() ) _a = hidden_states.reshape(a_ , a_ , a_ , a_ ) _a = hidden_states + residual if not return_dict: return (output,) return TransformerTemporalModelOutput(sample=a_ )
710
"""simple docstring""" import torch from diffusers import KDPMaDiscreteScheduler from diffusers.utils import torch_device from .test_schedulers import SchedulerCommonTest class lowercase_ (_UpperCAmelCase ): A__ : Tuple = (KDPMaDiscreteScheduler,) A__ : Tuple = 10 def lowerCamelCase__ ( self , **a_ ) ->List[str]: '''simple docstring''' _a = { "num_train_timesteps": 1_1_0_0, "beta_start": 0.0_001, "beta_end": 0.02, "beta_schedule": "linear", } config.update(**a_ ) return config def lowerCamelCase__ ( self ) ->Tuple: '''simple docstring''' for timesteps in [1_0, 5_0, 1_0_0, 1_0_0_0]: self.check_over_configs(num_train_timesteps=a_ ) def lowerCamelCase__ ( self ) ->List[Any]: '''simple docstring''' for beta_start, beta_end in zip([0.00_001, 0.0_001, 0.001] , [0.0_002, 0.002, 0.02] ): self.check_over_configs(beta_start=a_ , beta_end=a_ ) def lowerCamelCase__ ( self ) ->Any: '''simple docstring''' for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=a_ ) def lowerCamelCase__ ( self ) ->int: '''simple docstring''' for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=a_ ) def lowerCamelCase__ ( self ) ->Union[str, Any]: '''simple docstring''' _a = self.scheduler_classes[0] _a = self.get_scheduler_config(prediction_type="v_prediction" ) _a = scheduler_class(**a_ ) scheduler.set_timesteps(self.num_inference_steps ) _a = self.dummy_model() _a = self.dummy_sample_deter * scheduler.init_noise_sigma _a = sample.to(a_ ) for i, t in enumerate(scheduler.timesteps ): _a = scheduler.scale_model_input(a_ , a_ ) _a = model(a_ , a_ ) _a = scheduler.step(a_ , a_ , a_ ) _a = output.prev_sample _a = torch.sum(torch.abs(a_ ) ) _a = torch.mean(torch.abs(a_ ) ) if torch_device in ["cpu", "mps"]: assert abs(result_sum.item() - 4.6_934E-07 ) < 1E-2 assert abs(result_mean.item() - 6.1_112E-10 ) < 1E-3 else: # CUDA assert abs(result_sum.item() - 4.693_428_650_170_972E-07 ) < 1E-2 assert abs(result_mean.item() - 0.0_002 ) < 1E-3 def lowerCamelCase__ ( self ) ->Any: '''simple docstring''' if torch_device == "mps": return _a = self.scheduler_classes[0] _a = self.get_scheduler_config() _a = scheduler_class(**a_ ) scheduler.set_timesteps(self.num_inference_steps ) _a = self.dummy_model() _a = self.dummy_sample_deter * scheduler.init_noise_sigma _a = sample.to(a_ ) for i, t in enumerate(scheduler.timesteps ): _a = scheduler.scale_model_input(a_ , a_ ) _a = model(a_ , a_ ) _a = scheduler.step(a_ , a_ , a_ ) _a = output.prev_sample _a = torch.sum(torch.abs(a_ ) ) _a = torch.mean(torch.abs(a_ ) ) if torch_device in ["cpu", "mps"]: assert abs(result_sum.item() - 20.4_125 ) < 1E-2 assert abs(result_mean.item() - 0.0_266 ) < 1E-3 else: # CUDA assert abs(result_sum.item() - 20.4_125 ) < 1E-2 assert abs(result_mean.item() - 0.0_266 ) < 1E-3 def lowerCamelCase__ ( self ) ->int: '''simple docstring''' if torch_device == "mps": return _a = self.scheduler_classes[0] _a = self.get_scheduler_config() _a = scheduler_class(**a_ ) scheduler.set_timesteps(self.num_inference_steps , device=a_ ) _a = self.dummy_model() _a = self.dummy_sample_deter.to(a_ ) * scheduler.init_noise_sigma for t in scheduler.timesteps: _a = scheduler.scale_model_input(a_ , a_ ) _a = model(a_ , a_ ) _a = scheduler.step(a_ , a_ , a_ ) _a = output.prev_sample _a = torch.sum(torch.abs(a_ ) ) _a = torch.mean(torch.abs(a_ ) ) if str(a_ ).startswith("cpu" ): # The following sum varies between 148 and 156 on mps. Why? assert abs(result_sum.item() - 20.4_125 ) < 1E-2 assert abs(result_mean.item() - 0.0_266 ) < 1E-3 else: # CUDA assert abs(result_sum.item() - 20.4_125 ) < 1E-2 assert abs(result_mean.item() - 0.0_266 ) < 1E-3
612
0
import json from typing import List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_bart import BartTokenizer a_ :List[Any] = logging.get_logger(__name__) a_ :Tuple = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"} # See all BART models at https://huggingface.co/models?filter=bart a_ :Union[str, Any] = { "vocab_file": { "facebook/bart-base": "https://huggingface.co/facebook/bart-base/resolve/main/vocab.json", "facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/vocab.json", "facebook/bart-large-mnli": "https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json", "facebook/bart-large-cnn": "https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json", "facebook/bart-large-xsum": "https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json", "yjernite/bart_eli5": "https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json", }, "merges_file": { "facebook/bart-base": "https://huggingface.co/facebook/bart-base/resolve/main/merges.txt", "facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/merges.txt", "facebook/bart-large-mnli": "https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt", "facebook/bart-large-cnn": "https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt", "facebook/bart-large-xsum": "https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt", "yjernite/bart_eli5": "https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt", }, "tokenizer_file": { "facebook/bart-base": "https://huggingface.co/facebook/bart-base/resolve/main/tokenizer.json", "facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/tokenizer.json", "facebook/bart-large-mnli": "https://huggingface.co/facebook/bart-large-mnli/resolve/main/tokenizer.json", "facebook/bart-large-cnn": "https://huggingface.co/facebook/bart-large-cnn/resolve/main/tokenizer.json", "facebook/bart-large-xsum": "https://huggingface.co/facebook/bart-large-xsum/resolve/main/tokenizer.json", "yjernite/bart_eli5": "https://huggingface.co/yjernite/bart_eli5/resolve/main/tokenizer.json", }, } a_ :Dict = { "facebook/bart-base": 1_024, "facebook/bart-large": 1_024, "facebook/bart-large-mnli": 1_024, "facebook/bart-large-cnn": 1_024, "facebook/bart-large-xsum": 1_024, "yjernite/bart_eli5": 1_024, } class snake_case__ ( __SCREAMING_SNAKE_CASE ): """simple docstring""" _SCREAMING_SNAKE_CASE = VOCAB_FILES_NAMES _SCREAMING_SNAKE_CASE = PRETRAINED_VOCAB_FILES_MAP _SCREAMING_SNAKE_CASE = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _SCREAMING_SNAKE_CASE = ["""input_ids""", """attention_mask"""] _SCREAMING_SNAKE_CASE = BartTokenizer def __init__( self : Optional[int], _snake_case : List[Any]=None, _snake_case : List[Any]=None, _snake_case : Optional[Any]=None, _snake_case : Optional[int]="replace", _snake_case : List[str]="<s>", _snake_case : Any="</s>", _snake_case : List[Any]="</s>", _snake_case : Any="<s>", _snake_case : Tuple="<unk>", _snake_case : Optional[int]="<pad>", _snake_case : List[str]="<mask>", _snake_case : Dict=False, _snake_case : List[str]=True, **_snake_case : Any, ) ->Optional[Any]: super().__init__( _lowercase, _lowercase, tokenizer_file=_lowercase, errors=_lowercase, bos_token=_lowercase, eos_token=_lowercase, sep_token=_lowercase, cls_token=_lowercase, unk_token=_lowercase, pad_token=_lowercase, mask_token=_lowercase, add_prefix_space=_lowercase, trim_offsets=_lowercase, **_lowercase, ) snake_case__ : Tuple = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get('add_prefix_space', _lowercase ) != add_prefix_space: snake_case__ : str = getattr(_lowercase, pre_tok_state.pop('type' ) ) snake_case__ : Dict = add_prefix_space snake_case__ : Optional[int] = pre_tok_class(**_lowercase ) snake_case__ : str = add_prefix_space # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__` snake_case__ : Union[str, Any] = 'post_processor' snake_case__ : str = getattr(self.backend_tokenizer, _lowercase, _lowercase ) if tokenizer_component_instance: snake_case__ : Dict = json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: snake_case__ : Union[str, Any] = tuple(state['sep'] ) if "cls" in state: snake_case__ : List[Any] = tuple(state['cls'] ) snake_case__ : List[Any] = False if state.get('add_prefix_space', _lowercase ) != add_prefix_space: snake_case__ : Optional[int] = add_prefix_space snake_case__ : Optional[int] = True if state.get('trim_offsets', _lowercase ) != trim_offsets: snake_case__ : int = trim_offsets snake_case__ : int = True if changes_to_apply: snake_case__ : Tuple = getattr(_lowercase, state.pop('type' ) ) snake_case__ : List[str] = component_class(**_lowercase ) setattr(self.backend_tokenizer, _lowercase, _lowercase ) @property def lowercase_ ( self : Optional[Any] ) ->Union[str, Any]: if self._mask_token is None: if self.verbose: logger.error('Using mask_token, but it is not set yet.' ) return None return str(self._mask_token ) @mask_token.setter def lowercase_ ( self : Any, _snake_case : str ) ->Tuple: snake_case__ : str = AddedToken(_lowercase, lstrip=_lowercase, rstrip=_lowercase ) if isinstance(_lowercase, _lowercase ) else value snake_case__ : int = value def lowercase_ ( self : Any, *_snake_case : Tuple, **_snake_case : str ) ->Union[str, Any]: snake_case__ : Optional[Any] = kwargs.get('is_split_into_words', _lowercase ) if is_split_into_words and not self.add_prefix_space: raise ValueError( F'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True ''' 'to use it with pretokenized inputs.' ) return super()._batch_encode_plus(*_lowercase, **_lowercase ) def lowercase_ ( self : Tuple, *_snake_case : List[Any], **_snake_case : List[Any] ) ->List[str]: snake_case__ : Dict = kwargs.get('is_split_into_words', _lowercase ) if is_split_into_words and not self.add_prefix_space: raise ValueError( F'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True ''' 'to use it with pretokenized inputs.' ) return super()._encode_plus(*_lowercase, **_lowercase ) def lowercase_ ( self : Union[str, Any], _snake_case : str, _snake_case : Optional[str] = None ) ->Optional[int]: snake_case__ : List[Any] = self._tokenizer.model.save(_lowercase, name=_lowercase ) return tuple(_lowercase ) def lowercase_ ( self : Tuple, _snake_case : Optional[int], _snake_case : Optional[int]=None ) ->Union[str, Any]: snake_case__ : Optional[int] = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def lowercase_ ( self : Tuple, _snake_case : List[int], _snake_case : Optional[List[int]] = None ) ->Optional[int]: snake_case__ : List[Any] = [self.sep_token_id] snake_case__ : Optional[Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
478
from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel from ...schedulers import ScoreSdeVeScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class lowercase__ ( __SCREAMING_SNAKE_CASE ): A__= 42 A__= 42 def __init__( self : Tuple , _lowercase : UNetaDModel , _lowercase : ScoreSdeVeScheduler ): """simple docstring""" super().__init__() self.register_modules(unet=_lowercase , scheduler=_lowercase ) @torch.no_grad() def __call__( self : Dict , _lowercase : int = 1 , _lowercase : int = 20_00 , _lowercase : Optional[Union[torch.Generator, List[torch.Generator]]] = None , _lowercase : Optional[str] = "pil" , _lowercase : bool = True , **_lowercase : Any , ): """simple docstring""" UpperCAmelCase__ = self.unet.config.sample_size UpperCAmelCase__ = (batch_size, 3, img_size, img_size) UpperCAmelCase__ = self.unet UpperCAmelCase__ = randn_tensor(_lowercase , generator=_lowercase ) * self.scheduler.init_noise_sigma UpperCAmelCase__ = sample.to(self.device ) self.scheduler.set_timesteps(_lowercase ) self.scheduler.set_sigmas(_lowercase ) for i, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): UpperCAmelCase__ = self.scheduler.sigmas[i] * torch.ones(shape[0] , device=self.device ) # correction step for _ in range(self.scheduler.config.correct_steps ): UpperCAmelCase__ = self.unet(_lowercase , _lowercase ).sample UpperCAmelCase__ = self.scheduler.step_correct(_lowercase , _lowercase , generator=_lowercase ).prev_sample # prediction step UpperCAmelCase__ = model(_lowercase , _lowercase ).sample UpperCAmelCase__ = self.scheduler.step_pred(_lowercase , _lowercase , _lowercase , generator=_lowercase ) UpperCAmelCase__ , UpperCAmelCase__ = output.prev_sample, output.prev_sample_mean UpperCAmelCase__ = sample_mean.clamp(0 , 1 ) UpperCAmelCase__ = sample.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": UpperCAmelCase__ = self.numpy_to_pil(_lowercase ) if not return_dict: return (sample,) return ImagePipelineOutput(images=_lowercase )
475
0
'''simple docstring''' import inspect import unittest from transformers import ConvNextConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ConvNextBackbone, ConvNextForImageClassification, ConvNextModel from transformers.models.convnext.modeling_convnext import CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __magic_name__ : def __init__( self , snake_case , snake_case=1_3 , snake_case=3_2 , snake_case=3 , snake_case=4 , snake_case=[1_0, 2_0, 3_0, 4_0] , snake_case=[2, 2, 3, 2] , snake_case=True , snake_case=True , snake_case=3_7 , snake_case="gelu" , snake_case=1_0 , snake_case=0.02 , snake_case=["stage2", "stage3", "stage4"] , snake_case=[2, 3, 4] , snake_case=None , ) -> Optional[Any]: '''simple docstring''' _UpperCAmelCase : Dict =parent _UpperCAmelCase : int =batch_size _UpperCAmelCase : Union[str, Any] =image_size _UpperCAmelCase : List[str] =num_channels _UpperCAmelCase : Dict =num_stages _UpperCAmelCase : int =hidden_sizes _UpperCAmelCase : Tuple =depths _UpperCAmelCase : str =is_training _UpperCAmelCase : Any =use_labels _UpperCAmelCase : List[Any] =intermediate_size _UpperCAmelCase : Any =hidden_act _UpperCAmelCase : int =num_labels _UpperCAmelCase : int =initializer_range _UpperCAmelCase : Optional[int] =out_features _UpperCAmelCase : Dict =out_indices _UpperCAmelCase : int =scope def lowerCAmelCase ( self) -> List[Any]: '''simple docstring''' _UpperCAmelCase : Any =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) _UpperCAmelCase : int =None if self.use_labels: _UpperCAmelCase : Union[str, Any] =ids_tensor([self.batch_size] , self.num_labels) _UpperCAmelCase : Optional[int] =self.get_config() return config, pixel_values, labels def lowerCAmelCase ( self) -> Dict: '''simple docstring''' return ConvNextConfig( num_channels=self.num_channels , hidden_sizes=self.hidden_sizes , depths=self.depths , num_stages=self.num_stages , hidden_act=self.hidden_act , is_decoder=snake_case , initializer_range=self.initializer_range , out_features=self.out_features , out_indices=self.out_indices , num_labels=self.num_labels , ) def lowerCAmelCase ( self , snake_case , snake_case , snake_case) -> str: '''simple docstring''' _UpperCAmelCase : Optional[int] =ConvNextModel(config=snake_case) model.to(snake_case) model.eval() _UpperCAmelCase : List[str] =model(snake_case) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 3_2, self.image_size // 3_2) , ) def lowerCAmelCase ( self , snake_case , snake_case , snake_case) -> int: '''simple docstring''' _UpperCAmelCase : Optional[Any] =ConvNextForImageClassification(snake_case) model.to(snake_case) model.eval() _UpperCAmelCase : List[Any] =model(snake_case , labels=snake_case) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def lowerCAmelCase ( self , snake_case , snake_case , snake_case) -> Tuple: '''simple docstring''' _UpperCAmelCase : int =ConvNextBackbone(config=snake_case) model.to(snake_case) model.eval() _UpperCAmelCase : Dict =model(snake_case) # verify hidden states self.parent.assertEqual(len(result.feature_maps) , len(config.out_features)) self.parent.assertListEqual(list(result.feature_maps[0].shape) , [self.batch_size, self.hidden_sizes[1], 4, 4]) # verify channels self.parent.assertEqual(len(model.channels) , len(config.out_features)) self.parent.assertListEqual(model.channels , config.hidden_sizes[1:]) # verify backbone works with out_features=None _UpperCAmelCase : str =None _UpperCAmelCase : int =ConvNextBackbone(config=snake_case) model.to(snake_case) model.eval() _UpperCAmelCase : Union[str, Any] =model(snake_case) # verify feature maps self.parent.assertEqual(len(result.feature_maps) , 1) self.parent.assertListEqual(list(result.feature_maps[0].shape) , [self.batch_size, self.hidden_sizes[-1], 1, 1]) # verify channels self.parent.assertEqual(len(model.channels) , 1) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]]) def lowerCAmelCase ( self) -> Union[str, Any]: '''simple docstring''' _UpperCAmelCase : Optional[Any] =self.prepare_config_and_inputs() _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase : int =config_and_inputs _UpperCAmelCase : Dict ={'pixel_values': pixel_values} return config, inputs_dict @require_torch class __magic_name__ ( lowercase_ ,lowercase_ ,unittest.TestCase ): UpperCAmelCase =( ( ConvNextModel, ConvNextForImageClassification, ConvNextBackbone, ) if is_torch_available() else () ) UpperCAmelCase =( {'''feature-extraction''': ConvNextModel, '''image-classification''': ConvNextForImageClassification} if is_torch_available() else {} ) UpperCAmelCase =True UpperCAmelCase =False UpperCAmelCase =False UpperCAmelCase =False UpperCAmelCase =False def lowerCAmelCase ( self) -> Dict: '''simple docstring''' _UpperCAmelCase : Any =ConvNextModelTester(self) _UpperCAmelCase : Union[str, Any] =ConfigTester(self , config_class=snake_case , has_text_modality=snake_case , hidden_size=3_7) def lowerCAmelCase ( self) -> List[Any]: '''simple docstring''' self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def lowerCAmelCase ( self) -> str: '''simple docstring''' return @unittest.skip(reason='ConvNext does not use inputs_embeds') def lowerCAmelCase ( self) -> Optional[Any]: '''simple docstring''' pass @unittest.skip(reason='ConvNext does not support input and output embeddings') def lowerCAmelCase ( self) -> List[str]: '''simple docstring''' pass @unittest.skip(reason='ConvNext does not use feedforward chunking') def lowerCAmelCase ( self) -> Any: '''simple docstring''' pass def lowerCAmelCase ( self) -> Optional[Any]: '''simple docstring''' _UpperCAmelCase , _UpperCAmelCase : Optional[Any] =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _UpperCAmelCase : Union[str, Any] =model_class(snake_case) _UpperCAmelCase : Union[str, Any] =inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic _UpperCAmelCase : str =[*signature.parameters.keys()] _UpperCAmelCase : str =['pixel_values'] self.assertListEqual(arg_names[:1] , snake_case) def lowerCAmelCase ( self) -> Dict: '''simple docstring''' _UpperCAmelCase : Any =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case) def lowerCAmelCase ( self) -> Tuple: '''simple docstring''' _UpperCAmelCase : int =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*snake_case) def lowerCAmelCase ( self) -> str: '''simple docstring''' def check_hidden_states_output(snake_case , snake_case , snake_case): _UpperCAmelCase : str =model_class(snake_case) model.to(snake_case) model.eval() with torch.no_grad(): _UpperCAmelCase : Any =model(**self._prepare_for_class(snake_case , snake_case)) _UpperCAmelCase : Any =outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states _UpperCAmelCase : Any =self.model_tester.num_stages self.assertEqual(len(snake_case) , expected_num_stages + 1) # ConvNext's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:]) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) _UpperCAmelCase , _UpperCAmelCase : int =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _UpperCAmelCase : List[Any] =True check_hidden_states_output(snake_case , snake_case , snake_case) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _UpperCAmelCase : List[Any] =True check_hidden_states_output(snake_case , snake_case , snake_case) def lowerCAmelCase ( self) -> List[str]: '''simple docstring''' _UpperCAmelCase : int =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*snake_case) @slow def lowerCAmelCase ( self) -> str: '''simple docstring''' for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _UpperCAmelCase : str =ConvNextModel.from_pretrained(snake_case) self.assertIsNotNone(snake_case) def lowerCamelCase__ ( ): '''simple docstring''' _UpperCAmelCase : Optional[int] =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class __magic_name__ ( unittest.TestCase ): @cached_property def lowerCAmelCase ( self) -> List[str]: '''simple docstring''' return AutoImageProcessor.from_pretrained('facebook/convnext-tiny-224') if is_vision_available() else None @slow def lowerCAmelCase ( self) -> Any: '''simple docstring''' _UpperCAmelCase : List[Any] =ConvNextForImageClassification.from_pretrained('facebook/convnext-tiny-224').to(snake_case) _UpperCAmelCase : Dict =self.default_image_processor _UpperCAmelCase : List[str] =prepare_img() _UpperCAmelCase : str =image_processor(images=snake_case , return_tensors='pt').to(snake_case) # forward pass with torch.no_grad(): _UpperCAmelCase : str =model(**snake_case) # verify the logits _UpperCAmelCase : Union[str, Any] =torch.Size((1, 1_0_0_0)) self.assertEqual(outputs.logits.shape , snake_case) _UpperCAmelCase : str =torch.tensor([-0.02_60, -0.47_39, 0.19_11]).to(snake_case) self.assertTrue(torch.allclose(outputs.logits[0, :3] , snake_case , atol=1E-4)) @require_torch class __magic_name__ ( unittest.TestCase ,lowercase_ ): UpperCAmelCase =(ConvNextBackbone,) if is_torch_available() else () UpperCAmelCase =ConvNextConfig UpperCAmelCase =False def lowerCAmelCase ( self) -> Dict: '''simple docstring''' _UpperCAmelCase : str =ConvNextModelTester(self)
720
'''simple docstring''' import argparse import requests import torch # pip3 install salesforce-lavis # I'm actually installing a slightly modified version: pip3 install git+https://github.com/nielsrogge/LAVIS.git@fix_lavis from lavis.models import load_model_and_preprocess from PIL import Image from transformers import ( AutoTokenizer, BlipaConfig, BlipaForConditionalGeneration, BlipaProcessor, BlipaVisionConfig, BlipImageProcessor, OPTConfig, TaConfig, ) from transformers.utils.constants import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD def lowerCamelCase__ ( ): '''simple docstring''' _UpperCAmelCase : int ='https://storage.googleapis.com/sfr-vision-language-research/LAVIS/assets/merlion.png' _UpperCAmelCase : Optional[int] =Image.open(requests.get(__lowerCamelCase , stream=__lowerCamelCase ).raw ).convert('RGB' ) return image def lowerCamelCase__ ( __lowerCamelCase : Any ): '''simple docstring''' _UpperCAmelCase : int =[] # fmt: off # vision encoder rename_keys.append(('visual_encoder.cls_token', 'vision_model.embeddings.class_embedding') ) rename_keys.append(('visual_encoder.pos_embed', 'vision_model.embeddings.position_embedding') ) rename_keys.append(('visual_encoder.patch_embed.proj.weight', 'vision_model.embeddings.patch_embedding.weight') ) rename_keys.append(('visual_encoder.patch_embed.proj.bias', 'vision_model.embeddings.patch_embedding.bias') ) rename_keys.append(('ln_vision.weight', 'vision_model.post_layernorm.weight') ) rename_keys.append(('ln_vision.bias', 'vision_model.post_layernorm.bias') ) for i in range(config.vision_config.num_hidden_layers ): rename_keys.append((f"visual_encoder.blocks.{i}.norm1.weight", f"vision_model.encoder.layers.{i}.layer_norm1.weight") ) rename_keys.append((f"visual_encoder.blocks.{i}.norm1.bias", f"vision_model.encoder.layers.{i}.layer_norm1.bias") ) rename_keys.append((f"visual_encoder.blocks.{i}.norm2.weight", f"vision_model.encoder.layers.{i}.layer_norm2.weight") ) rename_keys.append((f"visual_encoder.blocks.{i}.norm2.bias", f"vision_model.encoder.layers.{i}.layer_norm2.bias") ) rename_keys.append((f"visual_encoder.blocks.{i}.attn.qkv.weight", f"vision_model.encoder.layers.{i}.self_attn.qkv.weight") ) rename_keys.append((f"visual_encoder.blocks.{i}.attn.proj.weight", f"vision_model.encoder.layers.{i}.self_attn.projection.weight",) ) rename_keys.append((f"visual_encoder.blocks.{i}.attn.proj.bias", f"vision_model.encoder.layers.{i}.self_attn.projection.bias") ) rename_keys.append((f"visual_encoder.blocks.{i}.mlp.fc1.weight", f"vision_model.encoder.layers.{i}.mlp.fc1.weight") ) rename_keys.append((f"visual_encoder.blocks.{i}.mlp.fc1.bias", f"vision_model.encoder.layers.{i}.mlp.fc1.bias") ) rename_keys.append((f"visual_encoder.blocks.{i}.mlp.fc2.weight", f"vision_model.encoder.layers.{i}.mlp.fc2.weight") ) rename_keys.append((f"visual_encoder.blocks.{i}.mlp.fc2.bias", f"vision_model.encoder.layers.{i}.mlp.fc2.bias") ) # QFormer rename_keys.append(('Qformer.bert.embeddings.LayerNorm.weight', 'qformer.layernorm.weight') ) rename_keys.append(('Qformer.bert.embeddings.LayerNorm.bias', 'qformer.layernorm.bias') ) # fmt: on return rename_keys def lowerCamelCase__ ( __lowerCamelCase : Union[str, Any] , __lowerCamelCase : int , __lowerCamelCase : int ): '''simple docstring''' _UpperCAmelCase : Optional[Any] =dct.pop(__lowerCamelCase ) _UpperCAmelCase : Dict =val def lowerCamelCase__ ( __lowerCamelCase : Union[str, Any] , __lowerCamelCase : List[str] ): '''simple docstring''' for i in range(config.vision_config.num_hidden_layers ): # read in original q and v biases _UpperCAmelCase : str =state_dict.pop(f"visual_encoder.blocks.{i}.attn.q_bias" ) _UpperCAmelCase : Tuple =state_dict.pop(f"visual_encoder.blocks.{i}.attn.v_bias" ) # next, set bias in the state dict _UpperCAmelCase : Optional[Any] =torch.cat((q_bias, torch.zeros_like(__lowerCamelCase , requires_grad=__lowerCamelCase ), v_bias) ) _UpperCAmelCase : int =qkv_bias def lowerCamelCase__ ( __lowerCamelCase : List[str] , __lowerCamelCase : int ): '''simple docstring''' _UpperCAmelCase : Union[str, Any] =3_6_4 if 'coco' in model_name else 2_2_4 _UpperCAmelCase : Optional[int] =BlipaVisionConfig(image_size=__lowerCamelCase ).to_dict() # make sure the models have proper bos_token_id and eos_token_id set (important for generation) # seems like flan-T5 models don't have bos_token_id properly set? if "opt-2.7b" in model_name: _UpperCAmelCase : Tuple =OPTConfig.from_pretrained('facebook/opt-2.7b' , eos_token_id=__lowerCamelCase ).to_dict() elif "opt-6.7b" in model_name: _UpperCAmelCase : Dict =OPTConfig.from_pretrained('facebook/opt-6.7b' , eos_token_id=__lowerCamelCase ).to_dict() elif "t5-xl" in model_name: _UpperCAmelCase : Union[str, Any] =TaConfig.from_pretrained('google/flan-t5-xl' , dense_act_fn='gelu' , bos_token_id=1 ).to_dict() elif "t5-xxl" in model_name: _UpperCAmelCase : Dict =TaConfig.from_pretrained('google/flan-t5-xxl' , dense_act_fn='gelu' , bos_token_id=1 ).to_dict() _UpperCAmelCase : str =BlipaConfig(vision_config=__lowerCamelCase , text_config=__lowerCamelCase ) return config, image_size @torch.no_grad() def lowerCamelCase__ ( __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Dict=None , __lowerCamelCase : Dict=False ): '''simple docstring''' _UpperCAmelCase : str =( AutoTokenizer.from_pretrained('facebook/opt-2.7b' ) if 'opt' in model_name else AutoTokenizer.from_pretrained('google/flan-t5-xl' ) ) _UpperCAmelCase : Tuple =tokenizer('\n' , add_special_tokens=__lowerCamelCase ).input_ids[0] _UpperCAmelCase , _UpperCAmelCase : List[str] =get_blipa_config(__lowerCamelCase , eos_token_id=__lowerCamelCase ) _UpperCAmelCase : Optional[int] =BlipaForConditionalGeneration(__lowerCamelCase ).eval() _UpperCAmelCase : int ={ 'blip2-opt-2.7b': ('blip2_opt', 'pretrain_opt2.7b'), 'blip2-opt-6.7b': ('blip2_opt', 'pretrain_opt6.7b'), 'blip2-opt-2.7b-coco': ('blip2_opt', 'caption_coco_opt2.7b'), 'blip2-opt-6.7b-coco': ('blip2_opt', 'caption_coco_opt6.7b'), 'blip2-flan-t5-xl': ('blip2_t5', 'pretrain_flant5xl'), 'blip2-flan-t5-xl-coco': ('blip2_t5', 'caption_coco_flant5xl'), 'blip2-flan-t5-xxl': ('blip2_t5', 'pretrain_flant5xxl'), } _UpperCAmelCase , _UpperCAmelCase : Tuple =model_name_to_original[model_name] # load original model print('Loading original model...' ) _UpperCAmelCase : Optional[int] ='cuda' if torch.cuda.is_available() else 'cpu' _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase : Union[str, Any] =load_model_and_preprocess( name=__lowerCamelCase , model_type=__lowerCamelCase , is_eval=__lowerCamelCase , device=__lowerCamelCase ) original_model.eval() print('Done!' ) # update state dict keys _UpperCAmelCase : List[Any] =original_model.state_dict() _UpperCAmelCase : Optional[Any] =create_rename_keys(__lowerCamelCase ) for src, dest in rename_keys: rename_key(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) # some keys can be renamed efficiently for key, val in state_dict.copy().items(): _UpperCAmelCase : Optional[Any] =state_dict.pop(__lowerCamelCase ) if key.startswith('Qformer.bert' ): _UpperCAmelCase : Tuple =key.replace('Qformer.bert' , 'qformer' ) if "attention.self" in key: _UpperCAmelCase : Optional[Any] =key.replace('self' , 'attention' ) if "opt_proj" in key: _UpperCAmelCase : List[str] =key.replace('opt_proj' , 'language_projection' ) if "t5_proj" in key: _UpperCAmelCase : Tuple =key.replace('t5_proj' , 'language_projection' ) if key.startswith('opt' ): _UpperCAmelCase : Optional[Any] =key.replace('opt' , 'language' ) if key.startswith('t5' ): _UpperCAmelCase : Dict =key.replace('t5' , 'language' ) _UpperCAmelCase : Any =val # read in qv biases read_in_q_v_bias(__lowerCamelCase , __lowerCamelCase ) _UpperCAmelCase , _UpperCAmelCase : List[Any] =hf_model.load_state_dict(__lowerCamelCase , strict=__lowerCamelCase ) assert len(__lowerCamelCase ) == 0 assert unexpected_keys == ["qformer.embeddings.position_ids"] _UpperCAmelCase : Union[str, Any] =load_demo_image() _UpperCAmelCase : str =vis_processors['eval'](__lowerCamelCase ).unsqueeze(0 ).to(__lowerCamelCase ) _UpperCAmelCase : Any =tokenizer(['\n'] , return_tensors='pt' ).input_ids.to(__lowerCamelCase ) # create processor _UpperCAmelCase : str =BlipImageProcessor( size={'height': image_size, 'width': image_size} , image_mean=__lowerCamelCase , image_std=__lowerCamelCase ) _UpperCAmelCase : Union[str, Any] =BlipaProcessor(image_processor=__lowerCamelCase , tokenizer=__lowerCamelCase ) _UpperCAmelCase : str =processor(images=__lowerCamelCase , return_tensors='pt' ).pixel_values.to(__lowerCamelCase ) # make sure processor creates exact same pixel values assert torch.allclose(__lowerCamelCase , __lowerCamelCase ) original_model.to(__lowerCamelCase ) hf_model.to(__lowerCamelCase ) with torch.no_grad(): if "opt" in model_name: _UpperCAmelCase : Dict =original_model({'image': original_pixel_values, 'text_input': ['']} ).logits _UpperCAmelCase : int =hf_model(__lowerCamelCase , __lowerCamelCase ).logits else: _UpperCAmelCase : Tuple =original_model( {'image': original_pixel_values, 'text_input': ['\n'], 'text_output': ['\n']} ).logits _UpperCAmelCase : Union[str, Any] =input_ids.masked_fill(input_ids == tokenizer.pad_token_id , -1_0_0 ) _UpperCAmelCase : Any =hf_model(__lowerCamelCase , __lowerCamelCase , labels=__lowerCamelCase ).logits assert original_logits.shape == logits.shape print('First values of original logits:' , original_logits[0, :3, :3] ) print('First values of HF logits:' , logits[0, :3, :3] ) # assert values if model_name == "blip2-flan-t5-xl": _UpperCAmelCase : Dict =torch.tensor( [[-41.58_50, -4.44_40, -8.99_22], [-47.43_22, -5.91_43, -1.73_40]] , device=__lowerCamelCase ) assert torch.allclose(logits[0, :3, :3] , __lowerCamelCase , atol=1e-4 ) elif model_name == "blip2-flan-t5-xl-coco": _UpperCAmelCase : Optional[Any] =torch.tensor( [[-57.01_09, -9.89_67, -12.62_80], [-68.65_78, -12.71_91, -10.50_65]] , device=__lowerCamelCase ) else: # cast to same type _UpperCAmelCase : List[str] =logits.dtype assert torch.allclose(original_logits.to(__lowerCamelCase ) , __lowerCamelCase , atol=1e-2 ) print('Looks ok!' ) print('Generating a caption...' ) _UpperCAmelCase : str ='' _UpperCAmelCase : Tuple =tokenizer(__lowerCamelCase , return_tensors='pt' ).input_ids.to(__lowerCamelCase ) _UpperCAmelCase : Any =original_model.generate({'image': original_pixel_values} ) _UpperCAmelCase : List[str] =hf_model.generate( __lowerCamelCase , __lowerCamelCase , do_sample=__lowerCamelCase , num_beams=5 , max_length=3_0 , min_length=1 , top_p=0.9 , repetition_penalty=1.0 , length_penalty=1.0 , temperature=1 , ) print('Original generation:' , __lowerCamelCase ) _UpperCAmelCase : List[Any] =input_ids.shape[1] _UpperCAmelCase : Optional[int] =processor.batch_decode(outputs[:, prompt_length:] , skip_special_tokens=__lowerCamelCase ) _UpperCAmelCase : Optional[Any] =[text.strip() for text in output_text] print('HF generation:' , __lowerCamelCase ) if pytorch_dump_folder_path is not None: processor.save_pretrained(__lowerCamelCase ) hf_model.save_pretrained(__lowerCamelCase ) if push_to_hub: processor.push_to_hub(f"nielsr/{model_name}" ) hf_model.push_to_hub(f"nielsr/{model_name}" ) if __name__ == "__main__": lowercase =argparse.ArgumentParser() lowercase =[ 'blip2-opt-2.7b', 'blip2-opt-6.7b', 'blip2-opt-2.7b-coco', 'blip2-opt-6.7b-coco', 'blip2-flan-t5-xl', 'blip2-flan-t5-xl-coco', 'blip2-flan-t5-xxl', ] parser.add_argument( '--model_name', default='blip2-opt-2.7b', choices=choices, type=str, help='Path to hf config.json of model to convert', ) parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument( '--push_to_hub', action='store_true', help='Whether to push the model and processor to the hub after converting', ) lowercase =parser.parse_args() convert_blipa_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
331
0
def lowerCAmelCase_ ( __a ) -> bool: """simple docstring""" lowerCamelCase__: Tuple =[int(__a ) for i in ip_va_address.split("." ) if i.isdigit()] return len(__a ) == 4 and all(0 <= int(__a ) <= 254 for octet in octets ) if __name__ == "__main__": __A = input().strip() __A = "valid" if is_ip_va_address_valid(ip) else "invalid" print(f'{ip} is a {valid_or_invalid} IP v4 address.')
59
class UpperCamelCase_ : '''simple docstring''' def __init__( self , a ) -> Tuple: snake_case_ = n snake_case_ = [None] * self.n snake_case_ = 0 # index of the first element snake_case_ = 0 snake_case_ = 0 def __len__( self ) -> int: return self.size def _UpperCamelCase ( self ) -> bool: return self.size == 0 def _UpperCamelCase ( self ) -> List[Any]: return False if self.is_empty() else self.array[self.front] def _UpperCamelCase ( self , a ) -> Dict: if self.size >= self.n: raise Exception('QUEUE IS FULL' ) snake_case_ = data snake_case_ = (self.rear + 1) % self.n self.size += 1 return self def _UpperCamelCase ( self ) -> List[Any]: if self.size == 0: raise Exception('UNDERFLOW' ) snake_case_ = self.array[self.front] snake_case_ = None snake_case_ = (self.front + 1) % self.n self.size -= 1 return temp
198
0
"""simple docstring""" from itertools import permutations def __UpperCAmelCase ( __UpperCamelCase ): if num[3] % 2 != 0: return False if (num[2] + num[3] + num[4]) % 3 != 0: return False if num[5] % 5 != 0: return False __lowercase : Union[str, Any] = [7, 11, 13, 17] for i, test in enumerate(__UpperCamelCase ): if (num[i + 4] * 1_00 + num[i + 5] * 10 + num[i + 6]) % test != 0: return False return True def __UpperCAmelCase ( __UpperCamelCase = 10 ): return sum( int(''''''.join(map(__UpperCamelCase , __UpperCamelCase ) ) ) for num in permutations(range(__UpperCamelCase ) ) if is_substring_divisible(__UpperCamelCase ) ) if __name__ == "__main__": print(F"{solution() = }")
523
"""simple docstring""" def __UpperCAmelCase ( __UpperCamelCase ): assert column_title.isupper() __lowercase : Optional[Any] = 0 __lowercase : Union[str, Any] = len(__UpperCamelCase ) - 1 __lowercase : Union[str, Any] = 0 while index >= 0: __lowercase : List[Any] = (ord(column_title[index] ) - 64) * pow(26 , __UpperCamelCase ) answer += value power += 1 index -= 1 return answer if __name__ == "__main__": from doctest import testmod testmod()
523
1
'''simple docstring''' from typing import List import numpy as np def lowercase__( _UpperCamelCase : dict )-> int: """simple docstring""" _UpperCamelCase = {key: len(_UpperCamelCase ) for key, value in gen_kwargs.items() if isinstance(_UpperCamelCase , _UpperCamelCase )} if len(set(lists_lengths.values() ) ) > 1: raise RuntimeError( ( "Sharding is ambiguous for this dataset: " + "we found several data sources lists of different lengths, and we don't know over which list we should parallelize:\n" + "\n".join(f"\t- key {key} has length {length}" for key, length in lists_lengths.items() ) + "\nTo fix this, check the 'gen_kwargs' and make sure to use lists only for data sources, " + "and use tuples otherwise. In the end there should only be one single list, or several lists with the same length." ) ) _UpperCamelCase = max(lists_lengths.values() , default=0 ) return max(1 , _UpperCamelCase ) def lowercase__( _UpperCamelCase : int , _UpperCamelCase : int )-> List[range]: """simple docstring""" _UpperCamelCase = [] for group_idx in range(_UpperCamelCase ): _UpperCamelCase = num_shards // max_num_jobs + (group_idx < (num_shards % max_num_jobs)) if num_shards_to_add == 0: break _UpperCamelCase = shards_indices_per_group[-1].stop if shards_indices_per_group else 0 _UpperCamelCase = range(_UpperCamelCase , start + num_shards_to_add ) shards_indices_per_group.append(_UpperCamelCase ) return shards_indices_per_group def lowercase__( _UpperCamelCase : dict , _UpperCamelCase : int )-> List[dict]: """simple docstring""" _UpperCamelCase = _number_of_shards_in_gen_kwargs(_UpperCamelCase ) if num_shards == 1: return [dict(_UpperCamelCase )] else: _UpperCamelCase = _distribute_shards(num_shards=_UpperCamelCase , max_num_jobs=_UpperCamelCase ) return [ { key: [value[shard_idx] for shard_idx in shard_indices_per_group[group_idx]] if isinstance(_UpperCamelCase , _UpperCamelCase ) else value for key, value in gen_kwargs.items() } for group_idx in range(len(_UpperCamelCase ) ) ] def lowercase__( _UpperCamelCase : List[dict] )-> dict: """simple docstring""" return { key: [value for gen_kwargs in gen_kwargs_list for value in gen_kwargs[key]] if isinstance(gen_kwargs_list[0][key] , _UpperCamelCase ) else gen_kwargs_list[0][key] for key in gen_kwargs_list[0] } def lowercase__( _UpperCamelCase : np.random.Generator , _UpperCamelCase : dict )-> dict: """simple docstring""" _UpperCamelCase = {len(_UpperCamelCase ) for value in gen_kwargs.values() if isinstance(_UpperCamelCase , _UpperCamelCase )} _UpperCamelCase = {} for size in list_sizes: _UpperCamelCase = list(range(_UpperCamelCase ) ) rng.shuffle(indices_per_size[size] ) # Now let's copy the gen_kwargs and shuffle the lists based on their sizes _UpperCamelCase = dict(_UpperCamelCase ) for key, value in shuffled_kwargs.items(): if isinstance(_UpperCamelCase , _UpperCamelCase ): _UpperCamelCase = [value[i] for i in indices_per_size[len(_UpperCamelCase )]] return shuffled_kwargs
138
'''simple docstring''' def lowercase__( _UpperCamelCase : str )-> str: """simple docstring""" return " ".join( "".join(word[::-1] ) if len(_UpperCamelCase ) > 4 else word for word in sentence.split() ) if __name__ == "__main__": import doctest doctest.testmod() print(reverse_long_words('''Hey wollef sroirraw'''))
138
1
from typing import Optional import torch import torch.utils.checkpoint from torch import Tensor, nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_outputs import ( BaseModelOutputWithNoAttention, BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention, ) from ...modeling_utils import PreTrainedModel from ...utils import logging from .configuration_regnet import RegNetConfig __lowerCAmelCase =logging.get_logger(__name__) # General docstring __lowerCAmelCase ='RegNetConfig' # Base docstring __lowerCAmelCase ='facebook/regnet-y-040' __lowerCAmelCase =[1, 1088, 7, 7] # Image classification docstring __lowerCAmelCase ='facebook/regnet-y-040' __lowerCAmelCase ='tabby, tabby cat' __lowerCAmelCase =[ 'facebook/regnet-y-040', # See all regnet models at https://huggingface.co/models?filter=regnet ] class __magic_name__ ( nn.Module): def __init__( self : Optional[int] ,__SCREAMING_SNAKE_CASE : Tuple ,__SCREAMING_SNAKE_CASE : int ,__SCREAMING_SNAKE_CASE : Any = 3 ,__SCREAMING_SNAKE_CASE : List[Any] = 1 ,__SCREAMING_SNAKE_CASE : Optional[Any] = 1 ,__SCREAMING_SNAKE_CASE : str = "relu" ,): super().__init__() UpperCAmelCase = nn.Convad( _SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,kernel_size=_SCREAMING_SNAKE_CASE ,stride=_SCREAMING_SNAKE_CASE ,padding=kernel_size // 2 ,groups=_SCREAMING_SNAKE_CASE ,bias=_SCREAMING_SNAKE_CASE ,) UpperCAmelCase = nn.BatchNormad(_SCREAMING_SNAKE_CASE ) UpperCAmelCase = ACTaFN[activation] if activation is not None else nn.Identity() def _UpperCAmelCase ( self : List[str] ,__SCREAMING_SNAKE_CASE : Union[str, Any] ): UpperCAmelCase = self.convolution(_SCREAMING_SNAKE_CASE ) UpperCAmelCase = self.normalization(_SCREAMING_SNAKE_CASE ) UpperCAmelCase = self.activation(_SCREAMING_SNAKE_CASE ) return hidden_state class __magic_name__ ( nn.Module): def __init__( self : Union[str, Any] ,__SCREAMING_SNAKE_CASE : Any ): super().__init__() UpperCAmelCase = RegNetConvLayer( config.num_channels ,config.embedding_size ,kernel_size=3 ,stride=2 ,activation=config.hidden_act ) UpperCAmelCase = config.num_channels def _UpperCAmelCase ( self : str ,__SCREAMING_SNAKE_CASE : List[Any] ): UpperCAmelCase = pixel_values.shape[1] if num_channels != self.num_channels: raise ValueError( "Make sure that the channel dimension of the pixel values match with the one set in the configuration." ) UpperCAmelCase = self.embedder(_SCREAMING_SNAKE_CASE ) return hidden_state class __magic_name__ ( nn.Module): def __init__( self : List[Any] ,__SCREAMING_SNAKE_CASE : int ,__SCREAMING_SNAKE_CASE : List[str] ,__SCREAMING_SNAKE_CASE : Any = 2 ): super().__init__() UpperCAmelCase = nn.Convad(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,kernel_size=1 ,stride=_SCREAMING_SNAKE_CASE ,bias=_SCREAMING_SNAKE_CASE ) UpperCAmelCase = nn.BatchNormad(_SCREAMING_SNAKE_CASE ) def _UpperCAmelCase ( self : Optional[Any] ,__SCREAMING_SNAKE_CASE : Any ): UpperCAmelCase = self.convolution(_SCREAMING_SNAKE_CASE ) UpperCAmelCase = self.normalization(_SCREAMING_SNAKE_CASE ) return hidden_state class __magic_name__ ( nn.Module): def __init__( self : Dict ,__SCREAMING_SNAKE_CASE : Any ,__SCREAMING_SNAKE_CASE : Dict ): super().__init__() UpperCAmelCase = nn.AdaptiveAvgPoolad((1, 1) ) UpperCAmelCase = nn.Sequential( nn.Convad(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,kernel_size=1 ) ,nn.ReLU() ,nn.Convad(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,kernel_size=1 ) ,nn.Sigmoid() ,) def _UpperCAmelCase ( self : List[Any] ,__SCREAMING_SNAKE_CASE : Tuple ): # b c h w -> b c 1 1 UpperCAmelCase = self.pooler(_SCREAMING_SNAKE_CASE ) UpperCAmelCase = self.attention(_SCREAMING_SNAKE_CASE ) UpperCAmelCase = hidden_state * attention return hidden_state class __magic_name__ ( nn.Module): def __init__( self : Union[str, Any] ,__SCREAMING_SNAKE_CASE : str ,__SCREAMING_SNAKE_CASE : List[Any] ,__SCREAMING_SNAKE_CASE : Tuple ,__SCREAMING_SNAKE_CASE : Optional[Any] = 1 ): super().__init__() UpperCAmelCase = in_channels != out_channels or stride != 1 UpperCAmelCase = max(1 ,out_channels // config.groups_width ) UpperCAmelCase = ( RegNetShortCut(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,stride=_SCREAMING_SNAKE_CASE ) if should_apply_shortcut else nn.Identity() ) UpperCAmelCase = nn.Sequential( RegNetConvLayer(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,kernel_size=1 ,activation=config.hidden_act ) ,RegNetConvLayer(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,stride=_SCREAMING_SNAKE_CASE ,groups=_SCREAMING_SNAKE_CASE ,activation=config.hidden_act ) ,RegNetConvLayer(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,kernel_size=1 ,activation=_SCREAMING_SNAKE_CASE ) ,) UpperCAmelCase = ACTaFN[config.hidden_act] def _UpperCAmelCase ( self : List[str] ,__SCREAMING_SNAKE_CASE : List[Any] ): UpperCAmelCase = hidden_state UpperCAmelCase = self.layer(_SCREAMING_SNAKE_CASE ) UpperCAmelCase = self.shortcut(_SCREAMING_SNAKE_CASE ) hidden_state += residual UpperCAmelCase = self.activation(_SCREAMING_SNAKE_CASE ) return hidden_state class __magic_name__ ( nn.Module): def __init__( self : Dict ,__SCREAMING_SNAKE_CASE : str ,__SCREAMING_SNAKE_CASE : Dict ,__SCREAMING_SNAKE_CASE : List[Any] ,__SCREAMING_SNAKE_CASE : Union[str, Any] = 1 ): super().__init__() UpperCAmelCase = in_channels != out_channels or stride != 1 UpperCAmelCase = max(1 ,out_channels // config.groups_width ) UpperCAmelCase = ( RegNetShortCut(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,stride=_SCREAMING_SNAKE_CASE ) if should_apply_shortcut else nn.Identity() ) UpperCAmelCase = nn.Sequential( RegNetConvLayer(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,kernel_size=1 ,activation=config.hidden_act ) ,RegNetConvLayer(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,stride=_SCREAMING_SNAKE_CASE ,groups=_SCREAMING_SNAKE_CASE ,activation=config.hidden_act ) ,RegNetSELayer(_SCREAMING_SNAKE_CASE ,reduced_channels=int(round(in_channels / 4 ) ) ) ,RegNetConvLayer(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,kernel_size=1 ,activation=_SCREAMING_SNAKE_CASE ) ,) UpperCAmelCase = ACTaFN[config.hidden_act] def _UpperCAmelCase ( self : int ,__SCREAMING_SNAKE_CASE : List[str] ): UpperCAmelCase = hidden_state UpperCAmelCase = self.layer(_SCREAMING_SNAKE_CASE ) UpperCAmelCase = self.shortcut(_SCREAMING_SNAKE_CASE ) hidden_state += residual UpperCAmelCase = self.activation(_SCREAMING_SNAKE_CASE ) return hidden_state class __magic_name__ ( nn.Module): def __init__( self : str ,__SCREAMING_SNAKE_CASE : int ,__SCREAMING_SNAKE_CASE : Any ,__SCREAMING_SNAKE_CASE : str ,__SCREAMING_SNAKE_CASE : List[str] = 2 ,__SCREAMING_SNAKE_CASE : Any = 2 ,): super().__init__() UpperCAmelCase = RegNetXLayer if config.layer_type == "x" else RegNetYLayer UpperCAmelCase = nn.Sequential( # downsampling is done in the first layer with stride of 2 layer( _SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,stride=_SCREAMING_SNAKE_CASE ,) ,*[layer(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) for _ in range(depth - 1 )] ,) def _UpperCAmelCase ( self : int ,__SCREAMING_SNAKE_CASE : Union[str, Any] ): UpperCAmelCase = self.layers(_SCREAMING_SNAKE_CASE ) return hidden_state class __magic_name__ ( nn.Module): def __init__( self : List[str] ,__SCREAMING_SNAKE_CASE : Any ): super().__init__() UpperCAmelCase = nn.ModuleList([] ) # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( RegNetStage( _SCREAMING_SNAKE_CASE ,config.embedding_size ,config.hidden_sizes[0] ,stride=2 if config.downsample_in_first_stage else 1 ,depth=config.depths[0] ,) ) UpperCAmelCase = zip(config.hidden_sizes ,config.hidden_sizes[1:] ) for (in_channels, out_channels), depth in zip(_SCREAMING_SNAKE_CASE ,config.depths[1:] ): self.stages.append(RegNetStage(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,depth=_SCREAMING_SNAKE_CASE ) ) def _UpperCAmelCase ( self : List[Any] ,__SCREAMING_SNAKE_CASE : int ,__SCREAMING_SNAKE_CASE : List[str] = False ,__SCREAMING_SNAKE_CASE : int = True ): UpperCAmelCase = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: UpperCAmelCase = hidden_states + (hidden_state,) UpperCAmelCase = stage_module(_SCREAMING_SNAKE_CASE ) if output_hidden_states: UpperCAmelCase = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return BaseModelOutputWithNoAttention(last_hidden_state=_SCREAMING_SNAKE_CASE ,hidden_states=_SCREAMING_SNAKE_CASE ) class __magic_name__ ( lowerCAmelCase__): _UpperCAmelCase : Any = RegNetConfig _UpperCAmelCase : List[str] = "regnet" _UpperCAmelCase : Optional[int] = "pixel_values" _UpperCAmelCase : Tuple = True def _UpperCAmelCase ( self : Dict ,__SCREAMING_SNAKE_CASE : Tuple ): if isinstance(_SCREAMING_SNAKE_CASE ,nn.Convad ): nn.init.kaiming_normal_(module.weight ,mode="fan_out" ,nonlinearity="relu" ) elif isinstance(_SCREAMING_SNAKE_CASE ,(nn.BatchNormad, nn.GroupNorm) ): nn.init.constant_(module.weight ,1 ) nn.init.constant_(module.bias ,0 ) def _UpperCAmelCase ( self : Tuple ,__SCREAMING_SNAKE_CASE : Any ,__SCREAMING_SNAKE_CASE : List[str]=False ): if isinstance(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ): UpperCAmelCase = value __lowerCAmelCase =R'\n This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it\n as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n behavior.\n\n Parameters:\n config ([`RegNetConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n' __lowerCAmelCase =R'\n Args:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`ConvNextImageProcessor.__call__`] for details.\n\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.\n' @add_start_docstrings( 'The bare RegNet model outputting raw features without any specific head on top.' , lowerCAmelCase__ , ) # Copied from transformers.models.resnet.modeling_resnet.ResNetModel with RESNET->REGNET,ResNet->RegNet class __magic_name__ ( lowerCAmelCase__): def __init__( self : List[str] ,__SCREAMING_SNAKE_CASE : Optional[int] ): super().__init__(_SCREAMING_SNAKE_CASE ) UpperCAmelCase = config UpperCAmelCase = RegNetEmbeddings(_SCREAMING_SNAKE_CASE ) UpperCAmelCase = RegNetEncoder(_SCREAMING_SNAKE_CASE ) UpperCAmelCase = nn.AdaptiveAvgPoolad((1, 1) ) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(_SCREAMING_SNAKE_CASE ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC ,output_type=_SCREAMING_SNAKE_CASE ,config_class=_CONFIG_FOR_DOC ,modality="vision" ,expected_output=_EXPECTED_OUTPUT_SHAPE ,) def _UpperCAmelCase ( self : Any ,__SCREAMING_SNAKE_CASE : List[Any] ,__SCREAMING_SNAKE_CASE : Dict = None ,__SCREAMING_SNAKE_CASE : Dict = None ): UpperCAmelCase = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) UpperCAmelCase = return_dict if return_dict is not None else self.config.use_return_dict UpperCAmelCase = self.embedder(_SCREAMING_SNAKE_CASE ) UpperCAmelCase = self.encoder( _SCREAMING_SNAKE_CASE ,output_hidden_states=_SCREAMING_SNAKE_CASE ,return_dict=_SCREAMING_SNAKE_CASE ) UpperCAmelCase = encoder_outputs[0] UpperCAmelCase = self.pooler(_SCREAMING_SNAKE_CASE ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return BaseModelOutputWithPoolingAndNoAttention( last_hidden_state=_SCREAMING_SNAKE_CASE ,pooler_output=_SCREAMING_SNAKE_CASE ,hidden_states=encoder_outputs.hidden_states ,) @add_start_docstrings( '\n RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n ' , lowerCAmelCase__ , ) # Copied from transformers.models.resnet.modeling_resnet.ResNetForImageClassification with RESNET->REGNET,ResNet->RegNet,resnet->regnet class __magic_name__ ( lowerCAmelCase__): def __init__( self : Dict ,__SCREAMING_SNAKE_CASE : List[Any] ): super().__init__(_SCREAMING_SNAKE_CASE ) UpperCAmelCase = config.num_labels UpperCAmelCase = RegNetModel(_SCREAMING_SNAKE_CASE ) # classification head UpperCAmelCase = nn.Sequential( nn.Flatten() ,nn.Linear(config.hidden_sizes[-1] ,config.num_labels ) if config.num_labels > 0 else nn.Identity() ,) # initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(_SCREAMING_SNAKE_CASE ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT ,output_type=_SCREAMING_SNAKE_CASE ,config_class=_CONFIG_FOR_DOC ,expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT ,) def _UpperCAmelCase ( self : Tuple ,__SCREAMING_SNAKE_CASE : Any = None ,__SCREAMING_SNAKE_CASE : Optional[int] = None ,__SCREAMING_SNAKE_CASE : Any = None ,__SCREAMING_SNAKE_CASE : str = None ,): UpperCAmelCase = return_dict if return_dict is not None else self.config.use_return_dict UpperCAmelCase = self.regnet(_SCREAMING_SNAKE_CASE ,output_hidden_states=_SCREAMING_SNAKE_CASE ,return_dict=_SCREAMING_SNAKE_CASE ) UpperCAmelCase = outputs.pooler_output if return_dict else outputs[1] UpperCAmelCase = self.classifier(_SCREAMING_SNAKE_CASE ) UpperCAmelCase = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: UpperCAmelCase = "regression" elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): UpperCAmelCase = "single_label_classification" else: UpperCAmelCase = "multi_label_classification" if self.config.problem_type == "regression": UpperCAmelCase = MSELoss() if self.num_labels == 1: UpperCAmelCase = loss_fct(logits.squeeze() ,labels.squeeze() ) else: UpperCAmelCase = loss_fct(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) elif self.config.problem_type == "single_label_classification": UpperCAmelCase = CrossEntropyLoss() UpperCAmelCase = loss_fct(logits.view(-1 ,self.num_labels ) ,labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": UpperCAmelCase = BCEWithLogitsLoss() UpperCAmelCase = loss_fct(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) if not return_dict: UpperCAmelCase = (logits,) + outputs[2:] return (loss,) + output if loss is not None else output return ImageClassifierOutputWithNoAttention(loss=_SCREAMING_SNAKE_CASE ,logits=_SCREAMING_SNAKE_CASE ,hidden_states=outputs.hidden_states )
709
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os from accelerate.utils import ComputeEnvironment from .cluster import get_cluster_input from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file # noqa: F401 from .config_utils import _ask_field, _ask_options, _convert_compute_environment # noqa: F401 from .sagemaker import get_sagemaker_input __lowerCAmelCase ="Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine" def __UpperCamelCase ( ): """simple docstring""" UpperCAmelCase = _ask_options( "In which compute environment are you running?" , ["This machine", "AWS (Amazon SageMaker)"] , _convert_compute_environment , ) if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: UpperCAmelCase = get_sagemaker_input() else: UpperCAmelCase = get_cluster_input() return config def __UpperCamelCase ( _lowerCAmelCase=None ): """simple docstring""" if subparsers is not None: UpperCAmelCase = subparsers.add_parser("config" , description=_lowerCAmelCase ) else: UpperCAmelCase = argparse.ArgumentParser("Accelerate config command" , description=_lowerCAmelCase ) parser.add_argument( "--config_file" , default=_lowerCAmelCase , help=( "The path to use to store the config file. Will default to a file named default_config.yaml in the cache " "location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have " "such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed " "with 'huggingface'." ) , ) if subparsers is not None: parser.set_defaults(func=_lowerCAmelCase ) return parser def __UpperCamelCase ( _lowerCAmelCase ): """simple docstring""" UpperCAmelCase = get_user_input() if args.config_file is not None: UpperCAmelCase = args.config_file else: if not os.path.isdir(_lowerCAmelCase ): os.makedirs(_lowerCAmelCase ) UpperCAmelCase = default_yaml_config_file if config_file.endswith(".json" ): config.to_json_file(_lowerCAmelCase ) else: config.to_yaml_file(_lowerCAmelCase ) print(F'''accelerate configuration saved at {config_file}''' ) def __UpperCamelCase ( ): """simple docstring""" UpperCAmelCase = config_command_parser() UpperCAmelCase = parser.parse_args() config_command(_lowerCAmelCase ) if __name__ == "__main__": main()
405
0
def lowerCAmelCase_ ( __A, __A, __A ) -> float: '''simple docstring''' return round(float(moles / volume ) * nfactor ) def lowerCAmelCase_ ( __A, __A, __A ) -> float: '''simple docstring''' return round(float((moles * 0.0821 * temperature) / (volume) ) ) def lowerCAmelCase_ ( __A, __A, __A ) -> float: '''simple docstring''' return round(float((moles * 0.0821 * temperature) / (pressure) ) ) def lowerCAmelCase_ ( __A, __A, __A ) -> float: '''simple docstring''' return round(float((pressure * volume) / (0.0821 * moles) ) ) if __name__ == "__main__": import doctest doctest.testmod()
486
import warnings from typing import List, Optional, Union from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class A ( UpperCAmelCase_ ): __UpperCAmelCase : Any = ['image_processor', 'tokenizer'] __UpperCAmelCase : List[str] = 'FlavaImageProcessor' __UpperCAmelCase : Dict = ('BertTokenizer', 'BertTokenizerFast') def __init__(self : int , __UpperCAmelCase : Dict=None , __UpperCAmelCase : Union[str, Any]=None , **__UpperCAmelCase : Dict ) -> List[Any]: """simple docstring""" UpperCAmelCase__ = 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 , ) UpperCAmelCase__ = kwargs.pop("feature_extractor" ) UpperCAmelCase__ = 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 ) UpperCAmelCase__ = self.image_processor def __call__(self : Optional[int] , __UpperCAmelCase : Optional[ImageInput] = None , __UpperCAmelCase : Optional[Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]]] = None , __UpperCAmelCase : bool = True , __UpperCAmelCase : Union[bool, str, PaddingStrategy] = False , __UpperCAmelCase : Union[bool, str, TruncationStrategy] = False , __UpperCAmelCase : Optional[int] = None , __UpperCAmelCase : int = 0 , __UpperCAmelCase : Optional[int] = None , __UpperCAmelCase : Optional[bool] = None , __UpperCAmelCase : Optional[bool] = None , __UpperCAmelCase : Optional[bool] = None , __UpperCAmelCase : Optional[bool] = None , __UpperCAmelCase : bool = False , __UpperCAmelCase : bool = False , __UpperCAmelCase : bool = False , __UpperCAmelCase : bool = False , __UpperCAmelCase : bool = True , __UpperCAmelCase : Optional[Union[str, TensorType]] = 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: UpperCAmelCase__ = self.tokenizer( text=__UpperCAmelCase , add_special_tokens=__UpperCAmelCase , padding=__UpperCAmelCase , truncation=__UpperCAmelCase , max_length=__UpperCAmelCase , stride=__UpperCAmelCase , pad_to_multiple_of=__UpperCAmelCase , return_token_type_ids=__UpperCAmelCase , return_attention_mask=__UpperCAmelCase , return_overflowing_tokens=__UpperCAmelCase , return_special_tokens_mask=__UpperCAmelCase , return_offsets_mapping=__UpperCAmelCase , return_length=__UpperCAmelCase , verbose=__UpperCAmelCase , return_tensors=__UpperCAmelCase , **__UpperCAmelCase , ) if images is not None: UpperCAmelCase__ = self.image_processor( __UpperCAmelCase , return_image_mask=__UpperCAmelCase , return_codebook_pixels=__UpperCAmelCase , return_tensors=__UpperCAmelCase , **__UpperCAmelCase , ) if text is not None and images is not None: encoding.update(__UpperCAmelCase ) return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**__UpperCAmelCase ) , tensor_type=__UpperCAmelCase ) def lowercase_ (self : Optional[Any] , *__UpperCAmelCase : str , **__UpperCAmelCase : Tuple ) -> int: """simple docstring""" return self.tokenizer.batch_decode(*__UpperCAmelCase , **__UpperCAmelCase ) def lowercase_ (self : int , *__UpperCAmelCase : List[str] , **__UpperCAmelCase : Union[str, Any] ) -> Any: """simple docstring""" return self.tokenizer.decode(*__UpperCAmelCase , **__UpperCAmelCase ) @property def lowercase_ (self : Tuple ) -> Dict: """simple docstring""" UpperCAmelCase__ = self.tokenizer.model_input_names UpperCAmelCase__ = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def lowercase_ (self : Any ) -> Optional[int]: """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 @property def lowercase_ (self : str ) -> Tuple: """simple docstring""" warnings.warn( "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead." , __UpperCAmelCase , ) return self.image_processor
486
1
import argparse import os import gluonnlp as nlp import mxnet as mx import numpy as np import torch from gluonnlp.base import get_home_dir from gluonnlp.model.bert import BERTEncoder from gluonnlp.model.utils import _load_vocab from gluonnlp.vocab import Vocab from packaging import version from torch import nn from transformers import BertConfig, BertForMaskedLM, BertModel, RobertaTokenizer from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertSelfAttention, BertSelfOutput, ) from transformers.utils import logging if version.parse(nlp.__version__) != version.parse('0.8.3'): raise Exception('requires gluonnlp == 0.8.3') if version.parse(mx.__version__) != version.parse('1.5.0'): raise Exception('requires mxnet == 1.5.0') logging.set_verbosity_info() __A : Any = logging.get_logger(__name__) __A : str = 'The Nymphenburg Palace is a beautiful palace in Munich!' def __UpperCamelCase ( _A : str , _A : str ) ->List[str]: """simple docstring""" lowerCamelCase_ ={ """attention_cell""": """multi_head""", """num_layers""": 4, """units""": 1024, """hidden_size""": 768, """max_length""": 512, """num_heads""": 8, """scaled""": True, """dropout""": 0.1, """use_residual""": True, """embed_size""": 1024, """embed_dropout""": 0.1, """word_embed""": None, """layer_norm_eps""": 1E-5, """token_type_vocab_size""": 2, } lowerCamelCase_ =bort_4_8_768_1024_hparams # Let's construct the original Bort model here # Taken from official BERT implementation, see: # https://github.com/alexa/bort/blob/master/bort/bort.py lowerCamelCase_ =BERTEncoder( attention_cell=predefined_args["""attention_cell"""] , num_layers=predefined_args["""num_layers"""] , units=predefined_args["""units"""] , hidden_size=predefined_args["""hidden_size"""] , max_length=predefined_args["""max_length"""] , num_heads=predefined_args["""num_heads"""] , scaled=predefined_args["""scaled"""] , dropout=predefined_args["""dropout"""] , output_attention=_A , output_all_encodings=_A , use_residual=predefined_args["""use_residual"""] , activation=predefined_args.get("""activation""" , """gelu""" ) , layer_norm_eps=predefined_args.get("""layer_norm_eps""" , _A ) , ) # Vocab information needs to be fetched first # It's the same as RoBERTa, so RobertaTokenizer can be used later lowerCamelCase_ ="""openwebtext_ccnews_stories_books_cased""" # Specify download folder to Gluonnlp's vocab lowerCamelCase_ =os.path.join(get_home_dir() , """models""" ) lowerCamelCase_ =_load_vocab(_A , _A , _A , cls=_A ) lowerCamelCase_ =nlp.model.BERTModel( _A , len(_A ) , units=predefined_args["""units"""] , embed_size=predefined_args["""embed_size"""] , embed_dropout=predefined_args["""embed_dropout"""] , word_embed=predefined_args["""word_embed"""] , use_pooler=_A , use_token_type_embed=_A , token_type_vocab_size=predefined_args["""token_type_vocab_size"""] , use_classifier=_A , use_decoder=_A , ) original_bort.load_parameters(_A , cast_dtype=_A , ignore_extra=_A ) lowerCamelCase_ =original_bort._collect_params_with_prefix() # Build our config 🤗 lowerCamelCase_ ={ """architectures""": ["""BertForMaskedLM"""], """attention_probs_dropout_prob""": predefined_args["""dropout"""], """hidden_act""": """gelu""", """hidden_dropout_prob""": predefined_args["""dropout"""], """hidden_size""": predefined_args["""embed_size"""], """initializer_range""": 0.0_2, """intermediate_size""": predefined_args["""hidden_size"""], """layer_norm_eps""": predefined_args["""layer_norm_eps"""], """max_position_embeddings""": predefined_args["""max_length"""], """model_type""": """bort""", """num_attention_heads""": predefined_args["""num_heads"""], """num_hidden_layers""": predefined_args["""num_layers"""], """pad_token_id""": 1, # 2 = BERT, 1 = RoBERTa """type_vocab_size""": 1, # 2 = BERT, 1 = RoBERTa """vocab_size""": len(_A ), } lowerCamelCase_ =BertConfig.from_dict(_A ) lowerCamelCase_ =BertForMaskedLM(_A ) hf_bort_model.eval() # Parameter mapping table (Gluonnlp to Transformers) # * denotes layer index # # | Gluon Parameter | Transformers Parameter # | -------------------------------------------------------------- | ---------------------- # | `encoder.layer_norm.beta` | `bert.embeddings.LayerNorm.bias` # | `encoder.layer_norm.gamma` | `bert.embeddings.LayerNorm.weight` # | `encoder.position_weight` | `bert.embeddings.position_embeddings.weight` # | `word_embed.0.weight` | `bert.embeddings.word_embeddings.weight` # | `encoder.transformer_cells.*.attention_cell.proj_key.bias` | `bert.encoder.layer.*.attention.self.key.bias` # | `encoder.transformer_cells.*.attention_cell.proj_key.weight` | `bert.encoder.layer.*.attention.self.key.weight` # | `encoder.transformer_cells.*.attention_cell.proj_query.bias` | `bert.encoder.layer.*.attention.self.query.bias` # | `encoder.transformer_cells.*.attention_cell.proj_query.weight` | `bert.encoder.layer.*.attention.self.query.weight` # | `encoder.transformer_cells.*.attention_cell.proj_value.bias` | `bert.encoder.layer.*.attention.self.value.bias` # | `encoder.transformer_cells.*.attention_cell.proj_value.weight` | `bert.encoder.layer.*.attention.self.value.weight` # | `encoder.transformer_cells.*.ffn.ffn_2.bias` | `bert.encoder.layer.*.attention.output.dense.bias` # | `encoder.transformer_cells.*.ffn.ffn_2.weight` | `bert.encoder.layer.*.attention.output.dense.weight` # | `encoder.transformer_cells.*.layer_norm.beta` | `bert.encoder.layer.*.attention.output.LayerNorm.bias` # | `encoder.transformer_cells.*.layer_norm.gamma` | `bert.encoder.layer.*.attention.output.LayerNorm.weight` # | `encoder.transformer_cells.*.ffn.ffn_1.bias` | `bert.encoder.layer.*.intermediate.dense.bias` # | `encoder.transformer_cells.*.ffn.ffn_1.weight` | `bert.encoder.layer.*.intermediate.dense.weight` # | `encoder.transformer_cells.*.ffn.layer_norm.beta` | `bert.encoder.layer.*.output.LayerNorm.bias` # | `encoder.transformer_cells.*.ffn.layer_norm.gamma` | `bert.encoder.layer.*.output.LayerNorm.weight` # | `encoder.transformer_cells.*.proj.bias` | `bert.encoder.layer.*.output.dense.bias` # | `encoder.transformer_cells.*.proj.weight` | `bert.encoder.layer.*.output.dense.weight` # Helper function to convert MXNET Arrays to PyTorch def to_torch(_A : Dict ) -> nn.Parameter: return nn.Parameter(torch.FloatTensor(mx_array.data().asnumpy() ) ) # Check param shapes and map new HF param back def check_and_map_params(_A : List[str] , _A : Any ): lowerCamelCase_ =hf_param.shape lowerCamelCase_ =to_torch(params[gluon_param] ) lowerCamelCase_ =gluon_param.shape assert ( shape_hf == shape_gluon ), f'The gluon parameter {gluon_param} has shape {shape_gluon}, but expects shape {shape_hf} for Transformers' return gluon_param lowerCamelCase_ =check_and_map_params( hf_bort_model.bert.embeddings.word_embeddings.weight , """word_embed.0.weight""" ) lowerCamelCase_ =check_and_map_params( hf_bort_model.bert.embeddings.position_embeddings.weight , """encoder.position_weight""" ) lowerCamelCase_ =check_and_map_params( hf_bort_model.bert.embeddings.LayerNorm.bias , """encoder.layer_norm.beta""" ) lowerCamelCase_ =check_and_map_params( hf_bort_model.bert.embeddings.LayerNorm.weight , """encoder.layer_norm.gamma""" ) # Inspired by RoBERTa conversion script, we just zero them out (Bort does not use them) lowerCamelCase_ =torch.zeros_like( hf_bort_model.bert.embeddings.token_type_embeddings.weight.data ) for i in range(hf_bort_config.num_hidden_layers ): lowerCamelCase_ =hf_bort_model.bert.encoder.layer[i] # self attention lowerCamelCase_ =layer.attention.self lowerCamelCase_ =check_and_map_params( self_attn.key.bias.data , f'encoder.transformer_cells.{i}.attention_cell.proj_key.bias' ) lowerCamelCase_ =check_and_map_params( self_attn.key.weight.data , f'encoder.transformer_cells.{i}.attention_cell.proj_key.weight' ) lowerCamelCase_ =check_and_map_params( self_attn.query.bias.data , f'encoder.transformer_cells.{i}.attention_cell.proj_query.bias' ) lowerCamelCase_ =check_and_map_params( self_attn.query.weight.data , f'encoder.transformer_cells.{i}.attention_cell.proj_query.weight' ) lowerCamelCase_ =check_and_map_params( self_attn.value.bias.data , f'encoder.transformer_cells.{i}.attention_cell.proj_value.bias' ) lowerCamelCase_ =check_and_map_params( self_attn.value.weight.data , f'encoder.transformer_cells.{i}.attention_cell.proj_value.weight' ) # self attention output lowerCamelCase_ =layer.attention.output lowerCamelCase_ =check_and_map_params( self_output.dense.bias , f'encoder.transformer_cells.{i}.proj.bias' ) lowerCamelCase_ =check_and_map_params( self_output.dense.weight , f'encoder.transformer_cells.{i}.proj.weight' ) lowerCamelCase_ =check_and_map_params( self_output.LayerNorm.bias , f'encoder.transformer_cells.{i}.layer_norm.beta' ) lowerCamelCase_ =check_and_map_params( self_output.LayerNorm.weight , f'encoder.transformer_cells.{i}.layer_norm.gamma' ) # intermediate lowerCamelCase_ =layer.intermediate lowerCamelCase_ =check_and_map_params( intermediate.dense.bias , f'encoder.transformer_cells.{i}.ffn.ffn_1.bias' ) lowerCamelCase_ =check_and_map_params( intermediate.dense.weight , f'encoder.transformer_cells.{i}.ffn.ffn_1.weight' ) # output lowerCamelCase_ =layer.output lowerCamelCase_ =check_and_map_params( bert_output.dense.bias , f'encoder.transformer_cells.{i}.ffn.ffn_2.bias' ) lowerCamelCase_ =check_and_map_params( bert_output.dense.weight , f'encoder.transformer_cells.{i}.ffn.ffn_2.weight' ) lowerCamelCase_ =check_and_map_params( bert_output.LayerNorm.bias , f'encoder.transformer_cells.{i}.ffn.layer_norm.beta' ) lowerCamelCase_ =check_and_map_params( bert_output.LayerNorm.weight , f'encoder.transformer_cells.{i}.ffn.layer_norm.gamma' ) # Save space and energy 🎄 hf_bort_model.half() # Compare output of both models lowerCamelCase_ =RobertaTokenizer.from_pretrained("""roberta-base""" ) lowerCamelCase_ =tokenizer.encode_plus(_A )["""input_ids"""] # Get gluon output lowerCamelCase_ =mx.nd.array([input_ids] ) lowerCamelCase_ =original_bort(inputs=_A , token_types=[] ) # Get Transformer output (save and reload model again) hf_bort_model.save_pretrained(_A ) lowerCamelCase_ =BertModel.from_pretrained(_A ) hf_bort_model.eval() lowerCamelCase_ =tokenizer.encode_plus(_A , return_tensors="""pt""" ) lowerCamelCase_ =hf_bort_model(**_A )[0] lowerCamelCase_ =output_gluon[0].asnumpy() lowerCamelCase_ =output_hf[0].detach().numpy() lowerCamelCase_ =np.max(np.abs(hf_layer - gluon_layer ) ).item() lowerCamelCase_ =np.allclose(_A , _A , atol=1E-3 ) if success: print("""✔️ Both model do output the same tensors""" ) else: print("""❌ Both model do **NOT** output the same tensors""" ) print("""Absolute difference is:""" , _A ) if __name__ == "__main__": __A : Dict = argparse.ArgumentParser() # Required parameters parser.add_argument( '--bort_checkpoint_path', default=None, type=str, required=True, help='Path the official Bort params file.' ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) __A : List[str] = parser.parse_args() convert_bort_checkpoint_to_pytorch(args.bort_checkpoint_path, args.pytorch_dump_folder_path)
75
from ..utils import DummyObject, requires_backends class _SCREAMING_SNAKE_CASE ( metaclass=lowerCAmelCase__): _UpperCamelCase:List[Any] = ["torch", "torchsde"] def __init__( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> List[Any]: requires_backends(self , ["""torch""", """torchsde"""] ) @classmethod def _snake_case ( cls , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> Union[str, Any]: requires_backends(cls , ["""torch""", """torchsde"""] ) @classmethod def _snake_case ( cls , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> str: requires_backends(cls , ["""torch""", """torchsde"""] )
75
1
import unittest import numpy as np from transformers import AlbertConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.albert.modeling_flax_albert import ( FlaxAlbertForMaskedLM, FlaxAlbertForMultipleChoice, FlaxAlbertForPreTraining, FlaxAlbertForQuestionAnswering, FlaxAlbertForSequenceClassification, FlaxAlbertForTokenClassification, FlaxAlbertModel, ) class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def __init__( self : str ,A : List[str] ,A : List[Any]=13 ,A : Optional[int]=7 ,A : Tuple=True ,A : Tuple=True ,A : Tuple=True ,A : Optional[Any]=True ,A : Optional[int]=99 ,A : Optional[Any]=32 ,A : int=5 ,A : List[Any]=4 ,A : Union[str, Any]=37 ,A : int="gelu" ,A : int=0.1 ,A : List[Any]=0.1 ,A : List[str]=5_12 ,A : int=16 ,A : str=2 ,A : int=0.02 ,A : Optional[Any]=4 ,): __A = parent __A = batch_size __A = seq_length __A = is_training __A = use_attention_mask __A = use_token_type_ids __A = use_labels __A = vocab_size __A = hidden_size __A = num_hidden_layers __A = num_attention_heads __A = intermediate_size __A = hidden_act __A = hidden_dropout_prob __A = attention_probs_dropout_prob __A = max_position_embeddings __A = type_vocab_size __A = type_sequence_label_size __A = initializer_range __A = num_choices def UpperCamelCase_ ( self : Dict ): __A = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) __A = None if self.use_attention_mask: __A = random_attention_mask([self.batch_size, self.seq_length] ) __A = None if self.use_token_type_ids: __A = ids_tensor([self.batch_size, self.seq_length] ,self.type_vocab_size ) __A = AlbertConfig( vocab_size=self.vocab_size ,hidden_size=self.hidden_size ,num_hidden_layers=self.num_hidden_layers ,num_attention_heads=self.num_attention_heads ,intermediate_size=self.intermediate_size ,hidden_act=self.hidden_act ,hidden_dropout_prob=self.hidden_dropout_prob ,attention_probs_dropout_prob=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,type_vocab_size=self.type_vocab_size ,is_decoder=A ,initializer_range=self.initializer_range ,) return config, input_ids, token_type_ids, attention_mask def UpperCamelCase_ ( self : Dict ): __A = self.prepare_config_and_inputs() __A , __A , __A , __A = config_and_inputs __A = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": attention_mask} return config, inputs_dict @require_flax class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' snake_case_ = ( ( FlaxAlbertModel, FlaxAlbertForPreTraining, FlaxAlbertForMaskedLM, FlaxAlbertForMultipleChoice, FlaxAlbertForQuestionAnswering, FlaxAlbertForSequenceClassification, FlaxAlbertForTokenClassification, FlaxAlbertForQuestionAnswering, ) if is_flax_available() else () ) def UpperCamelCase_ ( self : List[Any] ): __A = FlaxAlbertModelTester(self ) @slow def UpperCamelCase_ ( self : List[Any] ): for model_class_name in self.all_model_classes: __A = model_class_name.from_pretrained("albert-base-v2" ) __A = model(np.ones((1, 1) ) ) self.assertIsNotNone(A ) @require_flax class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' @slow def UpperCamelCase_ ( self : Optional[Any] ): __A = FlaxAlbertModel.from_pretrained("albert-base-v2" ) __A = np.array([[0, 3_45, 2_32, 3_28, 7_40, 1_40, 16_95, 69, 60_78, 15_88, 2]] ) __A = np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) __A = model(A ,attention_mask=A )[0] __A = (1, 11, 7_68) self.assertEqual(output.shape ,A ) __A = np.array( [[[-0.65_13, 1.50_35, -0.27_66], [-0.65_15, 1.50_46, -0.27_80], [-0.65_12, 1.50_49, -0.27_84]]] ) self.assertTrue(jnp.allclose(output[:, 1:4, 1:4] ,A ,atol=1E-4 ) )
55
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase__ = { '''configuration_longformer''': [ '''LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''LongformerConfig''', '''LongformerOnnxConfig''', ], '''tokenization_longformer''': ['''LongformerTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = ['''LongformerTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ '''LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''LongformerForMaskedLM''', '''LongformerForMultipleChoice''', '''LongformerForQuestionAnswering''', '''LongformerForSequenceClassification''', '''LongformerForTokenClassification''', '''LongformerModel''', '''LongformerPreTrainedModel''', '''LongformerSelfAttention''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ '''TF_LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFLongformerForMaskedLM''', '''TFLongformerForMultipleChoice''', '''TFLongformerForQuestionAnswering''', '''TFLongformerForSequenceClassification''', '''TFLongformerForTokenClassification''', '''TFLongformerModel''', '''TFLongformerPreTrainedModel''', '''TFLongformerSelfAttention''', ] if TYPE_CHECKING: from .configuration_longformer import ( LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, LongformerConfig, LongformerOnnxConfig, ) from .tokenization_longformer import LongformerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_longformer_fast import LongformerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_longformer import ( LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, LongformerForMaskedLM, LongformerForMultipleChoice, LongformerForQuestionAnswering, LongformerForSequenceClassification, LongformerForTokenClassification, LongformerModel, LongformerPreTrainedModel, LongformerSelfAttention, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_longformer import ( TF_LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFLongformerForMaskedLM, TFLongformerForMultipleChoice, TFLongformerForQuestionAnswering, TFLongformerForSequenceClassification, TFLongformerForTokenClassification, TFLongformerModel, TFLongformerPreTrainedModel, TFLongformerSelfAttention, ) else: import sys lowerCamelCase__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
547
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) a__ : Any = { """configuration_whisper""": ["""WHISPER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """WhisperConfig""", """WhisperOnnxConfig"""], """feature_extraction_whisper""": ["""WhisperFeatureExtractor"""], """processing_whisper""": ["""WhisperProcessor"""], """tokenization_whisper""": ["""WhisperTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Tuple = ["""WhisperTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Tuple = [ """WHISPER_PRETRAINED_MODEL_ARCHIVE_LIST""", """WhisperForConditionalGeneration""", """WhisperModel""", """WhisperPreTrainedModel""", """WhisperForAudioClassification""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Union[str, Any] = [ """TF_WHISPER_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFWhisperForConditionalGeneration""", """TFWhisperModel""", """TFWhisperPreTrainedModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Optional[Any] = [ """FlaxWhisperForConditionalGeneration""", """FlaxWhisperModel""", """FlaxWhisperPreTrainedModel""", """FlaxWhisperForAudioClassification""", ] if TYPE_CHECKING: from .configuration_whisper import WHISPER_PRETRAINED_CONFIG_ARCHIVE_MAP, WhisperConfig, WhisperOnnxConfig from .feature_extraction_whisper import WhisperFeatureExtractor from .processing_whisper import WhisperProcessor from .tokenization_whisper import WhisperTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_whisper_fast import WhisperTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_whisper import ( WHISPER_PRETRAINED_MODEL_ARCHIVE_LIST, WhisperForAudioClassification, WhisperForConditionalGeneration, WhisperModel, WhisperPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_whisper import ( TF_WHISPER_PRETRAINED_MODEL_ARCHIVE_LIST, TFWhisperForConditionalGeneration, TFWhisperModel, TFWhisperPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_whisper import ( FlaxWhisperForAudioClassification, FlaxWhisperForConditionalGeneration, FlaxWhisperModel, FlaxWhisperPreTrainedModel, ) else: import sys a__ : Tuple = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
702
"""simple docstring""" from __future__ import annotations import numpy as np def A__ ( __lowerCamelCase ): """simple docstring""" return np.maximum(0, __lowerCamelCase ) if __name__ == "__main__": print(np.array(relu([-1, 0, 5]))) # --> [0, 0, 5]
309
0
"""simple docstring""" import os from tempfile import TemporaryDirectory from unittest import TestCase import pytest from absl.testing import parameterized from datasets import config from datasets.arrow_reader import HF_GCP_BASE_URL from datasets.builder import DatasetBuilder from datasets.dataset_dict import IterableDatasetDict from datasets.iterable_dataset import IterableDataset from datasets.load import dataset_module_factory, import_main_class from datasets.utils.file_utils import cached_path _lowercase = [ {'''dataset''': '''wikipedia''', '''config_name''': '''20220301.de'''}, {'''dataset''': '''wikipedia''', '''config_name''': '''20220301.en'''}, {'''dataset''': '''wikipedia''', '''config_name''': '''20220301.fr'''}, {'''dataset''': '''wikipedia''', '''config_name''': '''20220301.frr'''}, {'''dataset''': '''wikipedia''', '''config_name''': '''20220301.it'''}, {'''dataset''': '''wikipedia''', '''config_name''': '''20220301.simple'''}, {'''dataset''': '''snli''', '''config_name''': '''plain_text'''}, {'''dataset''': '''eli5''', '''config_name''': '''LFQA_reddit'''}, {'''dataset''': '''wiki40b''', '''config_name''': '''en'''}, {'''dataset''': '''wiki_dpr''', '''config_name''': '''psgs_w100.nq.compressed'''}, {'''dataset''': '''wiki_dpr''', '''config_name''': '''psgs_w100.nq.no_index'''}, {'''dataset''': '''wiki_dpr''', '''config_name''': '''psgs_w100.multiset.no_index'''}, {'''dataset''': '''natural_questions''', '''config_name''': '''default'''}, ] def _snake_case ( snake_case__ : str=True ): if with_config: return [ { "testcase_name": d["dataset"] + "/" + d["config_name"], "dataset": d["dataset"], "config_name": d["config_name"], } for d in DATASETS_ON_HF_GCP ] else: return [ {"testcase_name": dataset, "dataset": dataset} for dataset in {d["dataset"] for d in DATASETS_ON_HF_GCP} ] @parameterized.named_parameters(list_datasets_on_hf_gcp_parameters(with_config=_lowercase ) ) class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: Optional[Any] = None _lowerCamelCase: str = None def _SCREAMING_SNAKE_CASE ( self : Tuple ,A_ : int ,A_ : Tuple ) -> Any: with TemporaryDirectory() as tmp_dir: A = dataset_module_factory(A_ ,cache_dir=A_ ) A = import_main_class(dataset_module.module_path ,dataset=A_ ) A = builder_cls( cache_dir=A_ ,config_name=A_ ,hash=dataset_module.hash ,) A = '/'.join( [ HF_GCP_BASE_URL, builder_instance._relative_data_dir(with_hash=A_ ).replace(os.sep ,'/' ), config.DATASET_INFO_FILENAME, ] ) A = cached_path(A_ ,cache_dir=A_ ) self.assertTrue(os.path.exists(A_ ) ) @pytest.mark.integration def _snake_case ( snake_case__ : Optional[int] ): A = tmp_path_factory.mktemp('test_hf_gcp' ) / 'test_wikipedia_simple' A = dataset_module_factory('wikipedia' , cache_dir=snake_case__ ) A = import_main_class(dataset_module.module_path ) A = builder_cls( cache_dir=snake_case__ , config_name='20220301.frr' , hash=dataset_module.hash , ) # use the HF cloud storage, not the original download_and_prepare that uses apache-beam A = None builder_instance.download_and_prepare() A = builder_instance.as_dataset() assert ds @pytest.mark.integration def _snake_case ( snake_case__ : List[Any] ): A = dataset_module_factory('wikipedia' , cache_dir=snake_case__ ) A = import_main_class(dataset_module.module_path , dataset=snake_case__ ) A = builder_cls( cache_dir=snake_case__ , config_name='20220301.frr' , hash=dataset_module.hash , ) A = builder_instance.as_streaming_dataset() assert ds assert isinstance(snake_case__ , snake_case__ ) assert "train" in ds assert isinstance(ds['train'] , snake_case__ ) assert next(iter(ds['train'] ) )
91
'''simple docstring''' import unittest import numpy as np from transformers import RobertaPreLayerNormConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.roberta_prelayernorm.modeling_flax_roberta_prelayernorm import ( FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormModel, ) class A__ ( unittest.TestCase ): def __init__( self :List[Any] , SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :Any=1_3 , SCREAMING_SNAKE_CASE :Any=7 , SCREAMING_SNAKE_CASE :Any=True , SCREAMING_SNAKE_CASE :int=True , SCREAMING_SNAKE_CASE :Optional[int]=True , SCREAMING_SNAKE_CASE :List[str]=True , SCREAMING_SNAKE_CASE :Optional[Any]=9_9 , SCREAMING_SNAKE_CASE :Tuple=3_2 , SCREAMING_SNAKE_CASE :Union[str, Any]=5 , SCREAMING_SNAKE_CASE :List[str]=4 , SCREAMING_SNAKE_CASE :int=3_7 , SCREAMING_SNAKE_CASE :Optional[Any]="gelu" , SCREAMING_SNAKE_CASE :Optional[int]=0.1 , SCREAMING_SNAKE_CASE :List[Any]=0.1 , SCREAMING_SNAKE_CASE :Dict=5_1_2 , SCREAMING_SNAKE_CASE :List[Any]=1_6 , SCREAMING_SNAKE_CASE :Union[str, Any]=2 , SCREAMING_SNAKE_CASE :List[Any]=0.02 , SCREAMING_SNAKE_CASE :int=4 , ) -> Tuple: '''simple docstring''' _a : Optional[Any] =parent _a : List[str] =batch_size _a : List[str] =seq_length _a : List[Any] =is_training _a : Optional[int] =use_attention_mask _a : List[Any] =use_token_type_ids _a : List[Any] =use_labels _a : Optional[Any] =vocab_size _a : str =hidden_size _a : List[Any] =num_hidden_layers _a : List[Any] =num_attention_heads _a : Union[str, Any] =intermediate_size _a : int =hidden_act _a : List[str] =hidden_dropout_prob _a : Optional[int] =attention_probs_dropout_prob _a : Dict =max_position_embeddings _a : Any =type_vocab_size _a : str =type_sequence_label_size _a : str =initializer_range _a : List[str] =num_choices def __UpperCAmelCase ( self :Union[str, Any] ) -> Dict: '''simple docstring''' _a : str =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _a : Dict =None if self.use_attention_mask: _a : Any =random_attention_mask([self.batch_size, self.seq_length] ) _a : Optional[int] =None if self.use_token_type_ids: _a : Any =ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _a : Union[str, Any] =RobertaPreLayerNormConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def __UpperCAmelCase ( self :Optional[Any] ) -> int: '''simple docstring''' _a : Tuple =self.prepare_config_and_inputs() _a , _a , _a , _a : List[Any] =config_and_inputs _a : Optional[int] ={"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": attention_mask} return config, inputs_dict def __UpperCAmelCase ( self :int ) -> str: '''simple docstring''' _a : List[Any] =self.prepare_config_and_inputs() _a , _a , _a , _a : Optional[int] =config_and_inputs _a : Tuple =True _a : Optional[Any] =floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) _a : Optional[int] =ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, encoder_hidden_states, encoder_attention_mask, ) @require_flax # Copied from tests.models.roberta.test_modelling_flax_roberta.FlaxRobertaPreLayerNormModelTest with ROBERTA->ROBERTA_PRELAYERNORM,Roberta->RobertaPreLayerNorm,roberta-base->andreasmadsen/efficient_mlm_m0.40 class A__ ( UpperCAmelCase__ , unittest.TestCase ): __UpperCamelCase : Union[str, Any] = True __UpperCamelCase : Dict = ( ( FlaxRobertaPreLayerNormModel, FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, ) if is_flax_available() else () ) def __UpperCAmelCase ( self :List[str] ) -> Optional[int]: '''simple docstring''' _a : Union[str, Any] =FlaxRobertaPreLayerNormModelTester(self ) @slow def __UpperCAmelCase ( self :str ) -> int: '''simple docstring''' for model_class_name in self.all_model_classes: _a : Optional[int] =model_class_name.from_pretrained("""andreasmadsen/efficient_mlm_m0.40""" , from_pt=SCREAMING_SNAKE_CASE ) _a : Dict =model(np.ones((1, 1) ) ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) @require_flax class A__ ( unittest.TestCase ): @slow def __UpperCAmelCase ( self :Any ) -> str: '''simple docstring''' _a : str =FlaxRobertaPreLayerNormForMaskedLM.from_pretrained("""andreasmadsen/efficient_mlm_m0.40""" , from_pt=SCREAMING_SNAKE_CASE ) _a : List[Any] =np.array([[0, 3_1_4_1_4, 2_3_2, 3_2_8, 7_4_0, 1_1_4_0, 1_2_6_9_5, 6_9, 4_6_0_7_8, 1_5_8_8, 2]] , dtype=jnp.intaa ) _a : Dict =model(SCREAMING_SNAKE_CASE )[0] _a : List[Any] =[1, 1_1, 5_0_2_6_5] self.assertEqual(list(output.shape ) , SCREAMING_SNAKE_CASE ) # compare the actual values for a slice. _a : Any =np.array( [[[40.4_880, 18.0_199, -5.2_367], [-1.8_877, -4.0_885, 10.7_085], [-2.2_613, -5.6_110, 7.2_665]]] , dtype=np.floataa ) self.assertTrue(np.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) ) @slow def __UpperCAmelCase ( self :int ) -> int: '''simple docstring''' _a : Union[str, Any] =FlaxRobertaPreLayerNormModel.from_pretrained("""andreasmadsen/efficient_mlm_m0.40""" , from_pt=SCREAMING_SNAKE_CASE ) _a : Any =np.array([[0, 3_1_4_1_4, 2_3_2, 3_2_8, 7_4_0, 1_1_4_0, 1_2_6_9_5, 6_9, 4_6_0_7_8, 1_5_8_8, 2]] , dtype=jnp.intaa ) _a : Optional[int] =model(SCREAMING_SNAKE_CASE )[0] # compare the actual values for a slice. _a : str =np.array( [[[0.0_208, -0.0_356, 0.0_237], [-0.1_569, -0.0_411, -0.2_626], [0.1_879, 0.0_125, -0.0_089]]] , dtype=np.floataa ) self.assertTrue(np.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) )
694
0
'''simple docstring''' import os from bleurt import score # From: git+https://github.com/google-research/bleurt.git import datasets a_ :Optional[Any] = datasets.logging.get_logger(__name__) a_ :List[str] = "\\n@inproceedings{bleurt,\n title={BLEURT: Learning Robust Metrics for Text Generation},\n author={Thibault Sellam and Dipanjan Das and Ankur P. Parikh},\n booktitle={ACL},\n year={2020},\n url={https://arxiv.org/abs/2004.04696}\n}\n" a_ :List[str] = "\\nBLEURT a learnt evaluation metric for Natural Language Generation. It is built using multiple phases of transfer learning starting from a pretrained BERT model (Devlin et al. 2018)\nand then employing another pre-training phrase using synthetic data. Finally it is trained on WMT human annotations. You may run BLEURT out-of-the-box or fine-tune\nit for your specific application (the latter is expected to perform better).\n\nSee the project's README at https://github.com/google-research/bleurt#readme for more information.\n" a_ :Optional[int] = "\nBLEURT score.\n\nArgs:\n `predictions` (list of str): prediction/candidate sentences\n `references` (list of str): reference sentences\n `checkpoint` BLEURT checkpoint. Will default to BLEURT-tiny if None.\n\nReturns:\n 'scores': List of scores.\nExamples:\n\n >>> predictions = [\"hello there\", \"general kenobi\"]\n >>> references = [\"hello there\", \"general kenobi\"]\n >>> bleurt = datasets.load_metric(\"bleurt\")\n >>> results = bleurt.compute(predictions=predictions, references=references)\n >>> print([round(v, 2) for v in results[\"scores\"]])\n [1.03, 1.04]\n" a_ :Optional[int] = { "bleurt-tiny-128": "https://storage.googleapis.com/bleurt-oss/bleurt-tiny-128.zip", "bleurt-tiny-512": "https://storage.googleapis.com/bleurt-oss/bleurt-tiny-512.zip", "bleurt-base-128": "https://storage.googleapis.com/bleurt-oss/bleurt-base-128.zip", "bleurt-base-512": "https://storage.googleapis.com/bleurt-oss/bleurt-base-512.zip", "bleurt-large-128": "https://storage.googleapis.com/bleurt-oss/bleurt-large-128.zip", "bleurt-large-512": "https://storage.googleapis.com/bleurt-oss/bleurt-large-512.zip", "BLEURT-20-D3": "https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D3.zip", "BLEURT-20-D6": "https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D6.zip", "BLEURT-20-D12": "https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D12.zip", "BLEURT-20": "https://storage.googleapis.com/bleurt-oss-21/BLEURT-20.zip", } @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class snake_case__ ( datasets.Metric ): """simple docstring""" def lowercase_ ( self : str ) ->int: return datasets.MetricInfo( description=_DESCRIPTION, citation=_CITATION, homepage='https://github.com/google-research/bleurt', inputs_description=_KWARGS_DESCRIPTION, features=datasets.Features( { 'predictions': datasets.Value('string', id='sequence' ), 'references': datasets.Value('string', id='sequence' ), } ), codebase_urls=['https://github.com/google-research/bleurt'], reference_urls=['https://github.com/google-research/bleurt', 'https://arxiv.org/abs/2004.04696'], ) def lowercase_ ( self : Union[str, Any], _snake_case : List[Any] ) ->Any: # check that config name specifies a valid BLEURT model if self.config_name == "default": logger.warning( 'Using default BLEURT-Base checkpoint for sequence maximum length 128. ' 'You can use a bigger model for better results with e.g.: datasets.load_metric(\'bleurt\', \'bleurt-large-512\').' ) snake_case__ : Optional[Any] = 'bleurt-base-128' if self.config_name.lower() in CHECKPOINT_URLS: snake_case__ : Union[str, Any] = self.config_name.lower() elif self.config_name.upper() in CHECKPOINT_URLS: snake_case__ : Optional[Any] = self.config_name.upper() else: raise KeyError( F'''{self.config_name} model not found. You should supply the name of a model checkpoint for bleurt in {CHECKPOINT_URLS.keys()}''' ) # download the model checkpoint specified by self.config_name and set up the scorer snake_case__ : List[str] = dl_manager.download_and_extract(CHECKPOINT_URLS[checkpoint_name] ) snake_case__ : List[str] = score.BleurtScorer(os.path.join(_snake_case, _snake_case ) ) def lowercase_ ( self : Tuple, _snake_case : Union[str, Any], _snake_case : Tuple ) ->Any: snake_case__ : Union[str, Any] = self.scorer.score(references=_snake_case, candidates=_snake_case ) return {"scores": scores}
700
import argparse import collections import torch from flax import traverse_util from tax import checkpoints from transformers import TaConfig, TaEncoderModel, TaForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() def lowercase_ (A : Optional[int] , A : Tuple , A : List[Any] , A : List[str]="attention" ): snake_case__ : str = params[F'''{prefix}/layers_{i}/{layer_name}/key/kernel'''] snake_case__ : List[str] = params[F'''{prefix}/layers_{i}/{layer_name}/out/kernel'''] snake_case__ : Optional[int] = params[F'''{prefix}/layers_{i}/{layer_name}/query/kernel'''] snake_case__ : Union[str, Any] = params[F'''{prefix}/layers_{i}/{layer_name}/value/kernel'''] return k, o, q, v def lowercase_ (A : Tuple , A : Union[str, Any] , A : int , A : Any=False ): if split_mlp_wi: snake_case__ : Dict = params[F'''{prefix}/layers_{i}/mlp/wi_0/kernel'''] snake_case__ : List[str] = params[F'''{prefix}/layers_{i}/mlp/wi_1/kernel'''] snake_case__ : Optional[Any] = (wi_a, wi_a) else: snake_case__ : Optional[Any] = params[F'''{prefix}/layers_{i}/mlp/wi/kernel'''] snake_case__ : Tuple = params[F'''{prefix}/layers_{i}/mlp/wo/kernel'''] return wi, wo def lowercase_ (A : Optional[int] , A : Dict , A : Any , A : List[str] ): return params[F'''{prefix}/layers_{i}/{layer_name}/scale'''] def lowercase_ (A : dict , *, A : int , A : bool ): snake_case__ : Dict = traverse_util.flatten_dict(variables['target'] ) snake_case__ : Union[str, Any] = {'/'.join(A ): v for k, v in old.items()} # v1.1 models have a gated GeLU with wi_0 and wi_1 instead of wi snake_case__ : Union[str, Any] = 'encoder/layers_0/mlp/wi_0/kernel' in old print('Split MLP:' , A ) snake_case__ : int = collections.OrderedDict() # Shared embeddings. snake_case__ : Dict = old['token_embedder/embedding'] # Encoder. for i in range(A ): # Block i, layer 0 (Self Attention). snake_case__ : Dict = tax_layer_norm_lookup(A , A , 'encoder' , 'pre_attention_layer_norm' ) snake_case__ , snake_case__ , snake_case__ , snake_case__ : Dict = tax_attention_lookup(A , A , 'encoder' , 'attention' ) snake_case__ : Optional[Any] = layer_norm snake_case__ : Union[str, Any] = k.T snake_case__ : List[Any] = o.T snake_case__ : Any = q.T snake_case__ : Union[str, Any] = v.T # Block i, layer 1 (MLP). snake_case__ : List[str] = tax_layer_norm_lookup(A , A , 'encoder' , 'pre_mlp_layer_norm' ) snake_case__ , snake_case__ : Dict = tax_mlp_lookup(A , A , 'encoder' , A ) snake_case__ : Optional[int] = layer_norm if split_mlp_wi: snake_case__ : Union[str, Any] = wi[0].T snake_case__ : int = wi[1].T else: snake_case__ : Optional[int] = wi.T snake_case__ : Tuple = wo.T snake_case__ : Optional[int] = old[ 'encoder/relpos_bias/rel_embedding' ].T snake_case__ : str = old['encoder/encoder_norm/scale'] if not is_encoder_only: # Decoder. for i in range(A ): # Block i, layer 0 (Self Attention). snake_case__ : List[str] = tax_layer_norm_lookup(A , A , 'decoder' , 'pre_self_attention_layer_norm' ) snake_case__ , snake_case__ , snake_case__ , snake_case__ : List[str] = tax_attention_lookup(A , A , 'decoder' , 'self_attention' ) snake_case__ : int = layer_norm snake_case__ : List[Any] = k.T snake_case__ : Tuple = o.T snake_case__ : Any = q.T snake_case__ : List[str] = v.T # Block i, layer 1 (Cross Attention). snake_case__ : List[str] = tax_layer_norm_lookup(A , A , 'decoder' , 'pre_cross_attention_layer_norm' ) snake_case__ , snake_case__ , snake_case__ , snake_case__ : int = tax_attention_lookup(A , A , 'decoder' , 'encoder_decoder_attention' ) snake_case__ : List[Any] = layer_norm snake_case__ : Union[str, Any] = k.T snake_case__ : List[str] = o.T snake_case__ : List[str] = q.T snake_case__ : List[Any] = v.T # Block i, layer 2 (MLP). snake_case__ : Any = tax_layer_norm_lookup(A , A , 'decoder' , 'pre_mlp_layer_norm' ) snake_case__ , snake_case__ : Tuple = tax_mlp_lookup(A , A , 'decoder' , A ) snake_case__ : List[str] = layer_norm if split_mlp_wi: snake_case__ : Any = wi[0].T snake_case__ : str = wi[1].T else: snake_case__ : Optional[int] = wi.T snake_case__ : int = wo.T snake_case__ : Dict = old['decoder/decoder_norm/scale'] snake_case__ : int = old[ 'decoder/relpos_bias/rel_embedding' ].T # LM Head (only in v1.1 checkpoints, in v1.0 embeddings are used instead) if "decoder/logits_dense/kernel" in old: snake_case__ : int = old['decoder/logits_dense/kernel'].T return new def lowercase_ (A : List[Any] , A : bool ): snake_case__ : Dict = collections.OrderedDict([(k, torch.from_numpy(v.copy() )) for (k, v) in converted_params.items()] ) # Add what is missing. if "encoder.embed_tokens.weight" not in state_dict: snake_case__ : Any = state_dict['shared.weight'] if not is_encoder_only: if "decoder.embed_tokens.weight" not in state_dict: snake_case__ : Optional[int] = state_dict['shared.weight'] if "lm_head.weight" not in state_dict: # For old 1.0 models. print('Using shared word embeddings as lm_head.' ) snake_case__ : List[Any] = state_dict['shared.weight'] return state_dict def lowercase_ (A : Union[str, Any] , A : Any , A : Union[str, Any] , A : Tuple ): snake_case__ : Optional[Any] = checkpoints.load_tax_checkpoint(A ) snake_case__ : List[str] = convert_tax_to_pytorch(A , num_layers=config.num_layers , is_encoder_only=A ) snake_case__ : Optional[int] = make_state_dict(A , A ) model.load_state_dict(A , strict=A ) def lowercase_ (A : List[str] , A : Union[str, Any] , A : Optional[Any] , A : bool = False ): snake_case__ : str = TaConfig.from_json_file(A ) print(F'''Building PyTorch model from configuration: {config}''' ) # Non-v1.1 checkpoints could also use T5Model, but this works for all. # The v1.0 checkpoints will simply have an LM head that is the word embeddings. if is_encoder_only: snake_case__ : List[str] = TaEncoderModel(A ) else: snake_case__ : str = TaForConditionalGeneration(A ) # Load weights from tf checkpoint load_tax_weights_in_ta(A , A , A , A ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) model.save_pretrained(A ) # Verify that we can load the checkpoint. model.from_pretrained(A ) print('Done' ) if __name__ == "__main__": a_ :Tuple = argparse.ArgumentParser(description="Converts a native T5X checkpoint into a PyTorch checkpoint.") # Required parameters parser.add_argument( "--t5x_checkpoint_path", default=None, type=str, required=True, help="Path to the T5X checkpoint." ) parser.add_argument( "--config_file", default=None, type=str, required=True, help="The config json file corresponding to the pre-trained T5 model.\nThis specifies the model architecture.", ) parser.add_argument( "--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) parser.add_argument( "--is_encoder_only", action="store_true", help="Check if the model is encoder-decoder model", default=False ) a_ :List[Any] = parser.parse_args() convert_tax_checkpoint_to_pytorch( args.tax_checkpoint_path, args.config_file, args.pytorch_dump_path, args.is_encoder_only )
243
0
from pathlib import Path import torch from ...utils import is_npu_available, is_xpu_available from .config_args import ClusterConfig, default_json_config_file from .config_utils import SubcommandHelpFormatter a_ : List[Any] = 'Create a default config file for Accelerate with only a few flags set.' def __a ( __UpperCAmelCase="no" , __UpperCAmelCase = default_json_config_file , __UpperCAmelCase = False ): a__ = Path(lowerCAmelCase__ ) path.parent.mkdir(parents=lowerCAmelCase__ , exist_ok=lowerCAmelCase__ ) if path.exists(): print( f"Configuration already exists at {save_location}, will not override. Run `accelerate config` manually or pass a different `save_location`." ) return False a__ = mixed_precision.lower() if mixed_precision not in ["no", "fp16", "bf16", "fp8"]: raise ValueError( f"`mixed_precision` should be one of \'no\', \'fp16\', \'bf16\', or \'fp8\'. Received {mixed_precision}" ) a__ = { '''compute_environment''': '''LOCAL_MACHINE''', '''mixed_precision''': mixed_precision, } if torch.cuda.is_available(): a__ = torch.cuda.device_count() a__ = num_gpus a__ = False if num_gpus > 1: a__ = '''MULTI_GPU''' else: a__ = '''NO''' elif is_xpu_available() and use_xpu: a__ = torch.xpu.device_count() a__ = num_xpus a__ = False if num_xpus > 1: a__ = '''MULTI_XPU''' else: a__ = '''NO''' elif is_npu_available(): a__ = torch.npu.device_count() a__ = num_npus a__ = False if num_npus > 1: a__ = '''MULTI_NPU''' else: a__ = '''NO''' else: a__ = 0 a__ = True a__ = 1 a__ = '''NO''' a__ = ClusterConfig(**lowerCAmelCase__ ) config.to_json_file(lowerCAmelCase__ ) return path def __a ( __UpperCAmelCase , __UpperCAmelCase ): a__ = parser.add_parser('''default''' , parents=lowerCAmelCase__ , help=lowerCAmelCase__ , formatter_class=lowerCAmelCase__ ) parser.add_argument( '''--config_file''' , default=lowerCAmelCase__ , help=( '''The path to use to store the config file. Will default to a file named default_config.yaml in the cache ''' '''location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have ''' '''such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed ''' '''with \'huggingface\'.''' ) , dest='''save_location''' , ) parser.add_argument( '''--mixed_precision''' , choices=['''no''', '''fp16''', '''bf16'''] , type=lowerCAmelCase__ , help='''Whether or not to use mixed precision training. ''' '''Choose between FP16 and BF16 (bfloat16) training. ''' '''BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later.''' , default='''no''' , ) parser.set_defaults(func=lowerCAmelCase__ ) return parser def __a ( __UpperCAmelCase ): a__ = write_basic_config(args.mixed_precision , args.save_location ) if config_file: print(f"accelerate configuration saved at {config_file}" )
194
"""simple docstring""" from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowercase_ = { "configuration_mctct": ["MCTCT_PRETRAINED_CONFIG_ARCHIVE_MAP", "MCTCTConfig"], "feature_extraction_mctct": ["MCTCTFeatureExtractor"], "processing_mctct": ["MCTCTProcessor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "MCTCT_PRETRAINED_MODEL_ARCHIVE_LIST", "MCTCTForCTC", "MCTCTModel", "MCTCTPreTrainedModel", ] if TYPE_CHECKING: from .configuration_mctct import MCTCT_PRETRAINED_CONFIG_ARCHIVE_MAP, MCTCTConfig from .feature_extraction_mctct import MCTCTFeatureExtractor from .processing_mctct import MCTCTProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mctct import MCTCT_PRETRAINED_MODEL_ARCHIVE_LIST, MCTCTForCTC, MCTCTModel, MCTCTPreTrainedModel else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
695
0
'''simple docstring''' from __future__ import annotations from collections.abc import Iterator from typing import Any class A : def __init__( self : Any , lowerCAmelCase_ : Any ) -> Tuple: """simple docstring""" _a = data _a = None class A : def __init__( self : List[Any] ) -> Union[str, Any]: """simple docstring""" _a = None _a = None def __iter__( self : Optional[int] ) -> Iterator[Any]: """simple docstring""" _a = self.head while self.head: yield node.data _a = node.next if node == self.head: break def __len__( self : Any ) -> int: """simple docstring""" return sum(1 for _ in self ) def __repr__( self : Tuple ) -> Dict: """simple docstring""" return "->".join(str(lowerCAmelCase_ ) for item in iter(self ) ) def __lowerCAmelCase ( self : Tuple , lowerCAmelCase_ : Any ) -> None: """simple docstring""" self.insert_nth(len(self ) , lowerCAmelCase_ ) def __lowerCAmelCase ( self : Optional[int] , lowerCAmelCase_ : Any ) -> None: """simple docstring""" self.insert_nth(0 , lowerCAmelCase_ ) def __lowerCAmelCase ( self : Dict , lowerCAmelCase_ : int , lowerCAmelCase_ : Any ) -> None: """simple docstring""" if index < 0 or index > len(self ): raise IndexError('''list index out of range.''' ) _a = Node(lowerCAmelCase_ ) if self.head is None: _a = new_node # first node points itself _a = _a = new_node elif index == 0: # insert at head _a = self.head _a = _a = new_node else: _a = self.head for _ in range(index - 1 ): _a = temp.next _a = temp.next _a = new_node if index == len(self ) - 1: # insert at tail _a = new_node def __lowerCAmelCase ( self : Tuple ) -> Optional[Any]: """simple docstring""" return self.delete_nth(0 ) def __lowerCAmelCase ( self : List[Any] ) -> Any: """simple docstring""" return self.delete_nth(len(self ) - 1 ) def __lowerCAmelCase ( self : List[str] , lowerCAmelCase_ : int = 0 ) -> Any: """simple docstring""" if not 0 <= index < len(self ): raise IndexError('''list index out of range.''' ) _a = self.head if self.head == self.tail: # just one node _a = _a = None elif index == 0: # delete head node _a = self.tail.next.next _a = self.head.next else: _a = self.head for _ in range(index - 1 ): _a = temp.next _a = temp.next _a = temp.next.next if index == len(self ) - 1: # delete at tail _a = temp return delete_node.data def __lowerCAmelCase ( self : Union[str, Any] ) -> bool: """simple docstring""" return len(self ) == 0 def snake_case_ (): '''simple docstring''' _a = CircularLinkedList() assert len(UpperCamelCase ) == 0 assert circular_linked_list.is_empty() is True assert str(UpperCamelCase ) == "" try: circular_linked_list.delete_front() raise AssertionError # This should not happen except IndexError: assert True # This should happen try: circular_linked_list.delete_tail() raise AssertionError # This should not happen except IndexError: assert True # This should happen try: circular_linked_list.delete_nth(-1 ) raise AssertionError except IndexError: assert True try: circular_linked_list.delete_nth(0 ) raise AssertionError except IndexError: assert True assert circular_linked_list.is_empty() is True for i in range(5 ): assert len(UpperCamelCase ) == i circular_linked_list.insert_nth(UpperCamelCase , i + 1 ) assert str(UpperCamelCase ) == "->".join(str(UpperCamelCase ) for i in range(1 , 6 ) ) circular_linked_list.insert_tail(6 ) assert str(UpperCamelCase ) == "->".join(str(UpperCamelCase ) for i in range(1 , 7 ) ) circular_linked_list.insert_head(0 ) assert str(UpperCamelCase ) == "->".join(str(UpperCamelCase ) for i in range(0 , 7 ) ) assert circular_linked_list.delete_front() == 0 assert circular_linked_list.delete_tail() == 6 assert str(UpperCamelCase ) == "->".join(str(UpperCamelCase ) for i in range(1 , 6 ) ) assert circular_linked_list.delete_nth(2 ) == 3 circular_linked_list.insert_nth(2 , 3 ) assert str(UpperCamelCase ) == "->".join(str(UpperCamelCase ) for i in range(1 , 6 ) ) assert circular_linked_list.is_empty() is False if __name__ == "__main__": import doctest doctest.testmod()
377
'''simple docstring''' import os import sys from contextlib import contextmanager # Windows only if os.name == "nt": import ctypes import msvcrt # noqa class A ( ctypes.Structure ): # _fields is a specific attr expected by ctypes lowercase_ = [('size', ctypes.c_int), ('visible', ctypes.c_byte)] def snake_case_ (): '''simple docstring''' if os.name == "nt": _a = CursorInfo() _a = ctypes.windll.kernelaa.GetStdHandle(-11 ) ctypes.windll.kernelaa.GetConsoleCursorInfo(UpperCamelCase , ctypes.byref(UpperCamelCase ) ) _a = False ctypes.windll.kernelaa.SetConsoleCursorInfo(UpperCamelCase , ctypes.byref(UpperCamelCase ) ) elif os.name == "posix": sys.stdout.write('''\033[?25l''' ) sys.stdout.flush() def snake_case_ (): '''simple docstring''' if os.name == "nt": _a = CursorInfo() _a = ctypes.windll.kernelaa.GetStdHandle(-11 ) ctypes.windll.kernelaa.GetConsoleCursorInfo(UpperCamelCase , ctypes.byref(UpperCamelCase ) ) _a = True ctypes.windll.kernelaa.SetConsoleCursorInfo(UpperCamelCase , ctypes.byref(UpperCamelCase ) ) elif os.name == "posix": sys.stdout.write('''\033[?25h''' ) sys.stdout.flush() @contextmanager def snake_case_ (): '''simple docstring''' try: hide_cursor() yield finally: show_cursor()
377
1
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { '''asapp/sew-tiny-100k''': '''https://huggingface.co/asapp/sew-tiny-100k/resolve/main/config.json''', # See all SEW models at https://huggingface.co/models?filter=sew } class _lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" lowerCAmelCase__ ='''sew''' def __init__( self , __SCREAMING_SNAKE_CASE=32 , __SCREAMING_SNAKE_CASE=768 , __SCREAMING_SNAKE_CASE=12 , __SCREAMING_SNAKE_CASE=12 , __SCREAMING_SNAKE_CASE=3072 , __SCREAMING_SNAKE_CASE=2 , __SCREAMING_SNAKE_CASE="gelu" , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=1e-5 , __SCREAMING_SNAKE_CASE="group" , __SCREAMING_SNAKE_CASE="gelu" , __SCREAMING_SNAKE_CASE=(64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512) , __SCREAMING_SNAKE_CASE=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1) , __SCREAMING_SNAKE_CASE=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1) , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=128 , __SCREAMING_SNAKE_CASE=16 , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=0.05 , __SCREAMING_SNAKE_CASE=10 , __SCREAMING_SNAKE_CASE=2 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=10 , __SCREAMING_SNAKE_CASE=0 , __SCREAMING_SNAKE_CASE="mean" , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=256 , __SCREAMING_SNAKE_CASE=0 , __SCREAMING_SNAKE_CASE=1 , __SCREAMING_SNAKE_CASE=2 , **__SCREAMING_SNAKE_CASE , ) -> int: """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE , pad_token_id=__SCREAMING_SNAKE_CASE , bos_token_id=__SCREAMING_SNAKE_CASE , eos_token_id=__SCREAMING_SNAKE_CASE ) snake_case__ : str =hidden_size snake_case__ : Union[str, Any] =feat_extract_norm snake_case__ : List[str] =feat_extract_activation snake_case__ : Union[str, Any] =list(__SCREAMING_SNAKE_CASE ) snake_case__ : Any =list(__SCREAMING_SNAKE_CASE ) snake_case__ : List[str] =list(__SCREAMING_SNAKE_CASE ) snake_case__ : str =conv_bias snake_case__ : Dict =num_conv_pos_embeddings snake_case__ : Tuple =num_conv_pos_embedding_groups snake_case__ : List[Any] =len(self.conv_dim ) snake_case__ : Tuple =num_hidden_layers snake_case__ : Union[str, Any] =intermediate_size snake_case__ : Optional[Any] =squeeze_factor snake_case__ : List[str] =hidden_act snake_case__ : List[Any] =num_attention_heads snake_case__ : List[str] =hidden_dropout snake_case__ : Any =attention_dropout snake_case__ : List[str] =activation_dropout snake_case__ : int =feat_proj_dropout snake_case__ : Union[str, Any] =final_dropout snake_case__ : str =layerdrop snake_case__ : Optional[Any] =layer_norm_eps snake_case__ : Any =initializer_range snake_case__ : Any =vocab_size if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( '''Configuration for convolutional layers is incorrect.''' '''It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,''' f'''but is `len(config.conv_dim) = {len(self.conv_dim )}`, `len(config.conv_stride)''' f'''= {len(self.conv_stride )}`, `len(config.conv_kernel) = {len(self.conv_kernel )}`.''' ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 snake_case__ : Optional[int] =apply_spec_augment snake_case__ : str =mask_time_prob snake_case__ : Tuple =mask_time_length snake_case__ : List[str] =mask_time_min_masks snake_case__ : int =mask_feature_prob snake_case__ : Optional[int] =mask_feature_length snake_case__ : List[Any] =mask_feature_min_masks # ctc loss snake_case__ : List[str] =ctc_loss_reduction snake_case__ : Dict =ctc_zero_infinity # sequence classification snake_case__ : Any =use_weighted_layer_sum snake_case__ : Any =classifier_proj_size @property def UpperCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" return functools.reduce(operator.mul , self.conv_stride , 1 )
381
import argparse import os import re # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_dummies.py lowerCamelCase__ = '''src/diffusers''' # Matches is_xxx_available() lowerCamelCase__ = re.compile(r'''is\_([a-z_]*)_available\(\)''') # Matches from xxx import bla lowerCamelCase__ = re.compile(r'''\s+from\s+\S*\s+import\s+([^\(\s].*)\n''') lowerCamelCase__ = ''' {0} = None ''' lowerCamelCase__ = ''' class {0}(metaclass=DummyObject): _backends = {1} def __init__(self, *args, **kwargs): requires_backends(self, {1}) @classmethod def from_config(cls, *args, **kwargs): requires_backends(cls, {1}) @classmethod def from_pretrained(cls, *args, **kwargs): requires_backends(cls, {1}) ''' lowerCamelCase__ = ''' def {0}(*args, **kwargs): requires_backends({0}, {1}) ''' def lowercase_ ( SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" snake_case__ : Tuple =_re_backend.findall(SCREAMING_SNAKE_CASE ) if len(SCREAMING_SNAKE_CASE ) == 0: return None return "_and_".join(SCREAMING_SNAKE_CASE ) def lowercase_ ( ): """simple docstring""" with open(os.path.join(SCREAMING_SNAKE_CASE , '''__init__.py''' ) , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: snake_case__ : int =f.readlines() # Get to the point we do the actual imports for type checking snake_case__ : Optional[Any] =0 snake_case__ : Any ={} # Go through the end of the file while line_index < len(SCREAMING_SNAKE_CASE ): # If the line contains is_backend_available, we grab all objects associated with the `else` block snake_case__ : List[str] =find_backend(lines[line_index] ) if backend is not None: while not lines[line_index].startswith('''else:''' ): line_index += 1 line_index += 1 snake_case__ : List[Any] =[] # Until we unindent, add backend objects to the list while line_index < len(SCREAMING_SNAKE_CASE ) and len(lines[line_index] ) > 1: snake_case__ : List[str] =lines[line_index] snake_case__ : Any =_re_single_line_import.search(SCREAMING_SNAKE_CASE ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(''', ''' ) ) elif line.startswith(''' ''' * 8 ): objects.append(line[8:-2] ) line_index += 1 if len(SCREAMING_SNAKE_CASE ) > 0: snake_case__ : List[Any] =objects else: line_index += 1 return backend_specific_objects def lowercase_ ( SCREAMING_SNAKE_CASE : Union[str, Any] , SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" if name.isupper(): return DUMMY_CONSTANT.format(SCREAMING_SNAKE_CASE ) elif name.islower(): return DUMMY_FUNCTION.format(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) else: return DUMMY_CLASS.format(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def lowercase_ ( SCREAMING_SNAKE_CASE : str=None ): """simple docstring""" if backend_specific_objects is None: snake_case__ : int =read_init() # For special correspondence backend to module name as used in the function requires_modulename snake_case__ : Dict ={} for backend, objects in backend_specific_objects.items(): snake_case__ : str ='''[''' + ''', '''.join(F'''"{b}"''' for b in backend.split('''_and_''' ) ) + ''']''' snake_case__ : List[Any] ='''# This file is autogenerated by the command `make fix-copies`, do not edit.\n''' dummy_file += "from ..utils import DummyObject, requires_backends\n\n" dummy_file += "\n".join([create_dummy_object(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for o in objects] ) snake_case__ : int =dummy_file return dummy_files def lowercase_ ( SCREAMING_SNAKE_CASE : Optional[int]=False ): """simple docstring""" snake_case__ : Dict =create_dummy_files() # For special correspondence backend to shortcut as used in utils/dummy_xxx_objects.py snake_case__ : int ={'''torch''': '''pt'''} # Locate actual dummy modules and read their content. snake_case__ : List[Any] =os.path.join(SCREAMING_SNAKE_CASE , '''utils''' ) snake_case__ : str ={ backend: os.path.join(SCREAMING_SNAKE_CASE , F'''dummy_{short_names.get(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )}_objects.py''' ) for backend in dummy_files.keys() } snake_case__ : Tuple ={} for backend, file_path in dummy_file_paths.items(): if os.path.isfile(SCREAMING_SNAKE_CASE ): with open(SCREAMING_SNAKE_CASE , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: snake_case__ : Optional[int] =f.read() else: snake_case__ : Union[str, Any] ='''''' for backend in dummy_files.keys(): if dummy_files[backend] != actual_dummies[backend]: if overwrite: print( F'''Updating diffusers.utils.dummy_{short_names.get(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )}_objects.py as the main ''' '''__init__ has new objects.''' ) with open(dummy_file_paths[backend] , '''w''' , encoding='''utf-8''' , newline='''\n''' ) as f: f.write(dummy_files[backend] ) else: raise ValueError( '''The main __init__ has objects that are not present in ''' F'''diffusers.utils.dummy_{short_names.get(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )}_objects.py. Run `make fix-copies` ''' '''to fix this.''' ) if __name__ == "__main__": lowerCamelCase__ = argparse.ArgumentParser() parser.add_argument('''--fix_and_overwrite''', action='''store_true''', help='''Whether to fix inconsistencies.''') lowerCamelCase__ = parser.parse_args() check_dummies(args.fix_and_overwrite)
381
1
"""simple docstring""" def lowerCamelCase_ ( _lowerCamelCase ): lowerCamelCase__ : Union[str, Any] = 1 for i in range(1 , num + 1 ): fact *= i return fact def lowerCamelCase_ ( _lowerCamelCase ): lowerCamelCase__ : Optional[Any] = 0 while number > 0: lowerCamelCase__ : List[str] = number % 10 sum_of_digits += last_digit lowerCamelCase__ : str = number // 10 # Removing the last_digit from the given number return sum_of_digits def lowerCamelCase_ ( _lowerCamelCase = 100 ): lowerCamelCase__ : Union[str, Any] = factorial(_lowerCamelCase ) lowerCamelCase__ : List[Any] = split_and_add(_lowerCamelCase ) return result if __name__ == "__main__": print(solution(int(input("Enter the Number: ").strip())))
696
"""simple docstring""" def lowerCamelCase_ ( _lowerCamelCase , _lowerCamelCase ): if mass < 0: raise ValueError('The mass of a body cannot be negative' ) return 0.5 * mass * abs(_lowerCamelCase ) * abs(_lowerCamelCase ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
696
1
'''simple docstring''' from __future__ import annotations import sys from collections import deque from typing import Generic, TypeVar _snake_case : str = TypeVar('T') class A ( Generic[T] ): lowercase_ = 42 # Cache store of keys lowercase_ = 42 # References of the keys in cache lowercase_ = 10 # Maximum capacity of cache def __init__( self : str , lowerCAmelCase_ : str ) -> Optional[Any]: """simple docstring""" _a = deque() _a = set() if not n: _a = sys.maxsize elif n < 0: raise ValueError('''n should be an integer greater than 0.''' ) else: _a = n def __lowerCAmelCase ( self : Any , lowerCAmelCase_ : Any ) -> Union[str, Any]: """simple docstring""" if x not in self.key_reference: if len(self.dq_store ) == LRUCache._MAX_CAPACITY: _a = self.dq_store.pop() self.key_reference.remove(_lowerCAmelCase ) else: self.dq_store.remove(_lowerCAmelCase ) self.dq_store.appendleft(_lowerCAmelCase ) self.key_reference.add(_lowerCAmelCase ) def __lowerCAmelCase ( self : int ) -> List[str]: """simple docstring""" for k in self.dq_store: print(_lowerCAmelCase ) def __repr__( self : List[str] ) -> Dict: """simple docstring""" return F'LRUCache({self._MAX_CAPACITY}) => {list(self.dq_store )}' if __name__ == "__main__": import doctest doctest.testmod() _snake_case : LRUCache[str | int] = LRUCache(4) lru_cache.refer('A') lru_cache.refer(2) lru_cache.refer(3) lru_cache.refer('A') lru_cache.refer(4) lru_cache.refer(5) lru_cache.display() print(lru_cache) assert str(lru_cache) == "LRUCache(4) => [5, 4, 'A', 3]"
22
from typing import Callable, Optional from .. import Features from ..packaged_modules.generator.generator import Generator from .abc import AbstractDatasetInputStream class a ( __lowercase ): def __init__( self , _lowerCAmelCase , _lowerCAmelCase = None , _lowerCAmelCase = None , _lowerCAmelCase = False , _lowerCAmelCase = False , _lowerCAmelCase = None , _lowerCAmelCase = None , **_lowerCAmelCase , ): """simple docstring""" super().__init__( features=_lowerCAmelCase , cache_dir=_lowerCAmelCase , keep_in_memory=_lowerCAmelCase , streaming=_lowerCAmelCase , num_proc=_lowerCAmelCase , **_lowerCAmelCase , ) __SCREAMING_SNAKE_CASE: Any = Generator( cache_dir=_lowerCAmelCase , features=_lowerCAmelCase , generator=_lowerCAmelCase , gen_kwargs=_lowerCAmelCase , **_lowerCAmelCase , ) def snake_case_ ( self ): """simple docstring""" if self.streaming: __SCREAMING_SNAKE_CASE: List[str] = self.builder.as_streaming_dataset(split='''train''' ) # Build regular (map-style) dataset else: __SCREAMING_SNAKE_CASE: str = None __SCREAMING_SNAKE_CASE: List[Any] = None __SCREAMING_SNAKE_CASE: Tuple = None __SCREAMING_SNAKE_CASE: Optional[Any] = None self.builder.download_and_prepare( download_config=_lowerCAmelCase , download_mode=_lowerCAmelCase , verification_mode=_lowerCAmelCase , base_path=_lowerCAmelCase , num_proc=self.num_proc , ) __SCREAMING_SNAKE_CASE: List[str] = self.builder.as_dataset( split='''train''' , verification_mode=_lowerCAmelCase , in_memory=self.keep_in_memory ) return dataset
202
0
'''simple docstring''' 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 : Tuple = False, False, False @dataclass class lowerCamelCase__ : """simple docstring""" __magic_name__ = None __magic_name__ = True __magic_name__ = True __magic_name__ = None # Automatically constructed __magic_name__ = "dict" __magic_name__ = pa.struct({"""bytes""": pa.binary(), """path""": pa.string()} ) __magic_name__ = field(default="""Audio""" , init=__SCREAMING_SNAKE_CASE , repr=__SCREAMING_SNAKE_CASE ) def __call__( self ) -> int: return self.pa_type def _lowerCamelCase ( self , UpperCAmelCase__ ) -> Any: 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(_a , _a ): return {"bytes": None, "path": value} elif isinstance(_a , _a ): return {"bytes": value, "path": None} elif "array" in value: # convert the audio array to wav bytes _A : Optional[Any] = BytesIO() sf.write(_a , 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 : Tuple = np.frombuffer(value['''bytes'''] , dtype=np.intaa ).astype(np.floataa ) / 3_2_7_6_7 else: _A : Optional[Any] = np.memmap(value['''path'''] , dtype='''h''' , mode='''r''' ).astype(np.floataa ) / 3_2_7_6_7 _A : Any = BytesIO(bytes() ) sf.write(_a , _a , 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 _lowerCamelCase ( self , UpperCAmelCase__ , UpperCAmelCase__ = None ) -> Optional[Any]: if not self.decode: raise RuntimeError('''Decoding is disabled for this feature. Please use Audio(decode=True) instead.''' ) _A , _A : Optional[int] = (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 : Optional[Any] = xsplitext(_a )[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 : Dict = token_per_repo_id or {} _A : Union[str, Any] = path.split('''::''' )[-1] try: _A : Optional[int] = string_to_dict(_a , config.HUB_DATASETS_URL )['''repo_id'''] _A : Union[str, Any] = token_per_repo_id[repo_id] except (ValueError, KeyError): _A : List[Any] = None with xopen(_a , '''rb''' , use_auth_token=_a ) as f: _A , _A : List[Any] = sf.read(_a ) else: _A , _A : Optional[Any] = sf.read(_a ) _A : Optional[Any] = array.T if self.mono: _A : Tuple = librosa.to_mono(_a ) if self.sampling_rate and self.sampling_rate != sampling_rate: _A : List[str] = librosa.resample(_a , orig_sr=_a , target_sr=self.sampling_rate ) _A : Optional[Any] = self.sampling_rate return {"path": path, "array": array, "sampling_rate": sampling_rate} def _lowerCamelCase ( self ) -> Optional[Any]: from .features import Value if self.decode: raise ValueError('''Cannot flatten a decoded Audio feature.''' ) return { "bytes": Value('''binary''' ), "path": Value('''string''' ), } def _lowerCamelCase ( self , UpperCAmelCase__ ) -> List[str]: if pa.types.is_string(storage.type ): _A : str = pa.array([None] * len(_a ) , type=pa.binary() ) _A : List[Any] = pa.StructArray.from_arrays([bytes_array, storage] , ['''bytes''', '''path'''] , mask=storage.is_null() ) elif pa.types.is_binary(storage.type ): _A : Optional[int] = pa.array([None] * len(_a ) , type=pa.string() ) _A : str = 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 : Tuple = pa.array([Audio().encode_example(_a ) 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 : Optional[Any] = storage.field('''bytes''' ) else: _A : Optional[Any] = pa.array([None] * len(_a ) , type=pa.binary() ) if storage.type.get_field_index('''path''' ) >= 0: _A : Any = storage.field('''path''' ) else: _A : Dict = pa.array([None] * len(_a ) , type=pa.string() ) _A : List[str] = pa.StructArray.from_arrays([bytes_array, path_array] , ['''bytes''', '''path'''] , mask=storage.is_null() ) return array_cast(_a , self.pa_type ) def _lowerCamelCase ( self , UpperCAmelCase__ ) -> int: @no_op_if_value_is_null def path_to_bytes(UpperCAmelCase__ ): with xopen(_a , '''rb''' ) as f: _A : Optional[Any] = f.read() return bytes_ _A : Optional[int] = 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 : Union[str, Any] = pa.array( [os.path.basename(_a ) if path is not None else None for path in storage.field('''path''' ).to_pylist()] , type=pa.string() , ) _A : Optional[int] = pa.StructArray.from_arrays([bytes_array, path_array] , ['''bytes''', '''path'''] , mask=bytes_array.is_null() ) return array_cast(_a , self.pa_type )
721
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig __UpperCamelCase : str = { '''albert-base-v1''': '''https://huggingface.co/albert-base-v1/resolve/main/config.json''', '''albert-large-v1''': '''https://huggingface.co/albert-large-v1/resolve/main/config.json''', '''albert-xlarge-v1''': '''https://huggingface.co/albert-xlarge-v1/resolve/main/config.json''', '''albert-xxlarge-v1''': '''https://huggingface.co/albert-xxlarge-v1/resolve/main/config.json''', '''albert-base-v2''': '''https://huggingface.co/albert-base-v2/resolve/main/config.json''', '''albert-large-v2''': '''https://huggingface.co/albert-large-v2/resolve/main/config.json''', '''albert-xlarge-v2''': '''https://huggingface.co/albert-xlarge-v2/resolve/main/config.json''', '''albert-xxlarge-v2''': '''https://huggingface.co/albert-xxlarge-v2/resolve/main/config.json''', } class lowerCamelCase__ ( snake_case_ ): """simple docstring""" __magic_name__ = """albert""" def __init__( self , UpperCAmelCase__=3_0_0_0_0 , UpperCAmelCase__=1_2_8 , UpperCAmelCase__=4_0_9_6 , UpperCAmelCase__=1_2 , UpperCAmelCase__=1 , UpperCAmelCase__=6_4 , UpperCAmelCase__=1_6_3_8_4 , UpperCAmelCase__=1 , UpperCAmelCase__="gelu_new" , UpperCAmelCase__=0 , UpperCAmelCase__=0 , UpperCAmelCase__=5_1_2 , UpperCAmelCase__=2 , UpperCAmelCase__=0.0_2 , UpperCAmelCase__=1e-12 , UpperCAmelCase__=0.1 , UpperCAmelCase__="absolute" , UpperCAmelCase__=0 , UpperCAmelCase__=2 , UpperCAmelCase__=3 , **UpperCAmelCase__ , ) -> Tuple: super().__init__(pad_token_id=UpperCAmelCase__ , bos_token_id=UpperCAmelCase__ , eos_token_id=UpperCAmelCase__ , **UpperCAmelCase__ ) _A : Optional[Any] = vocab_size _A : Optional[int] = embedding_size _A : str = hidden_size _A : Union[str, Any] = num_hidden_layers _A : Optional[int] = num_hidden_groups _A : Optional[Any] = num_attention_heads _A : Tuple = inner_group_num _A : Tuple = hidden_act _A : List[Any] = intermediate_size _A : str = hidden_dropout_prob _A : str = attention_probs_dropout_prob _A : List[str] = max_position_embeddings _A : List[Any] = type_vocab_size _A : Any = initializer_range _A : Tuple = layer_norm_eps _A : Dict = classifier_dropout_prob _A : Union[str, Any] = position_embedding_type class lowerCamelCase__ ( snake_case_ ): """simple docstring""" @property def _lowerCamelCase ( self ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": _A : Dict = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: _A : Any = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ('''token_type_ids''', dynamic_axis), ] )
417
0
import datasets from .nmt_bleu import compute_bleu # From: https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py a_ : Dict = '\\n@INPROCEEDINGS{Papineni02bleu:a,\n author = {Kishore Papineni and Salim Roukos and Todd Ward and Wei-jing Zhu},\n title = {BLEU: a Method for Automatic Evaluation of Machine Translation},\n booktitle = {},\n year = {2002},\n pages = {311--318}\n}\n@inproceedings{lin-och-2004-orange,\n title = "{ORANGE}: a Method for Evaluating Automatic Evaluation Metrics for Machine Translation",\n author = "Lin, Chin-Yew and\n Och, Franz Josef",\n booktitle = "{COLING} 2004: Proceedings of the 20th International Conference on Computational Linguistics",\n month = "aug 23{--}aug 27",\n year = "2004",\n address = "Geneva, Switzerland",\n publisher = "COLING",\n url = "https://www.aclweb.org/anthology/C04-1072",\n pages = "501--507",\n}\n' a_ : Dict = '\\nBLEU (bilingual evaluation understudy) is an algorithm for evaluating the quality of text which has been machine-translated from one natural language to another.\nQuality is considered to be the correspondence between a machine\'s output and that of a human: "the closer a machine translation is to a professional human translation,\nthe better it is" – this is the central idea behind BLEU. BLEU was one of the first metrics to claim a high correlation with human judgements of quality, and\nremains one of the most popular automated and inexpensive metrics.\n\nScores are calculated for individual translated segments—generally sentences—by comparing them with a set of good quality reference translations.\nThose scores are then averaged over the whole corpus to reach an estimate of the translation\'s overall quality. Intelligibility or grammatical correctness\nare not taken into account[citation needed].\n\nBLEU\'s output is always a number between 0 and 1. This value indicates how similar the candidate text is to the reference texts, with values closer to 1\nrepresenting more similar texts. Few human translations will attain a score of 1, since this would indicate that the candidate is identical to one of the\nreference translations. For this reason, it is not necessary to attain a score of 1. Because there are more opportunities to match, adding additional\nreference translations will increase the BLEU score.\n' a_ : int = '\nComputes BLEU score of translated segments against one or more references.\nArgs:\n predictions: list of translations to score.\n Each translation should be tokenized into a list of tokens.\n references: list of lists of references for each translation.\n Each reference should be tokenized into a list of tokens.\n max_order: Maximum n-gram order to use when computing BLEU score.\n smooth: Whether or not to apply Lin et al. 2004 smoothing.\nReturns:\n \'bleu\': bleu score,\n \'precisions\': geometric mean of n-gram precisions,\n \'brevity_penalty\': brevity penalty,\n \'length_ratio\': ratio of lengths,\n \'translation_length\': translation_length,\n \'reference_length\': reference_length\nExamples:\n\n >>> predictions = [\n ... ["hello", "there", "general", "kenobi"], # tokenized prediction of the first sample\n ... ["foo", "bar", "foobar"] # tokenized prediction of the second sample\n ... ]\n >>> references = [\n ... [["hello", "there", "general", "kenobi"], ["hello", "there", "!"]], # tokenized references for the first sample (2 references)\n ... [["foo", "bar", "foobar"]] # tokenized references for the second sample (1 reference)\n ... ]\n >>> bleu = datasets.load_metric("bleu")\n >>> results = bleu.compute(predictions=predictions, references=references)\n >>> print(results["bleu"])\n 1.0\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class lowerCamelCase__ ( datasets.Metric): """simple docstring""" def _a (self ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Sequence(datasets.Value("string" , id="token" ) , id="sequence" ), "references": datasets.Sequence( datasets.Sequence(datasets.Value("string" , id="token" ) , id="sequence" ) , id="references" ), } ) , codebase_urls=["https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py"] , reference_urls=[ "https://en.wikipedia.org/wiki/BLEU", "https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213", ] , ) def _a (self , __a , __a , __a=4 , __a=False ): '''simple docstring''' lowerCamelCase = compute_bleu( reference_corpus=__a , translation_corpus=__a , max_order=__a , smooth=__a ) ((lowerCamelCase) , (lowerCamelCase) , (lowerCamelCase) , (lowerCamelCase) , (lowerCamelCase) , (lowerCamelCase)) = score return { "bleu": bleu, "precisions": precisions, "brevity_penalty": bp, "length_ratio": ratio, "translation_length": translation_length, "reference_length": reference_length, }
623
from __future__ import annotations from math import pow, sqrt def __lowercase( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ): """simple docstring""" if (resistance, reactance, impedance).count(0 ) != 1: raise ValueError("One and only one argument must be 0" ) if resistance == 0: return {"resistance": sqrt(pow(UpperCAmelCase__ , 2 ) - pow(UpperCAmelCase__ , 2 ) )} elif reactance == 0: return {"reactance": sqrt(pow(UpperCAmelCase__ , 2 ) - pow(UpperCAmelCase__ , 2 ) )} elif impedance == 0: return {"impedance": sqrt(pow(UpperCAmelCase__ , 2 ) + pow(UpperCAmelCase__ , 2 ) )} else: raise ValueError("Exactly one argument must be 0" ) if __name__ == "__main__": import doctest doctest.testmod()
623
1
import math import unittest def __snake_case ( _UpperCAmelCase ): """simple docstring""" assert isinstance(_UpperCAmelCase , _UpperCAmelCase ) and ( number >= 0 ), "'number' must been an int and positive" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(_UpperCAmelCase ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True class a__ ( unittest.TestCase ): """simple docstring""" def __UpperCAmelCase ( self :List[str] ): self.assertTrue(is_prime(2 ) ) self.assertTrue(is_prime(3 ) ) self.assertTrue(is_prime(5 ) ) self.assertTrue(is_prime(7 ) ) self.assertTrue(is_prime(11 ) ) self.assertTrue(is_prime(13 ) ) self.assertTrue(is_prime(17 ) ) self.assertTrue(is_prime(19 ) ) self.assertTrue(is_prime(23 ) ) self.assertTrue(is_prime(29 ) ) def __UpperCAmelCase ( self :int ): with self.assertRaises(lowercase__ ): is_prime(-19 ) self.assertFalse( is_prime(0 ) , 'Zero doesn\'t have any positive factors, primes must have exactly two.' , ) self.assertFalse( is_prime(1 ) , 'One only has 1 positive factor, primes must have exactly two.' , ) self.assertFalse(is_prime(2 * 2 ) ) self.assertFalse(is_prime(2 * 3 ) ) self.assertFalse(is_prime(3 * 3 ) ) self.assertFalse(is_prime(3 * 5 ) ) self.assertFalse(is_prime(3 * 5 * 7 ) ) if __name__ == "__main__": unittest.main()
314
from queue import PriorityQueue from typing import Any import numpy as np def __snake_case ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , ): """simple docstring""" for nxt, d in graph[v]: if nxt in visited_forward: continue lowercase = cst_fwd.get(_UpperCAmelCase , np.inf ) lowercase = cst_fwd[v] + d if new_cost_f < old_cost_f: queue.put((new_cost_f, nxt) ) lowercase = new_cost_f lowercase = v if nxt in visited_backward: if cst_fwd[v] + d + cst_bwd[nxt] < shortest_distance: lowercase = cst_fwd[v] + d + cst_bwd[nxt] return shortest_distance def __snake_case ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): """simple docstring""" lowercase = -1 lowercase = set() lowercase = set() lowercase = {source: 0} lowercase = {destination: 0} lowercase = {source: None} lowercase = {destination: None} lowercase = PriorityQueue() lowercase = PriorityQueue() lowercase = np.inf queue_forward.put((0, source) ) queue_backward.put((0, destination) ) if source == destination: return 0 while not queue_forward.empty() and not queue_backward.empty(): lowercase , lowercase = queue_forward.get() visited_forward.add(_UpperCAmelCase ) lowercase , lowercase = queue_backward.get() visited_backward.add(_UpperCAmelCase ) lowercase = pass_and_relaxation( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , ) lowercase = pass_and_relaxation( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , ) if cst_fwd[v_fwd] + cst_bwd[v_bwd] >= shortest_distance: break if shortest_distance != np.inf: lowercase = shortest_distance return shortest_path_distance __magic_name__ = { '''B''': [['''C''', 1]], '''C''': [['''D''', 1]], '''D''': [['''F''', 1]], '''E''': [['''B''', 1], ['''G''', 2]], '''F''': [], '''G''': [['''F''', 1]], } __magic_name__ = { '''B''': [['''E''', 1]], '''C''': [['''B''', 1]], '''D''': [['''C''', 1]], '''F''': [['''D''', 1], ['''G''', 1]], '''E''': [[None, np.inf]], '''G''': [['''E''', 2]], } if __name__ == "__main__": import doctest doctest.testmod()
314
1
import argparse import json import os 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.deepspeed import DummyOptim, DummyScheduler __A = 16 __A = 32 def __a ( lowerCAmelCase_ : Accelerator ,lowerCAmelCase_ : int = 16 ,lowerCAmelCase_ : str = "bert-base-cased" ) -> List[str]: '''simple docstring''' UpperCAmelCase_= AutoTokenizer.from_pretrained(lowerCAmelCase_ ) UpperCAmelCase_= load_dataset("""glue""" ,"""mrpc""" ) def tokenize_function(lowerCAmelCase_ : Optional[int] ): # max_length=None => use the model max length (it's actually the default) UpperCAmelCase_= tokenizer(examples["""sentence1"""] ,examples["""sentence2"""] ,truncation=lowerCAmelCase_ ,max_length=lowerCAmelCase_ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset UpperCAmelCase_= datasets.map( lowerCAmelCase_ ,batched=lowerCAmelCase_ ,remove_columns=["""idx""", """sentence1""", """sentence2"""] ,load_from_cache_file=lowerCAmelCase_ ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library UpperCAmelCase_= tokenized_datasets.rename_column("""label""" ,"""labels""" ) def collate_fn(lowerCAmelCase_ : List[str] ): # 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(lowerCAmelCase_ ,padding="""max_length""" ,max_length=1_28 ,return_tensors="""pt""" ) return tokenizer.pad(lowerCAmelCase_ ,padding="""longest""" ,return_tensors="""pt""" ) # Instantiate dataloaders. UpperCAmelCase_= DataLoader( tokenized_datasets["""train"""] ,shuffle=lowerCAmelCase_ ,collate_fn=lowerCAmelCase_ ,batch_size=lowerCAmelCase_ ) UpperCAmelCase_= DataLoader( tokenized_datasets["""validation"""] ,shuffle=lowerCAmelCase_ ,collate_fn=lowerCAmelCase_ ,batch_size=lowerCAmelCase_ ) return train_dataloader, eval_dataloader def __a ( lowerCAmelCase_ : Dict ,lowerCAmelCase_ : str ) -> str: '''simple docstring''' UpperCAmelCase_= Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs UpperCAmelCase_= config["""lr"""] UpperCAmelCase_= int(config["""num_epochs"""] ) UpperCAmelCase_= int(config["""seed"""] ) UpperCAmelCase_= int(config["""batch_size"""] ) UpperCAmelCase_= args.model_name_or_path set_seed(lowerCAmelCase_ ) UpperCAmelCase_, UpperCAmelCase_= get_dataloaders(lowerCAmelCase_ ,lowerCAmelCase_ ,lowerCAmelCase_ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) UpperCAmelCase_= AutoModelForSequenceClassification.from_pretrained(lowerCAmelCase_ ,return_dict=lowerCAmelCase_ ) # Instantiate optimizer UpperCAmelCase_= ( AdamW if accelerator.state.deepspeed_plugin is None or """optimizer""" not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) UpperCAmelCase_= optimizer_cls(params=model.parameters() ,lr=lowerCAmelCase_ ) if accelerator.state.deepspeed_plugin is not None: UpperCAmelCase_= accelerator.state.deepspeed_plugin.deepspeed_config[ """gradient_accumulation_steps""" ] else: UpperCAmelCase_= 1 UpperCAmelCase_= (len(lowerCAmelCase_ ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): UpperCAmelCase_= get_linear_schedule_with_warmup( optimizer=lowerCAmelCase_ ,num_warmup_steps=0 ,num_training_steps=lowerCAmelCase_ ,) else: UpperCAmelCase_= DummyScheduler(lowerCAmelCase_ ,total_num_steps=lowerCAmelCase_ ,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. UpperCAmelCase_, UpperCAmelCase_, UpperCAmelCase_, UpperCAmelCase_, UpperCAmelCase_= accelerator.prepare( lowerCAmelCase_ ,lowerCAmelCase_ ,lowerCAmelCase_ ,lowerCAmelCase_ ,lowerCAmelCase_ ) # We need to keep track of how many total steps we have iterated over UpperCAmelCase_= 0 # We also need to keep track of the stating epoch so files are named properly UpperCAmelCase_= 0 # Now we train the model UpperCAmelCase_= evaluate.load("""glue""" ,"""mrpc""" ) UpperCAmelCase_= 0 UpperCAmelCase_= {} for epoch in range(lowerCAmelCase_ ,lowerCAmelCase_ ): model.train() for step, batch in enumerate(lowerCAmelCase_ ): UpperCAmelCase_= model(**lowerCAmelCase_ ) UpperCAmelCase_= outputs.loss UpperCAmelCase_= loss / gradient_accumulation_steps accelerator.backward(lowerCAmelCase_ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 model.eval() UpperCAmelCase_= 0 for step, batch in enumerate(lowerCAmelCase_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): UpperCAmelCase_= model(**lowerCAmelCase_ ) UpperCAmelCase_= outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times UpperCAmelCase_, UpperCAmelCase_= accelerator.gather( (predictions, batch["""labels"""]) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(lowerCAmelCase_ ) - 1: UpperCAmelCase_= predictions[: len(eval_dataloader.dataset ) - samples_seen] UpperCAmelCase_= references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=lowerCAmelCase_ ,references=lowerCAmelCase_ ,) UpperCAmelCase_= metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F"""epoch {epoch}:""" ,lowerCAmelCase_ ) UpperCAmelCase_= eval_metric["""accuracy"""] if best_performance < eval_metric["accuracy"]: UpperCAmelCase_= eval_metric["""accuracy"""] if args.performance_lower_bound is not None: assert ( args.performance_lower_bound <= best_performance ), F"""Best performance metric {best_performance} is lower than the lower bound {args.performance_lower_bound}""" accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir ,"""all_results.json""" ) ,"""w""" ) as f: json.dump(lowerCAmelCase_ ,lowerCAmelCase_ ) def __a ( ) -> List[Any]: '''simple docstring''' UpperCAmelCase_= argparse.ArgumentParser(description="""Simple example of training script tracking peak GPU memory usage.""" ) parser.add_argument( """--model_name_or_path""" ,type=lowerCAmelCase_ ,default="""bert-base-cased""" ,help="""Path to pretrained model or model identifier from huggingface.co/models.""" ,required=lowerCAmelCase_ ,) parser.add_argument( """--output_dir""" ,type=lowerCAmelCase_ ,default=""".""" ,help="""Optional save directory where all checkpoint folders will be stored. Default is the current working directory.""" ,) parser.add_argument( """--performance_lower_bound""" ,type=lowerCAmelCase_ ,default=lowerCAmelCase_ ,help="""Optional lower bound for the performance metric. If set, the training will throw error when the performance metric drops below this value.""" ,) parser.add_argument( """--num_epochs""" ,type=lowerCAmelCase_ ,default=3 ,help="""Number of train epochs.""" ,) UpperCAmelCase_= parser.parse_args() UpperCAmelCase_= {"""lr""": 2E-5, """num_epochs""": args.num_epochs, """seed""": 42, """batch_size""": 16} training_function(lowerCAmelCase_ ,lowerCAmelCase_ ) if __name__ == "__main__": main()
593
from argparse import ArgumentParser, Namespace from ..utils import logging from . import BaseTransformersCLICommand def __a ( lowerCAmelCase_ : Namespace ) -> Optional[int]: '''simple docstring''' return ConvertCommand( args.model_type ,args.tf_checkpoint ,args.pytorch_dump_output ,args.config ,args.finetuning_task_name ) __A = ''' transformers can only be used from the commandline to convert TensorFlow models in PyTorch, In that case, it requires TensorFlow to be installed. Please see https://www.tensorflow.org/install/ for installation instructions. ''' class lowercase ( snake_case__): """simple docstring""" @staticmethod def _SCREAMING_SNAKE_CASE ( __UpperCAmelCase : ArgumentParser ) -> Union[str, Any]: UpperCAmelCase_= parser.add_parser( """convert""" , help="""CLI tool to run convert model from original author checkpoints to Transformers PyTorch checkpoints.""" , ) train_parser.add_argument("""--model_type""" , type=__UpperCAmelCase , required=__UpperCAmelCase , help="""Model's type.""" ) train_parser.add_argument( """--tf_checkpoint""" , type=__UpperCAmelCase , required=__UpperCAmelCase , help="""TensorFlow checkpoint path or folder.""" ) train_parser.add_argument( """--pytorch_dump_output""" , type=__UpperCAmelCase , required=__UpperCAmelCase , help="""Path to the PyTorch saved model output.""" ) train_parser.add_argument("""--config""" , type=__UpperCAmelCase , default="""""" , help="""Configuration file path or folder.""" ) train_parser.add_argument( """--finetuning_task_name""" , type=__UpperCAmelCase , default=__UpperCAmelCase , help="""Optional fine-tuning task name if the TF model was a finetuned model.""" , ) train_parser.set_defaults(func=__UpperCAmelCase ) def __init__( self : Tuple , __UpperCAmelCase : str , __UpperCAmelCase : str , __UpperCAmelCase : str , __UpperCAmelCase : str , __UpperCAmelCase : str , *__UpperCAmelCase : Any , ) -> Optional[Any]: UpperCAmelCase_= logging.get_logger("""transformers-cli/converting""" ) self._logger.info(F"""Loading model {model_type}""" ) UpperCAmelCase_= model_type UpperCAmelCase_= tf_checkpoint UpperCAmelCase_= pytorch_dump_output UpperCAmelCase_= config UpperCAmelCase_= finetuning_task_name def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Optional[Any]: if self._model_type == "albert": try: from ..models.albert.convert_albert_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(__UpperCAmelCase ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "bert": try: from ..models.bert.convert_bert_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(__UpperCAmelCase ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "funnel": try: from ..models.funnel.convert_funnel_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(__UpperCAmelCase ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "t5": try: from ..models.ta.convert_ta_original_tf_checkpoint_to_pytorch import convert_tf_checkpoint_to_pytorch except ImportError: raise ImportError(__UpperCAmelCase ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "gpt": from ..models.openai.convert_openai_original_tf_checkpoint_to_pytorch import ( convert_openai_checkpoint_to_pytorch, ) convert_openai_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "transfo_xl": try: from ..models.transfo_xl.convert_transfo_xl_original_tf_checkpoint_to_pytorch import ( convert_transfo_xl_checkpoint_to_pytorch, ) except ImportError: raise ImportError(__UpperCAmelCase ) if "ckpt" in self._tf_checkpoint.lower(): UpperCAmelCase_= self._tf_checkpoint UpperCAmelCase_= """""" else: UpperCAmelCase_= self._tf_checkpoint UpperCAmelCase_= """""" convert_transfo_xl_checkpoint_to_pytorch( __UpperCAmelCase , self._config , self._pytorch_dump_output , __UpperCAmelCase ) elif self._model_type == "gpt2": try: from ..models.gpta.convert_gpta_original_tf_checkpoint_to_pytorch import ( convert_gpta_checkpoint_to_pytorch, ) except ImportError: raise ImportError(__UpperCAmelCase ) convert_gpta_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "xlnet": try: from ..models.xlnet.convert_xlnet_original_tf_checkpoint_to_pytorch import ( convert_xlnet_checkpoint_to_pytorch, ) except ImportError: raise ImportError(__UpperCAmelCase ) convert_xlnet_checkpoint_to_pytorch( self._tf_checkpoint , self._config , self._pytorch_dump_output , self._finetuning_task_name ) elif self._model_type == "xlm": from ..models.xlm.convert_xlm_original_pytorch_checkpoint_to_pytorch import ( convert_xlm_checkpoint_to_pytorch, ) convert_xlm_checkpoint_to_pytorch(self._tf_checkpoint , self._pytorch_dump_output ) elif self._model_type == "lxmert": from ..models.lxmert.convert_lxmert_original_tf_checkpoint_to_pytorch import ( convert_lxmert_checkpoint_to_pytorch, ) convert_lxmert_checkpoint_to_pytorch(self._tf_checkpoint , self._pytorch_dump_output ) elif self._model_type == "rembert": from ..models.rembert.convert_rembert_tf_checkpoint_to_pytorch import ( convert_rembert_tf_checkpoint_to_pytorch, ) convert_rembert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) else: raise ValueError( """--model_type should be selected in the list [bert, gpt, gpt2, t5, transfo_xl, xlnet, xlm, lxmert]""" )
593
1
'''simple docstring''' def lowerCamelCase_ ( lowercase__): if number < 0: raise ValueError("number must not be negative") return number & (number - 1) == 0 if __name__ == "__main__": import doctest doctest.testmod()
187
'''simple docstring''' import logging import sys from dataclasses import dataclass, field from typing import Any, Dict, List, Optional, Union import librosa import torch from datasets import DatasetDict, load_dataset from packaging import version from torch import nn from transformers import ( HfArgumentParser, Trainer, TrainingArguments, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaForPreTraining, is_apex_available, trainer_utils, ) from transformers.models.wavaveca.modeling_wavaveca import _compute_mask_indices if is_apex_available(): from apex import amp if version.parse(version.parse(torch.__version__).base_version) >= version.parse("""1.6"""): __A : List[Any] = True from torch.cuda.amp import autocast __A : List[Any] = logging.getLogger(__name__) @dataclass class lowercase : '''simple docstring''' lowerCAmelCase__ = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) lowerCAmelCase__ = field( default=_lowerCamelCase , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) lowerCAmelCase__ = field( default=_lowerCamelCase , metadata={"help": "Whether to freeze the feature extractor layers of the model."} ) lowerCAmelCase__ = field( default=_lowerCamelCase , metadata={"help": "Whether to log verbose messages or not."} , ) lowerCAmelCase__ = field( default=2.0 , metadata={"help": "Maximum temperature for gumbel softmax."} ) lowerCAmelCase__ = field( default=0.5 , metadata={"help": "Minimum temperature for gumbel softmax."} ) lowerCAmelCase__ = field( default=0.999995 , metadata={"help": "Decay of gumbel temperature during training."} ) def lowerCamelCase_ ( lowercase__ , lowercase__): logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , handlers=[logging.StreamHandler(sys.stdout)] , ) lowerCamelCase__ = logging.WARNING if model_args.verbose_logging: lowerCamelCase__ = logging.DEBUG elif trainer_utils.is_main_process(training_args.local_rank): lowerCamelCase__ = logging.INFO logger.setLevel(lowercase__) @dataclass class lowercase : '''simple docstring''' lowerCAmelCase__ = field( default=_lowerCamelCase , metadata={"help": "The name of the dataset to use (via the datasets library)."} ) lowerCAmelCase__ = field( default=_lowerCamelCase , metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} ) lowerCAmelCase__ = field( default="train" , metadata={ "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'" } , ) lowerCAmelCase__ = field( default="validation" , metadata={ "help": ( "The name of the validation data set split to use (via the datasets library). Defaults to 'validation'" ) } , ) lowerCAmelCase__ = field( default="file" , metadata={"help": "Column in the dataset that contains speech file path. Defaults to 'file'"} , ) lowerCAmelCase__ = field( default=_lowerCamelCase , metadata={"help": "Overwrite the cached preprocessed datasets or not."} ) lowerCAmelCase__ = field( default=1 , metadata={ "help": "The percentage of the train set used as validation set in case there's no validation split" } , ) lowerCAmelCase__ = field( default=_lowerCamelCase , metadata={"help": "The number of processes to use for the preprocessing."} , ) lowerCAmelCase__ = field( default=20.0 , metadata={"help": "Filter audio files that are longer than `max_duration_in_seconds` seconds"} ) @dataclass class lowercase : '''simple docstring''' lowerCAmelCase__ = 42 lowerCAmelCase__ = 42 lowerCAmelCase__ = "longest" lowerCAmelCase__ = None lowerCAmelCase__ = None def __call__( self : Optional[int] , __lowerCamelCase : List[Dict[str, Union[List[int], torch.Tensor]]] ) -> Dict[str, torch.Tensor]: '''simple docstring''' lowerCamelCase__ = self.feature_extractor.pad( __lowerCamelCase , max_length=self.max_length , padding=self.padding , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors="pt" , ) lowerCamelCase__ = self.model._get_feat_extract_output_lengths(batch["input_values"].shape[-1] ) lowerCamelCase__ = batch["input_values"].shape[0] # make sure that no loss is computed on padded inputs if batch["attention_mask"] is not None: # compute real output lengths according to convolution formula lowerCamelCase__ = self.model._get_feat_extract_output_lengths(batch["attention_mask"].sum(-1 ) ).to( torch.long ) lowerCamelCase__ = torch.zeros( (batch_size, mask_indices_seq_length) , dtype=torch.long , device=batch["input_values"].device ) # these two operations makes sure that all values # before the output lengths indices are attended to lowerCamelCase__ = 1 lowerCamelCase__ = attention_mask.flip([-1] ).cumsum(-1 ).flip([-1] ).bool() # sample randomly masked indices lowerCamelCase__ = _compute_mask_indices( (batch_size, mask_indices_seq_length) , self.model.config.mask_time_prob , self.model.config.mask_time_length , attention_mask=__lowerCamelCase , min_masks=2 , ) return batch class lowercase ( _lowerCamelCase ): '''simple docstring''' def __init__( self : str , *__lowerCamelCase : Union[str, Any] , __lowerCamelCase : int=1 , __lowerCamelCase : Optional[Any]=0 , __lowerCamelCase : str=1.0 , **__lowerCamelCase : Optional[Any] ) -> str: '''simple docstring''' super().__init__(*__lowerCamelCase , **__lowerCamelCase ) lowerCamelCase__ = 0 lowerCamelCase__ = max_gumbel_temp lowerCamelCase__ = min_gumbel_temp lowerCamelCase__ = gumbel_temp_decay def a__ ( self : Tuple , __lowerCamelCase : nn.Module , __lowerCamelCase : Dict[str, Union[torch.Tensor, Any]] ) -> torch.Tensor: '''simple docstring''' model.train() lowerCamelCase__ = self._prepare_inputs(__lowerCamelCase ) if self.use_amp: with autocast(): lowerCamelCase__ = self.compute_loss(__lowerCamelCase , __lowerCamelCase ) else: lowerCamelCase__ = self.compute_loss(__lowerCamelCase , __lowerCamelCase ) if self.args.n_gpu > 1 or self.deepspeed: if model.module.config.ctc_loss_reduction == "mean": lowerCamelCase__ = loss.mean() elif model.module.config.ctc_loss_reduction == "sum": lowerCamelCase__ = loss.sum() / (inputs["mask_time_indices"]).sum() else: raise ValueError(f'''{model.config.ctc_loss_reduction} is not valid. Choose one of [\'mean\', \'sum\']''' ) if self.args.gradient_accumulation_steps > 1: lowerCamelCase__ = loss / self.args.gradient_accumulation_steps if self.use_amp: self.scaler.scale(__lowerCamelCase ).backward() elif self.use_apex: with amp.scale_loss(__lowerCamelCase , self.optimizer ) as scaled_loss: scaled_loss.backward() elif self.deepspeed: self.deepspeed.backward(__lowerCamelCase ) else: loss.backward() self.num_update_step += 1 # make sure gumbel softmax temperature is decayed if self.args.n_gpu > 1 or self.deepspeed: model.module.set_gumbel_temperature( max(self.max_gumbel_temp * self.gumbel_temp_decay**self.num_update_step , self.min_gumbel_temp ) ) else: model.set_gumbel_temperature( max(self.max_gumbel_temp * self.gumbel_temp_decay**self.num_update_step , self.min_gumbel_temp ) ) return loss.detach() def lowerCamelCase_ ( ): # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. lowerCamelCase__ = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = parser.parse_args_into_dataclasses() configure_logger(lowercase__ , lowercase__) # Downloading and loading a dataset from the hub. lowerCamelCase__ = load_dataset(data_args.dataset_name , data_args.dataset_config_name , cache_dir=model_args.cache_dir) if "validation" not in datasets.keys(): # make sure only "validation" and "train" keys remain" lowerCamelCase__ = DatasetDict() lowerCamelCase__ = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=F'''{data_args.train_split_name}[:{data_args.validation_split_percentage}%]''' , cache_dir=model_args.cache_dir , ) lowerCamelCase__ = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=F'''{data_args.train_split_name}[{data_args.validation_split_percentage}%:]''' , cache_dir=model_args.cache_dir , ) else: # make sure only "validation" and "train" keys remain" lowerCamelCase__ = DatasetDict() lowerCamelCase__ = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split="validation" , cache_dir=model_args.cache_dir , ) lowerCamelCase__ = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=F'''{data_args.train_split_name}''' , cache_dir=model_args.cache_dir , ) # only normalized-inputs-training is supported lowerCamelCase__ = WavaVecaFeatureExtractor.from_pretrained( model_args.model_name_or_path , cache_dir=model_args.cache_dir , do_normalize=lowercase__) def prepare_dataset(lowercase__): # check that all files have the correct sampling rate lowerCamelCase__ , lowerCamelCase__ = librosa.load(batch[data_args.speech_file_column] , sr=feature_extractor.sampling_rate) return batch # load audio files into numpy arrays lowerCamelCase__ = datasets.map( lowercase__ , num_proc=data_args.preprocessing_num_workers , remove_columns=datasets["train"].column_names) # filter audio files that are too long lowerCamelCase__ = vectorized_datasets.filter( lambda lowercase__: len(data["speech"]) < int(data_args.max_duration_in_seconds * feature_extractor.sampling_rate)) def normalize(lowercase__): return feature_extractor(batch["speech"] , sampling_rate=feature_extractor.sampling_rate) # normalize and transform to `BatchFeatures` lowerCamelCase__ = vectorized_datasets.map( lowercase__ , batched=lowercase__ , num_proc=data_args.preprocessing_num_workers , load_from_cache_file=not data_args.overwrite_cache , remove_columns=vectorized_datasets["train"].column_names , ) # pretraining is only supported for "newer" stable layer norm architecture # apply_spec_augment has to be True, mask_feature_prob has to be 0.0 lowerCamelCase__ = WavaVecaConfig.from_pretrained( model_args.model_name_or_path , cache_dir=model_args.cache_dir , gradient_checkpointing=training_args.gradient_checkpointing , ) if not config.do_stable_layer_norm or config.feat_extract_norm != "layer": raise ValueError( "PreTraining is only supported for ``config.do_stable_layer_norm=True`` and" " ``config.feat_extract_norm='layer'") lowerCamelCase__ = WavaVecaForPreTraining(lowercase__) lowerCamelCase__ = DataCollatorForWavaVecaPretraining(model=lowercase__ , feature_extractor=lowercase__) lowerCamelCase__ = WavaVecaPreTrainer( model=lowercase__ , data_collator=lowercase__ , args=lowercase__ , train_dataset=vectorized_datasets["train"] , eval_dataset=vectorized_datasets["validation"] , tokenizer=lowercase__ , max_gumbel_temp=model_args.max_gumbel_temperature , min_gumbel_temp=model_args.min_gumbel_temperature , gumbel_temp_decay=model_args.gumbel_temperature_decay , ) trainer.train() if __name__ == "__main__": main()
187
1
"""simple docstring""" import argparse import torch from transformers import GPTaLMHeadModel, RobertaForMaskedLM if __name__ == "__main__": __lowerCamelCase = argparse.ArgumentParser( description=( "Extraction some layers of the full RobertaForMaskedLM or GPT2LMHeadModel for Transfer Learned" " Distillation" ) ) parser.add_argument("--model_type", default="roberta", choices=["roberta", "gpt2"]) parser.add_argument("--model_name", default="roberta-large", type=str) parser.add_argument("--dump_checkpoint", default="serialization_dir/tf_roberta_048131723.pth", type=str) parser.add_argument("--vocab_transform", action="store_true") __lowerCamelCase = parser.parse_args() if args.model_type == "roberta": __lowerCamelCase = RobertaForMaskedLM.from_pretrained(args.model_name) __lowerCamelCase = "roberta" elif args.model_type == "gpt2": __lowerCamelCase = GPTaLMHeadModel.from_pretrained(args.model_name) __lowerCamelCase = "transformer" __lowerCamelCase = model.state_dict() __lowerCamelCase = {} # Embeddings # if args.model_type == "gpt2": for param_name in ["wte.weight", "wpe.weight"]: __lowerCamelCase = state_dict[f"""{prefix}.{param_name}"""] else: for w in ["word_embeddings", "position_embeddings", "token_type_embeddings"]: __lowerCamelCase = f"""{prefix}.embeddings.{w}.weight""" __lowerCamelCase = state_dict[param_name] for w in ["weight", "bias"]: __lowerCamelCase = f"""{prefix}.embeddings.LayerNorm.{w}""" __lowerCamelCase = state_dict[param_name] # Transformer Blocks # __lowerCamelCase = 0 for teacher_idx in [0, 2, 4, 7, 9, 11]: if args.model_type == "gpt2": for layer in ["ln_1", "attn.c_attn", "attn.c_proj", "ln_2", "mlp.c_fc", "mlp.c_proj"]: for w in ["weight", "bias"]: __lowerCamelCase = state_dict[ f"""{prefix}.h.{teacher_idx}.{layer}.{w}""" ] __lowerCamelCase = state_dict[f"""{prefix}.h.{teacher_idx}.attn.bias"""] else: for layer in [ "attention.self.query", "attention.self.key", "attention.self.value", "attention.output.dense", "attention.output.LayerNorm", "intermediate.dense", "output.dense", "output.LayerNorm", ]: for w in ["weight", "bias"]: __lowerCamelCase = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.{layer}.{w}""" ] std_idx += 1 # Language Modeling Head ###s if args.model_type == "roberta": for layer in ["lm_head.decoder.weight", "lm_head.bias"]: __lowerCamelCase = state_dict[f"""{layer}"""] if args.vocab_transform: for w in ["weight", "bias"]: __lowerCamelCase = state_dict[f"""lm_head.dense.{w}"""] __lowerCamelCase = state_dict[f"""lm_head.layer_norm.{w}"""] elif args.model_type == "gpt2": for w in ["weight", "bias"]: __lowerCamelCase = state_dict[f"""{prefix}.ln_f.{w}"""] __lowerCamelCase = state_dict["lm_head.weight"] print(f"""N layers selected for distillation: {std_idx}""") print(f"""Number of params transferred for distillation: {len(compressed_sd.keys())}""") print(f"""Save transferred checkpoint to {args.dump_checkpoint}.""") torch.save(compressed_sd, args.dump_checkpoint)
490
"""simple docstring""" from collections import defaultdict from graphs.minimum_spanning_tree_prims import prisms_algorithm as mst def lowercase ( ) -> int: __magic_name__ , __magic_name__ = 9, 14 # noqa: F841 __magic_name__ = [ [0, 1, 4], [0, 7, 8], [1, 2, 8], [7, 8, 7], [7, 6, 1], [2, 8, 2], [8, 6, 6], [2, 3, 7], [2, 5, 4], [6, 5, 2], [3, 5, 14], [3, 4, 9], [5, 4, 10], [1, 7, 11], ] __magic_name__ = defaultdict(__UpperCamelCase ) for nodea, nodea, cost in edges: adjancency[nodea].append([nodea, cost] ) adjancency[nodea].append([nodea, cost] ) __magic_name__ = mst(__UpperCamelCase ) __magic_name__ = [ [7, 6, 1], [2, 8, 2], [6, 5, 2], [0, 1, 4], [2, 5, 4], [2, 3, 7], [0, 7, 8], [3, 4, 9], ] for answer in expected: __magic_name__ = tuple(answer[:2] ) __magic_name__ = tuple(edge[::-1] ) assert edge in result or reverse in result
490
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _UpperCamelCase = logging.get_logger(__name__) _UpperCamelCase = { """funnel-transformer/small""": """https://huggingface.co/funnel-transformer/small/resolve/main/config.json""", """funnel-transformer/small-base""": """https://huggingface.co/funnel-transformer/small-base/resolve/main/config.json""", """funnel-transformer/medium""": """https://huggingface.co/funnel-transformer/medium/resolve/main/config.json""", """funnel-transformer/medium-base""": """https://huggingface.co/funnel-transformer/medium-base/resolve/main/config.json""", """funnel-transformer/intermediate""": ( """https://huggingface.co/funnel-transformer/intermediate/resolve/main/config.json""" ), """funnel-transformer/intermediate-base""": ( """https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/config.json""" ), """funnel-transformer/large""": """https://huggingface.co/funnel-transformer/large/resolve/main/config.json""", """funnel-transformer/large-base""": """https://huggingface.co/funnel-transformer/large-base/resolve/main/config.json""", """funnel-transformer/xlarge""": """https://huggingface.co/funnel-transformer/xlarge/resolve/main/config.json""", """funnel-transformer/xlarge-base""": """https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/config.json""", } class lowerCamelCase__ ( snake_case ): SCREAMING_SNAKE_CASE = '''funnel''' SCREAMING_SNAKE_CASE = { '''hidden_size''': '''d_model''', '''num_attention_heads''': '''n_head''', } def __init__( self ,A=30_522 ,A=[4, 4, 4] ,A=None ,A=2 ,A=768 ,A=12 ,A=64 ,A=3_072 ,A="gelu_new" ,A=0.1 ,A=0.1 ,A=0.0 ,A=0.1 ,A=None ,A=1e-9 ,A="mean" ,A="relative_shift" ,A=True ,A=True ,A=True ,**A ,): UpperCAmelCase = vocab_size UpperCAmelCase = block_sizes UpperCAmelCase = [1] * len(A ) if block_repeats is None else block_repeats assert len(A ) == len( self.block_repeats ), "`block_sizes` and `block_repeats` should have the same length." UpperCAmelCase = num_decoder_layers UpperCAmelCase = d_model UpperCAmelCase = n_head UpperCAmelCase = d_head UpperCAmelCase = d_inner UpperCAmelCase = hidden_act UpperCAmelCase = hidden_dropout UpperCAmelCase = attention_dropout UpperCAmelCase = activation_dropout UpperCAmelCase = initializer_range UpperCAmelCase = initializer_std UpperCAmelCase = layer_norm_eps assert pooling_type in [ "mean", "max", ], F'''Got {pooling_type} for `pooling_type` but only \'mean\' and \'max\' are supported.''' UpperCAmelCase = pooling_type assert attention_type in [ "relative_shift", "factorized", ], F'''Got {attention_type} for `attention_type` but only \'relative_shift\' and \'factorized\' are supported.''' UpperCAmelCase = attention_type UpperCAmelCase = separate_cls UpperCAmelCase = truncate_seq UpperCAmelCase = pool_q_only super().__init__(**A ) @property def _UpperCamelCase ( self ): return sum(self.block_sizes ) @num_hidden_layers.setter def _UpperCamelCase ( self ,A ): raise NotImplementedError( """This model does not support the setting of `num_hidden_layers`. Please set `block_sizes`.""" ) @property def _UpperCamelCase ( self ): return len(self.block_sizes ) @num_blocks.setter def _UpperCamelCase ( self ,A ): raise NotImplementedError("""This model does not support the setting of `num_blocks`. Please set `block_sizes`.""" )
74
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, 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 numpy as np import tensorflow as tf from transformers import ( TF_FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST, FlaubertConfig, TFFlaubertForMultipleChoice, TFFlaubertForQuestionAnsweringSimple, TFFlaubertForSequenceClassification, TFFlaubertForTokenClassification, TFFlaubertModel, TFFlaubertWithLMHeadModel, ) class lowerCamelCase__ : def __init__( self ,A ,): UpperCAmelCase = parent UpperCAmelCase = 13 UpperCAmelCase = 7 UpperCAmelCase = True UpperCAmelCase = True UpperCAmelCase = True UpperCAmelCase = True UpperCAmelCase = True UpperCAmelCase = False UpperCAmelCase = False UpperCAmelCase = False UpperCAmelCase = 2 UpperCAmelCase = 99 UpperCAmelCase = 0 UpperCAmelCase = 32 UpperCAmelCase = 2 UpperCAmelCase = 4 UpperCAmelCase = 0.1 UpperCAmelCase = 0.1 UpperCAmelCase = 512 UpperCAmelCase = 16 UpperCAmelCase = 2 UpperCAmelCase = 0.02 UpperCAmelCase = 3 UpperCAmelCase = 4 UpperCAmelCase = """last""" UpperCAmelCase = True UpperCAmelCase = None UpperCAmelCase = 0 def _UpperCamelCase ( self ): UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) UpperCAmelCase = random_attention_mask([self.batch_size, self.seq_length] ,dtype=tf.floataa ) UpperCAmelCase = None if self.use_input_lengths: UpperCAmelCase = ( ids_tensor([self.batch_size] ,vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length UpperCAmelCase = None if self.use_token_type_ids: UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] ,self.n_langs ) 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] ,2 ,dtype=tf.floataa ) UpperCAmelCase = ids_tensor([self.batch_size] ,self.num_choices ) UpperCAmelCase = FlaubertConfig( vocab_size=self.vocab_size ,n_special=self.n_special ,emb_dim=self.hidden_size ,n_layers=self.num_hidden_layers ,n_heads=self.num_attention_heads ,dropout=self.hidden_dropout_prob ,attention_dropout=self.attention_probs_dropout_prob ,gelu_activation=self.gelu_activation ,sinusoidal_embeddings=self.sinusoidal_embeddings ,asm=self.asm ,causal=self.causal ,n_langs=self.n_langs ,max_position_embeddings=self.max_position_embeddings ,initializer_range=self.initializer_range ,summary_type=self.summary_type ,use_proj=self.use_proj ,bos_token_id=self.bos_token_id ,) return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def _UpperCamelCase ( self ,A ,A ,A ,A ,A ,A ,A ,A ,A ,): UpperCAmelCase = TFFlaubertModel(config=A ) UpperCAmelCase = {"""input_ids""": input_ids, """lengths""": input_lengths, """langs""": token_type_ids} UpperCAmelCase = model(A ) UpperCAmelCase = [input_ids, input_mask] 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 ,A ,A ,): UpperCAmelCase = TFFlaubertWithLMHeadModel(A ) UpperCAmelCase = {"""input_ids""": input_ids, """lengths""": input_lengths, """langs""": 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 ,A ,A ,): UpperCAmelCase = TFFlaubertForQuestionAnsweringSimple(A ) UpperCAmelCase = {"""input_ids""": input_ids, """lengths""": input_lengths} 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 ,A ,A ,A ,A ,A ,A ,A ,A ,A ,): UpperCAmelCase = TFFlaubertForSequenceClassification(A ) UpperCAmelCase = {"""input_ids""": input_ids, """lengths""": input_lengths} UpperCAmelCase = model(A ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) def _UpperCamelCase ( self ,A ,A ,A ,A ,A ,A ,A ,A ,A ,): UpperCAmelCase = self.num_labels UpperCAmelCase = TFFlaubertForTokenClassification(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 ,A ,A ,): UpperCAmelCase = self.num_choices UpperCAmelCase = TFFlaubertForMultipleChoice(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 ): UpperCAmelCase = self.prepare_config_and_inputs() ( ( UpperCAmelCase ) , ( UpperCAmelCase ) , ( UpperCAmelCase ) , ( UpperCAmelCase ) , ( UpperCAmelCase ) , ( UpperCAmelCase ) , ( UpperCAmelCase ) , ( UpperCAmelCase ) , ( UpperCAmelCase ) , ) = config_and_inputs UpperCAmelCase = { """input_ids""": input_ids, """token_type_ids""": token_type_ids, """langs""": token_type_ids, """lengths""": input_lengths, } return config, inputs_dict @require_tf class lowerCamelCase__ ( snake_case , snake_case , unittest.TestCase ): SCREAMING_SNAKE_CASE = ( ( TFFlaubertModel, TFFlaubertWithLMHeadModel, TFFlaubertForSequenceClassification, TFFlaubertForQuestionAnsweringSimple, TFFlaubertForTokenClassification, TFFlaubertForMultipleChoice, ) if is_tf_available() else () ) SCREAMING_SNAKE_CASE = ( (TFFlaubertWithLMHeadModel,) if is_tf_available() else () ) # TODO (PVP): Check other models whether language generation is also applicable SCREAMING_SNAKE_CASE = ( { '''feature-extraction''': TFFlaubertModel, '''fill-mask''': TFFlaubertWithLMHeadModel, '''question-answering''': TFFlaubertForQuestionAnsweringSimple, '''text-classification''': TFFlaubertForSequenceClassification, '''token-classification''': TFFlaubertForTokenClassification, '''zero-shot''': TFFlaubertForSequenceClassification, } if is_tf_available() else {} ) SCREAMING_SNAKE_CASE = False SCREAMING_SNAKE_CASE = False def _UpperCamelCase ( self ,A ,A ,A ,A ,A ): if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith("""Fast""" ) ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def _UpperCamelCase ( self ): UpperCAmelCase = TFFlaubertModelTester(self ) UpperCAmelCase = ConfigTester(self ,config_class=A ,emb_dim=37 ) def _UpperCamelCase ( self ): self.config_tester.run_common_tests() def _UpperCamelCase ( self ): UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_model(*A ) def _UpperCamelCase ( self ): UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_lm_head(*A ) def _UpperCamelCase ( self ): UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_qa(*A ) def _UpperCamelCase ( self ): UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_sequence_classif(*A ) def _UpperCamelCase ( self ): UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_for_token_classification(*A ) def _UpperCamelCase ( self ): UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_for_multiple_choice(*A ) @slow def _UpperCamelCase ( self ): for model_name in TF_FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase = TFFlaubertModel.from_pretrained(A ) self.assertIsNotNone(A ) @require_tf @require_sentencepiece @require_tokenizers class lowerCamelCase__ ( unittest.TestCase ): @slow def _UpperCamelCase ( self ): UpperCAmelCase = TFFlaubertModel.from_pretrained("""jplu/tf-flaubert-small-cased""" ) UpperCAmelCase = tf.convert_to_tensor( [[0, 158, 735, 2_592, 1_424, 6_727, 82, 1]] ,dtype=tf.intaa ,) # "J'aime flaubert !" UpperCAmelCase = model(A )[0] UpperCAmelCase = tf.TensorShape((1, 8, 512) ) self.assertEqual(output.shape ,A ) # compare the actual values for a slice. UpperCAmelCase = tf.convert_to_tensor( [ [ [-1.8768773, -1.566555, 0.27072418], [-1.6920038, -0.5873505, 1.9329599], [-2.9563985, -1.6993835, 1.7972052], ] ] ,dtype=tf.floataa ,) self.assertTrue(np.allclose(output[:, :3, :3].numpy() ,expected_slice.numpy() ,atol=1e-4 ) )
74
1
'''simple docstring''' import random import unittest import torch from diffusers import IFImgaImgSuperResolutionPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin from . import IFPipelineTesterMixin @skip_mps class __snake_case ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = IFImgaImgSuperResolutionPipeline lowerCamelCase__ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''width''', '''height'''} lowerCamelCase__ = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'''original_image'''} ) lowerCamelCase__ = PipelineTesterMixin.required_optional_params - {'''latents'''} def __UpperCamelCase ( self ): return self._get_superresolution_dummy_components() def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=0 ): if str(__SCREAMING_SNAKE_CASE ).startswith("""mps""" ): snake_case__ : List[Any] = torch.manual_seed(__SCREAMING_SNAKE_CASE ) else: snake_case__ : Tuple = torch.Generator(device=__SCREAMING_SNAKE_CASE ).manual_seed(__SCREAMING_SNAKE_CASE ) snake_case__ : Tuple = floats_tensor((1, 3, 3_2, 3_2) , rng=random.Random(__SCREAMING_SNAKE_CASE ) ).to(__SCREAMING_SNAKE_CASE ) snake_case__ : Union[str, Any] = floats_tensor((1, 3, 1_6, 1_6) , rng=random.Random(__SCREAMING_SNAKE_CASE ) ).to(__SCREAMING_SNAKE_CASE ) snake_case__ : int = { """prompt""": """A painting of a squirrel eating a burger""", """image""": image, """original_image""": original_image, """generator""": generator, """num_inference_steps""": 2, """output_type""": """numpy""", } return inputs @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , ) def __UpperCamelCase ( self ): self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3 ) def __UpperCamelCase ( self ): self._test_save_load_optional_components() @unittest.skipIf(torch_device != """cuda""" , reason="""float16 requires CUDA""" ) def __UpperCamelCase ( self ): # Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder super().test_save_load_floataa(expected_max_diff=1e-1 ) def __UpperCamelCase ( self ): self._test_attention_slicing_forward_pass(expected_max_diff=1e-2 ) def __UpperCamelCase ( self ): self._test_save_load_local() def __UpperCamelCase ( self ): self._test_inference_batch_single_identical( expected_max_diff=1e-2 , )
38
'''simple docstring''' def UpperCamelCase__ ( __magic_name__ : List[Any] ) -> Tuple: '''simple docstring''' if not head: return True # split the list to two parts snake_case__ , snake_case__ : Dict = head.next, head while fast and fast.next: snake_case__ : Any = fast.next.next snake_case__ : int = slow.next snake_case__ : Dict = slow.next snake_case__ : List[str] = None # Don't forget here! But forget still works! # reverse the second part snake_case__ : Tuple = None while second: snake_case__ : Tuple = second.next snake_case__ : Any = node snake_case__ : str = second snake_case__ : Optional[Any] = nxt # compare two parts # second part has the same or one less node while node: if node.val != head.val: return False snake_case__ : List[Any] = node.next snake_case__ : int = head.next return True def UpperCamelCase__ ( __magic_name__ : Any ) -> Optional[Any]: '''simple docstring''' if not head or not head.next: return True # 1. Get the midpoint (slow) snake_case__ : List[Any] = head while fast and fast.next: snake_case__ , snake_case__ : Any = fast.next.next, slow.next # 2. Push the second half into the stack snake_case__ : Tuple = [slow.val] while slow.next: snake_case__ : Optional[Any] = slow.next stack.append(slow.val ) # 3. Comparison while stack: if stack.pop() != cur.val: return False snake_case__ : str = cur.next return True def UpperCamelCase__ ( __magic_name__ : Optional[Any] ) -> Tuple: '''simple docstring''' if not head or not head.next: return True snake_case__ : int = {} snake_case__ : Union[str, Any] = 0 while head: if head.val in d: d[head.val].append(__magic_name__ ) else: snake_case__ : Tuple = [pos] snake_case__ : Optional[Any] = head.next pos += 1 snake_case__ : int = pos - 1 snake_case__ : str = 0 for v in d.values(): if len(__magic_name__ ) % 2 != 0: middle += 1 else: snake_case__ : List[str] = 0 for i in range(0 , len(__magic_name__ ) ): if v[i] + v[len(__magic_name__ ) - 1 - step] != checksum: return False step += 1 if middle > 1: return False return True
38
1
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging a = logging.get_logger(__name__) a = {"""vocab_file""": """sentencepiece.bpe.model"""} a = { """vocab_file""": { """camembert-base""": """https://huggingface.co/camembert-base/resolve/main/sentencepiece.bpe.model""", } } a = { """camembert-base""": 512, } a = """▁""" class UpperCAmelCase_ (snake_case__ ): """simple docstring""" lowerCamelCase : int = VOCAB_FILES_NAMES lowerCamelCase : Tuple = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase : int = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase : int = ['input_ids', 'attention_mask'] def __init__( self: List[Any] , _UpperCAmelCase: Union[str, Any] , _UpperCAmelCase: str="<s>" , _UpperCAmelCase: List[Any]="</s>" , _UpperCAmelCase: Any="</s>" , _UpperCAmelCase: int="<s>" , _UpperCAmelCase: str="<unk>" , _UpperCAmelCase: Any="<pad>" , _UpperCAmelCase: Any="<mask>" , _UpperCAmelCase: Union[str, Any]=["<s>NOTUSED", "</s>NOTUSED"] , _UpperCAmelCase: Optional[Dict[str, Any]] = None , **_UpperCAmelCase: Optional[int] , ): # Mask token behave like a normal word, i.e. include the space before it _lowerCAmelCase :Union[str, Any] = AddedToken(_UpperCAmelCase , lstrip=_UpperCAmelCase , rstrip=_UpperCAmelCase ) if isinstance(_UpperCAmelCase , _UpperCAmelCase ) else mask_token _lowerCAmelCase :Union[str, Any] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=_UpperCAmelCase , eos_token=_UpperCAmelCase , unk_token=_UpperCAmelCase , sep_token=_UpperCAmelCase , cls_token=_UpperCAmelCase , pad_token=_UpperCAmelCase , mask_token=_UpperCAmelCase , additional_special_tokens=_UpperCAmelCase , sp_model_kwargs=self.sp_model_kwargs , **_UpperCAmelCase , ) _lowerCAmelCase :Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(_UpperCAmelCase ) ) _lowerCAmelCase :Dict = vocab_file # HACK: These tokens were added by fairseq but don't seem to be actually used when duplicated in the actual # sentencepiece vocabulary (this is the case for <s> and </s> _lowerCAmelCase :int = {'<s>NOTUSED': 0, '<pad>': 1, '</s>NOTUSED': 2, '<unk>': 3} _lowerCAmelCase :List[Any] = len(self.fairseq_tokens_to_ids ) _lowerCAmelCase :List[str] = len(self.sp_model ) + len(self.fairseq_tokens_to_ids ) _lowerCAmelCase :str = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def SCREAMING_SNAKE_CASE__ ( self: Dict , _UpperCAmelCase: List[int] , _UpperCAmelCase: Optional[List[int]] = None ): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] _lowerCAmelCase :List[str] = [self.cls_token_id] _lowerCAmelCase :Dict = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE__ ( self: str , _UpperCAmelCase: List[int] , _UpperCAmelCase: Optional[List[int]] = None , _UpperCAmelCase: bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_UpperCAmelCase , token_ids_a=_UpperCAmelCase , already_has_special_tokens=_UpperCAmelCase ) if token_ids_a is None: return [1] + ([0] * len(_UpperCAmelCase )) + [1] return [1] + ([0] * len(_UpperCAmelCase )) + [1, 1] + ([0] * len(_UpperCAmelCase )) + [1] def SCREAMING_SNAKE_CASE__ ( self: Optional[int] , _UpperCAmelCase: List[int] , _UpperCAmelCase: Optional[List[int]] = None ): _lowerCAmelCase :List[Any] = [self.sep_token_id] _lowerCAmelCase :Optional[Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def SCREAMING_SNAKE_CASE__ ( self: Dict ): return len(self.fairseq_tokens_to_ids ) + len(self.sp_model ) def SCREAMING_SNAKE_CASE__ ( self: Optional[int] ): _lowerCAmelCase :List[str] = {self.convert_ids_to_tokens(_UpperCAmelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def SCREAMING_SNAKE_CASE__ ( self: Union[str, Any] , _UpperCAmelCase: str ): return self.sp_model.encode(_UpperCAmelCase , out_type=_UpperCAmelCase ) def SCREAMING_SNAKE_CASE__ ( self: Dict , _UpperCAmelCase: int ): if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] elif self.sp_model.PieceToId(_UpperCAmelCase ) == 0: # Convert sentence piece unk token to fairseq unk token index return self.unk_token_id return self.fairseq_offset + self.sp_model.PieceToId(_UpperCAmelCase ) def SCREAMING_SNAKE_CASE__ ( self: List[str] , _UpperCAmelCase: Union[str, Any] ): if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def SCREAMING_SNAKE_CASE__ ( self: Optional[Any] , _UpperCAmelCase: str ): _lowerCAmelCase :Union[str, Any] = [] _lowerCAmelCase :str = '' _lowerCAmelCase :Tuple = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(_UpperCAmelCase ) + token _lowerCAmelCase :Any = True _lowerCAmelCase :List[str] = [] else: current_sub_tokens.append(_UpperCAmelCase ) _lowerCAmelCase :Optional[Any] = False out_string += self.sp_model.decode(_UpperCAmelCase ) return out_string.strip() def __getstate__( self: Dict ): _lowerCAmelCase :Any = self.__dict__.copy() _lowerCAmelCase :List[Any] = None return state def __setstate__( self: Optional[int] , _UpperCAmelCase: str ): _lowerCAmelCase :List[str] = d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): _lowerCAmelCase :str = {} _lowerCAmelCase :Dict = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def SCREAMING_SNAKE_CASE__ ( self: List[str] , _UpperCAmelCase: str , _UpperCAmelCase: Optional[str] = None ): if not os.path.isdir(_UpperCAmelCase ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return _lowerCAmelCase :List[Any] = 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 :Union[str, Any] = self.sp_model.serialized_model_proto() fi.write(_UpperCAmelCase ) return (out_vocab_file,)
382
from math import sqrt def UpperCamelCase_( __magic_name__ : int = 1000000 ): """simple docstring""" _lowerCAmelCase :int = 0 _lowerCAmelCase :int = 0 _lowerCAmelCase :int while num_cuboids <= limit: max_cuboid_size += 1 for sum_shortest_sides in range(2 , 2 * max_cuboid_size + 1 ): if sqrt(sum_shortest_sides**2 + max_cuboid_size**2 ).is_integer(): num_cuboids += ( min(__magic_name__ , sum_shortest_sides // 2 ) - max(1 , sum_shortest_sides - max_cuboid_size ) + 1 ) return max_cuboid_size if __name__ == "__main__": print(F'''{solution() = }''')
382
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_tf_available, is_torch_available, ) SCREAMING_SNAKE_CASE_ = { '''configuration_speech_to_text''': ['''SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Speech2TextConfig'''], '''processing_speech_to_text''': ['''Speech2TextProcessor'''], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_ = ['''Speech2TextTokenizer'''] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_ = ['''Speech2TextFeatureExtractor'''] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_ = [ '''TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFSpeech2TextForConditionalGeneration''', '''TFSpeech2TextModel''', '''TFSpeech2TextPreTrainedModel''', ] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_ = [ '''SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''Speech2TextForConditionalGeneration''', '''Speech2TextModel''', '''Speech2TextPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_speech_to_text import SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, SpeechaTextConfig from .processing_speech_to_text import SpeechaTextProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speech_to_text import SpeechaTextTokenizer try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_speech_to_text import SpeechaTextFeatureExtractor try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_speech_to_text import ( TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, TFSpeechaTextForConditionalGeneration, TFSpeechaTextModel, TFSpeechaTextPreTrainedModel, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_to_text import ( SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechaTextForConditionalGeneration, SpeechaTextModel, SpeechaTextPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
465
"""simple docstring""" from __future__ import annotations from statistics import mean def lowercase (_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ): __lowerCAmelCase = [0] * no_of_processes __lowerCAmelCase = [0] * no_of_processes # Initialize remaining_time to waiting_time. for i in range(_lowerCAmelCase ): __lowerCAmelCase = burst_time[i] __lowerCAmelCase = [] __lowerCAmelCase = 0 __lowerCAmelCase = 0 # When processes are not completed, # A process whose arrival time has passed \ # and has remaining execution time is put into the ready_process. # The shortest process in the ready_process, target_process is executed. while completed != no_of_processes: __lowerCAmelCase = [] __lowerCAmelCase = -1 for i in range(_lowerCAmelCase ): if (arrival_time[i] <= total_time) and (remaining_time[i] > 0): ready_process.append(_lowerCAmelCase ) if len(_lowerCAmelCase ) > 0: __lowerCAmelCase = ready_process[0] for i in ready_process: if remaining_time[i] < remaining_time[target_process]: __lowerCAmelCase = i total_time += burst_time[target_process] completed += 1 __lowerCAmelCase = 0 __lowerCAmelCase = ( total_time - arrival_time[target_process] - burst_time[target_process] ) else: total_time += 1 return waiting_time def lowercase (_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ): __lowerCAmelCase = [0] * no_of_processes for i in range(_lowerCAmelCase ): __lowerCAmelCase = burst_time[i] + waiting_time[i] return turn_around_time if __name__ == "__main__": print('''[TEST CASE 01]''') SCREAMING_SNAKE_CASE_ = 4 SCREAMING_SNAKE_CASE_ = [2, 5, 3, 7] SCREAMING_SNAKE_CASE_ = [0, 0, 0, 0] SCREAMING_SNAKE_CASE_ = calculate_waitingtime(arrival_time, burst_time, no_of_processes) SCREAMING_SNAKE_CASE_ = calculate_turnaroundtime( burst_time, no_of_processes, waiting_time ) # Printing the Result print('''PID\tBurst Time\tArrival Time\tWaiting Time\tTurnaround Time''') for i, process_id in enumerate(list(range(1, 5))): print( F"{process_id}\t{burst_time[i]}\t\t\t{arrival_time[i]}\t\t\t\t" F"{waiting_time[i]}\t\t\t\t{turn_around_time[i]}" ) print(F"\nAverage waiting time = {mean(waiting_time):.5f}") print(F"Average turnaround time = {mean(turn_around_time):.5f}")
465
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) _UpperCamelCase = { "configuration_falcon": ["FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP", "FalconConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCamelCase = [ "FALCON_PRETRAINED_MODEL_ARCHIVE_LIST", "FalconForCausalLM", "FalconModel", "FalconPreTrainedModel", "FalconForSequenceClassification", "FalconForTokenClassification", "FalconForQuestionAnswering", ] if TYPE_CHECKING: from .configuration_falcon import FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP, FalconConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_falcon import ( FALCON_PRETRAINED_MODEL_ARCHIVE_LIST, FalconForCausalLM, FalconForQuestionAnswering, FalconForSequenceClassification, FalconForTokenClassification, FalconModel, FalconPreTrainedModel, ) else: import sys _UpperCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
705
"""simple docstring""" from typing import Optional, Tuple, Union import tensorflow as tf from ...activations_tf import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_tf_outputs import ( TFBaseModelOutputWithNoAttention, TFBaseModelOutputWithPoolingAndNoAttention, TFSequenceClassifierOutput, ) from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs from ...tf_utils import shape_list from ...utils import logging from .configuration_regnet import RegNetConfig _UpperCamelCase = logging.get_logger(__name__) # General docstring _UpperCamelCase = 'RegNetConfig' # Base docstring _UpperCamelCase = 'facebook/regnet-y-040' _UpperCamelCase = [1, 1088, 7, 7] # Image classification docstring _UpperCamelCase = 'facebook/regnet-y-040' _UpperCamelCase = 'tabby, tabby cat' _UpperCamelCase = [ 'facebook/regnet-y-040', # See all regnet models at https://huggingface.co/models?filter=regnet ] class SCREAMING_SNAKE_CASE_ ( tf.keras.layers.Layer ): """simple docstring""" def __init__( self :Dict , __lowercase :int , __lowercase :int = 3 , __lowercase :int = 1 , __lowercase :int = 1 , __lowercase :Optional[str] = "relu" , **__lowercase :int , ): super().__init__(**__lowercase ) # The padding and conv has been verified in # https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb __lowerCamelCase : int =tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2 ) __lowerCamelCase : str =tf.keras.layers.ConvaD( filters=__lowercase , kernel_size=__lowercase , strides=__lowercase , padding='''VALID''' , groups=__lowercase , use_bias=__lowercase , name='''convolution''' , ) __lowerCamelCase : str =tf.keras.layers.BatchNormalization(epsilon=1e-5 , momentum=0.9 , name='''normalization''' ) __lowerCamelCase : Optional[int] =ACTaFN[activation] if activation is not None else tf.identity def __lowercase ( self :Optional[int] , __lowercase :Any ): __lowerCamelCase : str =self.convolution(self.padding(__lowercase ) ) __lowerCamelCase : Optional[int] =self.normalization(__lowercase ) __lowerCamelCase : Any =self.activation(__lowercase ) return hidden_state class SCREAMING_SNAKE_CASE_ ( tf.keras.layers.Layer ): """simple docstring""" def __init__( self :Union[str, Any] , __lowercase :RegNetConfig , **__lowercase :Any ): super().__init__(**__lowercase ) __lowerCamelCase : Tuple =config.num_channels __lowerCamelCase : Union[str, Any] =TFRegNetConvLayer( out_channels=config.embedding_size , kernel_size=3 , stride=2 , activation=config.hidden_act , name='''embedder''' , ) def __lowercase ( self :int , __lowercase :List[str] ): __lowerCamelCase : int =shape_list(__lowercase )[1] if tf.executing_eagerly() and num_channels != self.num_channels: raise ValueError( '''Make sure that the channel dimension of the pixel values match with the one set in the configuration.''' ) # When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format. # So change the input format from `NCHW` to `NHWC`. # shape = (batch_size, in_height, in_width, in_channels=num_channels) __lowerCamelCase : Union[str, Any] =tf.transpose(__lowercase , perm=(0, 2, 3, 1) ) __lowerCamelCase : Optional[int] =self.embedder(__lowercase ) return hidden_state class SCREAMING_SNAKE_CASE_ ( tf.keras.layers.Layer ): """simple docstring""" def __init__( self :List[Any] , __lowercase :int , __lowercase :int = 2 , **__lowercase :Optional[int] ): super().__init__(**__lowercase ) __lowerCamelCase : int =tf.keras.layers.ConvaD( filters=__lowercase , kernel_size=1 , strides=__lowercase , use_bias=__lowercase , name='''convolution''' ) __lowerCamelCase : List[str] =tf.keras.layers.BatchNormalization(epsilon=1e-5 , momentum=0.9 , name='''normalization''' ) def __lowercase ( self :Optional[Any] , __lowercase :tf.Tensor , __lowercase :bool = False ): return self.normalization(self.convolution(__lowercase ) , training=__lowercase ) class SCREAMING_SNAKE_CASE_ ( tf.keras.layers.Layer ): """simple docstring""" def __init__( self :Dict , __lowercase :int , __lowercase :int , **__lowercase :List[str] ): super().__init__(**__lowercase ) __lowerCamelCase : int =tf.keras.layers.GlobalAveragePoolingaD(keepdims=__lowercase , name='''pooler''' ) __lowerCamelCase : int =[ tf.keras.layers.ConvaD(filters=__lowercase , kernel_size=1 , activation='''relu''' , name='''attention.0''' ), tf.keras.layers.ConvaD(filters=__lowercase , kernel_size=1 , activation='''sigmoid''' , name='''attention.2''' ), ] def __lowercase ( self :Dict , __lowercase :Union[str, Any] ): # [batch_size, h, w, num_channels] -> [batch_size, 1, 1, num_channels] __lowerCamelCase : Any =self.pooler(__lowercase ) for layer_module in self.attention: __lowerCamelCase : Any =layer_module(__lowercase ) __lowerCamelCase : Dict =hidden_state * pooled return hidden_state class SCREAMING_SNAKE_CASE_ ( tf.keras.layers.Layer ): """simple docstring""" def __init__( self :Optional[int] , __lowercase :RegNetConfig , __lowercase :int , __lowercase :int , __lowercase :int = 1 , **__lowercase :str ): super().__init__(**__lowercase ) __lowerCamelCase : Dict =in_channels != out_channels or stride != 1 __lowerCamelCase : int =max(1 , out_channels // config.groups_width ) __lowerCamelCase : List[str] =( TFRegNetShortCut(__lowercase , stride=__lowercase , name='''shortcut''' ) if should_apply_shortcut else tf.keras.layers.Activation('''linear''' , name='''shortcut''' ) ) # `self.layers` instead of `self.layer` because that is a reserved argument. __lowerCamelCase : str =[ TFRegNetConvLayer(__lowercase , kernel_size=1 , activation=config.hidden_act , name='''layer.0''' ), TFRegNetConvLayer( __lowercase , stride=__lowercase , groups=__lowercase , activation=config.hidden_act , name='''layer.1''' ), TFRegNetConvLayer(__lowercase , kernel_size=1 , activation=__lowercase , name='''layer.2''' ), ] __lowerCamelCase : Optional[int] =ACTaFN[config.hidden_act] def __lowercase ( self :int , __lowercase :Optional[int] ): __lowerCamelCase : List[Any] =hidden_state for layer_module in self.layers: __lowerCamelCase : str =layer_module(__lowercase ) __lowerCamelCase : List[Any] =self.shortcut(__lowercase ) hidden_state += residual __lowerCamelCase : Optional[int] =self.activation(__lowercase ) return hidden_state class SCREAMING_SNAKE_CASE_ ( tf.keras.layers.Layer ): """simple docstring""" def __init__( self :Union[str, Any] , __lowercase :RegNetConfig , __lowercase :int , __lowercase :int , __lowercase :int = 1 , **__lowercase :List[str] ): super().__init__(**__lowercase ) __lowerCamelCase : Optional[Any] =in_channels != out_channels or stride != 1 __lowerCamelCase : Optional[Any] =max(1 , out_channels // config.groups_width ) __lowerCamelCase : Dict =( TFRegNetShortCut(__lowercase , stride=__lowercase , name='''shortcut''' ) if should_apply_shortcut else tf.keras.layers.Activation('''linear''' , name='''shortcut''' ) ) __lowerCamelCase : Union[str, Any] =[ TFRegNetConvLayer(__lowercase , kernel_size=1 , activation=config.hidden_act , name='''layer.0''' ), TFRegNetConvLayer( __lowercase , stride=__lowercase , groups=__lowercase , activation=config.hidden_act , name='''layer.1''' ), TFRegNetSELayer(__lowercase , reduced_channels=int(round(in_channels / 4 ) ) , name='''layer.2''' ), TFRegNetConvLayer(__lowercase , kernel_size=1 , activation=__lowercase , name='''layer.3''' ), ] __lowerCamelCase : Tuple =ACTaFN[config.hidden_act] def __lowercase ( self :Tuple , __lowercase :Tuple ): __lowerCamelCase : List[Any] =hidden_state for layer_module in self.layers: __lowerCamelCase : int =layer_module(__lowercase ) __lowerCamelCase : List[str] =self.shortcut(__lowercase ) hidden_state += residual __lowerCamelCase : List[str] =self.activation(__lowercase ) return hidden_state class SCREAMING_SNAKE_CASE_ ( tf.keras.layers.Layer ): """simple docstring""" def __init__( self :int , __lowercase :RegNetConfig , __lowercase :int , __lowercase :int , __lowercase :int = 2 , __lowercase :int = 2 , **__lowercase :Union[str, Any] ): super().__init__(**__lowercase ) __lowerCamelCase : List[str] =TFRegNetXLayer if config.layer_type == '''x''' else TFRegNetYLayer __lowerCamelCase : List[Any] =[ # downsampling is done in the first layer with stride of 2 layer(__lowercase , __lowercase , __lowercase , stride=__lowercase , name='''layers.0''' ), *[layer(__lowercase , __lowercase , __lowercase , name=f'layers.{i+1}' ) for i in range(depth - 1 )], ] def __lowercase ( self :int , __lowercase :List[str] ): for layer_module in self.layers: __lowerCamelCase : int =layer_module(__lowercase ) return hidden_state class SCREAMING_SNAKE_CASE_ ( tf.keras.layers.Layer ): """simple docstring""" def __init__( self :List[Any] , __lowercase :RegNetConfig , **__lowercase :List[str] ): super().__init__(**__lowercase ) __lowerCamelCase : Optional[int] =[] # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( TFRegNetStage( __lowercase , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , name='''stages.0''' , ) ) __lowerCamelCase : Any =zip(config.hidden_sizes , config.hidden_sizes[1:] ) for i, ((in_channels, out_channels), depth) in enumerate(zip(__lowercase , config.depths[1:] ) ): self.stages.append(TFRegNetStage(__lowercase , __lowercase , __lowercase , depth=__lowercase , name=f'stages.{i+1}' ) ) def __lowercase ( self :str , __lowercase :tf.Tensor , __lowercase :bool = False , __lowercase :bool = True ): __lowerCamelCase : Optional[Any] =() if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: __lowerCamelCase : Dict =hidden_states + (hidden_state,) __lowerCamelCase : List[Any] =stage_module(__lowercase ) if output_hidden_states: __lowerCamelCase : Union[str, Any] =hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return TFBaseModelOutputWithNoAttention(last_hidden_state=__lowercase , hidden_states=__lowercase ) @keras_serializable class SCREAMING_SNAKE_CASE_ ( tf.keras.layers.Layer ): """simple docstring""" __snake_case : Optional[int] = RegNetConfig def __init__( self :List[Any] , __lowercase :Dict , **__lowercase :Union[str, Any] ): super().__init__(**__lowercase ) __lowerCamelCase : int =config __lowerCamelCase : List[str] =TFRegNetEmbeddings(__lowercase , name='''embedder''' ) __lowerCamelCase : List[str] =TFRegNetEncoder(__lowercase , name='''encoder''' ) __lowerCamelCase : List[Any] =tf.keras.layers.GlobalAveragePoolingaD(keepdims=__lowercase , name='''pooler''' ) @unpack_inputs def __lowercase ( self :List[Any] , __lowercase :tf.Tensor , __lowercase :Optional[bool] = None , __lowercase :Optional[bool] = None , __lowercase :bool = False , ): __lowerCamelCase : Union[str, Any] =( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __lowerCamelCase : Tuple =return_dict if return_dict is not None else self.config.use_return_dict __lowerCamelCase : Tuple =self.embedder(__lowercase , training=__lowercase ) __lowerCamelCase : Optional[Any] =self.encoder( __lowercase , output_hidden_states=__lowercase , return_dict=__lowercase , training=__lowercase ) __lowerCamelCase : str =encoder_outputs[0] __lowerCamelCase : Tuple =self.pooler(__lowercase ) # Change to NCHW output format have uniformity in the modules __lowerCamelCase : int =tf.transpose(__lowercase , perm=(0, 3, 1, 2) ) __lowerCamelCase : Any =tf.transpose(__lowercase , perm=(0, 3, 1, 2) ) # Change the other hidden state outputs to NCHW as well if output_hidden_states: __lowerCamelCase : str =tuple([tf.transpose(__lowercase , perm=(0, 3, 1, 2) ) for h in encoder_outputs[1]] ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=__lowercase , pooler_output=__lowercase , hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states , ) class SCREAMING_SNAKE_CASE_ ( snake_case__ ): """simple docstring""" __snake_case : Optional[int] = RegNetConfig __snake_case : int = """regnet""" __snake_case : int = """pixel_values""" @property def __lowercase ( self :List[str] ): return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 224, 224) , dtype=tf.floataa )} _UpperCamelCase = r'\n Parameters:\n This model is a Tensorflow\n [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a\n regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and\n behavior.\n config ([`RegNetConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.\n' _UpperCamelCase = r'\n Args:\n pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`ConveNextImageProcessor.__call__`] for details.\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n' @add_start_docstrings( """The bare RegNet model outputting raw features without any specific head on top.""" , snake_case__ , ) class SCREAMING_SNAKE_CASE_ ( snake_case__ ): """simple docstring""" def __init__( self :Union[str, Any] , __lowercase :RegNetConfig , *__lowercase :List[str] , **__lowercase :int ): super().__init__(__lowercase , *__lowercase , **__lowercase ) __lowerCamelCase : Tuple =TFRegNetMainLayer(__lowercase , name='''regnet''' ) @unpack_inputs @add_start_docstrings_to_model_forward(__lowercase ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=__lowercase , config_class=_CONFIG_FOR_DOC , modality='''vision''' , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def __lowercase ( self :Optional[Any] , __lowercase :tf.Tensor , __lowercase :Optional[bool] = None , __lowercase :Optional[bool] = None , __lowercase :Optional[int]=False , ): __lowerCamelCase : List[Any] =( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __lowerCamelCase : Optional[int] =return_dict if return_dict is not None else self.config.use_return_dict __lowerCamelCase : Dict =self.regnet( pixel_values=__lowercase , output_hidden_states=__lowercase , return_dict=__lowercase , training=__lowercase , ) if not return_dict: return (outputs[0],) + outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=outputs.last_hidden_state , pooler_output=outputs.pooler_output , hidden_states=outputs.hidden_states , ) @add_start_docstrings( """ RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet. """ , snake_case__ , ) class SCREAMING_SNAKE_CASE_ ( snake_case__ , snake_case__ ): """simple docstring""" def __init__( self :Union[str, Any] , __lowercase :RegNetConfig , *__lowercase :List[Any] , **__lowercase :Dict ): super().__init__(__lowercase , *__lowercase , **__lowercase ) __lowerCamelCase : Optional[int] =config.num_labels __lowerCamelCase : Optional[int] =TFRegNetMainLayer(__lowercase , name='''regnet''' ) # classification head __lowerCamelCase : Union[str, Any] =[ tf.keras.layers.Flatten(), tf.keras.layers.Dense(config.num_labels , name='''classifier.1''' ) if config.num_labels > 0 else tf.identity, ] @unpack_inputs @add_start_docstrings_to_model_forward(__lowercase ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=__lowercase , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def __lowercase ( self :List[Any] , __lowercase :tf.Tensor = None , __lowercase :tf.Tensor = None , __lowercase :bool = None , __lowercase :bool = None , __lowercase :int=False , ): __lowerCamelCase : str =( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __lowerCamelCase : Optional[int] =return_dict if return_dict is not None else self.config.use_return_dict __lowerCamelCase : str =self.regnet( __lowercase , output_hidden_states=__lowercase , return_dict=__lowercase , training=__lowercase ) __lowerCamelCase : Any =outputs.pooler_output if return_dict else outputs[1] __lowerCamelCase : List[str] =self.classifier[0](__lowercase ) __lowerCamelCase : str =self.classifier[1](__lowercase ) __lowerCamelCase : str =None if labels is None else self.hf_compute_loss(labels=__lowercase , logits=__lowercase ) if not return_dict: __lowerCamelCase : Optional[int] =(logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return TFSequenceClassifierOutput(loss=__lowercase , logits=__lowercase , hidden_states=outputs.hidden_states )
363
0
'''simple docstring''' # Lint as: python3 import sys from collections.abc import Mapping from typing import TYPE_CHECKING import numpy as np import pyarrow as pa from .. import config from ..utils.py_utils import map_nested from .formatting import TensorFormatter if TYPE_CHECKING: import torch class a__( TensorFormatter[Mapping, '''torch.Tensor''', Mapping] ): '''simple docstring''' def __init__( self , __lowerCAmelCase=None , **__lowerCAmelCase): """simple docstring""" super().__init__(features=__lowerCAmelCase) lowerCAmelCase = torch_tensor_kwargs import torch # noqa import torch at initialization def a_ ( self , __lowerCAmelCase): """simple docstring""" import torch if isinstance(__lowerCAmelCase , __lowerCAmelCase) and column: if all( isinstance(__lowerCAmelCase , torch.Tensor) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column): return torch.stack(__lowerCAmelCase) return column def a_ ( self , __lowerCAmelCase): """simple docstring""" import torch if isinstance(__lowerCAmelCase , (str, bytes, type(__lowerCAmelCase))): return value elif isinstance(__lowerCAmelCase , (np.character, np.ndarray)) and np.issubdtype(value.dtype , np.character): return value.tolist() lowerCAmelCase = {} if isinstance(__lowerCAmelCase , (np.number, np.ndarray)) and np.issubdtype(value.dtype , np.integer): lowerCAmelCase = {"""dtype""": torch.intaa} elif isinstance(__lowerCAmelCase , (np.number, np.ndarray)) and np.issubdtype(value.dtype , np.floating): lowerCAmelCase = {"""dtype""": torch.floataa} elif config.PIL_AVAILABLE and "PIL" in sys.modules: import PIL.Image if isinstance(__lowerCAmelCase , PIL.Image.Image): lowerCAmelCase = np.asarray(__lowerCAmelCase) return torch.tensor(__lowerCAmelCase , **{**default_dtype, **self.torch_tensor_kwargs}) def a_ ( self , __lowerCAmelCase): """simple docstring""" import torch # support for torch, tf, jax etc. if hasattr(__lowerCAmelCase , """__array__""") and not isinstance(__lowerCAmelCase , torch.Tensor): lowerCAmelCase = data_struct.__array__() # support for nested types like struct of list of struct if isinstance(__lowerCAmelCase , np.ndarray): if data_struct.dtype == object: # torch tensors cannot be instantied from an array of objects return self._consolidate([self.recursive_tensorize(__lowerCAmelCase) for substruct in data_struct]) elif isinstance(__lowerCAmelCase , (list, tuple)): return self._consolidate([self.recursive_tensorize(__lowerCAmelCase) for substruct in data_struct]) return self._tensorize(__lowerCAmelCase) def a_ ( self , __lowerCAmelCase): """simple docstring""" return map_nested(self._recursive_tensorize , __lowerCAmelCase , map_list=__lowerCAmelCase) def a_ ( self , __lowerCAmelCase): """simple docstring""" lowerCAmelCase = self.numpy_arrow_extractor().extract_row(__lowerCAmelCase) lowerCAmelCase = self.python_features_decoder.decode_row(__lowerCAmelCase) return self.recursive_tensorize(__lowerCAmelCase) def a_ ( self , __lowerCAmelCase): """simple docstring""" lowerCAmelCase = self.numpy_arrow_extractor().extract_column(__lowerCAmelCase) lowerCAmelCase = self.python_features_decoder.decode_column(__lowerCAmelCase , pa_table.column_names[0]) lowerCAmelCase = self.recursive_tensorize(__lowerCAmelCase) lowerCAmelCase = self._consolidate(__lowerCAmelCase) return column def a_ ( self , __lowerCAmelCase): """simple docstring""" lowerCAmelCase = self.numpy_arrow_extractor().extract_batch(__lowerCAmelCase) lowerCAmelCase = self.python_features_decoder.decode_batch(__lowerCAmelCase) lowerCAmelCase = self.recursive_tensorize(__lowerCAmelCase) for column_name in batch: lowerCAmelCase = self._consolidate(batch[column_name]) return batch
370
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import XLMRobertaTokenizerFast from diffusers import DDIMScheduler, KandinskyImgaImgPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class a__( lowerCAmelCase__ , unittest.TestCase ): '''simple docstring''' UpperCAmelCase_ : List[str] = KandinskyImgaImgPipeline UpperCAmelCase_ : Union[str, Any] = ['''prompt''', '''image_embeds''', '''negative_image_embeds''', '''image'''] UpperCAmelCase_ : List[str] = [ '''prompt''', '''negative_prompt''', '''image_embeds''', '''negative_image_embeds''', '''image''', ] UpperCAmelCase_ : Dict = [ '''generator''', '''height''', '''width''', '''strength''', '''guidance_scale''', '''negative_prompt''', '''num_inference_steps''', '''return_dict''', '''guidance_scale''', '''num_images_per_prompt''', '''output_type''', '''return_dict''', ] UpperCAmelCase_ : str = False @property def a_ ( self): """simple docstring""" return 32 @property def a_ ( self): """simple docstring""" return 32 @property def a_ ( self): """simple docstring""" return self.time_input_dim @property def a_ ( self): """simple docstring""" return self.time_input_dim * 4 @property def a_ ( self): """simple docstring""" return 100 @property def a_ ( self): """simple docstring""" lowerCAmelCase = XLMRobertaTokenizerFast.from_pretrained("""YiYiXu/tiny-random-mclip-base""") return tokenizer @property def a_ ( self): """simple docstring""" torch.manual_seed(0) lowerCAmelCase = MCLIPConfig( numDims=self.cross_attention_dim , transformerDimensions=self.text_embedder_hidden_size , hidden_size=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=1005 , ) lowerCAmelCase = MultilingualCLIP(__lowerCAmelCase) lowerCAmelCase = text_encoder.eval() return text_encoder @property def a_ ( self): """simple docstring""" torch.manual_seed(0) lowerCAmelCase = { """in_channels""": 4, # Out channels is double in channels because predicts mean and variance """out_channels""": 8, """addition_embed_type""": """text_image""", """down_block_types""": ("""ResnetDownsampleBlock2D""", """SimpleCrossAttnDownBlock2D"""), """up_block_types""": ("""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""), """mid_block_type""": """UNetMidBlock2DSimpleCrossAttn""", """block_out_channels""": (self.block_out_channels_a, self.block_out_channels_a * 2), """layers_per_block""": 1, """encoder_hid_dim""": self.text_embedder_hidden_size, """encoder_hid_dim_type""": """text_image_proj""", """cross_attention_dim""": self.cross_attention_dim, """attention_head_dim""": 4, """resnet_time_scale_shift""": """scale_shift""", """class_embed_type""": None, } lowerCAmelCase = UNetaDConditionModel(**__lowerCAmelCase) return model @property def a_ ( self): """simple docstring""" return { "block_out_channels": [32, 64], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def a_ ( self): """simple docstring""" torch.manual_seed(0) lowerCAmelCase = VQModel(**self.dummy_movq_kwargs) return model def a_ ( self): """simple docstring""" lowerCAmelCase = self.dummy_text_encoder lowerCAmelCase = self.dummy_tokenizer lowerCAmelCase = self.dummy_unet lowerCAmelCase = self.dummy_movq lowerCAmelCase = { """num_train_timesteps""": 1000, """beta_schedule""": """linear""", """beta_start""": 0.00085, """beta_end""": 0.012, """clip_sample""": False, """set_alpha_to_one""": False, """steps_offset""": 0, """prediction_type""": """epsilon""", """thresholding""": False, } lowerCAmelCase = DDIMScheduler(**__lowerCAmelCase) lowerCAmelCase = { """text_encoder""": text_encoder, """tokenizer""": tokenizer, """unet""": unet, """scheduler""": scheduler, """movq""": movq, } return components def a_ ( self , __lowerCAmelCase , __lowerCAmelCase=0): """simple docstring""" lowerCAmelCase = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(__lowerCAmelCase)).to(__lowerCAmelCase) lowerCAmelCase = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(seed + 1)).to(__lowerCAmelCase) # create init_image lowerCAmelCase = floats_tensor((1, 3, 64, 64) , rng=random.Random(__lowerCAmelCase)).to(__lowerCAmelCase) lowerCAmelCase = image.cpu().permute(0 , 2 , 3 , 1)[0] lowerCAmelCase = Image.fromarray(np.uinta(__lowerCAmelCase)).convert("""RGB""").resize((256, 256)) if str(__lowerCAmelCase).startswith("""mps"""): lowerCAmelCase = torch.manual_seed(__lowerCAmelCase) else: lowerCAmelCase = torch.Generator(device=__lowerCAmelCase).manual_seed(__lowerCAmelCase) lowerCAmelCase = { """prompt""": """horse""", """image""": init_image, """image_embeds""": image_embeds, """negative_image_embeds""": negative_image_embeds, """generator""": generator, """height""": 64, """width""": 64, """num_inference_steps""": 10, """guidance_scale""": 7.0, """strength""": 0.2, """output_type""": """np""", } return inputs def a_ ( self): """simple docstring""" lowerCAmelCase = """cpu""" lowerCAmelCase = self.get_dummy_components() lowerCAmelCase = self.pipeline_class(**__lowerCAmelCase) lowerCAmelCase = pipe.to(__lowerCAmelCase) pipe.set_progress_bar_config(disable=__lowerCAmelCase) lowerCAmelCase = pipe(**self.get_dummy_inputs(__lowerCAmelCase)) lowerCAmelCase = output.images lowerCAmelCase = pipe( **self.get_dummy_inputs(__lowerCAmelCase) , return_dict=__lowerCAmelCase , )[0] lowerCAmelCase = image[0, -3:, -3:, -1] lowerCAmelCase = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) lowerCAmelCase = np.array( [0.61474943, 0.6073539, 0.43308544, 0.5928269, 0.47493595, 0.46755973, 0.4613838, 0.45368797, 0.50119233]) assert ( np.abs(image_slice.flatten() - expected_slice).max() < 1E-2 ), f" expected_slice {expected_slice}, but got {image_slice.flatten()}" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice).max() < 1E-2 ), f" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}" @slow @require_torch_gpu class a__( unittest.TestCase ): '''simple docstring''' def a_ ( self): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def a_ ( self): """simple docstring""" lowerCAmelCase = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinsky/kandinsky_img2img_frog.npy""") lowerCAmelCase = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinsky/cat.png""") lowerCAmelCase = """A red cartoon frog, 4k""" lowerCAmelCase = KandinskyPriorPipeline.from_pretrained( """kandinsky-community/kandinsky-2-1-prior""" , torch_dtype=torch.floataa) pipe_prior.to(__lowerCAmelCase) lowerCAmelCase = KandinskyImgaImgPipeline.from_pretrained( """kandinsky-community/kandinsky-2-1""" , torch_dtype=torch.floataa) lowerCAmelCase = pipeline.to(__lowerCAmelCase) pipeline.set_progress_bar_config(disable=__lowerCAmelCase) lowerCAmelCase = torch.Generator(device="""cpu""").manual_seed(0) lowerCAmelCase , lowerCAmelCase = pipe_prior( __lowerCAmelCase , generator=__lowerCAmelCase , num_inference_steps=5 , negative_prompt="""""" , ).to_tuple() lowerCAmelCase = pipeline( __lowerCAmelCase , image=__lowerCAmelCase , image_embeds=__lowerCAmelCase , negative_image_embeds=__lowerCAmelCase , generator=__lowerCAmelCase , num_inference_steps=100 , height=768 , width=768 , strength=0.2 , output_type="""np""" , ) lowerCAmelCase = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(__lowerCAmelCase , __lowerCAmelCase)
370
1
from ..utils import DummyObject, requires_backends class _snake_case ( metaclass=A__ ): _lowercase : List[str] = ['''torch''', '''torchsde'''] def __init__( self , *a , **a) -> Optional[int]: requires_backends(self , ['torch', 'torchsde']) @classmethod def SCREAMING_SNAKE_CASE__ ( cls , *a , **a) -> List[str]: requires_backends(cls , ['torch', 'torchsde']) @classmethod def SCREAMING_SNAKE_CASE__ ( cls , *a , **a) -> List[Any]: requires_backends(cls , ['torch', 'torchsde'])
444
import os # Precomputes a list of the 100 first triangular numbers a_ : str = [int(0.5 * n * (n + 1)) for n in range(1, 1_01)] def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = os.path.dirname(os.path.realpath(_UpperCAmelCase)) SCREAMING_SNAKE_CASE = os.path.join(_UpperCAmelCase , 'words.txt') SCREAMING_SNAKE_CASE = '' with open(_UpperCAmelCase) as f: SCREAMING_SNAKE_CASE = f.readline() SCREAMING_SNAKE_CASE = [word.strip('"') for word in words.strip('\r\n').split(',')] SCREAMING_SNAKE_CASE = [ word for word in [sum(ord(_UpperCAmelCase) - 64 for x in word) for word in words] if word in TRIANGULAR_NUMBERS ] return len(_UpperCAmelCase) if __name__ == "__main__": print(solution())
444
1
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ....tokenization_utils_fast import PreTrainedTokenizerFast from ....utils import logging from .tokenization_retribert import RetriBertTokenizer __A =logging.get_logger(__name__) __A ={'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} __A ={ '''vocab_file''': { '''yjernite/retribert-base-uncased''': ( '''https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''yjernite/retribert-base-uncased''': ( '''https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/tokenizer.json''' ), }, } __A ={ '''yjernite/retribert-base-uncased''': 5_1_2, } __A ={ '''yjernite/retribert-base-uncased''': {'''do_lower_case''': True}, } class _SCREAMING_SNAKE_CASE ( snake_case_ ): lowerCAmelCase__ = VOCAB_FILES_NAMES lowerCAmelCase__ = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase__ = PRETRAINED_INIT_CONFIGURATION lowerCAmelCase__ = RetriBertTokenizer lowerCAmelCase__ = ['input_ids', 'attention_mask'] def __init__( self , lowercase=None , lowercase=None , lowercase=True , lowercase="[UNK]" , lowercase="[SEP]" , lowercase="[PAD]" , lowercase="[CLS]" , lowercase="[MASK]" , lowercase=True , lowercase=None , **lowercase , ) -> str: super().__init__( lowercase , tokenizer_file=lowercase , do_lower_case=lowercase , unk_token=lowercase , sep_token=lowercase , pad_token=lowercase , cls_token=lowercase , mask_token=lowercase , tokenize_chinese_chars=lowercase , strip_accents=lowercase , **lowercase , ) lowerCamelCase_ = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("lowercase" , lowercase ) != do_lower_case or normalizer_state.get("strip_accents" , lowercase ) != strip_accents or normalizer_state.get("handle_chinese_chars" , lowercase ) != tokenize_chinese_chars ): lowerCamelCase_ = getattr(lowercase , normalizer_state.pop("type" ) ) lowerCamelCase_ = do_lower_case lowerCamelCase_ = strip_accents lowerCamelCase_ = tokenize_chinese_chars lowerCamelCase_ = normalizer_class(**lowercase ) lowerCamelCase_ = do_lower_case def SCREAMING_SNAKE_CASE_( self , lowercase , lowercase=None ) -> Optional[int]: lowerCamelCase_ = [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 , lowercase , lowercase = None ) -> List[int]: lowerCamelCase_ = [self.sep_token_id] lowerCamelCase_ = [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 , lowercase , lowercase = None ) -> Tuple[str]: lowerCamelCase_ = self._tokenizer.model.save(lowercase , name=lowercase ) return tuple(lowercase )
463
import inspect import unittest from transformers import ConvNextConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ConvNextBackbone, ConvNextForImageClassification, ConvNextModel from transformers.models.convnext.modeling_convnext import CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class _SCREAMING_SNAKE_CASE : def __init__( self , lowercase , lowercase=13 , lowercase=32 , lowercase=3 , lowercase=4 , lowercase=[10, 20, 30, 40] , lowercase=[2, 2, 3, 2] , lowercase=True , lowercase=True , lowercase=37 , lowercase="gelu" , lowercase=10 , lowercase=0.0_2 , lowercase=["stage2", "stage3", "stage4"] , lowercase=[2, 3, 4] , lowercase=None , ) -> Any: lowerCamelCase_ = parent lowerCamelCase_ = batch_size lowerCamelCase_ = image_size lowerCamelCase_ = num_channels lowerCamelCase_ = num_stages lowerCamelCase_ = hidden_sizes lowerCamelCase_ = depths lowerCamelCase_ = is_training lowerCamelCase_ = use_labels lowerCamelCase_ = intermediate_size lowerCamelCase_ = hidden_act lowerCamelCase_ = num_labels lowerCamelCase_ = initializer_range lowerCamelCase_ = out_features lowerCamelCase_ = out_indices lowerCamelCase_ = scope def SCREAMING_SNAKE_CASE_( self ) -> Tuple: lowerCamelCase_ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCamelCase_ = None if self.use_labels: lowerCamelCase_ = ids_tensor([self.batch_size] , self.num_labels ) lowerCamelCase_ = self.get_config() return config, pixel_values, labels def SCREAMING_SNAKE_CASE_( self ) -> Dict: return ConvNextConfig( num_channels=self.num_channels , hidden_sizes=self.hidden_sizes , depths=self.depths , num_stages=self.num_stages , hidden_act=self.hidden_act , is_decoder=lowercase , initializer_range=self.initializer_range , out_features=self.out_features , out_indices=self.out_indices , num_labels=self.num_labels , ) def SCREAMING_SNAKE_CASE_( self , lowercase , lowercase , lowercase ) -> Tuple: lowerCamelCase_ = ConvNextModel(config=lowercase ) model.to(lowercase ) model.eval() lowerCamelCase_ = model(lowercase ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def SCREAMING_SNAKE_CASE_( self , lowercase , lowercase , lowercase ) -> str: lowerCamelCase_ = ConvNextForImageClassification(lowercase ) model.to(lowercase ) model.eval() lowerCamelCase_ = model(lowercase , labels=lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE_( self , lowercase , lowercase , lowercase ) -> str: lowerCamelCase_ = ConvNextBackbone(config=lowercase ) model.to(lowercase ) model.eval() lowerCamelCase_ = model(lowercase ) # verify hidden states self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[1], 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , config.hidden_sizes[1:] ) # verify backbone works with out_features=None lowerCamelCase_ = None lowerCamelCase_ = ConvNextBackbone(config=lowercase ) model.to(lowercase ) model.eval() lowerCamelCase_ = model(lowercase ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def SCREAMING_SNAKE_CASE_( self ) -> Optional[Any]: lowerCamelCase_ = self.prepare_config_and_inputs() lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ = config_and_inputs lowerCamelCase_ = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class _SCREAMING_SNAKE_CASE ( snake_case_ , snake_case_ , unittest.TestCase ): lowerCAmelCase__ = ( ( ConvNextModel, ConvNextForImageClassification, ConvNextBackbone, ) if is_torch_available() else () ) lowerCAmelCase__ = ( {'feature-extraction': ConvNextModel, 'image-classification': ConvNextForImageClassification} if is_torch_available() else {} ) lowerCAmelCase__ = True lowerCAmelCase__ = False lowerCAmelCase__ = False lowerCAmelCase__ = False lowerCAmelCase__ = False def SCREAMING_SNAKE_CASE_( self ) -> Optional[int]: lowerCamelCase_ = ConvNextModelTester(self ) lowerCamelCase_ = ConfigTester(self , config_class=lowercase , has_text_modality=lowercase , hidden_size=37 ) def SCREAMING_SNAKE_CASE_( self ) -> Union[str, Any]: self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def SCREAMING_SNAKE_CASE_( self ) -> Optional[Any]: return @unittest.skip(reason="ConvNext does not use inputs_embeds" ) def SCREAMING_SNAKE_CASE_( self ) -> List[str]: pass @unittest.skip(reason="ConvNext does not support input and output embeddings" ) def SCREAMING_SNAKE_CASE_( self ) -> List[Any]: pass @unittest.skip(reason="ConvNext does not use feedforward chunking" ) def SCREAMING_SNAKE_CASE_( self ) -> Tuple: pass def SCREAMING_SNAKE_CASE_( self ) -> Union[str, Any]: lowerCamelCase_ , lowerCamelCase_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase_ = model_class(lowercase ) lowerCamelCase_ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCamelCase_ = [*signature.parameters.keys()] lowerCamelCase_ = ["pixel_values"] self.assertListEqual(arg_names[:1] , lowercase ) def SCREAMING_SNAKE_CASE_( self ) -> Dict: lowerCamelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase ) def SCREAMING_SNAKE_CASE_( self ) -> Dict: lowerCamelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*lowercase ) def SCREAMING_SNAKE_CASE_( self ) -> Optional[Any]: def check_hidden_states_output(lowercase , lowercase , lowercase ): lowerCamelCase_ = model_class(lowercase ) model.to(lowercase ) model.eval() with torch.no_grad(): lowerCamelCase_ = model(**self._prepare_for_class(lowercase , lowercase ) ) lowerCamelCase_ = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states lowerCamelCase_ = self.model_tester.num_stages self.assertEqual(len(lowercase ) , expected_num_stages + 1 ) # ConvNext's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) lowerCamelCase_ , lowerCamelCase_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase_ = True check_hidden_states_output(lowercase , lowercase , lowercase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCamelCase_ = True check_hidden_states_output(lowercase , lowercase , lowercase ) def SCREAMING_SNAKE_CASE_( self ) -> str: lowerCamelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowercase ) @slow def SCREAMING_SNAKE_CASE_( self ) -> Dict: for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCamelCase_ = ConvNextModel.from_pretrained(lowercase ) self.assertIsNotNone(lowercase ) def lowerCamelCase_ ( ): lowerCamelCase_ = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): @cached_property def SCREAMING_SNAKE_CASE_( self ) -> List[str]: return AutoImageProcessor.from_pretrained("facebook/convnext-tiny-224" ) if is_vision_available() else None @slow def SCREAMING_SNAKE_CASE_( self ) -> List[Any]: lowerCamelCase_ = ConvNextForImageClassification.from_pretrained("facebook/convnext-tiny-224" ).to(lowercase ) lowerCamelCase_ = self.default_image_processor lowerCamelCase_ = prepare_img() lowerCamelCase_ = image_processor(images=lowercase , return_tensors="pt" ).to(lowercase ) # forward pass with torch.no_grad(): lowerCamelCase_ = model(**lowercase ) # verify the logits lowerCamelCase_ = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , lowercase ) lowerCamelCase_ = torch.tensor([-0.0_2_6_0, -0.4_7_3_9, 0.1_9_1_1] ).to(lowercase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowercase , atol=1e-4 ) ) @require_torch class _SCREAMING_SNAKE_CASE ( unittest.TestCase , snake_case_ ): lowerCAmelCase__ = (ConvNextBackbone,) if is_torch_available() else () lowerCAmelCase__ = ConvNextConfig lowerCAmelCase__ = False def SCREAMING_SNAKE_CASE_( self ) -> List[Any]: lowerCamelCase_ = ConvNextModelTester(self )
463
1
import gc import unittest import numpy as np import torch from torch.backends.cuda import sdp_kernel from diffusers import ( CMStochasticIterativeScheduler, ConsistencyModelPipeline, UNetaDModel, ) from diffusers.utils import randn_tensor, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_a, require_torch_gpu from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class __SCREAMING_SNAKE_CASE ( lowercase__ , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE_ = ConsistencyModelPipeline SCREAMING_SNAKE_CASE_ = UNCONDITIONAL_IMAGE_GENERATION_PARAMS SCREAMING_SNAKE_CASE_ = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS # Override required_optional_params to remove num_images_per_prompt SCREAMING_SNAKE_CASE_ = frozenset( [ 'num_inference_steps', 'generator', 'latents', 'output_type', 'return_dict', 'callback', 'callback_steps', ] ) @property def __lowerCamelCase( self ): """simple docstring""" _snake_case : Dict = UNetaDModel.from_pretrained( """diffusers/consistency-models-test""" , subfolder="""test_unet""" , ) return unet @property def __lowerCamelCase( self ): """simple docstring""" _snake_case : Union[str, Any] = UNetaDModel.from_pretrained( """diffusers/consistency-models-test""" , subfolder="""test_unet_class_cond""" , ) return unet def __lowerCamelCase( self , SCREAMING_SNAKE_CASE__=False ): """simple docstring""" if class_cond: _snake_case : Tuple = self.dummy_cond_unet else: _snake_case : Dict = self.dummy_uncond_unet # Default to CM multistep sampler _snake_case : Optional[Any] = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.002 , sigma_max=80.0 , ) _snake_case : List[Any] = { 'unet': unet, 'scheduler': scheduler, } return components def __lowerCamelCase( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=0 ): """simple docstring""" if str(SCREAMING_SNAKE_CASE__ ).startswith("""mps""" ): _snake_case : List[str] = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) else: _snake_case : str = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ ) _snake_case : str = { 'batch_size': 1, 'num_inference_steps': None, 'timesteps': [22, 0], 'generator': generator, 'output_type': 'np', } return inputs def __lowerCamelCase( self ): """simple docstring""" _snake_case : Any = 'cpu' # ensure determinism for the device-dependent torch.Generator _snake_case : Optional[Any] = self.get_dummy_components() _snake_case : List[Any] = ConsistencyModelPipeline(**SCREAMING_SNAKE_CASE__ ) _snake_case : Tuple = pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) _snake_case : str = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) _snake_case : str = pipe(**SCREAMING_SNAKE_CASE__ ).images assert image.shape == (1, 32, 32, 3) _snake_case : str = image[0, -3:, -3:, -1] _snake_case : Tuple = np.array([0.3572, 0.6273, 0.4031, 0.3961, 0.4321, 0.5730, 0.5266, 0.4780, 0.5004] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowerCamelCase( self ): """simple docstring""" _snake_case : int = 'cpu' # ensure determinism for the device-dependent torch.Generator _snake_case : Tuple = self.get_dummy_components(class_cond=SCREAMING_SNAKE_CASE__ ) _snake_case : Union[str, Any] = ConsistencyModelPipeline(**SCREAMING_SNAKE_CASE__ ) _snake_case : Tuple = pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) _snake_case : List[Any] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) _snake_case : int = 0 _snake_case : Union[str, Any] = pipe(**SCREAMING_SNAKE_CASE__ ).images assert image.shape == (1, 32, 32, 3) _snake_case : Tuple = image[0, -3:, -3:, -1] _snake_case : str = np.array([0.3572, 0.6273, 0.4031, 0.3961, 0.4321, 0.5730, 0.5266, 0.4780, 0.5004] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowerCamelCase( self ): """simple docstring""" _snake_case : Tuple = 'cpu' # ensure determinism for the device-dependent torch.Generator _snake_case : Union[str, Any] = self.get_dummy_components() _snake_case : Tuple = ConsistencyModelPipeline(**SCREAMING_SNAKE_CASE__ ) _snake_case : Dict = pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) _snake_case : Union[str, Any] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) _snake_case : Optional[Any] = 1 _snake_case : Dict = None _snake_case : List[Any] = pipe(**SCREAMING_SNAKE_CASE__ ).images assert image.shape == (1, 32, 32, 3) _snake_case : Tuple = image[0, -3:, -3:, -1] _snake_case : Optional[Any] = np.array([0.5004, 0.5004, 0.4994, 0.5008, 0.4976, 0.5018, 0.4990, 0.4982, 0.4987] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowerCamelCase( self ): """simple docstring""" _snake_case : Dict = 'cpu' # ensure determinism for the device-dependent torch.Generator _snake_case : Optional[int] = self.get_dummy_components(class_cond=SCREAMING_SNAKE_CASE__ ) _snake_case : List[Any] = ConsistencyModelPipeline(**SCREAMING_SNAKE_CASE__ ) _snake_case : Optional[Any] = pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) _snake_case : Tuple = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) _snake_case : Dict = 1 _snake_case : Tuple = None _snake_case : Optional[Any] = 0 _snake_case : str = pipe(**SCREAMING_SNAKE_CASE__ ).images assert image.shape == (1, 32, 32, 3) _snake_case : Union[str, Any] = image[0, -3:, -3:, -1] _snake_case : Dict = np.array([0.5004, 0.5004, 0.4994, 0.5008, 0.4976, 0.5018, 0.4990, 0.4982, 0.4987] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 @slow @require_torch_gpu class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): """simple docstring""" def __lowerCamelCase( self ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowerCamelCase( self , SCREAMING_SNAKE_CASE__=0 , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__="cpu" , SCREAMING_SNAKE_CASE__=torch.floataa , SCREAMING_SNAKE_CASE__=(1, 3, 64, 64) ): """simple docstring""" _snake_case : Union[str, Any] = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) _snake_case : List[Any] = { 'num_inference_steps': None, 'timesteps': [22, 0], 'class_labels': 0, 'generator': generator, 'output_type': 'np', } if get_fixed_latents: _snake_case : Optional[int] = self.get_fixed_latents(seed=SCREAMING_SNAKE_CASE__ , device=SCREAMING_SNAKE_CASE__ , dtype=SCREAMING_SNAKE_CASE__ , shape=SCREAMING_SNAKE_CASE__ ) _snake_case : Tuple = latents return inputs def __lowerCamelCase( self , SCREAMING_SNAKE_CASE__=0 , SCREAMING_SNAKE_CASE__="cpu" , SCREAMING_SNAKE_CASE__=torch.floataa , SCREAMING_SNAKE_CASE__=(1, 3, 64, 64) ): """simple docstring""" if type(SCREAMING_SNAKE_CASE__ ) == str: _snake_case : str = torch.device(SCREAMING_SNAKE_CASE__ ) _snake_case : List[str] = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ ) _snake_case : Any = randn_tensor(SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , device=SCREAMING_SNAKE_CASE__ , dtype=SCREAMING_SNAKE_CASE__ ) return latents def __lowerCamelCase( self ): """simple docstring""" _snake_case : int = UNetaDModel.from_pretrained("""diffusers/consistency_models""" , subfolder="""diffusers_cd_imagenet64_l2""" ) _snake_case : List[str] = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.002 , sigma_max=80.0 , ) _snake_case : List[Any] = ConsistencyModelPipeline(unet=SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ ) pipe.to(torch_device=SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) _snake_case : Optional[Any] = self.get_inputs() _snake_case : Dict = pipe(**SCREAMING_SNAKE_CASE__ ).images assert image.shape == (1, 64, 64, 3) _snake_case : List[str] = image[0, -3:, -3:, -1] _snake_case : Union[str, Any] = np.array([0.0888, 0.0881, 0.0666, 0.0479, 0.0292, 0.0195, 0.0201, 0.0163, 0.0254] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2 def __lowerCamelCase( self ): """simple docstring""" _snake_case : Optional[int] = UNetaDModel.from_pretrained("""diffusers/consistency_models""" , subfolder="""diffusers_cd_imagenet64_l2""" ) _snake_case : Any = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.002 , sigma_max=80.0 , ) _snake_case : Optional[int] = ConsistencyModelPipeline(unet=SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ ) pipe.to(torch_device=SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) _snake_case : List[str] = self.get_inputs() _snake_case : Union[str, Any] = 1 _snake_case : List[str] = None _snake_case : List[str] = pipe(**SCREAMING_SNAKE_CASE__ ).images assert image.shape == (1, 64, 64, 3) _snake_case : Optional[int] = image[0, -3:, -3:, -1] _snake_case : Union[str, Any] = np.array([0.0340, 0.0152, 0.0063, 0.0267, 0.0221, 0.0107, 0.0416, 0.0186, 0.0217] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2 @require_torch_a def __lowerCamelCase( self ): """simple docstring""" _snake_case : int = UNetaDModel.from_pretrained("""diffusers/consistency_models""" , subfolder="""diffusers_cd_imagenet64_l2""" ) _snake_case : List[Any] = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.002 , sigma_max=80.0 , ) _snake_case : Tuple = ConsistencyModelPipeline(unet=SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ ) pipe.to(torch_device=SCREAMING_SNAKE_CASE__ , torch_dtype=torch.floataa ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) _snake_case : str = self.get_inputs(get_fixed_latents=SCREAMING_SNAKE_CASE__ , device=SCREAMING_SNAKE_CASE__ ) # Ensure usage of flash attention in torch 2.0 with sdp_kernel(enable_flash=SCREAMING_SNAKE_CASE__ , enable_math=SCREAMING_SNAKE_CASE__ , enable_mem_efficient=SCREAMING_SNAKE_CASE__ ): _snake_case : Dict = pipe(**SCREAMING_SNAKE_CASE__ ).images assert image.shape == (1, 64, 64, 3) _snake_case : str = image[0, -3:, -3:, -1] _snake_case : str = np.array([0.1875, 0.1428, 0.1289, 0.2151, 0.2092, 0.1477, 0.1877, 0.1641, 0.1353] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 @require_torch_a def __lowerCamelCase( self ): """simple docstring""" _snake_case : Optional[Any] = UNetaDModel.from_pretrained("""diffusers/consistency_models""" , subfolder="""diffusers_cd_imagenet64_l2""" ) _snake_case : List[Any] = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.002 , sigma_max=80.0 , ) _snake_case : Dict = ConsistencyModelPipeline(unet=SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ ) pipe.to(torch_device=SCREAMING_SNAKE_CASE__ , torch_dtype=torch.floataa ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) _snake_case : Any = self.get_inputs(get_fixed_latents=SCREAMING_SNAKE_CASE__ , device=SCREAMING_SNAKE_CASE__ ) _snake_case : List[str] = 1 _snake_case : str = None # Ensure usage of flash attention in torch 2.0 with sdp_kernel(enable_flash=SCREAMING_SNAKE_CASE__ , enable_math=SCREAMING_SNAKE_CASE__ , enable_mem_efficient=SCREAMING_SNAKE_CASE__ ): _snake_case : List[str] = pipe(**SCREAMING_SNAKE_CASE__ ).images assert image.shape == (1, 64, 64, 3) _snake_case : Dict = image[0, -3:, -3:, -1] _snake_case : Optional[int] = np.array([0.1663, 0.1948, 0.2275, 0.1680, 0.1204, 0.1245, 0.1858, 0.1338, 0.2095] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3
703
from __future__ import annotations import unittest from transformers import BlenderbotSmallConfig, BlenderbotSmallTokenizer, is_tf_available from transformers.testing_utils import require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel @require_tf class __SCREAMING_SNAKE_CASE : """simple docstring""" SCREAMING_SNAKE_CASE_ = BlenderbotSmallConfig SCREAMING_SNAKE_CASE_ = {} SCREAMING_SNAKE_CASE_ = 'gelu' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=13 , SCREAMING_SNAKE_CASE__=7 , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=99 , SCREAMING_SNAKE_CASE__=32 , SCREAMING_SNAKE_CASE__=2 , SCREAMING_SNAKE_CASE__=4 , SCREAMING_SNAKE_CASE__=37 , SCREAMING_SNAKE_CASE__=0.1 , SCREAMING_SNAKE_CASE__=0.1 , SCREAMING_SNAKE_CASE__=20 , SCREAMING_SNAKE_CASE__=2 , SCREAMING_SNAKE_CASE__=1 , SCREAMING_SNAKE_CASE__=0 , ): """simple docstring""" _snake_case : Any = parent _snake_case : str = batch_size _snake_case : Optional[Any] = seq_length _snake_case : Union[str, Any] = is_training _snake_case : int = use_labels _snake_case : int = vocab_size _snake_case : Tuple = hidden_size _snake_case : Any = num_hidden_layers _snake_case : Optional[int] = num_attention_heads _snake_case : List[str] = intermediate_size _snake_case : int = hidden_dropout_prob _snake_case : str = attention_probs_dropout_prob _snake_case : str = max_position_embeddings _snake_case : Optional[Any] = eos_token_id _snake_case : Dict = pad_token_id _snake_case : Dict = bos_token_id def __lowerCamelCase( self ): """simple docstring""" _snake_case : Optional[Any] = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) _snake_case : Union[str, Any] = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) _snake_case : Tuple = tf.concat([input_ids, eos_tensor] , axis=1 ) _snake_case : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _snake_case : int = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) _snake_case : Dict = prepare_blenderbot_small_inputs_dict(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return config, inputs_dict def __lowerCamelCase( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): """simple docstring""" _snake_case : Dict = TFBlenderbotSmallModel(config=SCREAMING_SNAKE_CASE__ ).get_decoder() _snake_case : Any = inputs_dict["""input_ids"""] _snake_case : Optional[int] = input_ids[:1, :] _snake_case : Any = inputs_dict["""attention_mask"""][:1, :] _snake_case : Dict = inputs_dict["""head_mask"""] _snake_case : Dict = 1 # first forward pass _snake_case : str = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , head_mask=SCREAMING_SNAKE_CASE__ , use_cache=SCREAMING_SNAKE_CASE__ ) _snake_case , _snake_case : Tuple = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids _snake_case : Any = ids_tensor((self.batch_size, 3) , config.vocab_size ) _snake_case : Dict = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and _snake_case : Union[str, Any] = tf.concat([input_ids, next_tokens] , axis=-1 ) _snake_case : int = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) _snake_case : Dict = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ )[0] _snake_case : Dict = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , past_key_values=SCREAMING_SNAKE_CASE__ )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice _snake_case : List[str] = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) _snake_case : List[Any] = output_from_no_past[:, -3:, random_slice_idx] _snake_case : List[str] = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , rtol=1e-3 ) def UpperCAmelCase ( A__ , A__ , A__ , A__=None , A__=None , A__=None , A__=None , A__=None , ) -> Union[str, Any]: if attention_mask is None: _snake_case : str = tf.cast(tf.math.not_equal(A__ , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: _snake_case : Optional[Any] = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: _snake_case : Optional[Any] = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: _snake_case : Optional[Any] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: _snake_case : List[Any] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class __SCREAMING_SNAKE_CASE ( lowercase__ , lowercase__ , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE_ = ( (TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel) if is_tf_available() else () ) SCREAMING_SNAKE_CASE_ = (TFBlenderbotSmallForConditionalGeneration,) if is_tf_available() else () SCREAMING_SNAKE_CASE_ = ( { 'conversational': TFBlenderbotSmallForConditionalGeneration, 'feature-extraction': TFBlenderbotSmallModel, 'summarization': TFBlenderbotSmallForConditionalGeneration, 'text2text-generation': TFBlenderbotSmallForConditionalGeneration, 'translation': TFBlenderbotSmallForConditionalGeneration, } if is_tf_available() else {} ) SCREAMING_SNAKE_CASE_ = True SCREAMING_SNAKE_CASE_ = False SCREAMING_SNAKE_CASE_ = False def __lowerCamelCase( self ): """simple docstring""" _snake_case : int = TFBlenderbotSmallModelTester(self ) _snake_case : List[Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE__ ) def __lowerCamelCase( self ): """simple docstring""" self.config_tester.run_common_tests() def __lowerCamelCase( self ): """simple docstring""" _snake_case : int = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*SCREAMING_SNAKE_CASE__ ) @require_tokenizers @require_tf class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE_ = [ 'Social anxiety\nWow, I am never shy. Do you have anxiety?\nYes. I end up sweating and blushing and feel like ' ' i\'m going to throw up.\nand why is that?' ] SCREAMING_SNAKE_CASE_ = 'facebook/blenderbot_small-90M' @cached_property def __lowerCamelCase( self ): """simple docstring""" return BlenderbotSmallTokenizer.from_pretrained("""facebook/blenderbot-90M""" ) @cached_property def __lowerCamelCase( self ): """simple docstring""" _snake_case : Union[str, Any] = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model @slow def __lowerCamelCase( self ): """simple docstring""" _snake_case : Tuple = self.tokenizer(self.src_text , return_tensors="""tf""" ) _snake_case : List[str] = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 , use_cache=SCREAMING_SNAKE_CASE__ , ) _snake_case : Optional[int] = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=SCREAMING_SNAKE_CASE__ )[0] assert generated_words in ( "i don't know. i just feel like i'm going to throw up. it's not fun.", "i'm not sure. i just feel like i've been feeling like i have to be in a certain place", "i'm not sure. i just feel like i've been in a bad situation.", )
519
0
"""simple docstring""" import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ConvNextConfig, SegformerImageProcessor, UperNetConfig, UperNetForSemanticSegmentation def UpperCAmelCase ( A__: Optional[int] ) -> Dict: __lowerCamelCase : Optional[Any] = 384 if "tiny" in model_name: __lowerCamelCase : int = [3, 3, 9, 3] __lowerCamelCase : int = [96, 192, 384, 768] if "small" in model_name: __lowerCamelCase : Optional[int] = [3, 3, 27, 3] __lowerCamelCase : List[str] = [96, 192, 384, 768] if "base" in model_name: __lowerCamelCase : Dict = [3, 3, 27, 3] __lowerCamelCase : int = [128, 256, 512, 1024] __lowerCamelCase : List[str] = 512 if "large" in model_name: __lowerCamelCase : Optional[Any] = [3, 3, 27, 3] __lowerCamelCase : Tuple = [192, 384, 768, 1536] __lowerCamelCase : Any = 768 if "xlarge" in model_name: __lowerCamelCase : Tuple = [3, 3, 27, 3] __lowerCamelCase : Optional[int] = [256, 512, 1024, 2048] __lowerCamelCase : int = 1024 # set label information __lowerCamelCase : Optional[Any] = 150 __lowerCamelCase : List[Any] = 'huggingface/label-files' __lowerCamelCase : Optional[Any] = 'ade20k-id2label.json' __lowerCamelCase : Dict = json.load(open(hf_hub_download(A__ , A__ , repo_type='dataset' ) , 'r' ) ) __lowerCamelCase : Union[str, Any] = {int(A__ ): v for k, v in idalabel.items()} __lowerCamelCase : Any = {v: k for k, v in idalabel.items()} __lowerCamelCase : Optional[int] = ConvNextConfig( depths=A__ , hidden_sizes=A__ , out_features=['stage1', 'stage2', 'stage3', 'stage4'] ) __lowerCamelCase : Union[str, Any] = UperNetConfig( backbone_config=A__ , auxiliary_in_channels=A__ , num_labels=A__ , idalabel=A__ , labelaid=A__ , ) return config def UpperCAmelCase ( A__: Any ) -> List[Any]: __lowerCamelCase : Any = [] # fmt: off # stem rename_keys.append(('backbone.downsample_layers.0.0.weight', 'backbone.embeddings.patch_embeddings.weight') ) rename_keys.append(('backbone.downsample_layers.0.0.bias', 'backbone.embeddings.patch_embeddings.bias') ) rename_keys.append(('backbone.downsample_layers.0.1.weight', 'backbone.embeddings.layernorm.weight') ) rename_keys.append(('backbone.downsample_layers.0.1.bias', 'backbone.embeddings.layernorm.bias') ) # stages for i in range(len(config.backbone_config.depths ) ): for j in range(config.backbone_config.depths[i] ): rename_keys.append((f'''backbone.stages.{i}.{j}.gamma''', f'''backbone.encoder.stages.{i}.layers.{j}.layer_scale_parameter''') ) rename_keys.append((f'''backbone.stages.{i}.{j}.depthwise_conv.weight''', f'''backbone.encoder.stages.{i}.layers.{j}.dwconv.weight''') ) rename_keys.append((f'''backbone.stages.{i}.{j}.depthwise_conv.bias''', f'''backbone.encoder.stages.{i}.layers.{j}.dwconv.bias''') ) rename_keys.append((f'''backbone.stages.{i}.{j}.norm.weight''', f'''backbone.encoder.stages.{i}.layers.{j}.layernorm.weight''') ) rename_keys.append((f'''backbone.stages.{i}.{j}.norm.bias''', f'''backbone.encoder.stages.{i}.layers.{j}.layernorm.bias''') ) rename_keys.append((f'''backbone.stages.{i}.{j}.pointwise_conv1.weight''', f'''backbone.encoder.stages.{i}.layers.{j}.pwconv1.weight''') ) rename_keys.append((f'''backbone.stages.{i}.{j}.pointwise_conv1.bias''', f'''backbone.encoder.stages.{i}.layers.{j}.pwconv1.bias''') ) rename_keys.append((f'''backbone.stages.{i}.{j}.pointwise_conv2.weight''', f'''backbone.encoder.stages.{i}.layers.{j}.pwconv2.weight''') ) rename_keys.append((f'''backbone.stages.{i}.{j}.pointwise_conv2.bias''', f'''backbone.encoder.stages.{i}.layers.{j}.pwconv2.bias''') ) if i > 0: rename_keys.append((f'''backbone.downsample_layers.{i}.0.weight''', f'''backbone.encoder.stages.{i}.downsampling_layer.0.weight''') ) rename_keys.append((f'''backbone.downsample_layers.{i}.0.bias''', f'''backbone.encoder.stages.{i}.downsampling_layer.0.bias''') ) rename_keys.append((f'''backbone.downsample_layers.{i}.1.weight''', f'''backbone.encoder.stages.{i}.downsampling_layer.1.weight''') ) rename_keys.append((f'''backbone.downsample_layers.{i}.1.bias''', f'''backbone.encoder.stages.{i}.downsampling_layer.1.bias''') ) rename_keys.append((f'''backbone.norm{i}.weight''', f'''backbone.hidden_states_norms.stage{i+1}.weight''') ) rename_keys.append((f'''backbone.norm{i}.bias''', f'''backbone.hidden_states_norms.stage{i+1}.bias''') ) # decode head rename_keys.extend( [ ('decode_head.conv_seg.weight', 'decode_head.classifier.weight'), ('decode_head.conv_seg.bias', 'decode_head.classifier.bias'), ('auxiliary_head.conv_seg.weight', 'auxiliary_head.classifier.weight'), ('auxiliary_head.conv_seg.bias', 'auxiliary_head.classifier.bias'), ] ) # fmt: on return rename_keys def UpperCAmelCase ( A__: Dict , A__: Any , A__: str ) -> str: __lowerCamelCase : Union[str, Any] = dct.pop(A__ ) __lowerCamelCase : str = val def UpperCAmelCase ( A__: Tuple , A__: Optional[Any] , A__: str ) -> List[str]: __lowerCamelCase : Union[str, Any] = { 'upernet-convnext-tiny': 'https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_tiny_fp16_512x512_160k_ade20k/upernet_convnext_tiny_fp16_512x512_160k_ade20k_20220227_124553-cad485de.pth', 'upernet-convnext-small': 'https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_small_fp16_512x512_160k_ade20k/upernet_convnext_small_fp16_512x512_160k_ade20k_20220227_131208-1b1e394f.pth', 'upernet-convnext-base': 'https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_base_fp16_512x512_160k_ade20k/upernet_convnext_base_fp16_512x512_160k_ade20k_20220227_181227-02a24fc6.pth', 'upernet-convnext-large': 'https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_large_fp16_640x640_160k_ade20k/upernet_convnext_large_fp16_640x640_160k_ade20k_20220226_040532-e57aa54d.pth', 'upernet-convnext-xlarge': 'https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_xlarge_fp16_640x640_160k_ade20k/upernet_convnext_xlarge_fp16_640x640_160k_ade20k_20220226_080344-95fc38c2.pth', } __lowerCamelCase : int = model_name_to_url[model_name] __lowerCamelCase : Optional[Any] = torch.hub.load_state_dict_from_url(A__ , map_location='cpu' )['state_dict'] __lowerCamelCase : List[Any] = get_upernet_config(A__ ) __lowerCamelCase : str = UperNetForSemanticSegmentation(A__ ) model.eval() # replace "bn" => "batch_norm" for key in state_dict.copy().keys(): __lowerCamelCase : Dict = state_dict.pop(A__ ) if "bn" in key: __lowerCamelCase : Dict = key.replace('bn' , 'batch_norm' ) __lowerCamelCase : Optional[int] = val # rename keys __lowerCamelCase : str = create_rename_keys(A__ ) for src, dest in rename_keys: rename_key(A__ , A__ , A__ ) model.load_state_dict(A__ ) # verify on image __lowerCamelCase : List[Any] = 'https://huggingface.co/datasets/hf-internal-testing/fixtures_ade20k/resolve/main/ADE_val_00000001.jpg' __lowerCamelCase : Optional[Any] = Image.open(requests.get(A__ , stream=A__ ).raw ).convert('RGB' ) __lowerCamelCase : int = SegformerImageProcessor() __lowerCamelCase : Any = processor(A__ , return_tensors='pt' ).pixel_values with torch.no_grad(): __lowerCamelCase : Any = model(A__ ) if model_name == "upernet-convnext-tiny": __lowerCamelCase : Dict = torch.tensor( [[-8.8_110, -8.8_110, -8.6_521], [-8.8_110, -8.8_110, -8.6_521], [-8.7_746, -8.7_746, -8.6_130]] ) elif model_name == "upernet-convnext-small": __lowerCamelCase : List[str] = torch.tensor( [[-8.8_236, -8.8_236, -8.6_771], [-8.8_236, -8.8_236, -8.6_771], [-8.7_638, -8.7_638, -8.6_240]] ) elif model_name == "upernet-convnext-base": __lowerCamelCase : Tuple = torch.tensor( [[-8.8_558, -8.8_558, -8.6_905], [-8.8_558, -8.8_558, -8.6_905], [-8.7_669, -8.7_669, -8.6_021]] ) elif model_name == "upernet-convnext-large": __lowerCamelCase : str = torch.tensor( [[-8.6_660, -8.6_660, -8.6_210], [-8.6_660, -8.6_660, -8.6_210], [-8.6_310, -8.6_310, -8.5_964]] ) elif model_name == "upernet-convnext-xlarge": __lowerCamelCase : Optional[Any] = torch.tensor( [[-8.4_980, -8.4_980, -8.3_977], [-8.4_980, -8.4_980, -8.3_977], [-8.4_379, -8.4_379, -8.3_412]] ) print('Logits:' , outputs.logits[0, 0, :3, :3] ) assert torch.allclose(outputs.logits[0, 0, :3, :3] , A__ , atol=1E-4 ) print('Looks ok!' ) if pytorch_dump_folder_path is not None: print(f'''Saving model {model_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(A__ ) print(f'''Saving processor to {pytorch_dump_folder_path}''' ) processor.save_pretrained(A__ ) if push_to_hub: print(f'''Pushing model and processor for {model_name} to hub''' ) model.push_to_hub(f'''openmmlab/{model_name}''' ) processor.push_to_hub(f'''openmmlab/{model_name}''' ) if __name__ == "__main__": a_ : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--model_name''', default='''upernet-convnext-tiny''', type=str, choices=[F"""upernet-convnext-{size}""" for size in ['''tiny''', '''small''', '''base''', '''large''', '''xlarge''']], help='''Name of the ConvNext UperNet model you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) parser.add_argument( '''--push_to_hub''', action='''store_true''', help='''Whether or not to push the converted model to the 🤗 hub.''' ) a_ : Optional[Any] = parser.parse_args() convert_upernet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
594
"""simple docstring""" import unittest from transformers import DebertaVaConfig, 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 from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( DebertaVaForMaskedLM, DebertaVaForMultipleChoice, DebertaVaForQuestionAnswering, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaModel, ) from transformers.models.deberta_va.modeling_deberta_va import DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST class __lowercase( lowercase__ ): '''simple docstring''' def __init__( self , __a , __a=13 , __a=7 , __a=True , __a=True , __a=True , __a=True , __a=99 , __a=32 , __a=5 , __a=4 , __a=37 , __a="gelu" , __a=0.1 , __a=0.1 , __a=512 , __a=16 , __a=2 , __a=0.02 , __a=False , __a=True , __a="None" , __a=3 , __a=4 , __a=None , ): __lowerCamelCase : List[str] = parent __lowerCamelCase : Optional[int] = batch_size __lowerCamelCase : Union[str, Any] = seq_length __lowerCamelCase : Optional[int] = is_training __lowerCamelCase : List[str] = use_input_mask __lowerCamelCase : Dict = use_token_type_ids __lowerCamelCase : Dict = use_labels __lowerCamelCase : Union[str, Any] = vocab_size __lowerCamelCase : List[Any] = hidden_size __lowerCamelCase : int = num_hidden_layers __lowerCamelCase : int = num_attention_heads __lowerCamelCase : int = intermediate_size __lowerCamelCase : Dict = hidden_act __lowerCamelCase : Optional[int] = hidden_dropout_prob __lowerCamelCase : Any = attention_probs_dropout_prob __lowerCamelCase : List[str] = max_position_embeddings __lowerCamelCase : Tuple = type_vocab_size __lowerCamelCase : List[Any] = type_sequence_label_size __lowerCamelCase : Optional[Any] = initializer_range __lowerCamelCase : Any = num_labels __lowerCamelCase : Union[str, Any] = num_choices __lowerCamelCase : int = relative_attention __lowerCamelCase : Tuple = position_biased_input __lowerCamelCase : int = pos_att_type __lowerCamelCase : Dict = scope def snake_case_ ( self ): __lowerCamelCase : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __lowerCamelCase : Dict = None if self.use_input_mask: __lowerCamelCase : List[Any] = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) __lowerCamelCase : Dict = None if self.use_token_type_ids: __lowerCamelCase : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __lowerCamelCase : Any = None __lowerCamelCase : Optional[int] = None __lowerCamelCase : Union[str, Any] = None if self.use_labels: __lowerCamelCase : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowerCamelCase : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __lowerCamelCase : Optional[Any] = ids_tensor([self.batch_size] , self.num_choices ) __lowerCamelCase : List[str] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def snake_case_ ( self ): return DebertaVaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , pos_att_type=self.pos_att_type , ) def snake_case_ ( self , __a ): self.parent.assertListEqual(list(result.loss.size() ) , [] ) def snake_case_ ( self , __a , __a , __a , __a , __a , __a , __a ): __lowerCamelCase : Optional[int] = DebertaVaModel(config=__a ) model.to(__a ) model.eval() __lowerCamelCase : int = model(__a , attention_mask=__a , token_type_ids=__a )[0] __lowerCamelCase : Optional[int] = model(__a , token_type_ids=__a )[0] __lowerCamelCase : Optional[Any] = model(__a )[0] self.parent.assertListEqual(list(sequence_output.size() ) , [self.batch_size, self.seq_length, self.hidden_size] ) def snake_case_ ( self , __a , __a , __a , __a , __a , __a , __a ): __lowerCamelCase : List[str] = DebertaVaForMaskedLM(config=__a ) model.to(__a ) model.eval() __lowerCamelCase : List[str] = model(__a , attention_mask=__a , token_type_ids=__a , labels=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def snake_case_ ( self , __a , __a , __a , __a , __a , __a , __a ): __lowerCamelCase : str = self.num_labels __lowerCamelCase : Tuple = DebertaVaForSequenceClassification(__a ) model.to(__a ) model.eval() __lowerCamelCase : Optional[int] = model(__a , attention_mask=__a , token_type_ids=__a , labels=__a ) self.parent.assertListEqual(list(result.logits.size() ) , [self.batch_size, self.num_labels] ) self.check_loss_output(__a ) def snake_case_ ( self , __a , __a , __a , __a , __a , __a , __a ): __lowerCamelCase : Optional[Any] = self.num_labels __lowerCamelCase : List[str] = DebertaVaForTokenClassification(config=__a ) model.to(__a ) model.eval() __lowerCamelCase : List[Any] = model(__a , attention_mask=__a , token_type_ids=__a , labels=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def snake_case_ ( self , __a , __a , __a , __a , __a , __a , __a ): __lowerCamelCase : Optional[int] = DebertaVaForQuestionAnswering(config=__a ) model.to(__a ) model.eval() __lowerCamelCase : List[str] = model( __a , attention_mask=__a , token_type_ids=__a , start_positions=__a , end_positions=__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 snake_case_ ( self , __a , __a , __a , __a , __a , __a , __a ): __lowerCamelCase : Optional[Any] = DebertaVaForMultipleChoice(config=__a ) model.to(__a ) model.eval() __lowerCamelCase : str = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __lowerCamelCase : Dict = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __lowerCamelCase : int = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __lowerCamelCase : str = model( __a , attention_mask=__a , token_type_ids=__a , labels=__a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def snake_case_ ( self ): __lowerCamelCase : Tuple = self.prepare_config_and_inputs() ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : int = config_and_inputs __lowerCamelCase : Tuple = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class __lowercase( lowercase__ , lowercase__ , unittest.TestCase ): '''simple docstring''' __a : str = ( ( DebertaVaModel, DebertaVaForMaskedLM, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaForQuestionAnswering, DebertaVaForMultipleChoice, ) if is_torch_available() else () ) __a : Optional[int] = ( { 'feature-extraction': DebertaVaModel, 'fill-mask': DebertaVaForMaskedLM, 'question-answering': DebertaVaForQuestionAnswering, 'text-classification': DebertaVaForSequenceClassification, 'token-classification': DebertaVaForTokenClassification, 'zero-shot': DebertaVaForSequenceClassification, } if is_torch_available() else {} ) __a : Tuple = True __a : List[Any] = False __a : Any = False __a : Tuple = False __a : Tuple = False def snake_case_ ( self ): __lowerCamelCase : Optional[int] = DebertaVaModelTester(self ) __lowerCamelCase : Union[str, Any] = ConfigTester(self , config_class=__a , hidden_size=37 ) def snake_case_ ( self ): self.config_tester.run_common_tests() def snake_case_ ( self ): __lowerCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_model(*__a ) def snake_case_ ( self ): __lowerCamelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_sequence_classification(*__a ) def snake_case_ ( self ): __lowerCamelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_masked_lm(*__a ) def snake_case_ ( self ): __lowerCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_question_answering(*__a ) def snake_case_ ( self ): __lowerCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_token_classification(*__a ) def snake_case_ ( self ): __lowerCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_multiple_choice(*__a ) @slow def snake_case_ ( self ): for model_name in DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCamelCase : List[str] = DebertaVaModel.from_pretrained(__a ) self.assertIsNotNone(__a ) @require_torch @require_sentencepiece @require_tokenizers class __lowercase( unittest.TestCase ): '''simple docstring''' @unittest.skip(reason='Model not available yet' ) def snake_case_ ( self ): pass @slow def snake_case_ ( self ): __lowerCamelCase : Optional[int] = DebertaVaModel.from_pretrained('microsoft/deberta-v2-xlarge' ) __lowerCamelCase : Dict = torch.tensor([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]] ) __lowerCamelCase : Optional[int] = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __lowerCamelCase : Union[str, Any] = model(__a , attention_mask=__a )[0] # compare the actual values for a slice. __lowerCamelCase : Optional[int] = torch.tensor( [[[0.2_356, 0.1_948, 0.0_369], [-0.1_063, 0.3_586, -0.5_152], [-0.6_399, -0.0_259, -0.2_525]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , __a , atol=1E-4 ) , f'''{output[:, 1:4, 1:4]}''' )
594
1
'''simple docstring''' from dataclasses import dataclass, field from typing import Optional from transformers import AutoConfig, AutoImageProcessor, AutoTokenizer, FlaxVisionEncoderDecoderModel, HfArgumentParser @dataclass class _lowerCAmelCase : """simple docstring""" lowerCamelCase = field( metadata={'''help''': '''The output directory where the model will be written.'''}, ) lowerCamelCase = field( metadata={ '''help''': ( '''The encoder model checkpoint for weights initialization.''' '''Don\'t set if you want to train an encoder model from scratch.''' ) }, ) lowerCamelCase = field( metadata={ '''help''': ( '''The decoder model checkpoint for weights initialization.''' '''Don\'t set if you want to train a decoder model from scratch.''' ) }, ) lowerCamelCase = field( default=__A, metadata={'''help''': '''Pretrained encoder config name or path if not the same as encoder_model_name'''} ) lowerCamelCase = field( default=__A, metadata={'''help''': '''Pretrained decoder config name or path if not the same as decoder_model_name'''} ) def UpperCAmelCase ( ) -> List[str]: """simple docstring""" A_ : Union[str, Any] = HfArgumentParser((ModelArguments,) ) (A_ ) : str = parser.parse_args_into_dataclasses() # Load pretrained model and tokenizer # Use explicit specified encoder config if model_args.encoder_config_name: A_ : List[str] = AutoConfig.from_pretrained(model_args.encoder_config_name ) # Use pretrained encoder model's config else: A_ : str = AutoConfig.from_pretrained(model_args.encoder_model_name_or_path ) # Use explicit specified decoder config if model_args.decoder_config_name: A_ : Optional[Any] = AutoConfig.from_pretrained(model_args.decoder_config_name ) # Use pretrained decoder model's config else: A_ : Union[str, Any] = AutoConfig.from_pretrained(model_args.decoder_model_name_or_path ) # necessary for `from_encoder_decoder_pretrained` when `decoder_config` is passed A_ : str = True A_ : Optional[Any] = True A_ : Union[str, Any] = FlaxVisionEncoderDecoderModel.from_encoder_decoder_pretrained( encoder_pretrained_model_name_or_path=model_args.encoder_model_name_or_path , decoder_pretrained_model_name_or_path=model_args.decoder_model_name_or_path , encoder_config=a_ , decoder_config=a_ , ) # GPT2 only has bos/eos tokens but not decoder_start/pad tokens A_ : Any = decoder_config.decoder_start_token_id A_ : List[Any] = decoder_config.pad_token_id if decoder_start_token_id is None: A_ : Optional[Any] = decoder_config.bos_token_id if pad_token_id is None: A_ : List[Any] = decoder_config.eos_token_id # This is necessary to make Flax's generate() work A_ : Any = decoder_config.eos_token_id A_ : Union[str, Any] = decoder_start_token_id A_ : Any = pad_token_id A_ : Dict = AutoImageProcessor.from_pretrained(model_args.encoder_model_name_or_path ) A_ : Optional[int] = AutoTokenizer.from_pretrained(model_args.decoder_model_name_or_path ) A_ : Optional[int] = tokenizer.convert_ids_to_tokens(model.config.pad_token_id ) model.save_pretrained(model_args.output_dir ) image_processor.save_pretrained(model_args.output_dir ) tokenizer.save_pretrained(model_args.output_dir ) if __name__ == "__main__": main()
706
'''simple docstring''' import importlib.util import json import os import warnings from dataclasses import dataclass, field import torch from ..training_args import TrainingArguments from ..utils import cached_property, is_sagemaker_dp_enabled, logging UpperCamelCase__ : str = logging.get_logger(__name__) def UpperCAmelCase ( ) -> Optional[int]: """simple docstring""" A_ : Optional[Any] = os.getenv("""SM_HP_MP_PARAMETERS""" , """{}""" ) try: # Parse it and check the field "partitions" is included, it is required for model parallel. A_ : Any = json.loads(a_ ) if "partitions" not in smp_options: return False except json.JSONDecodeError: return False # Get the sagemaker specific framework parameters from mpi_options variable. A_ : Dict = os.getenv("""SM_FRAMEWORK_PARAMS""" , """{}""" ) try: # Parse it and check the field "sagemaker_distributed_dataparallel_enabled". A_ : int = json.loads(a_ ) if not mpi_options.get("""sagemaker_mpi_enabled""" , a_ ): return False except json.JSONDecodeError: return False # Lastly, check if the `smdistributed` module is present. return importlib.util.find_spec("""smdistributed""" ) is not None if is_sagemaker_model_parallel_available(): import smdistributed.modelparallel.torch as smp smp.init() @dataclass class _lowerCAmelCase ( __A ): """simple docstring""" lowerCamelCase = field( default='''''', metadata={'''help''': '''Used by the SageMaker launcher to send mp-specific args. Ignored in SageMakerTrainer'''}, ) def UpperCAmelCase_ ( self ) -> Optional[int]: super().__post_init__() warnings.warn( """`SageMakerTrainingArguments` is deprecated and will be removed in v5 of Transformers. You can use """ """`TrainingArguments` instead.""" , _lowerCamelCase , ) @cached_property def UpperCAmelCase_ ( self ) -> "torch.device": logger.info("""PyTorch: setting up devices""" ) if torch.distributed.is_available() and torch.distributed.is_initialized() and self.local_rank == -1: logger.warning( """torch.distributed process group is initialized, but local_rank == -1. """ """In order to use Torch DDP, launch your script with `python -m torch.distributed.launch""" ) if self.no_cuda: A_ : Union[str, Any] = torch.device("""cpu""" ) A_ : Any = 0 elif is_sagemaker_model_parallel_available(): A_ : Dict = smp.local_rank() A_ : Union[str, Any] = torch.device("""cuda""" , _lowerCamelCase ) A_ : int = 1 elif is_sagemaker_dp_enabled(): import smdistributed.dataparallel.torch.torch_smddp # noqa: F401 torch.distributed.init_process_group(backend="""smddp""" , timeout=self.ddp_timeout_delta ) A_ : str = int(os.getenv("""SMDATAPARALLEL_LOCAL_RANK""" ) ) A_ : Any = torch.device("""cuda""" , self.local_rank ) A_ : List[str] = 1 elif self.local_rank == -1: # if n_gpu is > 1 we'll use nn.DataParallel. # If you only want to use a specific subset of GPUs use `CUDA_VISIBLE_DEVICES=0` # Explicitly set CUDA to the first (index 0) CUDA device, otherwise `set_device` will # trigger an error that a device index is missing. Index 0 takes into account the # GPUs available in the environment, so `CUDA_VISIBLE_DEVICES=1,2` with `cuda:0` # will use the first GPU in that env, i.e. GPU#1 A_ : Optional[Any] = torch.device("""cuda:0""" if torch.cuda.is_available() else """cpu""" ) # Sometimes the line in the postinit has not been run before we end up here, so just checking we're not at # the default value. A_ : Optional[int] = torch.cuda.device_count() else: # Here, we'll use torch.distributed. # Initializes the distributed backend which will take care of synchronizing nodes/GPUs if not torch.distributed.is_initialized(): torch.distributed.init_process_group(backend="""nccl""" , timeout=self.ddp_timeout_delta ) A_ : Any = torch.device("""cuda""" , self.local_rank ) A_ : str = 1 if device.type == "cuda": torch.cuda.set_device(_lowerCamelCase ) return device @property def UpperCAmelCase_ ( self ) -> Optional[int]: if is_sagemaker_model_parallel_available(): return smp.dp_size() return super().world_size @property def UpperCAmelCase_ ( self ) -> int: return not is_sagemaker_model_parallel_available() @property def UpperCAmelCase_ ( self ) -> Tuple: return False
385
0
'''simple docstring''' def lowercase_ ( __A : int ) -> bool: """simple docstring""" return number & 1 == 0 if __name__ == "__main__": import doctest doctest.testmod()
94
'''simple docstring''' from __future__ import annotations def lowercase_ ( __A : list[list[int]] ) -> int: """simple docstring""" for i in range(1 , len(matrix[0] ) ): matrix[0][i] += matrix[0][i - 1] # preprocessing the first column for i in range(1 , len(__A ) ): matrix[i][0] += matrix[i - 1][0] # updating the path cost for current position for i in range(1 , len(__A ) ): for j in range(1 , len(matrix[0] ) ): matrix[i][j] += min(matrix[i - 1][j] , matrix[i][j - 1] ) return matrix[-1][-1] if __name__ == "__main__": import doctest doctest.testmod()
94
1
'''simple docstring''' import numpy as np import torch import tqdm from ...models.unet_ad import UNetaDModel from ...pipelines import DiffusionPipeline from ...utils import randn_tensor from ...utils.dummy_pt_objects import DDPMScheduler class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' def __init__( self : Optional[int] , a__ : UNetaDModel , a__ : UNetaDModel , a__ : DDPMScheduler , a__ : Dict , ): super().__init__() UpperCAmelCase = value_function UpperCAmelCase = unet UpperCAmelCase = scheduler UpperCAmelCase = env UpperCAmelCase = env.get_dataset() UpperCAmelCase = {} for key in self.data.keys(): try: UpperCAmelCase = self.data[key].mean() except: # noqa: E722 pass UpperCAmelCase = {} for key in self.data.keys(): try: UpperCAmelCase = self.data[key].std() except: # noqa: E722 pass UpperCAmelCase = env.observation_space.shape[0] UpperCAmelCase = env.action_space.shape[0] def __snake_case ( self : Union[str, Any] , a__ : Tuple , a__ : Optional[int] ): return (x_in - self.means[key]) / self.stds[key] def __snake_case ( self : str , a__ : List[Any] , a__ : Dict ): return x_in * self.stds[key] + self.means[key] def __snake_case ( self : Dict , a__ : int ): if type(a__ ) is dict: return {k: self.to_torch(a__ ) for k, v in x_in.items()} elif torch.is_tensor(a__ ): return x_in.to(self.unet.device ) return torch.tensor(a__ , device=self.unet.device ) def __snake_case ( self : Tuple , a__ : List[str] , a__ : Union[str, Any] , a__ : str ): for key, val in cond.items(): UpperCAmelCase = val.clone() return x_in def __snake_case ( self : Dict , a__ : Optional[Any] , a__ : Optional[Any] , a__ : Tuple , a__ : int ): UpperCAmelCase = x.shape[0] UpperCAmelCase = None for i in tqdm.tqdm(self.scheduler.timesteps ): # create batch of timesteps to pass into model UpperCAmelCase = torch.full((batch_size,) , a__ , device=self.unet.device , dtype=torch.long ) for _ in range(a__ ): with torch.enable_grad(): x.requires_grad_() # permute to match dimension for pre-trained models UpperCAmelCase = self.value_function(x.permute(0 , 2 , 1 ) , a__ ).sample UpperCAmelCase = torch.autograd.grad([y.sum()] , [x] )[0] UpperCAmelCase = self.scheduler._get_variance(a__ ) UpperCAmelCase = torch.exp(0.5 * posterior_variance ) UpperCAmelCase = model_std * grad UpperCAmelCase = 0 UpperCAmelCase = x.detach() UpperCAmelCase = x + scale * grad UpperCAmelCase = self.reset_xa(a__ , a__ , self.action_dim ) UpperCAmelCase = self.unet(x.permute(0 , 2 , 1 ) , a__ ).sample.permute(0 , 2 , 1 ) # TODO: verify deprecation of this kwarg UpperCAmelCase = self.scheduler.step(a__ , a__ , a__ , predict_epsilon=a__ )['''prev_sample'''] # apply conditions to the trajectory (set the initial state) UpperCAmelCase = self.reset_xa(a__ , a__ , self.action_dim ) UpperCAmelCase = self.to_torch(a__ ) return x, y def __call__( self : List[str] , a__ : List[str] , a__ : Dict=64 , a__ : str=32 , a__ : List[str]=2 , a__ : Any=0.1 ): # normalize the observations and create batch dimension UpperCAmelCase = self.normalize(a__ , '''observations''' ) UpperCAmelCase = obs[None].repeat(a__ , axis=0 ) UpperCAmelCase = {0: self.to_torch(a__ )} UpperCAmelCase = (batch_size, planning_horizon, self.state_dim + self.action_dim) # generate initial noise and apply our conditions (to make the trajectories start at current state) UpperCAmelCase = randn_tensor(a__ , device=self.unet.device ) UpperCAmelCase = self.reset_xa(a__ , a__ , self.action_dim ) UpperCAmelCase = self.to_torch(a__ ) # run the diffusion process UpperCAmelCase, UpperCAmelCase = self.run_diffusion(a__ , a__ , a__ , a__ ) # sort output trajectories by value UpperCAmelCase = y.argsort(0 , descending=a__ ).squeeze() UpperCAmelCase = x[sorted_idx] UpperCAmelCase = sorted_values[:, :, : self.action_dim] UpperCAmelCase = actions.detach().cpu().numpy() UpperCAmelCase = self.de_normalize(a__ , key='''actions''' ) # select the action with the highest value if y is not None: UpperCAmelCase = 0 else: # if we didn't run value guiding, select a random action UpperCAmelCase = np.random.randint(0 , a__ ) UpperCAmelCase = denorm_actions[selected_index, 0] return denorm_actions
570
'''simple docstring''' from typing import List, Optional, Union import torch from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) a__ : List[Any] = logging.get_logger(__name__) # pylint: disable=invalid-name a__ : List[str] = '\n Examples:\n ```py\n >>> import torch\n >>> import numpy as np\n\n >>> from diffusers import KandinskyV22PriorPipeline, KandinskyV22ControlnetPipeline\n >>> from transformers import pipeline\n >>> from diffusers.utils import load_image\n\n\n >>> def make_hint(image, depth_estimator):\n ... image = depth_estimator(image)["depth"]\n ... image = np.array(image)\n ... image = image[:, :, None]\n ... image = np.concatenate([image, image, image], axis=2)\n ... detected_map = torch.from_numpy(image).float() / 255.0\n ... hint = detected_map.permute(2, 0, 1)\n ... return hint\n\n\n >>> depth_estimator = pipeline("depth-estimation")\n\n >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\n ... "kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16\n ... )\n >>> pipe_prior = pipe_prior.to("cuda")\n\n >>> pipe = KandinskyV22ControlnetPipeline.from_pretrained(\n ... "kandinsky-community/kandinsky-2-2-controlnet-depth", torch_dtype=torch.float16\n ... )\n >>> pipe = pipe.to("cuda")\n\n\n >>> img = load_image(\n ... "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"\n ... "/kandinsky/cat.png"\n ... ).resize((768, 768))\n\n >>> hint = make_hint(img, depth_estimator).unsqueeze(0).half().to("cuda")\n\n >>> prompt = "A robot, 4k photo"\n >>> negative_prior_prompt = "lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature"\n\n >>> generator = torch.Generator(device="cuda").manual_seed(43)\n\n >>> image_emb, zero_image_emb = pipe_prior(\n ... prompt=prompt, negative_prompt=negative_prior_prompt, generator=generator\n ... ).to_tuple()\n\n >>> images = pipe(\n ... image_embeds=image_emb,\n ... negative_image_embeds=zero_image_emb,\n ... hint=hint,\n ... num_inference_steps=50,\n ... generator=generator,\n ... height=768,\n ... width=768,\n ... ).images\n\n >>> images[0].save("robot_cat.png")\n ```\n' def __snake_case ( SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : List[str]=8 ) -> str: """simple docstring""" UpperCAmelCase = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 UpperCAmelCase = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' def __init__( self : Tuple , a__ : UNetaDConditionModel , a__ : DDPMScheduler , a__ : VQModel , ): super().__init__() self.register_modules( unet=a__ , scheduler=a__ , movq=a__ , ) UpperCAmelCase = 2 ** (len(self.movq.config.block_out_channels ) - 1) def __snake_case ( self : str , a__ : Union[str, Any] , a__ : List[str] , a__ : int , a__ : Optional[Any] , a__ : List[Any] , a__ : Union[str, Any] ): if latents is None: UpperCAmelCase = randn_tensor(a__ , generator=a__ , device=a__ , dtype=a__ ) else: if latents.shape != shape: raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}" ) UpperCAmelCase = latents.to(a__ ) UpperCAmelCase = latents * scheduler.init_noise_sigma return latents def __snake_case ( self : Optional[Any] , a__ : Union[str, Any]=0 ): if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('''Please install accelerate via `pip install accelerate`''' ) UpperCAmelCase = torch.device(f"cuda:{gpu_id}" ) UpperCAmelCase = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(a__ , a__ ) def __snake_case ( self : Union[str, Any] , a__ : List[str]=0 ): if is_accelerate_available() and is_accelerate_version('''>=''' , '''0.17.0.dev0''' ): from accelerate import cpu_offload_with_hook else: raise ImportError('''`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.''' ) UpperCAmelCase = torch.device(f"cuda:{gpu_id}" ) if self.device.type != "cpu": self.to('''cpu''' , silence_dtype_warnings=a__ ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) UpperCAmelCase = None for cpu_offloaded_model in [self.unet, self.movq]: UpperCAmelCase, UpperCAmelCase = cpu_offload_with_hook(a__ , a__ , prev_module_hook=a__ ) # We'll offload the last model manually. UpperCAmelCase = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def __snake_case ( self : List[Any] ): if not hasattr(self.unet , '''_hf_hook''' ): return self.device for module in self.unet.modules(): if ( hasattr(a__ , '''_hf_hook''' ) and hasattr(module._hf_hook , '''execution_device''' ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() @replace_example_docstring(a__ ) def __call__( self : Union[str, Any] , a__ : Union[torch.FloatTensor, List[torch.FloatTensor]] , a__ : Union[torch.FloatTensor, List[torch.FloatTensor]] , a__ : torch.FloatTensor , a__ : int = 512 , a__ : int = 512 , a__ : int = 100 , a__ : float = 4.0 , a__ : int = 1 , a__ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , a__ : Optional[torch.FloatTensor] = None , a__ : Optional[str] = "pil" , a__ : bool = True , ): UpperCAmelCase = self._execution_device UpperCAmelCase = guidance_scale > 1.0 if isinstance(a__ , a__ ): UpperCAmelCase = torch.cat(a__ , dim=0 ) if isinstance(a__ , a__ ): UpperCAmelCase = torch.cat(a__ , dim=0 ) if isinstance(a__ , a__ ): UpperCAmelCase = torch.cat(a__ , dim=0 ) UpperCAmelCase = image_embeds.shape[0] * num_images_per_prompt if do_classifier_free_guidance: UpperCAmelCase = image_embeds.repeat_interleave(a__ , dim=0 ) UpperCAmelCase = negative_image_embeds.repeat_interleave(a__ , dim=0 ) UpperCAmelCase = hint.repeat_interleave(a__ , dim=0 ) UpperCAmelCase = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=a__ ) UpperCAmelCase = torch.cat([hint, hint] , dim=0 ).to(dtype=self.unet.dtype , device=a__ ) self.scheduler.set_timesteps(a__ , device=a__ ) UpperCAmelCase = self.scheduler.timesteps UpperCAmelCase = self.movq.config.latent_channels UpperCAmelCase, UpperCAmelCase = downscale_height_and_width(a__ , a__ , self.movq_scale_factor ) # create initial latent UpperCAmelCase = self.prepare_latents( (batch_size, num_channels_latents, height, width) , image_embeds.dtype , a__ , a__ , a__ , self.scheduler , ) for i, t in enumerate(self.progress_bar(a__ ) ): # expand the latents if we are doing classifier free guidance UpperCAmelCase = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents UpperCAmelCase = {'''image_embeds''': image_embeds, '''hint''': hint} UpperCAmelCase = self.unet( sample=a__ , timestep=a__ , encoder_hidden_states=a__ , added_cond_kwargs=a__ , return_dict=a__ , )[0] if do_classifier_free_guidance: UpperCAmelCase, UpperCAmelCase = noise_pred.split(latents.shape[1] , dim=1 ) UpperCAmelCase, UpperCAmelCase = noise_pred.chunk(2 ) UpperCAmelCase, UpperCAmelCase = variance_pred.chunk(2 ) UpperCAmelCase = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) UpperCAmelCase = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , '''variance_type''' ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): UpperCAmelCase, UpperCAmelCase = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 UpperCAmelCase = self.scheduler.step( a__ , a__ , a__ , generator=a__ , )[0] # post-processing UpperCAmelCase = self.movq.decode(a__ , force_not_quantize=a__ )['''sample'''] if output_type not in ["pt", "np", "pil"]: raise ValueError(f"Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}" ) if output_type in ["np", "pil"]: UpperCAmelCase = image * 0.5 + 0.5 UpperCAmelCase = image.clamp(0 , 1 ) UpperCAmelCase = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": UpperCAmelCase = self.numpy_to_pil(a__ ) if not return_dict: return (image,) return ImagePipelineOutput(images=a__ )
570
1
import re def __UpperCamelCase ( A ): UpperCamelCase__ = re.compile(r'''^(\+91[\-\s]?)?[0]?(91)?[789]\d{9}$''' ) if match := re.search(A , A ): return match.string == phone return False if __name__ == "__main__": print(indian_phone_validator('''+918827897895'''))
415
def __UpperCamelCase ( A ): if len(A ) < 2: return collection def circle_sort_util(A , A , A ) -> bool: UpperCamelCase__ = False if low == high: return swapped UpperCamelCase__ = low UpperCamelCase__ = high while left < right: if collection[left] > collection[right]: UpperCamelCase__ , UpperCamelCase__ = ( collection[right], collection[left], ) UpperCamelCase__ = True left += 1 right -= 1 if left == right and collection[left] > collection[right + 1]: UpperCamelCase__ , UpperCamelCase__ = ( collection[right + 1], collection[left], ) UpperCamelCase__ = True UpperCamelCase__ = low + int((high - low) / 2 ) UpperCamelCase__ = circle_sort_util(A , A , A ) UpperCamelCase__ = circle_sort_util(A , mid + 1 , A ) return swapped or left_swap or right_swap UpperCamelCase__ = True while is_not_sorted is True: UpperCamelCase__ = circle_sort_util(A , 0 , len(A ) - 1 ) return collection if __name__ == "__main__": __magic_name__ =input('''Enter numbers separated by a comma:\n''').strip() __magic_name__ =[int(item) for item in user_input.split(''',''')] print(circle_sort(unsorted))
415
1
'''simple docstring''' import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import AutoImageProcessor, ViTImageProcessor from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test sys.path.append(str(Path(__file__).parent.parent / 'utils')) from test_module.custom_image_processing import CustomImageProcessor # noqa E402 lowerCamelCase__ = get_tests_dir('fixtures') class _lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __lowercase ( self : List[Any] ) -> str: '''simple docstring''' _lowercase : Union[str, Any] = mock.Mock() _lowercase : List[Any] = 500 _lowercase : Tuple = {} _lowercase : Tuple = HTTPError _lowercase : str = {} # Download this model to make sure it's in the cache. _lowercase : List[str] = ViTImageProcessor.from_pretrained('''hf-internal-testing/tiny-random-vit''' ) # Under the mock environment we get a 500 error when trying to reach the model. with mock.patch('''requests.Session.request''' , return_value=UpperCamelCase_ ) as mock_head: _lowercase : int = ViTImageProcessor.from_pretrained('''hf-internal-testing/tiny-random-vit''' ) # This check we did call the fake head request mock_head.assert_called() def __lowercase ( self : List[Any] ) -> Optional[int]: '''simple docstring''' _lowercase : List[Any] = ViTImageProcessor.from_pretrained( '''https://huggingface.co/hf-internal-testing/tiny-random-vit/resolve/main/preprocessor_config.json''' ) def __lowercase ( self : Union[str, Any] ) -> List[Any]: '''simple docstring''' with self.assertRaises(UpperCamelCase_ ): # config is in subfolder, the following should not work without specifying the subfolder _lowercase : Tuple = AutoImageProcessor.from_pretrained('''hf-internal-testing/stable-diffusion-all-variants''' ) _lowercase : Optional[int] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/stable-diffusion-all-variants''' , subfolder='''feature_extractor''' ) self.assertIsNotNone(UpperCamelCase_ ) @is_staging_test class _lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' @classmethod def __lowercase ( cls : List[str] ) -> Optional[Any]: '''simple docstring''' _lowercase : List[Any] = TOKEN HfFolder.save_token(UpperCamelCase_ ) @classmethod def __lowercase ( cls : str ) -> str: '''simple docstring''' try: delete_repo(token=cls._token , repo_id='''test-image-processor''' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''valid_org/test-image-processor-org''' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''test-dynamic-image-processor''' ) except HTTPError: pass def __lowercase ( self : Any ) -> Optional[Any]: '''simple docstring''' _lowercase : Union[str, Any] = ViTImageProcessor.from_pretrained(UpperCamelCase_ ) image_processor.push_to_hub('''test-image-processor''' , use_auth_token=self._token ) _lowercase : Tuple = ViTImageProcessor.from_pretrained(F"{USER}/test-image-processor" ) for k, v in image_processor.__dict__.items(): self.assertEqual(UpperCamelCase_ , getattr(UpperCamelCase_ , UpperCamelCase_ ) ) # Reset repo delete_repo(token=self._token , repo_id='''test-image-processor''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained( UpperCamelCase_ , repo_id='''test-image-processor''' , push_to_hub=UpperCamelCase_ , use_auth_token=self._token ) _lowercase : Tuple = ViTImageProcessor.from_pretrained(F"{USER}/test-image-processor" ) for k, v in image_processor.__dict__.items(): self.assertEqual(UpperCamelCase_ , getattr(UpperCamelCase_ , UpperCamelCase_ ) ) def __lowercase ( self : Any ) -> Tuple: '''simple docstring''' _lowercase : Dict = ViTImageProcessor.from_pretrained(UpperCamelCase_ ) image_processor.push_to_hub('''valid_org/test-image-processor''' , use_auth_token=self._token ) _lowercase : Tuple = ViTImageProcessor.from_pretrained('''valid_org/test-image-processor''' ) for k, v in image_processor.__dict__.items(): self.assertEqual(UpperCamelCase_ , getattr(UpperCamelCase_ , UpperCamelCase_ ) ) # Reset repo delete_repo(token=self._token , repo_id='''valid_org/test-image-processor''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained( UpperCamelCase_ , repo_id='''valid_org/test-image-processor-org''' , push_to_hub=UpperCamelCase_ , use_auth_token=self._token ) _lowercase : Tuple = ViTImageProcessor.from_pretrained('''valid_org/test-image-processor-org''' ) for k, v in image_processor.__dict__.items(): self.assertEqual(UpperCamelCase_ , getattr(UpperCamelCase_ , UpperCamelCase_ ) ) def __lowercase ( self : Union[str, Any] ) -> Optional[int]: '''simple docstring''' CustomImageProcessor.register_for_auto_class() _lowercase : Any = CustomImageProcessor.from_pretrained(UpperCamelCase_ ) image_processor.push_to_hub('''test-dynamic-image-processor''' , use_auth_token=self._token ) # This has added the proper auto_map field to the config self.assertDictEqual( image_processor.auto_map , {'''AutoImageProcessor''': '''custom_image_processing.CustomImageProcessor'''} , ) _lowercase : Union[str, Any] = AutoImageProcessor.from_pretrained( F"{USER}/test-dynamic-image-processor" , trust_remote_code=UpperCamelCase_ ) # Can't make an isinstance check because the new_image_processor is from the CustomImageProcessor class of a dynamic module self.assertEqual(new_image_processor.__class__.__name__ , '''CustomImageProcessor''' )
411
'''simple docstring''' import warnings from ...utils import logging from .image_processing_clip import CLIPImageProcessor lowerCamelCase__ = logging.get_logger(__name__) class _lowerCAmelCase ( __A ): '''simple docstring''' def __init__( self : Optional[int] , *UpperCamelCase_ : Union[str, Any] , **UpperCamelCase_ : Optional[int] ) -> None: '''simple docstring''' warnings.warn( '''The class CLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please''' ''' use CLIPImageProcessor instead.''' , UpperCamelCase_ , ) super().__init__(*UpperCamelCase_ , **UpperCamelCase_ )
411
1
def lowerCamelCase__ (): return [ a * b * (1000 - a - b) for a in range(1 , 999) for b in range(_UpperCAmelCase , 999) if (a * a + b * b == (1000 - a - b) ** 2) ][0] if __name__ == "__main__": print(f"""{solution() = }""")
73
from torch import nn def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str ): if act_fn in ["swish", "silu"]: return nn.SiLU() elif act_fn == "mish": return nn.Mish() elif act_fn == "gelu": return nn.GELU() else: raise ValueError(f'''Unsupported activation function: {act_fn}''' )
6
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available _A = { "configuration_bloom": ["BLOOM_PRETRAINED_CONFIG_ARCHIVE_MAP", "BloomConfig", "BloomOnnxConfig"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = ["BloomTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ "BLOOM_PRETRAINED_MODEL_ARCHIVE_LIST", "BloomForCausalLM", "BloomModel", "BloomPreTrainedModel", "BloomForSequenceClassification", "BloomForTokenClassification", "BloomForQuestionAnswering", ] if TYPE_CHECKING: from .configuration_bloom import BLOOM_PRETRAINED_CONFIG_ARCHIVE_MAP, BloomConfig, BloomOnnxConfig try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bloom_fast import BloomTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bloom import ( BLOOM_PRETRAINED_MODEL_ARCHIVE_LIST, BloomForCausalLM, BloomForQuestionAnswering, BloomForSequenceClassification, BloomForTokenClassification, BloomModel, BloomPreTrainedModel, ) else: import sys _A = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
721
from ...processing_utils import ProcessorMixin class _lowerCAmelCase ( __a ): _lowercase ='''SpeechT5FeatureExtractor''' _lowercase ='''SpeechT5Tokenizer''' def __init__( self , _UpperCamelCase , _UpperCamelCase ) -> int: super().__init__(_UpperCamelCase , _UpperCamelCase ) def __call__( self , *_UpperCamelCase , **_UpperCamelCase ) -> Optional[int]: lowerCAmelCase_ = kwargs.pop("audio" , _UpperCamelCase ) lowerCAmelCase_ = kwargs.pop("text" , _UpperCamelCase ) lowerCAmelCase_ = kwargs.pop("text_target" , _UpperCamelCase ) lowerCAmelCase_ = kwargs.pop("audio_target" , _UpperCamelCase ) lowerCAmelCase_ = kwargs.pop("sampling_rate" , _UpperCamelCase ) if audio is not None and text is not None: raise ValueError( "Cannot process both `audio` and `text` inputs. Did you mean `audio_target` or `text_target`?" ) if audio_target is not None and text_target is not None: raise ValueError( "Cannot process both `audio_target` and `text_target` inputs. Did you mean `audio` or `text`?" ) if audio is None and audio_target is None and text is None and text_target is None: raise ValueError( "You need to specify either an `audio`, `audio_target`, `text`, or `text_target` input to process." ) if audio is not None: lowerCAmelCase_ = self.feature_extractor(_UpperCamelCase , *_UpperCamelCase , sampling_rate=_UpperCamelCase , **_UpperCamelCase ) elif text is not None: lowerCAmelCase_ = self.tokenizer(_UpperCamelCase , **_UpperCamelCase ) else: lowerCAmelCase_ = None if audio_target is not None: lowerCAmelCase_ = self.feature_extractor(audio_target=_UpperCamelCase , *_UpperCamelCase , sampling_rate=_UpperCamelCase , **_UpperCamelCase ) lowerCAmelCase_ = targets["input_values"] elif text_target is not None: lowerCAmelCase_ = self.tokenizer(_UpperCamelCase , **_UpperCamelCase ) lowerCAmelCase_ = targets["input_ids"] else: lowerCAmelCase_ = None if inputs is None: return targets if targets is not None: lowerCAmelCase_ = labels lowerCAmelCase_ = targets.get("attention_mask" ) if decoder_attention_mask is not None: lowerCAmelCase_ = decoder_attention_mask return inputs def __a ( self , *_UpperCamelCase , **_UpperCamelCase ) -> str: lowerCAmelCase_ = kwargs.pop("input_values" , _UpperCamelCase ) lowerCAmelCase_ = kwargs.pop("input_ids" , _UpperCamelCase ) lowerCAmelCase_ = kwargs.pop("labels" , _UpperCamelCase ) if input_values is not None and input_ids is not None: raise ValueError("Cannot process both `input_values` and `input_ids` inputs." ) if input_values is None and input_ids is None and labels is None: raise ValueError( "You need to specify either an `input_values`, `input_ids`, or `labels` input to be padded." ) if input_values is not None: lowerCAmelCase_ = self.feature_extractor.pad(_UpperCamelCase , *_UpperCamelCase , **_UpperCamelCase ) elif input_ids is not None: lowerCAmelCase_ = self.tokenizer.pad(_UpperCamelCase , **_UpperCamelCase ) else: lowerCAmelCase_ = None if labels is not None: if "input_ids" in labels or (isinstance(_UpperCamelCase , _UpperCamelCase ) and "input_ids" in labels[0]): lowerCAmelCase_ = self.tokenizer.pad(_UpperCamelCase , **_UpperCamelCase ) lowerCAmelCase_ = targets["input_ids"] else: lowerCAmelCase_ = self.feature_extractor.feature_size lowerCAmelCase_ = self.feature_extractor.num_mel_bins lowerCAmelCase_ = self.feature_extractor.pad(_UpperCamelCase , *_UpperCamelCase , **_UpperCamelCase ) lowerCAmelCase_ = feature_size_hack lowerCAmelCase_ = targets["input_values"] else: lowerCAmelCase_ = None if inputs is None: return targets if targets is not None: lowerCAmelCase_ = labels lowerCAmelCase_ = targets.get("attention_mask" ) if decoder_attention_mask is not None: lowerCAmelCase_ = decoder_attention_mask return inputs def __a ( self , *_UpperCamelCase , **_UpperCamelCase ) -> List[Any]: return self.tokenizer.batch_decode(*_UpperCamelCase , **_UpperCamelCase ) def __a ( self , *_UpperCamelCase , **_UpperCamelCase ) -> Optional[Any]: return self.tokenizer.decode(*_UpperCamelCase , **_UpperCamelCase )
279
0
import logging from transformers import PretrainedConfig __magic_name__ : Optional[int] = logging.getLogger(__name__) __magic_name__ : Optional[int] = { '''bertabs-finetuned-cnndm''': '''https://huggingface.co/remi/bertabs-finetuned-cnndm-extractive-abstractive-summarization/resolve/main/config.json''', } class A__ ( __snake_case ): '''simple docstring''' snake_case__ = """bertabs""" def __init__( self : Any , _SCREAMING_SNAKE_CASE : Optional[int]=3_0522 , _SCREAMING_SNAKE_CASE : Dict=512 , _SCREAMING_SNAKE_CASE : Tuple=6 , _SCREAMING_SNAKE_CASE : str=512 , _SCREAMING_SNAKE_CASE : Tuple=8 , _SCREAMING_SNAKE_CASE : Optional[int]=512 , _SCREAMING_SNAKE_CASE : Tuple=0.2 , _SCREAMING_SNAKE_CASE : Dict=6 , _SCREAMING_SNAKE_CASE : Optional[int]=768 , _SCREAMING_SNAKE_CASE : List[Any]=8 , _SCREAMING_SNAKE_CASE : Any=2048 , _SCREAMING_SNAKE_CASE : Optional[Any]=0.2 , **_SCREAMING_SNAKE_CASE : List[str] , ): """simple docstring""" super().__init__(**__lowerCAmelCase ) UpperCamelCase = vocab_size UpperCamelCase = max_pos UpperCamelCase = enc_layers UpperCamelCase = enc_hidden_size UpperCamelCase = enc_heads UpperCamelCase = enc_ff_size UpperCamelCase = enc_dropout UpperCamelCase = dec_layers UpperCamelCase = dec_hidden_size UpperCamelCase = dec_heads UpperCamelCase = dec_ff_size UpperCamelCase = dec_dropout
280
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from argparse import ArgumentParser from accelerate.commands.config import get_config_parser from accelerate.commands.env import env_command_parser from accelerate.commands.launch import launch_command_parser from accelerate.commands.test import test_command_parser from accelerate.commands.tpu import tpu_command_parser def lowerCAmelCase__() -> str: '''simple docstring''' lowerCamelCase__ = ArgumentParser('''Accelerate CLI tool''' ,usage='''accelerate <command> [<args>]''' ,allow_abbrev=__snake_case ) lowerCamelCase__ = parser.add_subparsers(help='''accelerate command helpers''' ) # Register commands get_config_parser(subparsers=__snake_case ) env_command_parser(subparsers=__snake_case ) launch_command_parser(subparsers=__snake_case ) tpu_command_parser(subparsers=__snake_case ) test_command_parser(subparsers=__snake_case ) # Let's go lowerCamelCase__ = parser.parse_args() if not hasattr(__snake_case ,'''func''' ): parser.print_help() exit(1 ) # Run args.func(__snake_case ) if __name__ == "__main__": main()
481
0
"""simple docstring""" from __future__ import annotations import random import unittest from transformers import TransfoXLConfig, 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 from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST, TFTransfoXLForSequenceClassification, TFTransfoXLLMHeadModel, TFTransfoXLModel, ) class __lowerCAmelCase : """simple docstring""" def __init__( self : int , _snake_case : Tuple , ) -> Tuple: """simple docstring""" A_ = parent A_ = 13 A_ = 7 A_ = 30 A_ = self.seq_length + self.mem_len A_ = 15 A_ = True A_ = True A_ = 99 A_ = [10, 50, 80] A_ = 32 A_ = 32 A_ = 4 A_ = 8 A_ = 128 A_ = 2 A_ = 2 A_ = None A_ = 1 A_ = 0 A_ = 3 A_ = self.vocab_size - 1 A_ = 0.0_1 def lowerCamelCase__ ( self : Optional[int] ) -> Dict: """simple docstring""" A_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A_ = None if self.use_labels: A_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A_ = TransfoXLConfig( vocab_size=self.vocab_size , mem_len=self.mem_len , clamp_len=self.clamp_len , cutoffs=self.cutoffs , d_model=self.hidden_size , d_embed=self.d_embed , n_head=self.num_attention_heads , d_head=self.d_head , d_inner=self.d_inner , div_val=self.div_val , n_layer=self.num_hidden_layers , eos_token_id=self.eos_token_id , pad_token_id=self.vocab_size - 1 , init_range=self.init_range , num_labels=self.num_labels , ) return (config, input_ids_a, input_ids_a, lm_labels) def lowerCamelCase__ ( self : List[Any] ) -> Optional[int]: """simple docstring""" random.seed(self.seed ) tf.random.set_seed(self.seed ) def lowerCamelCase__ ( self : Optional[int] , _snake_case : Union[str, Any] , _snake_case : Any , _snake_case : Tuple , _snake_case : Any ) -> List[Any]: """simple docstring""" A_ = TFTransfoXLModel(UpperCAmelCase__ ) A_ = model(UpperCAmelCase__ ).to_tuple() A_ = {'''input_ids''': input_ids_a, '''mems''': mems_a} A_ = model(UpperCAmelCase__ ).to_tuple() self.parent.assertEqual(hidden_states_a.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(hidden_states_a.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertListEqual( [mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , ) self.parent.assertListEqual( [mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , ) def lowerCamelCase__ ( self : Tuple , _snake_case : int , _snake_case : str , _snake_case : Any , _snake_case : Tuple ) -> int: """simple docstring""" A_ = TFTransfoXLLMHeadModel(UpperCAmelCase__ ) A_ = model(UpperCAmelCase__ ).to_tuple() A_ = {'''input_ids''': input_ids_a, '''labels''': lm_labels} A_ = model(UpperCAmelCase__ ).to_tuple() A_ = model([input_ids_a, mems_a] ).to_tuple() A_ = {'''input_ids''': input_ids_a, '''mems''': mems_a, '''labels''': lm_labels} A_ = model(UpperCAmelCase__ ).to_tuple() self.parent.assertEqual(lm_logits_a.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertListEqual( [mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , ) self.parent.assertEqual(lm_logits_a.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertListEqual( [mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , ) def lowerCamelCase__ ( self : int , _snake_case : str , _snake_case : List[Any] , _snake_case : Optional[int] , _snake_case : int ) -> Union[str, Any]: """simple docstring""" A_ = TFTransfoXLForSequenceClassification(UpperCAmelCase__ ) A_ = model(UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCamelCase__ ( self : str ) -> List[Any]: """simple docstring""" A_ = self.prepare_config_and_inputs() (A_) = config_and_inputs A_ = {'''input_ids''': input_ids_a} return config, inputs_dict @require_tf class __lowerCAmelCase ( lowercase__ , lowercase__ , unittest.TestCase ): """simple docstring""" snake_case = ( (TFTransfoXLModel, TFTransfoXLLMHeadModel, TFTransfoXLForSequenceClassification) if is_tf_available() else () ) snake_case = () if is_tf_available() else () snake_case = ( { "feature-extraction": TFTransfoXLModel, "text-classification": TFTransfoXLForSequenceClassification, "text-generation": TFTransfoXLLMHeadModel, "zero-shot": TFTransfoXLForSequenceClassification, } if is_tf_available() else {} ) # TODO: add this test when TFTransfoXLLMHead has a linear output layer implemented snake_case = False snake_case = False snake_case = False snake_case = False def lowerCamelCase__ ( self : Optional[int] , _snake_case : List[str] , _snake_case : Union[str, Any] , _snake_case : Any , _snake_case : Tuple , _snake_case : Union[str, Any] ) -> Tuple: """simple docstring""" if pipeline_test_casse_name == "TextGenerationPipelineTests": # Get `ValueError: AttributeError: 'NoneType' object has no attribute 'new_ones'` or `AssertionError`. # `TransfoXLConfig` was never used in pipeline tests: cannot create a simple # tokenizer. return True return False def lowerCamelCase__ ( self : List[Any] ) -> Optional[Any]: """simple docstring""" A_ = TFTransfoXLModelTester(self ) A_ = ConfigTester(self , config_class=UpperCAmelCase__ , d_embed=37 ) def lowerCamelCase__ ( self : int ) -> Tuple: """simple docstring""" self.config_tester.run_common_tests() def lowerCamelCase__ ( self : int ) -> Optional[Any]: """simple docstring""" self.model_tester.set_seed() A_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_transfo_xl_model(*UpperCAmelCase__ ) def lowerCamelCase__ ( self : Optional[Any] ) -> Dict: """simple docstring""" self.model_tester.set_seed() A_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_transfo_xl_lm_head(*UpperCAmelCase__ ) def lowerCamelCase__ ( self : Any ) -> Union[str, Any]: """simple docstring""" A_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_transfo_xl_for_sequence_classification(*UpperCAmelCase__ ) def lowerCamelCase__ ( self : Optional[int] ) -> Any: """simple docstring""" A_ = self.model_tester.prepare_config_and_inputs_for_common() A_ = [TFTransfoXLForSequenceClassification] for model_class in self.all_model_classes: A_ = model_class(UpperCAmelCase__ ) assert isinstance(model.get_input_embeddings() , tf.keras.layers.Layer ) if model_class in list_other_models_with_output_ebd: A_ = model.get_output_embeddings() assert isinstance(UpperCAmelCase__ , tf.keras.layers.Layer ) A_ = model.get_bias() assert name is None else: A_ = model.get_output_embeddings() assert x is None A_ = model.get_bias() assert name is None def lowerCamelCase__ ( self : Union[str, Any] ) -> Dict: """simple docstring""" pass @slow def lowerCamelCase__ ( self : int ) -> Optional[Any]: """simple docstring""" for model_name in TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A_ = TFTransfoXLModel.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) @unittest.skip(reason="This model doesn\'t play well with fit() due to not returning a single loss." ) def lowerCamelCase__ ( self : List[Any] ) -> Tuple: """simple docstring""" pass @require_tf class __lowerCAmelCase ( unittest.TestCase ): """simple docstring""" @unittest.skip("Skip test until #12651 is resolved." ) @slow def lowerCamelCase__ ( self : int ) -> List[str]: """simple docstring""" A_ = TFTransfoXLLMHeadModel.from_pretrained("transfo-xl-wt103" ) # fmt: off A_ = tf.convert_to_tensor([[33,1_297,2,1,1_009,4,1_109,11_739,4_762,358,5,25,245,22,1_706,17,20_098,5,3_215,21,37,1_110,3,13,1_041,4,24,603,490,2,71_477,20_098,104_447,2,20_961,1,2_604,4,1,329,3,6_224,831,16_002,2,8,603,78_967,29_546,23,803,20,25,416,5,8,232,4,277,6,1_855,4_601,3,29_546,54,8,3_609,5,57_211,49,4,1,277,18,8,1_755,15_691,3,341,25,416,693,42_573,71,17,401,94,31,17_919,2,29_546,7_873,18,1,435,23,11_011,755,5,5_167,3,7_983,98,84,2,29_546,3_267,8,3_609,4,1,4_865,1_075,2,6_087,71,6,346,8,5_854,3,29_546,824,1_400,1_868,2,19,160,2,311,8,5_496,2,20_920,17,25,15_097,3,24,24,0]] , dtype=tf.intaa ) # noqa: E231 # fmt: on # In 1991 , the remains of Russian Tsar Nicholas II and his family # ( except for Alexei and Maria ) are discovered . # The voice of Nicholas's young son , Tsarevich Alexei Nikolaevich , narrates the # remainder of the story . 1883 Western Siberia , # a young Grigori Rasputin is asked by his father and a group of men to perform magic . # Rasputin has a vision and denounces one of the men as a horse thief . Although his # father initially slaps him for making such an accusation , Rasputin watches as the # man is chased outside and beaten . Twenty years later , Rasputin sees a vision of # the Virgin Mary , prompting him to become a priest . Rasputin quickly becomes famous , # with people , even a bishop , begging for his blessing . <eod> </s> <eos> # fmt: off A_ = [33,1_297,2,1,1_009,4,1_109,11_739,4_762,358,5,25,245,22,1_706,17,20_098,5,3_215,21,37,1_110,3,13,1_041,4,24,603,490,2,71_477,20_098,104_447,2,20_961,1,2_604,4,1,329,3,6_224,831,16_002,2,8,603,78_967,29_546,23,803,20,25,416,5,8,232,4,277,6,1_855,4_601,3,29_546,54,8,3_609,5,57_211,49,4,1,277,18,8,1_755,15_691,3,341,25,416,693,42_573,71,17,401,94,31,17_919,2,29_546,7_873,18,1,435,23,11_011,755,5,5_167,3,7_983,98,84,2,29_546,3_267,8,3_609,4,1,4_865,1_075,2,6_087,71,6,346,8,5_854,3,29_546,824,1_400,1_868,2,19,160,2,311,8,5_496,2,20_920,17,25,15_097,3,24,24,0,33,1,1_857,2,1,1_009,4,1_109,11_739,4_762,358,5,25,245,28,1_110,3,13,1_041,4,24,603,490,2,71_477,20_098,104_447,2,20_961,1,2_604,4,1,329,3,0] # noqa: E231 # fmt: on # In 1991, the remains of Russian Tsar Nicholas II and his family ( # except for Alexei and Maria ) are discovered. The voice of young son, # Tsarevich Alexei Nikolaevich, narrates the remainder of the story. # 1883 Western Siberia, a young Grigori Rasputin is asked by his father # and a group of men to perform magic. Rasputin has a vision and # denounces one of the men as a horse thief. Although his father initially # slaps him for making such an accusation, Rasputin watches as the man # is chased outside and beaten. Twenty years later, Rasputin sees a vision # of the Virgin Mary, prompting him to become a priest. # Rasputin quickly becomes famous, with people, even a bishop, begging for # his blessing. <unk> <unk> <eos> In the 1990s, the remains of Russian Tsar # Nicholas II and his family were discovered. The voice of <unk> young son, # Tsarevich Alexei Nikolaevich, narrates the remainder of the story.<eos> A_ = model.generate(UpperCAmelCase__ , max_length=200 , do_sample=UpperCAmelCase__ ) self.assertListEqual(output_ids[0].numpy().tolist() , UpperCAmelCase__ )
700
"""simple docstring""" from argparse import ArgumentParser, Namespace from ..utils import logging from . import BaseTransformersCLICommand def A_ (__a ): '''simple docstring''' return ConvertCommand( args.model_type , args.tf_checkpoint , args.pytorch_dump_output , args.config , args.finetuning_task_name ) UpperCamelCase_ : Tuple = ''' transformers can only be used from the commandline to convert TensorFlow models in PyTorch, In that case, it requires TensorFlow to be installed. Please see https://www.tensorflow.org/install/ for installation instructions. ''' class __lowerCAmelCase ( _lowercase ): """simple docstring""" @staticmethod def lowerCamelCase__ ( _snake_case : ArgumentParser ) -> Union[str, Any]: """simple docstring""" A_ = parser.add_parser( "convert" , help="CLI tool to run convert model from original author checkpoints to Transformers PyTorch checkpoints." , ) train_parser.add_argument("--model_type" , type=_snake_case , required=_snake_case , help="Model's type." ) train_parser.add_argument( "--tf_checkpoint" , type=_snake_case , required=_snake_case , help="TensorFlow checkpoint path or folder." ) train_parser.add_argument( "--pytorch_dump_output" , type=_snake_case , required=_snake_case , help="Path to the PyTorch saved model output." ) train_parser.add_argument("--config" , type=_snake_case , default="" , help="Configuration file path or folder." ) train_parser.add_argument( "--finetuning_task_name" , type=_snake_case , default=_snake_case , help="Optional fine-tuning task name if the TF model was a finetuned model." , ) train_parser.set_defaults(func=_snake_case ) def __init__( self : str , _snake_case : str , _snake_case : str , _snake_case : str , _snake_case : str , _snake_case : str , *_snake_case : Optional[int] , ) -> Union[str, Any]: """simple docstring""" A_ = logging.get_logger("transformers-cli/converting" ) self._logger.info(F'Loading model {model_type}' ) A_ = model_type A_ = tf_checkpoint A_ = pytorch_dump_output A_ = config A_ = finetuning_task_name def lowerCamelCase__ ( self : Tuple ) -> Dict: """simple docstring""" if self._model_type == "albert": try: from ..models.albert.convert_albert_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_snake_case ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "bert": try: from ..models.bert.convert_bert_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_snake_case ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "funnel": try: from ..models.funnel.convert_funnel_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_snake_case ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "t5": try: from ..models.ta.convert_ta_original_tf_checkpoint_to_pytorch import convert_tf_checkpoint_to_pytorch except ImportError: raise ImportError(_snake_case ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "gpt": from ..models.openai.convert_openai_original_tf_checkpoint_to_pytorch import ( convert_openai_checkpoint_to_pytorch, ) convert_openai_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "transfo_xl": try: from ..models.transfo_xl.convert_transfo_xl_original_tf_checkpoint_to_pytorch import ( convert_transfo_xl_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_snake_case ) if "ckpt" in self._tf_checkpoint.lower(): A_ = self._tf_checkpoint A_ = "" else: A_ = self._tf_checkpoint A_ = "" convert_transfo_xl_checkpoint_to_pytorch( _snake_case , self._config , self._pytorch_dump_output , _snake_case ) elif self._model_type == "gpt2": try: from ..models.gpta.convert_gpta_original_tf_checkpoint_to_pytorch import ( convert_gpta_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_snake_case ) convert_gpta_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "xlnet": try: from ..models.xlnet.convert_xlnet_original_tf_checkpoint_to_pytorch import ( convert_xlnet_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_snake_case ) convert_xlnet_checkpoint_to_pytorch( self._tf_checkpoint , self._config , self._pytorch_dump_output , self._finetuning_task_name ) elif self._model_type == "xlm": from ..models.xlm.convert_xlm_original_pytorch_checkpoint_to_pytorch import ( convert_xlm_checkpoint_to_pytorch, ) convert_xlm_checkpoint_to_pytorch(self._tf_checkpoint , self._pytorch_dump_output ) elif self._model_type == "lxmert": from ..models.lxmert.convert_lxmert_original_tf_checkpoint_to_pytorch import ( convert_lxmert_checkpoint_to_pytorch, ) convert_lxmert_checkpoint_to_pytorch(self._tf_checkpoint , self._pytorch_dump_output ) elif self._model_type == "rembert": from ..models.rembert.convert_rembert_tf_checkpoint_to_pytorch import ( convert_rembert_tf_checkpoint_to_pytorch, ) convert_rembert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) else: raise ValueError( "--model_type should be selected in the list [bert, gpt, gpt2, t5, transfo_xl, xlnet, xlm, lxmert]" )
482
0
from __future__ import annotations from sys import maxsize from typing import Generic, TypeVar __lowerCamelCase : Union[str, Any] = TypeVar("""T""") def A__ ( _a : int ): '''simple docstring''' return (position - 1) // 2 def A__ ( _a : int ): '''simple docstring''' return (2 * position) + 1 def A__ ( _a : int ): '''simple docstring''' return (2 * position) + 2 class _lowercase ( Generic[T] ): def __init__( self ): snake_case__ : list[tuple[T, int]] =[] snake_case__ : dict[T, int] ={} snake_case__ : int =0 def __len__( self ): return self.elements def __repr__( self ): return str(self.heap ) def lowercase__ ( self ): # Check if the priority queue is empty return self.elements == 0 def lowercase__ ( self , a , a ): # Add an element with given priority to the queue self.heap.append((elem, weight) ) snake_case__ : Tuple =self.elements self.elements += 1 self._bubble_up(a ) def lowercase__ ( self ): # Remove and return the element with lowest weight (highest priority) if self.elements > 1: self._swap_nodes(0 , self.elements - 1 ) snake_case__ , snake_case__ : Any =self.heap.pop() del self.position_map[elem] self.elements -= 1 if self.elements > 0: snake_case__ , snake_case__ : Tuple =self.heap[0] self._bubble_down(a ) return elem def lowercase__ ( self , a , a ): # Update the weight of the given key snake_case__ : Optional[int] =self.position_map[elem] snake_case__ : Union[str, Any] =(elem, weight) if position > 0: snake_case__ : List[Any] =get_parent_position(a ) snake_case__ , snake_case__ : Union[str, Any] =self.heap[parent_position] if parent_weight > weight: self._bubble_up(a ) else: self._bubble_down(a ) else: self._bubble_down(a ) def lowercase__ ( self , a ): # Place a node at the proper position (upward movement) [to be used internally # only] snake_case__ : List[Any] =self.position_map[elem] if curr_pos == 0: return None snake_case__ : List[str] =get_parent_position(a ) snake_case__ , snake_case__ : Dict =self.heap[curr_pos] snake_case__ , snake_case__ : Tuple =self.heap[parent_position] if parent_weight > weight: self._swap_nodes(a , a ) return self._bubble_up(a ) return None def lowercase__ ( self , a ): # Place a node at the proper position (downward movement) [to be used # internally only] snake_case__ : Dict =self.position_map[elem] snake_case__ , snake_case__ : Tuple =self.heap[curr_pos] snake_case__ : Optional[int] =get_child_left_position(a ) snake_case__ : Union[str, Any] =get_child_right_position(a ) if child_left_position < self.elements and child_right_position < self.elements: snake_case__ , snake_case__ : str =self.heap[child_left_position] snake_case__ , snake_case__ : Any =self.heap[child_right_position] if child_right_weight < child_left_weight and child_right_weight < weight: self._swap_nodes(a , a ) return self._bubble_down(a ) if child_left_position < self.elements: snake_case__ , snake_case__ : List[str] =self.heap[child_left_position] if child_left_weight < weight: self._swap_nodes(a , a ) return self._bubble_down(a ) else: return None if child_right_position < self.elements: snake_case__ , snake_case__ : Tuple =self.heap[child_right_position] if child_right_weight < weight: self._swap_nodes(a , a ) return self._bubble_down(a ) return None def lowercase__ ( self , a , a ): # Swap the nodes at the given positions snake_case__ : Any =self.heap[nodea_pos][0] snake_case__ : int =self.heap[nodea_pos][0] snake_case__ , snake_case__ : List[str] =( self.heap[nodea_pos], self.heap[nodea_pos], ) snake_case__ : Optional[Any] =nodea_pos snake_case__ : str =nodea_pos class _lowercase ( Generic[T] ): def __init__( self ): snake_case__ : dict[T, dict[T, int]] ={} snake_case__ : int =0 def __repr__( self ): return str(self.connections ) def __len__( self ): return self.nodes def lowercase__ ( self , a ): # Add a node in the graph if it is not in the graph if node not in self.connections: snake_case__ : int ={} self.nodes += 1 def lowercase__ ( self , a , a , a ): # Add an edge between 2 nodes in the graph self.add_node(a ) self.add_node(a ) snake_case__ : List[str] =weight snake_case__ : Dict =weight def A__ ( _a : GraphUndirectedWeighted[T] , ): '''simple docstring''' snake_case__ : dict[T, int] ={node: maxsize for node in graph.connections} snake_case__ : dict[T, T | None] ={node: None for node in graph.connections} snake_case__ : MinPriorityQueue[T] =MinPriorityQueue() for node, weight in dist.items(): priority_queue.push(_a , _a ) if priority_queue.is_empty(): return dist, parent # initialization snake_case__ : Dict =priority_queue.extract_min() snake_case__ : Any =0 for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: snake_case__ : Optional[Any] =dist[node] + graph.connections[node][neighbour] priority_queue.update_key(_a , dist[neighbour] ) snake_case__ : List[Any] =node # running prim's algorithm while not priority_queue.is_empty(): snake_case__ : int =priority_queue.extract_min() for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: snake_case__ : Union[str, Any] =dist[node] + graph.connections[node][neighbour] priority_queue.update_key(_a , dist[neighbour] ) snake_case__ : Tuple =node return dist, parent
385
import os from itertools import chain from random import randrange, shuffle import pytest from .sola import PokerHand __lowerCamelCase : List[str] = ( """4S 3H 2C 7S 5H""", """9D 8H 2C 6S 7H""", """2D 6D 9D TH 7D""", """TC 8C 2S JH 6C""", """JH 8S TH AH QH""", """TS KS 5S 9S AC""", """KD 6S 9D TH AD""", """KS 8D 4D 9S 4S""", # pair """8C 4S KH JS 4D""", # pair """QH 8H KD JH 8S""", # pair """KC 4H KS 2H 8D""", # pair """KD 4S KC 3H 8S""", # pair """AH 8S AS KC JH""", # pair """3H 4C 4H 3S 2H""", # 2 pairs """5S 5D 2C KH KH""", # 2 pairs """3C KH 5D 5S KH""", # 2 pairs """AS 3C KH AD KH""", # 2 pairs """7C 7S 3S 7H 5S""", # 3 of a kind """7C 7S KH 2H 7H""", # 3 of a kind """AC KH QH AH AS""", # 3 of a kind """2H 4D 3C AS 5S""", # straight (low ace) """3C 5C 4C 2C 6H""", # straight """6S 8S 7S 5H 9H""", # straight """JS QS 9H TS KH""", # straight """QC KH TS JS AH""", # straight (high ace) """8C 9C 5C 3C TC""", # flush """3S 8S 9S 5S KS""", # flush """4C 5C 9C 8C KC""", # flush """JH 8H AH KH QH""", # flush """3D 2H 3H 2C 2D""", # full house """2H 2C 3S 3H 3D""", # full house """KH KC 3S 3H 3D""", # full house """JC 6H JS JD JH""", # 4 of a kind """JC 7H JS JD JH""", # 4 of a kind """JC KH JS JD JH""", # 4 of a kind """2S AS 4S 5S 3S""", # straight flush (low ace) """2D 6D 3D 4D 5D""", # straight flush """5C 6C 3C 7C 4C""", # straight flush """JH 9H TH KH QH""", # straight flush """JH AH TH KH QH""", # royal flush (high ace straight flush) ) __lowerCamelCase : Optional[Any] = ( ("""2H 3H 4H 5H 6H""", """KS AS TS QS JS""", """Loss"""), ("""2H 3H 4H 5H 6H""", """AS AD AC AH JD""", """Win"""), ("""AS AH 2H AD AC""", """JS JD JC JH 3D""", """Win"""), ("""2S AH 2H AS AC""", """JS JD JC JH AD""", """Loss"""), ("""2S AH 2H AS AC""", """2H 3H 5H 6H 7H""", """Win"""), ("""AS 3S 4S 8S 2S""", """2H 3H 5H 6H 7H""", """Win"""), ("""2H 3H 5H 6H 7H""", """2S 3H 4H 5S 6C""", """Win"""), ("""2S 3H 4H 5S 6C""", """3D 4C 5H 6H 2S""", """Tie"""), ("""2S 3H 4H 5S 6C""", """AH AC 5H 6H AS""", """Win"""), ("""2S 2H 4H 5S 4C""", """AH AC 5H 6H AS""", """Loss"""), ("""2S 2H 4H 5S 4C""", """AH AC 5H 6H 7S""", """Win"""), ("""6S AD 7H 4S AS""", """AH AC 5H 6H 7S""", """Loss"""), ("""2S AH 4H 5S KC""", """AH AC 5H 6H 7S""", """Loss"""), ("""2S 3H 6H 7S 9C""", """7H 3C TH 6H 9S""", """Loss"""), ("""4S 5H 6H TS AC""", """3S 5H 6H TS AC""", """Win"""), ("""2S AH 4H 5S 6C""", """AD 4C 5H 6H 2C""", """Tie"""), ("""AS AH 3H AD AC""", """AS AH 2H AD AC""", """Win"""), ("""AH AC 5H 5C QS""", """AH AC 5H 5C KS""", """Loss"""), ("""AH AC 5H 5C QS""", """KH KC 5H 5C QS""", """Win"""), ("""7C 7S KH 2H 7H""", """3C 3S AH 2H 3H""", """Win"""), ("""3C 3S AH 2H 3H""", """7C 7S KH 2H 7H""", """Loss"""), ("""6H 5H 4H 3H 2H""", """5H 4H 3H 2H AH""", """Win"""), ("""5H 4H 3H 2H AH""", """5H 4H 3H 2H AH""", """Tie"""), ("""5H 4H 3H 2H AH""", """6H 5H 4H 3H 2H""", """Loss"""), ("""AH AD KS KC AC""", """AH KD KH AC KC""", """Win"""), ("""2H 4D 3C AS 5S""", """2H 4D 3C 6S 5S""", """Loss"""), ("""2H 3S 3C 3H 2S""", """3S 3C 2S 2H 2D""", """Win"""), ("""4D 6D 5D 2D JH""", """3S 8S 3H TC KH""", """Loss"""), ("""4S 6C 8S 3S 7S""", """AD KS 2D 7D 7C""", """Loss"""), ("""6S 4C 7H 8C 3H""", """5H JC AH 9D 9C""", """Loss"""), ("""9D 9H JH TC QH""", """3C 2S JS 5C 7H""", """Win"""), ("""2H TC 8S AD 9S""", """4H TS 7H 2C 5C""", """Win"""), ("""9D 3S 2C 7S 7C""", """JC TD 3C TC 9H""", """Loss"""), ) __lowerCamelCase : List[str] = ( ("""2H 3H 4H 5H 6H""", True), ("""AS AH 2H AD AC""", False), ("""2H 3H 5H 6H 7H""", True), ("""KS AS TS QS JS""", True), ("""8H 9H QS JS TH""", False), ("""AS 3S 4S 8S 2S""", True), ) __lowerCamelCase : Tuple = ( ("""2H 3H 4H 5H 6H""", True), ("""AS AH 2H AD AC""", False), ("""2H 3H 5H 6H 7H""", False), ("""KS AS TS QS JS""", True), ("""8H 9H QS JS TH""", True), ) __lowerCamelCase : List[Any] = ( ("""2H 4D 3C AS 5S""", True, [5, 4, 3, 2, 14]), ("""2H 5D 3C AS 5S""", False, [14, 5, 5, 3, 2]), ("""JH QD KC AS TS""", False, [14, 13, 12, 11, 10]), ("""9D 3S 2C 7S 7C""", False, [9, 7, 7, 3, 2]), ) __lowerCamelCase : Any = ( ("""JH AH TH KH QH""", 0), ("""JH 9H TH KH QH""", 0), ("""JC KH JS JD JH""", 7), ("""KH KC 3S 3H 3D""", 6), ("""8C 9C 5C 3C TC""", 0), ("""JS QS 9H TS KH""", 0), ("""7C 7S KH 2H 7H""", 3), ("""3C KH 5D 5S KH""", 2), ("""QH 8H KD JH 8S""", 1), ("""2D 6D 9D TH 7D""", 0), ) __lowerCamelCase : Tuple = ( ("""JH AH TH KH QH""", 23), ("""JH 9H TH KH QH""", 22), ("""JC KH JS JD JH""", 21), ("""KH KC 3S 3H 3D""", 20), ("""8C 9C 5C 3C TC""", 19), ("""JS QS 9H TS KH""", 18), ("""7C 7S KH 2H 7H""", 17), ("""3C KH 5D 5S KH""", 16), ("""QH 8H KD JH 8S""", 15), ("""2D 6D 9D TH 7D""", 14), ) def A__ ( ): '''simple docstring''' snake_case__ , snake_case__ : Any =randrange(len(_a ) ), randrange(len(_a ) ) snake_case__ : Tuple =["""Loss""", """Tie""", """Win"""][(play >= oppo) + (play > oppo)] snake_case__ , snake_case__ : Union[str, Any] =SORTED_HANDS[play], SORTED_HANDS[oppo] return hand, other, expected def A__ ( _a : int = 100 ): '''simple docstring''' return (generate_random_hand() for _ in range(_a )) @pytest.mark.parametrize("""hand, expected""" , _a ) def A__ ( _a : List[Any] , _a : Any ): '''simple docstring''' assert PokerHand(_a )._is_flush() == expected @pytest.mark.parametrize("""hand, expected""" , _a ) def A__ ( _a : Union[str, Any] , _a : int ): '''simple docstring''' assert PokerHand(_a )._is_straight() == expected @pytest.mark.parametrize("""hand, expected, card_values""" , _a ) def A__ ( _a : Optional[int] , _a : Tuple , _a : Tuple ): '''simple docstring''' snake_case__ : Any =PokerHand(_a ) assert player._is_five_high_straight() == expected assert player._card_values == card_values @pytest.mark.parametrize("""hand, expected""" , _a ) def A__ ( _a : Any , _a : Tuple ): '''simple docstring''' assert PokerHand(_a )._is_same_kind() == expected @pytest.mark.parametrize("""hand, expected""" , _a ) def A__ ( _a : Union[str, Any] , _a : Tuple ): '''simple docstring''' assert PokerHand(_a )._hand_type == expected @pytest.mark.parametrize("""hand, other, expected""" , _a ) def A__ ( _a : str , _a : Tuple , _a : Union[str, Any] ): '''simple docstring''' assert PokerHand(_a ).compare_with(PokerHand(_a ) ) == expected @pytest.mark.parametrize("""hand, other, expected""" , generate_random_hands() ) def A__ ( _a : Any , _a : Optional[Any] , _a : str ): '''simple docstring''' assert PokerHand(_a ).compare_with(PokerHand(_a ) ) == expected def A__ ( ): '''simple docstring''' snake_case__ : str =[PokerHand(_a ) for hand in SORTED_HANDS] snake_case__ : List[str] =poker_hands.copy() shuffle(_a ) snake_case__ : Any =chain(sorted(_a ) ) for index, hand in enumerate(_a ): assert hand == poker_hands[index] def A__ ( ): '''simple docstring''' snake_case__ : Tuple =[PokerHand("""2D AC 3H 4H 5S""" ), PokerHand("""2S 3H 4H 5S 6C""" )] pokerhands.sort(reverse=_a ) assert pokerhands[0].__str__() == "2S 3H 4H 5S 6C" def A__ ( ): '''simple docstring''' snake_case__ : Optional[int] =PokerHand("""2C 4S AS 3D 5C""" ) snake_case__ : Optional[Any] =True snake_case__ : Any =[5, 4, 3, 2, 14] for _ in range(10 ): assert pokerhand._is_five_high_straight() == expected assert pokerhand._card_values == expected_card_values def A__ ( ): '''simple docstring''' snake_case__ : Tuple =0 snake_case__ : int =os.path.abspath(os.path.dirname(_a ) ) snake_case__ : List[Any] =os.path.join(_a , """poker_hands.txt""" ) with open(_a ) as file_hand: for line in file_hand: snake_case__ : List[Any] =line[:14].strip() snake_case__ : Any =line[15:].strip() snake_case__ , snake_case__ : str =PokerHand(_a ), PokerHand(_a ) snake_case__ : Optional[Any] =player.compare_with(_a ) if output == "Win": answer += 1 assert answer == 376
385
1
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = { '''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 A_ ( __lowerCamelCase ): '''simple docstring''' _UpperCamelCase : Dict = """big_bird""" def __init__( self , snake_case=5_0358 , snake_case=768 , snake_case=12 , snake_case=12 , snake_case=3072 , snake_case="gelu_new" , snake_case=0.1 , snake_case=0.1 , snake_case=4096 , snake_case=2 , snake_case=0.02 , snake_case=1E-12 , snake_case=True , snake_case=0 , snake_case=1 , snake_case=2 , snake_case=66 , snake_case="block_sparse" , snake_case=True , snake_case=False , snake_case=64 , snake_case=3 , snake_case=None , **snake_case , ): super().__init__( pad_token_id=snake_case , bos_token_id=snake_case , eos_token_id=snake_case , sep_token_id=snake_case , **snake_case , ) lowercase = vocab_size lowercase = max_position_embeddings lowercase = hidden_size lowercase = num_hidden_layers lowercase = num_attention_heads lowercase = intermediate_size lowercase = hidden_act lowercase = hidden_dropout_prob lowercase = attention_probs_dropout_prob lowercase = initializer_range lowercase = type_vocab_size lowercase = layer_norm_eps lowercase = use_cache lowercase = rescale_embeddings lowercase = attention_type lowercase = use_bias lowercase = block_size lowercase = num_random_blocks lowercase = classifier_dropout class A_ ( __lowerCamelCase ): '''simple docstring''' @property def SCREAMING_SNAKE_CASE__ ( self ): if self.task == "multiple-choice": lowercase = {0: 'batch', 1: 'choice', 2: 'sequence'} else: lowercase = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
565
from bisect import bisect from itertools import accumulate def UpperCAmelCase_ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase = sorted(zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) , key=lambda __SCREAMING_SNAKE_CASE : x[0] / x[1] , reverse=__SCREAMING_SNAKE_CASE ) lowercase , lowercase = [i[0] for i in r], [i[1] for i in r] lowercase = list(accumulate(__SCREAMING_SNAKE_CASE ) ) lowercase = bisect(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) return ( 0 if k == 0 else sum(vl[:k] ) + (w - acc[k - 1]) * (vl[k]) / (wt[k]) if k != n else sum(vl[:k] ) ) if __name__ == "__main__": import doctest doctest.testmod()
565
1
"""simple docstring""" from typing import List, Optional, Tuple, Union import torch from torch import nn from torch.nn import CrossEntropyLoss from ... import AutoBackbone from ...modeling_outputs import SemanticSegmenterOutput from ...modeling_utils import PreTrainedModel from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, replace_return_docstrings from ...utils.backbone_utils import BackboneMixin from .configuration_upernet import UperNetConfig SCREAMING_SNAKE_CASE_ = [ 'openmmlab/upernet-convnext-tiny', # See all UperNet models at https://huggingface.co/models?filter=upernet ] # General docstring SCREAMING_SNAKE_CASE_ = 'UperNetConfig' class snake_case_ ( nn.Module ): """simple docstring""" def __init__( self , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ = 0 , lowerCamelCase_ = False , lowerCamelCase_ = 1 , ) -> None: super().__init__() UpperCamelCase = nn.Convad( in_channels=lowerCamelCase_ , out_channels=lowerCamelCase_ , kernel_size=lowerCamelCase_ , padding=lowerCamelCase_ , bias=lowerCamelCase_ , dilation=lowerCamelCase_ , ) UpperCamelCase = nn.BatchNormad(lowerCamelCase_) UpperCamelCase = nn.ReLU() def UpperCAmelCase__ ( self , lowerCamelCase_) -> torch.Tensor: UpperCamelCase = self.conv(lowerCamelCase_) UpperCamelCase = self.batch_norm(lowerCamelCase_) UpperCamelCase = self.activation(lowerCamelCase_) return output class snake_case_ ( nn.Module ): """simple docstring""" def __init__( self , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_) -> None: super().__init__() UpperCamelCase = [ nn.AdaptiveAvgPoolad(lowerCamelCase_), UperNetConvModule(lowerCamelCase_ , lowerCamelCase_ , kernel_size=1), ] for i, layer in enumerate(self.layers): self.add_module(str(lowerCamelCase_) , lowerCamelCase_) def UpperCAmelCase__ ( self , lowerCamelCase_) -> torch.Tensor: UpperCamelCase = input for layer in self.layers: UpperCamelCase = layer(lowerCamelCase_) return hidden_state class snake_case_ ( nn.Module ): """simple docstring""" def __init__( self , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_) -> None: super().__init__() UpperCamelCase = pool_scales UpperCamelCase = align_corners UpperCamelCase = in_channels UpperCamelCase = channels UpperCamelCase = [] for i, pool_scale in enumerate(lowerCamelCase_): UpperCamelCase = UperNetPyramidPoolingBlock(pool_scale=lowerCamelCase_ , in_channels=lowerCamelCase_ , channels=lowerCamelCase_) self.blocks.append(lowerCamelCase_) self.add_module(str(lowerCamelCase_) , lowerCamelCase_) def UpperCAmelCase__ ( self , lowerCamelCase_) -> List[torch.Tensor]: UpperCamelCase = [] for ppm in self.blocks: UpperCamelCase = ppm(lowerCamelCase_) UpperCamelCase = nn.functional.interpolate( lowerCamelCase_ , size=x.size()[2:] , mode='''bilinear''' , align_corners=self.align_corners) ppm_outs.append(lowerCamelCase_) return ppm_outs class snake_case_ ( nn.Module ): """simple docstring""" def __init__( self , lowerCamelCase_ , lowerCamelCase_) -> Any: super().__init__() UpperCamelCase = config UpperCamelCase = config.pool_scales # e.g. (1, 2, 3, 6) UpperCamelCase = in_channels UpperCamelCase = config.hidden_size UpperCamelCase = False UpperCamelCase = nn.Convad(self.channels , config.num_labels , kernel_size=1) # PSP Module UpperCamelCase = UperNetPyramidPoolingModule( self.pool_scales , self.in_channels[-1] , self.channels , align_corners=self.align_corners , ) UpperCamelCase = UperNetConvModule( self.in_channels[-1] + len(self.pool_scales) * self.channels , self.channels , kernel_size=3 , padding=1 , ) # FPN Module UpperCamelCase = nn.ModuleList() UpperCamelCase = nn.ModuleList() for in_channels in self.in_channels[:-1]: # skip the top layer UpperCamelCase = UperNetConvModule(lowerCamelCase_ , self.channels , kernel_size=1) UpperCamelCase = UperNetConvModule(self.channels , self.channels , kernel_size=3 , padding=1) self.lateral_convs.append(lowerCamelCase_) self.fpn_convs.append(lowerCamelCase_) UpperCamelCase = UperNetConvModule( len(self.in_channels) * self.channels , self.channels , kernel_size=3 , padding=1 , ) def UpperCAmelCase__ ( self) -> Union[str, Any]: self.apply(self._init_weights) def UpperCAmelCase__ ( self , lowerCamelCase_) -> Union[str, Any]: if isinstance(lowerCamelCase_ , nn.Convad): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range) if module.bias is not None: module.bias.data.zero_() def UpperCAmelCase__ ( self , lowerCamelCase_) -> Tuple: UpperCamelCase = inputs[-1] UpperCamelCase = [x] psp_outs.extend(self.psp_modules(lowerCamelCase_)) UpperCamelCase = torch.cat(lowerCamelCase_ , dim=1) UpperCamelCase = self.bottleneck(lowerCamelCase_) return output def UpperCAmelCase__ ( self , lowerCamelCase_) -> torch.Tensor: # build laterals UpperCamelCase = [lateral_conv(encoder_hidden_states[i]) for i, lateral_conv in enumerate(self.lateral_convs)] laterals.append(self.psp_forward(lowerCamelCase_)) # build top-down path UpperCamelCase = len(lowerCamelCase_) for i in range(used_backbone_levels - 1 , 0 , -1): UpperCamelCase = laterals[i - 1].shape[2:] UpperCamelCase = laterals[i - 1] + nn.functional.interpolate( laterals[i] , size=lowerCamelCase_ , mode='''bilinear''' , align_corners=self.align_corners) # build outputs UpperCamelCase = [self.fpn_convs[i](laterals[i]) for i in range(used_backbone_levels - 1)] # append psp feature fpn_outs.append(laterals[-1]) for i in range(used_backbone_levels - 1 , 0 , -1): UpperCamelCase = nn.functional.interpolate( fpn_outs[i] , size=fpn_outs[0].shape[2:] , mode='''bilinear''' , align_corners=self.align_corners) UpperCamelCase = torch.cat(lowerCamelCase_ , dim=1) UpperCamelCase = self.fpn_bottleneck(lowerCamelCase_) UpperCamelCase = self.classifier(lowerCamelCase_) return output class snake_case_ ( nn.Module ): """simple docstring""" def __init__( self , lowerCamelCase_ , lowerCamelCase_ = 2 , lowerCamelCase_ = 3 , lowerCamelCase_ = 1) -> None: super().__init__() UpperCamelCase = config UpperCamelCase = config.auxiliary_in_channels UpperCamelCase = config.auxiliary_channels UpperCamelCase = config.auxiliary_num_convs UpperCamelCase = config.auxiliary_concat_input UpperCamelCase = in_index UpperCamelCase = (kernel_size // 2) * dilation UpperCamelCase = [] convs.append( UperNetConvModule( self.in_channels , self.channels , kernel_size=lowerCamelCase_ , padding=lowerCamelCase_ , dilation=lowerCamelCase_)) for i in range(self.num_convs - 1): convs.append( UperNetConvModule( self.channels , self.channels , kernel_size=lowerCamelCase_ , padding=lowerCamelCase_ , dilation=lowerCamelCase_)) if self.num_convs == 0: UpperCamelCase = nn.Identity() else: UpperCamelCase = nn.Sequential(*lowerCamelCase_) if self.concat_input: UpperCamelCase = UperNetConvModule( self.in_channels + self.channels , self.channels , kernel_size=lowerCamelCase_ , padding=kernel_size // 2) UpperCamelCase = nn.Convad(self.channels , config.num_labels , kernel_size=1) def UpperCAmelCase__ ( self) -> Optional[int]: self.apply(self._init_weights) def UpperCAmelCase__ ( self , lowerCamelCase_) -> Any: if isinstance(lowerCamelCase_ , nn.Convad): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range) if module.bias is not None: module.bias.data.zero_() def UpperCAmelCase__ ( self , lowerCamelCase_) -> torch.Tensor: # just take the relevant feature maps UpperCamelCase = encoder_hidden_states[self.in_index] UpperCamelCase = self.convs(lowerCamelCase_) if self.concat_input: UpperCamelCase = self.conv_cat(torch.cat([hidden_states, output] , dim=1)) UpperCamelCase = self.classifier(lowerCamelCase_) return output class snake_case_ ( lowerCamelCase_ ): """simple docstring""" A_ = UperNetConfig A_ = '''pixel_values''' A_ = True def UpperCAmelCase__ ( self , lowerCamelCase_) -> List[str]: if isinstance(lowerCamelCase_ , lowerCamelCase_): module.backbone.init_weights() module.decode_head.init_weights() module.auxiliary_head.init_weights() def UpperCAmelCase__ ( self) -> List[Any]: self.backbone.init_weights() self.decode_head.init_weights() self.auxiliary_head.init_weights() def UpperCAmelCase__ ( self , lowerCamelCase_ , lowerCamelCase_=False) -> str: if isinstance(lowerCamelCase_ , lowerCamelCase_): UpperCamelCase = value SCREAMING_SNAKE_CASE_ = R'\n Parameters:\n This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use\n it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n behavior.\n config ([`UperNetConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n' SCREAMING_SNAKE_CASE_ = R'\n Args:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using\n [`AutoImageProcessor`]. See [`SegformerImageProcessor.__call__`] for details.\n output_attentions (`bool`, *optional*):\n Whether or not to return the attentions tensors of all attention layers in case the backbone has them. See\n `attentions` under returned tensors for more detail.\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers of the backbone. See `hidden_states` under\n returned tensors for more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n' @add_start_docstrings( '''UperNet framework leveraging any vision backbone e.g. for ADE20k, CityScapes.''' , lowerCamelCase_ , ) class snake_case_ ( lowerCamelCase_ ): """simple docstring""" def __init__( self , lowerCamelCase_) -> int: super().__init__(lowerCamelCase_) UpperCamelCase = AutoBackbone.from_config(config.backbone_config) # Semantic segmentation head(s) UpperCamelCase = UperNetHead(lowerCamelCase_ , in_channels=self.backbone.channels) UpperCamelCase = UperNetFCNHead(lowerCamelCase_) if config.use_auxiliary_head else None # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(UPERNET_INPUTS_DOCSTRING.format('''batch_size, sequence_length''')) @replace_return_docstrings(output_type=lowerCamelCase_ , config_class=_CONFIG_FOR_DOC) def UpperCAmelCase__ ( self , lowerCamelCase_ = None , lowerCamelCase_ = None , lowerCamelCase_ = None , lowerCamelCase_ = None , lowerCamelCase_ = None , ) -> Union[tuple, SemanticSegmenterOutput]: UpperCamelCase = return_dict if return_dict is not None else self.config.use_return_dict UpperCamelCase = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) UpperCamelCase = output_attentions if output_attentions is not None else self.config.output_attentions UpperCamelCase = self.backbone.forward_with_filtered_kwargs( lowerCamelCase_ , output_hidden_states=lowerCamelCase_ , output_attentions=lowerCamelCase_) UpperCamelCase = outputs.feature_maps UpperCamelCase = self.decode_head(lowerCamelCase_) UpperCamelCase = nn.functional.interpolate(lowerCamelCase_ , size=pixel_values.shape[2:] , mode='''bilinear''' , align_corners=lowerCamelCase_) UpperCamelCase = None if self.auxiliary_head is not None: UpperCamelCase = self.auxiliary_head(lowerCamelCase_) UpperCamelCase = nn.functional.interpolate( lowerCamelCase_ , size=pixel_values.shape[2:] , mode='''bilinear''' , align_corners=lowerCamelCase_) UpperCamelCase = None if labels is not None: if self.config.num_labels == 1: raise ValueError('''The number of labels should be greater than one''') else: # compute weighted loss UpperCamelCase = CrossEntropyLoss(ignore_index=self.config.loss_ignore_index) UpperCamelCase = loss_fct(lowerCamelCase_ , lowerCamelCase_) UpperCamelCase = loss_fct(lowerCamelCase_ , lowerCamelCase_) UpperCamelCase = main_loss + self.config.auxiliary_loss_weight * auxiliary_loss if not return_dict: if output_hidden_states: UpperCamelCase = (logits,) + outputs[1:] else: UpperCamelCase = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return SemanticSegmenterOutput( loss=lowerCamelCase_ , logits=lowerCamelCase_ , hidden_states=outputs.hidden_states , attentions=outputs.attentions , )
34
"""simple docstring""" import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import SPIECE_UNDERLINE, logging SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_ = {'vocab_file': 'spiece.model'} SCREAMING_SNAKE_CASE_ = { 'vocab_file': { 'xlnet-base-cased': 'https://huggingface.co/xlnet-base-cased/resolve/main/spiece.model', 'xlnet-large-cased': 'https://huggingface.co/xlnet-large-cased/resolve/main/spiece.model', } } SCREAMING_SNAKE_CASE_ = { 'xlnet-base-cased': None, 'xlnet-large-cased': None, } # Segments (not really needed) SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = 1 SCREAMING_SNAKE_CASE_ = 2 SCREAMING_SNAKE_CASE_ = 3 SCREAMING_SNAKE_CASE_ = 4 class snake_case_ ( lowerCamelCase_ ): """simple docstring""" A_ = VOCAB_FILES_NAMES A_ = PRETRAINED_VOCAB_FILES_MAP A_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A_ = '''left''' def __init__( self , lowerCamelCase_ , lowerCamelCase_=False , lowerCamelCase_=True , lowerCamelCase_=False , lowerCamelCase_="<s>" , lowerCamelCase_="</s>" , lowerCamelCase_="<unk>" , lowerCamelCase_="<sep>" , lowerCamelCase_="<pad>" , lowerCamelCase_="<cls>" , lowerCamelCase_="<mask>" , lowerCamelCase_=["<eop>", "<eod>"] , lowerCamelCase_ = None , **lowerCamelCase_ , ) -> None: # Mask token behave like a normal word, i.e. include the space before it UpperCamelCase = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_) if isinstance(lowerCamelCase_ , lowerCamelCase_) else mask_token UpperCamelCase = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=lowerCamelCase_ , remove_space=lowerCamelCase_ , keep_accents=lowerCamelCase_ , bos_token=lowerCamelCase_ , eos_token=lowerCamelCase_ , unk_token=lowerCamelCase_ , sep_token=lowerCamelCase_ , pad_token=lowerCamelCase_ , cls_token=lowerCamelCase_ , mask_token=lowerCamelCase_ , additional_special_tokens=lowerCamelCase_ , sp_model_kwargs=self.sp_model_kwargs , **lowerCamelCase_ , ) UpperCamelCase = 3 UpperCamelCase = do_lower_case UpperCamelCase = remove_space UpperCamelCase = keep_accents UpperCamelCase = vocab_file UpperCamelCase = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(lowerCamelCase_) @property def UpperCAmelCase__ ( self) -> List[str]: return len(self.sp_model) def UpperCAmelCase__ ( self) -> Tuple: UpperCamelCase = {self.convert_ids_to_tokens(lowerCamelCase_): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def __getstate__( self) -> Any: UpperCamelCase = self.__dict__.copy() UpperCamelCase = None return state def __setstate__( self , lowerCamelCase_) -> str: UpperCamelCase = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs'''): UpperCamelCase = {} UpperCamelCase = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(self.vocab_file) def UpperCAmelCase__ ( self , lowerCamelCase_) -> Union[str, Any]: if self.remove_space: UpperCamelCase = ''' '''.join(inputs.strip().split()) else: UpperCamelCase = inputs UpperCamelCase = outputs.replace('''``''' , '''"''').replace('''\'\'''' , '''"''') if not self.keep_accents: UpperCamelCase = unicodedata.normalize('''NFKD''' , lowerCamelCase_) UpperCamelCase = ''''''.join([c for c in outputs if not unicodedata.combining(lowerCamelCase_)]) if self.do_lower_case: UpperCamelCase = outputs.lower() return outputs def UpperCAmelCase__ ( self , lowerCamelCase_) -> List[str]: UpperCamelCase = self.preprocess_text(lowerCamelCase_) UpperCamelCase = self.sp_model.encode(lowerCamelCase_ , out_type=lowerCamelCase_) UpperCamelCase = [] for piece in pieces: if len(lowerCamelCase_) > 1 and piece[-1] == str(''',''') and piece[-2].isdigit(): UpperCamelCase = self.sp_model.EncodeAsPieces(piece[:-1].replace(lowerCamelCase_ , '''''')) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0]) == 1: UpperCamelCase = cur_pieces[1:] else: UpperCamelCase = cur_pieces[0][1:] cur_pieces.append(piece[-1]) new_pieces.extend(lowerCamelCase_) else: new_pieces.append(lowerCamelCase_) return new_pieces def UpperCAmelCase__ ( self , lowerCamelCase_) -> int: return self.sp_model.PieceToId(lowerCamelCase_) def UpperCAmelCase__ ( self , lowerCamelCase_) -> Optional[int]: return self.sp_model.IdToPiece(lowerCamelCase_) def UpperCAmelCase__ ( self , lowerCamelCase_) -> Dict: UpperCamelCase = ''''''.join(lowerCamelCase_).replace(lowerCamelCase_ , ''' ''').strip() return out_string def UpperCAmelCase__ ( self , lowerCamelCase_ , lowerCamelCase_ = False , lowerCamelCase_ = None , lowerCamelCase_ = True , **lowerCamelCase_ , ) -> str: UpperCamelCase = kwargs.pop('''use_source_tokenizer''' , lowerCamelCase_) UpperCamelCase = self.convert_ids_to_tokens(lowerCamelCase_ , skip_special_tokens=lowerCamelCase_) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 UpperCamelCase = [] UpperCamelCase = [] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(lowerCamelCase_)) UpperCamelCase = [] sub_texts.append(lowerCamelCase_) else: current_sub_text.append(lowerCamelCase_) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(lowerCamelCase_)) # Mimic the behavior of the Rust tokenizer: # By default, there are no spaces between special tokens UpperCamelCase = ''''''.join(lowerCamelCase_) UpperCamelCase = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: UpperCamelCase = self.clean_up_tokenization(lowerCamelCase_) return clean_text else: return text def UpperCAmelCase__ ( self , lowerCamelCase_ , lowerCamelCase_ = None) -> List[int]: UpperCamelCase = [self.sep_token_id] UpperCamelCase = [self.cls_token_id] if token_ids_a is None: return token_ids_a + sep + cls return token_ids_a + sep + token_ids_a + sep + cls def UpperCAmelCase__ ( self , lowerCamelCase_ , lowerCamelCase_ = None , lowerCamelCase_ = False) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=lowerCamelCase_ , token_ids_a=lowerCamelCase_ , already_has_special_tokens=lowerCamelCase_) if token_ids_a is not None: return ([0] * len(lowerCamelCase_)) + [1] + ([0] * len(lowerCamelCase_)) + [1, 1] return ([0] * len(lowerCamelCase_)) + [1, 1] def UpperCAmelCase__ ( self , lowerCamelCase_ , lowerCamelCase_ = None) -> List[int]: UpperCamelCase = [self.sep_token_id] UpperCamelCase = [2] if token_ids_a is None: return len(token_ids_a + sep) * [0] + cls_segment_id return len(token_ids_a + sep) * [0] + len(token_ids_a + sep) * [1] + cls_segment_id def UpperCAmelCase__ ( self , lowerCamelCase_ , lowerCamelCase_ = None) -> Tuple[str]: if not os.path.isdir(lowerCamelCase_): logger.error(F'Vocabulary path ({save_directory}) should be a directory') return UpperCamelCase = os.path.join( lowerCamelCase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']) if os.path.abspath(self.vocab_file) != os.path.abspath(lowerCamelCase_) and os.path.isfile(self.vocab_file): copyfile(self.vocab_file , lowerCamelCase_) elif not os.path.isfile(self.vocab_file): with open(lowerCamelCase_ , '''wb''') as fi: UpperCamelCase = self.sp_model.serialized_model_proto() fi.write(lowerCamelCase_) return (out_vocab_file,)
34
1
SCREAMING_SNAKE_CASE : Union[str, Any] = """\n# Installazione di Transformers\n! pip install transformers datasets\n# Per installare dalla fonte invece dell'ultima versione rilasciata, commenta il comando sopra e\n# rimuovi la modalità commento al comando seguente.\n# ! pip install git+https://github.com/huggingface/transformers.git\n""" SCREAMING_SNAKE_CASE : Dict = [{"""type""": """code""", """content""": INSTALL_CONTENT}] SCREAMING_SNAKE_CASE : List[Any] = { """{processor_class}""": """FakeProcessorClass""", """{model_class}""": """FakeModelClass""", """{object_class}""": """FakeObjectClass""", }
707
import argparse import re from typing import Dict import torch from datasets import Audio, Dataset, load_dataset, load_metric from transformers import AutoFeatureExtractor, pipeline def __A ( _A , _A ): """simple docstring""" __a = args.log_outputs __a = "_".join(args.dataset.split("/" ) + [args.config, args.split] ) # load metric __a = load_metric("wer" ) __a = load_metric("cer" ) # compute metrics __a = wer.compute(references=result["target"] , predictions=result["prediction"] ) __a = cer.compute(references=result["target"] , predictions=result["prediction"] ) # print & log results __a = f"""WER: {wer_result}\nCER: {cer_result}""" print(_A ) with open(f"""{dataset_id}_eval_results.txt""" , "w" ) as f: f.write(_A ) # log all results in text file. Possibly interesting for analysis if log_outputs is not None: __a = f"""log_{dataset_id}_predictions.txt""" __a = f"""log_{dataset_id}_targets.txt""" with open(_A , "w" ) as p, open(_A , "w" ) as t: # mapping function to write output def write_to_file(_A , _A ): p.write(f"""{i}""" + "\n" ) p.write(batch["prediction"] + "\n" ) t.write(f"""{i}""" + "\n" ) t.write(batch["target"] + "\n" ) result.map(_A , with_indices=_A ) def __A ( _A ): """simple docstring""" __a = "[,?.!\-\;\:\"“%‘”�—’…–]" # noqa: W605 IMPORTANT: this should correspond to the chars that were ignored during training __a = re.sub(_A , "" , text.lower() ) # In addition, we can normalize the target text, e.g. removing new lines characters etc... # note that order is important here! __a = ["\n\n", "\n", " ", " "] for t in token_sequences_to_ignore: __a = " ".join(text.split(_A ) ) return text def __A ( _A ): """simple docstring""" __a = load_dataset(args.dataset , args.config , split=args.split , use_auth_token=_A ) # for testing: only process the first two examples as a test # dataset = dataset.select(range(10)) # load processor __a = AutoFeatureExtractor.from_pretrained(args.model_id ) __a = feature_extractor.sampling_rate # resample audio __a = dataset.cast_column("audio" , Audio(sampling_rate=_A ) ) # load eval pipeline if args.device is None: __a = 0 if torch.cuda.is_available() else -1 __a = pipeline("automatic-speech-recognition" , model=args.model_id , device=args.device ) # map function to decode audio def map_to_pred(_A ): __a = asr( batch["audio"]["array"] , chunk_length_s=args.chunk_length_s , stride_length_s=args.stride_length_s ) __a = prediction["text"] __a = normalize_text(batch["sentence"] ) return batch # run inference on all examples __a = dataset.map(_A , remove_columns=dataset.column_names ) # compute and log_results # do not change function below log_results(_A , _A ) if __name__ == "__main__": SCREAMING_SNAKE_CASE : Any = argparse.ArgumentParser() parser.add_argument( """--model_id""", type=str, required=True, help="""Model identifier. Should be loadable with 🤗 Transformers""" ) parser.add_argument( """--dataset""", type=str, required=True, help="""Dataset name to evaluate the `model_id`. Should be loadable with 🤗 Datasets""", ) parser.add_argument( """--config""", type=str, required=True, help="""Config of the dataset. *E.g.* `'en'` for Common Voice""" ) parser.add_argument("""--split""", type=str, required=True, help="""Split of the dataset. *E.g.* `'test'`""") parser.add_argument( """--chunk_length_s""", type=float, default=None, help="""Chunk length in seconds. Defaults to 5 seconds.""" ) parser.add_argument( """--stride_length_s""", type=float, default=None, help="""Stride of the audio chunks. Defaults to 1 second.""" ) parser.add_argument( """--log_outputs""", action="""store_true""", help="""If defined, write outputs to log file for analysis.""" ) parser.add_argument( """--device""", type=int, default=None, help="""The device to run the pipeline on. -1 for CPU (default), 0 for the first GPU and so on.""", ) SCREAMING_SNAKE_CASE : Optional[Any] = parser.parse_args() main(args)
525
0
class _a : '''simple docstring''' def __init__( self , __UpperCAmelCase ): __A : Optional[Any] = n __A : Optional[int] = [None] * self.n __A : Optional[int] = 0 # index of the first element __A : Any = 0 __A : Any = 0 def __len__( self ): return self.size def __UpperCAmelCase( self ): return self.size == 0 def __UpperCAmelCase( self ): return False if self.is_empty() else self.array[self.front] def __UpperCAmelCase( self , __UpperCAmelCase ): if self.size >= self.n: raise Exception("QUEUE IS FULL" ) __A : Tuple = data __A : List[Any] = (self.rear + 1) % self.n self.size += 1 return self def __UpperCAmelCase( self ): if self.size == 0: raise Exception("UNDERFLOW" ) __A : List[Any] = self.array[self.front] __A : str = None __A : Optional[Any] = (self.front + 1) % self.n self.size -= 1 return temp
520
from pickle import UnpicklingError import jax import jax.numpy as jnp import numpy as np from flax.serialization import from_bytes from flax.traverse_util import flatten_dict from ..utils import logging UpperCamelCase = logging.get_logger(__name__) def lowerCamelCase_ ( _lowercase , _lowercase ) -> Optional[int]: try: with open(_lowercase , "rb" ) as flax_state_f: __A : int = from_bytes(_lowercase , flax_state_f.read() ) except UnpicklingError as e: try: with open(_lowercase ) as f: if f.read().startswith("version" ): raise OSError( "You seem to have cloned a repository without having git-lfs installed. Please" " install git-lfs and run `git lfs install` followed by `git lfs pull` in the" " folder you cloned." ) else: raise ValueError from e except (UnicodeDecodeError, ValueError): raise EnvironmentError(F"Unable to convert {model_file} to Flax deserializable object. " ) return load_flax_weights_in_pytorch_model(_lowercase , _lowercase ) def lowerCamelCase_ ( _lowercase , _lowercase ) -> Optional[Any]: try: import torch # noqa: F401 except ImportError: logger.error( "Loading Flax weights in PyTorch requires both PyTorch and Flax to be installed. Please see" " https://pytorch.org/ and https://flax.readthedocs.io/en/latest/installation.html for installation" " instructions." ) raise # check if we have bf16 weights __A : Dict = flatten_dict(jax.tree_util.tree_map(lambda _lowercase : x.dtype == jnp.bfloataa , _lowercase ) ).values() if any(_lowercase ): # convert all weights to fp32 if they are bf16 since torch.from_numpy can-not handle bf16 # and bf16 is not fully supported in PT yet. logger.warning( "Found ``bfloat16`` weights in Flax model. Casting all ``bfloat16`` weights to ``float32`` " "before loading those in PyTorch model." ) __A : Any = jax.tree_util.tree_map( lambda _lowercase : params.astype(np.floataa ) if params.dtype == jnp.bfloataa else params , _lowercase ) __A : Union[str, Any] = "" __A : List[Any] = flatten_dict(_lowercase , sep="." ) __A : str = pt_model.state_dict() # keep track of unexpected & missing keys __A : Tuple = [] __A : List[Any] = set(pt_model_dict.keys() ) for flax_key_tuple, flax_tensor in flax_state_dict.items(): __A : List[Any] = flax_key_tuple.split("." ) if flax_key_tuple_array[-1] == "kernel" and flax_tensor.ndim == 4: __A : Dict = flax_key_tuple_array[:-1] + ["weight"] __A : List[str] = jnp.transpose(_lowercase , (3, 2, 0, 1) ) elif flax_key_tuple_array[-1] == "kernel": __A : str = flax_key_tuple_array[:-1] + ["weight"] __A : List[str] = flax_tensor.T elif flax_key_tuple_array[-1] == "scale": __A : Optional[int] = flax_key_tuple_array[:-1] + ["weight"] if "time_embedding" not in flax_key_tuple_array: for i, flax_key_tuple_string in enumerate(_lowercase ): __A : List[Any] = ( flax_key_tuple_string.replace("_0" , ".0" ) .replace("_1" , ".1" ) .replace("_2" , ".2" ) .replace("_3" , ".3" ) .replace("_4" , ".4" ) .replace("_5" , ".5" ) .replace("_6" , ".6" ) .replace("_7" , ".7" ) .replace("_8" , ".8" ) .replace("_9" , ".9" ) ) __A : Optional[int] = ".".join(_lowercase ) if flax_key in pt_model_dict: if flax_tensor.shape != pt_model_dict[flax_key].shape: raise ValueError( F"Flax checkpoint seems to be incorrect. Weight {flax_key_tuple} was expected " F"to be of shape {pt_model_dict[flax_key].shape}, but is {flax_tensor.shape}." ) else: # add weight to pytorch dict __A : str = np.asarray(_lowercase ) if not isinstance(_lowercase , np.ndarray ) else flax_tensor __A : Union[str, Any] = torch.from_numpy(_lowercase ) # remove from missing keys missing_keys.remove(_lowercase ) else: # weight is not expected by PyTorch model unexpected_keys.append(_lowercase ) pt_model.load_state_dict(_lowercase ) # re-transform missing_keys to list __A : Optional[Any] = list(_lowercase ) if len(_lowercase ) > 0: logger.warning( "Some weights of the Flax model were not used when initializing the PyTorch model" F" {pt_model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are initializing" F" {pt_model.__class__.__name__} from a Flax model trained on another task or with another architecture" " (e.g. initializing a BertForSequenceClassification model from a FlaxBertForPreTraining model).\n- This" F" IS NOT expected if you are initializing {pt_model.__class__.__name__} from a Flax model that you expect" " to be exactly identical (e.g. initializing a BertForSequenceClassification model from a" " FlaxBertForSequenceClassification model)." ) if len(_lowercase ) > 0: logger.warning( F"Some weights of {pt_model.__class__.__name__} were not initialized from the Flax model and are newly" F" initialized: {missing_keys}\nYou should probably TRAIN this model on a down-stream task to be able to" " use it for predictions and inference." ) return pt_model
520
1
"""simple docstring""" import os import tempfile import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from torch import nn from transformers import ( Adafactor, AdamW, get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_inverse_sqrt_schedule, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) def __UpperCAmelCase ( __lowerCamelCase , __lowerCamelCase=10 ) -> Any: lowercase__ : int = [] for _ in range(__lowerCamelCase ): lrs.append(scheduler.get_lr()[0] ) scheduler.step() return lrs def __UpperCAmelCase ( __lowerCamelCase , __lowerCamelCase=10 ) -> Optional[int]: lowercase__ : Dict = [] for step in range(__lowerCamelCase ): lrs.append(scheduler.get_lr()[0] ) scheduler.step() if step == num_steps // 2: with tempfile.TemporaryDirectory() as tmpdirname: lowercase__ : Optional[Any] = os.path.join(__lowerCamelCase , '''schedule.bin''' ) torch.save(scheduler.state_dict() , __lowerCamelCase ) lowercase__ : int = torch.load(__lowerCamelCase ) scheduler.load_state_dict(__lowerCamelCase ) return lrs @require_torch class __A ( unittest.TestCase ): def UpperCAmelCase ( self : str ,_snake_case : List[str] ,_snake_case : str ,_snake_case : Any ) -> List[Any]: """simple docstring""" self.assertEqual(len(_snake_case ) ,len(_snake_case ) ) for a, b in zip(_snake_case ,_snake_case ): self.assertAlmostEqual(_snake_case ,_snake_case ,delta=_snake_case ) def UpperCAmelCase ( self : List[str] ) -> str: """simple docstring""" lowercase__ : List[Any] = torch.tensor([0.1, -0.2, -0.1] ,requires_grad=_snake_case ) lowercase__ : Any = torch.tensor([0.4, 0.2, -0.5] ) lowercase__ : Tuple = nn.MSELoss() # No warmup, constant schedule, no gradient clipping lowercase__ : Union[str, Any] = AdamW(params=[w] ,lr=2e-1 ,weight_decay=0.0 ) for _ in range(100 ): lowercase__ : Tuple = criterion(_snake_case ,_snake_case ) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist() ,[0.4, 0.2, -0.5] ,tol=1e-2 ) def UpperCAmelCase ( self : List[str] ) -> List[str]: """simple docstring""" lowercase__ : str = torch.tensor([0.1, -0.2, -0.1] ,requires_grad=_snake_case ) lowercase__ : Union[str, Any] = torch.tensor([0.4, 0.2, -0.5] ) lowercase__ : int = nn.MSELoss() # No warmup, constant schedule, no gradient clipping lowercase__ : str = Adafactor( params=[w] ,lr=1e-2 ,eps=(1e-30, 1e-3) ,clip_threshold=1.0 ,decay_rate=-0.8 ,betaa=_snake_case ,weight_decay=0.0 ,relative_step=_snake_case ,scale_parameter=_snake_case ,warmup_init=_snake_case ,) for _ in range(1_000 ): lowercase__ : Tuple = criterion(_snake_case ,_snake_case ) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist() ,[0.4, 0.2, -0.5] ,tol=1e-2 ) @require_torch class __A ( unittest.TestCase ): lowerCAmelCase : List[str] = nn.Linear(5_0 ,5_0 ) if is_torch_available() else None lowerCAmelCase : Optional[Any] = AdamW(m.parameters() ,lr=10.0 ) if is_torch_available() else None lowerCAmelCase : List[str] = 1_0 def UpperCAmelCase ( self : Tuple ,_snake_case : List[Any] ,_snake_case : Union[str, Any] ,_snake_case : Any ,_snake_case : Optional[Any]=None ) -> str: """simple docstring""" self.assertEqual(len(_snake_case ) ,len(_snake_case ) ) for a, b in zip(_snake_case ,_snake_case ): self.assertAlmostEqual(_snake_case ,_snake_case ,delta=_snake_case ,msg=_snake_case ) def UpperCAmelCase ( self : Optional[Any] ) -> Any: """simple docstring""" lowercase__ : Any = {'''num_warmup_steps''': 2, '''num_training_steps''': 10} # schedulers doct format # function: (sched_args_dict, expected_learning_rates) lowercase__ : str = { get_constant_schedule: ({}, [10.0] * self.num_steps), get_constant_schedule_with_warmup: ( {'''num_warmup_steps''': 4}, [0.0, 2.5, 5.0, 7.5, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0], ), get_linear_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 10.0, 8.75, 7.5, 6.25, 5.0, 3.75, 2.5, 1.25], ), get_cosine_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 10.0, 9.61, 8.53, 6.91, 5.0, 3.08, 1.46, 0.38], ), get_cosine_with_hard_restarts_schedule_with_warmup: ( {**common_kwargs, '''num_cycles''': 2}, [0.0, 5.0, 10.0, 8.53, 5.0, 1.46, 10.0, 8.53, 5.0, 1.46], ), get_polynomial_decay_schedule_with_warmup: ( {**common_kwargs, '''power''': 2.0, '''lr_end''': 1e-7}, [0.0, 5.0, 10.0, 7.656, 5.625, 3.906, 2.5, 1.406, 0.625, 0.156], ), get_inverse_sqrt_schedule: ( {'''num_warmup_steps''': 2}, [0.0, 5.0, 10.0, 8.165, 7.071, 6.325, 5.774, 5.345, 5.0, 4.714], ), } for scheduler_func, data in scheds.items(): lowercase__ : int = data lowercase__ : List[Any] = scheduler_func(self.optimizer ,**_snake_case ) self.assertEqual(len([scheduler.get_lr()[0]] ) ,1 ) lowercase__ : List[str] = unwrap_schedule(_snake_case ,self.num_steps ) self.assertListAlmostEqual( _snake_case ,_snake_case ,tol=1e-2 ,msg=f"""failed for {scheduler_func} in normal scheduler""" ,) lowercase__ : Union[str, Any] = scheduler_func(self.optimizer ,**_snake_case ) if scheduler_func.__name__ != "get_constant_schedule": LambdaScheduleWrapper.wrap_scheduler(_snake_case ) # wrap to test picklability of the schedule lowercase__ : List[str] = unwrap_and_save_reload_schedule(_snake_case ,self.num_steps ) self.assertListEqual(_snake_case ,_snake_case ,msg=f"""failed for {scheduler_func} in save and reload""" ) class __A : def __init__( self : Optional[int] ,_snake_case : List[Any] ) -> Optional[int]: """simple docstring""" lowercase__ : List[str] = fn def __call__( self : Optional[Any] ,*_snake_case : Optional[int] ,**_snake_case : Optional[Any] ) -> str: """simple docstring""" return self.fn(*_snake_case ,**_snake_case ) @classmethod def UpperCAmelCase ( self : Dict ,_snake_case : Any ) -> Optional[int]: """simple docstring""" lowercase__ : Optional[Any] = list(map(self ,scheduler.lr_lambdas ) )
717
"""simple docstring""" import os import socket from contextlib import contextmanager import torch from ..commands.config.default import write_basic_config # noqa: F401 from ..state import PartialState from .dataclasses import DistributedType from .imports import is_deepspeed_available, is_tpu_available from .transformer_engine import convert_model from .versions import is_torch_version if is_deepspeed_available(): from deepspeed import DeepSpeedEngine if is_tpu_available(check_device=False): import torch_xla.core.xla_model as xm def __UpperCAmelCase ( __lowerCamelCase ) -> Optional[int]: if is_torch_version('''<''' , '''2.0.0''' ) or not hasattr(__lowerCamelCase , '''_dynamo''' ): return False return isinstance(__lowerCamelCase , torch._dynamo.eval_frame.OptimizedModule ) def __UpperCAmelCase ( __lowerCamelCase , __lowerCamelCase = True ) -> Optional[Any]: lowercase__ : List[Any] = (torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel) lowercase__ : str = is_compiled_module(__lowerCamelCase ) if is_compiled: lowercase__ : int = model lowercase__ : int = model._orig_mod if is_deepspeed_available(): options += (DeepSpeedEngine,) while isinstance(__lowerCamelCase , __lowerCamelCase ): lowercase__ : Union[str, Any] = model.module if not keep_fpaa_wrapper: lowercase__ : List[Any] = getattr(__lowerCamelCase , '''forward''' ) lowercase__ : Any = model.__dict__.pop('''_original_forward''' , __lowerCamelCase ) if original_forward is not None: while hasattr(__lowerCamelCase , '''__wrapped__''' ): lowercase__ : Optional[int] = forward.__wrapped__ if forward == original_forward: break lowercase__ : Dict = forward if getattr(__lowerCamelCase , '''_converted_to_transformer_engine''' , __lowerCamelCase ): convert_model(__lowerCamelCase , to_transformer_engine=__lowerCamelCase ) if is_compiled: lowercase__ : Optional[Any] = model lowercase__ : Tuple = compiled_model return model def __UpperCAmelCase ( ) -> int: PartialState().wait_for_everyone() def __UpperCAmelCase ( __lowerCamelCase , __lowerCamelCase ) -> str: if PartialState().distributed_type == DistributedType.TPU: xm.save(__lowerCamelCase , __lowerCamelCase ) elif PartialState().local_process_index == 0: torch.save(__lowerCamelCase , __lowerCamelCase ) @contextmanager def __UpperCAmelCase ( **__lowerCamelCase ) -> Optional[int]: for key, value in kwargs.items(): lowercase__ : Optional[int] = str(__lowerCamelCase ) yield for key in kwargs: if key.upper() in os.environ: del os.environ[key.upper()] def __UpperCAmelCase ( __lowerCamelCase ) -> Union[str, Any]: if not hasattr(__lowerCamelCase , '''__qualname__''' ) and not hasattr(__lowerCamelCase , '''__name__''' ): lowercase__ : Tuple = getattr(__lowerCamelCase , '''__class__''' , __lowerCamelCase ) if hasattr(__lowerCamelCase , '''__qualname__''' ): return obj.__qualname__ if hasattr(__lowerCamelCase , '''__name__''' ): return obj.__name__ return str(__lowerCamelCase ) def __UpperCAmelCase ( __lowerCamelCase , __lowerCamelCase ) -> int: for key, value in source.items(): if isinstance(__lowerCamelCase , __lowerCamelCase ): lowercase__ : int = destination.setdefault(__lowerCamelCase , {} ) merge_dicts(__lowerCamelCase , __lowerCamelCase ) else: lowercase__ : Optional[int] = value return destination def __UpperCAmelCase ( __lowerCamelCase = None ) -> bool: if port is None: lowercase__ : List[Any] = 2_95_00 with socket.socket(socket.AF_INET , socket.SOCK_STREAM ) as s: return s.connect_ex(('''localhost''', port) ) == 0
122
0
'''simple docstring''' import unittest from typing import Tuple import torch from diffusers.utils import floats_tensor, randn_tensor, torch_all_close, torch_device from diffusers.utils.testing_utils import require_torch @require_torch class __SCREAMING_SNAKE_CASE : @property def __UpperCamelCase ( self ) ->Tuple: '''simple docstring''' return self.get_dummy_input() @property def __UpperCamelCase ( self ) ->Optional[int]: '''simple docstring''' if self.block_type == "down": return (4, 32, 16, 16) elif self.block_type == "mid": return (4, 32, 32, 32) elif self.block_type == "up": return (4, 32, 64, 64) raise ValueError(F"""\'{self.block_type}\' is not a supported block_type. Set it to \'up\', \'mid\', or \'down\'.""" ) def __UpperCamelCase ( self , lowerCamelCase=True , lowerCamelCase=False , lowerCamelCase=False , lowerCamelCase=False , ) ->str: '''simple docstring''' __a = 4 __a = 32 __a = (32, 32) __a = torch.manual_seed(0 ) __a = torch.device(lowerCamelCase ) __a = (batch_size, num_channels) + sizes __a = randn_tensor(lowerCamelCase , generator=lowerCamelCase , device=lowerCamelCase ) __a = {'''hidden_states''': hidden_states} if include_temb: __a = 128 __a = randn_tensor((batch_size, temb_channels) , generator=lowerCamelCase , device=lowerCamelCase ) if include_res_hidden_states_tuple: __a = torch.manual_seed(1 ) __a = (randn_tensor(lowerCamelCase , generator=lowerCamelCase , device=lowerCamelCase ),) if include_encoder_hidden_states: __a = floats_tensor((batch_size, 32, 32) ).to(lowerCamelCase ) if include_skip_sample: __a = randn_tensor(((batch_size, 3) + sizes) , generator=lowerCamelCase , device=lowerCamelCase ) return dummy_input def __UpperCamelCase ( self ) ->Optional[Any]: '''simple docstring''' __a = { '''in_channels''': 32, '''out_channels''': 32, '''temb_channels''': 128, } if self.block_type == "up": __a = 32 if self.block_type == "mid": init_dict.pop('out_channels' ) __a = self.dummy_input return init_dict, inputs_dict def __UpperCamelCase ( self , lowerCamelCase ) ->List[str]: '''simple docstring''' __a = self.prepare_init_args_and_inputs_for_common() __a = self.block_class(**lowerCamelCase ) unet_block.to(lowerCamelCase ) unet_block.eval() with torch.no_grad(): __a = unet_block(**lowerCamelCase ) if isinstance(lowerCamelCase , lowerCamelCase ): __a = output[0] self.assertEqual(output.shape , self.output_shape ) __a = output[0, -1, -3:, -3:] __a = torch.tensor(lowerCamelCase ).to(lowerCamelCase ) assert torch_all_close(output_slice.flatten() , lowerCamelCase , atol=5e-3 ) @unittest.skipIf(torch_device == 'mps' , 'Training is not supported in mps' ) def __UpperCamelCase ( self ) ->Optional[int]: '''simple docstring''' __a = self.prepare_init_args_and_inputs_for_common() __a = self.block_class(**lowerCamelCase ) model.to(lowerCamelCase ) model.train() __a = model(**lowerCamelCase ) if isinstance(lowerCamelCase , lowerCamelCase ): __a = output[0] __a = torch.device(lowerCamelCase ) __a = randn_tensor(output.shape , device=lowerCamelCase ) __a = torch.nn.functional.mse_loss(lowerCamelCase , lowerCamelCase ) loss.backward()
448
from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('>=', '4.25.0')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import UnCLIPImageVariationPipeline, UnCLIPPipeline else: from .pipeline_unclip import UnCLIPPipeline from .pipeline_unclip_image_variation import UnCLIPImageVariationPipeline from .text_proj import UnCLIPTextProjModel
64
0
'''simple docstring''' from math import sqrt def a_ ( _UpperCAmelCase : int ) -> bool: if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 ,int(sqrt(_UpperCAmelCase ) + 1 ) ,6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def a_ ( _UpperCAmelCase : int = 1_00_01 ) -> int: __snake_case : List[Any] = 0 __snake_case : Optional[int] = 1 while count != nth and number < 3: number += 1 if is_prime(_UpperCAmelCase ): count += 1 while count != nth: number += 2 if is_prime(_UpperCAmelCase ): count += 1 return number if __name__ == "__main__": print(F"""{solution() = }""")
124
'''simple docstring''' A__ : str = '''ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/''' def a_ ( _UpperCAmelCase : bytes ) -> bytes: # Make sure the supplied data is a bytes-like object if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): __snake_case : int = f'''a bytes-like object is required, not \'{data.__class__.__name__}\'''' raise TypeError(_UpperCAmelCase ) __snake_case : Optional[int] = ''.join(bin(_UpperCAmelCase )[2:].zfill(8 ) for byte in data ) __snake_case : Optional[int] = len(_UpperCAmelCase ) % 6 != 0 if padding_needed: # The padding that will be added later __snake_case : Dict = b'=' * ((6 - len(_UpperCAmelCase ) % 6) // 2) # Append binary_stream with arbitrary binary digits (0's by default) to make its # length a multiple of 6. binary_stream += "0" * (6 - len(_UpperCAmelCase ) % 6) else: __snake_case : List[Any] = b'' # Encode every 6 binary digits to their corresponding Base64 character return ( "".join( B64_CHARSET[int(binary_stream[index : index + 6] ,2 )] for index in range(0 ,len(_UpperCAmelCase ) ,6 ) ).encode() + padding ) def a_ ( _UpperCAmelCase : str ) -> bytes: # Make sure encoded_data is either a string or a bytes-like object if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): __snake_case : List[Any] = ( 'argument should be a bytes-like object or ASCII string, ' f'''not \'{encoded_data.__class__.__name__}\'''' ) raise TypeError(_UpperCAmelCase ) # In case encoded_data is a bytes-like object, make sure it contains only # ASCII characters so we convert it to a string object if isinstance(_UpperCAmelCase ,_UpperCAmelCase ): try: __snake_case : Optional[int] = encoded_data.decode('utf-8' ) except UnicodeDecodeError: raise ValueError('base64 encoded data should only contain ASCII characters' ) __snake_case : List[Any] = encoded_data.count('=' ) # Check if the encoded string contains non base64 characters if padding: assert all( char in B64_CHARSET for char in encoded_data[:-padding] ), "Invalid base64 character(s) found." else: assert all( char in B64_CHARSET for char in encoded_data ), "Invalid base64 character(s) found." # Check the padding assert len(_UpperCAmelCase ) % 4 == 0 and padding < 3, "Incorrect padding" if padding: # Remove padding if there is one __snake_case : Any = encoded_data[:-padding] __snake_case : str = ''.join( bin(B64_CHARSET.index(_UpperCAmelCase ) )[2:].zfill(6 ) for char in encoded_data )[: -padding * 2] else: __snake_case : str = ''.join( bin(B64_CHARSET.index(_UpperCAmelCase ) )[2:].zfill(6 ) for char in encoded_data ) __snake_case : Tuple = [ int(binary_stream[index : index + 8] ,2 ) for index in range(0 ,len(_UpperCAmelCase ) ,8 ) ] return bytes(_UpperCAmelCase ) if __name__ == "__main__": import doctest doctest.testmod()
124
1
import os from pickle import UnpicklingError from typing import Dict, Tuple import jax import jax.numpy as jnp import numpy as np from flax.serialization import from_bytes from flax.traverse_util import flatten_dict, unflatten_dict import transformers from .utils import logging SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: Dict , lowerCAmelCase: Optional[int] , lowerCAmelCase: int , lowerCAmelCase: str=False ) -> Any: try: import torch # noqa: F401 except ImportError: logger.error( "Loading a PyTorch model in Flax, requires both PyTorch and Flax to be installed. Please see" " https://pytorch.org/ and https://flax.readthedocs.io/en/latest/installation.html for installation" " instructions." ) raise if not is_sharded: _UpperCAmelCase : Dict = os.path.abspath(lowerCAmelCase ) logger.info(F'Loading PyTorch weights from {pt_path}' ) _UpperCAmelCase : Dict = torch.load(lowerCAmelCase , map_location="cpu" ) logger.info(F'PyTorch checkpoint contains {sum(t.numel() for t in pt_state_dict.values() ):,} parameters.' ) _UpperCAmelCase : int = convert_pytorch_state_dict_to_flax(lowerCAmelCase , lowerCAmelCase ) else: # model is sharded and pytorch_checkpoint_path already contains the list of .pt shard files _UpperCAmelCase : List[Any] = convert_pytorch_sharded_state_dict_to_flax(lowerCAmelCase , lowerCAmelCase ) return flax_state_dict def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: Tuple[str] , lowerCAmelCase: np.ndarray , lowerCAmelCase: Dict[str, jnp.ndarray] , lowerCAmelCase: str , ) -> (Tuple[str], np.ndarray): def is_key_or_prefix_key_in_dict(lowerCAmelCase: Tuple[str] ) -> bool: return len(set(lowerCAmelCase ) & {key, (model_prefix,) + key} ) > 0 # layer norm _UpperCAmelCase : Any = pt_tuple_key[:-1] + ("scale",) if pt_tuple_key[-1] in ["weight", "gamma"] and is_key_or_prefix_key_in_dict(lowerCAmelCase ): return renamed_pt_tuple_key, pt_tensor # batch norm layer mean _UpperCAmelCase : int = pt_tuple_key[:-1] + ("mean",) if pt_tuple_key[-1] == "running_mean" and not is_key_or_prefix_key_in_dict(lowerCAmelCase ): return renamed_pt_tuple_key, pt_tensor # batch norm layer var _UpperCAmelCase : List[str] = pt_tuple_key[:-1] + ("var",) if pt_tuple_key[-1] == "running_var" and not is_key_or_prefix_key_in_dict(lowerCAmelCase ): return renamed_pt_tuple_key, pt_tensor # embedding _UpperCAmelCase : List[Any] = pt_tuple_key[:-1] + ("embedding",) if pt_tuple_key[-1] == "weight" and is_key_or_prefix_key_in_dict(lowerCAmelCase ): return renamed_pt_tuple_key, pt_tensor # conv layer _UpperCAmelCase : Optional[int] = pt_tuple_key[:-1] + ("kernel",) if pt_tuple_key[-1] == "weight" and pt_tensor.ndim == 4 and not is_key_or_prefix_key_in_dict(lowerCAmelCase ): _UpperCAmelCase : List[str] = pt_tensor.transpose(2 , 3 , 1 , 0 ) return renamed_pt_tuple_key, pt_tensor # linear layer _UpperCAmelCase : Dict = pt_tuple_key[:-1] + ("kernel",) if pt_tuple_key[-1] == "weight" and not is_key_or_prefix_key_in_dict(lowerCAmelCase ): _UpperCAmelCase : int = pt_tensor.T return renamed_pt_tuple_key, pt_tensor # old PyTorch layer norm weight _UpperCAmelCase : List[str] = pt_tuple_key[:-1] + ("weight",) if pt_tuple_key[-1] == "gamma": return renamed_pt_tuple_key, pt_tensor # old PyTorch layer norm bias _UpperCAmelCase : List[str] = pt_tuple_key[:-1] + ("bias",) if pt_tuple_key[-1] == "beta": return renamed_pt_tuple_key, pt_tensor # New `weight_norm` from https://github.com/huggingface/transformers/pull/24030 _UpperCAmelCase : List[Any] = None if pt_tuple_key[-3::2] == ("parametrizations", "original0"): _UpperCAmelCase : str = pt_tuple_key[-2] + "_g" elif pt_tuple_key[-3::2] == ("parametrizations", "original1"): _UpperCAmelCase : str = pt_tuple_key[-2] + "_v" if name is not None: _UpperCAmelCase : str = pt_tuple_key[:-3] + (name,) return renamed_pt_tuple_key, pt_tensor return pt_tuple_key, pt_tensor def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: Optional[int] , lowerCAmelCase: Optional[int] ) -> Optional[int]: # convert pytorch tensor to numpy _UpperCAmelCase : Optional[Any] = {k: v.numpy() for k, v in pt_state_dict.items()} _UpperCAmelCase : List[str] = flax_model.base_model_prefix # use params dict if the model contains batch norm layers if "params" in flax_model.params: _UpperCAmelCase : int = flax_model.params["params"] else: _UpperCAmelCase : str = flax_model.params _UpperCAmelCase : Tuple = flatten_dict(lowerCAmelCase ) # add batch_stats keys,values to dict if "batch_stats" in flax_model.params: _UpperCAmelCase : List[Any] = flatten_dict(flax_model.params["batch_stats"] ) random_flax_state_dict.update(lowerCAmelCase ) _UpperCAmelCase : List[Any] = {} _UpperCAmelCase : Any = (model_prefix not in flax_model_params) and ( model_prefix in {k.split("." )[0] for k in pt_state_dict.keys()} ) _UpperCAmelCase : Optional[int] = (model_prefix in flax_model_params) and ( model_prefix not in {k.split("." )[0] for k in pt_state_dict.keys()} ) # Need to change some parameters name to match Flax names for pt_key, pt_tensor in pt_state_dict.items(): _UpperCAmelCase : str = tuple(pt_key.split("." ) ) # remove base model prefix if necessary _UpperCAmelCase : Optional[Any] = pt_tuple_key[0] == model_prefix if load_model_with_head_into_base_model and has_base_model_prefix: _UpperCAmelCase : Any = pt_tuple_key[1:] # Correctly rename weight parameters _UpperCAmelCase , _UpperCAmelCase : str = rename_key_and_reshape_tensor( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) # add model prefix if necessary _UpperCAmelCase : Dict = (model_prefix,) + flax_key in random_flax_state_dict if load_base_model_into_model_with_head and require_base_model_prefix: _UpperCAmelCase : Dict = (model_prefix,) + flax_key if flax_key in random_flax_state_dict: if flax_tensor.shape != random_flax_state_dict[flax_key].shape: raise ValueError( F'PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape ' F'{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}.' ) # add batch stats if the model contains batchnorm layers if "batch_stats" in flax_model.params: if "mean" in flax_key[-1] or "var" in flax_key[-1]: _UpperCAmelCase : List[str] = jnp.asarray(lowerCAmelCase ) continue # remove num_batches_tracked key if "num_batches_tracked" in flax_key[-1]: flax_state_dict.pop(lowerCAmelCase , lowerCAmelCase ) continue # also add unexpected weight so that warning is thrown _UpperCAmelCase : Optional[Any] = jnp.asarray(lowerCAmelCase ) else: # also add unexpected weight so that warning is thrown _UpperCAmelCase : List[Any] = jnp.asarray(lowerCAmelCase ) return unflatten_dict(lowerCAmelCase ) def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: List[str] , lowerCAmelCase: List[str] ) -> Optional[int]: import torch # Load the index _UpperCAmelCase : List[Any] = {} for shard_file in shard_filenames: # load using msgpack utils _UpperCAmelCase : List[str] = torch.load(lowerCAmelCase ) _UpperCAmelCase : Union[str, Any] = {k: v.numpy() for k, v in pt_state_dict.items()} _UpperCAmelCase : List[str] = flax_model.base_model_prefix # use params dict if the model contains batch norm layers and then add batch_stats keys,values to dict if "batch_stats" in flax_model.params: _UpperCAmelCase : List[str] = flax_model.params["params"] _UpperCAmelCase : Tuple = flatten_dict(lowerCAmelCase ) random_flax_state_dict.update(flatten_dict(flax_model.params["batch_stats"] ) ) else: _UpperCAmelCase : int = flax_model.params _UpperCAmelCase : List[str] = flatten_dict(lowerCAmelCase ) _UpperCAmelCase : Dict = (model_prefix not in flax_model_params) and ( model_prefix in {k.split("." )[0] for k in pt_state_dict.keys()} ) _UpperCAmelCase : Dict = (model_prefix in flax_model_params) and ( model_prefix not in {k.split("." )[0] for k in pt_state_dict.keys()} ) # Need to change some parameters name to match Flax names for pt_key, pt_tensor in pt_state_dict.items(): _UpperCAmelCase : Dict = tuple(pt_key.split("." ) ) # remove base model prefix if necessary _UpperCAmelCase : List[Any] = pt_tuple_key[0] == model_prefix if load_model_with_head_into_base_model and has_base_model_prefix: _UpperCAmelCase : Any = pt_tuple_key[1:] # Correctly rename weight parameters _UpperCAmelCase , _UpperCAmelCase : List[Any] = rename_key_and_reshape_tensor( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) # add model prefix if necessary _UpperCAmelCase : Dict = (model_prefix,) + flax_key in random_flax_state_dict if load_base_model_into_model_with_head and require_base_model_prefix: _UpperCAmelCase : Optional[Any] = (model_prefix,) + flax_key if flax_key in random_flax_state_dict: if flax_tensor.shape != random_flax_state_dict[flax_key].shape: raise ValueError( F'PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape ' F'{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}.' ) # add batch stats if the model contains batchnorm layers if "batch_stats" in flax_model.params: if "mean" in flax_key[-1]: _UpperCAmelCase : Tuple = jnp.asarray(lowerCAmelCase ) continue if "var" in flax_key[-1]: _UpperCAmelCase : Dict = jnp.asarray(lowerCAmelCase ) continue # remove num_batches_tracked key if "num_batches_tracked" in flax_key[-1]: flax_state_dict.pop(lowerCAmelCase , lowerCAmelCase ) continue # also add unexpected weight so that warning is thrown _UpperCAmelCase : int = jnp.asarray(lowerCAmelCase ) else: # also add unexpected weight so that warning is thrown _UpperCAmelCase : int = jnp.asarray(lowerCAmelCase ) return unflatten_dict(lowerCAmelCase ) def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: List[Any] , lowerCAmelCase: str ) -> Optional[Any]: _UpperCAmelCase : List[str] = os.path.abspath(lowerCAmelCase ) logger.info(F'Loading Flax weights from {flax_checkpoint_path}' ) # import correct flax class _UpperCAmelCase : Any = getattr(lowerCAmelCase , "Flax" + model.__class__.__name__ ) # load flax weight dict with open(lowerCAmelCase , "rb" ) as state_f: try: _UpperCAmelCase : str = from_bytes(lowerCAmelCase , state_f.read() ) except UnpicklingError: raise EnvironmentError(F'Unable to convert {flax_checkpoint_path} to Flax deserializable object. ' ) return load_flax_weights_in_pytorch_model(lowerCAmelCase , lowerCAmelCase ) def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: Optional[int] , lowerCAmelCase: int ) -> Union[str, Any]: try: import torch # noqa: F401 except ImportError: logger.error( "Loading a Flax weights in PyTorch, requires both PyTorch and Flax to be installed. Please see" " https://pytorch.org/ and https://flax.readthedocs.io/en/latest/installation.html for installation" " instructions." ) raise # check if we have bf16 weights _UpperCAmelCase : int = flatten_dict(jax.tree_util.tree_map(lambda lowerCAmelCase : x.dtype == jnp.bfloataa , lowerCAmelCase ) ).values() if any(lowerCAmelCase ): # convert all weights to fp32 if the are bf16 since torch.from_numpy can-not handle bf16 # and bf16 is not fully supported in PT yet. logger.warning( "Found ``bfloat16`` weights in Flax model. Casting all ``bfloat16`` weights to ``float32`` " "before loading those in PyTorch model." ) _UpperCAmelCase : Union[str, Any] = jax.tree_util.tree_map( lambda lowerCAmelCase : params.astype(np.floataa ) if params.dtype == jnp.bfloataa else params , lowerCAmelCase ) _UpperCAmelCase : Tuple = flatten_dict(lowerCAmelCase ) _UpperCAmelCase : Optional[Any] = pt_model.state_dict() _UpperCAmelCase : Tuple = (pt_model.base_model_prefix in flax_state) and ( pt_model.base_model_prefix not in {k.split("." )[0] for k in pt_model_dict.keys()} ) _UpperCAmelCase : Optional[Any] = (pt_model.base_model_prefix not in flax_state) and ( pt_model.base_model_prefix in {k.split("." )[0] for k in pt_model_dict.keys()} ) # keep track of unexpected & missing keys _UpperCAmelCase : List[Any] = [] _UpperCAmelCase : Union[str, Any] = set(pt_model_dict.keys() ) for flax_key_tuple, flax_tensor in flax_state_dict.items(): _UpperCAmelCase : str = flax_key_tuple[0] == pt_model.base_model_prefix _UpperCAmelCase : Union[str, Any] = ".".join((pt_model.base_model_prefix,) + flax_key_tuple ) in pt_model_dict # adapt flax_key to prepare for loading from/to base model only if load_model_with_head_into_base_model and has_base_model_prefix: _UpperCAmelCase : str = flax_key_tuple[1:] elif load_base_model_into_model_with_head and require_base_model_prefix: _UpperCAmelCase : Any = (pt_model.base_model_prefix,) + flax_key_tuple # rename flax weights to PyTorch format if flax_key_tuple[-1] == "kernel" and flax_tensor.ndim == 4 and ".".join(lowerCAmelCase ) not in pt_model_dict: # conv layer _UpperCAmelCase : Any = flax_key_tuple[:-1] + ("weight",) _UpperCAmelCase : Dict = jnp.transpose(lowerCAmelCase , (3, 2, 0, 1) ) elif flax_key_tuple[-1] == "kernel" and ".".join(lowerCAmelCase ) not in pt_model_dict: # linear layer _UpperCAmelCase : Optional[int] = flax_key_tuple[:-1] + ("weight",) _UpperCAmelCase : Tuple = flax_tensor.T elif flax_key_tuple[-1] in ["scale", "embedding"]: _UpperCAmelCase : List[str] = flax_key_tuple[:-1] + ("weight",) # adding batch stats from flax batch norm to pt elif "mean" in flax_key_tuple[-1]: _UpperCAmelCase : int = flax_key_tuple[:-1] + ("running_mean",) elif "var" in flax_key_tuple[-1]: _UpperCAmelCase : Any = flax_key_tuple[:-1] + ("running_var",) if "batch_stats" in flax_state: _UpperCAmelCase : Tuple = ".".join(flax_key_tuple[1:] ) # Remove the params/batch_stats header else: _UpperCAmelCase : List[str] = ".".join(lowerCAmelCase ) # We also need to look at `pt_model_dict` and see if there are keys requiring further transformation. _UpperCAmelCase : Optional[Any] = {} # New `weight_norm` from https://github.com/huggingface/transformers/pull/24030 for key in pt_model_dict: _UpperCAmelCase : Union[str, Any] = key.split("." ) _UpperCAmelCase : Any = None if key_components[-3::2] == ["parametrizations", "original0"]: _UpperCAmelCase : Tuple = key_components[-2] + "_g" elif key_components[-3::2] == ["parametrizations", "original1"]: _UpperCAmelCase : int = key_components[-2] + "_v" if name is not None: _UpperCAmelCase : Union[str, Any] = key_components[:-3] + [name] _UpperCAmelCase : Tuple = ".".join(lowerCAmelCase ) _UpperCAmelCase : Dict = key if flax_key in special_pt_names: _UpperCAmelCase : List[Any] = special_pt_names[flax_key] if flax_key in pt_model_dict: if flax_tensor.shape != pt_model_dict[flax_key].shape: raise ValueError( F'Flax checkpoint seems to be incorrect. Weight {flax_key_tuple} was expected ' F'to be of shape {pt_model_dict[flax_key].shape}, but is {flax_tensor.shape}.' ) else: # add weight to pytorch dict _UpperCAmelCase : str = np.asarray(lowerCAmelCase ) if not isinstance(lowerCAmelCase , np.ndarray ) else flax_tensor _UpperCAmelCase : Optional[Any] = torch.from_numpy(lowerCAmelCase ) # remove from missing keys missing_keys.remove(lowerCAmelCase ) else: # weight is not expected by PyTorch model unexpected_keys.append(lowerCAmelCase ) pt_model.load_state_dict(lowerCAmelCase ) # re-transform missing_keys to list _UpperCAmelCase : Optional[Any] = list(lowerCAmelCase ) if len(lowerCAmelCase ) > 0: logger.warning( "Some weights of the Flax model were not used when initializing the PyTorch model" F' {pt_model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are initializing' F' {pt_model.__class__.__name__} from a Flax model trained on another task or with another architecture' " (e.g. initializing a BertForSequenceClassification model from a FlaxBertForPreTraining model).\n- This" F' IS NOT expected if you are initializing {pt_model.__class__.__name__} from a Flax model that you expect' " to be exactly identical (e.g. initializing a BertForSequenceClassification model from a" " FlaxBertForSequenceClassification model)." ) else: logger.warning(F'All Flax model weights were used when initializing {pt_model.__class__.__name__}.\n' ) if len(lowerCAmelCase ) > 0: logger.warning( F'Some weights of {pt_model.__class__.__name__} were not initialized from the Flax model and are newly' F' initialized: {missing_keys}\nYou should probably TRAIN this model on a down-stream task to be able to' " use it for predictions and inference." ) else: logger.warning( F'All the weights of {pt_model.__class__.__name__} were initialized from the Flax model.\n' "If your task is similar to the task the model of the checkpoint was trained on, " F'you can already use {pt_model.__class__.__name__} for predictions without further training.' ) return pt_model
300
import doctest from collections import deque import numpy as np class a : def __init__( self ): '''simple docstring''' _UpperCAmelCase : Optional[Any] = [2, 1, 2, -1] _UpperCAmelCase : Dict = [1, 2, 3, 4] def _UpperCAmelCase ( self ): '''simple docstring''' _UpperCAmelCase : Union[str, Any] = len(self.first_signal ) _UpperCAmelCase : Optional[Any] = len(self.second_signal ) _UpperCAmelCase : int = max(A_ , A_ ) # create a zero matrix of max_length x max_length _UpperCAmelCase : int = [[0] * max_length for i in range(A_ )] # fills the smaller signal with zeros to make both signals of same length if length_first_signal < length_second_signal: self.first_signal += [0] * (max_length - length_first_signal) elif length_first_signal > length_second_signal: self.second_signal += [0] * (max_length - length_second_signal) for i in range(A_ ): _UpperCAmelCase : Any = deque(self.second_signal ) rotated_signal.rotate(A_ ) for j, item in enumerate(A_ ): matrix[i][j] += item # multiply the matrix with the first signal _UpperCAmelCase : Any = np.matmul(np.transpose(A_ ) , np.transpose(self.first_signal ) ) # rounding-off to two decimal places return [round(A_ , 2 ) for i in final_signal] if __name__ == "__main__": doctest.testmod()
300
1
from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class __SCREAMING_SNAKE_CASE ( A_): """simple docstring""" __UpperCAmelCase = '''ClapFeatureExtractor''' __UpperCAmelCase = ('''RobertaTokenizer''', '''RobertaTokenizerFast''') def __init__( self , _UpperCAmelCase , _UpperCAmelCase ): super().__init__(_UpperCAmelCase , _UpperCAmelCase ) def __call__( self , _UpperCAmelCase=None , _UpperCAmelCase=None , _UpperCAmelCase=None , **_UpperCAmelCase ): __snake_case : List[Any] = kwargs.pop('sampling_rate' , _UpperCAmelCase ) if text is None and audios is None: raise ValueError('You have to specify either text or audios. Both cannot be none.' ) if text is not None: __snake_case : str = self.tokenizer(_UpperCAmelCase , return_tensors=_UpperCAmelCase , **_UpperCAmelCase ) if audios is not None: __snake_case : str = self.feature_extractor( _UpperCAmelCase , sampling_rate=_UpperCAmelCase , return_tensors=_UpperCAmelCase , **_UpperCAmelCase ) if text is not None and audios is not None: __snake_case : int = audio_features.input_features return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**_UpperCAmelCase ) , tensor_type=_UpperCAmelCase ) def lowercase_ ( self , *_UpperCAmelCase , **_UpperCAmelCase ): return self.tokenizer.batch_decode(*_UpperCAmelCase , **_UpperCAmelCase ) def lowercase_ ( self , *_UpperCAmelCase , **_UpperCAmelCase ): return self.tokenizer.decode(*_UpperCAmelCase , **_UpperCAmelCase ) @property def lowercase_ ( self ): __snake_case : int = self.tokenizer.model_input_names __snake_case : List[str] = self.feature_extractor.model_input_names return list(dict.fromkeys(tokenizer_input_names + feature_extractor_input_names ) )
708
from __future__ import annotations __magic_name__ = [ [-1, 0], # left [0, -1], # down [1, 0], # right [0, 1], # up ] def UpperCAmelCase__( __UpperCAmelCase : list[list[int]] , __UpperCAmelCase : list[int] , __UpperCAmelCase : list[int] , __UpperCAmelCase : int , __UpperCAmelCase : list[list[int]] , ): __snake_case : Optional[int] = [ [0 for col in range(len(grid[0] ) )] for row in range(len(__UpperCAmelCase ) ) ] # the reference grid __snake_case : List[str] = 1 __snake_case : str = [ [0 for col in range(len(grid[0] ) )] for row in range(len(__UpperCAmelCase ) ) ] # the action grid __snake_case : Dict = init[0] __snake_case : List[str] = init[1] __snake_case : Optional[Any] = 0 __snake_case : Union[str, Any] = g + heuristic[x][y] # cost from starting cell to destination cell __snake_case : Any = [[f, g, x, y]] __snake_case : List[str] = False # flag that is set when search is complete __snake_case : str = False # flag set if we can't find expand while not found and not resign: if len(__UpperCAmelCase ) == 0: raise ValueError('Algorithm is unable to find solution' ) else: # to choose the least costliest action so as to move closer to the goal cell.sort() cell.reverse() __snake_case : List[Any] = cell.pop() __snake_case : Optional[int] = next_cell[2] __snake_case : int = next_cell[3] __snake_case : Optional[Any] = next_cell[1] if x == goal[0] and y == goal[1]: __snake_case : Union[str, Any] = True else: for i in range(len(__UpperCAmelCase ) ): # to try out different valid actions __snake_case : Tuple = x + DIRECTIONS[i][0] __snake_case : Tuple = y + DIRECTIONS[i][1] if xa >= 0 and xa < len(__UpperCAmelCase ) and ya >= 0 and ya < len(grid[0] ): if closed[xa][ya] == 0 and grid[xa][ya] == 0: __snake_case : List[str] = g + cost __snake_case : Optional[Any] = ga + heuristic[xa][ya] cell.append([fa, ga, xa, ya] ) __snake_case : Dict = 1 __snake_case : Any = i __snake_case : Tuple = [] __snake_case : Dict = goal[0] __snake_case : Optional[int] = goal[1] invpath.append([x, y] ) # we get the reverse path from here while x != init[0] or y != init[1]: __snake_case : Tuple = x - DIRECTIONS[action[x][y]][0] __snake_case : Optional[Any] = y - DIRECTIONS[action[x][y]][1] __snake_case : Tuple = xa __snake_case : List[str] = ya invpath.append([x, y] ) __snake_case : Dict = [] for i in range(len(__UpperCAmelCase ) ): path.append(invpath[len(__UpperCAmelCase ) - 1 - i] ) return path, action if __name__ == "__main__": __magic_name__ = [ [0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0], [0, 0, 0, 0, 1, 0], ] __magic_name__ = [0, 0] # all coordinates are given in format [y,x] __magic_name__ = [len(grid) - 1, len(grid[0]) - 1] __magic_name__ = 1 # the cost map which pushes the path closer to the goal __magic_name__ = [[0 for row in range(len(grid[0]))] for col in range(len(grid))] for i in range(len(grid)): for j in range(len(grid[0])): __magic_name__ = abs(i - goal[0]) + abs(j - goal[1]) if grid[i][j] == 1: # added extra penalty in the heuristic map __magic_name__ = 99 __magic_name__ , __magic_name__ = search(grid, init, goal, cost, heuristic) print('''ACTION MAP''') for i in range(len(action)): print(action[i]) for i in range(len(path)): print(path[i])
679
0
"""simple docstring""" import json import os import unittest from transformers import BatchEncoding, MvpTokenizer, MvpTokenizerFast from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, require_torch from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin, filter_roberta_detectors @require_tokenizers class UpperCamelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): A__ = MvpTokenizer A__ = MvpTokenizerFast A__ = True A__ = filter_roberta_detectors def __SCREAMING_SNAKE_CASE ( self ): """simple docstring""" super().setUp() _SCREAMING_SNAKE_CASE : Optional[Any] = [ "l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "\u0120", "\u0120l", "\u0120n", "\u0120lo", "\u0120low", "er", "\u0120lowest", "\u0120newer", "\u0120wider", "<unk>", ] _SCREAMING_SNAKE_CASE : Tuple = dict(zip(snake_case__ , range(len(snake_case__ ) ) ) ) _SCREAMING_SNAKE_CASE : Dict = ["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""] _SCREAMING_SNAKE_CASE : int = {"unk_token": "<unk>"} _SCREAMING_SNAKE_CASE : str = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) _SCREAMING_SNAKE_CASE : Optional[int] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as fp: fp.write(json.dumps(snake_case__ ) + "\n" ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(snake_case__ ) ) def __SCREAMING_SNAKE_CASE ( self , **snake_case__ ): """simple docstring""" kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **snake_case__ ) def __SCREAMING_SNAKE_CASE ( self , **snake_case__ ): """simple docstring""" kwargs.update(self.special_tokens_map ) return self.rust_tokenizer_class.from_pretrained(self.tmpdirname , **snake_case__ ) def __SCREAMING_SNAKE_CASE ( self , snake_case__ ): """simple docstring""" return "lower newer", "lower newer" @cached_property def __SCREAMING_SNAKE_CASE ( self ): """simple docstring""" return MvpTokenizer.from_pretrained("RUCAIBox/mvp" ) @cached_property def __SCREAMING_SNAKE_CASE ( self ): """simple docstring""" return MvpTokenizerFast.from_pretrained("RUCAIBox/mvp" ) @require_torch def __SCREAMING_SNAKE_CASE ( self ): """simple docstring""" _SCREAMING_SNAKE_CASE : Union[str, Any] = ["A long paragraph for summarization.", "Another paragraph for summarization."] _SCREAMING_SNAKE_CASE : Dict = [0, 250, 251, 17818, 13, 39186, 1938, 4, 2] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: _SCREAMING_SNAKE_CASE : List[str] = tokenizer(snake_case__ , max_length=len(snake_case__ ) , padding=snake_case__ , return_tensors="pt" ) self.assertIsInstance(snake_case__ , snake_case__ ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) _SCREAMING_SNAKE_CASE : int = batch.input_ids.tolist()[0] self.assertListEqual(snake_case__ , snake_case__ ) # Test that special tokens are reset @require_torch def __SCREAMING_SNAKE_CASE ( self ): """simple docstring""" _SCREAMING_SNAKE_CASE : str = ["A long paragraph for summarization.", "Another paragraph for summarization."] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: _SCREAMING_SNAKE_CASE : List[str] = tokenizer(snake_case__ , padding=snake_case__ , return_tensors="pt" ) # check if input_ids are returned and no labels self.assertIn("input_ids" , snake_case__ ) self.assertIn("attention_mask" , snake_case__ ) self.assertNotIn("labels" , snake_case__ ) self.assertNotIn("decoder_attention_mask" , snake_case__ ) @require_torch def __SCREAMING_SNAKE_CASE ( self ): """simple docstring""" _SCREAMING_SNAKE_CASE : Any = [ "Summary of the text.", "Another summary.", ] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: _SCREAMING_SNAKE_CASE : str = tokenizer(text_target=snake_case__ , max_length=32 , padding="max_length" , return_tensors="pt" ) self.assertEqual(32 , targets["input_ids"].shape[1] ) @require_torch def __SCREAMING_SNAKE_CASE ( self ): """simple docstring""" for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: _SCREAMING_SNAKE_CASE : int = tokenizer( ["I am a small frog" * 1024, "I am a small frog"] , padding=snake_case__ , truncation=snake_case__ , return_tensors="pt" ) self.assertIsInstance(snake_case__ , snake_case__ ) self.assertEqual(batch.input_ids.shape , (2, 1024) ) @require_torch def __SCREAMING_SNAKE_CASE ( self ): """simple docstring""" _SCREAMING_SNAKE_CASE : str = ["A long paragraph for summarization."] _SCREAMING_SNAKE_CASE : Any = [ "Summary of the text.", ] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: _SCREAMING_SNAKE_CASE : Any = tokenizer(snake_case__ , text_target=snake_case__ , return_tensors="pt" ) _SCREAMING_SNAKE_CASE : Union[str, Any] = inputs["input_ids"] _SCREAMING_SNAKE_CASE : Any = inputs["labels"] self.assertTrue((input_ids[:, 0] == tokenizer.bos_token_id).all().item() ) self.assertTrue((labels[:, 0] == tokenizer.bos_token_id).all().item() ) self.assertTrue((input_ids[:, -1] == tokenizer.eos_token_id).all().item() ) self.assertTrue((labels[:, -1] == tokenizer.eos_token_id).all().item() ) def __SCREAMING_SNAKE_CASE ( self ): """simple docstring""" pass def __SCREAMING_SNAKE_CASE ( self ): """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): _SCREAMING_SNAKE_CASE : Any = self.rust_tokenizer_class.from_pretrained(snake_case__ , **snake_case__ ) _SCREAMING_SNAKE_CASE : Optional[Any] = self.tokenizer_class.from_pretrained(snake_case__ , **snake_case__ ) _SCREAMING_SNAKE_CASE : str = "A, <mask> AllenNLP sentence." _SCREAMING_SNAKE_CASE : Tuple = tokenizer_r.encode_plus(snake_case__ , add_special_tokens=snake_case__ , return_token_type_ids=snake_case__ ) _SCREAMING_SNAKE_CASE : str = tokenizer_p.encode_plus(snake_case__ , add_special_tokens=snake_case__ , return_token_type_ids=snake_case__ ) # token_type_ids should put 0 everywhere self.assertEqual(sum(tokens_r["token_type_ids"] ) , sum(tokens_p["token_type_ids"] ) ) # attention_mask should put 1 everywhere, so sum over length should be 1 self.assertEqual( sum(tokens_r["attention_mask"] ) / len(tokens_r["attention_mask"] ) , sum(tokens_p["attention_mask"] ) / len(tokens_p["attention_mask"] ) , ) _SCREAMING_SNAKE_CASE : List[Any] = tokenizer_r.convert_ids_to_tokens(tokens_r["input_ids"] ) _SCREAMING_SNAKE_CASE : int = tokenizer_p.convert_ids_to_tokens(tokens_p["input_ids"] ) # Rust correctly handles the space before the mask while python doesnt self.assertSequenceEqual(tokens_p["input_ids"] , [0, 250, 6, 50264, 3823, 487, 21992, 3645, 4, 2] ) self.assertSequenceEqual(tokens_r["input_ids"] , [0, 250, 6, 50264, 3823, 487, 21992, 3645, 4, 2] ) self.assertSequenceEqual( snake_case__ , ["<s>", "A", ",", "<mask>", "ĠAllen", "N", "LP", "Ġsentence", ".", "</s>"] ) self.assertSequenceEqual( snake_case__ , ["<s>", "A", ",", "<mask>", "ĠAllen", "N", "LP", "Ġsentence", ".", "</s>"] )
572
"""simple docstring""" import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import AutoImageProcessor, SwinvaConfig, SwinvaForImageClassification def _lowerCAmelCase ( lowerCamelCase__ : str ) -> Any: _SCREAMING_SNAKE_CASE : Any = SwinvaConfig() _SCREAMING_SNAKE_CASE : List[str] = swinva_name.split("_" ) _SCREAMING_SNAKE_CASE : Dict = name_split[1] if "to" in name_split[3]: _SCREAMING_SNAKE_CASE : Union[str, Any] = int(name_split[3][-3:] ) else: _SCREAMING_SNAKE_CASE : Tuple = int(name_split[3] ) if "to" in name_split[2]: _SCREAMING_SNAKE_CASE : str = int(name_split[2][-2:] ) else: _SCREAMING_SNAKE_CASE : Union[str, Any] = int(name_split[2][6:] ) if model_size == "tiny": _SCREAMING_SNAKE_CASE : List[Any] = 9_6 _SCREAMING_SNAKE_CASE : List[Any] = (2, 2, 6, 2) _SCREAMING_SNAKE_CASE : List[str] = (3, 6, 1_2, 2_4) elif model_size == "small": _SCREAMING_SNAKE_CASE : Optional[int] = 9_6 _SCREAMING_SNAKE_CASE : Optional[Any] = (2, 2, 1_8, 2) _SCREAMING_SNAKE_CASE : List[str] = (3, 6, 1_2, 2_4) elif model_size == "base": _SCREAMING_SNAKE_CASE : Union[str, Any] = 1_2_8 _SCREAMING_SNAKE_CASE : List[str] = (2, 2, 1_8, 2) _SCREAMING_SNAKE_CASE : List[str] = (4, 8, 1_6, 3_2) else: _SCREAMING_SNAKE_CASE : Dict = 1_9_2 _SCREAMING_SNAKE_CASE : Optional[Any] = (2, 2, 1_8, 2) _SCREAMING_SNAKE_CASE : List[str] = (6, 1_2, 2_4, 4_8) if "to" in swinva_name: _SCREAMING_SNAKE_CASE : Optional[int] = (1_2, 1_2, 1_2, 6) if ("22k" in swinva_name) and ("to" not in swinva_name): _SCREAMING_SNAKE_CASE : Tuple = 2_1_8_4_1 _SCREAMING_SNAKE_CASE : Optional[int] = "huggingface/label-files" _SCREAMING_SNAKE_CASE : int = "imagenet-22k-id2label.json" _SCREAMING_SNAKE_CASE : str = json.load(open(hf_hub_download(lowerCamelCase__, lowerCamelCase__, repo_type="dataset" ), "r" ) ) _SCREAMING_SNAKE_CASE : Optional[int] = {int(lowerCamelCase__ ): v for k, v in idalabel.items()} _SCREAMING_SNAKE_CASE : int = idalabel _SCREAMING_SNAKE_CASE : List[str] = {v: k for k, v in idalabel.items()} else: _SCREAMING_SNAKE_CASE : Optional[Any] = 1_0_0_0 _SCREAMING_SNAKE_CASE : Dict = "huggingface/label-files" _SCREAMING_SNAKE_CASE : Any = "imagenet-1k-id2label.json" _SCREAMING_SNAKE_CASE : Tuple = json.load(open(hf_hub_download(lowerCamelCase__, lowerCamelCase__, repo_type="dataset" ), "r" ) ) _SCREAMING_SNAKE_CASE : Dict = {int(lowerCamelCase__ ): v for k, v in idalabel.items()} _SCREAMING_SNAKE_CASE : int = idalabel _SCREAMING_SNAKE_CASE : List[Any] = {v: k for k, v in idalabel.items()} _SCREAMING_SNAKE_CASE : List[str] = img_size _SCREAMING_SNAKE_CASE : List[Any] = num_classes _SCREAMING_SNAKE_CASE : List[Any] = embed_dim _SCREAMING_SNAKE_CASE : List[Any] = depths _SCREAMING_SNAKE_CASE : List[Any] = num_heads _SCREAMING_SNAKE_CASE : int = window_size return config def _lowerCAmelCase ( lowerCamelCase__ : Dict ) -> List[str]: if "patch_embed.proj" in name: _SCREAMING_SNAKE_CASE : List[str] = name.replace("patch_embed.proj", "embeddings.patch_embeddings.projection" ) if "patch_embed.norm" in name: _SCREAMING_SNAKE_CASE : List[str] = name.replace("patch_embed.norm", "embeddings.norm" ) if "layers" in name: _SCREAMING_SNAKE_CASE : Optional[Any] = "encoder." + name if "attn.proj" in name: _SCREAMING_SNAKE_CASE : List[Any] = name.replace("attn.proj", "attention.output.dense" ) if "attn" in name: _SCREAMING_SNAKE_CASE : str = name.replace("attn", "attention.self" ) if "norm1" in name: _SCREAMING_SNAKE_CASE : List[str] = name.replace("norm1", "layernorm_before" ) if "norm2" in name: _SCREAMING_SNAKE_CASE : str = name.replace("norm2", "layernorm_after" ) if "mlp.fc1" in name: _SCREAMING_SNAKE_CASE : Dict = name.replace("mlp.fc1", "intermediate.dense" ) if "mlp.fc2" in name: _SCREAMING_SNAKE_CASE : Tuple = name.replace("mlp.fc2", "output.dense" ) if "q_bias" in name: _SCREAMING_SNAKE_CASE : Dict = name.replace("q_bias", "query.bias" ) if "k_bias" in name: _SCREAMING_SNAKE_CASE : Optional[int] = name.replace("k_bias", "key.bias" ) if "v_bias" in name: _SCREAMING_SNAKE_CASE : int = name.replace("v_bias", "value.bias" ) if "cpb_mlp" in name: _SCREAMING_SNAKE_CASE : Optional[Any] = name.replace("cpb_mlp", "continuous_position_bias_mlp" ) if name == "norm.weight": _SCREAMING_SNAKE_CASE : str = "layernorm.weight" if name == "norm.bias": _SCREAMING_SNAKE_CASE : Tuple = "layernorm.bias" if "head" in name: _SCREAMING_SNAKE_CASE : str = name.replace("head", "classifier" ) else: _SCREAMING_SNAKE_CASE : Tuple = "swinv2." + name return name def _lowerCAmelCase ( lowerCamelCase__ : Any, lowerCamelCase__ : int ) -> Tuple: for key in orig_state_dict.copy().keys(): _SCREAMING_SNAKE_CASE : List[str] = orig_state_dict.pop(lowerCamelCase__ ) if "mask" in key: continue elif "qkv" in key: _SCREAMING_SNAKE_CASE : Any = key.split("." ) _SCREAMING_SNAKE_CASE : Optional[Any] = int(key_split[1] ) _SCREAMING_SNAKE_CASE : Union[str, Any] = int(key_split[3] ) _SCREAMING_SNAKE_CASE : Tuple = model.swinva.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: _SCREAMING_SNAKE_CASE : Optional[int] = val[:dim, :] _SCREAMING_SNAKE_CASE : Tuple = val[dim : dim * 2, :] _SCREAMING_SNAKE_CASE : List[str] = val[-dim:, :] else: _SCREAMING_SNAKE_CASE : List[Any] = val[:dim] _SCREAMING_SNAKE_CASE : str = val[ dim : dim * 2 ] _SCREAMING_SNAKE_CASE : Union[str, Any] = val[-dim:] else: _SCREAMING_SNAKE_CASE : Optional[Any] = val return orig_state_dict def _lowerCAmelCase ( lowerCamelCase__ : List[Any], lowerCamelCase__ : str ) -> Optional[Any]: _SCREAMING_SNAKE_CASE : Any = timm.create_model(lowerCamelCase__, pretrained=lowerCamelCase__ ) timm_model.eval() _SCREAMING_SNAKE_CASE : Tuple = get_swinva_config(lowerCamelCase__ ) _SCREAMING_SNAKE_CASE : int = SwinvaForImageClassification(lowerCamelCase__ ) model.eval() _SCREAMING_SNAKE_CASE : int = convert_state_dict(timm_model.state_dict(), lowerCamelCase__ ) model.load_state_dict(lowerCamelCase__ ) _SCREAMING_SNAKE_CASE : List[str] = "http://images.cocodataset.org/val2017/000000039769.jpg" _SCREAMING_SNAKE_CASE : str = AutoImageProcessor.from_pretrained("microsoft/{}".format(swinva_name.replace("_", "-" ) ) ) _SCREAMING_SNAKE_CASE : List[Any] = Image.open(requests.get(lowerCamelCase__, stream=lowerCamelCase__ ).raw ) _SCREAMING_SNAKE_CASE : Dict = image_processor(images=lowerCamelCase__, return_tensors="pt" ) _SCREAMING_SNAKE_CASE : Tuple = timm_model(inputs["pixel_values"] ) _SCREAMING_SNAKE_CASE : Dict = model(**lowerCamelCase__ ).logits assert torch.allclose(lowerCamelCase__, lowerCamelCase__, atol=1E-3 ) print(f'''Saving model {swinva_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowerCamelCase__ ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(lowerCamelCase__ ) model.push_to_hub( repo_path_or_name=Path(lowerCamelCase__, lowerCamelCase__ ), organization="nandwalritik", commit_message="Add model", ) if __name__ == "__main__": lowercase_ : Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--swinv2_name''', default='''swinv2_tiny_patch4_window8_256''', type=str, help='''Name of the Swinv2 timm model you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) lowercase_ : Optional[int] = parser.parse_args() convert_swinva_checkpoint(args.swinva_name, args.pytorch_dump_folder_path)
572
1
'''simple docstring''' def a ( ): '''simple docstring''' return [ a * b * (10_00 - a - b) for a in range(1 , 9_99 ) for b in range(lowerCamelCase__ , 9_99 ) if (a * a + b * b == (10_00 - a - b) ** 2) ][0] if __name__ == "__main__": print(F"{solution() = }")
712
'''simple docstring''' 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 lowerCamelCase :Any = logging.get_logger(__name__) lowerCamelCase :Any = { '''microsoft/beit-base-patch16-224-pt22k''': ( '''https://huggingface.co/microsoft/beit-base-patch16-224-pt22k/resolve/main/config.json''' ), # See all BEiT models at https://huggingface.co/models?filter=beit } class _lowerCAmelCase ( __UpperCAmelCase ): __SCREAMING_SNAKE_CASE : Optional[Any] = 'beit' def __init__(self , lowercase=8192 , lowercase=768 , lowercase=12 , lowercase=12 , lowercase=3072 , lowercase="gelu" , lowercase=0.0 , lowercase=0.0 , lowercase=0.02 , lowercase=1E-12 , lowercase=224 , lowercase=16 , lowercase=3 , lowercase=False , lowercase=False , lowercase=False , lowercase=False , lowercase=0.1 , lowercase=0.1 , lowercase=True , lowercase=[3, 5, 7, 11] , lowercase=[1, 2, 3, 6] , lowercase=True , lowercase=0.4 , lowercase=256 , lowercase=1 , lowercase=False , lowercase=255 , **lowercase , ): super().__init__(**lowercase ) A_ : Union[str, Any] = vocab_size A_ : List[str] = hidden_size A_ : Optional[int] = num_hidden_layers A_ : Tuple = num_attention_heads A_ : List[Any] = intermediate_size A_ : Optional[int] = hidden_act A_ : str = hidden_dropout_prob A_ : Any = attention_probs_dropout_prob A_ : Dict = initializer_range A_ : str = layer_norm_eps A_ : Any = image_size A_ : int = patch_size A_ : List[str] = num_channels A_ : Any = use_mask_token A_ : Dict = use_absolute_position_embeddings A_ : List[Any] = use_relative_position_bias A_ : Tuple = use_shared_relative_position_bias A_ : Optional[int] = layer_scale_init_value A_ : Tuple = drop_path_rate A_ : Dict = use_mean_pooling # decode head attributes (semantic segmentation) A_ : Tuple = out_indices A_ : Union[str, Any] = pool_scales # auxiliary head attributes (semantic segmentation) A_ : Optional[int] = use_auxiliary_head A_ : Union[str, Any] = auxiliary_loss_weight A_ : Tuple = auxiliary_channels A_ : List[Any] = auxiliary_num_convs A_ : Dict = auxiliary_concat_input A_ : Optional[Any] = semantic_loss_ignore_index class _lowerCAmelCase ( __UpperCAmelCase ): __SCREAMING_SNAKE_CASE : Optional[Any] = version.parse('1.11' ) @property def _a (self ): return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) @property def _a (self ): return 1E-4
686
0