code
stringlengths
87
55.2k
code_codestyle
int64
0
349
style_context
stringlengths
135
49.1k
style_context_codestyle
int64
0
349
label
int64
0
1
'''simple docstring''' import numpy as np import pandas as pd from sklearn.preprocessing import Normalizer from sklearn.svm import SVR from statsmodels.tsa.statespace.sarimax import SARIMAX def a__ ( a__ , a__ , a__ , a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = np.array([[1, item, train_mtch[i]] for i, item in enumerate(a__ )] ) __SCREAMING_SNAKE_CASE = np.array(a__ ) __SCREAMING_SNAKE_CASE = np.dot(np.dot(np.linalg.inv(np.dot(x.transpose() , a__ ) ) , x.transpose() ) , a__ ) return abs(beta[0] + test_dt[0] * beta[1] + test_mtch[0] + beta[2] ) def a__ ( a__ , a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = (1, 2, 1) __SCREAMING_SNAKE_CASE = (1, 1, 0, 7) __SCREAMING_SNAKE_CASE = SARIMAX( a__ , exog=a__ , order=a__ , seasonal_order=a__ ) __SCREAMING_SNAKE_CASE = model.fit(disp=a__ , maxiter=6_00 , method="""nm""" ) __SCREAMING_SNAKE_CASE = model_fit.predict(1 , len(a__ ) , exog=[test_match] ) return result[0] def a__ ( a__ , a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = SVR(kernel="""rbf""" , C=1 , gamma=0.1 , epsilon=0.1 ) regressor.fit(a__ , a__ ) __SCREAMING_SNAKE_CASE = regressor.predict(a__ ) return y_pred[0] def a__ ( a__ ): """simple docstring""" train_user.sort() __SCREAMING_SNAKE_CASE = np.percentile(a__ , 25 ) __SCREAMING_SNAKE_CASE = np.percentile(a__ , 75 ) __SCREAMING_SNAKE_CASE = qa - qa __SCREAMING_SNAKE_CASE = qa - (iqr * 0.1) return low_lim def a__ ( a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 for i in list_vote: if i > actual_result: __SCREAMING_SNAKE_CASE = not_safe + 1 else: if abs(abs(a__ ) - abs(a__ ) ) <= 0.1: safe += 1 else: not_safe += 1 return safe > not_safe if __name__ == "__main__": # data_input_df = pd.read_csv("ex_data.csv", header=None) UpperCAmelCase : List[str] = [[1_8_2_3_1, 0.0, 1], [2_2_6_2_1, 1.0, 2], [1_5_6_7_5, 0.0, 3], [2_3_5_8_3, 1.0, 4]] UpperCAmelCase : Dict = pd.DataFrame( data_input, columns=['total_user', 'total_even', 'days'] ) UpperCAmelCase : List[Any] = Normalizer().fit_transform(data_input_df.values) # split data UpperCAmelCase : Any = normalize_df[:, 2].tolist() UpperCAmelCase : Tuple = normalize_df[:, 0].tolist() UpperCAmelCase : Any = normalize_df[:, 1].tolist() # for svr (input variable = total date and total match) UpperCAmelCase : Optional[int] = normalize_df[:, [1, 2]].tolist() UpperCAmelCase : Optional[Any] = x[: len(x) - 1] UpperCAmelCase : List[str] = x[len(x) - 1 :] # for linear regression & sarimax UpperCAmelCase : str = total_date[: len(total_date) - 1] UpperCAmelCase : Tuple = total_user[: len(total_user) - 1] UpperCAmelCase : Any = total_match[: len(total_match) - 1] UpperCAmelCase : str = total_date[len(total_date) - 1 :] UpperCAmelCase : List[Any] = total_user[len(total_user) - 1 :] UpperCAmelCase : Union[str, Any] = total_match[len(total_match) - 1 :] # voting system with forecasting UpperCAmelCase : Dict = [ linear_regression_prediction( trn_date, trn_user, trn_match, tst_date, tst_match ), sarimax_predictor(trn_user, trn_match, tst_match), support_vector_regressor(x_train, x_test, trn_user), ] # check the safety of today's data UpperCAmelCase : Optional[int] = '' if data_safety_checker(res_vote, tst_user) else 'not ' print('Today\'s data is {not_str}safe.')
267
'''simple docstring''' import unittest from transformers import ( MODEL_FOR_OBJECT_DETECTION_MAPPING, AutoFeatureExtractor, AutoModelForObjectDetection, ObjectDetectionPipeline, is_vision_available, pipeline, ) from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_pytesseract, require_tf, require_timm, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class lowerCAmelCase__ : """simple docstring""" @staticmethod def UpperCAmelCase__ ( *__SCREAMING_SNAKE_CASE : Tuple , **__SCREAMING_SNAKE_CASE : Union[str, Any] ) -> List[str]: """simple docstring""" pass @is_pipeline_test @require_vision @require_timm @require_torch class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = MODEL_FOR_OBJECT_DETECTION_MAPPING def UpperCAmelCase__ ( self : List[Any] , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Tuple ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = ObjectDetectionPipeline(model=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) return object_detector, ["./tests/fixtures/tests_samples/COCO/000000039769.png"] def UpperCAmelCase__ ( self : Optional[int] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : List[Any] ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = object_detector("""./tests/fixtures/tests_samples/COCO/000000039769.png""" , threshold=0.0 ) self.assertGreater(len(__SCREAMING_SNAKE_CASE ) , 0 ) for detected_object in outputs: self.assertEqual( __SCREAMING_SNAKE_CASE , { """score""": ANY(__SCREAMING_SNAKE_CASE ), """label""": ANY(__SCREAMING_SNAKE_CASE ), """box""": {"""xmin""": ANY(__SCREAMING_SNAKE_CASE ), """ymin""": ANY(__SCREAMING_SNAKE_CASE ), """xmax""": ANY(__SCREAMING_SNAKE_CASE ), """ymax""": ANY(__SCREAMING_SNAKE_CASE )}, } , ) import datasets __SCREAMING_SNAKE_CASE = datasets.load_dataset("""hf-internal-testing/fixtures_image_utils""" , """image""" , split="""test""" ) __SCREAMING_SNAKE_CASE = [ Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ), """http://images.cocodataset.org/val2017/000000039769.jpg""", # RGBA dataset[0]["""file"""], # LA dataset[1]["""file"""], # L dataset[2]["""file"""], ] __SCREAMING_SNAKE_CASE = object_detector(__SCREAMING_SNAKE_CASE , threshold=0.0 ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , len(__SCREAMING_SNAKE_CASE ) ) for outputs in batch_outputs: self.assertGreater(len(__SCREAMING_SNAKE_CASE ) , 0 ) for detected_object in outputs: self.assertEqual( __SCREAMING_SNAKE_CASE , { """score""": ANY(__SCREAMING_SNAKE_CASE ), """label""": ANY(__SCREAMING_SNAKE_CASE ), """box""": {"""xmin""": ANY(__SCREAMING_SNAKE_CASE ), """ymin""": ANY(__SCREAMING_SNAKE_CASE ), """xmax""": ANY(__SCREAMING_SNAKE_CASE ), """ymax""": ANY(__SCREAMING_SNAKE_CASE )}, } , ) @require_tf @unittest.skip("""Object detection not implemented in TF""" ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> str: """simple docstring""" pass @require_torch def UpperCAmelCase__ ( self : str ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = """hf-internal-testing/tiny-detr-mobilenetsv3""" __SCREAMING_SNAKE_CASE = AutoModelForObjectDetection.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = AutoFeatureExtractor.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = ObjectDetectionPipeline(model=__SCREAMING_SNAKE_CASE , feature_extractor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" , threshold=0.0 ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ] , ) __SCREAMING_SNAKE_CASE = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] , threshold=0.0 , ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ], [ {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ], ] , ) @require_torch @slow def UpperCAmelCase__ ( self : Optional[int] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = """facebook/detr-resnet-50""" __SCREAMING_SNAKE_CASE = AutoModelForObjectDetection.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = AutoFeatureExtractor.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = ObjectDetectionPipeline(model=__SCREAMING_SNAKE_CASE , feature_extractor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) __SCREAMING_SNAKE_CASE = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], ] , ) @require_torch @slow def UpperCAmelCase__ ( self : List[Any] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = """facebook/detr-resnet-50""" __SCREAMING_SNAKE_CASE = pipeline("""object-detection""" , model=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) __SCREAMING_SNAKE_CASE = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], ] , ) @require_torch @slow def UpperCAmelCase__ ( self : Dict ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = 0.9985 __SCREAMING_SNAKE_CASE = """facebook/detr-resnet-50""" __SCREAMING_SNAKE_CASE = pipeline("""object-detection""" , model=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" , threshold=__SCREAMING_SNAKE_CASE ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) @require_torch @require_pytesseract @slow def UpperCAmelCase__ ( self : int ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = """Narsil/layoutlmv3-finetuned-funsd""" __SCREAMING_SNAKE_CASE = 0.9993 __SCREAMING_SNAKE_CASE = pipeline("""object-detection""" , model=__SCREAMING_SNAKE_CASE , threshold=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector( """https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9993, """label""": """I-ANSWER""", """box""": {"""xmin""": 294, """ymin""": 254, """xmax""": 343, """ymax""": 264}}, {"""score""": 0.9993, """label""": """I-ANSWER""", """box""": {"""xmin""": 294, """ymin""": 254, """xmax""": 343, """ymax""": 264}}, ] , )
267
1
'''simple docstring''' from manim import * class lowerCAmelCase__ ( a ): """simple docstring""" def UpperCAmelCase__ ( self : Tuple ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = Rectangle(height=0.5 , width=0.5 ) __SCREAMING_SNAKE_CASE = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0 ) __SCREAMING_SNAKE_CASE = Rectangle(height=0.25 , width=0.25 ) __SCREAMING_SNAKE_CASE = [mem.copy() for i in range(6 )] __SCREAMING_SNAKE_CASE = [mem.copy() for i in range(6 )] __SCREAMING_SNAKE_CASE = VGroup(*__SCREAMING_SNAKE_CASE ).arrange(__SCREAMING_SNAKE_CASE , buff=0 ) __SCREAMING_SNAKE_CASE = VGroup(*__SCREAMING_SNAKE_CASE ).arrange(__SCREAMING_SNAKE_CASE , buff=0 ) __SCREAMING_SNAKE_CASE = VGroup(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).arrange(__SCREAMING_SNAKE_CASE , buff=0 ) __SCREAMING_SNAKE_CASE = Text("""CPU""" , font_size=24 ) __SCREAMING_SNAKE_CASE = Group(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).arrange(__SCREAMING_SNAKE_CASE , buff=0.5 , aligned_edge=__SCREAMING_SNAKE_CASE ) cpu.move_to([-2.5, -0.5, 0] ) self.add(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = [mem.copy() for i in range(4 )] __SCREAMING_SNAKE_CASE = VGroup(*__SCREAMING_SNAKE_CASE ).arrange(__SCREAMING_SNAKE_CASE , buff=0 ) __SCREAMING_SNAKE_CASE = Text("""GPU""" , font_size=24 ) __SCREAMING_SNAKE_CASE = Group(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).arrange(__SCREAMING_SNAKE_CASE , buff=0.5 , aligned_edge=__SCREAMING_SNAKE_CASE ) gpu.move_to([-1, -1, 0] ) self.add(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = [mem.copy() for i in range(6 )] __SCREAMING_SNAKE_CASE = VGroup(*__SCREAMING_SNAKE_CASE ).arrange(__SCREAMING_SNAKE_CASE , buff=0 ) __SCREAMING_SNAKE_CASE = Text("""Model""" , font_size=24 ) __SCREAMING_SNAKE_CASE = Group(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).arrange(__SCREAMING_SNAKE_CASE , buff=0.5 , aligned_edge=__SCREAMING_SNAKE_CASE ) model.move_to([3, -1.0, 0] ) self.add(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] for i, rect in enumerate(__SCREAMING_SNAKE_CASE ): __SCREAMING_SNAKE_CASE = fill.copy().set_fill(__SCREAMING_SNAKE_CASE , opacity=0.8 ) target.move_to(__SCREAMING_SNAKE_CASE ) model_arr.append(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0.0 ).set_fill(__SCREAMING_SNAKE_CASE , opacity=0.8 ) cpu_target.move_to(cpu_left_col_base[i] ) model_cpu_arr.append(__SCREAMING_SNAKE_CASE ) self.add(*__SCREAMING_SNAKE_CASE , *__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = [meta_mem.copy() for i in range(6 )] __SCREAMING_SNAKE_CASE = [meta_mem.copy() for i in range(6 )] __SCREAMING_SNAKE_CASE = VGroup(*__SCREAMING_SNAKE_CASE ).arrange(__SCREAMING_SNAKE_CASE , buff=0 ) __SCREAMING_SNAKE_CASE = VGroup(*__SCREAMING_SNAKE_CASE ).arrange(__SCREAMING_SNAKE_CASE , buff=0 ) __SCREAMING_SNAKE_CASE = VGroup(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).arrange(__SCREAMING_SNAKE_CASE , buff=0 ) __SCREAMING_SNAKE_CASE = Text("""Disk""" , font_size=24 ) __SCREAMING_SNAKE_CASE = Group(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).arrange(__SCREAMING_SNAKE_CASE , buff=0.5 , aligned_edge=__SCREAMING_SNAKE_CASE ) disk.move_to([-4, -1.25, 0] ) self.add(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) __SCREAMING_SNAKE_CASE = MarkupText( f'<b>Key:</b>\n\n<span fgcolor=\'{YELLOW}\'>●</span> Empty Model' , font_size=18 , ) key_text.move_to([-5, 2.4, 0] ) self.add(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = MarkupText( f'<span fgcolor=\'{BLUE}\'>●</span> Checkpoint' , font_size=18 , ) blue_text.next_to(__SCREAMING_SNAKE_CASE , DOWN * 2.4 , aligned_edge=key_text.get_left() ) self.add(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = MarkupText( f'Now watch as an input is passed through the model\nand how the memory is utilized and handled.' , font_size=24 , ) step_a.move_to([2, 2, 0] ) self.play(Write(__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = Square(0.3 ) input.set_fill(__SCREAMING_SNAKE_CASE , opacity=1.0 ) input.set_stroke(width=0.0 ) input.next_to(model_base[0] , __SCREAMING_SNAKE_CASE , buff=0.5 ) self.play(Write(__SCREAMING_SNAKE_CASE ) ) input.generate_target() input.target.next_to(model_arr[0] , direction=__SCREAMING_SNAKE_CASE , buff=0.02 ) self.play(MoveToTarget(__SCREAMING_SNAKE_CASE ) ) self.play(FadeOut(__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = Arrow(start=__SCREAMING_SNAKE_CASE , end=__SCREAMING_SNAKE_CASE , color=__SCREAMING_SNAKE_CASE , buff=0.5 ) a.next_to(model_arr[0].get_left() , __SCREAMING_SNAKE_CASE , buff=0.2 ) model_cpu_arr[0].generate_target() model_cpu_arr[0].target.move_to(gpu_rect[0] ) __SCREAMING_SNAKE_CASE = MarkupText( f'As the input reaches a layer, the hook triggers\nand weights are moved from the CPU\nto the GPU and back.' , font_size=24 , ) step_a.move_to([2, 2, 0] ) self.play(Write(__SCREAMING_SNAKE_CASE , run_time=3 ) ) __SCREAMING_SNAKE_CASE = {"""run_time""": 1, """fade_in""": True, """fade_out""": True, """buff""": 0.02} self.play( Write(__SCREAMING_SNAKE_CASE ) , Circumscribe(model_arr[0] , color=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) , Circumscribe(model_cpu_arr[0] , color=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) , Circumscribe(gpu_rect[0] , color=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) , ) self.play(MoveToTarget(model_cpu_arr[0] ) ) __SCREAMING_SNAKE_CASE = a.copy() for i in range(6 ): a_c.next_to(model_arr[i].get_right() + 0.02 , __SCREAMING_SNAKE_CASE , buff=0.2 ) input.generate_target() input.target.move_to(model_arr[i].get_right() + 0.02 ) __SCREAMING_SNAKE_CASE = AnimationGroup( FadeOut(__SCREAMING_SNAKE_CASE , run_time=0.5 ) , MoveToTarget(__SCREAMING_SNAKE_CASE , run_time=0.5 ) , FadeIn(__SCREAMING_SNAKE_CASE , run_time=0.5 ) , lag_ratio=0.2 ) self.play(__SCREAMING_SNAKE_CASE ) model_cpu_arr[i].generate_target() model_cpu_arr[i].target.move_to(cpu_left_col_base[i] ) if i < 5: model_cpu_arr[i + 1].generate_target() model_cpu_arr[i + 1].target.move_to(gpu_rect[0] ) if i >= 1: __SCREAMING_SNAKE_CASE = 0.7 self.play( Circumscribe(model_arr[i] , **__SCREAMING_SNAKE_CASE ) , Circumscribe(cpu_left_col_base[i] , **__SCREAMING_SNAKE_CASE ) , Circumscribe(cpu_left_col_base[i + 1] , color=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) , Circumscribe(gpu_rect[0] , color=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) , Circumscribe(model_arr[i + 1] , color=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) , ) if i < 1: self.play( MoveToTarget(model_cpu_arr[i] ) , MoveToTarget(model_cpu_arr[i + 1] ) , ) else: self.play( MoveToTarget(model_cpu_arr[i] , run_time=0.7 ) , MoveToTarget(model_cpu_arr[i + 1] , run_time=0.7 ) , ) else: model_cpu_arr[i].generate_target() model_cpu_arr[i].target.move_to(cpu_left_col_base[-1] ) input.generate_target() input.target.next_to(model_arr[-1].get_right() , RIGHT + 0.02 , buff=0.2 ) self.play( Circumscribe(model_arr[-1] , color=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) , Circumscribe(cpu_left_col_base[-1] , color=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) , Circumscribe(gpu_rect[0] , color=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) , ) self.play(MoveToTarget(model_cpu_arr[i] ) ) __SCREAMING_SNAKE_CASE = a_c __SCREAMING_SNAKE_CASE = a_c.copy() input.generate_target() input.target.next_to(model_base[-1] , RIGHT + 0.02 , buff=0.5 ) self.play( FadeOut(__SCREAMING_SNAKE_CASE ) , FadeOut(__SCREAMING_SNAKE_CASE , run_time=0.5 ) , ) __SCREAMING_SNAKE_CASE = MarkupText(f'Inference on a model too large for GPU memory\nis successfully completed.' , font_size=24 ) step_a.move_to([2, 2, 0] ) self.play(Write(__SCREAMING_SNAKE_CASE , run_time=3 ) , MoveToTarget(__SCREAMING_SNAKE_CASE ) ) self.wait()
267
'''simple docstring''' import unittest from diffusers import FlaxAutoencoderKL from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax from .test_modeling_common_flax import FlaxModelTesterMixin if is_flax_available(): import jax @require_flax class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = FlaxAutoencoderKL @property def UpperCAmelCase__ ( self : Tuple ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = 4 __SCREAMING_SNAKE_CASE = 3 __SCREAMING_SNAKE_CASE = (32, 32) __SCREAMING_SNAKE_CASE = jax.random.PRNGKey(0 ) __SCREAMING_SNAKE_CASE = jax.random.uniform(__SCREAMING_SNAKE_CASE , ((batch_size, num_channels) + sizes) ) return {"sample": image, "prng_key": prng_key} def UpperCAmelCase__ ( self : Union[str, Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = { """block_out_channels""": [32, 64], """in_channels""": 3, """out_channels""": 3, """down_block_types""": ["""DownEncoderBlock2D""", """DownEncoderBlock2D"""], """up_block_types""": ["""UpDecoderBlock2D""", """UpDecoderBlock2D"""], """latent_channels""": 4, } __SCREAMING_SNAKE_CASE = self.dummy_input return init_dict, inputs_dict
267
1
'''simple docstring''' def a__ ( a__ ): """simple docstring""" if not isinstance(a__ , a__ ): __SCREAMING_SNAKE_CASE = F'Input value of [number={number}] must be an integer' raise TypeError(a__ ) if number < 1: __SCREAMING_SNAKE_CASE = F'Input value of [number={number}] must be > 0' raise ValueError(a__ ) __SCREAMING_SNAKE_CASE = 1 for i in range(1 , a__ ): current_number *= 4 * i - 2 current_number //= i + 1 return current_number if __name__ == "__main__": import doctest doctest.testmod()
267
'''simple docstring''' import itertools import os import random import tempfile import unittest import numpy as np from datasets import load_dataset from transformers import is_speech_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_speech_available(): from transformers import WhisperFeatureExtractor if is_torch_available(): import torch UpperCAmelCase : int = random.Random() def a__ ( a__ , a__=1.0 , a__=None , a__=None ): """simple docstring""" if rng is None: __SCREAMING_SNAKE_CASE = global_rng __SCREAMING_SNAKE_CASE = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch @require_torchaudio class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __init__( self : str , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : str=7 , __SCREAMING_SNAKE_CASE : List[str]=400 , __SCREAMING_SNAKE_CASE : Any=2_000 , __SCREAMING_SNAKE_CASE : List[str]=10 , __SCREAMING_SNAKE_CASE : Optional[int]=160 , __SCREAMING_SNAKE_CASE : List[str]=8 , __SCREAMING_SNAKE_CASE : Optional[Any]=0.0 , __SCREAMING_SNAKE_CASE : Dict=4_000 , __SCREAMING_SNAKE_CASE : Optional[int]=False , __SCREAMING_SNAKE_CASE : List[Any]=True , ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = min_seq_length __SCREAMING_SNAKE_CASE = max_seq_length __SCREAMING_SNAKE_CASE = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) __SCREAMING_SNAKE_CASE = padding_value __SCREAMING_SNAKE_CASE = sampling_rate __SCREAMING_SNAKE_CASE = return_attention_mask __SCREAMING_SNAKE_CASE = do_normalize __SCREAMING_SNAKE_CASE = feature_size __SCREAMING_SNAKE_CASE = chunk_length __SCREAMING_SNAKE_CASE = hop_length def UpperCAmelCase__ ( self : Dict ) -> Dict: """simple docstring""" return { "feature_size": self.feature_size, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def UpperCAmelCase__ ( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : Union[str, Any]=False , __SCREAMING_SNAKE_CASE : Optional[Any]=False ) -> Union[str, Any]: """simple docstring""" def _flatten(__SCREAMING_SNAKE_CASE : Dict ): return list(itertools.chain(*__SCREAMING_SNAKE_CASE ) ) if equal_length: __SCREAMING_SNAKE_CASE = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size __SCREAMING_SNAKE_CASE = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = WhisperFeatureExtractor if is_speech_available() else None def UpperCAmelCase__ ( self : str ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = WhisperFeatureExtractionTester(self ) def UpperCAmelCase__ ( self : str ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE = feat_extract_first.save_pretrained(__SCREAMING_SNAKE_CASE )[0] check_json_file_has_correct_format(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.feature_extraction_class.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = feat_extract_first.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_second.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_first.mel_filters __SCREAMING_SNAKE_CASE = feat_extract_second.mel_filters self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[str] ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE = os.path.join(__SCREAMING_SNAKE_CASE , """feat_extract.json""" ) feat_extract_first.to_json_file(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.feature_extraction_class.from_json_file(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = feat_extract_first.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_second.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_first.mel_filters __SCREAMING_SNAKE_CASE = feat_extract_second.mel_filters self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[Any] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in range(800 , 1_400 , 200 )] __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs] # Test feature size __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , padding="""max_length""" , return_tensors="""np""" ).input_features self.assertTrue(input_features.ndim == 3 ) self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames ) self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size ) # Test not batched input __SCREAMING_SNAKE_CASE = feature_extractor(speech_inputs[0] , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(np_speech_inputs[0] , return_tensors="""np""" ).input_features self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test batched __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test 2-D numpy arrays are batched. __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in (800, 800, 800)] __SCREAMING_SNAKE_CASE = np.asarray(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test truncation required __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in range(200 , (feature_extractor.n_samples + 500) , 200 )] __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs] __SCREAMING_SNAKE_CASE = [x[: feature_extractor.n_samples] for x in speech_inputs] __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs_truncated] __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) def UpperCAmelCase__ ( self : Dict ) -> Optional[int]: """simple docstring""" import torch __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __SCREAMING_SNAKE_CASE = np.random.rand(100 , 32 ).astype(np.floataa ) __SCREAMING_SNAKE_CASE = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: __SCREAMING_SNAKE_CASE = feature_extractor.pad([{"""input_features""": inputs}] , return_tensors="""np""" ) self.assertTrue(np_processed.input_features.dtype == np.floataa ) __SCREAMING_SNAKE_CASE = feature_extractor.pad([{"""input_features""": inputs}] , return_tensors="""pt""" ) self.assertTrue(pt_processed.input_features.dtype == torch.floataa ) def UpperCAmelCase__ ( self : str , __SCREAMING_SNAKE_CASE : Tuple ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = load_dataset("""hf-internal-testing/librispeech_asr_dummy""" , """clean""" , split="""validation""" ) # automatic decoding with librispeech __SCREAMING_SNAKE_CASE = ds.sort("""id""" ).select(range(__SCREAMING_SNAKE_CASE ) )[:num_samples]["""audio"""] return [x["array"] for x in speech_samples] def UpperCAmelCase__ ( self : Tuple ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = torch.tensor( [ 0.1193, -0.0946, -0.1098, -0.0196, 0.0225, -0.0690, -0.1736, 0.0951, 0.0971, -0.0817, -0.0702, 0.0162, 0.0260, 0.0017, -0.0192, -0.1678, 0.0709, -0.1867, -0.0655, -0.0274, -0.0234, -0.1884, -0.0516, -0.0554, -0.0274, -0.1425, -0.1423, 0.0837, 0.0377, -0.0854 ] ) # fmt: on __SCREAMING_SNAKE_CASE = self._load_datasamples(1 ) __SCREAMING_SNAKE_CASE = WhisperFeatureExtractor() __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).input_features self.assertEqual(input_features.shape , (1, 80, 3_000) ) self.assertTrue(torch.allclose(input_features[0, 0, :30] , __SCREAMING_SNAKE_CASE , atol=1E-4 ) ) def UpperCAmelCase__ ( self : List[Any] ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __SCREAMING_SNAKE_CASE = self._load_datasamples(1 )[0] __SCREAMING_SNAKE_CASE = ((audio - audio.min()) / (audio.max() - audio.min())) * 65_535 # Rescale to [0, 65535] to show issue __SCREAMING_SNAKE_CASE = feat_extract.zero_mean_unit_var_norm([audio] , attention_mask=__SCREAMING_SNAKE_CASE )[0] self.assertTrue(np.all(np.mean(__SCREAMING_SNAKE_CASE ) < 1E-3 ) ) self.assertTrue(np.all(np.abs(np.var(__SCREAMING_SNAKE_CASE ) - 1 ) < 1E-3 ) )
267
1
'''simple docstring''' import math from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase : Optional[Any] = logging.get_logger(__name__) UpperCAmelCase : Tuple = { 'facebook/data2vec-base-960h': 'https://huggingface.co/facebook/data2vec-audio-base-960h/resolve/main/config.json', # See all Data2VecAudio models at https://huggingface.co/models?filter=data2vec-audio } class lowerCAmelCase__ ( a ): """simple docstring""" lowerCAmelCase__ = "data2vec-audio" def __init__( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Dict=32 , __SCREAMING_SNAKE_CASE : Optional[Any]=768 , __SCREAMING_SNAKE_CASE : Optional[Any]=12 , __SCREAMING_SNAKE_CASE : Any=12 , __SCREAMING_SNAKE_CASE : Union[str, Any]=3_072 , __SCREAMING_SNAKE_CASE : Optional[Any]="gelu" , __SCREAMING_SNAKE_CASE : Tuple=0.1 , __SCREAMING_SNAKE_CASE : Optional[Any]=0.1 , __SCREAMING_SNAKE_CASE : Dict=0.1 , __SCREAMING_SNAKE_CASE : str=0.0 , __SCREAMING_SNAKE_CASE : List[str]=0.1 , __SCREAMING_SNAKE_CASE : List[str]=0.1 , __SCREAMING_SNAKE_CASE : List[str]=0.02 , __SCREAMING_SNAKE_CASE : List[str]=1E-5 , __SCREAMING_SNAKE_CASE : str="gelu" , __SCREAMING_SNAKE_CASE : Union[str, Any]=(512, 512, 512, 512, 512, 512, 512) , __SCREAMING_SNAKE_CASE : List[Any]=(5, 2, 2, 2, 2, 2, 2) , __SCREAMING_SNAKE_CASE : Union[str, Any]=(10, 3, 3, 3, 3, 2, 2) , __SCREAMING_SNAKE_CASE : Union[str, Any]=False , __SCREAMING_SNAKE_CASE : Optional[Any]=16 , __SCREAMING_SNAKE_CASE : Union[str, Any]=19 , __SCREAMING_SNAKE_CASE : Any=5 , __SCREAMING_SNAKE_CASE : int=0.05 , __SCREAMING_SNAKE_CASE : Dict=10 , __SCREAMING_SNAKE_CASE : Dict=2 , __SCREAMING_SNAKE_CASE : Optional[Any]=0.0 , __SCREAMING_SNAKE_CASE : Tuple=10 , __SCREAMING_SNAKE_CASE : List[str]=0 , __SCREAMING_SNAKE_CASE : List[str]="sum" , __SCREAMING_SNAKE_CASE : int=False , __SCREAMING_SNAKE_CASE : Tuple=False , __SCREAMING_SNAKE_CASE : List[Any]=256 , __SCREAMING_SNAKE_CASE : Dict=(512, 512, 512, 512, 1_500) , __SCREAMING_SNAKE_CASE : str=(5, 3, 3, 1, 1) , __SCREAMING_SNAKE_CASE : Optional[int]=(1, 2, 3, 1, 1) , __SCREAMING_SNAKE_CASE : Any=512 , __SCREAMING_SNAKE_CASE : List[Any]=0 , __SCREAMING_SNAKE_CASE : List[str]=1 , __SCREAMING_SNAKE_CASE : Optional[Any]=2 , __SCREAMING_SNAKE_CASE : Any=False , __SCREAMING_SNAKE_CASE : List[str]=3 , __SCREAMING_SNAKE_CASE : Optional[int]=2 , __SCREAMING_SNAKE_CASE : Dict=3 , __SCREAMING_SNAKE_CASE : Optional[Any]=None , **__SCREAMING_SNAKE_CASE : Optional[Any] , ) -> str: """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 ) __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = feat_extract_activation __SCREAMING_SNAKE_CASE = list(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = list(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = list(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = conv_bias __SCREAMING_SNAKE_CASE = num_conv_pos_embeddings __SCREAMING_SNAKE_CASE = num_conv_pos_embedding_groups __SCREAMING_SNAKE_CASE = conv_pos_kernel_size __SCREAMING_SNAKE_CASE = len(self.conv_dim ) __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = hidden_dropout __SCREAMING_SNAKE_CASE = attention_dropout __SCREAMING_SNAKE_CASE = activation_dropout __SCREAMING_SNAKE_CASE = feat_proj_dropout __SCREAMING_SNAKE_CASE = final_dropout __SCREAMING_SNAKE_CASE = layerdrop __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = use_weighted_layer_sum if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( """Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==""" """ `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =""" f' {len(self.conv_dim )}`, `len(config.conv_stride) = {len(self.conv_stride )}`,' f' `len(config.conv_kernel) = {len(self.conv_kernel )}`.' ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 __SCREAMING_SNAKE_CASE = mask_time_prob __SCREAMING_SNAKE_CASE = mask_time_length __SCREAMING_SNAKE_CASE = mask_time_min_masks __SCREAMING_SNAKE_CASE = mask_feature_prob __SCREAMING_SNAKE_CASE = mask_feature_length __SCREAMING_SNAKE_CASE = mask_feature_min_masks # ctc loss __SCREAMING_SNAKE_CASE = ctc_loss_reduction __SCREAMING_SNAKE_CASE = ctc_zero_infinity # adapter __SCREAMING_SNAKE_CASE = add_adapter __SCREAMING_SNAKE_CASE = adapter_kernel_size __SCREAMING_SNAKE_CASE = adapter_stride __SCREAMING_SNAKE_CASE = num_adapter_layers __SCREAMING_SNAKE_CASE = output_hidden_size or hidden_size # SequenceClassification-specific parameter. Feel free to ignore for other classes. __SCREAMING_SNAKE_CASE = classifier_proj_size # XVector-specific parameters. Feel free to ignore for other classes. __SCREAMING_SNAKE_CASE = list(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = list(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = list(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = xvector_output_dim @property def UpperCAmelCase__ ( self : int ) -> Any: """simple docstring""" return math.prod(self.conv_stride )
267
'''simple docstring''' from __future__ import annotations def a__ ( a__ , a__ , a__ ): """simple docstring""" if len(a__ ) == 0: raise ValueError("""find_max() arg is an empty sequence""" ) if ( left >= len(a__ ) or left < -len(a__ ) or right >= len(a__ ) or right < -len(a__ ) ): raise IndexError("""list index out of range""" ) if left == right: return nums[left] __SCREAMING_SNAKE_CASE = (left + right) >> 1 # the middle __SCREAMING_SNAKE_CASE = find_max(a__ , a__ , a__ ) # find max in range[left, mid] __SCREAMING_SNAKE_CASE = find_max(a__ , mid + 1 , a__ ) # find max in range[mid + 1, right] return left_max if left_max >= right_max else right_max if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
267
1
'''simple docstring''' import os import re import warnings from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_ta import TaTokenizer else: UpperCAmelCase : List[Any] = None UpperCAmelCase : Optional[int] = logging.get_logger(__name__) UpperCAmelCase : Optional[Any] = {'vocab_file': 'spiece.model', 'tokenizer_file': 'tokenizer.json'} UpperCAmelCase : int = { 'vocab_file': { 't5-small': 'https://huggingface.co/t5-small/resolve/main/spiece.model', 't5-base': 'https://huggingface.co/t5-base/resolve/main/spiece.model', 't5-large': 'https://huggingface.co/t5-large/resolve/main/spiece.model', 't5-3b': 'https://huggingface.co/t5-3b/resolve/main/spiece.model', 't5-11b': 'https://huggingface.co/t5-11b/resolve/main/spiece.model', }, 'tokenizer_file': { 't5-small': 'https://huggingface.co/t5-small/resolve/main/tokenizer.json', 't5-base': 'https://huggingface.co/t5-base/resolve/main/tokenizer.json', 't5-large': 'https://huggingface.co/t5-large/resolve/main/tokenizer.json', 't5-3b': 'https://huggingface.co/t5-3b/resolve/main/tokenizer.json', 't5-11b': 'https://huggingface.co/t5-11b/resolve/main/tokenizer.json', }, } # TODO(PVP) - this should be removed in Transformers v5 UpperCAmelCase : Optional[int] = { 't5-small': 5_1_2, 't5-base': 5_1_2, 't5-large': 5_1_2, 't5-3b': 5_1_2, 't5-11b': 5_1_2, } class lowerCAmelCase__ ( a ): """simple docstring""" lowerCAmelCase__ = VOCAB_FILES_NAMES lowerCAmelCase__ = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase__ = ["input_ids", "attention_mask"] lowerCAmelCase__ = TaTokenizer lowerCAmelCase__ = [] def __init__( self : Any , __SCREAMING_SNAKE_CASE : Dict=None , __SCREAMING_SNAKE_CASE : Union[str, Any]=None , __SCREAMING_SNAKE_CASE : List[str]="</s>" , __SCREAMING_SNAKE_CASE : Optional[int]="<unk>" , __SCREAMING_SNAKE_CASE : Optional[Any]="<pad>" , __SCREAMING_SNAKE_CASE : Tuple=100 , __SCREAMING_SNAKE_CASE : Tuple=None , **__SCREAMING_SNAKE_CASE : Dict , ) -> List[str]: """simple docstring""" if extra_ids > 0 and additional_special_tokens is None: __SCREAMING_SNAKE_CASE = [f'<extra_id_{i}>' for i in range(__SCREAMING_SNAKE_CASE )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra special tokens __SCREAMING_SNAKE_CASE = len(set(filter(lambda __SCREAMING_SNAKE_CASE : bool("""extra_id_""" in str(__SCREAMING_SNAKE_CASE ) ) , __SCREAMING_SNAKE_CASE ) ) ) if extra_tokens != extra_ids: raise ValueError( f'Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are' """ provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids""" """ tokens""" ) super().__init__( __SCREAMING_SNAKE_CASE , tokenizer_file=__SCREAMING_SNAKE_CASE , eos_token=__SCREAMING_SNAKE_CASE , unk_token=__SCREAMING_SNAKE_CASE , pad_token=__SCREAMING_SNAKE_CASE , extra_ids=__SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) __SCREAMING_SNAKE_CASE = vocab_file __SCREAMING_SNAKE_CASE = False if not self.vocab_file else True __SCREAMING_SNAKE_CASE = extra_ids @staticmethod def UpperCAmelCase__ ( __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Any ) -> Tuple: """simple docstring""" if pretrained_model_name_or_path in TaTokenizerFast.max_model_input_sizes: __SCREAMING_SNAKE_CASE = TaTokenizerFast.max_model_input_sizes[pretrained_model_name_or_path] if init_max_model_length is not None and init_max_model_length != max_model_length: return init_max_model_length elif init_max_model_length is None: warnings.warn( """This tokenizer was incorrectly instantiated with a model max length of""" f' {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this' """ behavior is kept to avoid breaking backwards compatibility when padding/encoding with""" """ `truncation is True`.\n- Be aware that you SHOULD NOT rely on""" f' {pretrained_model_name_or_path} automatically truncating your input to' f' {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences' f' longer than {deprecated_max_model_length} you can either instantiate this tokenizer with' """ `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please""" """ instantiate this tokenizer with `model_max_length` set to your preferred value.""" , __SCREAMING_SNAKE_CASE , ) return max_model_length def UpperCAmelCase__ ( self : str , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Optional[str] = None ) -> Tuple[str]: """simple docstring""" if not self.can_save_slow_tokenizer: raise ValueError( """Your fast tokenizer does not have the necessary information to save the vocabulary for a slow """ """tokenizer.""" ) if not os.path.isdir(__SCREAMING_SNAKE_CASE ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return __SCREAMING_SNAKE_CASE = os.path.join( __SCREAMING_SNAKE_CASE , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__SCREAMING_SNAKE_CASE ): copyfile(self.vocab_file , __SCREAMING_SNAKE_CASE ) logger.info(f'Copy vocab file to {out_vocab_file}' ) return (out_vocab_file,) def UpperCAmelCase__ ( self : Dict , __SCREAMING_SNAKE_CASE : List[int] , __SCREAMING_SNAKE_CASE : Optional[List[int]] = None ) -> List[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = token_ids_a + [self.eos_token_id] if token_ids_a is None: return self.prefix_tokens + token_ids_a else: __SCREAMING_SNAKE_CASE = token_ids_a + [self.eos_token_id] return self.prefix_tokens + token_ids_a + token_ids_a def UpperCAmelCase__ ( self : str , __SCREAMING_SNAKE_CASE : List[int] , __SCREAMING_SNAKE_CASE : Optional[List[int]] = None ) -> List[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def UpperCAmelCase__ ( self : List[str] ) -> Dict: """simple docstring""" return list( set(filter(lambda __SCREAMING_SNAKE_CASE : bool(re.search(r"""<extra_id_\d+>""" , __SCREAMING_SNAKE_CASE ) ) is not None , self.additional_special_tokens ) ) ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> Any: """simple docstring""" return [self.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) for token in self.get_sentinel_tokens()]
267
'''simple docstring''' def a__ ( a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) # Initialize Result __SCREAMING_SNAKE_CASE = [] # Traverse through all denomination for denomination in reversed(a__ ): # Find denominations while int(a__ ) >= int(a__ ): total_value -= int(a__ ) answer.append(a__ ) # Append the "answers" array return answer # Driver Code if __name__ == "__main__": UpperCAmelCase : Dict = [] UpperCAmelCase : List[str] = '0' if ( input('Do you want to enter your denominations ? (yY/n): ').strip().lower() == "y" ): UpperCAmelCase : List[str] = int(input('Enter the number of denominations you want to add: ').strip()) for i in range(0, n): denominations.append(int(input(f"""Denomination {i}: """).strip())) UpperCAmelCase : str = input('Enter the change you want to make in Indian Currency: ').strip() else: # All denominations of Indian Currency if user does not enter UpperCAmelCase : int = [1, 2, 5, 1_0, 2_0, 5_0, 1_0_0, 5_0_0, 2_0_0_0] UpperCAmelCase : Any = input('Enter the change you want to make: ').strip() if int(value) == 0 or int(value) < 0: print('The total value cannot be zero or negative.') else: print(f"""Following is minimal change for {value}: """) UpperCAmelCase : Any = find_minimum_change(denominations, value) # Print result for i in range(len(answer)): print(answer[i], end=' ')
267
1
'''simple docstring''' def a__ ( a__ = 10_00 ): """simple docstring""" __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = 1, 1 __SCREAMING_SNAKE_CASE = [] for i in range(1 , n + 1 ): __SCREAMING_SNAKE_CASE = prev_numerator + 2 * prev_denominator __SCREAMING_SNAKE_CASE = prev_numerator + prev_denominator if len(str(a__ ) ) > len(str(a__ ) ): result.append(a__ ) __SCREAMING_SNAKE_CASE = numerator __SCREAMING_SNAKE_CASE = denominator return len(a__ ) if __name__ == "__main__": print(f"""{solution() = }""")
267
'''simple docstring''' # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse from ...utils.dataclasses import ( ComputeEnvironment, DistributedType, DynamoBackend, PrecisionType, SageMakerDistributedType, ) from ..menu import BulletMenu UpperCAmelCase : Any = [ 'EAGER', 'AOT_EAGER', 'INDUCTOR', 'NVFUSER', 'AOT_NVFUSER', 'AOT_CUDAGRAPHS', 'OFI', 'FX2TRT', 'ONNXRT', 'IPEX', ] def a__ ( a__ , a__=None , a__=None , a__=None ): """simple docstring""" __SCREAMING_SNAKE_CASE = True while ask_again: __SCREAMING_SNAKE_CASE = input(a__ ) try: if default is not None and len(a__ ) == 0: return default return convert_value(a__ ) if convert_value is not None else result except Exception: if error_message is not None: print(a__ ) def a__ ( a__ , a__=[] , a__=None , a__=0 ): """simple docstring""" __SCREAMING_SNAKE_CASE = BulletMenu(a__ , a__ ) __SCREAMING_SNAKE_CASE = menu.run(default_choice=a__ ) return convert_value(a__ ) if convert_value is not None else result def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return ComputeEnvironment(["""LOCAL_MACHINE""", """AMAZON_SAGEMAKER"""][value] ) def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return DistributedType(["""NO""", """MULTI_CPU""", """MULTI_XPU""", """MULTI_GPU""", """MULTI_NPU""", """TPU"""][value] ) def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return DynamoBackend(DYNAMO_BACKENDS[value] ).value def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return PrecisionType(["""no""", """fp16""", """bf16""", """fp8"""][value] ) def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return SageMakerDistributedType(["""NO""", """DATA_PARALLEL""", """MODEL_PARALLEL"""][value] ) def a__ ( a__ ): """simple docstring""" return {"yes": True, "no": False}[value.lower()] class lowerCAmelCase__ ( argparse.RawDescriptionHelpFormatter ): """simple docstring""" def UpperCAmelCase__ ( self : str , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : List[Any] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = super()._format_usage(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = usage.replace("""<command> [<args>] """ , """""" ) return usage
267
1
'''simple docstring''' import importlib import inspect import json import os import re import shutil import sys from pathlib import Path from typing import Dict, Optional, Union from urllib import request from huggingface_hub import HfFolder, cached_download, hf_hub_download, model_info from packaging import version from .. import __version__ from . import DIFFUSERS_DYNAMIC_MODULE_NAME, HF_MODULES_CACHE, logging UpperCAmelCase : Dict = ( 'https://raw.githubusercontent.com/huggingface/diffusers/{revision}/examples/community/{pipeline}.py' ) UpperCAmelCase : Optional[int] = logging.get_logger(__name__) # pylint: disable=invalid-name def a__ ( ): """simple docstring""" __SCREAMING_SNAKE_CASE = """https://pypi.org/pypi/diffusers/json""" __SCREAMING_SNAKE_CASE = json.loads(request.urlopen(a__ ).read() )["""releases"""].keys() return sorted(a__ , key=lambda a__ : version.Version(a__ ) ) def a__ ( ): """simple docstring""" if HF_MODULES_CACHE in sys.path: return sys.path.append(a__ ) os.makedirs(a__ , exist_ok=a__ ) __SCREAMING_SNAKE_CASE = Path(a__ ) / """__init__.py""" if not init_path.exists(): init_path.touch() def a__ ( a__ ): """simple docstring""" init_hf_modules() __SCREAMING_SNAKE_CASE = Path(a__ ) / name # If the parent module does not exist yet, recursively create it. if not dynamic_module_path.parent.exists(): create_dynamic_module(dynamic_module_path.parent ) os.makedirs(a__ , exist_ok=a__ ) __SCREAMING_SNAKE_CASE = dynamic_module_path / """__init__.py""" if not init_path.exists(): init_path.touch() def a__ ( a__ ): """simple docstring""" with open(a__ , """r""" , encoding="""utf-8""" ) as f: __SCREAMING_SNAKE_CASE = f.read() # Imports of the form `import .xxx` __SCREAMING_SNAKE_CASE = re.findall("""^\s*import\s+\.(\S+)\s*$""" , a__ , flags=re.MULTILINE ) # Imports of the form `from .xxx import yyy` relative_imports += re.findall("""^\s*from\s+\.(\S+)\s+import""" , a__ , flags=re.MULTILINE ) # Unique-ify return list(set(a__ ) ) def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = [module_file] __SCREAMING_SNAKE_CASE = [] # Let's recurse through all relative imports while not no_change: __SCREAMING_SNAKE_CASE = [] for f in files_to_check: new_imports.extend(get_relative_imports(a__ ) ) __SCREAMING_SNAKE_CASE = Path(a__ ).parent __SCREAMING_SNAKE_CASE = [str(module_path / m ) for m in new_imports] __SCREAMING_SNAKE_CASE = [f for f in new_import_files if f not in all_relative_imports] __SCREAMING_SNAKE_CASE = [F'{f}.py' for f in new_import_files] __SCREAMING_SNAKE_CASE = len(a__ ) == 0 all_relative_imports.extend(a__ ) return all_relative_imports def a__ ( a__ ): """simple docstring""" with open(a__ , """r""" , encoding="""utf-8""" ) as f: __SCREAMING_SNAKE_CASE = f.read() # Imports of the form `import xxx` __SCREAMING_SNAKE_CASE = re.findall("""^\s*import\s+(\S+)\s*$""" , a__ , flags=re.MULTILINE ) # Imports of the form `from xxx import yyy` imports += re.findall("""^\s*from\s+(\S+)\s+import""" , a__ , flags=re.MULTILINE ) # Only keep the top-level module __SCREAMING_SNAKE_CASE = [imp.split(""".""" )[0] for imp in imports if not imp.startswith(""".""" )] # Unique-ify and test we got them all __SCREAMING_SNAKE_CASE = list(set(a__ ) ) __SCREAMING_SNAKE_CASE = [] for imp in imports: try: importlib.import_module(a__ ) except ImportError: missing_packages.append(a__ ) if len(a__ ) > 0: raise ImportError( """This modeling file requires the following packages that were not found in your environment: """ F'{", ".join(a__ )}. Run `pip install {" ".join(a__ )}`' ) return get_relative_imports(a__ ) def a__ ( a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = module_path.replace(os.path.sep , """.""" ) __SCREAMING_SNAKE_CASE = importlib.import_module(a__ ) if class_name is None: return find_pipeline_class(a__ ) return getattr(a__ , a__ ) def a__ ( a__ ): """simple docstring""" from ..pipelines import DiffusionPipeline __SCREAMING_SNAKE_CASE = dict(inspect.getmembers(a__ , inspect.isclass ) ) __SCREAMING_SNAKE_CASE = None for cls_name, cls in cls_members.items(): if ( cls_name != DiffusionPipeline.__name__ and issubclass(cls , a__ ) and cls.__module__.split(""".""" )[0] != "diffusers" ): if pipeline_class is not None: raise ValueError( F'Multiple classes that inherit from {DiffusionPipeline.__name__} have been found:' F' {pipeline_class.__name__}, and {cls_name}. Please make sure to define only one in' F' {loaded_module}.' ) __SCREAMING_SNAKE_CASE = cls return pipeline_class def a__ ( a__ , a__ , a__ = None , a__ = False , a__ = False , a__ = None , a__ = None , a__ = None , a__ = False , ): """simple docstring""" __SCREAMING_SNAKE_CASE = str(a__ ) __SCREAMING_SNAKE_CASE = os.path.join(a__ , a__ ) if os.path.isfile(a__ ): __SCREAMING_SNAKE_CASE = module_file_or_url __SCREAMING_SNAKE_CASE = """local""" elif pretrained_model_name_or_path.count("""/""" ) == 0: __SCREAMING_SNAKE_CASE = get_diffusers_versions() # cut ".dev0" __SCREAMING_SNAKE_CASE = """v""" + """.""".join(__version__.split(""".""" )[:3] ) # retrieve github version that matches if revision is None: __SCREAMING_SNAKE_CASE = latest_version if latest_version[1:] in available_versions else """main""" logger.info(F'Defaulting to latest_version: {revision}.' ) elif revision in available_versions: __SCREAMING_SNAKE_CASE = F'v{revision}' elif revision == "main": __SCREAMING_SNAKE_CASE = revision else: raise ValueError( F'`custom_revision`: {revision} does not exist. Please make sure to choose one of' F' {", ".join(available_versions + ["main"] )}.' ) # community pipeline on GitHub __SCREAMING_SNAKE_CASE = COMMUNITY_PIPELINES_URL.format(revision=a__ , pipeline=a__ ) try: __SCREAMING_SNAKE_CASE = cached_download( a__ , cache_dir=a__ , force_download=a__ , proxies=a__ , resume_download=a__ , local_files_only=a__ , use_auth_token=a__ , ) __SCREAMING_SNAKE_CASE = """git""" __SCREAMING_SNAKE_CASE = pretrained_model_name_or_path + """.py""" except EnvironmentError: logger.error(F'Could not locate the {module_file} inside {pretrained_model_name_or_path}.' ) raise else: try: # Load from URL or cache if already cached __SCREAMING_SNAKE_CASE = hf_hub_download( a__ , a__ , cache_dir=a__ , force_download=a__ , proxies=a__ , resume_download=a__ , local_files_only=a__ , use_auth_token=a__ , ) __SCREAMING_SNAKE_CASE = os.path.join("""local""" , """--""".join(pretrained_model_name_or_path.split("""/""" ) ) ) except EnvironmentError: logger.error(F'Could not locate the {module_file} inside {pretrained_model_name_or_path}.' ) raise # Check we have all the requirements in our environment __SCREAMING_SNAKE_CASE = check_imports(a__ ) # Now we move the module inside our cached dynamic modules. __SCREAMING_SNAKE_CASE = DIFFUSERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule create_dynamic_module(a__ ) __SCREAMING_SNAKE_CASE = Path(a__ ) / full_submodule if submodule == "local" or submodule == "git": # We always copy local files (we could hash the file to see if there was a change, and give them the name of # that hash, to only copy when there is a modification but it seems overkill for now). # The only reason we do the copy is to avoid putting too many folders in sys.path. shutil.copy(a__ , submodule_path / module_file ) for module_needed in modules_needed: __SCREAMING_SNAKE_CASE = F'{module_needed}.py' shutil.copy(os.path.join(a__ , a__ ) , submodule_path / module_needed ) else: # Get the commit hash # TODO: we will get this info in the etag soon, so retrieve it from there and not here. if isinstance(a__ , a__ ): __SCREAMING_SNAKE_CASE = use_auth_token elif use_auth_token is True: __SCREAMING_SNAKE_CASE = HfFolder.get_token() else: __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = model_info(a__ , revision=a__ , token=a__ ).sha # The module file will end up being placed in a subfolder with the git hash of the repo. This way we get the # benefit of versioning. __SCREAMING_SNAKE_CASE = submodule_path / commit_hash __SCREAMING_SNAKE_CASE = full_submodule + os.path.sep + commit_hash create_dynamic_module(a__ ) if not (submodule_path / module_file).exists(): shutil.copy(a__ , submodule_path / module_file ) # Make sure we also have every file with relative for module_needed in modules_needed: if not (submodule_path / module_needed).exists(): get_cached_module_file( a__ , F'{module_needed}.py' , cache_dir=a__ , force_download=a__ , resume_download=a__ , proxies=a__ , use_auth_token=a__ , revision=a__ , local_files_only=a__ , ) return os.path.join(a__ , a__ ) def a__ ( a__ , a__ , a__ = None , a__ = None , a__ = False , a__ = False , a__ = None , a__ = None , a__ = None , a__ = False , **a__ , ): """simple docstring""" __SCREAMING_SNAKE_CASE = get_cached_module_file( a__ , a__ , cache_dir=a__ , force_download=a__ , resume_download=a__ , proxies=a__ , use_auth_token=a__ , revision=a__ , local_files_only=a__ , ) return get_class_in_module(a__ , final_module.replace(""".py""" , """""" ) )
267
'''simple docstring''' def a__ ( a__ , a__ ): """simple docstring""" _enforce_args(a__ , a__ ) if n == 0: return 0 __SCREAMING_SNAKE_CASE = float("""-inf""" ) for i in range(1 , n + 1 ): __SCREAMING_SNAKE_CASE = max( a__ , prices[i - 1] + naive_cut_rod_recursive(n - i , a__ ) ) return max_revue def a__ ( a__ , a__ ): """simple docstring""" _enforce_args(a__ , a__ ) __SCREAMING_SNAKE_CASE = [float("""-inf""" ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ ): """simple docstring""" if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: __SCREAMING_SNAKE_CASE = float("""-inf""" ) for i in range(1 , n + 1 ): __SCREAMING_SNAKE_CASE = max( a__ , prices[i - 1] + _top_down_cut_rod_recursive(n - i , a__ , a__ ) , ) __SCREAMING_SNAKE_CASE = max_revenue return max_rev[n] def a__ ( a__ , a__ ): """simple docstring""" _enforce_args(a__ , a__ ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. __SCREAMING_SNAKE_CASE = [float("""-inf""" ) for _ in range(n + 1 )] __SCREAMING_SNAKE_CASE = 0 for i in range(1 , n + 1 ): __SCREAMING_SNAKE_CASE = max_rev[i] for j in range(1 , i + 1 ): __SCREAMING_SNAKE_CASE = max(a__ , prices[j - 1] + max_rev[i - j] ) __SCREAMING_SNAKE_CASE = max_revenue_i return max_rev[n] def a__ ( a__ , a__ ): """simple docstring""" if n < 0: __SCREAMING_SNAKE_CASE = F'n must be greater than or equal to 0. Got n = {n}' raise ValueError(a__ ) if n > len(a__ ): __SCREAMING_SNAKE_CASE = ( """Each integral piece of rod must have a corresponding price. """ F'Got n = {n} but length of prices = {len(a__ )}' ) raise ValueError(a__ ) def a__ ( ): """simple docstring""" __SCREAMING_SNAKE_CASE = [6, 10, 12, 15, 20, 23] __SCREAMING_SNAKE_CASE = len(a__ ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. __SCREAMING_SNAKE_CASE = 36 __SCREAMING_SNAKE_CASE = top_down_cut_rod(a__ , a__ ) __SCREAMING_SNAKE_CASE = bottom_up_cut_rod(a__ , a__ ) __SCREAMING_SNAKE_CASE = naive_cut_rod_recursive(a__ , a__ ) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
267
1
'''simple docstring''' import copy from typing import Any, Dict, List, Optional, Union import numpy as np import torch from ...audio_utils import mel_filter_bank, spectrogram, window_function from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import TensorType, logging UpperCAmelCase : Union[str, Any] = logging.get_logger(__name__) class lowerCAmelCase__ ( a ): """simple docstring""" lowerCAmelCase__ = ["input_features", "is_longer"] def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : List[Any]=64 , __SCREAMING_SNAKE_CASE : Optional[Any]=48_000 , __SCREAMING_SNAKE_CASE : Union[str, Any]=480 , __SCREAMING_SNAKE_CASE : str=10 , __SCREAMING_SNAKE_CASE : Dict=1_024 , __SCREAMING_SNAKE_CASE : Tuple=0.0 , __SCREAMING_SNAKE_CASE : Dict=False , __SCREAMING_SNAKE_CASE : float = 0 , __SCREAMING_SNAKE_CASE : float = 14_000 , __SCREAMING_SNAKE_CASE : int = None , __SCREAMING_SNAKE_CASE : str = "fusion" , __SCREAMING_SNAKE_CASE : str = "repeatpad" , **__SCREAMING_SNAKE_CASE : Any , ) -> Union[str, Any]: """simple docstring""" super().__init__( feature_size=__SCREAMING_SNAKE_CASE , sampling_rate=__SCREAMING_SNAKE_CASE , padding_value=__SCREAMING_SNAKE_CASE , return_attention_mask=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) __SCREAMING_SNAKE_CASE = top_db __SCREAMING_SNAKE_CASE = truncation __SCREAMING_SNAKE_CASE = padding __SCREAMING_SNAKE_CASE = fft_window_size __SCREAMING_SNAKE_CASE = (fft_window_size >> 1) + 1 __SCREAMING_SNAKE_CASE = hop_length __SCREAMING_SNAKE_CASE = max_length_s __SCREAMING_SNAKE_CASE = max_length_s * sampling_rate __SCREAMING_SNAKE_CASE = sampling_rate __SCREAMING_SNAKE_CASE = frequency_min __SCREAMING_SNAKE_CASE = frequency_max __SCREAMING_SNAKE_CASE = mel_filter_bank( num_frequency_bins=self.nb_frequency_bins , num_mel_filters=__SCREAMING_SNAKE_CASE , min_frequency=__SCREAMING_SNAKE_CASE , max_frequency=__SCREAMING_SNAKE_CASE , sampling_rate=__SCREAMING_SNAKE_CASE , norm=__SCREAMING_SNAKE_CASE , mel_scale="""htk""" , ) __SCREAMING_SNAKE_CASE = mel_filter_bank( num_frequency_bins=self.nb_frequency_bins , num_mel_filters=__SCREAMING_SNAKE_CASE , min_frequency=__SCREAMING_SNAKE_CASE , max_frequency=__SCREAMING_SNAKE_CASE , sampling_rate=__SCREAMING_SNAKE_CASE , norm="""slaney""" , mel_scale="""slaney""" , ) def UpperCAmelCase__ ( self : Dict ) -> Dict[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = copy.deepcopy(self.__dict__ ) __SCREAMING_SNAKE_CASE = self.__class__.__name__ if "mel_filters" in output: del output["mel_filters"] if "mel_filters_slaney" in output: del output["mel_filters_slaney"] return output def UpperCAmelCase__ ( self : Tuple , __SCREAMING_SNAKE_CASE : np.array , __SCREAMING_SNAKE_CASE : Optional[np.array] = None ) -> np.ndarray: """simple docstring""" __SCREAMING_SNAKE_CASE = spectrogram( __SCREAMING_SNAKE_CASE , window_function(self.fft_window_size , """hann""" ) , frame_length=self.fft_window_size , hop_length=self.hop_length , power=2.0 , mel_filters=__SCREAMING_SNAKE_CASE , log_mel="""dB""" , ) return log_mel_spectrogram.T def UpperCAmelCase__ ( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = np.array_split(list(range(0 , total_frames - chunk_frames + 1 ) ) , 3 ) if len(ranges[1] ) == 0: # if the audio is too short, we just use the first chunk __SCREAMING_SNAKE_CASE = [0] if len(ranges[2] ) == 0: # if the audio is too short, we just use the first chunk __SCREAMING_SNAKE_CASE = [0] # randomly choose index for each part __SCREAMING_SNAKE_CASE = np.random.choice(ranges[0] ) __SCREAMING_SNAKE_CASE = np.random.choice(ranges[1] ) __SCREAMING_SNAKE_CASE = np.random.choice(ranges[2] ) __SCREAMING_SNAKE_CASE = mel[idx_front : idx_front + chunk_frames, :] __SCREAMING_SNAKE_CASE = mel[idx_middle : idx_middle + chunk_frames, :] __SCREAMING_SNAKE_CASE = mel[idx_back : idx_back + chunk_frames, :] __SCREAMING_SNAKE_CASE = torch.tensor(mel[None, None, :] ) __SCREAMING_SNAKE_CASE = torch.nn.functional.interpolate( __SCREAMING_SNAKE_CASE , size=[chunk_frames, 64] , mode="""bilinear""" , align_corners=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = mel_shrink[0][0].numpy() __SCREAMING_SNAKE_CASE = np.stack([mel_shrink, mel_chunk_front, mel_chunk_middle, mel_chunk_back] , axis=0 ) return mel_fusion def UpperCAmelCase__ ( self : List[str] , __SCREAMING_SNAKE_CASE : np.array , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Dict ) -> np.array: """simple docstring""" if waveform.shape[0] > max_length: if truncation == "rand_trunc": __SCREAMING_SNAKE_CASE = True # random crop to max_length (for compatibility) -> this should be handled by self.pad __SCREAMING_SNAKE_CASE = len(__SCREAMING_SNAKE_CASE ) - max_length __SCREAMING_SNAKE_CASE = np.random.randint(0 , overflow + 1 ) __SCREAMING_SNAKE_CASE = waveform[idx : idx + max_length] __SCREAMING_SNAKE_CASE = self._np_extract_fbank_features(__SCREAMING_SNAKE_CASE , self.mel_filters_slaney )[None, :] elif truncation == "fusion": __SCREAMING_SNAKE_CASE = self._np_extract_fbank_features(__SCREAMING_SNAKE_CASE , self.mel_filters ) __SCREAMING_SNAKE_CASE = max_length // self.hop_length + 1 # the +1 related to how the spectrogram is computed __SCREAMING_SNAKE_CASE = mel.shape[0] if chunk_frames == total_frames: # there is a corner case where the audio length is larger than max_length but smaller than max_length+hop_length. # In this case, we just use the whole audio. __SCREAMING_SNAKE_CASE = np.stack([mel, mel, mel, mel] , axis=0 ) __SCREAMING_SNAKE_CASE = False else: __SCREAMING_SNAKE_CASE = self._random_mel_fusion(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = True else: raise NotImplementedError(f'data_truncating {truncation} not implemented' ) else: __SCREAMING_SNAKE_CASE = False # only use repeat as a new possible value for padding. you repeat the audio before applying the usual max_length padding if waveform.shape[0] < max_length: if padding == "repeat": __SCREAMING_SNAKE_CASE = int(max_length / len(__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = np.stack(np.tile(__SCREAMING_SNAKE_CASE , n_repeat + 1 ) )[:max_length] if padding == "repeatpad": __SCREAMING_SNAKE_CASE = int(max_length / len(__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = np.stack(np.tile(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = np.pad(__SCREAMING_SNAKE_CASE , (0, max_length - waveform.shape[0]) , mode="""constant""" , constant_values=0 ) if truncation == "fusion": __SCREAMING_SNAKE_CASE = self._np_extract_fbank_features(__SCREAMING_SNAKE_CASE , self.mel_filters ) __SCREAMING_SNAKE_CASE = np.stack([input_mel, input_mel, input_mel, input_mel] , axis=0 ) else: __SCREAMING_SNAKE_CASE = self._np_extract_fbank_features(__SCREAMING_SNAKE_CASE , self.mel_filters_slaney )[None, :] return input_mel, longer def __call__( self : Tuple , __SCREAMING_SNAKE_CASE : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , __SCREAMING_SNAKE_CASE : str = None , __SCREAMING_SNAKE_CASE : Optional[str] = None , __SCREAMING_SNAKE_CASE : Optional[int] = None , __SCREAMING_SNAKE_CASE : Optional[int] = None , __SCREAMING_SNAKE_CASE : Optional[Union[str, TensorType]] = None , **__SCREAMING_SNAKE_CASE : Dict , ) -> BatchFeature: """simple docstring""" __SCREAMING_SNAKE_CASE = truncation if truncation is not None else self.truncation __SCREAMING_SNAKE_CASE = padding if padding else self.padding if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f'The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a' f' sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input' f' was sampled with {self.sampling_rate} and not {sampling_rate}.' ) else: logger.warning( """It is strongly recommended to pass the `sampling_rate` argument to this function. """ """Failing to do so can result in silent errors that might be hard to debug.""" ) __SCREAMING_SNAKE_CASE = isinstance(__SCREAMING_SNAKE_CASE , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(f'Only mono-channel audio is supported for input to {self}' ) __SCREAMING_SNAKE_CASE = is_batched_numpy or ( isinstance(__SCREAMING_SNAKE_CASE , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE , dtype=np.floataa ) for speech in raw_speech] elif not is_batched and not isinstance(__SCREAMING_SNAKE_CASE , np.ndarray ): __SCREAMING_SNAKE_CASE = np.asarray(__SCREAMING_SNAKE_CASE , dtype=np.floataa ) elif isinstance(__SCREAMING_SNAKE_CASE , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): __SCREAMING_SNAKE_CASE = raw_speech.astype(np.floataa ) # always return batch if not is_batched: __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE )] # convert to mel spectrogram, truncate and pad if needed. __SCREAMING_SNAKE_CASE = [ self._get_input_mel(__SCREAMING_SNAKE_CASE , max_length if max_length else self.nb_max_samples , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) for waveform in raw_speech ] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] for mel, longer in padded_inputs: input_mel.append(__SCREAMING_SNAKE_CASE ) is_longer.append(__SCREAMING_SNAKE_CASE ) if truncation == "fusion" and sum(__SCREAMING_SNAKE_CASE ) == 0: # if no audio is longer than 10s, then randomly select one audio to be longer __SCREAMING_SNAKE_CASE = np.random.randint(0 , len(__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = True if isinstance(input_mel[0] , __SCREAMING_SNAKE_CASE ): __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE , dtype=np.floataa ) for feature in input_mel] # is_longer is a list of bool __SCREAMING_SNAKE_CASE = [[longer] for longer in is_longer] __SCREAMING_SNAKE_CASE = {"""input_features""": input_mel, """is_longer""": is_longer} __SCREAMING_SNAKE_CASE = BatchFeature(__SCREAMING_SNAKE_CASE ) if return_tensors is not None: __SCREAMING_SNAKE_CASE = input_features.convert_to_tensors(__SCREAMING_SNAKE_CASE ) return input_features
267
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase : Union[str, Any] = {'configuration_sew': ['SEW_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SEWConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Union[str, Any] = [ 'SEW_PRETRAINED_MODEL_ARCHIVE_LIST', 'SEWForCTC', 'SEWForSequenceClassification', 'SEWModel', 'SEWPreTrainedModel', ] if TYPE_CHECKING: from .configuration_sew import SEW_PRETRAINED_CONFIG_ARCHIVE_MAP, SEWConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_sew import ( SEW_PRETRAINED_MODEL_ARCHIVE_LIST, SEWForCTC, SEWForSequenceClassification, SEWModel, SEWPreTrainedModel, ) else: import sys UpperCAmelCase : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
267
1
'''simple docstring''' import warnings from ...utils import logging from .image_processing_chinese_clip import ChineseCLIPImageProcessor UpperCAmelCase : Tuple = logging.get_logger(__name__) class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : List[Any] , *__SCREAMING_SNAKE_CASE : Dict , **__SCREAMING_SNAKE_CASE : str ) -> None: """simple docstring""" warnings.warn( """The class ChineseCLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use ChineseCLIPImageProcessor instead.""" , __SCREAMING_SNAKE_CASE , ) super().__init__(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE )
267
'''simple docstring''' class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Any ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = name __SCREAMING_SNAKE_CASE = value __SCREAMING_SNAKE_CASE = weight def __repr__( self : str ) -> Union[str, Any]: """simple docstring""" return f'{self.__class__.__name__}({self.name}, {self.value}, {self.weight})' def UpperCAmelCase__ ( self : List[Any] ) -> List[Any]: """simple docstring""" return self.value def UpperCAmelCase__ ( self : Any ) -> str: """simple docstring""" return self.name def UpperCAmelCase__ ( self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" return self.weight def UpperCAmelCase__ ( self : int ) -> Tuple: """simple docstring""" return self.value / self.weight def a__ ( a__ , a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = [] for i in range(len(a__ ) ): menu.append(Things(name[i] , value[i] , weight[i] ) ) return menu def a__ ( a__ , a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = sorted(a__ , key=a__ , reverse=a__ ) __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = 0.0, 0.0 for i in range(len(a__ ) ): if (total_cost + items_copy[i].get_weight()) <= max_cost: result.append(items_copy[i] ) total_cost += items_copy[i].get_weight() total_value += items_copy[i].get_value() return (result, total_value) def a__ ( ): """simple docstring""" if __name__ == "__main__": import doctest doctest.testmod()
267
1
'''simple docstring''' import os import string import sys UpperCAmelCase : Union[str, Any] = 1 << 8 UpperCAmelCase : Any = { 'tab': ord('\t'), 'newline': ord('\r'), 'esc': 2_7, 'up': 6_5 + ARROW_KEY_FLAG, 'down': 6_6 + ARROW_KEY_FLAG, 'right': 6_7 + ARROW_KEY_FLAG, 'left': 6_8 + ARROW_KEY_FLAG, 'mod_int': 9_1, 'undefined': sys.maxsize, 'interrupt': 3, 'insert': 5_0, 'delete': 5_1, 'pg_up': 5_3, 'pg_down': 5_4, } UpperCAmelCase : Optional[Any] = KEYMAP['up'] UpperCAmelCase : Optional[int] = KEYMAP['left'] if sys.platform == "win32": UpperCAmelCase : Union[str, Any] = [] UpperCAmelCase : Dict = { b'\xe0H': KEYMAP['up'] - ARROW_KEY_FLAG, b'\x00H': KEYMAP['up'] - ARROW_KEY_FLAG, b'\xe0P': KEYMAP['down'] - ARROW_KEY_FLAG, b'\x00P': KEYMAP['down'] - ARROW_KEY_FLAG, b'\xe0M': KEYMAP['right'] - ARROW_KEY_FLAG, b'\x00M': KEYMAP['right'] - ARROW_KEY_FLAG, b'\xe0K': KEYMAP['left'] - ARROW_KEY_FLAG, b'\x00K': KEYMAP['left'] - ARROW_KEY_FLAG, } for i in range(1_0): UpperCAmelCase : Tuple = ord(str(i)) def a__ ( ): """simple docstring""" if os.name == "nt": import msvcrt __SCREAMING_SNAKE_CASE = """mbcs""" # Flush the keyboard buffer while msvcrt.kbhit(): msvcrt.getch() if len(a__ ) == 0: # Read the keystroke __SCREAMING_SNAKE_CASE = msvcrt.getch() # If it is a prefix char, get second part if ch in (b"\x00", b"\xe0"): __SCREAMING_SNAKE_CASE = ch + msvcrt.getch() # Translate actual Win chars to bullet char types try: __SCREAMING_SNAKE_CASE = chr(WIN_KEYMAP[cha] ) WIN_CH_BUFFER.append(chr(KEYMAP["""mod_int"""] ) ) WIN_CH_BUFFER.append(a__ ) if ord(a__ ) in ( KEYMAP["insert"] - 1 << 9, KEYMAP["delete"] - 1 << 9, KEYMAP["pg_up"] - 1 << 9, KEYMAP["pg_down"] - 1 << 9, ): WIN_CH_BUFFER.append(chr(1_26 ) ) __SCREAMING_SNAKE_CASE = chr(KEYMAP["""esc"""] ) except KeyError: __SCREAMING_SNAKE_CASE = cha[1] else: __SCREAMING_SNAKE_CASE = ch.decode(a__ ) else: __SCREAMING_SNAKE_CASE = WIN_CH_BUFFER.pop(0 ) elif os.name == "posix": import termios import tty __SCREAMING_SNAKE_CASE = sys.stdin.fileno() __SCREAMING_SNAKE_CASE = termios.tcgetattr(a__ ) try: tty.setraw(a__ ) __SCREAMING_SNAKE_CASE = sys.stdin.read(1 ) finally: termios.tcsetattr(a__ , termios.TCSADRAIN , a__ ) return ch def a__ ( ): """simple docstring""" __SCREAMING_SNAKE_CASE = get_raw_chars() if ord(a__ ) in [KEYMAP["interrupt"], KEYMAP["newline"]]: return char elif ord(a__ ) == KEYMAP["esc"]: __SCREAMING_SNAKE_CASE = get_raw_chars() if ord(a__ ) == KEYMAP["mod_int"]: __SCREAMING_SNAKE_CASE = get_raw_chars() if ord(a__ ) >= KEYMAP["arrow_begin"] - ARROW_KEY_FLAG and ord(a__ ) <= KEYMAP["arrow_end"] - ARROW_KEY_FLAG: return chr(ord(a__ ) + ARROW_KEY_FLAG ) else: return KEYMAP["undefined"] else: return get_raw_chars() else: if char in string.printable: return char else: return KEYMAP["undefined"]
267
'''simple docstring''' import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import CLIPImageProcessor, CLIPProcessor @require_vision class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : Union[str, Any] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() # fmt: off __SCREAMING_SNAKE_CASE = ["""l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """lo""", """l</w>""", """w</w>""", """r</w>""", """t</w>""", """low</w>""", """er</w>""", """lowest</w>""", """newer</w>""", """wider""", """<unk>""", """<|startoftext|>""", """<|endoftext|>"""] # fmt: on __SCREAMING_SNAKE_CASE = dict(zip(__SCREAMING_SNAKE_CASE , range(len(__SCREAMING_SNAKE_CASE ) ) ) ) __SCREAMING_SNAKE_CASE = ["""#version: 0.2""", """l o""", """lo w</w>""", """e r</w>""", """"""] __SCREAMING_SNAKE_CASE = {"""unk_token""": """<unk>"""} __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) __SCREAMING_SNAKE_CASE = 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(__SCREAMING_SNAKE_CASE ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = { """do_resize""": True, """size""": 20, """do_center_crop""": True, """crop_size""": 18, """do_normalize""": True, """image_mean""": [0.48145466, 0.4578275, 0.40821073], """image_std""": [0.26862954, 0.26130258, 0.27577711], } __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , __SCREAMING_SNAKE_CASE ) with open(self.image_processor_file , """w""" , encoding="""utf-8""" ) as fp: json.dump(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] , **__SCREAMING_SNAKE_CASE : Optional[int] ) -> str: """simple docstring""" return CLIPTokenizer.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Tuple , **__SCREAMING_SNAKE_CASE : Any ) -> int: """simple docstring""" return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[Any] , **__SCREAMING_SNAKE_CASE : Optional[int] ) -> List[str]: """simple docstring""" return CLIPImageProcessor.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Tuple ) -> str: """simple docstring""" shutil.rmtree(self.tmpdirname ) def UpperCAmelCase__ ( self : Optional[Any] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __SCREAMING_SNAKE_CASE = [Image.fromarray(np.moveaxis(__SCREAMING_SNAKE_CASE , 0 , -1 ) ) for x in image_inputs] return image_inputs def UpperCAmelCase__ ( self : Optional[int] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = self.get_rust_tokenizer() __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) processor_slow.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = CLIPProcessor.from_pretrained(self.tmpdirname , use_fast=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) processor_fast.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = CLIPProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , __SCREAMING_SNAKE_CASE ) self.assertIsInstance(processor_fast.tokenizer , __SCREAMING_SNAKE_CASE ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , __SCREAMING_SNAKE_CASE ) self.assertIsInstance(processor_fast.image_processor , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) __SCREAMING_SNAKE_CASE = self.get_image_processor(do_normalize=__SCREAMING_SNAKE_CASE , padding_value=1.0 ) __SCREAMING_SNAKE_CASE = CLIPProcessor.from_pretrained( self.tmpdirname , bos_token="""(BOS)""" , eos_token="""(EOS)""" , do_normalize=__SCREAMING_SNAKE_CASE , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , __SCREAMING_SNAKE_CASE ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[str] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = image_processor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ) __SCREAMING_SNAKE_CASE = processor(images=__SCREAMING_SNAKE_CASE , return_tensors="""np""" ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1E-2 ) def UpperCAmelCase__ ( self : List[Any] ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """lower newer""" __SCREAMING_SNAKE_CASE = processor(text=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer(__SCREAMING_SNAKE_CASE ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def UpperCAmelCase__ ( self : Dict ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """lower newer""" __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = processor(text=__SCREAMING_SNAKE_CASE , images=__SCREAMING_SNAKE_CASE ) self.assertListEqual(list(inputs.keys() ) , ["""input_ids""", """attention_mask""", """pixel_values"""] ) # test if it raises when no input is passed with pytest.raises(__SCREAMING_SNAKE_CASE ): processor() def UpperCAmelCase__ ( self : List[str] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __SCREAMING_SNAKE_CASE = processor.batch_decode(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer.batch_decode(__SCREAMING_SNAKE_CASE ) self.assertListEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : int ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """lower newer""" __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = processor(text=__SCREAMING_SNAKE_CASE , images=__SCREAMING_SNAKE_CASE ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
267
1
'''simple docstring''' import argparse import json import os from collections import OrderedDict import torch from transformers import LukeConfig, LukeForMaskedLM, MLukeTokenizer, XLMRobertaTokenizer from transformers.tokenization_utils_base import AddedToken @torch.no_grad() def a__ ( a__ , a__ , a__ , a__ , a__ ): """simple docstring""" with open(a__ ) as metadata_file: __SCREAMING_SNAKE_CASE = json.load(a__ ) __SCREAMING_SNAKE_CASE = LukeConfig(use_entity_aware_attention=a__ , **metadata["""model_config"""] ) # Load in the weights from the checkpoint_path __SCREAMING_SNAKE_CASE = torch.load(a__ , map_location="""cpu""" )["""module"""] # Load the entity vocab file __SCREAMING_SNAKE_CASE = load_original_entity_vocab(a__ ) # add an entry for [MASK2] __SCREAMING_SNAKE_CASE = max(entity_vocab.values() ) + 1 config.entity_vocab_size += 1 __SCREAMING_SNAKE_CASE = XLMRobertaTokenizer.from_pretrained(metadata["""model_config"""]["""bert_model_name"""] ) # Add special tokens to the token vocabulary for downstream tasks __SCREAMING_SNAKE_CASE = AddedToken("""<ent>""" , lstrip=a__ , rstrip=a__ ) __SCREAMING_SNAKE_CASE = AddedToken("""<ent2>""" , lstrip=a__ , rstrip=a__ ) tokenizer.add_special_tokens({"""additional_special_tokens""": [entity_token_a, entity_token_a]} ) config.vocab_size += 2 print(F'Saving tokenizer to {pytorch_dump_folder_path}' ) tokenizer.save_pretrained(a__ ) with open(os.path.join(a__ , """tokenizer_config.json""" ) , """r""" ) as f: __SCREAMING_SNAKE_CASE = json.load(a__ ) __SCREAMING_SNAKE_CASE = """MLukeTokenizer""" with open(os.path.join(a__ , """tokenizer_config.json""" ) , """w""" ) as f: json.dump(a__ , a__ ) with open(os.path.join(a__ , MLukeTokenizer.vocab_files_names["""entity_vocab_file"""] ) , """w""" ) as f: json.dump(a__ , a__ ) __SCREAMING_SNAKE_CASE = MLukeTokenizer.from_pretrained(a__ ) # Initialize the embeddings of the special tokens __SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_ids(["""@"""] )[0] __SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_ids(["""#"""] )[0] __SCREAMING_SNAKE_CASE = state_dict["""embeddings.word_embeddings.weight"""] __SCREAMING_SNAKE_CASE = word_emb[ent_init_index].unsqueeze(0 ) __SCREAMING_SNAKE_CASE = word_emb[enta_init_index].unsqueeze(0 ) __SCREAMING_SNAKE_CASE = torch.cat([word_emb, ent_emb, enta_emb] ) # add special tokens for 'entity_predictions.bias' for bias_name in ["lm_head.decoder.bias", "lm_head.bias"]: __SCREAMING_SNAKE_CASE = state_dict[bias_name] __SCREAMING_SNAKE_CASE = decoder_bias[ent_init_index].unsqueeze(0 ) __SCREAMING_SNAKE_CASE = decoder_bias[enta_init_index].unsqueeze(0 ) __SCREAMING_SNAKE_CASE = torch.cat([decoder_bias, ent_decoder_bias, enta_decoder_bias] ) # Initialize the query layers of the entity-aware self-attention mechanism for layer_index in range(config.num_hidden_layers ): for matrix_name in ["query.weight", "query.bias"]: __SCREAMING_SNAKE_CASE = F'encoder.layer.{layer_index}.attention.self.' __SCREAMING_SNAKE_CASE = state_dict[prefix + matrix_name] __SCREAMING_SNAKE_CASE = state_dict[prefix + matrix_name] __SCREAMING_SNAKE_CASE = state_dict[prefix + matrix_name] # Initialize the embedding of the [MASK2] entity using that of the [MASK] entity for downstream tasks __SCREAMING_SNAKE_CASE = state_dict["""entity_embeddings.entity_embeddings.weight"""] __SCREAMING_SNAKE_CASE = entity_emb[entity_vocab["""[MASK]"""]].unsqueeze(0 ) __SCREAMING_SNAKE_CASE = torch.cat([entity_emb, entity_mask_emb] ) # add [MASK2] for 'entity_predictions.bias' __SCREAMING_SNAKE_CASE = state_dict["""entity_predictions.bias"""] __SCREAMING_SNAKE_CASE = entity_prediction_bias[entity_vocab["""[MASK]"""]].unsqueeze(0 ) __SCREAMING_SNAKE_CASE = torch.cat([entity_prediction_bias, entity_mask_bias] ) __SCREAMING_SNAKE_CASE = LukeForMaskedLM(config=a__ ).eval() state_dict.pop("""entity_predictions.decoder.weight""" ) state_dict.pop("""lm_head.decoder.weight""" ) state_dict.pop("""lm_head.decoder.bias""" ) __SCREAMING_SNAKE_CASE = OrderedDict() for key, value in state_dict.items(): if not (key.startswith("""lm_head""" ) or key.startswith("""entity_predictions""" )): __SCREAMING_SNAKE_CASE = state_dict[key] else: __SCREAMING_SNAKE_CASE = state_dict[key] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = model.load_state_dict(a__ , strict=a__ ) if set(a__ ) != {"luke.embeddings.position_ids"}: raise ValueError(F'Unexpected unexpected_keys: {unexpected_keys}' ) if set(a__ ) != { "lm_head.decoder.weight", "lm_head.decoder.bias", "entity_predictions.decoder.weight", }: raise ValueError(F'Unexpected missing_keys: {missing_keys}' ) model.tie_weights() assert (model.luke.embeddings.word_embeddings.weight == model.lm_head.decoder.weight).all() assert (model.luke.entity_embeddings.entity_embeddings.weight == model.entity_predictions.decoder.weight).all() # Check outputs __SCREAMING_SNAKE_CASE = MLukeTokenizer.from_pretrained(a__ , task="""entity_classification""" ) __SCREAMING_SNAKE_CASE = """ISO 639-3 uses the code fas for the dialects spoken across Iran and アフガニスタン (Afghanistan).""" __SCREAMING_SNAKE_CASE = (0, 9) __SCREAMING_SNAKE_CASE = tokenizer(a__ , entity_spans=[span] , return_tensors="""pt""" ) __SCREAMING_SNAKE_CASE = model(**a__ ) # Verify word hidden states if model_size == "large": raise NotImplementedError else: # base __SCREAMING_SNAKE_CASE = torch.Size((1, 33, 7_68) ) __SCREAMING_SNAKE_CASE = torch.tensor([[0.0_892, 0.0_596, -0.2_819], [0.0_134, 0.1_199, 0.0_573], [-0.0_169, 0.0_927, 0.0_644]] ) if not (outputs.last_hidden_state.shape == expected_shape): raise ValueError( F'Outputs.last_hidden_state.shape is {outputs.last_hidden_state.shape}, Expected shape is {expected_shape}' ) if not torch.allclose(outputs.last_hidden_state[0, :3, :3] , a__ , atol=1E-4 ): raise ValueError # Verify entity hidden states if model_size == "large": raise NotImplementedError else: # base __SCREAMING_SNAKE_CASE = torch.Size((1, 1, 7_68) ) __SCREAMING_SNAKE_CASE = torch.tensor([[-0.1_482, 0.0_609, 0.0_322]] ) if not (outputs.entity_last_hidden_state.shape == expected_shape): raise ValueError( F'Outputs.entity_last_hidden_state.shape is {outputs.entity_last_hidden_state.shape}, Expected shape is' F' {expected_shape}' ) if not torch.allclose(outputs.entity_last_hidden_state[0, :3, :3] , a__ , atol=1E-4 ): raise ValueError # Verify masked word/entity prediction __SCREAMING_SNAKE_CASE = MLukeTokenizer.from_pretrained(a__ ) __SCREAMING_SNAKE_CASE = """Tokyo is the capital of <mask>.""" __SCREAMING_SNAKE_CASE = (24, 30) __SCREAMING_SNAKE_CASE = tokenizer(a__ , entity_spans=[span] , return_tensors="""pt""" ) __SCREAMING_SNAKE_CASE = model(**a__ ) __SCREAMING_SNAKE_CASE = encoding["""input_ids"""][0].tolist() __SCREAMING_SNAKE_CASE = input_ids.index(tokenizer.convert_tokens_to_ids("""<mask>""" ) ) __SCREAMING_SNAKE_CASE = outputs.logits[0][mask_position_id].argmax(dim=-1 ) assert "Japan" == tokenizer.decode(a__ ) __SCREAMING_SNAKE_CASE = outputs.entity_logits[0][0].argmax().item() __SCREAMING_SNAKE_CASE = [ entity for entity, entity_id in tokenizer.entity_vocab.items() if entity_id == predicted_entity_id ] assert [e for e in multilingual_predicted_entities if e.startswith("""en:""" )][0] == "en:Japan" # Finally, save our PyTorch model and tokenizer print("""Saving PyTorch model to {}""".format(a__ ) ) model.save_pretrained(a__ ) def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = ["""[MASK]""", """[PAD]""", """[UNK]"""] __SCREAMING_SNAKE_CASE = [json.loads(a__ ) for line in open(a__ )] __SCREAMING_SNAKE_CASE = {} for entry in data: __SCREAMING_SNAKE_CASE = entry["""id"""] for entity_name, language in entry["entities"]: if entity_name in SPECIAL_TOKENS: __SCREAMING_SNAKE_CASE = entity_id break __SCREAMING_SNAKE_CASE = F'{language}:{entity_name}' __SCREAMING_SNAKE_CASE = entity_id return new_mapping if __name__ == "__main__": UpperCAmelCase : str = argparse.ArgumentParser() # Required parameters parser.add_argument('--checkpoint_path', type=str, help='Path to a pytorch_model.bin file.') parser.add_argument( '--metadata_path', default=None, type=str, help='Path to a metadata.json file, defining the configuration.' ) parser.add_argument( '--entity_vocab_path', default=None, type=str, help='Path to an entity_vocab.tsv file, containing the entity vocabulary.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to where to dump the output PyTorch model.' ) parser.add_argument( '--model_size', default='base', type=str, choices=['base', 'large'], help='Size of the model to be converted.' ) UpperCAmelCase : int = parser.parse_args() convert_luke_checkpoint( args.checkpoint_path, args.metadata_path, args.entity_vocab_path, args.pytorch_dump_folder_path, args.model_size, )
267
'''simple docstring''' import numpy as np def a__ ( a__ , a__ , a__ = 1E-1_2 , a__ = 1_00 , ): """simple docstring""" assert np.shape(a__ )[0] == np.shape(a__ )[1] # Ensure proper dimensionality. assert np.shape(a__ )[0] == np.shape(a__ )[0] # Ensure inputs are either both complex or both real assert np.iscomplexobj(a__ ) == np.iscomplexobj(a__ ) __SCREAMING_SNAKE_CASE = np.iscomplexobj(a__ ) if is_complex: # Ensure complex input_matrix is Hermitian assert np.array_equal(a__ , input_matrix.conj().T ) # Set convergence to False. Will define convergence when we exceed max_iterations # or when we have small changes from one iteration to next. __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 1E1_2 while not convergence: # Multiple matrix by the vector. __SCREAMING_SNAKE_CASE = np.dot(a__ , a__ ) # Normalize the resulting output vector. __SCREAMING_SNAKE_CASE = w / np.linalg.norm(a__ ) # Find rayleigh quotient # (faster than usual b/c we know vector is normalized already) __SCREAMING_SNAKE_CASE = vector.conj().T if is_complex else vector.T __SCREAMING_SNAKE_CASE = np.dot(a__ , np.dot(a__ , a__ ) ) # Check convergence. __SCREAMING_SNAKE_CASE = np.abs(lambda_ - lambda_previous ) / lambda_ iterations += 1 if error <= error_tol or iterations >= max_iterations: __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = lambda_ if is_complex: __SCREAMING_SNAKE_CASE = np.real(lambda_ ) return lambda_, vector def a__ ( ): """simple docstring""" __SCREAMING_SNAKE_CASE = np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]] ) __SCREAMING_SNAKE_CASE = np.array([41, 4, 20] ) __SCREAMING_SNAKE_CASE = real_input_matrix.astype(np.complexaaa ) __SCREAMING_SNAKE_CASE = np.triu(1J * complex_input_matrix , 1 ) complex_input_matrix += imag_matrix complex_input_matrix += -1 * imag_matrix.T __SCREAMING_SNAKE_CASE = np.array([41, 4, 20] ).astype(np.complexaaa ) for problem_type in ["real", "complex"]: if problem_type == "real": __SCREAMING_SNAKE_CASE = real_input_matrix __SCREAMING_SNAKE_CASE = real_vector elif problem_type == "complex": __SCREAMING_SNAKE_CASE = complex_input_matrix __SCREAMING_SNAKE_CASE = complex_vector # Our implementation. __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = power_iteration(a__ , a__ ) # Numpy implementation. # Get eigenvalues and eigenvectors using built-in numpy # eigh (eigh used for symmetric or hermetian matrices). __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = np.linalg.eigh(a__ ) # Last eigenvalue is the maximum one. __SCREAMING_SNAKE_CASE = eigen_values[-1] # Last column in this matrix is eigenvector corresponding to largest eigenvalue. __SCREAMING_SNAKE_CASE = eigen_vectors[:, -1] # Check our implementation and numpy gives close answers. assert np.abs(eigen_value - eigen_value_max ) <= 1E-6 # Take absolute values element wise of each eigenvector. # as they are only unique to a minus sign. assert np.linalg.norm(np.abs(a__ ) - np.abs(a__ ) ) <= 1E-6 if __name__ == "__main__": import doctest doctest.testmod() test_power_iteration()
267
1
'''simple docstring''' import numpy as np from transformers import BatchFeature from transformers.testing_utils import require_tf, require_torch from .test_feature_extraction_common import FeatureExtractionSavingTestMixin class lowerCAmelCase__ ( a ): """simple docstring""" lowerCAmelCase__ = None lowerCAmelCase__ = None @property def UpperCAmelCase__ ( self : str ) -> Union[str, Any]: """simple docstring""" return self.feat_extract_tester.prepare_feat_extract_dict() def UpperCAmelCase__ ( self : Tuple ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """feature_size""" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """sampling_rate""" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """padding_value""" ) ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feat_extract_tester.prepare_inputs_for_common() __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) __SCREAMING_SNAKE_CASE = feat_extract.model_input_names[0] __SCREAMING_SNAKE_CASE = BatchFeature({input_name: speech_inputs} ) self.assertTrue(all(len(__SCREAMING_SNAKE_CASE ) == len(__SCREAMING_SNAKE_CASE ) for x, y in zip(__SCREAMING_SNAKE_CASE , processed_features[input_name] ) ) ) __SCREAMING_SNAKE_CASE = self.feat_extract_tester.prepare_inputs_for_common(equal_length=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = BatchFeature({input_name: speech_inputs} , tensor_type="""np""" ) __SCREAMING_SNAKE_CASE = processed_features[input_name] if len(batch_features_input.shape ) < 3: __SCREAMING_SNAKE_CASE = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) @require_torch def UpperCAmelCase__ ( self : Dict ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feat_extract_tester.prepare_inputs_for_common(equal_length=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) __SCREAMING_SNAKE_CASE = feat_extract.model_input_names[0] __SCREAMING_SNAKE_CASE = BatchFeature({input_name: speech_inputs} , tensor_type="""pt""" ) __SCREAMING_SNAKE_CASE = processed_features[input_name] if len(batch_features_input.shape ) < 3: __SCREAMING_SNAKE_CASE = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) @require_tf def UpperCAmelCase__ ( self : int ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feat_extract_tester.prepare_inputs_for_common(equal_length=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) __SCREAMING_SNAKE_CASE = feat_extract.model_input_names[0] __SCREAMING_SNAKE_CASE = BatchFeature({input_name: speech_inputs} , tensor_type="""tf""" ) __SCREAMING_SNAKE_CASE = processed_features[input_name] if len(batch_features_input.shape ) < 3: __SCREAMING_SNAKE_CASE = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) def UpperCAmelCase__ ( self : List[str] , __SCREAMING_SNAKE_CASE : Dict=False ) -> Optional[int]: """simple docstring""" def _inputs_have_equal_length(__SCREAMING_SNAKE_CASE : Union[str, Any] ): __SCREAMING_SNAKE_CASE = len(input[0] ) for input_slice in input[1:]: if len(__SCREAMING_SNAKE_CASE ) != length: return False return True def _inputs_are_equal(__SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : Union[str, Any] ): if len(__SCREAMING_SNAKE_CASE ) != len(__SCREAMING_SNAKE_CASE ): return False for input_slice_a, input_slice_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): if not np.allclose(np.asarray(__SCREAMING_SNAKE_CASE ) , np.asarray(__SCREAMING_SNAKE_CASE ) , atol=1E-3 ): return False return True __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) __SCREAMING_SNAKE_CASE = self.feat_extract_tester.prepare_inputs_for_common(numpify=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = feat_extract.model_input_names[0] __SCREAMING_SNAKE_CASE = BatchFeature({input_name: speech_inputs} ) __SCREAMING_SNAKE_CASE = self.feat_extract_tester.seq_length_diff __SCREAMING_SNAKE_CASE = self.feat_extract_tester.max_seq_length + pad_diff __SCREAMING_SNAKE_CASE = self.feat_extract_tester.min_seq_length __SCREAMING_SNAKE_CASE = self.feat_extract_tester.batch_size __SCREAMING_SNAKE_CASE = self.feat_extract_tester.feature_size # test padding for List[int] + numpy __SCREAMING_SNAKE_CASE = feat_extract.pad(__SCREAMING_SNAKE_CASE , padding=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = input_a[input_name] __SCREAMING_SNAKE_CASE = feat_extract.pad(__SCREAMING_SNAKE_CASE , padding="""longest""" ) __SCREAMING_SNAKE_CASE = input_a[input_name] __SCREAMING_SNAKE_CASE = feat_extract.pad(__SCREAMING_SNAKE_CASE , padding="""max_length""" , max_length=len(speech_inputs[-1] ) ) __SCREAMING_SNAKE_CASE = input_a[input_name] __SCREAMING_SNAKE_CASE = feat_extract.pad(__SCREAMING_SNAKE_CASE , padding="""longest""" , return_tensors="""np""" ) __SCREAMING_SNAKE_CASE = input_a[input_name] # max_length parameter has to be provided when setting `padding="max_length"` with self.assertRaises(__SCREAMING_SNAKE_CASE ): feat_extract.pad(__SCREAMING_SNAKE_CASE , padding="""max_length""" )[input_name] __SCREAMING_SNAKE_CASE = feat_extract.pad( __SCREAMING_SNAKE_CASE , padding="""max_length""" , max_length=__SCREAMING_SNAKE_CASE , return_tensors="""np""" ) __SCREAMING_SNAKE_CASE = input_a[input_name] self.assertFalse(_inputs_have_equal_length(__SCREAMING_SNAKE_CASE ) ) self.assertTrue(_inputs_have_equal_length(__SCREAMING_SNAKE_CASE ) ) self.assertTrue(_inputs_have_equal_length(__SCREAMING_SNAKE_CASE ) ) self.assertTrue(_inputs_are_equal(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) self.assertTrue(len(input_a[0] ) == pad_min_length ) self.assertTrue(len(input_a[1] ) == pad_min_length + pad_diff ) self.assertTrue(input_a.shape[:2] == (batch_size, len(input_a[0] )) ) self.assertTrue(input_a.shape[:2] == (batch_size, pad_max_length) ) if feature_size > 1: self.assertTrue(input_a.shape[2] == input_a.shape[2] == feature_size ) # test padding for `pad_to_multiple_of` for List[int] + numpy __SCREAMING_SNAKE_CASE = feat_extract.pad(__SCREAMING_SNAKE_CASE , pad_to_multiple_of=10 ) __SCREAMING_SNAKE_CASE = input_a[input_name] __SCREAMING_SNAKE_CASE = feat_extract.pad(__SCREAMING_SNAKE_CASE , padding="""longest""" , pad_to_multiple_of=10 ) __SCREAMING_SNAKE_CASE = input_a[input_name] __SCREAMING_SNAKE_CASE = feat_extract.pad( __SCREAMING_SNAKE_CASE , padding="""max_length""" , pad_to_multiple_of=10 , max_length=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = input_a[input_name] __SCREAMING_SNAKE_CASE = feat_extract.pad( __SCREAMING_SNAKE_CASE , padding="""max_length""" , pad_to_multiple_of=10 , max_length=__SCREAMING_SNAKE_CASE , return_tensors="""np""" , ) __SCREAMING_SNAKE_CASE = input_a[input_name] self.assertTrue(all(len(__SCREAMING_SNAKE_CASE ) % 10 == 0 for x in input_a ) ) self.assertTrue(_inputs_are_equal(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = pad_max_length if pad_max_length % 10 == 0 else (pad_max_length // 10 + 1) * 10 self.assertTrue(all(len(__SCREAMING_SNAKE_CASE ) == expected_mult_pad_length for x in input_a ) ) self.assertEqual(input_a.shape[:2] , (batch_size, expected_mult_pad_length) ) if feature_size > 1: self.assertTrue(input_a.shape[2] == feature_size ) # Check padding value is correct __SCREAMING_SNAKE_CASE = (np.ones(self.feat_extract_tester.feature_size ) * feat_extract.padding_value).sum() self.assertTrue( abs(np.asarray(input_a[0] )[pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length) ) < 1E-3 ) self.assertTrue( abs( np.asarray(input_a[1] )[pad_min_length + pad_diff :].sum() - padding_vector_sum * (pad_max_length - pad_min_length - pad_diff) ) < 1E-3 ) self.assertTrue( abs( np.asarray(input_a[2] )[pad_min_length + 2 * pad_diff :].sum() - padding_vector_sum * (pad_max_length - pad_min_length - 2 * pad_diff) ) < 1E-3 ) self.assertTrue( abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length) ) < 1E-3 ) self.assertTrue( abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (expected_mult_pad_length - pad_min_length) ) < 1E-3 ) def UpperCAmelCase__ ( self : Optional[int] , __SCREAMING_SNAKE_CASE : str=False ) -> Optional[int]: """simple docstring""" def _inputs_have_equal_length(__SCREAMING_SNAKE_CASE : Any ): __SCREAMING_SNAKE_CASE = len(input[0] ) for input_slice in input[1:]: if len(__SCREAMING_SNAKE_CASE ) != length: return False return True def _inputs_are_equal(__SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : int ): if len(__SCREAMING_SNAKE_CASE ) != len(__SCREAMING_SNAKE_CASE ): return False for input_slice_a, input_slice_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): if not np.allclose(np.asarray(__SCREAMING_SNAKE_CASE ) , np.asarray(__SCREAMING_SNAKE_CASE ) , atol=1E-3 ): return False return True __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) __SCREAMING_SNAKE_CASE = self.feat_extract_tester.prepare_inputs_for_common(numpify=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = feat_extract.model_input_names[0] __SCREAMING_SNAKE_CASE = BatchFeature({input_name: speech_inputs} ) # truncate to smallest __SCREAMING_SNAKE_CASE = feat_extract.pad( __SCREAMING_SNAKE_CASE , padding="""max_length""" , max_length=len(speech_inputs[0] ) , truncation=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = input_a[input_name] __SCREAMING_SNAKE_CASE = feat_extract.pad(__SCREAMING_SNAKE_CASE , padding="""max_length""" , max_length=len(speech_inputs[0] ) ) __SCREAMING_SNAKE_CASE = input_a[input_name] self.assertTrue(_inputs_have_equal_length(__SCREAMING_SNAKE_CASE ) ) self.assertFalse(_inputs_have_equal_length(__SCREAMING_SNAKE_CASE ) ) # truncate to smallest with np __SCREAMING_SNAKE_CASE = feat_extract.pad( __SCREAMING_SNAKE_CASE , padding="""max_length""" , max_length=len(speech_inputs[0] ) , return_tensors="""np""" , truncation=__SCREAMING_SNAKE_CASE , ) __SCREAMING_SNAKE_CASE = input_a[input_name] __SCREAMING_SNAKE_CASE = feat_extract.pad( __SCREAMING_SNAKE_CASE , padding="""max_length""" , max_length=len(speech_inputs[0] ) , return_tensors="""np""" ) __SCREAMING_SNAKE_CASE = input_a[input_name] self.assertTrue(_inputs_have_equal_length(__SCREAMING_SNAKE_CASE ) ) self.assertTrue(input_a.shape[1] == len(speech_inputs[0] ) ) # since truncation forces padding to be smaller than longest input # function can't return `np.ndarray`, but has to return list self.assertFalse(_inputs_have_equal_length(__SCREAMING_SNAKE_CASE ) ) # truncate to middle __SCREAMING_SNAKE_CASE = feat_extract.pad( __SCREAMING_SNAKE_CASE , padding="""max_length""" , max_length=len(speech_inputs[1] ) , truncation=__SCREAMING_SNAKE_CASE , return_tensors="""np""" , ) __SCREAMING_SNAKE_CASE = input_a[input_name] __SCREAMING_SNAKE_CASE = feat_extract.pad( __SCREAMING_SNAKE_CASE , padding="""max_length""" , max_length=len(speech_inputs[1] ) , truncation=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = input_a[input_name] __SCREAMING_SNAKE_CASE = feat_extract.pad( __SCREAMING_SNAKE_CASE , padding="""max_length""" , max_length=len(speech_inputs[1] ) , return_tensors="""np""" ) __SCREAMING_SNAKE_CASE = input_a[input_name] self.assertTrue(input_a.shape[1] == len(speech_inputs[1] ) ) self.assertTrue(_inputs_have_equal_length(__SCREAMING_SNAKE_CASE ) ) self.assertTrue(_inputs_have_equal_length(__SCREAMING_SNAKE_CASE ) ) self.assertTrue(_inputs_are_equal(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) # since truncation forces padding to be smaller than longest input # function can't return `np.ndarray`, but has to return list self.assertFalse(_inputs_have_equal_length(__SCREAMING_SNAKE_CASE ) ) self.assertTrue(len(input_a[-1] ) == len(speech_inputs[-1] ) ) # padding has to be max_length when setting `truncation=True` with self.assertRaises(__SCREAMING_SNAKE_CASE ): feat_extract.pad(__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE )[input_name] # padding has to be max_length when setting `truncation=True` with self.assertRaises(__SCREAMING_SNAKE_CASE ): feat_extract.pad(__SCREAMING_SNAKE_CASE , padding="""longest""" , truncation=__SCREAMING_SNAKE_CASE )[input_name] # padding has to be max_length when setting `truncation=True` with self.assertRaises(__SCREAMING_SNAKE_CASE ): feat_extract.pad(__SCREAMING_SNAKE_CASE , padding="""longest""" , truncation=__SCREAMING_SNAKE_CASE )[input_name] # max_length parameter has to be provided when setting `truncation=True` and padding="max_length" with self.assertRaises(__SCREAMING_SNAKE_CASE ): feat_extract.pad(__SCREAMING_SNAKE_CASE , padding="""max_length""" , truncation=__SCREAMING_SNAKE_CASE )[input_name] # test truncation for `pad_to_multiple_of` for List[int] + numpy __SCREAMING_SNAKE_CASE = 12 __SCREAMING_SNAKE_CASE = feat_extract.pad( __SCREAMING_SNAKE_CASE , padding="""max_length""" , max_length=len(speech_inputs[0] ) , pad_to_multiple_of=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , ) __SCREAMING_SNAKE_CASE = input_a[input_name] __SCREAMING_SNAKE_CASE = feat_extract.pad( __SCREAMING_SNAKE_CASE , padding="""max_length""" , max_length=len(speech_inputs[0] ) , pad_to_multiple_of=__SCREAMING_SNAKE_CASE , ) __SCREAMING_SNAKE_CASE = input_a[input_name] # retrieve expected_length as multiple of pad_to_multiple_of __SCREAMING_SNAKE_CASE = len(speech_inputs[0] ) if expected_length % pad_to_multiple_of != 0: __SCREAMING_SNAKE_CASE = ((len(speech_inputs[0] ) // pad_to_multiple_of) + 1) * pad_to_multiple_of self.assertTrue(len(input_a[0] ) == expected_length ) self.assertTrue(_inputs_have_equal_length(__SCREAMING_SNAKE_CASE ) ) self.assertFalse(_inputs_have_equal_length(__SCREAMING_SNAKE_CASE ) ) def UpperCAmelCase__ ( self : Dict ) -> Optional[Any]: """simple docstring""" self._check_padding(numpify=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Union[str, Any]: """simple docstring""" self._check_padding(numpify=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[Any] ) -> int: """simple docstring""" self._check_truncation(numpify=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : int ) -> Optional[Any]: """simple docstring""" self._check_truncation(numpify=__SCREAMING_SNAKE_CASE ) @require_torch def UpperCAmelCase__ ( self : Union[str, Any] ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) __SCREAMING_SNAKE_CASE = self.feat_extract_tester.prepare_inputs_for_common() __SCREAMING_SNAKE_CASE = feat_extract.model_input_names[0] __SCREAMING_SNAKE_CASE = BatchFeature({input_name: speech_inputs} ) __SCREAMING_SNAKE_CASE = feat_extract.pad(__SCREAMING_SNAKE_CASE , padding="""longest""" , return_tensors="""np""" )[input_name] __SCREAMING_SNAKE_CASE = feat_extract.pad(__SCREAMING_SNAKE_CASE , padding="""longest""" , return_tensors="""pt""" )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_pt.numpy().astype(np.floataa ).sum() ) < 1E-2 ) @require_tf def UpperCAmelCase__ ( self : Optional[int] ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) __SCREAMING_SNAKE_CASE = self.feat_extract_tester.prepare_inputs_for_common() __SCREAMING_SNAKE_CASE = feat_extract.model_input_names[0] __SCREAMING_SNAKE_CASE = BatchFeature({input_name: speech_inputs} ) __SCREAMING_SNAKE_CASE = feat_extract.pad(__SCREAMING_SNAKE_CASE , padding="""longest""" , return_tensors="""np""" )[input_name] __SCREAMING_SNAKE_CASE = feat_extract.pad(__SCREAMING_SNAKE_CASE , padding="""longest""" , return_tensors="""tf""" )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_tf.numpy().astype(np.floataa ).sum() ) < 1E-2 ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feat_extract_dict __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.feat_extract_tester.prepare_inputs_for_common() __SCREAMING_SNAKE_CASE = [len(__SCREAMING_SNAKE_CASE ) for x in speech_inputs] __SCREAMING_SNAKE_CASE = feat_extract.model_input_names[0] __SCREAMING_SNAKE_CASE = BatchFeature({input_name: speech_inputs} ) __SCREAMING_SNAKE_CASE = feat_extract.pad(__SCREAMING_SNAKE_CASE , padding="""longest""" , return_tensors="""np""" ) self.assertIn("""attention_mask""" , __SCREAMING_SNAKE_CASE ) self.assertListEqual(list(processed.attention_mask.shape ) , list(processed[input_name].shape[:2] ) ) self.assertListEqual(processed.attention_mask.sum(-1 ).tolist() , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[Any] ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feat_extract_dict __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.feat_extract_tester.prepare_inputs_for_common() __SCREAMING_SNAKE_CASE = [len(__SCREAMING_SNAKE_CASE ) for x in speech_inputs] __SCREAMING_SNAKE_CASE = feat_extract.model_input_names[0] __SCREAMING_SNAKE_CASE = BatchFeature({input_name: speech_inputs} ) __SCREAMING_SNAKE_CASE = min(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = feat_extract.pad( __SCREAMING_SNAKE_CASE , padding="""max_length""" , max_length=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , return_tensors="""np""" ) self.assertIn("""attention_mask""" , __SCREAMING_SNAKE_CASE ) self.assertListEqual( list(processed_pad.attention_mask.shape ) , [processed_pad[input_name].shape[0], max_length] ) self.assertListEqual( processed_pad.attention_mask[:, :max_length].sum(-1 ).tolist() , [max_length for x in speech_inputs] )
267
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowerCAmelCase__ ( a , a , a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = StableDiffusionInpaintPipeline lowerCAmelCase__ = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS lowerCAmelCase__ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS lowerCAmelCase__ = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess lowerCAmelCase__ = frozenset([] ) def UpperCAmelCase__ ( self : str ) -> List[Any]: """simple docstring""" torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=9 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=__SCREAMING_SNAKE_CASE , ) __SCREAMING_SNAKE_CASE = PNDMScheduler(skip_prk_steps=__SCREAMING_SNAKE_CASE ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act="""gelu""" , projection_dim=512 , ) __SCREAMING_SNAKE_CASE = CLIPTextModel(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) __SCREAMING_SNAKE_CASE = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def UpperCAmelCase__ ( self : Any , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : List[Any]=0 ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = floats_tensor((1, 3, 32, 32) , rng=random.Random(__SCREAMING_SNAKE_CASE ) ).to(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1 )[0] __SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(__SCREAMING_SNAKE_CASE ) ).convert("""RGB""" ).resize((64, 64) ) __SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(image + 4 ) ).convert("""RGB""" ).resize((64, 64) ) if str(__SCREAMING_SNAKE_CASE ).startswith("""mps""" ): __SCREAMING_SNAKE_CASE = torch.manual_seed(__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = torch.Generator(device=__SCREAMING_SNAKE_CASE ).manual_seed(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = { """prompt""": """A painting of a squirrel eating a burger""", """image""": init_image, """mask_image""": mask_image, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def UpperCAmelCase__ ( self : Union[str, Any] ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = """cpu""" # ensure determinism for the device-dependent torch.Generator __SCREAMING_SNAKE_CASE = self.get_dummy_components() __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = sd_pipe.to(__SCREAMING_SNAKE_CASE ) sd_pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.get_dummy_inputs(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = sd_pipe(**__SCREAMING_SNAKE_CASE ).images __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __SCREAMING_SNAKE_CASE = np.array([0.4727, 0.5735, 0.3941, 0.5446, 0.5926, 0.4394, 0.5062, 0.4654, 0.4476] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def UpperCAmelCase__ ( self : Tuple ) -> str: """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : List[Any] ) -> str: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase__ ( self : List[str] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) __SCREAMING_SNAKE_CASE = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench.npy""" ) __SCREAMING_SNAKE_CASE = """stabilityai/stable-diffusion-2-inpainting""" __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline.from_pretrained(__SCREAMING_SNAKE_CASE , safety_checker=__SCREAMING_SNAKE_CASE ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) pipe.enable_attention_slicing() __SCREAMING_SNAKE_CASE = """Face of a yellow cat, high resolution, sitting on a park bench""" __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , mask_image=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , output_type="""np""" , ) __SCREAMING_SNAKE_CASE = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 9E-3 def UpperCAmelCase__ ( self : List[Any] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) __SCREAMING_SNAKE_CASE = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench_fp16.npy""" ) __SCREAMING_SNAKE_CASE = """stabilityai/stable-diffusion-2-inpainting""" __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline.from_pretrained( __SCREAMING_SNAKE_CASE , torch_dtype=torch.floataa , safety_checker=__SCREAMING_SNAKE_CASE , ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) pipe.enable_attention_slicing() __SCREAMING_SNAKE_CASE = """Face of a yellow cat, high resolution, sitting on a park bench""" __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , mask_image=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , output_type="""np""" , ) __SCREAMING_SNAKE_CASE = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 5E-1 def UpperCAmelCase__ ( self : Tuple ) -> Any: """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) __SCREAMING_SNAKE_CASE = """stabilityai/stable-diffusion-2-inpainting""" __SCREAMING_SNAKE_CASE = PNDMScheduler.from_pretrained(__SCREAMING_SNAKE_CASE , subfolder="""scheduler""" ) __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline.from_pretrained( __SCREAMING_SNAKE_CASE , safety_checker=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE , torch_dtype=torch.floataa , ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() __SCREAMING_SNAKE_CASE = """Face of a yellow cat, high resolution, sitting on a park bench""" __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , mask_image=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , num_inference_steps=2 , output_type="""np""" , ) __SCREAMING_SNAKE_CASE = torch.cuda.max_memory_allocated() # make sure that less than 2.65 GB is allocated assert mem_bytes < 2.65 * 10**9
267
1
'''simple docstring''' import os import re import shutil import sys import tempfile import unittest import black UpperCAmelCase : Dict = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, 'utils')) import check_copies # noqa: E402 # This is the reference code that will be used in the tests. # If BertLMPredictionHead is changed in modeling_bert.py, this code needs to be manually updated. UpperCAmelCase : Optional[Any] = ' def __init__(self, config):\n super().__init__()\n self.transform = BertPredictionHeadTransform(config)\n\n # The output weights are the same as the input embeddings, but there is\n # an output-only bias for each token.\n self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)\n\n self.bias = nn.Parameter(torch.zeros(config.vocab_size))\n\n # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`\n self.decoder.bias = self.bias\n\n def forward(self, hidden_states):\n hidden_states = self.transform(hidden_states)\n hidden_states = self.decoder(hidden_states)\n return hidden_states\n' class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : str ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() os.makedirs(os.path.join(self.transformer_dir , """models/bert/""" ) ) __SCREAMING_SNAKE_CASE = self.transformer_dir shutil.copy( os.path.join(__SCREAMING_SNAKE_CASE , """src/transformers/models/bert/modeling_bert.py""" ) , os.path.join(self.transformer_dir , """models/bert/modeling_bert.py""" ) , ) def UpperCAmelCase__ ( self : Any ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = """src/transformers""" shutil.rmtree(self.transformer_dir ) def UpperCAmelCase__ ( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Union[str, Any]=None ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = comment + f'\nclass {class_name}(nn.Module):\n' + class_code if overwrite_result is not None: __SCREAMING_SNAKE_CASE = comment + f'\nclass {class_name}(nn.Module):\n' + overwrite_result __SCREAMING_SNAKE_CASE = black.Mode(target_versions={black.TargetVersion.PYaa} , line_length=119 ) __SCREAMING_SNAKE_CASE = black.format_str(__SCREAMING_SNAKE_CASE , mode=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = os.path.join(self.transformer_dir , """new_code.py""" ) with open(__SCREAMING_SNAKE_CASE , """w""" , newline="""\n""" ) as f: f.write(__SCREAMING_SNAKE_CASE ) if overwrite_result is None: self.assertTrue(len(check_copies.is_copy_consistent(__SCREAMING_SNAKE_CASE ) ) == 0 ) else: check_copies.is_copy_consistent(f.name , overwrite=__SCREAMING_SNAKE_CASE ) with open(__SCREAMING_SNAKE_CASE , """r""" ) as f: self.assertTrue(f.read() , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Tuple ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = check_copies.find_code_in_transformers("""models.bert.modeling_bert.BertLMPredictionHead""" ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Tuple ) -> Dict: """simple docstring""" self.check_copy_consistency( """# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead""" , """BertLMPredictionHead""" , REFERENCE_CODE + """\n""" , ) # With no empty line at the end self.check_copy_consistency( """# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead""" , """BertLMPredictionHead""" , __SCREAMING_SNAKE_CASE , ) # Copy consistency with rename self.check_copy_consistency( """# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->TestModel""" , """TestModelLMPredictionHead""" , re.sub("""Bert""" , """TestModel""" , __SCREAMING_SNAKE_CASE ) , ) # Copy consistency with a really long name __SCREAMING_SNAKE_CASE = """TestModelWithAReallyLongNameBecauseSomePeopleLikeThatForSomeReason""" self.check_copy_consistency( f'# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->{long_class_name}' , f'{long_class_name}LMPredictionHead' , re.sub("""Bert""" , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) , ) # Copy consistency with overwrite self.check_copy_consistency( """# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->TestModel""" , """TestModelLMPredictionHead""" , __SCREAMING_SNAKE_CASE , overwrite_result=re.sub("""Bert""" , """TestModel""" , __SCREAMING_SNAKE_CASE ) , ) def UpperCAmelCase__ ( self : Tuple ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = check_copies.LOCALIZED_READMES["""README_zh-hans.md"""] __SCREAMING_SNAKE_CASE = ( """1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the""" """ Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for""" """ Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong""" """ Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.\n1.""" """ **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (from HuggingFace),""" """ released together with the paper [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and""" """ lighter](https://arxiv.org/abs/1910.01108) by Victor Sanh, Lysandre Debut and Thomas Wolf. The same""" """ method has been applied to compress GPT2 into""" """ [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into""" """ [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation),""" """ Multilingual BERT into""" """ [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German""" """ version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)**""" """ (from Google Research/Stanford University) released with the paper [ELECTRA: Pre-training text encoders""" """ as discriminators rather than generators](https://arxiv.org/abs/2003.10555) by Kevin Clark, Minh-Thang""" """ Luong, Quoc V. Le, Christopher D. Manning.""" ) __SCREAMING_SNAKE_CASE = ( """1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the""" """ Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of""" """ Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian""" """ Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n""" ) __SCREAMING_SNAKE_CASE = ( """1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the""" """ Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of""" """ Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian""" """ Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n1.""" """ **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (来自 HuggingFace) 伴随论文""" """ [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and""" """ lighter](https://arxiv.org/abs/1910.01108) 由 Victor Sanh, Lysandre Debut and Thomas Wolf 发布。 The same""" """ method has been applied to compress GPT2 into""" """ [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into""" """ [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation),""" """ Multilingual BERT into""" """ [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German""" """ version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)** (来自""" """ Google Research/Stanford University) 伴随论文 [ELECTRA: Pre-training text encoders as discriminators rather""" """ than generators](https://arxiv.org/abs/2003.10555) 由 Kevin Clark, Minh-Thang Luong, Quoc V. Le,""" """ Christopher D. Manning 发布。\n""" ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = check_copies.convert_to_localized_md( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , localized_readme["""format_model_list"""] ) self.assertFalse(__SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = check_copies.convert_to_localized_md( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , localized_readme["""format_model_list"""] ) # Check whether the number of models is equal to README.md after conversion. self.assertTrue(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = ( """1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the""" """ Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for""" """ Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong""" """ Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.""" ) __SCREAMING_SNAKE_CASE = ( """1. **[ALBERT](https://huggingface.co/transformers/main/model_doc/albert.html)** (来自 Google Research and""" """ the Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of""" """ Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian""" """ Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n""" ) __SCREAMING_SNAKE_CASE = ( """1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the""" """ Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of""" """ Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian""" """ Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n""" ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = check_copies.convert_to_localized_md( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , localized_readme["""format_model_list"""] ) # Check if the model link is synchronized. self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
267
'''simple docstring''' from itertools import count def a__ ( a__ = 50 ): """simple docstring""" __SCREAMING_SNAKE_CASE = [1] * min_block_length for n in count(a__ ): fill_count_functions.append(1 ) for block_length in range(a__ , n + 1 ): for block_start in range(n - block_length ): fill_count_functions[n] += fill_count_functions[ n - block_start - block_length - 1 ] fill_count_functions[n] += 1 if fill_count_functions[n] > 1_00_00_00: break return n if __name__ == "__main__": print(f"""{solution() = }""")
267
1
'''simple docstring''' import os from math import logaa def a__ ( a__ = "base_exp.txt" ): """simple docstring""" __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 for i, line in enumerate(open(os.path.join(os.path.dirname(a__ ) , a__ ) ) ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = list(map(a__ , line.split(""",""" ) ) ) if x * logaa(a__ ) > largest: __SCREAMING_SNAKE_CASE = x * logaa(a__ ) __SCREAMING_SNAKE_CASE = i + 1 return result if __name__ == "__main__": print(solution())
267
'''simple docstring''' import logging import os import threading import time try: import warnings except ImportError: UpperCAmelCase : Optional[Any] = None try: import msvcrt except ImportError: UpperCAmelCase : List[Any] = None try: import fcntl except ImportError: UpperCAmelCase : int = None # Backward compatibility # ------------------------------------------------ try: TimeoutError except NameError: UpperCAmelCase : Union[str, Any] = OSError # Data # ------------------------------------------------ UpperCAmelCase : List[Any] = [ 'Timeout', 'BaseFileLock', 'WindowsFileLock', 'UnixFileLock', 'SoftFileLock', 'FileLock', ] UpperCAmelCase : Tuple = '3.0.12' UpperCAmelCase : str = None def a__ ( ): """simple docstring""" global _logger __SCREAMING_SNAKE_CASE = _logger or logging.getLogger(__name__ ) return _logger class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Any , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = lock_file return None def __str__( self : str ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = f'The file lock \'{self.lock_file}\' could not be acquired.' return temp class lowerCAmelCase__ : """simple docstring""" def __init__( self : Tuple , __SCREAMING_SNAKE_CASE : List[Any] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = lock return None def __enter__( self : List[str] ) -> List[Any]: """simple docstring""" return self.lock def __exit__( self : Tuple , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> List[str]: """simple docstring""" self.lock.release() return None class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : str=-1 , __SCREAMING_SNAKE_CASE : Optional[Any]=None ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = max_filename_length if max_filename_length is not None else 255 # Hash the filename if it's too long __SCREAMING_SNAKE_CASE = self.hash_filename_if_too_long(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # The path to the lock file. __SCREAMING_SNAKE_CASE = lock_file # The file descriptor for the *_lock_file* as it is returned by the # os.open() function. # This file lock is only NOT None, if the object currently holds the # lock. __SCREAMING_SNAKE_CASE = None # The default timeout value. __SCREAMING_SNAKE_CASE = timeout # We use this lock primarily for the lock counter. __SCREAMING_SNAKE_CASE = threading.Lock() # The lock counter is used for implementing the nested locking # mechanism. Whenever the lock is acquired, the counter is increased and # the lock is only released, when this value is 0 again. __SCREAMING_SNAKE_CASE = 0 return None @property def UpperCAmelCase__ ( self : List[Any] ) -> List[str]: """simple docstring""" return self._lock_file @property def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" return self._timeout @timeout.setter def UpperCAmelCase__ ( self : List[str] , __SCREAMING_SNAKE_CASE : Dict ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = float(__SCREAMING_SNAKE_CASE ) return None def UpperCAmelCase__ ( self : Optional[Any] ) -> List[Any]: """simple docstring""" raise NotImplementedError() def UpperCAmelCase__ ( self : Union[str, Any] ) -> Any: """simple docstring""" raise NotImplementedError() @property def UpperCAmelCase__ ( self : Union[str, Any] ) -> int: """simple docstring""" return self._lock_file_fd is not None def UpperCAmelCase__ ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[Any]=None , __SCREAMING_SNAKE_CASE : Optional[int]=0.05 ) -> Optional[Any]: """simple docstring""" if timeout is None: __SCREAMING_SNAKE_CASE = self.timeout # Increment the number right at the beginning. # We can still undo it, if something fails. with self._thread_lock: self._lock_counter += 1 __SCREAMING_SNAKE_CASE = id(self ) __SCREAMING_SNAKE_CASE = self._lock_file __SCREAMING_SNAKE_CASE = time.time() try: while True: with self._thread_lock: if not self.is_locked: logger().debug(f'Attempting to acquire lock {lock_id} on {lock_filename}' ) self._acquire() if self.is_locked: logger().debug(f'Lock {lock_id} acquired on {lock_filename}' ) break elif timeout >= 0 and time.time() - start_time > timeout: logger().debug(f'Timeout on acquiring lock {lock_id} on {lock_filename}' ) raise Timeout(self._lock_file ) else: logger().debug( f'Lock {lock_id} not acquired on {lock_filename}, waiting {poll_intervall} seconds ...' ) time.sleep(__SCREAMING_SNAKE_CASE ) except: # noqa # Something did go wrong, so decrement the counter. with self._thread_lock: __SCREAMING_SNAKE_CASE = max(0 , self._lock_counter - 1 ) raise return _Acquire_ReturnProxy(lock=self ) def UpperCAmelCase__ ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[Any]=False ) -> Dict: """simple docstring""" with self._thread_lock: if self.is_locked: self._lock_counter -= 1 if self._lock_counter == 0 or force: __SCREAMING_SNAKE_CASE = id(self ) __SCREAMING_SNAKE_CASE = self._lock_file logger().debug(f'Attempting to release lock {lock_id} on {lock_filename}' ) self._release() __SCREAMING_SNAKE_CASE = 0 logger().debug(f'Lock {lock_id} released on {lock_filename}' ) return None def __enter__( self : Union[str, Any] ) -> Optional[int]: """simple docstring""" self.acquire() return self def __exit__( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Any ) -> Tuple: """simple docstring""" self.release() return None def __del__( self : str ) -> Union[str, Any]: """simple docstring""" self.release(force=__SCREAMING_SNAKE_CASE ) return None def UpperCAmelCase__ ( self : Optional[int] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : int ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = os.path.basename(__SCREAMING_SNAKE_CASE ) if len(__SCREAMING_SNAKE_CASE ) > max_length and max_length > 0: __SCREAMING_SNAKE_CASE = os.path.dirname(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = str(hash(__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = filename[: max_length - len(__SCREAMING_SNAKE_CASE ) - 8] + """...""" + hashed_filename + """.lock""" return os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else: return path class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Tuple , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Dict=-1 , __SCREAMING_SNAKE_CASE : Dict=None ) -> List[Any]: """simple docstring""" from .file_utils import relative_to_absolute_path super().__init__(__SCREAMING_SNAKE_CASE , timeout=__SCREAMING_SNAKE_CASE , max_filename_length=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """\\\\?\\""" + relative_to_absolute_path(self.lock_file ) def UpperCAmelCase__ ( self : Dict ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = os.O_RDWR | os.O_CREAT | os.O_TRUNC try: __SCREAMING_SNAKE_CASE = os.open(self._lock_file , __SCREAMING_SNAKE_CASE ) except OSError: pass else: try: msvcrt.locking(__SCREAMING_SNAKE_CASE , msvcrt.LK_NBLCK , 1 ) except OSError: os.close(__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = fd return None def UpperCAmelCase__ ( self : Tuple ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self._lock_file_fd __SCREAMING_SNAKE_CASE = None msvcrt.locking(__SCREAMING_SNAKE_CASE , msvcrt.LK_UNLCK , 1 ) os.close(__SCREAMING_SNAKE_CASE ) try: os.remove(self._lock_file ) # Probably another instance of the application # that acquired the file lock. except OSError: pass return None class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Union[str, Any]=-1 , __SCREAMING_SNAKE_CASE : Optional[Any]=None ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = os.statvfs(os.path.dirname(__SCREAMING_SNAKE_CASE ) ).f_namemax super().__init__(__SCREAMING_SNAKE_CASE , timeout=__SCREAMING_SNAKE_CASE , max_filename_length=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = os.O_RDWR | os.O_CREAT | os.O_TRUNC __SCREAMING_SNAKE_CASE = os.open(self._lock_file , __SCREAMING_SNAKE_CASE ) try: fcntl.flock(__SCREAMING_SNAKE_CASE , fcntl.LOCK_EX | fcntl.LOCK_NB ) except OSError: os.close(__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = fd return None def UpperCAmelCase__ ( self : List[Any] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = self._lock_file_fd __SCREAMING_SNAKE_CASE = None fcntl.flock(__SCREAMING_SNAKE_CASE , fcntl.LOCK_UN ) os.close(__SCREAMING_SNAKE_CASE ) return None class lowerCAmelCase__ ( a ): """simple docstring""" def UpperCAmelCase__ ( self : List[str] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC try: __SCREAMING_SNAKE_CASE = os.open(self._lock_file , __SCREAMING_SNAKE_CASE ) except OSError: pass else: __SCREAMING_SNAKE_CASE = fd return None def UpperCAmelCase__ ( self : int ) -> Optional[int]: """simple docstring""" os.close(self._lock_file_fd ) __SCREAMING_SNAKE_CASE = None try: os.remove(self._lock_file ) # The file is already deleted and that's what we want. except OSError: pass return None UpperCAmelCase : Dict = None if msvcrt: UpperCAmelCase : Optional[int] = WindowsFileLock elif fcntl: UpperCAmelCase : Optional[Any] = UnixFileLock else: UpperCAmelCase : int = SoftFileLock if warnings is not None: warnings.warn('only soft file lock is available')
267
1
'''simple docstring''' import copy import unittest from transformers.models.auto import get_values from transformers.testing_utils import require_torch, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_MULTIPLE_CHOICE_MAPPING, MODEL_FOR_QUESTION_ANSWERING_MAPPING, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, LayoutLMvaForQuestionAnswering, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaModel, ) from transformers.models.layoutlmva.modeling_layoutlmva import LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[str] , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Dict=2 , __SCREAMING_SNAKE_CASE : int=3 , __SCREAMING_SNAKE_CASE : Any=4 , __SCREAMING_SNAKE_CASE : List[Any]=2 , __SCREAMING_SNAKE_CASE : Dict=7 , __SCREAMING_SNAKE_CASE : str=True , __SCREAMING_SNAKE_CASE : Optional[int]=True , __SCREAMING_SNAKE_CASE : List[str]=True , __SCREAMING_SNAKE_CASE : Optional[Any]=True , __SCREAMING_SNAKE_CASE : int=99 , __SCREAMING_SNAKE_CASE : Union[str, Any]=36 , __SCREAMING_SNAKE_CASE : Optional[int]=3 , __SCREAMING_SNAKE_CASE : Optional[Any]=4 , __SCREAMING_SNAKE_CASE : Union[str, Any]=37 , __SCREAMING_SNAKE_CASE : Union[str, Any]="gelu" , __SCREAMING_SNAKE_CASE : Tuple=0.1 , __SCREAMING_SNAKE_CASE : Dict=0.1 , __SCREAMING_SNAKE_CASE : Tuple=512 , __SCREAMING_SNAKE_CASE : Tuple=16 , __SCREAMING_SNAKE_CASE : Dict=2 , __SCREAMING_SNAKE_CASE : int=0.02 , __SCREAMING_SNAKE_CASE : Tuple=6 , __SCREAMING_SNAKE_CASE : int=6 , __SCREAMING_SNAKE_CASE : str=3 , __SCREAMING_SNAKE_CASE : List[Any]=4 , __SCREAMING_SNAKE_CASE : List[Any]=None , __SCREAMING_SNAKE_CASE : Tuple=1_000 , ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = patch_size __SCREAMING_SNAKE_CASE = text_seq_length __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_input_mask __SCREAMING_SNAKE_CASE = use_token_type_ids __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = type_vocab_size __SCREAMING_SNAKE_CASE = type_sequence_label_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = coordinate_size __SCREAMING_SNAKE_CASE = shape_size __SCREAMING_SNAKE_CASE = num_labels __SCREAMING_SNAKE_CASE = num_choices __SCREAMING_SNAKE_CASE = scope __SCREAMING_SNAKE_CASE = range_bbox # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token) __SCREAMING_SNAKE_CASE = text_seq_length __SCREAMING_SNAKE_CASE = (image_size // patch_size) ** 2 + 1 __SCREAMING_SNAKE_CASE = self.text_seq_length + self.image_seq_length def UpperCAmelCase__ ( self : Union[str, Any] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.text_seq_length, 4] , self.range_bbox ) # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: __SCREAMING_SNAKE_CASE = bbox[i, j, 3] __SCREAMING_SNAKE_CASE = bbox[i, j, 1] __SCREAMING_SNAKE_CASE = t if bbox[i, j, 2] < bbox[i, j, 0]: __SCREAMING_SNAKE_CASE = bbox[i, j, 2] __SCREAMING_SNAKE_CASE = bbox[i, j, 0] __SCREAMING_SNAKE_CASE = t __SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __SCREAMING_SNAKE_CASE = None if self.use_input_mask: __SCREAMING_SNAKE_CASE = random_attention_mask([self.batch_size, self.text_seq_length] ) __SCREAMING_SNAKE_CASE = None if self.use_token_type_ids: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size ) __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None if self.use_labels: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.text_seq_length] , self.num_labels ) __SCREAMING_SNAKE_CASE = LayoutLMvaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , coordinate_size=self.coordinate_size , shape_size=self.shape_size , input_size=self.image_size , patch_size=self.patch_size , ) return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels def UpperCAmelCase__ ( self : Tuple , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = LayoutLMvaModel(config=__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() # text + image __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE , pixel_values=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = model( __SCREAMING_SNAKE_CASE , bbox=__SCREAMING_SNAKE_CASE , pixel_values=__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , token_type_ids=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE , bbox=__SCREAMING_SNAKE_CASE , pixel_values=__SCREAMING_SNAKE_CASE , token_type_ids=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE , bbox=__SCREAMING_SNAKE_CASE , pixel_values=__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # text only __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size) ) # image only __SCREAMING_SNAKE_CASE = model(pixel_values=__SCREAMING_SNAKE_CASE ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size) ) def UpperCAmelCase__ ( self : Tuple , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : List[Any] ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = LayoutLMvaForSequenceClassification(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() __SCREAMING_SNAKE_CASE = model( __SCREAMING_SNAKE_CASE , bbox=__SCREAMING_SNAKE_CASE , pixel_values=__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , token_type_ids=__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCAmelCase__ ( self : Optional[int] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : str ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = LayoutLMvaForTokenClassification(config=__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() __SCREAMING_SNAKE_CASE = model( __SCREAMING_SNAKE_CASE , bbox=__SCREAMING_SNAKE_CASE , pixel_values=__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , token_type_ids=__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels) ) def UpperCAmelCase__ ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Union[str, Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = LayoutLMvaForQuestionAnswering(config=__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() __SCREAMING_SNAKE_CASE = model( __SCREAMING_SNAKE_CASE , bbox=__SCREAMING_SNAKE_CASE , pixel_values=__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , token_type_ids=__SCREAMING_SNAKE_CASE , start_positions=__SCREAMING_SNAKE_CASE , end_positions=__SCREAMING_SNAKE_CASE , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def UpperCAmelCase__ ( self : Tuple ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() ( ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ) = config_and_inputs __SCREAMING_SNAKE_CASE = { """input_ids""": input_ids, """bbox""": bbox, """pixel_values""": pixel_values, """token_type_ids""": token_type_ids, """attention_mask""": input_mask, } return config, inputs_dict @require_torch class lowerCAmelCase__ ( a , a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = False lowerCAmelCase__ = False lowerCAmelCase__ = False lowerCAmelCase__ = ( ( LayoutLMvaModel, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaForQuestionAnswering, ) if is_torch_available() else () ) lowerCAmelCase__ = ( {"document-question-answering": LayoutLMvaForQuestionAnswering, "feature-extraction": LayoutLMvaModel} if is_torch_available() else {} ) def UpperCAmelCase__ ( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> Tuple: """simple docstring""" return True def UpperCAmelCase__ ( self : Any ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = LayoutLMvaModelTester(self ) __SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=__SCREAMING_SNAKE_CASE , hidden_size=37 ) def UpperCAmelCase__ ( self : Dict , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : str=False ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = copy.deepcopy(__SCREAMING_SNAKE_CASE ) if model_class in get_values(__SCREAMING_SNAKE_CASE ): __SCREAMING_SNAKE_CASE = { k: v.unsqueeze(1 ).expand(-1 , self.model_tester.num_choices , -1 ).contiguous() if isinstance(__SCREAMING_SNAKE_CASE , torch.Tensor ) and v.ndim > 1 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(__SCREAMING_SNAKE_CASE ): __SCREAMING_SNAKE_CASE = torch.ones(self.model_tester.batch_size , dtype=torch.long , device=__SCREAMING_SNAKE_CASE ) elif model_class in get_values(__SCREAMING_SNAKE_CASE ): __SCREAMING_SNAKE_CASE = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__SCREAMING_SNAKE_CASE ) elif model_class in [ *get_values(__SCREAMING_SNAKE_CASE ), ]: __SCREAMING_SNAKE_CASE = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__SCREAMING_SNAKE_CASE ) elif model_class in [ *get_values(__SCREAMING_SNAKE_CASE ), ]: __SCREAMING_SNAKE_CASE = torch.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=torch.long , device=__SCREAMING_SNAKE_CASE , ) return inputs_dict def UpperCAmelCase__ ( self : Optional[int] ) -> Union[str, Any]: """simple docstring""" self.config_tester.run_common_tests() def UpperCAmelCase__ ( self : List[Any] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __SCREAMING_SNAKE_CASE = type self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : int ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : int ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__SCREAMING_SNAKE_CASE ) @slow def UpperCAmelCase__ ( self : str ) -> Tuple: """simple docstring""" for model_name in LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE = LayoutLMvaModel.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertIsNotNone(__SCREAMING_SNAKE_CASE ) def a__ ( ): """simple docstring""" __SCREAMING_SNAKE_CASE = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" @cached_property def UpperCAmelCase__ ( self : Tuple ) -> Optional[Any]: """simple docstring""" return LayoutLMvaImageProcessor(apply_ocr=__SCREAMING_SNAKE_CASE ) if is_vision_available() else None @slow def UpperCAmelCase__ ( self : int ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = LayoutLMvaModel.from_pretrained("""microsoft/layoutlmv3-base""" ).to(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.default_image_processor __SCREAMING_SNAKE_CASE = prepare_img() __SCREAMING_SNAKE_CASE = image_processor(images=__SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).pixel_values.to(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = torch.tensor([[1, 2]] ) __SCREAMING_SNAKE_CASE = torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]] ).unsqueeze(0 ) # forward pass __SCREAMING_SNAKE_CASE = model( input_ids=input_ids.to(__SCREAMING_SNAKE_CASE ) , bbox=bbox.to(__SCREAMING_SNAKE_CASE ) , pixel_values=pixel_values.to(__SCREAMING_SNAKE_CASE ) , ) # verify the logits __SCREAMING_SNAKE_CASE = torch.Size((1, 199, 768) ) self.assertEqual(outputs.last_hidden_state.shape , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = torch.tensor( [[-0.0529, 0.3618, 0.1632], [-0.1587, -0.1667, -0.0400], [-0.1557, -0.1671, -0.0505]] ).to(__SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3] , __SCREAMING_SNAKE_CASE , atol=1E-4 ) )
267
'''simple docstring''' import shutil import tempfile import unittest from transformers import ( SPIECE_UNDERLINE, AddedToken, BatchEncoding, NllbTokenizer, NllbTokenizerFast, is_torch_available, ) from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...test_tokenization_common import TokenizerTesterMixin UpperCAmelCase : Optional[int] = get_tests_dir('fixtures/test_sentencepiece.model') if is_torch_available(): from transformers.models.mam_aaa.modeling_mam_aaa import shift_tokens_right UpperCAmelCase : Optional[int] = 2_5_6_0_4_7 UpperCAmelCase : Union[str, Any] = 2_5_6_1_4_5 @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = NllbTokenizer lowerCAmelCase__ = NllbTokenizerFast lowerCAmelCase__ = True lowerCAmelCase__ = True lowerCAmelCase__ = {} def UpperCAmelCase__ ( self : List[Any] ) -> int: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing __SCREAMING_SNAKE_CASE = NllbTokenizer(__SCREAMING_SNAKE_CASE , keep_accents=__SCREAMING_SNAKE_CASE ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCAmelCase__ ( self : Dict ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = NllbTokenizer(__SCREAMING_SNAKE_CASE , keep_accents=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(__SCREAMING_SNAKE_CASE , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) __SCREAMING_SNAKE_CASE = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ 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""", """é""", """.""", ] , ) __SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ 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] ] , ) __SCREAMING_SNAKE_CASE = tokenizer.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ 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>""", """.""", ] , ) def UpperCAmelCase__ ( self : Dict ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = (self.rust_tokenizer_class, """hf-internal-testing/tiny-random-nllb""", {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) __SCREAMING_SNAKE_CASE = tuple(f for f in tokenizer_r_files if """tokenizer.json""" not in f ) self.assertSequenceEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Checks everything loads correctly in the same way __SCREAMING_SNAKE_CASE = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) # Save tokenizer rust, legacy_format=True __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE , legacy_format=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it save with the same files self.assertSequenceEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Checks everything loads correctly in the same way __SCREAMING_SNAKE_CASE = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) # Save tokenizer rust, legacy_format=False __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE , legacy_format=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it saved the tokenizer.json file self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way __SCREAMING_SNAKE_CASE = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) @require_torch def UpperCAmelCase__ ( self : List[Any] ) -> Any: """simple docstring""" if not self.test_seqaseq: return __SCREAMING_SNAKE_CASE = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): # Longer text that will definitely require truncation. __SCREAMING_SNAKE_CASE = [ """ UN Chief Says There Is No Military Solution in Syria""", """ Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for""" """ Syria is that 'there is no military solution' to the nearly five-year conflict and more weapons""" """ will only worsen the violence and misery for millions of people.""", ] __SCREAMING_SNAKE_CASE = [ """Şeful ONU declară că nu există o soluţie militară în Siria""", """Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al""" """ Rusiei pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi""" """ că noi arme nu vor face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.""", ] try: __SCREAMING_SNAKE_CASE = tokenizer.prepare_seqaseq_batch( src_texts=__SCREAMING_SNAKE_CASE , tgt_texts=__SCREAMING_SNAKE_CASE , max_length=3 , max_target_length=10 , return_tensors="""pt""" , src_lang="""eng_Latn""" , tgt_lang="""ron_Latn""" , ) except NotImplementedError: return self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.labels.shape[1] , 10 ) # max_target_length will default to max_length if not specified __SCREAMING_SNAKE_CASE = tokenizer.prepare_seqaseq_batch( __SCREAMING_SNAKE_CASE , tgt_texts=__SCREAMING_SNAKE_CASE , max_length=3 , return_tensors="""pt""" ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.labels.shape[1] , 3 ) __SCREAMING_SNAKE_CASE = tokenizer.prepare_seqaseq_batch( src_texts=__SCREAMING_SNAKE_CASE , max_length=3 , max_target_length=10 , return_tensors="""pt""" ) self.assertEqual(batch_encoder_only.input_ids.shape[1] , 3 ) self.assertEqual(batch_encoder_only.attention_mask.shape[1] , 3 ) self.assertNotIn("""decoder_input_ids""" , __SCREAMING_SNAKE_CASE ) @unittest.skip("""Unfortunately way too slow to build a BPE with SentencePiece.""" ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" pass def UpperCAmelCase__ ( self : List[str] ) -> Dict: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): __SCREAMING_SNAKE_CASE = [AddedToken("""<special>""" , lstrip=__SCREAMING_SNAKE_CASE )] __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_r.encode("""Hey this is a <special> token""" ) __SCREAMING_SNAKE_CASE = tokenizer_r.encode("""<special>""" , add_special_tokens=__SCREAMING_SNAKE_CASE )[0] self.assertTrue(special_token_id in r_output ) if self.test_slow_tokenizer: __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.encode("""Hey this is a <special> token""" ) __SCREAMING_SNAKE_CASE = tokenizer_cr.encode("""Hey this is a <special> token""" ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertTrue(special_token_id in p_output ) self.assertTrue(special_token_id in cr_output ) @require_torch @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = "facebook/nllb-200-distilled-600M" lowerCAmelCase__ = [ " UN Chief Says There Is No Military Solution in Syria", " Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for Syria is that \"there is no military solution\" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.", ] lowerCAmelCase__ = [ "Şeful ONU declară că nu există o soluţie militară în Siria", "Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei" " pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi că noi arme nu vor" " face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.", ] lowerCAmelCase__ = [ 256047, 16297, 134408, 8165, 248066, 14734, 950, 1135, 105721, 3573, 83, 27352, 108, 49486, 2, ] @classmethod def UpperCAmelCase__ ( cls : List[Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = NllbTokenizer.from_pretrained( cls.checkpoint_name , src_lang="""eng_Latn""" , tgt_lang="""ron_Latn""" ) __SCREAMING_SNAKE_CASE = 1 return cls def UpperCAmelCase__ ( self : Union[str, Any] ) -> List[str]: """simple docstring""" self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ace_Arab"""] , 256_001 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ace_Latn"""] , 256_002 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""fra_Latn"""] , 256_057 ) def UpperCAmelCase__ ( self : Optional[int] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Any ) -> int: """simple docstring""" self.assertIn(__SCREAMING_SNAKE_CASE , self.tokenizer.all_special_ids ) # fmt: off __SCREAMING_SNAKE_CASE = [RO_CODE, 4_254, 98_068, 112_923, 39_072, 3_909, 713, 102_767, 26, 17_314, 35_642, 14_683, 33_118, 2_022, 66_987, 2, 256_047] # fmt: on __SCREAMING_SNAKE_CASE = self.tokenizer.decode(__SCREAMING_SNAKE_CASE , skip_special_tokens=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertNotIn(self.tokenizer.eos_token , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = ["""this is gunna be a long sentence """ * 20] assert isinstance(src_text[0] , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = 10 __SCREAMING_SNAKE_CASE = self.tokenizer(__SCREAMING_SNAKE_CASE , max_length=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE ).input_ids[0] self.assertEqual(ids[-1] , 2 ) self.assertEqual(ids[0] , __SCREAMING_SNAKE_CASE ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : int ) -> List[Any]: """simple docstring""" self.assertListEqual(self.tokenizer.convert_tokens_to_ids(["""<mask>""", """ar_AR"""] ) , [256_203, 3] ) def UpperCAmelCase__ ( self : str ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = NllbTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , __SCREAMING_SNAKE_CASE ) @require_torch def UpperCAmelCase__ ( self : str ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=len(self.expected_src_tokens ) , return_tensors="""pt""" , ) __SCREAMING_SNAKE_CASE = shift_tokens_right( batch["""labels"""] , self.tokenizer.pad_token_id , self.tokenizer.lang_code_to_id["""ron_Latn"""] ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertEqual((2, 15) , batch.input_ids.shape ) self.assertEqual((2, 15) , batch.attention_mask.shape ) __SCREAMING_SNAKE_CASE = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , __SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , batch.decoder_input_ids[0, 0] ) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [EN_CODE] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer(self.src_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=3 , return_tensors="""pt""" ) __SCREAMING_SNAKE_CASE = self.tokenizer( text_target=self.tgt_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=10 , return_tensors="""pt""" ) __SCREAMING_SNAKE_CASE = targets["""input_ids"""] __SCREAMING_SNAKE_CASE = shift_tokens_right( __SCREAMING_SNAKE_CASE , self.tokenizer.pad_token_id , decoder_start_token_id=self.tokenizer.lang_code_to_id[self.tokenizer.tgt_lang] , ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 10 ) @require_torch def UpperCAmelCase__ ( self : int ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer._build_translation_inputs( """A test""" , return_tensors="""pt""" , src_lang="""eng_Latn""" , tgt_lang="""fra_Latn""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE ) , { # A, test, EOS, en_XX """input_ids""": [[256_047, 70, 7_356, 2]], """attention_mask""": [[1, 1, 1, 1]], # ar_AR """forced_bos_token_id""": 256_057, } , ) @require_torch def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = self.tokenizer( """UN Chief says there is no military solution in Syria""" , src_lang="""eng_Latn""" , tgt_lang="""fra_Latn""" ) self.assertEqual( inputs.input_ids , [16_297, 134_408, 25_653, 6_370, 248, 254, 103_929, 94_995, 108, 49_486, 2, 256_047] ) __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = self.tokenizer( """UN Chief says there is no military solution in Syria""" , src_lang="""eng_Latn""" , tgt_lang="""fra_Latn""" ) self.assertEqual( inputs.input_ids , [256_047, 16_297, 134_408, 25_653, 6_370, 248, 254, 103_929, 94_995, 108, 49_486, 2] )
267
1
'''simple docstring''' import math from enum import Enum from typing import Optional, Union from torch.optim import Optimizer from torch.optim.lr_scheduler import LambdaLR from .utils import logging UpperCAmelCase : str = logging.get_logger(__name__) class lowerCAmelCase__ ( a ): """simple docstring""" lowerCAmelCase__ = "linear" lowerCAmelCase__ = "cosine" lowerCAmelCase__ = "cosine_with_restarts" lowerCAmelCase__ = "polynomial" lowerCAmelCase__ = "constant" lowerCAmelCase__ = "constant_with_warmup" lowerCAmelCase__ = "piecewise_constant" def a__ ( a__ , a__ = -1 ): """simple docstring""" return LambdaLR(a__ , lambda a__ : 1 , last_epoch=a__ ) def a__ ( a__ , a__ , a__ = -1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1.0 , a__ ) ) return 1.0 return LambdaLR(a__ , a__ , last_epoch=a__ ) def a__ ( a__ , a__ , a__ = -1 ): """simple docstring""" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = step_rules.split(""",""" ) for rule_str in rule_list[:-1]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = rule_str.split(""":""" ) __SCREAMING_SNAKE_CASE = int(a__ ) __SCREAMING_SNAKE_CASE = float(a__ ) __SCREAMING_SNAKE_CASE = value __SCREAMING_SNAKE_CASE = float(rule_list[-1] ) def create_rules_function(a__ , a__ ): def rule_func(a__ ) -> float: __SCREAMING_SNAKE_CASE = sorted(rules_dict.keys() ) for i, sorted_step in enumerate(a__ ): if steps < sorted_step: return rules_dict[sorted_steps[i]] return last_lr_multiple return rule_func __SCREAMING_SNAKE_CASE = create_rules_function(a__ , a__ ) return LambdaLR(a__ , a__ , last_epoch=a__ ) def a__ ( a__ , a__ , a__ , a__=-1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) return max( 0.0 , float(num_training_steps - current_step ) / float(max(1 , num_training_steps - num_warmup_steps ) ) ) return LambdaLR(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ , a__ = 0.5 , a__ = -1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) __SCREAMING_SNAKE_CASE = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * float(a__ ) * 2.0 * progress )) ) return LambdaLR(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ , a__ = 1 , a__ = -1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) __SCREAMING_SNAKE_CASE = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) if progress >= 1.0: return 0.0 return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * ((float(a__ ) * progress) % 1.0) )) ) return LambdaLR(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ , a__=1E-7 , a__=1.0 , a__=-1 ): """simple docstring""" __SCREAMING_SNAKE_CASE = optimizer.defaults["""lr"""] if not (lr_init > lr_end): raise ValueError(F'lr_end ({lr_end}) must be be smaller than initial lr ({lr_init})' ) def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) elif current_step > num_training_steps: return lr_end / lr_init # as LambdaLR multiplies by lr_init else: __SCREAMING_SNAKE_CASE = lr_init - lr_end __SCREAMING_SNAKE_CASE = num_training_steps - num_warmup_steps __SCREAMING_SNAKE_CASE = 1 - (current_step - num_warmup_steps) / decay_steps __SCREAMING_SNAKE_CASE = lr_range * pct_remaining**power + lr_end return decay / lr_init # as LambdaLR multiplies by lr_init return LambdaLR(a__ , a__ , a__ ) UpperCAmelCase : Optional[Any] = { SchedulerType.LINEAR: get_linear_schedule_with_warmup, SchedulerType.COSINE: get_cosine_schedule_with_warmup, SchedulerType.COSINE_WITH_RESTARTS: get_cosine_with_hard_restarts_schedule_with_warmup, SchedulerType.POLYNOMIAL: get_polynomial_decay_schedule_with_warmup, SchedulerType.CONSTANT: get_constant_schedule, SchedulerType.CONSTANT_WITH_WARMUP: get_constant_schedule_with_warmup, SchedulerType.PIECEWISE_CONSTANT: get_piecewise_constant_schedule, } def a__ ( a__ , a__ , a__ = None , a__ = None , a__ = None , a__ = 1 , a__ = 1.0 , a__ = -1 , ): """simple docstring""" __SCREAMING_SNAKE_CASE = SchedulerType(a__ ) __SCREAMING_SNAKE_CASE = TYPE_TO_SCHEDULER_FUNCTION[name] if name == SchedulerType.CONSTANT: return schedule_func(a__ , last_epoch=a__ ) if name == SchedulerType.PIECEWISE_CONSTANT: return schedule_func(a__ , step_rules=a__ , last_epoch=a__ ) # All other schedulers require `num_warmup_steps` if num_warmup_steps is None: raise ValueError(F'{name} requires `num_warmup_steps`, please provide that argument.' ) if name == SchedulerType.CONSTANT_WITH_WARMUP: return schedule_func(a__ , num_warmup_steps=a__ , last_epoch=a__ ) # All other schedulers require `num_training_steps` if num_training_steps is None: raise ValueError(F'{name} requires `num_training_steps`, please provide that argument.' ) if name == SchedulerType.COSINE_WITH_RESTARTS: return schedule_func( a__ , num_warmup_steps=a__ , num_training_steps=a__ , num_cycles=a__ , last_epoch=a__ , ) if name == SchedulerType.POLYNOMIAL: return schedule_func( a__ , num_warmup_steps=a__ , num_training_steps=a__ , power=a__ , last_epoch=a__ , ) return schedule_func( a__ , num_warmup_steps=a__ , num_training_steps=a__ , last_epoch=a__ )
267
'''simple docstring''' import math from enum import Enum from typing import Optional, Union from torch.optim import Optimizer from torch.optim.lr_scheduler import LambdaLR from .utils import logging UpperCAmelCase : str = logging.get_logger(__name__) class lowerCAmelCase__ ( a ): """simple docstring""" lowerCAmelCase__ = "linear" lowerCAmelCase__ = "cosine" lowerCAmelCase__ = "cosine_with_restarts" lowerCAmelCase__ = "polynomial" lowerCAmelCase__ = "constant" lowerCAmelCase__ = "constant_with_warmup" lowerCAmelCase__ = "piecewise_constant" def a__ ( a__ , a__ = -1 ): """simple docstring""" return LambdaLR(a__ , lambda a__ : 1 , last_epoch=a__ ) def a__ ( a__ , a__ , a__ = -1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1.0 , a__ ) ) return 1.0 return LambdaLR(a__ , a__ , last_epoch=a__ ) def a__ ( a__ , a__ , a__ = -1 ): """simple docstring""" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = step_rules.split(""",""" ) for rule_str in rule_list[:-1]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = rule_str.split(""":""" ) __SCREAMING_SNAKE_CASE = int(a__ ) __SCREAMING_SNAKE_CASE = float(a__ ) __SCREAMING_SNAKE_CASE = value __SCREAMING_SNAKE_CASE = float(rule_list[-1] ) def create_rules_function(a__ , a__ ): def rule_func(a__ ) -> float: __SCREAMING_SNAKE_CASE = sorted(rules_dict.keys() ) for i, sorted_step in enumerate(a__ ): if steps < sorted_step: return rules_dict[sorted_steps[i]] return last_lr_multiple return rule_func __SCREAMING_SNAKE_CASE = create_rules_function(a__ , a__ ) return LambdaLR(a__ , a__ , last_epoch=a__ ) def a__ ( a__ , a__ , a__ , a__=-1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) return max( 0.0 , float(num_training_steps - current_step ) / float(max(1 , num_training_steps - num_warmup_steps ) ) ) return LambdaLR(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ , a__ = 0.5 , a__ = -1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) __SCREAMING_SNAKE_CASE = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * float(a__ ) * 2.0 * progress )) ) return LambdaLR(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ , a__ = 1 , a__ = -1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) __SCREAMING_SNAKE_CASE = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) if progress >= 1.0: return 0.0 return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * ((float(a__ ) * progress) % 1.0) )) ) return LambdaLR(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ , a__=1E-7 , a__=1.0 , a__=-1 ): """simple docstring""" __SCREAMING_SNAKE_CASE = optimizer.defaults["""lr"""] if not (lr_init > lr_end): raise ValueError(F'lr_end ({lr_end}) must be be smaller than initial lr ({lr_init})' ) def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) elif current_step > num_training_steps: return lr_end / lr_init # as LambdaLR multiplies by lr_init else: __SCREAMING_SNAKE_CASE = lr_init - lr_end __SCREAMING_SNAKE_CASE = num_training_steps - num_warmup_steps __SCREAMING_SNAKE_CASE = 1 - (current_step - num_warmup_steps) / decay_steps __SCREAMING_SNAKE_CASE = lr_range * pct_remaining**power + lr_end return decay / lr_init # as LambdaLR multiplies by lr_init return LambdaLR(a__ , a__ , a__ ) UpperCAmelCase : Optional[Any] = { SchedulerType.LINEAR: get_linear_schedule_with_warmup, SchedulerType.COSINE: get_cosine_schedule_with_warmup, SchedulerType.COSINE_WITH_RESTARTS: get_cosine_with_hard_restarts_schedule_with_warmup, SchedulerType.POLYNOMIAL: get_polynomial_decay_schedule_with_warmup, SchedulerType.CONSTANT: get_constant_schedule, SchedulerType.CONSTANT_WITH_WARMUP: get_constant_schedule_with_warmup, SchedulerType.PIECEWISE_CONSTANT: get_piecewise_constant_schedule, } def a__ ( a__ , a__ , a__ = None , a__ = None , a__ = None , a__ = 1 , a__ = 1.0 , a__ = -1 , ): """simple docstring""" __SCREAMING_SNAKE_CASE = SchedulerType(a__ ) __SCREAMING_SNAKE_CASE = TYPE_TO_SCHEDULER_FUNCTION[name] if name == SchedulerType.CONSTANT: return schedule_func(a__ , last_epoch=a__ ) if name == SchedulerType.PIECEWISE_CONSTANT: return schedule_func(a__ , step_rules=a__ , last_epoch=a__ ) # All other schedulers require `num_warmup_steps` if num_warmup_steps is None: raise ValueError(F'{name} requires `num_warmup_steps`, please provide that argument.' ) if name == SchedulerType.CONSTANT_WITH_WARMUP: return schedule_func(a__ , num_warmup_steps=a__ , last_epoch=a__ ) # All other schedulers require `num_training_steps` if num_training_steps is None: raise ValueError(F'{name} requires `num_training_steps`, please provide that argument.' ) if name == SchedulerType.COSINE_WITH_RESTARTS: return schedule_func( a__ , num_warmup_steps=a__ , num_training_steps=a__ , num_cycles=a__ , last_epoch=a__ , ) if name == SchedulerType.POLYNOMIAL: return schedule_func( a__ , num_warmup_steps=a__ , num_training_steps=a__ , power=a__ , last_epoch=a__ , ) return schedule_func( a__ , num_warmup_steps=a__ , num_training_steps=a__ , last_epoch=a__ )
267
1
'''simple docstring''' import unittest from transformers import TrOCRConfig from transformers.testing_utils import is_torch_available, require_torch, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers.models.trocr.modeling_trocr import TrOCRDecoder, TrOCRForCausalLM @require_torch class lowerCAmelCase__ : """simple docstring""" def __init__( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : List[Any]=99 , __SCREAMING_SNAKE_CASE : List[Any]=13 , __SCREAMING_SNAKE_CASE : Optional[Any]=16 , __SCREAMING_SNAKE_CASE : List[str]=7 , __SCREAMING_SNAKE_CASE : List[str]=True , __SCREAMING_SNAKE_CASE : Tuple=True , __SCREAMING_SNAKE_CASE : Dict=True , __SCREAMING_SNAKE_CASE : Optional[Any]=False , __SCREAMING_SNAKE_CASE : Any=True , __SCREAMING_SNAKE_CASE : Optional[Any]=2 , __SCREAMING_SNAKE_CASE : Tuple=32 , __SCREAMING_SNAKE_CASE : str=4 , __SCREAMING_SNAKE_CASE : int=4 , __SCREAMING_SNAKE_CASE : Optional[int]=30 , __SCREAMING_SNAKE_CASE : str=0 , __SCREAMING_SNAKE_CASE : str=1 , __SCREAMING_SNAKE_CASE : Tuple=2 , __SCREAMING_SNAKE_CASE : Any=None , ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = decoder_seq_length # For common tests __SCREAMING_SNAKE_CASE = self.decoder_seq_length __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_attention_mask __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = d_model __SCREAMING_SNAKE_CASE = d_model __SCREAMING_SNAKE_CASE = decoder_layers __SCREAMING_SNAKE_CASE = decoder_layers __SCREAMING_SNAKE_CASE = decoder_ffn_dim __SCREAMING_SNAKE_CASE = decoder_attention_heads __SCREAMING_SNAKE_CASE = decoder_attention_heads __SCREAMING_SNAKE_CASE = eos_token_id __SCREAMING_SNAKE_CASE = bos_token_id __SCREAMING_SNAKE_CASE = pad_token_id __SCREAMING_SNAKE_CASE = decoder_start_token_id __SCREAMING_SNAKE_CASE = use_cache __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = decoder_seq_length __SCREAMING_SNAKE_CASE = 2 __SCREAMING_SNAKE_CASE = 1 def UpperCAmelCase__ ( self : Any ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE = None if self.use_attention_mask: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.decoder_seq_length] , vocab_size=2 ) __SCREAMING_SNAKE_CASE = None if self.use_labels: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE = TrOCRConfig( vocab_size=self.vocab_size , d_model=self.d_model , decoder_layers=self.decoder_layers , decoder_ffn_dim=self.decoder_ffn_dim , decoder_attention_heads=self.decoder_attention_heads , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , use_cache=self.use_cache , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , max_position_embeddings=self.max_position_embeddings , ) return (config, input_ids, attention_mask, lm_labels) def UpperCAmelCase__ ( self : str , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : str , ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = TrOCRDecoder(config=__SCREAMING_SNAKE_CASE ).to(__SCREAMING_SNAKE_CASE ).eval() __SCREAMING_SNAKE_CASE = input_ids[:2] input_ids[input_ids == 0] += 1 # first forward pass __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE , use_cache=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE , use_cache=__SCREAMING_SNAKE_CASE ) self.parent.assertTrue(len(__SCREAMING_SNAKE_CASE ) == len(__SCREAMING_SNAKE_CASE ) ) self.parent.assertTrue(len(__SCREAMING_SNAKE_CASE ) == len(__SCREAMING_SNAKE_CASE ) + 1 ) __SCREAMING_SNAKE_CASE = outputs["""past_key_values"""] # create hypothetical next token and extent to next_input_ids __SCREAMING_SNAKE_CASE = ids_tensor((2, 1) , config.vocab_size - 1 ) + 1 # append to next input_ids and __SCREAMING_SNAKE_CASE = torch.cat([input_ids, next_tokens] , dim=-1 ) __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE )["""last_hidden_state"""] __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE , past_key_values=__SCREAMING_SNAKE_CASE )["""last_hidden_state"""] # select random slice __SCREAMING_SNAKE_CASE = ids_tensor((1,) , output_from_past.shape[-1] ).item() __SCREAMING_SNAKE_CASE = output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach() __SCREAMING_SNAKE_CASE = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice assert torch.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = config_and_inputs __SCREAMING_SNAKE_CASE = {"""input_ids""": input_ids, """attention_mask""": attention_mask} return config, inputs_dict @require_torch class lowerCAmelCase__ ( a , a , a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = (TrOCRDecoder, TrOCRForCausalLM) if is_torch_available() else () lowerCAmelCase__ = (TrOCRForCausalLM,) if is_torch_available() else () lowerCAmelCase__ = {"text-generation": TrOCRForCausalLM} if is_torch_available() else {} lowerCAmelCase__ = True lowerCAmelCase__ = False def UpperCAmelCase__ ( self : Tuple ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = TrOCRStandaloneDecoderModelTester(self , is_training=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] ) -> Optional[Any]: """simple docstring""" pass def UpperCAmelCase__ ( self : Tuple ) -> Any: """simple docstring""" pass def UpperCAmelCase__ ( self : Optional[int] ) -> Any: """simple docstring""" pass def UpperCAmelCase__ ( self : List[str] ) -> Any: """simple docstring""" self.config_tester.run_common_tests() def UpperCAmelCase__ ( self : int ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_decoder_model_past(*__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : int ) -> Optional[Any]: """simple docstring""" return @unittest.skip("""The model doesn't support left padding""" ) # and it's not used enough to be worth fixing :) def UpperCAmelCase__ ( self : int ) -> List[Any]: """simple docstring""" pass
267
'''simple docstring''' import argparse import os from . import ( ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, BART_PRETRAINED_MODEL_ARCHIVE_LIST, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, AlbertConfig, BartConfig, BertConfig, CamembertConfig, CTRLConfig, DistilBertConfig, DPRConfig, ElectraConfig, FlaubertConfig, GPTaConfig, LayoutLMConfig, LxmertConfig, OpenAIGPTConfig, RobertaConfig, TaConfig, TFAlbertForPreTraining, TFBartForConditionalGeneration, TFBartForSequenceClassification, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFCamembertForMaskedLM, TFCTRLLMHeadModel, TFDistilBertForMaskedLM, TFDistilBertForQuestionAnswering, TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, TFElectraForPreTraining, TFFlaubertWithLMHeadModel, TFGPTaLMHeadModel, TFLayoutLMForMaskedLM, TFLxmertForPreTraining, TFLxmertVisualFeatureEncoder, TFOpenAIGPTLMHeadModel, TFRobertaForCausalLM, TFRobertaForMaskedLM, TFRobertaForSequenceClassification, TFTaForConditionalGeneration, TFTransfoXLLMHeadModel, TFWavaVecaModel, TFXLMRobertaForMaskedLM, TFXLMWithLMHeadModel, TFXLNetLMHeadModel, TransfoXLConfig, WavaVecaConfig, WavaVecaModel, XLMConfig, XLMRobertaConfig, XLNetConfig, is_torch_available, load_pytorch_checkpoint_in_tfa_model, ) from .utils import CONFIG_NAME, WEIGHTS_NAME, cached_file, logging if is_torch_available(): import numpy as np import torch from . import ( AlbertForPreTraining, BartForConditionalGeneration, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, CamembertForMaskedLM, CTRLLMHeadModel, DistilBertForMaskedLM, DistilBertForQuestionAnswering, DPRContextEncoder, DPRQuestionEncoder, DPRReader, ElectraForPreTraining, FlaubertWithLMHeadModel, GPTaLMHeadModel, LayoutLMForMaskedLM, LxmertForPreTraining, LxmertVisualFeatureEncoder, OpenAIGPTLMHeadModel, RobertaForMaskedLM, RobertaForSequenceClassification, TaForConditionalGeneration, TransfoXLLMHeadModel, XLMRobertaForMaskedLM, XLMWithLMHeadModel, XLNetLMHeadModel, ) logging.set_verbosity_info() UpperCAmelCase : Tuple = { 'bart': ( BartConfig, TFBartForConditionalGeneration, TFBartForSequenceClassification, BartForConditionalGeneration, BART_PRETRAINED_MODEL_ARCHIVE_LIST, ), 'bert': ( BertConfig, TFBertForPreTraining, BertForPreTraining, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'bert-large-uncased-whole-word-masking-finetuned-squad': ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'bert-large-cased-whole-word-masking-finetuned-squad': ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'bert-base-cased-finetuned-mrpc': ( BertConfig, TFBertForSequenceClassification, BertForSequenceClassification, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'dpr': ( DPRConfig, TFDPRQuestionEncoder, TFDPRContextEncoder, TFDPRReader, DPRQuestionEncoder, DPRContextEncoder, DPRReader, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ), 'gpt2': ( GPTaConfig, TFGPTaLMHeadModel, GPTaLMHeadModel, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'xlnet': ( XLNetConfig, TFXLNetLMHeadModel, XLNetLMHeadModel, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'xlm': ( XLMConfig, TFXLMWithLMHeadModel, XLMWithLMHeadModel, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'xlm-roberta': ( XLMRobertaConfig, TFXLMRobertaForMaskedLM, XLMRobertaForMaskedLM, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'transfo-xl': ( TransfoXLConfig, TFTransfoXLLMHeadModel, TransfoXLLMHeadModel, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'openai-gpt': ( OpenAIGPTConfig, TFOpenAIGPTLMHeadModel, OpenAIGPTLMHeadModel, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'roberta': ( RobertaConfig, TFRobertaForCausalLM, TFRobertaForMaskedLM, RobertaForMaskedLM, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'layoutlm': ( LayoutLMConfig, TFLayoutLMForMaskedLM, LayoutLMForMaskedLM, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, ), 'roberta-large-mnli': ( RobertaConfig, TFRobertaForSequenceClassification, RobertaForSequenceClassification, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'camembert': ( CamembertConfig, TFCamembertForMaskedLM, CamembertForMaskedLM, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'flaubert': ( FlaubertConfig, TFFlaubertWithLMHeadModel, FlaubertWithLMHeadModel, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'distilbert': ( DistilBertConfig, TFDistilBertForMaskedLM, DistilBertForMaskedLM, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'distilbert-base-distilled-squad': ( DistilBertConfig, TFDistilBertForQuestionAnswering, DistilBertForQuestionAnswering, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'lxmert': ( LxmertConfig, TFLxmertForPreTraining, LxmertForPreTraining, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'lxmert-visual-feature-encoder': ( LxmertConfig, TFLxmertVisualFeatureEncoder, LxmertVisualFeatureEncoder, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'ctrl': ( CTRLConfig, TFCTRLLMHeadModel, CTRLLMHeadModel, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'albert': ( AlbertConfig, TFAlbertForPreTraining, AlbertForPreTraining, ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 't5': ( TaConfig, TFTaForConditionalGeneration, TaForConditionalGeneration, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'electra': ( ElectraConfig, TFElectraForPreTraining, ElectraForPreTraining, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'wav2vec2': ( WavaVecaConfig, TFWavaVecaModel, WavaVecaModel, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), } def a__ ( a__ , a__ , a__ , a__ , a__=False , a__=True ): """simple docstring""" if model_type not in MODEL_CLASSES: raise ValueError(F'Unrecognized model type, should be one of {list(MODEL_CLASSES.keys() )}.' ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = MODEL_CLASSES[model_type] # Initialise TF model if config_file in aws_config_map: __SCREAMING_SNAKE_CASE = cached_file(a__ , a__ , force_download=not use_cached_models ) __SCREAMING_SNAKE_CASE = config_class.from_json_file(a__ ) __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = True print(F'Building TensorFlow model from configuration: {config}' ) __SCREAMING_SNAKE_CASE = model_class(a__ ) # Load weights from tf checkpoint if pytorch_checkpoint_path in aws_config_map.keys(): __SCREAMING_SNAKE_CASE = cached_file( a__ , a__ , force_download=not use_cached_models ) # Load PyTorch checkpoint in tf2 model: __SCREAMING_SNAKE_CASE = load_pytorch_checkpoint_in_tfa_model(a__ , a__ ) if compare_with_pt_model: __SCREAMING_SNAKE_CASE = tf_model(tf_model.dummy_inputs , training=a__ ) # build the network __SCREAMING_SNAKE_CASE = torch.load(a__ , map_location="""cpu""" ) __SCREAMING_SNAKE_CASE = pt_model_class.from_pretrained( pretrained_model_name_or_path=a__ , config=a__ , state_dict=a__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = pt_model(**pt_model.dummy_inputs ) __SCREAMING_SNAKE_CASE = pto[0].numpy() __SCREAMING_SNAKE_CASE = tfo[0].numpy() __SCREAMING_SNAKE_CASE = np.amax(np.abs(np_pt - np_tf ) ) print(F'Max absolute difference between models outputs {diff}' ) assert diff <= 2E-2, F'Error, model absolute difference is >2e-2: {diff}' # Save pytorch-model print(F'Save TensorFlow model to {tf_dump_path}' ) tf_model.save_weights(a__ , save_format="""h5""" ) def a__ ( a__ , a__ , a__=None , a__=None , a__=False , a__=False , a__=False , a__=False , ): """simple docstring""" if args_model_type is None: __SCREAMING_SNAKE_CASE = list(MODEL_CLASSES.keys() ) else: __SCREAMING_SNAKE_CASE = [args_model_type] for j, model_type in enumerate(a__ , start=1 ): print("""=""" * 1_00 ) print(F' Converting model type {j}/{len(a__ )}: {model_type}' ) print("""=""" * 1_00 ) if model_type not in MODEL_CLASSES: raise ValueError(F'Unrecognized model type {model_type}, should be one of {list(MODEL_CLASSES.keys() )}.' ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = MODEL_CLASSES[model_type] if model_shortcut_names_or_path is None: __SCREAMING_SNAKE_CASE = list(aws_model_maps.keys() ) if config_shortcut_names_or_path is None: __SCREAMING_SNAKE_CASE = model_shortcut_names_or_path for i, (model_shortcut_name, config_shortcut_name) in enumerate( zip(a__ , a__ ) , start=1 ): print("""-""" * 1_00 ) if "-squad" in model_shortcut_name or "-mrpc" in model_shortcut_name or "-mnli" in model_shortcut_name: if not only_convert_finetuned_models: print(F' Skipping finetuned checkpoint {model_shortcut_name}' ) continue __SCREAMING_SNAKE_CASE = model_shortcut_name elif only_convert_finetuned_models: print(F' Skipping not finetuned checkpoint {model_shortcut_name}' ) continue print( F' Converting checkpoint {i}/{len(a__ )}: {model_shortcut_name} - model_type {model_type}' ) print("""-""" * 1_00 ) if config_shortcut_name in aws_config_map: __SCREAMING_SNAKE_CASE = cached_file(a__ , a__ , force_download=not use_cached_models ) else: __SCREAMING_SNAKE_CASE = config_shortcut_name if model_shortcut_name in aws_model_maps: __SCREAMING_SNAKE_CASE = cached_file(a__ , a__ , force_download=not use_cached_models ) else: __SCREAMING_SNAKE_CASE = model_shortcut_name if os.path.isfile(a__ ): __SCREAMING_SNAKE_CASE = """converted_model""" convert_pt_checkpoint_to_tf( model_type=a__ , pytorch_checkpoint_path=a__ , config_file=a__ , tf_dump_path=os.path.join(a__ , model_shortcut_name + """-tf_model.h5""" ) , compare_with_pt_model=a__ , ) if remove_cached_files: os.remove(a__ ) os.remove(a__ ) if __name__ == "__main__": UpperCAmelCase : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--tf_dump_path', default=None, type=str, required=True, help='Path to the output Tensorflow dump file.' ) parser.add_argument( '--model_type', default=None, type=str, help=( f"""Model type selected in the list of {list(MODEL_CLASSES.keys())}. If not given, will download and """ 'convert all the models from AWS.' ), ) parser.add_argument( '--pytorch_checkpoint_path', default=None, type=str, help=( 'Path to the PyTorch checkpoint path or shortcut name to download from AWS. ' 'If not given, will download and convert all the checkpoints from AWS.' ), ) parser.add_argument( '--config_file', default=None, type=str, help=( 'The config json file corresponding to the pre-trained model. \n' 'This specifies the model architecture. If not given and ' '--pytorch_checkpoint_path is not given or is a shortcut name ' 'use the configuration associated to the shortcut name on the AWS' ), ) parser.add_argument( '--compare_with_pt_model', action='store_true', help='Compare Tensorflow and PyTorch model predictions.' ) parser.add_argument( '--use_cached_models', action='store_true', help='Use cached models if possible instead of updating to latest checkpoint versions.', ) parser.add_argument( '--remove_cached_files', action='store_true', help='Remove pytorch models after conversion (save memory when converting in batches).', ) parser.add_argument('--only_convert_finetuned_models', action='store_true', help='Only convert finetuned models.') UpperCAmelCase : List[Any] = parser.parse_args() # if args.pytorch_checkpoint_path is not None: # convert_pt_checkpoint_to_tf(args.model_type.lower(), # args.pytorch_checkpoint_path, # args.config_file if args.config_file is not None else args.pytorch_checkpoint_path, # args.tf_dump_path, # compare_with_pt_model=args.compare_with_pt_model, # use_cached_models=args.use_cached_models) # else: convert_all_pt_checkpoints_to_tf( args.model_type.lower() if args.model_type is not None else None, args.tf_dump_path, model_shortcut_names_or_path=[args.pytorch_checkpoint_path] if args.pytorch_checkpoint_path is not None else None, config_shortcut_names_or_path=[args.config_file] if args.config_file is not None else None, compare_with_pt_model=args.compare_with_pt_model, use_cached_models=args.use_cached_models, remove_cached_files=args.remove_cached_files, only_convert_finetuned_models=args.only_convert_finetuned_models, )
267
1
'''simple docstring''' from manim import * class lowerCAmelCase__ ( a ): """simple docstring""" def UpperCAmelCase__ ( self : Dict ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = Rectangle(height=0.5 , width=0.5 ) __SCREAMING_SNAKE_CASE = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0 ) __SCREAMING_SNAKE_CASE = [mem.copy() for i in range(6 )] __SCREAMING_SNAKE_CASE = [mem.copy() for i in range(6 )] __SCREAMING_SNAKE_CASE = VGroup(*__SCREAMING_SNAKE_CASE ).arrange(__SCREAMING_SNAKE_CASE , buff=0 ) __SCREAMING_SNAKE_CASE = VGroup(*__SCREAMING_SNAKE_CASE ).arrange(__SCREAMING_SNAKE_CASE , buff=0 ) __SCREAMING_SNAKE_CASE = VGroup(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).arrange(__SCREAMING_SNAKE_CASE , buff=0 ) __SCREAMING_SNAKE_CASE = Text("""CPU""" , font_size=24 ) __SCREAMING_SNAKE_CASE = Group(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).arrange(__SCREAMING_SNAKE_CASE , buff=0.5 , aligned_edge=__SCREAMING_SNAKE_CASE ) cpu.move_to([-2.5, -0.5, 0] ) self.add(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = [mem.copy() for i in range(1 )] __SCREAMING_SNAKE_CASE = VGroup(*__SCREAMING_SNAKE_CASE ).arrange(__SCREAMING_SNAKE_CASE , buff=0 ) __SCREAMING_SNAKE_CASE = Text("""GPU""" , font_size=24 ) __SCREAMING_SNAKE_CASE = Group(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).arrange(__SCREAMING_SNAKE_CASE , buff=0.5 , aligned_edge=__SCREAMING_SNAKE_CASE ) gpu.align_to(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) gpu.set_x(gpu.get_x() - 1 ) self.add(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = [mem.copy() for i in range(6 )] __SCREAMING_SNAKE_CASE = VGroup(*__SCREAMING_SNAKE_CASE ).arrange(__SCREAMING_SNAKE_CASE , buff=0 ) __SCREAMING_SNAKE_CASE = Text("""Model""" , font_size=24 ) __SCREAMING_SNAKE_CASE = Group(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).arrange(__SCREAMING_SNAKE_CASE , buff=0.5 , aligned_edge=__SCREAMING_SNAKE_CASE ) model.move_to([3, -1.0, 0] ) self.play( Create(__SCREAMING_SNAKE_CASE , run_time=1 ) , Create(__SCREAMING_SNAKE_CASE , run_time=1 ) , Create(__SCREAMING_SNAKE_CASE , run_time=1 ) , ) __SCREAMING_SNAKE_CASE = MarkupText( f'First, an empty model skeleton is loaded\ninto <span fgcolor=\'{YELLOW}\'>memory</span> without using much RAM.' , font_size=24 , ) __SCREAMING_SNAKE_CASE = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) __SCREAMING_SNAKE_CASE = MarkupText( f'<b>Key:</b>\n\n<span fgcolor=\'{YELLOW}\'>●</span> Empty Model' , font_size=18 , ) key_text.move_to([-5, 2.4, 0] ) step_a.move_to([2, 2, 0] ) self.play(Write(__SCREAMING_SNAKE_CASE , run_time=2.5 ) , Write(__SCREAMING_SNAKE_CASE ) , Write(__SCREAMING_SNAKE_CASE ) ) self.add(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] for i, rect in enumerate(__SCREAMING_SNAKE_CASE ): __SCREAMING_SNAKE_CASE = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0.0 ).set_fill(__SCREAMING_SNAKE_CASE , opacity=0.7 ) cpu_target.move_to(__SCREAMING_SNAKE_CASE ) cpu_target.generate_target() __SCREAMING_SNAKE_CASE = 0.46 / 4 __SCREAMING_SNAKE_CASE = 0.46 / 3 if i == 0: cpu_target.target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) , buff=0.02 , direction=__SCREAMING_SNAKE_CASE ) cpu_target.target.set_x(cpu_target.target.get_x() + 0.1 ) elif i == 3: cpu_target.target.next_to(cpu_targs[0].target , direction=__SCREAMING_SNAKE_CASE , buff=0.0 ) else: cpu_target.target.next_to(cpu_targs[i - 1].target , direction=__SCREAMING_SNAKE_CASE , buff=0.0 ) cpu_targs.append(__SCREAMING_SNAKE_CASE ) first_animations.append(rect.animate(run_time=0.5 ).set_stroke(__SCREAMING_SNAKE_CASE ) ) second_animations.append(MoveToTarget(__SCREAMING_SNAKE_CASE , run_time=1.5 ) ) self.play(*__SCREAMING_SNAKE_CASE ) self.play(*__SCREAMING_SNAKE_CASE ) self.wait()
267
'''simple docstring''' def a__ ( a__ ): """simple docstring""" if isinstance(a__ , a__ ): raise TypeError("""'float' object cannot be interpreted as an integer""" ) if isinstance(a__ , a__ ): raise TypeError("""'str' object cannot be interpreted as an integer""" ) if num == 0: return "0b0" __SCREAMING_SNAKE_CASE = False if num < 0: __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = -num __SCREAMING_SNAKE_CASE = [] while num > 0: binary.insert(0 , num % 2 ) num >>= 1 if negative: return "-0b" + "".join(str(a__ ) for e in binary ) return "0b" + "".join(str(a__ ) for e in binary ) if __name__ == "__main__": import doctest doctest.testmod()
267
1
'''simple docstring''' import argparse import torch from torch import nn from transformers import SpeechaTextConfig, SpeechaTextForConditionalGeneration def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = [ """encoder.version""", """decoder.version""", """model.encoder.version""", """model.decoder.version""", """decoder.output_projection.weight""", """_float_tensor""", """encoder.embed_positions._float_tensor""", """decoder.embed_positions._float_tensor""", ] for k in ignore_keys: state_dict.pop(a__ , a__ ) def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = list(s_dict.keys() ) for key in keys: if "transformer_layers" in key: __SCREAMING_SNAKE_CASE = s_dict.pop(a__ ) elif "subsample" in key: __SCREAMING_SNAKE_CASE = s_dict.pop(a__ ) def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = emb.weight.shape __SCREAMING_SNAKE_CASE = nn.Linear(a__ , a__ , bias=a__ ) __SCREAMING_SNAKE_CASE = emb.weight.data return lin_layer def a__ ( a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = torch.load(a__ , map_location="""cpu""" ) __SCREAMING_SNAKE_CASE = mam_aaa["""args"""] __SCREAMING_SNAKE_CASE = mam_aaa["""model"""] __SCREAMING_SNAKE_CASE = state_dict["""decoder.output_projection.weight"""] remove_ignore_keys_(a__ ) rename_keys(a__ ) __SCREAMING_SNAKE_CASE = state_dict["""decoder.embed_tokens.weight"""].shape[0] __SCREAMING_SNAKE_CASE = args.share_decoder_input_output_embed __SCREAMING_SNAKE_CASE = [int(a__ ) for i in args.conv_kernel_sizes.split(""",""" )] __SCREAMING_SNAKE_CASE = SpeechaTextConfig( vocab_size=a__ , max_source_positions=args.max_source_positions , max_target_positions=args.max_target_positions , encoder_layers=args.encoder_layers , decoder_layers=args.decoder_layers , encoder_attention_heads=args.encoder_attention_heads , decoder_attention_heads=args.decoder_attention_heads , encoder_ffn_dim=args.encoder_ffn_embed_dim , decoder_ffn_dim=args.decoder_ffn_embed_dim , d_model=args.encoder_embed_dim , dropout=args.dropout , attention_dropout=args.attention_dropout , activation_dropout=args.activation_dropout , activation_function="""relu""" , num_conv_layers=len(a__ ) , conv_channels=args.conv_channels , conv_kernel_sizes=a__ , input_feat_per_channel=args.input_feat_per_channel , input_channels=args.input_channels , tie_word_embeddings=a__ , num_beams=5 , max_length=2_00 , use_cache=a__ , decoder_start_token_id=2 , early_stopping=a__ , ) __SCREAMING_SNAKE_CASE = SpeechaTextForConditionalGeneration(a__ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = model.model.load_state_dict(a__ , strict=a__ ) if len(a__ ) > 0 and not set(a__ ) <= { "encoder.embed_positions.weights", "decoder.embed_positions.weights", }: raise ValueError( """Only `encoder.embed_positions.weights` and `decoder.embed_positions.weights` are allowed to be missing,""" F' but all the following weights are missing {missing}' ) if tie_embeds: __SCREAMING_SNAKE_CASE = make_linear_from_emb(model.model.decoder.embed_tokens ) else: __SCREAMING_SNAKE_CASE = lm_head_weights model.save_pretrained(a__ ) if __name__ == "__main__": UpperCAmelCase : Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument('--fairseq_path', type=str, help='Path to the fairseq model (.pt) file.') parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') UpperCAmelCase : List[str] = parser.parse_args() convert_fairseq_sat_checkpoint_to_tfms(args.fairseq_path, args.pytorch_dump_folder_path)
267
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices UpperCAmelCase : Optional[int] = logging.get_logger(__name__) UpperCAmelCase : str = { 'facebook/convnextv2-tiny-1k-224': 'https://huggingface.co/facebook/convnextv2-tiny-1k-224/resolve/main/config.json', } class lowerCAmelCase__ ( a , a ): """simple docstring""" lowerCAmelCase__ = "convnextv2" def __init__( self : Any , __SCREAMING_SNAKE_CASE : int=3 , __SCREAMING_SNAKE_CASE : Dict=4 , __SCREAMING_SNAKE_CASE : List[Any]=4 , __SCREAMING_SNAKE_CASE : Optional[int]=None , __SCREAMING_SNAKE_CASE : Dict=None , __SCREAMING_SNAKE_CASE : Optional[int]="gelu" , __SCREAMING_SNAKE_CASE : Union[str, Any]=0.02 , __SCREAMING_SNAKE_CASE : Dict=1E-12 , __SCREAMING_SNAKE_CASE : List[str]=0.0 , __SCREAMING_SNAKE_CASE : Optional[Any]=224 , __SCREAMING_SNAKE_CASE : Tuple=None , __SCREAMING_SNAKE_CASE : List[str]=None , **__SCREAMING_SNAKE_CASE : Union[str, Any] , ) -> Union[str, Any]: """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = patch_size __SCREAMING_SNAKE_CASE = num_stages __SCREAMING_SNAKE_CASE = [96, 192, 384, 768] if hidden_sizes is None else hidden_sizes __SCREAMING_SNAKE_CASE = [3, 3, 9, 3] if depths is None else depths __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = drop_path_rate __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = ["""stem"""] + [f'stage{idx}' for idx in range(1 , len(self.depths ) + 1 )] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = get_aligned_output_features_output_indices( out_features=__SCREAMING_SNAKE_CASE , out_indices=__SCREAMING_SNAKE_CASE , stage_names=self.stage_names )
267
1
'''simple docstring''' import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import CLIPImageProcessor, CLIPProcessor @require_vision class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : Union[str, Any] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() # fmt: off __SCREAMING_SNAKE_CASE = ["""l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """lo""", """l</w>""", """w</w>""", """r</w>""", """t</w>""", """low</w>""", """er</w>""", """lowest</w>""", """newer</w>""", """wider""", """<unk>""", """<|startoftext|>""", """<|endoftext|>"""] # fmt: on __SCREAMING_SNAKE_CASE = dict(zip(__SCREAMING_SNAKE_CASE , range(len(__SCREAMING_SNAKE_CASE ) ) ) ) __SCREAMING_SNAKE_CASE = ["""#version: 0.2""", """l o""", """lo w</w>""", """e r</w>""", """"""] __SCREAMING_SNAKE_CASE = {"""unk_token""": """<unk>"""} __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) __SCREAMING_SNAKE_CASE = 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(__SCREAMING_SNAKE_CASE ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = { """do_resize""": True, """size""": 20, """do_center_crop""": True, """crop_size""": 18, """do_normalize""": True, """image_mean""": [0.48145466, 0.4578275, 0.40821073], """image_std""": [0.26862954, 0.26130258, 0.27577711], } __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , __SCREAMING_SNAKE_CASE ) with open(self.image_processor_file , """w""" , encoding="""utf-8""" ) as fp: json.dump(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] , **__SCREAMING_SNAKE_CASE : Optional[int] ) -> str: """simple docstring""" return CLIPTokenizer.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Tuple , **__SCREAMING_SNAKE_CASE : Any ) -> int: """simple docstring""" return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[Any] , **__SCREAMING_SNAKE_CASE : Optional[int] ) -> List[str]: """simple docstring""" return CLIPImageProcessor.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Tuple ) -> str: """simple docstring""" shutil.rmtree(self.tmpdirname ) def UpperCAmelCase__ ( self : Optional[Any] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __SCREAMING_SNAKE_CASE = [Image.fromarray(np.moveaxis(__SCREAMING_SNAKE_CASE , 0 , -1 ) ) for x in image_inputs] return image_inputs def UpperCAmelCase__ ( self : Optional[int] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = self.get_rust_tokenizer() __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) processor_slow.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = CLIPProcessor.from_pretrained(self.tmpdirname , use_fast=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) processor_fast.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = CLIPProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , __SCREAMING_SNAKE_CASE ) self.assertIsInstance(processor_fast.tokenizer , __SCREAMING_SNAKE_CASE ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , __SCREAMING_SNAKE_CASE ) self.assertIsInstance(processor_fast.image_processor , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) __SCREAMING_SNAKE_CASE = self.get_image_processor(do_normalize=__SCREAMING_SNAKE_CASE , padding_value=1.0 ) __SCREAMING_SNAKE_CASE = CLIPProcessor.from_pretrained( self.tmpdirname , bos_token="""(BOS)""" , eos_token="""(EOS)""" , do_normalize=__SCREAMING_SNAKE_CASE , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , __SCREAMING_SNAKE_CASE ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[str] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = image_processor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ) __SCREAMING_SNAKE_CASE = processor(images=__SCREAMING_SNAKE_CASE , return_tensors="""np""" ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1E-2 ) def UpperCAmelCase__ ( self : List[Any] ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """lower newer""" __SCREAMING_SNAKE_CASE = processor(text=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer(__SCREAMING_SNAKE_CASE ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def UpperCAmelCase__ ( self : Dict ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """lower newer""" __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = processor(text=__SCREAMING_SNAKE_CASE , images=__SCREAMING_SNAKE_CASE ) self.assertListEqual(list(inputs.keys() ) , ["""input_ids""", """attention_mask""", """pixel_values"""] ) # test if it raises when no input is passed with pytest.raises(__SCREAMING_SNAKE_CASE ): processor() def UpperCAmelCase__ ( self : List[str] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __SCREAMING_SNAKE_CASE = processor.batch_decode(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer.batch_decode(__SCREAMING_SNAKE_CASE ) self.assertListEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : int ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """lower newer""" __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = processor(text=__SCREAMING_SNAKE_CASE , images=__SCREAMING_SNAKE_CASE ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
267
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices UpperCAmelCase : List[str] = logging.get_logger(__name__) class lowerCAmelCase__ ( a , a ): """simple docstring""" lowerCAmelCase__ = "maskformer-swin" lowerCAmelCase__ = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self : str , __SCREAMING_SNAKE_CASE : Tuple=224 , __SCREAMING_SNAKE_CASE : str=4 , __SCREAMING_SNAKE_CASE : Union[str, Any]=3 , __SCREAMING_SNAKE_CASE : Optional[Any]=96 , __SCREAMING_SNAKE_CASE : Optional[Any]=[2, 2, 6, 2] , __SCREAMING_SNAKE_CASE : Any=[3, 6, 12, 24] , __SCREAMING_SNAKE_CASE : Dict=7 , __SCREAMING_SNAKE_CASE : Dict=4.0 , __SCREAMING_SNAKE_CASE : Dict=True , __SCREAMING_SNAKE_CASE : str=0.0 , __SCREAMING_SNAKE_CASE : int=0.0 , __SCREAMING_SNAKE_CASE : str=0.1 , __SCREAMING_SNAKE_CASE : List[Any]="gelu" , __SCREAMING_SNAKE_CASE : str=False , __SCREAMING_SNAKE_CASE : Optional[int]=0.02 , __SCREAMING_SNAKE_CASE : Optional[int]=1E-5 , __SCREAMING_SNAKE_CASE : Dict=None , __SCREAMING_SNAKE_CASE : Dict=None , **__SCREAMING_SNAKE_CASE : Tuple , ) -> Tuple: """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = patch_size __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = embed_dim __SCREAMING_SNAKE_CASE = depths __SCREAMING_SNAKE_CASE = len(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = num_heads __SCREAMING_SNAKE_CASE = window_size __SCREAMING_SNAKE_CASE = mlp_ratio __SCREAMING_SNAKE_CASE = qkv_bias __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = drop_path_rate __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = use_absolute_embeddings __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = initializer_range # we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model __SCREAMING_SNAKE_CASE = int(embed_dim * 2 ** (len(__SCREAMING_SNAKE_CASE ) - 1) ) __SCREAMING_SNAKE_CASE = ["""stem"""] + [f'stage{idx}' for idx in range(1 , len(__SCREAMING_SNAKE_CASE ) + 1 )] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = get_aligned_output_features_output_indices( out_features=__SCREAMING_SNAKE_CASE , out_indices=__SCREAMING_SNAKE_CASE , stage_names=self.stage_names )
267
1
'''simple docstring''' import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase : Optional[Any] = logging.get_logger(__name__) UpperCAmelCase : Optional[Any] = { 'microsoft/wavlm-base': 'https://huggingface.co/microsoft/wavlm-base/resolve/main/config.json', # See all WavLM models at https://huggingface.co/models?filter=wavlm } class lowerCAmelCase__ ( a ): """simple docstring""" lowerCAmelCase__ = "wavlm" def __init__( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[int]=32 , __SCREAMING_SNAKE_CASE : Optional[int]=768 , __SCREAMING_SNAKE_CASE : Tuple=12 , __SCREAMING_SNAKE_CASE : Any=12 , __SCREAMING_SNAKE_CASE : Union[str, Any]=3_072 , __SCREAMING_SNAKE_CASE : Optional[int]="gelu" , __SCREAMING_SNAKE_CASE : Union[str, Any]=0.1 , __SCREAMING_SNAKE_CASE : Tuple=0.1 , __SCREAMING_SNAKE_CASE : int=0.1 , __SCREAMING_SNAKE_CASE : List[Any]=0.0 , __SCREAMING_SNAKE_CASE : str=0.1 , __SCREAMING_SNAKE_CASE : Optional[int]=0.1 , __SCREAMING_SNAKE_CASE : Optional[Any]=0.02 , __SCREAMING_SNAKE_CASE : Dict=1E-5 , __SCREAMING_SNAKE_CASE : Optional[Any]="group" , __SCREAMING_SNAKE_CASE : str="gelu" , __SCREAMING_SNAKE_CASE : Any=(512, 512, 512, 512, 512, 512, 512) , __SCREAMING_SNAKE_CASE : int=(5, 2, 2, 2, 2, 2, 2) , __SCREAMING_SNAKE_CASE : str=(10, 3, 3, 3, 3, 2, 2) , __SCREAMING_SNAKE_CASE : List[str]=False , __SCREAMING_SNAKE_CASE : Any=128 , __SCREAMING_SNAKE_CASE : Union[str, Any]=16 , __SCREAMING_SNAKE_CASE : Tuple=320 , __SCREAMING_SNAKE_CASE : Union[str, Any]=800 , __SCREAMING_SNAKE_CASE : Dict=False , __SCREAMING_SNAKE_CASE : List[str]=True , __SCREAMING_SNAKE_CASE : Optional[int]=0.05 , __SCREAMING_SNAKE_CASE : str=10 , __SCREAMING_SNAKE_CASE : Union[str, Any]=2 , __SCREAMING_SNAKE_CASE : int=0.0 , __SCREAMING_SNAKE_CASE : Any=10 , __SCREAMING_SNAKE_CASE : Optional[int]=320 , __SCREAMING_SNAKE_CASE : List[Any]=2 , __SCREAMING_SNAKE_CASE : List[str]=0.1 , __SCREAMING_SNAKE_CASE : Any=100 , __SCREAMING_SNAKE_CASE : List[Any]=256 , __SCREAMING_SNAKE_CASE : List[str]=256 , __SCREAMING_SNAKE_CASE : Optional[Any]=0.1 , __SCREAMING_SNAKE_CASE : Any="mean" , __SCREAMING_SNAKE_CASE : Any=False , __SCREAMING_SNAKE_CASE : Optional[int]=False , __SCREAMING_SNAKE_CASE : Union[str, Any]=256 , __SCREAMING_SNAKE_CASE : List[Any]=(512, 512, 512, 512, 1_500) , __SCREAMING_SNAKE_CASE : Any=(5, 3, 3, 1, 1) , __SCREAMING_SNAKE_CASE : int=(1, 2, 3, 1, 1) , __SCREAMING_SNAKE_CASE : int=512 , __SCREAMING_SNAKE_CASE : int=80 , __SCREAMING_SNAKE_CASE : Optional[int]=0 , __SCREAMING_SNAKE_CASE : List[str]=1 , __SCREAMING_SNAKE_CASE : Any=2 , __SCREAMING_SNAKE_CASE : Optional[int]=False , __SCREAMING_SNAKE_CASE : List[Any]=3 , __SCREAMING_SNAKE_CASE : List[str]=2 , __SCREAMING_SNAKE_CASE : Any=3 , __SCREAMING_SNAKE_CASE : List[Any]=None , **__SCREAMING_SNAKE_CASE : Optional[Any] , ) -> Optional[Any]: """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 ) __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = feat_extract_norm __SCREAMING_SNAKE_CASE = feat_extract_activation __SCREAMING_SNAKE_CASE = list(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = list(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = list(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = conv_bias __SCREAMING_SNAKE_CASE = num_buckets __SCREAMING_SNAKE_CASE = max_bucket_distance __SCREAMING_SNAKE_CASE = num_conv_pos_embeddings __SCREAMING_SNAKE_CASE = num_conv_pos_embedding_groups __SCREAMING_SNAKE_CASE = len(self.conv_dim ) __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = hidden_dropout __SCREAMING_SNAKE_CASE = attention_dropout __SCREAMING_SNAKE_CASE = activation_dropout __SCREAMING_SNAKE_CASE = feat_proj_dropout __SCREAMING_SNAKE_CASE = final_dropout __SCREAMING_SNAKE_CASE = layerdrop __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = num_ctc_classes __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = do_stable_layer_norm __SCREAMING_SNAKE_CASE = use_weighted_layer_sum __SCREAMING_SNAKE_CASE = classifier_proj_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)`, but is `len(config.conv_dim) =""" f' {len(self.conv_dim )}`, `len(config.conv_stride) = {len(self.conv_stride )}`,' f' `len(config.conv_kernel) = {len(self.conv_kernel )}`.' ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 __SCREAMING_SNAKE_CASE = apply_spec_augment __SCREAMING_SNAKE_CASE = mask_time_prob __SCREAMING_SNAKE_CASE = mask_time_length __SCREAMING_SNAKE_CASE = mask_time_min_masks __SCREAMING_SNAKE_CASE = mask_feature_prob __SCREAMING_SNAKE_CASE = mask_feature_length # parameters for pretraining with codevector quantized representations __SCREAMING_SNAKE_CASE = num_codevectors_per_group __SCREAMING_SNAKE_CASE = num_codevector_groups __SCREAMING_SNAKE_CASE = contrastive_logits_temperature __SCREAMING_SNAKE_CASE = num_negatives __SCREAMING_SNAKE_CASE = codevector_dim __SCREAMING_SNAKE_CASE = proj_codevector_dim __SCREAMING_SNAKE_CASE = diversity_loss_weight # ctc loss __SCREAMING_SNAKE_CASE = ctc_loss_reduction __SCREAMING_SNAKE_CASE = ctc_zero_infinity # adapter __SCREAMING_SNAKE_CASE = add_adapter __SCREAMING_SNAKE_CASE = adapter_kernel_size __SCREAMING_SNAKE_CASE = adapter_stride __SCREAMING_SNAKE_CASE = num_adapter_layers __SCREAMING_SNAKE_CASE = output_hidden_size or hidden_size # SequenceClassification-specific parameter. Feel free to ignore for other classes. __SCREAMING_SNAKE_CASE = classifier_proj_size # XVector-specific parameters. Feel free to ignore for other classes. __SCREAMING_SNAKE_CASE = list(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = list(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = list(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = xvector_output_dim @property def UpperCAmelCase__ ( self : Tuple ) -> List[Any]: """simple docstring""" return functools.reduce(operator.mul , self.conv_stride , 1 )
267
'''simple docstring''' class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : int ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = n __SCREAMING_SNAKE_CASE = [None] * self.n __SCREAMING_SNAKE_CASE = 0 # index of the first element __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 def __len__( self : Tuple ) -> int: """simple docstring""" return self.size def UpperCAmelCase__ ( self : Optional[Any] ) -> bool: """simple docstring""" return self.size == 0 def UpperCAmelCase__ ( self : Any ) -> int: """simple docstring""" return False if self.is_empty() else self.array[self.front] def UpperCAmelCase__ ( self : Dict , __SCREAMING_SNAKE_CASE : Union[str, Any] ) -> Dict: """simple docstring""" if self.size >= self.n: raise Exception("""QUEUE IS FULL""" ) __SCREAMING_SNAKE_CASE = data __SCREAMING_SNAKE_CASE = (self.rear + 1) % self.n self.size += 1 return self def UpperCAmelCase__ ( self : List[str] ) -> Optional[Any]: """simple docstring""" if self.size == 0: raise Exception("""UNDERFLOW""" ) __SCREAMING_SNAKE_CASE = self.array[self.front] __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = (self.front + 1) % self.n self.size -= 1 return temp
267
1
'''simple docstring''' # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from ...utils import deprecate from ..controlnet.pipeline_flax_controlnet import FlaxStableDiffusionControlNetPipeline # noqa: F401 deprecate( 'stable diffusion controlnet', '0.22.0', 'Importing `FlaxStableDiffusionControlNetPipeline` from diffusers.pipelines.stable_diffusion.flax_pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import FlaxStableDiffusionControlNetPipeline` instead.', standard_warn=False, stacklevel=3, )
267
'''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] ) -> Optional[int]: """simple docstring""" torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = 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 : List[Any] ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.dummy_uncond_unet __SCREAMING_SNAKE_CASE = PNDMScheduler() __SCREAMING_SNAKE_CASE = PNDMPipeline(unet=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE ) pndm.to(__SCREAMING_SNAKE_CASE ) pndm.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pndm(generator=__SCREAMING_SNAKE_CASE , num_inference_steps=20 , output_type="""numpy""" ).images __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pndm(generator=__SCREAMING_SNAKE_CASE , num_inference_steps=20 , output_type="""numpy""" , return_dict=__SCREAMING_SNAKE_CASE )[0] __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] __SCREAMING_SNAKE_CASE = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __SCREAMING_SNAKE_CASE = 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 : Optional[int] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = """google/ddpm-cifar10-32""" __SCREAMING_SNAKE_CASE = UNetaDModel.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = PNDMScheduler() __SCREAMING_SNAKE_CASE = PNDMPipeline(unet=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE ) pndm.to(__SCREAMING_SNAKE_CASE ) pndm.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pndm(generator=__SCREAMING_SNAKE_CASE , output_type="""numpy""" ).images __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __SCREAMING_SNAKE_CASE = np.array([0.1564, 0.14645, 0.1406, 0.14715, 0.12425, 0.14045, 0.13115, 0.12175, 0.125] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
267
1
'''simple docstring''' from __future__ import annotations def a__ ( a__ , a__ , a__ ): """simple docstring""" if len(a__ ) == 0: raise ValueError("""find_max() arg is an empty sequence""" ) if ( left >= len(a__ ) or left < -len(a__ ) or right >= len(a__ ) or right < -len(a__ ) ): raise IndexError("""list index out of range""" ) if left == right: return nums[left] __SCREAMING_SNAKE_CASE = (left + right) >> 1 # the middle __SCREAMING_SNAKE_CASE = find_max(a__ , a__ , a__ ) # find max in range[left, mid] __SCREAMING_SNAKE_CASE = find_max(a__ , mid + 1 , a__ ) # find max in range[mid + 1, right] return left_max if left_max >= right_max else right_max if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
267
'''simple docstring''' import unittest from transformers import ( MODEL_FOR_OBJECT_DETECTION_MAPPING, AutoFeatureExtractor, AutoModelForObjectDetection, ObjectDetectionPipeline, is_vision_available, pipeline, ) from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_pytesseract, require_tf, require_timm, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class lowerCAmelCase__ : """simple docstring""" @staticmethod def UpperCAmelCase__ ( *__SCREAMING_SNAKE_CASE : Tuple , **__SCREAMING_SNAKE_CASE : Union[str, Any] ) -> List[str]: """simple docstring""" pass @is_pipeline_test @require_vision @require_timm @require_torch class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = MODEL_FOR_OBJECT_DETECTION_MAPPING def UpperCAmelCase__ ( self : List[Any] , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Tuple ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = ObjectDetectionPipeline(model=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) return object_detector, ["./tests/fixtures/tests_samples/COCO/000000039769.png"] def UpperCAmelCase__ ( self : Optional[int] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : List[Any] ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = object_detector("""./tests/fixtures/tests_samples/COCO/000000039769.png""" , threshold=0.0 ) self.assertGreater(len(__SCREAMING_SNAKE_CASE ) , 0 ) for detected_object in outputs: self.assertEqual( __SCREAMING_SNAKE_CASE , { """score""": ANY(__SCREAMING_SNAKE_CASE ), """label""": ANY(__SCREAMING_SNAKE_CASE ), """box""": {"""xmin""": ANY(__SCREAMING_SNAKE_CASE ), """ymin""": ANY(__SCREAMING_SNAKE_CASE ), """xmax""": ANY(__SCREAMING_SNAKE_CASE ), """ymax""": ANY(__SCREAMING_SNAKE_CASE )}, } , ) import datasets __SCREAMING_SNAKE_CASE = datasets.load_dataset("""hf-internal-testing/fixtures_image_utils""" , """image""" , split="""test""" ) __SCREAMING_SNAKE_CASE = [ Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ), """http://images.cocodataset.org/val2017/000000039769.jpg""", # RGBA dataset[0]["""file"""], # LA dataset[1]["""file"""], # L dataset[2]["""file"""], ] __SCREAMING_SNAKE_CASE = object_detector(__SCREAMING_SNAKE_CASE , threshold=0.0 ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , len(__SCREAMING_SNAKE_CASE ) ) for outputs in batch_outputs: self.assertGreater(len(__SCREAMING_SNAKE_CASE ) , 0 ) for detected_object in outputs: self.assertEqual( __SCREAMING_SNAKE_CASE , { """score""": ANY(__SCREAMING_SNAKE_CASE ), """label""": ANY(__SCREAMING_SNAKE_CASE ), """box""": {"""xmin""": ANY(__SCREAMING_SNAKE_CASE ), """ymin""": ANY(__SCREAMING_SNAKE_CASE ), """xmax""": ANY(__SCREAMING_SNAKE_CASE ), """ymax""": ANY(__SCREAMING_SNAKE_CASE )}, } , ) @require_tf @unittest.skip("""Object detection not implemented in TF""" ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> str: """simple docstring""" pass @require_torch def UpperCAmelCase__ ( self : str ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = """hf-internal-testing/tiny-detr-mobilenetsv3""" __SCREAMING_SNAKE_CASE = AutoModelForObjectDetection.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = AutoFeatureExtractor.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = ObjectDetectionPipeline(model=__SCREAMING_SNAKE_CASE , feature_extractor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" , threshold=0.0 ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ] , ) __SCREAMING_SNAKE_CASE = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] , threshold=0.0 , ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ], [ {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ], ] , ) @require_torch @slow def UpperCAmelCase__ ( self : Optional[int] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = """facebook/detr-resnet-50""" __SCREAMING_SNAKE_CASE = AutoModelForObjectDetection.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = AutoFeatureExtractor.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = ObjectDetectionPipeline(model=__SCREAMING_SNAKE_CASE , feature_extractor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) __SCREAMING_SNAKE_CASE = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], ] , ) @require_torch @slow def UpperCAmelCase__ ( self : List[Any] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = """facebook/detr-resnet-50""" __SCREAMING_SNAKE_CASE = pipeline("""object-detection""" , model=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) __SCREAMING_SNAKE_CASE = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], ] , ) @require_torch @slow def UpperCAmelCase__ ( self : Dict ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = 0.9985 __SCREAMING_SNAKE_CASE = """facebook/detr-resnet-50""" __SCREAMING_SNAKE_CASE = pipeline("""object-detection""" , model=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" , threshold=__SCREAMING_SNAKE_CASE ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) @require_torch @require_pytesseract @slow def UpperCAmelCase__ ( self : int ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = """Narsil/layoutlmv3-finetuned-funsd""" __SCREAMING_SNAKE_CASE = 0.9993 __SCREAMING_SNAKE_CASE = pipeline("""object-detection""" , model=__SCREAMING_SNAKE_CASE , threshold=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector( """https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9993, """label""": """I-ANSWER""", """box""": {"""xmin""": 294, """ymin""": 254, """xmax""": 343, """ymax""": 264}}, {"""score""": 0.9993, """label""": """I-ANSWER""", """box""": {"""xmin""": 294, """ymin""": 254, """xmax""": 343, """ymax""": 264}}, ] , )
267
1
'''simple docstring''' import json import os import re import unicodedata from json.encoder import INFINITY from typing import Any, Dict, List, Optional, Tuple, Union import numpy as np import regex from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, is_flax_available, is_tf_available, is_torch_available, logging from ...utils.generic import _is_jax, _is_numpy UpperCAmelCase : int = logging.get_logger(__name__) UpperCAmelCase : List[str] = { 'artists_file': 'artists.json', 'lyrics_file': 'lyrics.json', 'genres_file': 'genres.json', } UpperCAmelCase : int = { 'artists_file': { 'jukebox': 'https://huggingface.co/ArthurZ/jukebox/blob/main/artists.json', }, 'genres_file': { 'jukebox': 'https://huggingface.co/ArthurZ/jukebox/blob/main/genres.json', }, 'lyrics_file': { 'jukebox': 'https://huggingface.co/ArthurZ/jukebox/blob/main/lyrics.json', }, } UpperCAmelCase : Dict = { 'jukebox': 5_1_2, } class lowerCAmelCase__ ( a ): """simple docstring""" lowerCAmelCase__ = VOCAB_FILES_NAMES lowerCAmelCase__ = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase__ = PRETRAINED_LYRIC_TOKENS_SIZES lowerCAmelCase__ = ["input_ids", "attention_mask"] def __init__( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : List[str]=["v3", "v2", "v2"] , __SCREAMING_SNAKE_CASE : Optional[Any]=512 , __SCREAMING_SNAKE_CASE : Optional[int]=5 , __SCREAMING_SNAKE_CASE : Optional[Any]="<|endoftext|>" , **__SCREAMING_SNAKE_CASE : str , ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = AddedToken(__SCREAMING_SNAKE_CASE , lstrip=__SCREAMING_SNAKE_CASE , rstrip=__SCREAMING_SNAKE_CASE ) if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else unk_token super().__init__( unk_token=__SCREAMING_SNAKE_CASE , n_genres=__SCREAMING_SNAKE_CASE , version=__SCREAMING_SNAKE_CASE , max_n_lyric_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) __SCREAMING_SNAKE_CASE = version __SCREAMING_SNAKE_CASE = max_n_lyric_tokens __SCREAMING_SNAKE_CASE = n_genres with open(__SCREAMING_SNAKE_CASE , encoding="""utf-8""" ) as vocab_handle: __SCREAMING_SNAKE_CASE = json.load(__SCREAMING_SNAKE_CASE ) with open(__SCREAMING_SNAKE_CASE , encoding="""utf-8""" ) as vocab_handle: __SCREAMING_SNAKE_CASE = json.load(__SCREAMING_SNAKE_CASE ) with open(__SCREAMING_SNAKE_CASE , encoding="""utf-8""" ) as vocab_handle: __SCREAMING_SNAKE_CASE = json.load(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = r"""[^A-Za-z0-9.,:;!?\-'\"()\[\] \t\n]+""" # In v2, we had a n_vocab=80 and in v3 we missed + and so n_vocab=79 of characters. if len(self.lyrics_encoder ) == 79: __SCREAMING_SNAKE_CASE = oov.replace(r"""\-'""" , r"""\-+'""" ) __SCREAMING_SNAKE_CASE = regex.compile(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = {v: k for k, v in self.artists_encoder.items()} __SCREAMING_SNAKE_CASE = {v: k for k, v in self.genres_encoder.items()} __SCREAMING_SNAKE_CASE = {v: k for k, v in self.lyrics_encoder.items()} @property def UpperCAmelCase__ ( self : Optional[int] ) -> Dict: """simple docstring""" return len(self.artists_encoder ) + len(self.genres_encoder ) + len(self.lyrics_encoder ) def UpperCAmelCase__ ( self : Dict ) -> Any: """simple docstring""" return dict(self.artists_encoder , self.genres_encoder , self.lyrics_encoder ) def UpperCAmelCase__ ( self : Optional[int] , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Any ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = [self.artists_encoder.get(__SCREAMING_SNAKE_CASE , 0 ) for artist in list_artists] for genres in range(len(__SCREAMING_SNAKE_CASE ) ): __SCREAMING_SNAKE_CASE = [self.genres_encoder.get(__SCREAMING_SNAKE_CASE , 0 ) for genre in list_genres[genres]] __SCREAMING_SNAKE_CASE = list_genres[genres] + [-1] * (self.n_genres - len(list_genres[genres] )) __SCREAMING_SNAKE_CASE = [[self.lyrics_encoder.get(__SCREAMING_SNAKE_CASE , 0 ) for character in list_lyrics[0]], [], []] return artists_id, list_genres, lyric_ids def UpperCAmelCase__ ( self : int , __SCREAMING_SNAKE_CASE : int ) -> Tuple: """simple docstring""" return list(__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[Any] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : List[Any] , **__SCREAMING_SNAKE_CASE : Optional[Any] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.prepare_for_tokenization(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self._tokenize(__SCREAMING_SNAKE_CASE ) return artist, genre, lyrics def UpperCAmelCase__ ( self : Any , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : bool = False ) -> Tuple[str, str, str, Dict[str, Any]]: """simple docstring""" for idx in range(len(self.version ) ): if self.version[idx] == "v3": __SCREAMING_SNAKE_CASE = artists[idx].lower() __SCREAMING_SNAKE_CASE = [genres[idx].lower()] else: __SCREAMING_SNAKE_CASE = self._normalize(artists[idx] ) + """.v2""" __SCREAMING_SNAKE_CASE = [ self._normalize(__SCREAMING_SNAKE_CASE ) + """.v2""" for genre in genres[idx].split("""_""" ) ] # split is for the full dictionary with combined genres if self.version[0] == "v2": __SCREAMING_SNAKE_CASE = regex.compile(r"""[^A-Za-z0-9.,:;!?\-'\"()\[\] \t\n]+""" ) __SCREAMING_SNAKE_CASE = """ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,:;!?-+'\"()[] \t\n""" __SCREAMING_SNAKE_CASE = {vocab[index]: index + 1 for index in range(len(__SCREAMING_SNAKE_CASE ) )} __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = len(__SCREAMING_SNAKE_CASE ) + 1 __SCREAMING_SNAKE_CASE = self.vocab __SCREAMING_SNAKE_CASE = {v: k for k, v in self.vocab.items()} __SCREAMING_SNAKE_CASE = """""" else: __SCREAMING_SNAKE_CASE = regex.compile(r"""[^A-Za-z0-9.,:;!?\-+'\"()\[\] \t\n]+""" ) __SCREAMING_SNAKE_CASE = self._run_strip_accents(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = lyrics.replace("""\\""" , """\n""" ) __SCREAMING_SNAKE_CASE = self.out_of_vocab.sub("""""" , __SCREAMING_SNAKE_CASE ), [], [] return artists, genres, lyrics def UpperCAmelCase__ ( self : List[Any] , __SCREAMING_SNAKE_CASE : List[str] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = unicodedata.normalize("""NFD""" , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = [] for char in text: __SCREAMING_SNAKE_CASE = unicodedata.category(__SCREAMING_SNAKE_CASE ) if cat == "Mn": continue output.append(__SCREAMING_SNAKE_CASE ) return "".join(__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[Any] , __SCREAMING_SNAKE_CASE : str ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = ( [chr(__SCREAMING_SNAKE_CASE ) for i in range(ord("""a""" ) , ord("""z""" ) + 1 )] + [chr(__SCREAMING_SNAKE_CASE ) for i in range(ord("""A""" ) , ord("""Z""" ) + 1 )] + [chr(__SCREAMING_SNAKE_CASE ) for i in range(ord("""0""" ) , ord("""9""" ) + 1 )] + ["""."""] ) __SCREAMING_SNAKE_CASE = frozenset(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = re.compile(r"""_+""" ) __SCREAMING_SNAKE_CASE = """""".join([c if c in accepted else """_""" for c in text.lower()] ) __SCREAMING_SNAKE_CASE = pattern.sub("""_""" , __SCREAMING_SNAKE_CASE ).strip("""_""" ) return text def UpperCAmelCase__ ( self : Any , __SCREAMING_SNAKE_CASE : List[str] ) -> str: """simple docstring""" return " ".join(__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : str , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : Optional[Union[str, TensorType]] = None , __SCREAMING_SNAKE_CASE : bool = False ) -> Tuple: """simple docstring""" if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): __SCREAMING_SNAKE_CASE = TensorType(__SCREAMING_SNAKE_CASE ) # Get a function reference for the correct framework if tensor_type == TensorType.TENSORFLOW: if not is_tf_available(): raise ImportError( """Unable to convert output to TensorFlow tensors format, TensorFlow is not installed.""" ) import tensorflow as tf __SCREAMING_SNAKE_CASE = tf.constant __SCREAMING_SNAKE_CASE = tf.is_tensor elif tensor_type == TensorType.PYTORCH: if not is_torch_available(): raise ImportError("""Unable to convert output to PyTorch tensors format, PyTorch is not installed.""" ) import torch __SCREAMING_SNAKE_CASE = torch.tensor __SCREAMING_SNAKE_CASE = torch.is_tensor elif tensor_type == TensorType.JAX: if not is_flax_available(): raise ImportError("""Unable to convert output to JAX tensors format, JAX is not installed.""" ) import jax.numpy as jnp # noqa: F811 __SCREAMING_SNAKE_CASE = jnp.array __SCREAMING_SNAKE_CASE = _is_jax else: __SCREAMING_SNAKE_CASE = np.asarray __SCREAMING_SNAKE_CASE = _is_numpy # Do the tensor conversion in batch try: if prepend_batch_axis: __SCREAMING_SNAKE_CASE = [inputs] if not is_tensor(__SCREAMING_SNAKE_CASE ): __SCREAMING_SNAKE_CASE = as_tensor(__SCREAMING_SNAKE_CASE ) except: # noqa E722 raise ValueError( """Unable to create tensor, you should probably activate truncation and/or padding """ """with 'padding=True' 'truncation=True' to have batched tensors with the same length.""" ) return inputs def __call__( self : Any , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : int="" , __SCREAMING_SNAKE_CASE : List[Any]="pt" ) -> BatchEncoding: """simple docstring""" __SCREAMING_SNAKE_CASE = [0, 0, 0] __SCREAMING_SNAKE_CASE = [artist] * len(self.version ) __SCREAMING_SNAKE_CASE = [genres] * len(self.version ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.tokenize(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self._convert_token_to_id(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = [-INFINITY] * len(full_tokens[-1] ) __SCREAMING_SNAKE_CASE = [ self.convert_to_tensors( [input_ids + [artists_id[i]] + genres_ids[i] + full_tokens[i]] , tensor_type=__SCREAMING_SNAKE_CASE ) for i in range(len(self.version ) ) ] return BatchEncoding({"""input_ids""": input_ids, """attention_masks""": attention_masks} ) def UpperCAmelCase__ ( self : List[str] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Optional[str] = None ) -> Tuple[str]: """simple docstring""" if not os.path.isdir(__SCREAMING_SNAKE_CASE ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return __SCREAMING_SNAKE_CASE = os.path.join( __SCREAMING_SNAKE_CASE , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""artists_file"""] ) with open(__SCREAMING_SNAKE_CASE , """w""" , encoding="""utf-8""" ) as f: f.write(json.dumps(self.artists_encoder , ensure_ascii=__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = os.path.join( __SCREAMING_SNAKE_CASE , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""genres_file"""] ) with open(__SCREAMING_SNAKE_CASE , """w""" , encoding="""utf-8""" ) as f: f.write(json.dumps(self.genres_encoder , ensure_ascii=__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = os.path.join( __SCREAMING_SNAKE_CASE , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""lyrics_file"""] ) with open(__SCREAMING_SNAKE_CASE , """w""" , encoding="""utf-8""" ) as f: f.write(json.dumps(self.lyrics_encoder , ensure_ascii=__SCREAMING_SNAKE_CASE ) ) return (artists_file, genres_file, lyrics_file) def UpperCAmelCase__ ( self : List[str] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : int ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.artists_decoder.get(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = [self.genres_decoder.get(__SCREAMING_SNAKE_CASE ) for genre in genres_index] __SCREAMING_SNAKE_CASE = [self.lyrics_decoder.get(__SCREAMING_SNAKE_CASE ) for character in lyric_index] return artist, genres, lyrics
267
'''simple docstring''' import unittest from diffusers import FlaxAutoencoderKL from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax from .test_modeling_common_flax import FlaxModelTesterMixin if is_flax_available(): import jax @require_flax class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = FlaxAutoencoderKL @property def UpperCAmelCase__ ( self : Tuple ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = 4 __SCREAMING_SNAKE_CASE = 3 __SCREAMING_SNAKE_CASE = (32, 32) __SCREAMING_SNAKE_CASE = jax.random.PRNGKey(0 ) __SCREAMING_SNAKE_CASE = jax.random.uniform(__SCREAMING_SNAKE_CASE , ((batch_size, num_channels) + sizes) ) return {"sample": image, "prng_key": prng_key} def UpperCAmelCase__ ( self : Union[str, Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = { """block_out_channels""": [32, 64], """in_channels""": 3, """out_channels""": 3, """down_block_types""": ["""DownEncoderBlock2D""", """DownEncoderBlock2D"""], """up_block_types""": ["""UpDecoderBlock2D""", """UpDecoderBlock2D"""], """latent_channels""": 4, } __SCREAMING_SNAKE_CASE = self.dummy_input return init_dict, inputs_dict
267
1
'''simple docstring''' import unittest from transformers import ( MODEL_FOR_OBJECT_DETECTION_MAPPING, AutoFeatureExtractor, AutoModelForObjectDetection, ObjectDetectionPipeline, is_vision_available, pipeline, ) from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_pytesseract, require_tf, require_timm, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class lowerCAmelCase__ : """simple docstring""" @staticmethod def UpperCAmelCase__ ( *__SCREAMING_SNAKE_CASE : Tuple , **__SCREAMING_SNAKE_CASE : Union[str, Any] ) -> List[str]: """simple docstring""" pass @is_pipeline_test @require_vision @require_timm @require_torch class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = MODEL_FOR_OBJECT_DETECTION_MAPPING def UpperCAmelCase__ ( self : List[Any] , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Tuple ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = ObjectDetectionPipeline(model=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) return object_detector, ["./tests/fixtures/tests_samples/COCO/000000039769.png"] def UpperCAmelCase__ ( self : Optional[int] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : List[Any] ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = object_detector("""./tests/fixtures/tests_samples/COCO/000000039769.png""" , threshold=0.0 ) self.assertGreater(len(__SCREAMING_SNAKE_CASE ) , 0 ) for detected_object in outputs: self.assertEqual( __SCREAMING_SNAKE_CASE , { """score""": ANY(__SCREAMING_SNAKE_CASE ), """label""": ANY(__SCREAMING_SNAKE_CASE ), """box""": {"""xmin""": ANY(__SCREAMING_SNAKE_CASE ), """ymin""": ANY(__SCREAMING_SNAKE_CASE ), """xmax""": ANY(__SCREAMING_SNAKE_CASE ), """ymax""": ANY(__SCREAMING_SNAKE_CASE )}, } , ) import datasets __SCREAMING_SNAKE_CASE = datasets.load_dataset("""hf-internal-testing/fixtures_image_utils""" , """image""" , split="""test""" ) __SCREAMING_SNAKE_CASE = [ Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ), """http://images.cocodataset.org/val2017/000000039769.jpg""", # RGBA dataset[0]["""file"""], # LA dataset[1]["""file"""], # L dataset[2]["""file"""], ] __SCREAMING_SNAKE_CASE = object_detector(__SCREAMING_SNAKE_CASE , threshold=0.0 ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , len(__SCREAMING_SNAKE_CASE ) ) for outputs in batch_outputs: self.assertGreater(len(__SCREAMING_SNAKE_CASE ) , 0 ) for detected_object in outputs: self.assertEqual( __SCREAMING_SNAKE_CASE , { """score""": ANY(__SCREAMING_SNAKE_CASE ), """label""": ANY(__SCREAMING_SNAKE_CASE ), """box""": {"""xmin""": ANY(__SCREAMING_SNAKE_CASE ), """ymin""": ANY(__SCREAMING_SNAKE_CASE ), """xmax""": ANY(__SCREAMING_SNAKE_CASE ), """ymax""": ANY(__SCREAMING_SNAKE_CASE )}, } , ) @require_tf @unittest.skip("""Object detection not implemented in TF""" ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> str: """simple docstring""" pass @require_torch def UpperCAmelCase__ ( self : str ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = """hf-internal-testing/tiny-detr-mobilenetsv3""" __SCREAMING_SNAKE_CASE = AutoModelForObjectDetection.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = AutoFeatureExtractor.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = ObjectDetectionPipeline(model=__SCREAMING_SNAKE_CASE , feature_extractor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" , threshold=0.0 ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ] , ) __SCREAMING_SNAKE_CASE = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] , threshold=0.0 , ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ], [ {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ], ] , ) @require_torch @slow def UpperCAmelCase__ ( self : Optional[int] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = """facebook/detr-resnet-50""" __SCREAMING_SNAKE_CASE = AutoModelForObjectDetection.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = AutoFeatureExtractor.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = ObjectDetectionPipeline(model=__SCREAMING_SNAKE_CASE , feature_extractor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) __SCREAMING_SNAKE_CASE = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], ] , ) @require_torch @slow def UpperCAmelCase__ ( self : List[Any] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = """facebook/detr-resnet-50""" __SCREAMING_SNAKE_CASE = pipeline("""object-detection""" , model=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) __SCREAMING_SNAKE_CASE = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], ] , ) @require_torch @slow def UpperCAmelCase__ ( self : Dict ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = 0.9985 __SCREAMING_SNAKE_CASE = """facebook/detr-resnet-50""" __SCREAMING_SNAKE_CASE = pipeline("""object-detection""" , model=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" , threshold=__SCREAMING_SNAKE_CASE ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) @require_torch @require_pytesseract @slow def UpperCAmelCase__ ( self : int ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = """Narsil/layoutlmv3-finetuned-funsd""" __SCREAMING_SNAKE_CASE = 0.9993 __SCREAMING_SNAKE_CASE = pipeline("""object-detection""" , model=__SCREAMING_SNAKE_CASE , threshold=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector( """https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9993, """label""": """I-ANSWER""", """box""": {"""xmin""": 294, """ymin""": 254, """xmax""": 343, """ymax""": 264}}, {"""score""": 0.9993, """label""": """I-ANSWER""", """box""": {"""xmin""": 294, """ymin""": 254, """xmax""": 343, """ymax""": 264}}, ] , )
267
'''simple docstring''' import itertools import os import random import tempfile import unittest import numpy as np from datasets import load_dataset from transformers import is_speech_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_speech_available(): from transformers import WhisperFeatureExtractor if is_torch_available(): import torch UpperCAmelCase : int = random.Random() def a__ ( a__ , a__=1.0 , a__=None , a__=None ): """simple docstring""" if rng is None: __SCREAMING_SNAKE_CASE = global_rng __SCREAMING_SNAKE_CASE = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch @require_torchaudio class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __init__( self : str , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : str=7 , __SCREAMING_SNAKE_CASE : List[str]=400 , __SCREAMING_SNAKE_CASE : Any=2_000 , __SCREAMING_SNAKE_CASE : List[str]=10 , __SCREAMING_SNAKE_CASE : Optional[int]=160 , __SCREAMING_SNAKE_CASE : List[str]=8 , __SCREAMING_SNAKE_CASE : Optional[Any]=0.0 , __SCREAMING_SNAKE_CASE : Dict=4_000 , __SCREAMING_SNAKE_CASE : Optional[int]=False , __SCREAMING_SNAKE_CASE : List[Any]=True , ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = min_seq_length __SCREAMING_SNAKE_CASE = max_seq_length __SCREAMING_SNAKE_CASE = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) __SCREAMING_SNAKE_CASE = padding_value __SCREAMING_SNAKE_CASE = sampling_rate __SCREAMING_SNAKE_CASE = return_attention_mask __SCREAMING_SNAKE_CASE = do_normalize __SCREAMING_SNAKE_CASE = feature_size __SCREAMING_SNAKE_CASE = chunk_length __SCREAMING_SNAKE_CASE = hop_length def UpperCAmelCase__ ( self : Dict ) -> Dict: """simple docstring""" return { "feature_size": self.feature_size, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def UpperCAmelCase__ ( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : Union[str, Any]=False , __SCREAMING_SNAKE_CASE : Optional[Any]=False ) -> Union[str, Any]: """simple docstring""" def _flatten(__SCREAMING_SNAKE_CASE : Dict ): return list(itertools.chain(*__SCREAMING_SNAKE_CASE ) ) if equal_length: __SCREAMING_SNAKE_CASE = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size __SCREAMING_SNAKE_CASE = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = WhisperFeatureExtractor if is_speech_available() else None def UpperCAmelCase__ ( self : str ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = WhisperFeatureExtractionTester(self ) def UpperCAmelCase__ ( self : str ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE = feat_extract_first.save_pretrained(__SCREAMING_SNAKE_CASE )[0] check_json_file_has_correct_format(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.feature_extraction_class.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = feat_extract_first.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_second.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_first.mel_filters __SCREAMING_SNAKE_CASE = feat_extract_second.mel_filters self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[str] ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE = os.path.join(__SCREAMING_SNAKE_CASE , """feat_extract.json""" ) feat_extract_first.to_json_file(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.feature_extraction_class.from_json_file(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = feat_extract_first.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_second.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_first.mel_filters __SCREAMING_SNAKE_CASE = feat_extract_second.mel_filters self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[Any] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in range(800 , 1_400 , 200 )] __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs] # Test feature size __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , padding="""max_length""" , return_tensors="""np""" ).input_features self.assertTrue(input_features.ndim == 3 ) self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames ) self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size ) # Test not batched input __SCREAMING_SNAKE_CASE = feature_extractor(speech_inputs[0] , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(np_speech_inputs[0] , return_tensors="""np""" ).input_features self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test batched __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test 2-D numpy arrays are batched. __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in (800, 800, 800)] __SCREAMING_SNAKE_CASE = np.asarray(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test truncation required __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in range(200 , (feature_extractor.n_samples + 500) , 200 )] __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs] __SCREAMING_SNAKE_CASE = [x[: feature_extractor.n_samples] for x in speech_inputs] __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs_truncated] __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) def UpperCAmelCase__ ( self : Dict ) -> Optional[int]: """simple docstring""" import torch __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __SCREAMING_SNAKE_CASE = np.random.rand(100 , 32 ).astype(np.floataa ) __SCREAMING_SNAKE_CASE = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: __SCREAMING_SNAKE_CASE = feature_extractor.pad([{"""input_features""": inputs}] , return_tensors="""np""" ) self.assertTrue(np_processed.input_features.dtype == np.floataa ) __SCREAMING_SNAKE_CASE = feature_extractor.pad([{"""input_features""": inputs}] , return_tensors="""pt""" ) self.assertTrue(pt_processed.input_features.dtype == torch.floataa ) def UpperCAmelCase__ ( self : str , __SCREAMING_SNAKE_CASE : Tuple ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = load_dataset("""hf-internal-testing/librispeech_asr_dummy""" , """clean""" , split="""validation""" ) # automatic decoding with librispeech __SCREAMING_SNAKE_CASE = ds.sort("""id""" ).select(range(__SCREAMING_SNAKE_CASE ) )[:num_samples]["""audio"""] return [x["array"] for x in speech_samples] def UpperCAmelCase__ ( self : Tuple ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = torch.tensor( [ 0.1193, -0.0946, -0.1098, -0.0196, 0.0225, -0.0690, -0.1736, 0.0951, 0.0971, -0.0817, -0.0702, 0.0162, 0.0260, 0.0017, -0.0192, -0.1678, 0.0709, -0.1867, -0.0655, -0.0274, -0.0234, -0.1884, -0.0516, -0.0554, -0.0274, -0.1425, -0.1423, 0.0837, 0.0377, -0.0854 ] ) # fmt: on __SCREAMING_SNAKE_CASE = self._load_datasamples(1 ) __SCREAMING_SNAKE_CASE = WhisperFeatureExtractor() __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).input_features self.assertEqual(input_features.shape , (1, 80, 3_000) ) self.assertTrue(torch.allclose(input_features[0, 0, :30] , __SCREAMING_SNAKE_CASE , atol=1E-4 ) ) def UpperCAmelCase__ ( self : List[Any] ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __SCREAMING_SNAKE_CASE = self._load_datasamples(1 )[0] __SCREAMING_SNAKE_CASE = ((audio - audio.min()) / (audio.max() - audio.min())) * 65_535 # Rescale to [0, 65535] to show issue __SCREAMING_SNAKE_CASE = feat_extract.zero_mean_unit_var_norm([audio] , attention_mask=__SCREAMING_SNAKE_CASE )[0] self.assertTrue(np.all(np.mean(__SCREAMING_SNAKE_CASE ) < 1E-3 ) ) self.assertTrue(np.all(np.abs(np.var(__SCREAMING_SNAKE_CASE ) - 1 ) < 1E-3 ) )
267
1
'''simple docstring''' # limitations under the License. # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from .pipelines import DiffusionPipeline, ImagePipelineOutput # noqa: F401 from .utils import deprecate deprecate( 'pipelines_utils', '0.22.0', 'Importing `DiffusionPipeline` or `ImagePipelineOutput` from diffusers.pipeline_utils is deprecated. Please import from diffusers.pipelines.pipeline_utils instead.', standard_warn=False, stacklevel=3, )
267
'''simple docstring''' from __future__ import annotations def a__ ( a__ , a__ , a__ ): """simple docstring""" if len(a__ ) == 0: raise ValueError("""find_max() arg is an empty sequence""" ) if ( left >= len(a__ ) or left < -len(a__ ) or right >= len(a__ ) or right < -len(a__ ) ): raise IndexError("""list index out of range""" ) if left == right: return nums[left] __SCREAMING_SNAKE_CASE = (left + right) >> 1 # the middle __SCREAMING_SNAKE_CASE = find_max(a__ , a__ , a__ ) # find max in range[left, mid] __SCREAMING_SNAKE_CASE = find_max(a__ , mid + 1 , a__ ) # find max in range[mid + 1, right] return left_max if left_max >= right_max else right_max if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
267
1
'''simple docstring''' import itertools import random import unittest import numpy as np from transformers import is_speech_available from transformers.testing_utils import require_torch, require_torchaudio from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_speech_available(): from transformers import SpeechaTextFeatureExtractor UpperCAmelCase : Dict = random.Random() def a__ ( a__ , a__=1.0 , a__=None , a__=None ): """simple docstring""" if rng is None: __SCREAMING_SNAKE_CASE = global_rng __SCREAMING_SNAKE_CASE = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch @require_torchaudio class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : int=7 , __SCREAMING_SNAKE_CASE : List[str]=400 , __SCREAMING_SNAKE_CASE : Any=2_000 , __SCREAMING_SNAKE_CASE : str=24 , __SCREAMING_SNAKE_CASE : Union[str, Any]=24 , __SCREAMING_SNAKE_CASE : Optional[Any]=0.0 , __SCREAMING_SNAKE_CASE : Optional[Any]=16_000 , __SCREAMING_SNAKE_CASE : List[str]=True , __SCREAMING_SNAKE_CASE : int=True , ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = min_seq_length __SCREAMING_SNAKE_CASE = max_seq_length __SCREAMING_SNAKE_CASE = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) __SCREAMING_SNAKE_CASE = feature_size __SCREAMING_SNAKE_CASE = num_mel_bins __SCREAMING_SNAKE_CASE = padding_value __SCREAMING_SNAKE_CASE = sampling_rate __SCREAMING_SNAKE_CASE = return_attention_mask __SCREAMING_SNAKE_CASE = do_normalize def UpperCAmelCase__ ( self : Optional[int] ) -> List[str]: """simple docstring""" return { "feature_size": self.feature_size, "num_mel_bins": self.num_mel_bins, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def UpperCAmelCase__ ( self : Optional[int] , __SCREAMING_SNAKE_CASE : Any=False , __SCREAMING_SNAKE_CASE : Optional[Any]=False ) -> Optional[Any]: """simple docstring""" def _flatten(__SCREAMING_SNAKE_CASE : Optional[int] ): return list(itertools.chain(*__SCREAMING_SNAKE_CASE ) ) if equal_length: __SCREAMING_SNAKE_CASE = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size __SCREAMING_SNAKE_CASE = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = SpeechaTextFeatureExtractor if is_speech_available() else None def UpperCAmelCase__ ( self : Tuple ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = SpeechaTextFeatureExtractionTester(self ) def UpperCAmelCase__ ( self : str , __SCREAMING_SNAKE_CASE : int ) -> int: """simple docstring""" self.assertTrue(np.all(np.mean(__SCREAMING_SNAKE_CASE , axis=0 ) < 1E-3 ) ) self.assertTrue(np.all(np.abs(np.var(__SCREAMING_SNAKE_CASE , axis=0 ) - 1 ) < 1E-3 ) ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in range(800 , 1_400 , 200 )] __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs] # Test feature size __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , padding=__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features self.assertTrue(input_features.ndim == 3 ) self.assertTrue(input_features.shape[-1] == feature_extractor.feature_size ) # Test not batched input __SCREAMING_SNAKE_CASE = feature_extractor(speech_inputs[0] , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(np_speech_inputs[0] , return_tensors="""np""" ).input_features self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test batched __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test 2-D numpy arrays are batched. __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in (800, 800, 800)] __SCREAMING_SNAKE_CASE = np.asarray(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) def UpperCAmelCase__ ( self : Any ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in range(800 , 1_400 , 200 )] __SCREAMING_SNAKE_CASE = ["""longest""", """max_length""", """do_not_pad"""] __SCREAMING_SNAKE_CASE = [None, 16, None] for max_length, padding in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): __SCREAMING_SNAKE_CASE = feature_extractor( __SCREAMING_SNAKE_CASE , padding=__SCREAMING_SNAKE_CASE , max_length=__SCREAMING_SNAKE_CASE , return_attention_mask=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = inputs.input_features __SCREAMING_SNAKE_CASE = inputs.attention_mask __SCREAMING_SNAKE_CASE = [np.sum(__SCREAMING_SNAKE_CASE ) for x in attention_mask] self._check_zero_mean_unit_variance(input_features[0][: fbank_feat_lengths[0]] ) self._check_zero_mean_unit_variance(input_features[1][: fbank_feat_lengths[1]] ) self._check_zero_mean_unit_variance(input_features[2][: fbank_feat_lengths[2]] ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in range(800 , 1_400 , 200 )] __SCREAMING_SNAKE_CASE = ["""longest""", """max_length""", """do_not_pad"""] __SCREAMING_SNAKE_CASE = [None, 16, None] for max_length, padding in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): __SCREAMING_SNAKE_CASE = feature_extractor( __SCREAMING_SNAKE_CASE , max_length=__SCREAMING_SNAKE_CASE , padding=__SCREAMING_SNAKE_CASE , return_tensors="""np""" , return_attention_mask=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = inputs.input_features __SCREAMING_SNAKE_CASE = inputs.attention_mask __SCREAMING_SNAKE_CASE = [np.sum(__SCREAMING_SNAKE_CASE ) for x in attention_mask] self._check_zero_mean_unit_variance(input_features[0][: fbank_feat_lengths[0]] ) self.assertTrue(input_features[0][fbank_feat_lengths[0] :].sum() < 1E-6 ) self._check_zero_mean_unit_variance(input_features[1][: fbank_feat_lengths[1]] ) self.assertTrue(input_features[0][fbank_feat_lengths[1] :].sum() < 1E-6 ) self._check_zero_mean_unit_variance(input_features[2][: fbank_feat_lengths[2]] ) def UpperCAmelCase__ ( self : Any ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in range(800 , 1_400 , 200 )] __SCREAMING_SNAKE_CASE = feature_extractor( __SCREAMING_SNAKE_CASE , padding="""max_length""" , max_length=4 , truncation=__SCREAMING_SNAKE_CASE , return_tensors="""np""" , return_attention_mask=__SCREAMING_SNAKE_CASE , ) __SCREAMING_SNAKE_CASE = inputs.input_features __SCREAMING_SNAKE_CASE = inputs.attention_mask __SCREAMING_SNAKE_CASE = np.sum(attention_mask == 1 , axis=1 ) self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]] ) self._check_zero_mean_unit_variance(input_features[1] ) self._check_zero_mean_unit_variance(input_features[2] ) def UpperCAmelCase__ ( self : Any ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in range(800 , 1_400 , 200 )] __SCREAMING_SNAKE_CASE = feature_extractor( __SCREAMING_SNAKE_CASE , padding="""longest""" , max_length=4 , truncation=__SCREAMING_SNAKE_CASE , return_tensors="""np""" , return_attention_mask=__SCREAMING_SNAKE_CASE , ) __SCREAMING_SNAKE_CASE = inputs.input_features __SCREAMING_SNAKE_CASE = inputs.attention_mask __SCREAMING_SNAKE_CASE = np.sum(attention_mask == 1 , axis=1 ) self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]] ) self._check_zero_mean_unit_variance(input_features[1, : fbank_feat_lengths[1]] ) self._check_zero_mean_unit_variance(input_features[2] ) # make sure that if max_length < longest -> then pad to max_length self.assertEqual(input_features.shape , (3, 4, 24) ) __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in range(800 , 1_400 , 200 )] __SCREAMING_SNAKE_CASE = feature_extractor( __SCREAMING_SNAKE_CASE , padding="""longest""" , max_length=16 , truncation=__SCREAMING_SNAKE_CASE , return_tensors="""np""" , return_attention_mask=__SCREAMING_SNAKE_CASE , ) __SCREAMING_SNAKE_CASE = inputs.input_features __SCREAMING_SNAKE_CASE = inputs.attention_mask __SCREAMING_SNAKE_CASE = np.sum(attention_mask == 1 , axis=1 ) self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]] ) self._check_zero_mean_unit_variance(input_features[1, : fbank_feat_lengths[1]] ) self._check_zero_mean_unit_variance(input_features[2] ) # make sure that if max_length < longest -> then pad to max_length self.assertEqual(input_features.shape , (3, 6, 24) ) def UpperCAmelCase__ ( self : str ) -> Dict: """simple docstring""" import torch __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __SCREAMING_SNAKE_CASE = np.random.rand(100 , 32 ).astype(np.floataa ) __SCREAMING_SNAKE_CASE = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: __SCREAMING_SNAKE_CASE = feature_extractor.pad([{"""input_features""": inputs}] , return_tensors="""np""" ) self.assertTrue(np_processed.input_features.dtype == np.floataa ) __SCREAMING_SNAKE_CASE = feature_extractor.pad([{"""input_features""": inputs}] , return_tensors="""pt""" ) self.assertTrue(pt_processed.input_features.dtype == torch.floataa ) def UpperCAmelCase__ ( self : List[Any] , __SCREAMING_SNAKE_CASE : str ) -> Union[str, Any]: """simple docstring""" from datasets import load_dataset __SCREAMING_SNAKE_CASE = load_dataset("""hf-internal-testing/librispeech_asr_dummy""" , """clean""" , split="""validation""" ) # automatic decoding with librispeech __SCREAMING_SNAKE_CASE = ds.sort("""id""" ).select(range(__SCREAMING_SNAKE_CASE ) )[:num_samples]["""audio"""] return [x["array"] for x in speech_samples] def UpperCAmelCase__ ( self : List[Any] ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = np.array([ -1.5745, -1.7713, -1.7020, -1.6069, -1.2250, -1.1105, -0.9072, -0.8241, -1.2310, -0.8098, -0.3320, -0.4101, -0.7985, -0.4996, -0.8213, -0.9128, -1.0420, -1.1286, -1.0440, -0.7999, -0.8405, -1.2275, -1.5443, -1.4625, ] ) # fmt: on __SCREAMING_SNAKE_CASE = self._load_datasamples(1 ) __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).input_features self.assertEquals(input_features.shape , (1, 584, 24) ) self.assertTrue(np.allclose(input_features[0, 0, :30] , __SCREAMING_SNAKE_CASE , atol=1E-4 ) )
267
'''simple docstring''' def a__ ( a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) # Initialize Result __SCREAMING_SNAKE_CASE = [] # Traverse through all denomination for denomination in reversed(a__ ): # Find denominations while int(a__ ) >= int(a__ ): total_value -= int(a__ ) answer.append(a__ ) # Append the "answers" array return answer # Driver Code if __name__ == "__main__": UpperCAmelCase : Dict = [] UpperCAmelCase : List[str] = '0' if ( input('Do you want to enter your denominations ? (yY/n): ').strip().lower() == "y" ): UpperCAmelCase : List[str] = int(input('Enter the number of denominations you want to add: ').strip()) for i in range(0, n): denominations.append(int(input(f"""Denomination {i}: """).strip())) UpperCAmelCase : str = input('Enter the change you want to make in Indian Currency: ').strip() else: # All denominations of Indian Currency if user does not enter UpperCAmelCase : int = [1, 2, 5, 1_0, 2_0, 5_0, 1_0_0, 5_0_0, 2_0_0_0] UpperCAmelCase : Any = input('Enter the change you want to make: ').strip() if int(value) == 0 or int(value) < 0: print('The total value cannot be zero or negative.') else: print(f"""Following is minimal change for {value}: """) UpperCAmelCase : Any = find_minimum_change(denominations, value) # Print result for i in range(len(answer)): print(answer[i], end=' ')
267
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase : Union[str, Any] = {'configuration_vit_msn': ['VIT_MSN_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ViTMSNConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : int = [ 'VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST', 'ViTMSNModel', 'ViTMSNForImageClassification', 'ViTMSNPreTrainedModel', ] if TYPE_CHECKING: from .configuration_vit_msn import VIT_MSN_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTMSNConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vit_msn import ( VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST, ViTMSNForImageClassification, ViTMSNModel, ViTMSNPreTrainedModel, ) else: import sys UpperCAmelCase : List[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
267
'''simple docstring''' # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse from ...utils.dataclasses import ( ComputeEnvironment, DistributedType, DynamoBackend, PrecisionType, SageMakerDistributedType, ) from ..menu import BulletMenu UpperCAmelCase : Any = [ 'EAGER', 'AOT_EAGER', 'INDUCTOR', 'NVFUSER', 'AOT_NVFUSER', 'AOT_CUDAGRAPHS', 'OFI', 'FX2TRT', 'ONNXRT', 'IPEX', ] def a__ ( a__ , a__=None , a__=None , a__=None ): """simple docstring""" __SCREAMING_SNAKE_CASE = True while ask_again: __SCREAMING_SNAKE_CASE = input(a__ ) try: if default is not None and len(a__ ) == 0: return default return convert_value(a__ ) if convert_value is not None else result except Exception: if error_message is not None: print(a__ ) def a__ ( a__ , a__=[] , a__=None , a__=0 ): """simple docstring""" __SCREAMING_SNAKE_CASE = BulletMenu(a__ , a__ ) __SCREAMING_SNAKE_CASE = menu.run(default_choice=a__ ) return convert_value(a__ ) if convert_value is not None else result def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return ComputeEnvironment(["""LOCAL_MACHINE""", """AMAZON_SAGEMAKER"""][value] ) def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return DistributedType(["""NO""", """MULTI_CPU""", """MULTI_XPU""", """MULTI_GPU""", """MULTI_NPU""", """TPU"""][value] ) def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return DynamoBackend(DYNAMO_BACKENDS[value] ).value def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return PrecisionType(["""no""", """fp16""", """bf16""", """fp8"""][value] ) def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return SageMakerDistributedType(["""NO""", """DATA_PARALLEL""", """MODEL_PARALLEL"""][value] ) def a__ ( a__ ): """simple docstring""" return {"yes": True, "no": False}[value.lower()] class lowerCAmelCase__ ( argparse.RawDescriptionHelpFormatter ): """simple docstring""" def UpperCAmelCase__ ( self : str , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : List[Any] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = super()._format_usage(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = usage.replace("""<command> [<args>] """ , """""" ) return usage
267
1
'''simple docstring''' import gc import random import unittest import numpy as np import torch from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import ( DiffusionPipeline, UnCLIPImageVariationPipeline, UnCLIPScheduler, UNetaDConditionModel, UNetaDModel, ) from diffusers.pipelines.unclip.text_proj import UnCLIPTextProjModel from diffusers.utils import floats_tensor, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, load_image, require_torch_gpu, skip_mps from ..pipeline_params import IMAGE_VARIATION_BATCH_PARAMS, IMAGE_VARIATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = UnCLIPImageVariationPipeline lowerCAmelCase__ = IMAGE_VARIATION_PARAMS - {"height", "width", "guidance_scale"} lowerCAmelCase__ = IMAGE_VARIATION_BATCH_PARAMS lowerCAmelCase__ = [ "generator", "return_dict", "decoder_num_inference_steps", "super_res_num_inference_steps", ] lowerCAmelCase__ = False @property def UpperCAmelCase__ ( self : Optional[int] ) -> Optional[int]: """simple docstring""" return 32 @property def UpperCAmelCase__ ( self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" return 32 @property def UpperCAmelCase__ ( self : Optional[Any] ) -> int: """simple docstring""" return self.time_input_dim @property def UpperCAmelCase__ ( self : List[str] ) -> Optional[Any]: """simple docstring""" return self.time_input_dim * 4 @property def UpperCAmelCase__ ( self : Any ) -> str: """simple docstring""" return 100 @property def UpperCAmelCase__ ( self : Tuple ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) return tokenizer @property def UpperCAmelCase__ ( self : List[str] ) -> Optional[int]: """simple docstring""" torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , ) return CLIPTextModelWithProjection(__SCREAMING_SNAKE_CASE ) @property def UpperCAmelCase__ ( self : Union[str, Any] ) -> Dict: """simple docstring""" torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , num_hidden_layers=5 , num_attention_heads=4 , image_size=32 , intermediate_size=37 , patch_size=1 , ) return CLIPVisionModelWithProjection(__SCREAMING_SNAKE_CASE ) @property def UpperCAmelCase__ ( self : List[Any] ) -> Any: """simple docstring""" torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = { """clip_embeddings_dim""": self.text_embedder_hidden_size, """time_embed_dim""": self.time_embed_dim, """cross_attention_dim""": self.cross_attention_dim, } __SCREAMING_SNAKE_CASE = UnCLIPTextProjModel(**__SCREAMING_SNAKE_CASE ) return model @property def UpperCAmelCase__ ( self : List[Any] ) -> Optional[Any]: """simple docstring""" torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = { """sample_size""": 32, # RGB in channels """in_channels""": 3, # Out channels is double in channels because predicts mean and variance """out_channels""": 6, """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, """cross_attention_dim""": self.cross_attention_dim, """attention_head_dim""": 4, """resnet_time_scale_shift""": """scale_shift""", """class_embed_type""": """identity""", } __SCREAMING_SNAKE_CASE = UNetaDConditionModel(**__SCREAMING_SNAKE_CASE ) return model @property def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" return { "sample_size": 64, "layers_per_block": 1, "down_block_types": ("ResnetDownsampleBlock2D", "ResnetDownsampleBlock2D"), "up_block_types": ("ResnetUpsampleBlock2D", "ResnetUpsampleBlock2D"), "block_out_channels": (self.block_out_channels_a, self.block_out_channels_a * 2), "in_channels": 6, "out_channels": 3, } @property def UpperCAmelCase__ ( self : str ) -> List[Any]: """simple docstring""" torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = UNetaDModel(**self.dummy_super_res_kwargs ) return model @property def UpperCAmelCase__ ( self : Any ) -> str: """simple docstring""" torch.manual_seed(1 ) __SCREAMING_SNAKE_CASE = UNetaDModel(**self.dummy_super_res_kwargs ) return model def UpperCAmelCase__ ( self : Any ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = self.dummy_decoder __SCREAMING_SNAKE_CASE = self.dummy_text_proj __SCREAMING_SNAKE_CASE = self.dummy_text_encoder __SCREAMING_SNAKE_CASE = self.dummy_tokenizer __SCREAMING_SNAKE_CASE = self.dummy_super_res_first __SCREAMING_SNAKE_CASE = self.dummy_super_res_last __SCREAMING_SNAKE_CASE = UnCLIPScheduler( variance_type="""learned_range""" , prediction_type="""epsilon""" , num_train_timesteps=1_000 , ) __SCREAMING_SNAKE_CASE = UnCLIPScheduler( variance_type="""fixed_small_log""" , prediction_type="""epsilon""" , num_train_timesteps=1_000 , ) __SCREAMING_SNAKE_CASE = CLIPImageProcessor(crop_size=32 , size=32 ) __SCREAMING_SNAKE_CASE = self.dummy_image_encoder return { "decoder": decoder, "text_encoder": text_encoder, "tokenizer": tokenizer, "text_proj": text_proj, "feature_extractor": feature_extractor, "image_encoder": image_encoder, "super_res_first": super_res_first, "super_res_last": super_res_last, "decoder_scheduler": decoder_scheduler, "super_res_scheduler": super_res_scheduler, } def UpperCAmelCase__ ( self : str , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : List[Any]=0 , __SCREAMING_SNAKE_CASE : int=True ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = floats_tensor((1, 3, 32, 32) , rng=random.Random(__SCREAMING_SNAKE_CASE ) ).to(__SCREAMING_SNAKE_CASE ) if str(__SCREAMING_SNAKE_CASE ).startswith("""mps""" ): __SCREAMING_SNAKE_CASE = torch.manual_seed(__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = torch.Generator(device=__SCREAMING_SNAKE_CASE ).manual_seed(__SCREAMING_SNAKE_CASE ) if pil_image: __SCREAMING_SNAKE_CASE = input_image * 0.5 + 0.5 __SCREAMING_SNAKE_CASE = input_image.clamp(0 , 1 ) __SCREAMING_SNAKE_CASE = input_image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() __SCREAMING_SNAKE_CASE = DiffusionPipeline.numpy_to_pil(__SCREAMING_SNAKE_CASE )[0] return { "image": input_image, "generator": generator, "decoder_num_inference_steps": 2, "super_res_num_inference_steps": 2, "output_type": "np", } def UpperCAmelCase__ ( self : List[Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = """cpu""" __SCREAMING_SNAKE_CASE = self.get_dummy_components() __SCREAMING_SNAKE_CASE = self.pipeline_class(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.get_dummy_inputs(__SCREAMING_SNAKE_CASE , pil_image=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = pipe(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = output.images __SCREAMING_SNAKE_CASE = self.get_dummy_inputs(__SCREAMING_SNAKE_CASE , pil_image=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = pipe( **__SCREAMING_SNAKE_CASE , return_dict=__SCREAMING_SNAKE_CASE , )[0] __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] __SCREAMING_SNAKE_CASE = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __SCREAMING_SNAKE_CASE = np.array( [ 0.9997, 0.0002, 0.9997, 0.9997, 0.9969, 0.0023, 0.9997, 0.9969, 0.9970, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 def UpperCAmelCase__ ( self : str ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = """cpu""" __SCREAMING_SNAKE_CASE = self.get_dummy_components() __SCREAMING_SNAKE_CASE = self.pipeline_class(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.get_dummy_inputs(__SCREAMING_SNAKE_CASE , pil_image=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = pipe(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = output.images __SCREAMING_SNAKE_CASE = self.get_dummy_inputs(__SCREAMING_SNAKE_CASE , pil_image=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = pipe( **__SCREAMING_SNAKE_CASE , return_dict=__SCREAMING_SNAKE_CASE , )[0] __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] __SCREAMING_SNAKE_CASE = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __SCREAMING_SNAKE_CASE = np.array([0.9997, 0.0003, 0.9997, 0.9997, 0.9970, 0.0024, 0.9997, 0.9971, 0.9971] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 def UpperCAmelCase__ ( self : int ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = """cpu""" __SCREAMING_SNAKE_CASE = self.get_dummy_components() __SCREAMING_SNAKE_CASE = self.pipeline_class(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.get_dummy_inputs(__SCREAMING_SNAKE_CASE , pil_image=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = [ pipeline_inputs["""image"""], pipeline_inputs["""image"""], ] __SCREAMING_SNAKE_CASE = pipe(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = output.images __SCREAMING_SNAKE_CASE = self.get_dummy_inputs(__SCREAMING_SNAKE_CASE , pil_image=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = [ tuple_pipeline_inputs["""image"""], tuple_pipeline_inputs["""image"""], ] __SCREAMING_SNAKE_CASE = pipe( **__SCREAMING_SNAKE_CASE , return_dict=__SCREAMING_SNAKE_CASE , )[0] __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] __SCREAMING_SNAKE_CASE = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (2, 64, 64, 3) __SCREAMING_SNAKE_CASE = np.array( [ 0.9997, 0.9989, 0.0008, 0.0021, 0.9960, 0.0018, 0.0014, 0.0002, 0.9933, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 def UpperCAmelCase__ ( self : Optional[int] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = torch.device("""cpu""" ) class lowerCAmelCase__ : """simple docstring""" lowerCAmelCase__ = 1 __SCREAMING_SNAKE_CASE = self.get_dummy_components() __SCREAMING_SNAKE_CASE = self.pipeline_class(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = torch.Generator(device=__SCREAMING_SNAKE_CASE ).manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe.decoder.dtype __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = ( batch_size, pipe.decoder.config.in_channels, pipe.decoder.config.sample_size, pipe.decoder.config.sample_size, ) __SCREAMING_SNAKE_CASE = pipe.prepare_latents( __SCREAMING_SNAKE_CASE , dtype=__SCREAMING_SNAKE_CASE , device=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , latents=__SCREAMING_SNAKE_CASE , scheduler=DummyScheduler() ) __SCREAMING_SNAKE_CASE = ( batch_size, pipe.super_res_first.config.in_channels // 2, pipe.super_res_first.config.sample_size, pipe.super_res_first.config.sample_size, ) __SCREAMING_SNAKE_CASE = pipe.prepare_latents( __SCREAMING_SNAKE_CASE , dtype=__SCREAMING_SNAKE_CASE , device=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , latents=__SCREAMING_SNAKE_CASE , scheduler=DummyScheduler() ) __SCREAMING_SNAKE_CASE = self.get_dummy_inputs(__SCREAMING_SNAKE_CASE , pil_image=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = pipe( **__SCREAMING_SNAKE_CASE , decoder_latents=__SCREAMING_SNAKE_CASE , super_res_latents=__SCREAMING_SNAKE_CASE ).images __SCREAMING_SNAKE_CASE = self.get_dummy_inputs(__SCREAMING_SNAKE_CASE , pil_image=__SCREAMING_SNAKE_CASE ) # Don't pass image, instead pass embedding __SCREAMING_SNAKE_CASE = pipeline_inputs.pop("""image""" ) __SCREAMING_SNAKE_CASE = pipe.image_encoder(__SCREAMING_SNAKE_CASE ).image_embeds __SCREAMING_SNAKE_CASE = pipe( **__SCREAMING_SNAKE_CASE , decoder_latents=__SCREAMING_SNAKE_CASE , super_res_latents=__SCREAMING_SNAKE_CASE , image_embeddings=__SCREAMING_SNAKE_CASE , ).images # make sure passing text embeddings manually is identical assert np.abs(img_out_a - img_out_a ).max() < 1E-4 @skip_mps def UpperCAmelCase__ ( self : List[str] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = torch_device == """cpu""" # Check is relaxed because there is not a torch 2.0 sliced attention added kv processor __SCREAMING_SNAKE_CASE = 1E-2 self._test_attention_slicing_forward_pass( test_max_difference=__SCREAMING_SNAKE_CASE , expected_max_diff=__SCREAMING_SNAKE_CASE ) @skip_mps def UpperCAmelCase__ ( self : Optional[int] ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = torch_device == """cpu""" __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = [ """decoder_num_inference_steps""", """super_res_num_inference_steps""", ] self._test_inference_batch_single_identical( test_max_difference=__SCREAMING_SNAKE_CASE , relax_max_difference=__SCREAMING_SNAKE_CASE , additional_params_copy_to_batched_inputs=__SCREAMING_SNAKE_CASE , ) def UpperCAmelCase__ ( self : Tuple ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = [ """decoder_num_inference_steps""", """super_res_num_inference_steps""", ] if torch_device == "mps": # TODO: MPS errors with larger batch sizes __SCREAMING_SNAKE_CASE = [2, 3] self._test_inference_batch_consistent( batch_sizes=__SCREAMING_SNAKE_CASE , additional_params_copy_to_batched_inputs=__SCREAMING_SNAKE_CASE , ) else: self._test_inference_batch_consistent( additional_params_copy_to_batched_inputs=__SCREAMING_SNAKE_CASE ) @skip_mps def UpperCAmelCase__ ( self : Any ) -> Tuple: """simple docstring""" return super().test_dict_tuple_outputs_equivalent() @skip_mps def UpperCAmelCase__ ( self : Tuple ) -> List[str]: """simple docstring""" return super().test_save_load_local() @skip_mps def UpperCAmelCase__ ( self : Dict ) -> List[Any]: """simple docstring""" return super().test_save_load_optional_components() @slow @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : Dict ) -> str: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase__ ( self : List[str] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/unclip/cat.png""" ) __SCREAMING_SNAKE_CASE = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/unclip/karlo_v1_alpha_cat_variation_fp16.npy""" ) __SCREAMING_SNAKE_CASE = UnCLIPImageVariationPipeline.from_pretrained( """kakaobrain/karlo-v1-alpha-image-variations""" , torch_dtype=torch.floataa ) __SCREAMING_SNAKE_CASE = pipeline.to(__SCREAMING_SNAKE_CASE ) pipeline.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = torch.Generator(device="""cpu""" ).manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipeline( __SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , output_type="""np""" , ) __SCREAMING_SNAKE_CASE = output.images[0] assert image.shape == (256, 256, 3) assert_mean_pixel_difference(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , 15 )
267
'''simple docstring''' def a__ ( a__ , a__ ): """simple docstring""" _enforce_args(a__ , a__ ) if n == 0: return 0 __SCREAMING_SNAKE_CASE = float("""-inf""" ) for i in range(1 , n + 1 ): __SCREAMING_SNAKE_CASE = max( a__ , prices[i - 1] + naive_cut_rod_recursive(n - i , a__ ) ) return max_revue def a__ ( a__ , a__ ): """simple docstring""" _enforce_args(a__ , a__ ) __SCREAMING_SNAKE_CASE = [float("""-inf""" ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ ): """simple docstring""" if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: __SCREAMING_SNAKE_CASE = float("""-inf""" ) for i in range(1 , n + 1 ): __SCREAMING_SNAKE_CASE = max( a__ , prices[i - 1] + _top_down_cut_rod_recursive(n - i , a__ , a__ ) , ) __SCREAMING_SNAKE_CASE = max_revenue return max_rev[n] def a__ ( a__ , a__ ): """simple docstring""" _enforce_args(a__ , a__ ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. __SCREAMING_SNAKE_CASE = [float("""-inf""" ) for _ in range(n + 1 )] __SCREAMING_SNAKE_CASE = 0 for i in range(1 , n + 1 ): __SCREAMING_SNAKE_CASE = max_rev[i] for j in range(1 , i + 1 ): __SCREAMING_SNAKE_CASE = max(a__ , prices[j - 1] + max_rev[i - j] ) __SCREAMING_SNAKE_CASE = max_revenue_i return max_rev[n] def a__ ( a__ , a__ ): """simple docstring""" if n < 0: __SCREAMING_SNAKE_CASE = F'n must be greater than or equal to 0. Got n = {n}' raise ValueError(a__ ) if n > len(a__ ): __SCREAMING_SNAKE_CASE = ( """Each integral piece of rod must have a corresponding price. """ F'Got n = {n} but length of prices = {len(a__ )}' ) raise ValueError(a__ ) def a__ ( ): """simple docstring""" __SCREAMING_SNAKE_CASE = [6, 10, 12, 15, 20, 23] __SCREAMING_SNAKE_CASE = len(a__ ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. __SCREAMING_SNAKE_CASE = 36 __SCREAMING_SNAKE_CASE = top_down_cut_rod(a__ , a__ ) __SCREAMING_SNAKE_CASE = bottom_up_cut_rod(a__ , a__ ) __SCREAMING_SNAKE_CASE = naive_cut_rod_recursive(a__ , a__ ) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
267
1
'''simple docstring''' from math import ceil def a__ ( a__ = 10_01 ): """simple docstring""" __SCREAMING_SNAKE_CASE = 1 for i in range(1 , int(ceil(n / 2.0 ) ) ): __SCREAMING_SNAKE_CASE = 2 * i + 1 __SCREAMING_SNAKE_CASE = 2 * i __SCREAMING_SNAKE_CASE = total + 4 * odd**2 - 6 * even return total if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution()) else: try: UpperCAmelCase : Optional[int] = int(sys.argv[1]) print(solution(n)) except ValueError: print('Invalid entry - please enter a number')
267
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase : Union[str, Any] = {'configuration_sew': ['SEW_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SEWConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Union[str, Any] = [ 'SEW_PRETRAINED_MODEL_ARCHIVE_LIST', 'SEWForCTC', 'SEWForSequenceClassification', 'SEWModel', 'SEWPreTrainedModel', ] if TYPE_CHECKING: from .configuration_sew import SEW_PRETRAINED_CONFIG_ARCHIVE_MAP, SEWConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_sew import ( SEW_PRETRAINED_MODEL_ARCHIVE_LIST, SEWForCTC, SEWForSequenceClassification, SEWModel, SEWPreTrainedModel, ) else: import sys UpperCAmelCase : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
267
1
'''simple docstring''' import numpy as np import skfuzzy as fuzz if __name__ == "__main__": # Create universe of discourse in Python using linspace () UpperCAmelCase : Dict = np.linspace(start=0, stop=7_5, num=7_5, endpoint=True, retstep=False) # Create two fuzzy sets by defining any membership function # (trapmf(), gbellmf(), gaussmf(), etc). UpperCAmelCase : List[Any] = [0, 2_5, 5_0] UpperCAmelCase : List[Any] = [2_5, 5_0, 7_5] UpperCAmelCase : Tuple = fuzz.membership.trimf(X, abca) UpperCAmelCase : Tuple = fuzz.membership.trimf(X, abca) # Compute the different operations using inbuilt functions. UpperCAmelCase : Any = np.ones(7_5) UpperCAmelCase : Tuple = np.zeros((7_5,)) # 1. Union = max(µA(x), µB(x)) UpperCAmelCase : Optional[Any] = fuzz.fuzzy_or(X, young, X, middle_aged)[1] # 2. Intersection = min(µA(x), µB(x)) UpperCAmelCase : Tuple = fuzz.fuzzy_and(X, young, X, middle_aged)[1] # 3. Complement (A) = (1- min(µA(x)) UpperCAmelCase : List[Any] = fuzz.fuzzy_not(young) # 4. Difference (A/B) = min(µA(x),(1- µB(x))) UpperCAmelCase : Union[str, Any] = fuzz.fuzzy_and(X, young, X, fuzz.fuzzy_not(middle_aged)[1])[1] # 5. Algebraic Sum = [µA(x) + µB(x) – (µA(x) * µB(x))] UpperCAmelCase : Optional[int] = young + middle_aged - (young * middle_aged) # 6. Algebraic Product = (µA(x) * µB(x)) UpperCAmelCase : Any = young * middle_aged # 7. Bounded Sum = min[1,(µA(x), µB(x))] UpperCAmelCase : int = fuzz.fuzzy_and(X, one, X, young + middle_aged)[1] # 8. Bounded difference = min[0,(µA(x), µB(x))] UpperCAmelCase : int = fuzz.fuzzy_or(X, zero, X, young - middle_aged)[1] # max-min composition # max-product composition # Plot each set A, set B and each operation result using plot() and subplot(). from matplotlib import pyplot as plt plt.figure() plt.subplot(4, 3, 1) plt.plot(X, young) plt.title('Young') plt.grid(True) plt.subplot(4, 3, 2) plt.plot(X, middle_aged) plt.title('Middle aged') plt.grid(True) plt.subplot(4, 3, 3) plt.plot(X, union) plt.title('union') plt.grid(True) plt.subplot(4, 3, 4) plt.plot(X, intersection) plt.title('intersection') plt.grid(True) plt.subplot(4, 3, 5) plt.plot(X, complement_a) plt.title('complement_a') plt.grid(True) plt.subplot(4, 3, 6) plt.plot(X, difference) plt.title('difference a/b') plt.grid(True) plt.subplot(4, 3, 7) plt.plot(X, alg_sum) plt.title('alg_sum') plt.grid(True) plt.subplot(4, 3, 8) plt.plot(X, alg_product) plt.title('alg_product') plt.grid(True) plt.subplot(4, 3, 9) plt.plot(X, bdd_sum) plt.title('bdd_sum') plt.grid(True) plt.subplot(4, 3, 1_0) plt.plot(X, bdd_difference) plt.title('bdd_difference') plt.grid(True) plt.subplots_adjust(hspace=0.5) plt.show()
267
'''simple docstring''' class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Any ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = name __SCREAMING_SNAKE_CASE = value __SCREAMING_SNAKE_CASE = weight def __repr__( self : str ) -> Union[str, Any]: """simple docstring""" return f'{self.__class__.__name__}({self.name}, {self.value}, {self.weight})' def UpperCAmelCase__ ( self : List[Any] ) -> List[Any]: """simple docstring""" return self.value def UpperCAmelCase__ ( self : Any ) -> str: """simple docstring""" return self.name def UpperCAmelCase__ ( self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" return self.weight def UpperCAmelCase__ ( self : int ) -> Tuple: """simple docstring""" return self.value / self.weight def a__ ( a__ , a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = [] for i in range(len(a__ ) ): menu.append(Things(name[i] , value[i] , weight[i] ) ) return menu def a__ ( a__ , a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = sorted(a__ , key=a__ , reverse=a__ ) __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = 0.0, 0.0 for i in range(len(a__ ) ): if (total_cost + items_copy[i].get_weight()) <= max_cost: result.append(items_copy[i] ) total_cost += items_copy[i].get_weight() total_value += items_copy[i].get_value() return (result, total_value) def a__ ( ): """simple docstring""" if __name__ == "__main__": import doctest doctest.testmod()
267
1
'''simple docstring''' import random def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = num - 1 __SCREAMING_SNAKE_CASE = 0 while s % 2 == 0: __SCREAMING_SNAKE_CASE = s // 2 t += 1 for _ in range(5 ): __SCREAMING_SNAKE_CASE = random.randrange(2 , num - 1 ) __SCREAMING_SNAKE_CASE = pow(a__ , a__ , a__ ) if v != 1: __SCREAMING_SNAKE_CASE = 0 while v != (num - 1): if i == t - 1: return False else: __SCREAMING_SNAKE_CASE = i + 1 __SCREAMING_SNAKE_CASE = (v**2) % num return True def a__ ( a__ ): """simple docstring""" if num < 2: return False __SCREAMING_SNAKE_CASE = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 1_01, 1_03, 1_07, 1_09, 1_13, 1_27, 1_31, 1_37, 1_39, 1_49, 1_51, 1_57, 1_63, 1_67, 1_73, 1_79, 1_81, 1_91, 1_93, 1_97, 1_99, 2_11, 2_23, 2_27, 2_29, 2_33, 2_39, 2_41, 2_51, 2_57, 2_63, 2_69, 2_71, 2_77, 2_81, 2_83, 2_93, 3_07, 3_11, 3_13, 3_17, 3_31, 3_37, 3_47, 3_49, 3_53, 3_59, 3_67, 3_73, 3_79, 3_83, 3_89, 3_97, 4_01, 4_09, 4_19, 4_21, 4_31, 4_33, 4_39, 4_43, 4_49, 4_57, 4_61, 4_63, 4_67, 4_79, 4_87, 4_91, 4_99, 5_03, 5_09, 5_21, 5_23, 5_41, 5_47, 5_57, 5_63, 5_69, 5_71, 5_77, 5_87, 5_93, 5_99, 6_01, 6_07, 6_13, 6_17, 6_19, 6_31, 6_41, 6_43, 6_47, 6_53, 6_59, 6_61, 6_73, 6_77, 6_83, 6_91, 7_01, 7_09, 7_19, 7_27, 7_33, 7_39, 7_43, 7_51, 7_57, 7_61, 7_69, 7_73, 7_87, 7_97, 8_09, 8_11, 8_21, 8_23, 8_27, 8_29, 8_39, 8_53, 8_57, 8_59, 8_63, 8_77, 8_81, 8_83, 8_87, 9_07, 9_11, 9_19, 9_29, 9_37, 9_41, 9_47, 9_53, 9_67, 9_71, 9_77, 9_83, 9_91, 9_97, ] if num in low_primes: return True for prime in low_primes: if (num % prime) == 0: return False return rabin_miller(a__ ) def a__ ( a__ = 10_24 ): """simple docstring""" while True: __SCREAMING_SNAKE_CASE = random.randrange(2 ** (keysize - 1) , 2 ** (keysize) ) if is_prime_low_num(a__ ): return num if __name__ == "__main__": UpperCAmelCase : Tuple = generate_large_prime() print(('Prime number:', num)) print(('is_prime_low_num:', is_prime_low_num(num)))
267
'''simple docstring''' import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import CLIPImageProcessor, CLIPProcessor @require_vision class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : Union[str, Any] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() # fmt: off __SCREAMING_SNAKE_CASE = ["""l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """lo""", """l</w>""", """w</w>""", """r</w>""", """t</w>""", """low</w>""", """er</w>""", """lowest</w>""", """newer</w>""", """wider""", """<unk>""", """<|startoftext|>""", """<|endoftext|>"""] # fmt: on __SCREAMING_SNAKE_CASE = dict(zip(__SCREAMING_SNAKE_CASE , range(len(__SCREAMING_SNAKE_CASE ) ) ) ) __SCREAMING_SNAKE_CASE = ["""#version: 0.2""", """l o""", """lo w</w>""", """e r</w>""", """"""] __SCREAMING_SNAKE_CASE = {"""unk_token""": """<unk>"""} __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) __SCREAMING_SNAKE_CASE = 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(__SCREAMING_SNAKE_CASE ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = { """do_resize""": True, """size""": 20, """do_center_crop""": True, """crop_size""": 18, """do_normalize""": True, """image_mean""": [0.48145466, 0.4578275, 0.40821073], """image_std""": [0.26862954, 0.26130258, 0.27577711], } __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , __SCREAMING_SNAKE_CASE ) with open(self.image_processor_file , """w""" , encoding="""utf-8""" ) as fp: json.dump(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] , **__SCREAMING_SNAKE_CASE : Optional[int] ) -> str: """simple docstring""" return CLIPTokenizer.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Tuple , **__SCREAMING_SNAKE_CASE : Any ) -> int: """simple docstring""" return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[Any] , **__SCREAMING_SNAKE_CASE : Optional[int] ) -> List[str]: """simple docstring""" return CLIPImageProcessor.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Tuple ) -> str: """simple docstring""" shutil.rmtree(self.tmpdirname ) def UpperCAmelCase__ ( self : Optional[Any] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __SCREAMING_SNAKE_CASE = [Image.fromarray(np.moveaxis(__SCREAMING_SNAKE_CASE , 0 , -1 ) ) for x in image_inputs] return image_inputs def UpperCAmelCase__ ( self : Optional[int] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = self.get_rust_tokenizer() __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) processor_slow.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = CLIPProcessor.from_pretrained(self.tmpdirname , use_fast=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) processor_fast.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = CLIPProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , __SCREAMING_SNAKE_CASE ) self.assertIsInstance(processor_fast.tokenizer , __SCREAMING_SNAKE_CASE ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , __SCREAMING_SNAKE_CASE ) self.assertIsInstance(processor_fast.image_processor , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) __SCREAMING_SNAKE_CASE = self.get_image_processor(do_normalize=__SCREAMING_SNAKE_CASE , padding_value=1.0 ) __SCREAMING_SNAKE_CASE = CLIPProcessor.from_pretrained( self.tmpdirname , bos_token="""(BOS)""" , eos_token="""(EOS)""" , do_normalize=__SCREAMING_SNAKE_CASE , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , __SCREAMING_SNAKE_CASE ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[str] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = image_processor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ) __SCREAMING_SNAKE_CASE = processor(images=__SCREAMING_SNAKE_CASE , return_tensors="""np""" ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1E-2 ) def UpperCAmelCase__ ( self : List[Any] ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """lower newer""" __SCREAMING_SNAKE_CASE = processor(text=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer(__SCREAMING_SNAKE_CASE ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def UpperCAmelCase__ ( self : Dict ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """lower newer""" __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = processor(text=__SCREAMING_SNAKE_CASE , images=__SCREAMING_SNAKE_CASE ) self.assertListEqual(list(inputs.keys() ) , ["""input_ids""", """attention_mask""", """pixel_values"""] ) # test if it raises when no input is passed with pytest.raises(__SCREAMING_SNAKE_CASE ): processor() def UpperCAmelCase__ ( self : List[str] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __SCREAMING_SNAKE_CASE = processor.batch_decode(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer.batch_decode(__SCREAMING_SNAKE_CASE ) self.assertListEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : int ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """lower newer""" __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = processor(text=__SCREAMING_SNAKE_CASE , images=__SCREAMING_SNAKE_CASE ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
267
1
'''simple docstring''' import gc import random import tempfile import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMInverseScheduler, DDIMScheduler, DPMSolverMultistepInverseScheduler, DPMSolverMultistepScheduler, StableDiffusionDiffEditPipeline, UNetaDConditionModel, ) from diffusers.utils import load_image, slow from diffusers.utils.testing_utils import enable_full_determinism, floats_tensor, require_torch_gpu, torch_device from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowerCAmelCase__ ( a , a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = StableDiffusionDiffEditPipeline lowerCAmelCase__ = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {"height", "width", "image"} | {"image_latents"} lowerCAmelCase__ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS - {"image"} | {"image_latents"} lowerCAmelCase__ = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess lowerCAmelCase__ = frozenset([] ) def UpperCAmelCase__ ( self : Optional[int] ) -> Union[str, Any]: """simple docstring""" torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=__SCREAMING_SNAKE_CASE , ) __SCREAMING_SNAKE_CASE = DDIMScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=__SCREAMING_SNAKE_CASE , set_alpha_to_one=__SCREAMING_SNAKE_CASE , ) __SCREAMING_SNAKE_CASE = DDIMInverseScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=__SCREAMING_SNAKE_CASE , set_alpha_to_zero=__SCREAMING_SNAKE_CASE , ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act="""gelu""" , projection_dim=512 , ) __SCREAMING_SNAKE_CASE = CLIPTextModel(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) __SCREAMING_SNAKE_CASE = { """unet""": unet, """scheduler""": scheduler, """inverse_scheduler""": inverse_scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def UpperCAmelCase__ ( self : List[Any] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : List[Any]=0 ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = floats_tensor((1, 16, 16) , rng=random.Random(__SCREAMING_SNAKE_CASE ) ).to(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = floats_tensor((1, 2, 4, 16, 16) , rng=random.Random(__SCREAMING_SNAKE_CASE ) ).to(__SCREAMING_SNAKE_CASE ) if str(__SCREAMING_SNAKE_CASE ).startswith("""mps""" ): __SCREAMING_SNAKE_CASE = torch.manual_seed(__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = torch.Generator(device=__SCREAMING_SNAKE_CASE ).manual_seed(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = { """prompt""": """a dog and a newt""", """mask_image""": mask, """image_latents""": latents, """generator""": generator, """num_inference_steps""": 2, """inpaint_strength""": 1.0, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def UpperCAmelCase__ ( self : Optional[int] , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[int]=0 ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = floats_tensor((1, 3, 32, 32) , rng=random.Random(__SCREAMING_SNAKE_CASE ) ).to(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1 )[0] __SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(__SCREAMING_SNAKE_CASE ) ).convert("""RGB""" ) if str(__SCREAMING_SNAKE_CASE ).startswith("""mps""" ): __SCREAMING_SNAKE_CASE = torch.manual_seed(__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = torch.Generator(device=__SCREAMING_SNAKE_CASE ).manual_seed(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = { """image""": image, """source_prompt""": """a cat and a frog""", """target_prompt""": """a dog and a newt""", """generator""": generator, """num_inference_steps""": 2, """num_maps_per_mask""": 2, """mask_encode_strength""": 1.0, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def UpperCAmelCase__ ( self : List[str] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Optional[int]=0 ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = floats_tensor((1, 3, 32, 32) , rng=random.Random(__SCREAMING_SNAKE_CASE ) ).to(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1 )[0] __SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(__SCREAMING_SNAKE_CASE ) ).convert("""RGB""" ) if str(__SCREAMING_SNAKE_CASE ).startswith("""mps""" ): __SCREAMING_SNAKE_CASE = torch.manual_seed(__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = torch.Generator(device=__SCREAMING_SNAKE_CASE ).manual_seed(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = { """image""": image, """prompt""": """a cat and a frog""", """generator""": generator, """num_inference_steps""": 2, """inpaint_strength""": 1.0, """guidance_scale""": 6.0, """decode_latents""": True, """output_type""": """numpy""", } return inputs def UpperCAmelCase__ ( self : Tuple ) -> str: """simple docstring""" if not hasattr(self.pipeline_class , """_optional_components""" ): return __SCREAMING_SNAKE_CASE = self.get_dummy_components() __SCREAMING_SNAKE_CASE = self.pipeline_class(**__SCREAMING_SNAKE_CASE ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) # set all optional components to None and update pipeline config accordingly for optional_component in pipe._optional_components: setattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) pipe.register_modules(**{optional_component: None for optional_component in pipe._optional_components} ) __SCREAMING_SNAKE_CASE = self.get_dummy_inputs(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = pipe(**__SCREAMING_SNAKE_CASE )[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.pipeline_class.from_pretrained(__SCREAMING_SNAKE_CASE ) pipe_loaded.to(__SCREAMING_SNAKE_CASE ) pipe_loaded.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) for optional_component in pipe._optional_components: self.assertTrue( getattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) is None , f'`{optional_component}` did not stay set to None after loading.' , ) __SCREAMING_SNAKE_CASE = self.get_dummy_inputs(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = pipe_loaded(**__SCREAMING_SNAKE_CASE )[0] __SCREAMING_SNAKE_CASE = np.abs(output - output_loaded ).max() self.assertLess(__SCREAMING_SNAKE_CASE , 1E-4 ) def UpperCAmelCase__ ( self : List[Any] ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = """cpu""" __SCREAMING_SNAKE_CASE = self.get_dummy_components() __SCREAMING_SNAKE_CASE = self.pipeline_class(**__SCREAMING_SNAKE_CASE ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.get_dummy_mask_inputs(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = pipe.generate_mask(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = mask[0, -3:, -3:] self.assertEqual(mask.shape , (1, 16, 16) ) __SCREAMING_SNAKE_CASE = np.array([0] * 9 ) __SCREAMING_SNAKE_CASE = np.abs(mask_slice.flatten() - expected_slice ).max() self.assertLessEqual(__SCREAMING_SNAKE_CASE , 1E-3 ) self.assertEqual(mask[0, -3, -4] , 0 ) def UpperCAmelCase__ ( self : Optional[int] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = """cpu""" __SCREAMING_SNAKE_CASE = self.get_dummy_components() __SCREAMING_SNAKE_CASE = self.pipeline_class(**__SCREAMING_SNAKE_CASE ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.get_dummy_inversion_inputs(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = pipe.invert(**__SCREAMING_SNAKE_CASE ).images __SCREAMING_SNAKE_CASE = image[0, -1, -3:, -3:] self.assertEqual(image.shape , (2, 32, 32, 3) ) __SCREAMING_SNAKE_CASE = np.array( [0.5150, 0.5134, 0.5043, 0.5376, 0.4694, 0.51050, 0.5015, 0.4407, 0.4799] , ) __SCREAMING_SNAKE_CASE = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(__SCREAMING_SNAKE_CASE , 1E-3 ) def UpperCAmelCase__ ( self : List[str] ) -> Optional[int]: """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=5E-3 ) def UpperCAmelCase__ ( self : Dict ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = """cpu""" __SCREAMING_SNAKE_CASE = self.get_dummy_components() __SCREAMING_SNAKE_CASE = {"""beta_start""": 0.00085, """beta_end""": 0.012, """beta_schedule""": """scaled_linear"""} __SCREAMING_SNAKE_CASE = DPMSolverMultistepScheduler(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = DPMSolverMultistepInverseScheduler(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.pipeline_class(**__SCREAMING_SNAKE_CASE ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.get_dummy_inversion_inputs(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = pipe.invert(**__SCREAMING_SNAKE_CASE ).images __SCREAMING_SNAKE_CASE = image[0, -1, -3:, -3:] self.assertEqual(image.shape , (2, 32, 32, 3) ) __SCREAMING_SNAKE_CASE = np.array( [0.5150, 0.5134, 0.5043, 0.5376, 0.4694, 0.51050, 0.5015, 0.4407, 0.4799] , ) __SCREAMING_SNAKE_CASE = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(__SCREAMING_SNAKE_CASE , 1E-3 ) @require_torch_gpu @slow class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : List[str] ) -> Optional[Any]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() @classmethod def UpperCAmelCase__ ( cls : List[str] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/diffedit/fruit.png""" ) __SCREAMING_SNAKE_CASE = raw_image.convert("""RGB""" ).resize((768, 768) ) __SCREAMING_SNAKE_CASE = raw_image def UpperCAmelCase__ ( self : Dict ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = StableDiffusionDiffEditPipeline.from_pretrained( """stabilityai/stable-diffusion-2-1""" , safety_checker=__SCREAMING_SNAKE_CASE , torch_dtype=torch.floataa ) __SCREAMING_SNAKE_CASE = DDIMScheduler.from_config(pipe.scheduler.config ) __SCREAMING_SNAKE_CASE = DDIMInverseScheduler.from_config(pipe.scheduler.config ) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """a bowl of fruit""" __SCREAMING_SNAKE_CASE = """a bowl of pears""" __SCREAMING_SNAKE_CASE = pipe.generate_mask( image=self.raw_image , source_prompt=__SCREAMING_SNAKE_CASE , target_prompt=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , ) __SCREAMING_SNAKE_CASE = pipe.invert( prompt=__SCREAMING_SNAKE_CASE , image=self.raw_image , inpaint_strength=0.7 , generator=__SCREAMING_SNAKE_CASE ).latents __SCREAMING_SNAKE_CASE = pipe( prompt=__SCREAMING_SNAKE_CASE , mask_image=__SCREAMING_SNAKE_CASE , image_latents=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , negative_prompt=__SCREAMING_SNAKE_CASE , inpaint_strength=0.7 , output_type="""numpy""" , ).images[0] __SCREAMING_SNAKE_CASE = ( np.array( load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/diffedit/pears.png""" ).resize((768, 768) ) ) / 255 ) assert np.abs((expected_image - image).max() ) < 5E-1 def UpperCAmelCase__ ( self : Optional[int] ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = StableDiffusionDiffEditPipeline.from_pretrained( """stabilityai/stable-diffusion-2-1""" , safety_checker=__SCREAMING_SNAKE_CASE , torch_dtype=torch.floataa ) __SCREAMING_SNAKE_CASE = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) __SCREAMING_SNAKE_CASE = DPMSolverMultistepInverseScheduler.from_config(pipe.scheduler.config ) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """a bowl of fruit""" __SCREAMING_SNAKE_CASE = """a bowl of pears""" __SCREAMING_SNAKE_CASE = pipe.generate_mask( image=self.raw_image , source_prompt=__SCREAMING_SNAKE_CASE , target_prompt=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , ) __SCREAMING_SNAKE_CASE = pipe.invert( prompt=__SCREAMING_SNAKE_CASE , image=self.raw_image , inpaint_strength=0.7 , generator=__SCREAMING_SNAKE_CASE , num_inference_steps=25 , ).latents __SCREAMING_SNAKE_CASE = pipe( prompt=__SCREAMING_SNAKE_CASE , mask_image=__SCREAMING_SNAKE_CASE , image_latents=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , negative_prompt=__SCREAMING_SNAKE_CASE , inpaint_strength=0.7 , num_inference_steps=25 , output_type="""numpy""" , ).images[0] __SCREAMING_SNAKE_CASE = ( np.array( load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/diffedit/pears.png""" ).resize((768, 768) ) ) / 255 ) assert np.abs((expected_image - image).max() ) < 5E-1
267
'''simple docstring''' import numpy as np def a__ ( a__ , a__ , a__ = 1E-1_2 , a__ = 1_00 , ): """simple docstring""" assert np.shape(a__ )[0] == np.shape(a__ )[1] # Ensure proper dimensionality. assert np.shape(a__ )[0] == np.shape(a__ )[0] # Ensure inputs are either both complex or both real assert np.iscomplexobj(a__ ) == np.iscomplexobj(a__ ) __SCREAMING_SNAKE_CASE = np.iscomplexobj(a__ ) if is_complex: # Ensure complex input_matrix is Hermitian assert np.array_equal(a__ , input_matrix.conj().T ) # Set convergence to False. Will define convergence when we exceed max_iterations # or when we have small changes from one iteration to next. __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 1E1_2 while not convergence: # Multiple matrix by the vector. __SCREAMING_SNAKE_CASE = np.dot(a__ , a__ ) # Normalize the resulting output vector. __SCREAMING_SNAKE_CASE = w / np.linalg.norm(a__ ) # Find rayleigh quotient # (faster than usual b/c we know vector is normalized already) __SCREAMING_SNAKE_CASE = vector.conj().T if is_complex else vector.T __SCREAMING_SNAKE_CASE = np.dot(a__ , np.dot(a__ , a__ ) ) # Check convergence. __SCREAMING_SNAKE_CASE = np.abs(lambda_ - lambda_previous ) / lambda_ iterations += 1 if error <= error_tol or iterations >= max_iterations: __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = lambda_ if is_complex: __SCREAMING_SNAKE_CASE = np.real(lambda_ ) return lambda_, vector def a__ ( ): """simple docstring""" __SCREAMING_SNAKE_CASE = np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]] ) __SCREAMING_SNAKE_CASE = np.array([41, 4, 20] ) __SCREAMING_SNAKE_CASE = real_input_matrix.astype(np.complexaaa ) __SCREAMING_SNAKE_CASE = np.triu(1J * complex_input_matrix , 1 ) complex_input_matrix += imag_matrix complex_input_matrix += -1 * imag_matrix.T __SCREAMING_SNAKE_CASE = np.array([41, 4, 20] ).astype(np.complexaaa ) for problem_type in ["real", "complex"]: if problem_type == "real": __SCREAMING_SNAKE_CASE = real_input_matrix __SCREAMING_SNAKE_CASE = real_vector elif problem_type == "complex": __SCREAMING_SNAKE_CASE = complex_input_matrix __SCREAMING_SNAKE_CASE = complex_vector # Our implementation. __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = power_iteration(a__ , a__ ) # Numpy implementation. # Get eigenvalues and eigenvectors using built-in numpy # eigh (eigh used for symmetric or hermetian matrices). __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = np.linalg.eigh(a__ ) # Last eigenvalue is the maximum one. __SCREAMING_SNAKE_CASE = eigen_values[-1] # Last column in this matrix is eigenvector corresponding to largest eigenvalue. __SCREAMING_SNAKE_CASE = eigen_vectors[:, -1] # Check our implementation and numpy gives close answers. assert np.abs(eigen_value - eigen_value_max ) <= 1E-6 # Take absolute values element wise of each eigenvector. # as they are only unique to a minus sign. assert np.linalg.norm(np.abs(a__ ) - np.abs(a__ ) ) <= 1E-6 if __name__ == "__main__": import doctest doctest.testmod() test_power_iteration()
267
1
'''simple docstring''' from heapq import heappop, heappush import numpy as np def a__ ( a__ , a__ , a__ , a__ , ): """simple docstring""" __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = grid.shape __SCREAMING_SNAKE_CASE = [-1, 1, 0, 0] __SCREAMING_SNAKE_CASE = [0, 0, -1, 1] if allow_diagonal: dx += [-1, -1, 1, 1] dy += [-1, 1, -1, 1] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = [(0, source)], set() __SCREAMING_SNAKE_CASE = np.full((rows, cols) , np.inf ) __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = np.empty((rows, cols) , dtype=a__ ) __SCREAMING_SNAKE_CASE = None while queue: ((__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE)) = heappop(a__ ) if (x, y) in visited: continue visited.add((x, y) ) if (x, y) == destination: __SCREAMING_SNAKE_CASE = [] while (x, y) != source: path.append((x, y) ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = predecessors[x, y] path.append(a__ ) # add the source manually path.reverse() return matrix[destination], path for i in range(len(a__ ) ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = x + dx[i], y + dy[i] if 0 <= nx < rows and 0 <= ny < cols: __SCREAMING_SNAKE_CASE = grid[nx][ny] if next_node == 1 and matrix[nx, ny] > dist + 1: heappush(a__ , (dist + 1, (nx, ny)) ) __SCREAMING_SNAKE_CASE = dist + 1 __SCREAMING_SNAKE_CASE = (x, y) return np.inf, [] if __name__ == "__main__": import doctest doctest.testmod()
267
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowerCAmelCase__ ( a , a , a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = StableDiffusionInpaintPipeline lowerCAmelCase__ = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS lowerCAmelCase__ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS lowerCAmelCase__ = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess lowerCAmelCase__ = frozenset([] ) def UpperCAmelCase__ ( self : str ) -> List[Any]: """simple docstring""" torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=9 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=__SCREAMING_SNAKE_CASE , ) __SCREAMING_SNAKE_CASE = PNDMScheduler(skip_prk_steps=__SCREAMING_SNAKE_CASE ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act="""gelu""" , projection_dim=512 , ) __SCREAMING_SNAKE_CASE = CLIPTextModel(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) __SCREAMING_SNAKE_CASE = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def UpperCAmelCase__ ( self : Any , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : List[Any]=0 ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = floats_tensor((1, 3, 32, 32) , rng=random.Random(__SCREAMING_SNAKE_CASE ) ).to(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1 )[0] __SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(__SCREAMING_SNAKE_CASE ) ).convert("""RGB""" ).resize((64, 64) ) __SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(image + 4 ) ).convert("""RGB""" ).resize((64, 64) ) if str(__SCREAMING_SNAKE_CASE ).startswith("""mps""" ): __SCREAMING_SNAKE_CASE = torch.manual_seed(__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = torch.Generator(device=__SCREAMING_SNAKE_CASE ).manual_seed(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = { """prompt""": """A painting of a squirrel eating a burger""", """image""": init_image, """mask_image""": mask_image, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def UpperCAmelCase__ ( self : Union[str, Any] ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = """cpu""" # ensure determinism for the device-dependent torch.Generator __SCREAMING_SNAKE_CASE = self.get_dummy_components() __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = sd_pipe.to(__SCREAMING_SNAKE_CASE ) sd_pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.get_dummy_inputs(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = sd_pipe(**__SCREAMING_SNAKE_CASE ).images __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __SCREAMING_SNAKE_CASE = np.array([0.4727, 0.5735, 0.3941, 0.5446, 0.5926, 0.4394, 0.5062, 0.4654, 0.4476] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def UpperCAmelCase__ ( self : Tuple ) -> str: """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : List[Any] ) -> str: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase__ ( self : List[str] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) __SCREAMING_SNAKE_CASE = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench.npy""" ) __SCREAMING_SNAKE_CASE = """stabilityai/stable-diffusion-2-inpainting""" __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline.from_pretrained(__SCREAMING_SNAKE_CASE , safety_checker=__SCREAMING_SNAKE_CASE ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) pipe.enable_attention_slicing() __SCREAMING_SNAKE_CASE = """Face of a yellow cat, high resolution, sitting on a park bench""" __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , mask_image=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , output_type="""np""" , ) __SCREAMING_SNAKE_CASE = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 9E-3 def UpperCAmelCase__ ( self : List[Any] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) __SCREAMING_SNAKE_CASE = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench_fp16.npy""" ) __SCREAMING_SNAKE_CASE = """stabilityai/stable-diffusion-2-inpainting""" __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline.from_pretrained( __SCREAMING_SNAKE_CASE , torch_dtype=torch.floataa , safety_checker=__SCREAMING_SNAKE_CASE , ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) pipe.enable_attention_slicing() __SCREAMING_SNAKE_CASE = """Face of a yellow cat, high resolution, sitting on a park bench""" __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , mask_image=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , output_type="""np""" , ) __SCREAMING_SNAKE_CASE = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 5E-1 def UpperCAmelCase__ ( self : Tuple ) -> Any: """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) __SCREAMING_SNAKE_CASE = """stabilityai/stable-diffusion-2-inpainting""" __SCREAMING_SNAKE_CASE = PNDMScheduler.from_pretrained(__SCREAMING_SNAKE_CASE , subfolder="""scheduler""" ) __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline.from_pretrained( __SCREAMING_SNAKE_CASE , safety_checker=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE , torch_dtype=torch.floataa , ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() __SCREAMING_SNAKE_CASE = """Face of a yellow cat, high resolution, sitting on a park bench""" __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , mask_image=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , num_inference_steps=2 , output_type="""np""" , ) __SCREAMING_SNAKE_CASE = torch.cuda.max_memory_allocated() # make sure that less than 2.65 GB is allocated assert mem_bytes < 2.65 * 10**9
267
1
'''simple docstring''' from __future__ import annotations from sys import maxsize from typing import Generic, TypeVar UpperCAmelCase : Tuple = TypeVar('T') def a__ ( a__ ): """simple docstring""" return (position - 1) // 2 def a__ ( a__ ): """simple docstring""" return (2 * position) + 1 def a__ ( a__ ): """simple docstring""" return (2 * position) + 2 class lowerCAmelCase__ ( Generic[T] ): """simple docstring""" def __init__( self : Union[str, Any] ) -> None: """simple docstring""" __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = 0 def __len__( self : Optional[int] ) -> int: """simple docstring""" return self.elements def __repr__( self : Optional[Any] ) -> str: """simple docstring""" return str(self.heap ) def UpperCAmelCase__ ( self : int ) -> bool: """simple docstring""" return self.elements == 0 def UpperCAmelCase__ ( self : List[str] , __SCREAMING_SNAKE_CASE : T , __SCREAMING_SNAKE_CASE : int ) -> None: """simple docstring""" self.heap.append((elem, weight) ) __SCREAMING_SNAKE_CASE = self.elements self.elements += 1 self._bubble_up(__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Tuple ) -> T: """simple docstring""" if self.elements > 1: self._swap_nodes(0 , self.elements - 1 ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.heap.pop() del self.position_map[elem] self.elements -= 1 if self.elements > 0: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.heap[0] self._bubble_down(__SCREAMING_SNAKE_CASE ) return elem def UpperCAmelCase__ ( self : int , __SCREAMING_SNAKE_CASE : T , __SCREAMING_SNAKE_CASE : int ) -> None: """simple docstring""" __SCREAMING_SNAKE_CASE = self.position_map[elem] __SCREAMING_SNAKE_CASE = (elem, weight) if position > 0: __SCREAMING_SNAKE_CASE = get_parent_position(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.heap[parent_position] if parent_weight > weight: self._bubble_up(__SCREAMING_SNAKE_CASE ) else: self._bubble_down(__SCREAMING_SNAKE_CASE ) else: self._bubble_down(__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Tuple , __SCREAMING_SNAKE_CASE : T ) -> None: """simple docstring""" __SCREAMING_SNAKE_CASE = self.position_map[elem] if curr_pos == 0: return None __SCREAMING_SNAKE_CASE = get_parent_position(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.heap[curr_pos] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.heap[parent_position] if parent_weight > weight: self._swap_nodes(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) return self._bubble_up(__SCREAMING_SNAKE_CASE ) return None def UpperCAmelCase__ ( self : int , __SCREAMING_SNAKE_CASE : T ) -> None: """simple docstring""" __SCREAMING_SNAKE_CASE = self.position_map[elem] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.heap[curr_pos] __SCREAMING_SNAKE_CASE = get_child_left_position(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = get_child_right_position(__SCREAMING_SNAKE_CASE ) if child_left_position < self.elements and child_right_position < self.elements: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.heap[child_left_position] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.heap[child_right_position] if child_right_weight < child_left_weight and child_right_weight < weight: self._swap_nodes(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) return self._bubble_down(__SCREAMING_SNAKE_CASE ) if child_left_position < self.elements: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.heap[child_left_position] if child_left_weight < weight: self._swap_nodes(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) return self._bubble_down(__SCREAMING_SNAKE_CASE ) else: return None if child_right_position < self.elements: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.heap[child_right_position] if child_right_weight < weight: self._swap_nodes(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) return self._bubble_down(__SCREAMING_SNAKE_CASE ) return None def UpperCAmelCase__ ( self : Any , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : int ) -> None: """simple docstring""" __SCREAMING_SNAKE_CASE = self.heap[nodea_pos][0] __SCREAMING_SNAKE_CASE = self.heap[nodea_pos][0] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = ( self.heap[nodea_pos], self.heap[nodea_pos], ) __SCREAMING_SNAKE_CASE = nodea_pos __SCREAMING_SNAKE_CASE = nodea_pos class lowerCAmelCase__ ( Generic[T] ): """simple docstring""" def __init__( self : Optional[Any] ) -> None: """simple docstring""" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = 0 def __repr__( self : Tuple ) -> str: """simple docstring""" return str(self.connections ) def __len__( self : Union[str, Any] ) -> int: """simple docstring""" return self.nodes def UpperCAmelCase__ ( self : Tuple , __SCREAMING_SNAKE_CASE : T ) -> None: """simple docstring""" if node not in self.connections: __SCREAMING_SNAKE_CASE = {} self.nodes += 1 def UpperCAmelCase__ ( self : str , __SCREAMING_SNAKE_CASE : T , __SCREAMING_SNAKE_CASE : T , __SCREAMING_SNAKE_CASE : int ) -> None: """simple docstring""" self.add_node(__SCREAMING_SNAKE_CASE ) self.add_node(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = weight __SCREAMING_SNAKE_CASE = weight def a__ ( a__ , ): """simple docstring""" __SCREAMING_SNAKE_CASE = {node: maxsize for node in graph.connections} __SCREAMING_SNAKE_CASE = {node: None for node in graph.connections} __SCREAMING_SNAKE_CASE = MinPriorityQueue() for node, weight in dist.items(): priority_queue.push(a__ , a__ ) if priority_queue.is_empty(): return dist, parent # initialization __SCREAMING_SNAKE_CASE = priority_queue.extract_min() __SCREAMING_SNAKE_CASE = 0 for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: __SCREAMING_SNAKE_CASE = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(a__ , dist[neighbour] ) __SCREAMING_SNAKE_CASE = node # running prim's algorithm while not priority_queue.is_empty(): __SCREAMING_SNAKE_CASE = priority_queue.extract_min() for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: __SCREAMING_SNAKE_CASE = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(a__ , dist[neighbour] ) __SCREAMING_SNAKE_CASE = node return dist, parent
267
'''simple docstring''' from itertools import count def a__ ( a__ = 50 ): """simple docstring""" __SCREAMING_SNAKE_CASE = [1] * min_block_length for n in count(a__ ): fill_count_functions.append(1 ) for block_length in range(a__ , n + 1 ): for block_start in range(n - block_length ): fill_count_functions[n] += fill_count_functions[ n - block_start - block_length - 1 ] fill_count_functions[n] += 1 if fill_count_functions[n] > 1_00_00_00: break return n if __name__ == "__main__": print(f"""{solution() = }""")
267
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available UpperCAmelCase : List[str] = { 'configuration_mobilenet_v2': [ 'MOBILENET_V2_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MobileNetV2Config', 'MobileNetV2OnnxConfig', ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Dict = ['MobileNetV2FeatureExtractor'] UpperCAmelCase : Dict = ['MobileNetV2ImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Any = [ 'MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST', 'MobileNetV2ForImageClassification', 'MobileNetV2ForSemanticSegmentation', 'MobileNetV2Model', 'MobileNetV2PreTrainedModel', 'load_tf_weights_in_mobilenet_v2', ] if TYPE_CHECKING: from .configuration_mobilenet_va import ( MOBILENET_V2_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileNetVaConfig, MobileNetVaOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_mobilenet_va import MobileNetVaFeatureExtractor from .image_processing_mobilenet_va import MobileNetVaImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mobilenet_va import ( MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation, MobileNetVaModel, MobileNetVaPreTrainedModel, load_tf_weights_in_mobilenet_va, ) else: import sys UpperCAmelCase : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
267
'''simple docstring''' import logging import os import threading import time try: import warnings except ImportError: UpperCAmelCase : Optional[Any] = None try: import msvcrt except ImportError: UpperCAmelCase : List[Any] = None try: import fcntl except ImportError: UpperCAmelCase : int = None # Backward compatibility # ------------------------------------------------ try: TimeoutError except NameError: UpperCAmelCase : Union[str, Any] = OSError # Data # ------------------------------------------------ UpperCAmelCase : List[Any] = [ 'Timeout', 'BaseFileLock', 'WindowsFileLock', 'UnixFileLock', 'SoftFileLock', 'FileLock', ] UpperCAmelCase : Tuple = '3.0.12' UpperCAmelCase : str = None def a__ ( ): """simple docstring""" global _logger __SCREAMING_SNAKE_CASE = _logger or logging.getLogger(__name__ ) return _logger class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Any , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = lock_file return None def __str__( self : str ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = f'The file lock \'{self.lock_file}\' could not be acquired.' return temp class lowerCAmelCase__ : """simple docstring""" def __init__( self : Tuple , __SCREAMING_SNAKE_CASE : List[Any] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = lock return None def __enter__( self : List[str] ) -> List[Any]: """simple docstring""" return self.lock def __exit__( self : Tuple , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> List[str]: """simple docstring""" self.lock.release() return None class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : str=-1 , __SCREAMING_SNAKE_CASE : Optional[Any]=None ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = max_filename_length if max_filename_length is not None else 255 # Hash the filename if it's too long __SCREAMING_SNAKE_CASE = self.hash_filename_if_too_long(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # The path to the lock file. __SCREAMING_SNAKE_CASE = lock_file # The file descriptor for the *_lock_file* as it is returned by the # os.open() function. # This file lock is only NOT None, if the object currently holds the # lock. __SCREAMING_SNAKE_CASE = None # The default timeout value. __SCREAMING_SNAKE_CASE = timeout # We use this lock primarily for the lock counter. __SCREAMING_SNAKE_CASE = threading.Lock() # The lock counter is used for implementing the nested locking # mechanism. Whenever the lock is acquired, the counter is increased and # the lock is only released, when this value is 0 again. __SCREAMING_SNAKE_CASE = 0 return None @property def UpperCAmelCase__ ( self : List[Any] ) -> List[str]: """simple docstring""" return self._lock_file @property def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" return self._timeout @timeout.setter def UpperCAmelCase__ ( self : List[str] , __SCREAMING_SNAKE_CASE : Dict ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = float(__SCREAMING_SNAKE_CASE ) return None def UpperCAmelCase__ ( self : Optional[Any] ) -> List[Any]: """simple docstring""" raise NotImplementedError() def UpperCAmelCase__ ( self : Union[str, Any] ) -> Any: """simple docstring""" raise NotImplementedError() @property def UpperCAmelCase__ ( self : Union[str, Any] ) -> int: """simple docstring""" return self._lock_file_fd is not None def UpperCAmelCase__ ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[Any]=None , __SCREAMING_SNAKE_CASE : Optional[int]=0.05 ) -> Optional[Any]: """simple docstring""" if timeout is None: __SCREAMING_SNAKE_CASE = self.timeout # Increment the number right at the beginning. # We can still undo it, if something fails. with self._thread_lock: self._lock_counter += 1 __SCREAMING_SNAKE_CASE = id(self ) __SCREAMING_SNAKE_CASE = self._lock_file __SCREAMING_SNAKE_CASE = time.time() try: while True: with self._thread_lock: if not self.is_locked: logger().debug(f'Attempting to acquire lock {lock_id} on {lock_filename}' ) self._acquire() if self.is_locked: logger().debug(f'Lock {lock_id} acquired on {lock_filename}' ) break elif timeout >= 0 and time.time() - start_time > timeout: logger().debug(f'Timeout on acquiring lock {lock_id} on {lock_filename}' ) raise Timeout(self._lock_file ) else: logger().debug( f'Lock {lock_id} not acquired on {lock_filename}, waiting {poll_intervall} seconds ...' ) time.sleep(__SCREAMING_SNAKE_CASE ) except: # noqa # Something did go wrong, so decrement the counter. with self._thread_lock: __SCREAMING_SNAKE_CASE = max(0 , self._lock_counter - 1 ) raise return _Acquire_ReturnProxy(lock=self ) def UpperCAmelCase__ ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[Any]=False ) -> Dict: """simple docstring""" with self._thread_lock: if self.is_locked: self._lock_counter -= 1 if self._lock_counter == 0 or force: __SCREAMING_SNAKE_CASE = id(self ) __SCREAMING_SNAKE_CASE = self._lock_file logger().debug(f'Attempting to release lock {lock_id} on {lock_filename}' ) self._release() __SCREAMING_SNAKE_CASE = 0 logger().debug(f'Lock {lock_id} released on {lock_filename}' ) return None def __enter__( self : Union[str, Any] ) -> Optional[int]: """simple docstring""" self.acquire() return self def __exit__( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Any ) -> Tuple: """simple docstring""" self.release() return None def __del__( self : str ) -> Union[str, Any]: """simple docstring""" self.release(force=__SCREAMING_SNAKE_CASE ) return None def UpperCAmelCase__ ( self : Optional[int] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : int ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = os.path.basename(__SCREAMING_SNAKE_CASE ) if len(__SCREAMING_SNAKE_CASE ) > max_length and max_length > 0: __SCREAMING_SNAKE_CASE = os.path.dirname(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = str(hash(__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = filename[: max_length - len(__SCREAMING_SNAKE_CASE ) - 8] + """...""" + hashed_filename + """.lock""" return os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else: return path class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Tuple , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Dict=-1 , __SCREAMING_SNAKE_CASE : Dict=None ) -> List[Any]: """simple docstring""" from .file_utils import relative_to_absolute_path super().__init__(__SCREAMING_SNAKE_CASE , timeout=__SCREAMING_SNAKE_CASE , max_filename_length=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """\\\\?\\""" + relative_to_absolute_path(self.lock_file ) def UpperCAmelCase__ ( self : Dict ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = os.O_RDWR | os.O_CREAT | os.O_TRUNC try: __SCREAMING_SNAKE_CASE = os.open(self._lock_file , __SCREAMING_SNAKE_CASE ) except OSError: pass else: try: msvcrt.locking(__SCREAMING_SNAKE_CASE , msvcrt.LK_NBLCK , 1 ) except OSError: os.close(__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = fd return None def UpperCAmelCase__ ( self : Tuple ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self._lock_file_fd __SCREAMING_SNAKE_CASE = None msvcrt.locking(__SCREAMING_SNAKE_CASE , msvcrt.LK_UNLCK , 1 ) os.close(__SCREAMING_SNAKE_CASE ) try: os.remove(self._lock_file ) # Probably another instance of the application # that acquired the file lock. except OSError: pass return None class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Union[str, Any]=-1 , __SCREAMING_SNAKE_CASE : Optional[Any]=None ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = os.statvfs(os.path.dirname(__SCREAMING_SNAKE_CASE ) ).f_namemax super().__init__(__SCREAMING_SNAKE_CASE , timeout=__SCREAMING_SNAKE_CASE , max_filename_length=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = os.O_RDWR | os.O_CREAT | os.O_TRUNC __SCREAMING_SNAKE_CASE = os.open(self._lock_file , __SCREAMING_SNAKE_CASE ) try: fcntl.flock(__SCREAMING_SNAKE_CASE , fcntl.LOCK_EX | fcntl.LOCK_NB ) except OSError: os.close(__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = fd return None def UpperCAmelCase__ ( self : List[Any] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = self._lock_file_fd __SCREAMING_SNAKE_CASE = None fcntl.flock(__SCREAMING_SNAKE_CASE , fcntl.LOCK_UN ) os.close(__SCREAMING_SNAKE_CASE ) return None class lowerCAmelCase__ ( a ): """simple docstring""" def UpperCAmelCase__ ( self : List[str] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC try: __SCREAMING_SNAKE_CASE = os.open(self._lock_file , __SCREAMING_SNAKE_CASE ) except OSError: pass else: __SCREAMING_SNAKE_CASE = fd return None def UpperCAmelCase__ ( self : int ) -> Optional[int]: """simple docstring""" os.close(self._lock_file_fd ) __SCREAMING_SNAKE_CASE = None try: os.remove(self._lock_file ) # The file is already deleted and that's what we want. except OSError: pass return None UpperCAmelCase : Dict = None if msvcrt: UpperCAmelCase : Optional[int] = WindowsFileLock elif fcntl: UpperCAmelCase : Optional[Any] = UnixFileLock else: UpperCAmelCase : int = SoftFileLock if warnings is not None: warnings.warn('only soft file lock is available')
267
1
'''simple docstring''' import itertools import string from collections.abc import Generator, Iterable def a__ ( a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = iter(a__ ) while True: __SCREAMING_SNAKE_CASE = tuple(itertools.islice(a__ , a__ ) ) if not chunk: return yield chunk def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = """""".join([c.upper() for c in dirty if c in string.ascii_letters] ) __SCREAMING_SNAKE_CASE = """""" if len(a__ ) < 2: return dirty for i in range(len(a__ ) - 1 ): clean += dirty[i] if dirty[i] == dirty[i + 1]: clean += "X" clean += dirty[-1] if len(a__ ) & 1: clean += "X" return clean def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = """ABCDEFGHIKLMNOPQRSTUVWXYZ""" # we're using a list instead of a '2d' array because it makes the math # for setting up the table and doing the actual encoding/decoding simpler __SCREAMING_SNAKE_CASE = [] # copy key chars into the table if they are in `alphabet` ignoring duplicates for char in key.upper(): if char not in table and char in alphabet: table.append(a__ ) # fill the rest of the table in with the remaining alphabet chars for char in alphabet: if char not in table: table.append(a__ ) return table def a__ ( a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = generate_table(a__ ) __SCREAMING_SNAKE_CASE = prepare_input(a__ ) __SCREAMING_SNAKE_CASE = """""" # https://en.wikipedia.org/wiki/Playfair_cipher#Description for chara, chara in chunker(a__ , 2 ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = divmod(table.index(a__ ) , 5 ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = divmod(table.index(a__ ) , 5 ) if rowa == rowa: ciphertext += table[rowa * 5 + (cola + 1) % 5] ciphertext += table[rowa * 5 + (cola + 1) % 5] elif cola == cola: ciphertext += table[((rowa + 1) % 5) * 5 + cola] ciphertext += table[((rowa + 1) % 5) * 5 + cola] else: # rectangle ciphertext += table[rowa * 5 + cola] ciphertext += table[rowa * 5 + cola] return ciphertext def a__ ( a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = generate_table(a__ ) __SCREAMING_SNAKE_CASE = """""" # https://en.wikipedia.org/wiki/Playfair_cipher#Description for chara, chara in chunker(a__ , 2 ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = divmod(table.index(a__ ) , 5 ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = divmod(table.index(a__ ) , 5 ) if rowa == rowa: plaintext += table[rowa * 5 + (cola - 1) % 5] plaintext += table[rowa * 5 + (cola - 1) % 5] elif cola == cola: plaintext += table[((rowa - 1) % 5) * 5 + cola] plaintext += table[((rowa - 1) % 5) * 5 + cola] else: # rectangle plaintext += table[rowa * 5 + cola] plaintext += table[rowa * 5 + cola] return plaintext
267
'''simple docstring''' import shutil import tempfile import unittest from transformers import ( SPIECE_UNDERLINE, AddedToken, BatchEncoding, NllbTokenizer, NllbTokenizerFast, is_torch_available, ) from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...test_tokenization_common import TokenizerTesterMixin UpperCAmelCase : Optional[int] = get_tests_dir('fixtures/test_sentencepiece.model') if is_torch_available(): from transformers.models.mam_aaa.modeling_mam_aaa import shift_tokens_right UpperCAmelCase : Optional[int] = 2_5_6_0_4_7 UpperCAmelCase : Union[str, Any] = 2_5_6_1_4_5 @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = NllbTokenizer lowerCAmelCase__ = NllbTokenizerFast lowerCAmelCase__ = True lowerCAmelCase__ = True lowerCAmelCase__ = {} def UpperCAmelCase__ ( self : List[Any] ) -> int: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing __SCREAMING_SNAKE_CASE = NllbTokenizer(__SCREAMING_SNAKE_CASE , keep_accents=__SCREAMING_SNAKE_CASE ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCAmelCase__ ( self : Dict ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = NllbTokenizer(__SCREAMING_SNAKE_CASE , keep_accents=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(__SCREAMING_SNAKE_CASE , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) __SCREAMING_SNAKE_CASE = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ 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""", """é""", """.""", ] , ) __SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ 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] ] , ) __SCREAMING_SNAKE_CASE = tokenizer.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ 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>""", """.""", ] , ) def UpperCAmelCase__ ( self : Dict ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = (self.rust_tokenizer_class, """hf-internal-testing/tiny-random-nllb""", {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) __SCREAMING_SNAKE_CASE = tuple(f for f in tokenizer_r_files if """tokenizer.json""" not in f ) self.assertSequenceEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Checks everything loads correctly in the same way __SCREAMING_SNAKE_CASE = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) # Save tokenizer rust, legacy_format=True __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE , legacy_format=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it save with the same files self.assertSequenceEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Checks everything loads correctly in the same way __SCREAMING_SNAKE_CASE = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) # Save tokenizer rust, legacy_format=False __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE , legacy_format=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it saved the tokenizer.json file self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way __SCREAMING_SNAKE_CASE = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) @require_torch def UpperCAmelCase__ ( self : List[Any] ) -> Any: """simple docstring""" if not self.test_seqaseq: return __SCREAMING_SNAKE_CASE = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): # Longer text that will definitely require truncation. __SCREAMING_SNAKE_CASE = [ """ UN Chief Says There Is No Military Solution in Syria""", """ Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for""" """ Syria is that 'there is no military solution' to the nearly five-year conflict and more weapons""" """ will only worsen the violence and misery for millions of people.""", ] __SCREAMING_SNAKE_CASE = [ """Şeful ONU declară că nu există o soluţie militară în Siria""", """Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al""" """ Rusiei pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi""" """ că noi arme nu vor face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.""", ] try: __SCREAMING_SNAKE_CASE = tokenizer.prepare_seqaseq_batch( src_texts=__SCREAMING_SNAKE_CASE , tgt_texts=__SCREAMING_SNAKE_CASE , max_length=3 , max_target_length=10 , return_tensors="""pt""" , src_lang="""eng_Latn""" , tgt_lang="""ron_Latn""" , ) except NotImplementedError: return self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.labels.shape[1] , 10 ) # max_target_length will default to max_length if not specified __SCREAMING_SNAKE_CASE = tokenizer.prepare_seqaseq_batch( __SCREAMING_SNAKE_CASE , tgt_texts=__SCREAMING_SNAKE_CASE , max_length=3 , return_tensors="""pt""" ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.labels.shape[1] , 3 ) __SCREAMING_SNAKE_CASE = tokenizer.prepare_seqaseq_batch( src_texts=__SCREAMING_SNAKE_CASE , max_length=3 , max_target_length=10 , return_tensors="""pt""" ) self.assertEqual(batch_encoder_only.input_ids.shape[1] , 3 ) self.assertEqual(batch_encoder_only.attention_mask.shape[1] , 3 ) self.assertNotIn("""decoder_input_ids""" , __SCREAMING_SNAKE_CASE ) @unittest.skip("""Unfortunately way too slow to build a BPE with SentencePiece.""" ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" pass def UpperCAmelCase__ ( self : List[str] ) -> Dict: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): __SCREAMING_SNAKE_CASE = [AddedToken("""<special>""" , lstrip=__SCREAMING_SNAKE_CASE )] __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_r.encode("""Hey this is a <special> token""" ) __SCREAMING_SNAKE_CASE = tokenizer_r.encode("""<special>""" , add_special_tokens=__SCREAMING_SNAKE_CASE )[0] self.assertTrue(special_token_id in r_output ) if self.test_slow_tokenizer: __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.encode("""Hey this is a <special> token""" ) __SCREAMING_SNAKE_CASE = tokenizer_cr.encode("""Hey this is a <special> token""" ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertTrue(special_token_id in p_output ) self.assertTrue(special_token_id in cr_output ) @require_torch @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = "facebook/nllb-200-distilled-600M" lowerCAmelCase__ = [ " UN Chief Says There Is No Military Solution in Syria", " Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for Syria is that \"there is no military solution\" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.", ] lowerCAmelCase__ = [ "Şeful ONU declară că nu există o soluţie militară în Siria", "Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei" " pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi că noi arme nu vor" " face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.", ] lowerCAmelCase__ = [ 256047, 16297, 134408, 8165, 248066, 14734, 950, 1135, 105721, 3573, 83, 27352, 108, 49486, 2, ] @classmethod def UpperCAmelCase__ ( cls : List[Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = NllbTokenizer.from_pretrained( cls.checkpoint_name , src_lang="""eng_Latn""" , tgt_lang="""ron_Latn""" ) __SCREAMING_SNAKE_CASE = 1 return cls def UpperCAmelCase__ ( self : Union[str, Any] ) -> List[str]: """simple docstring""" self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ace_Arab"""] , 256_001 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ace_Latn"""] , 256_002 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""fra_Latn"""] , 256_057 ) def UpperCAmelCase__ ( self : Optional[int] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Any ) -> int: """simple docstring""" self.assertIn(__SCREAMING_SNAKE_CASE , self.tokenizer.all_special_ids ) # fmt: off __SCREAMING_SNAKE_CASE = [RO_CODE, 4_254, 98_068, 112_923, 39_072, 3_909, 713, 102_767, 26, 17_314, 35_642, 14_683, 33_118, 2_022, 66_987, 2, 256_047] # fmt: on __SCREAMING_SNAKE_CASE = self.tokenizer.decode(__SCREAMING_SNAKE_CASE , skip_special_tokens=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertNotIn(self.tokenizer.eos_token , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = ["""this is gunna be a long sentence """ * 20] assert isinstance(src_text[0] , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = 10 __SCREAMING_SNAKE_CASE = self.tokenizer(__SCREAMING_SNAKE_CASE , max_length=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE ).input_ids[0] self.assertEqual(ids[-1] , 2 ) self.assertEqual(ids[0] , __SCREAMING_SNAKE_CASE ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : int ) -> List[Any]: """simple docstring""" self.assertListEqual(self.tokenizer.convert_tokens_to_ids(["""<mask>""", """ar_AR"""] ) , [256_203, 3] ) def UpperCAmelCase__ ( self : str ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = NllbTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , __SCREAMING_SNAKE_CASE ) @require_torch def UpperCAmelCase__ ( self : str ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=len(self.expected_src_tokens ) , return_tensors="""pt""" , ) __SCREAMING_SNAKE_CASE = shift_tokens_right( batch["""labels"""] , self.tokenizer.pad_token_id , self.tokenizer.lang_code_to_id["""ron_Latn"""] ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertEqual((2, 15) , batch.input_ids.shape ) self.assertEqual((2, 15) , batch.attention_mask.shape ) __SCREAMING_SNAKE_CASE = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , __SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , batch.decoder_input_ids[0, 0] ) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [EN_CODE] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer(self.src_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=3 , return_tensors="""pt""" ) __SCREAMING_SNAKE_CASE = self.tokenizer( text_target=self.tgt_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=10 , return_tensors="""pt""" ) __SCREAMING_SNAKE_CASE = targets["""input_ids"""] __SCREAMING_SNAKE_CASE = shift_tokens_right( __SCREAMING_SNAKE_CASE , self.tokenizer.pad_token_id , decoder_start_token_id=self.tokenizer.lang_code_to_id[self.tokenizer.tgt_lang] , ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 10 ) @require_torch def UpperCAmelCase__ ( self : int ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer._build_translation_inputs( """A test""" , return_tensors="""pt""" , src_lang="""eng_Latn""" , tgt_lang="""fra_Latn""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE ) , { # A, test, EOS, en_XX """input_ids""": [[256_047, 70, 7_356, 2]], """attention_mask""": [[1, 1, 1, 1]], # ar_AR """forced_bos_token_id""": 256_057, } , ) @require_torch def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = self.tokenizer( """UN Chief says there is no military solution in Syria""" , src_lang="""eng_Latn""" , tgt_lang="""fra_Latn""" ) self.assertEqual( inputs.input_ids , [16_297, 134_408, 25_653, 6_370, 248, 254, 103_929, 94_995, 108, 49_486, 2, 256_047] ) __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = self.tokenizer( """UN Chief says there is no military solution in Syria""" , src_lang="""eng_Latn""" , tgt_lang="""fra_Latn""" ) self.assertEqual( inputs.input_ids , [256_047, 16_297, 134_408, 25_653, 6_370, 248, 254, 103_929, 94_995, 108, 49_486, 2] )
267
1
'''simple docstring''' import doctest from collections import deque import numpy as np class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[str] ) -> None: """simple docstring""" __SCREAMING_SNAKE_CASE = [2, 1, 2, -1] __SCREAMING_SNAKE_CASE = [1, 2, 3, 4] def UpperCAmelCase__ ( self : Union[str, Any] ) -> list[float]: """simple docstring""" __SCREAMING_SNAKE_CASE = len(self.first_signal ) __SCREAMING_SNAKE_CASE = len(self.second_signal ) __SCREAMING_SNAKE_CASE = max(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # create a zero matrix of max_length x max_length __SCREAMING_SNAKE_CASE = [[0] * max_length for i in range(__SCREAMING_SNAKE_CASE )] # 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(__SCREAMING_SNAKE_CASE ): __SCREAMING_SNAKE_CASE = deque(self.second_signal ) rotated_signal.rotate(__SCREAMING_SNAKE_CASE ) for j, item in enumerate(__SCREAMING_SNAKE_CASE ): matrix[i][j] += item # multiply the matrix with the first signal __SCREAMING_SNAKE_CASE = np.matmul(np.transpose(__SCREAMING_SNAKE_CASE ) , np.transpose(self.first_signal ) ) # rounding-off to two decimal places return [round(__SCREAMING_SNAKE_CASE , 2 ) for i in final_signal] if __name__ == "__main__": doctest.testmod()
267
'''simple docstring''' import math from enum import Enum from typing import Optional, Union from torch.optim import Optimizer from torch.optim.lr_scheduler import LambdaLR from .utils import logging UpperCAmelCase : str = logging.get_logger(__name__) class lowerCAmelCase__ ( a ): """simple docstring""" lowerCAmelCase__ = "linear" lowerCAmelCase__ = "cosine" lowerCAmelCase__ = "cosine_with_restarts" lowerCAmelCase__ = "polynomial" lowerCAmelCase__ = "constant" lowerCAmelCase__ = "constant_with_warmup" lowerCAmelCase__ = "piecewise_constant" def a__ ( a__ , a__ = -1 ): """simple docstring""" return LambdaLR(a__ , lambda a__ : 1 , last_epoch=a__ ) def a__ ( a__ , a__ , a__ = -1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1.0 , a__ ) ) return 1.0 return LambdaLR(a__ , a__ , last_epoch=a__ ) def a__ ( a__ , a__ , a__ = -1 ): """simple docstring""" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = step_rules.split(""",""" ) for rule_str in rule_list[:-1]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = rule_str.split(""":""" ) __SCREAMING_SNAKE_CASE = int(a__ ) __SCREAMING_SNAKE_CASE = float(a__ ) __SCREAMING_SNAKE_CASE = value __SCREAMING_SNAKE_CASE = float(rule_list[-1] ) def create_rules_function(a__ , a__ ): def rule_func(a__ ) -> float: __SCREAMING_SNAKE_CASE = sorted(rules_dict.keys() ) for i, sorted_step in enumerate(a__ ): if steps < sorted_step: return rules_dict[sorted_steps[i]] return last_lr_multiple return rule_func __SCREAMING_SNAKE_CASE = create_rules_function(a__ , a__ ) return LambdaLR(a__ , a__ , last_epoch=a__ ) def a__ ( a__ , a__ , a__ , a__=-1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) return max( 0.0 , float(num_training_steps - current_step ) / float(max(1 , num_training_steps - num_warmup_steps ) ) ) return LambdaLR(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ , a__ = 0.5 , a__ = -1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) __SCREAMING_SNAKE_CASE = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * float(a__ ) * 2.0 * progress )) ) return LambdaLR(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ , a__ = 1 , a__ = -1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) __SCREAMING_SNAKE_CASE = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) if progress >= 1.0: return 0.0 return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * ((float(a__ ) * progress) % 1.0) )) ) return LambdaLR(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ , a__=1E-7 , a__=1.0 , a__=-1 ): """simple docstring""" __SCREAMING_SNAKE_CASE = optimizer.defaults["""lr"""] if not (lr_init > lr_end): raise ValueError(F'lr_end ({lr_end}) must be be smaller than initial lr ({lr_init})' ) def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) elif current_step > num_training_steps: return lr_end / lr_init # as LambdaLR multiplies by lr_init else: __SCREAMING_SNAKE_CASE = lr_init - lr_end __SCREAMING_SNAKE_CASE = num_training_steps - num_warmup_steps __SCREAMING_SNAKE_CASE = 1 - (current_step - num_warmup_steps) / decay_steps __SCREAMING_SNAKE_CASE = lr_range * pct_remaining**power + lr_end return decay / lr_init # as LambdaLR multiplies by lr_init return LambdaLR(a__ , a__ , a__ ) UpperCAmelCase : Optional[Any] = { SchedulerType.LINEAR: get_linear_schedule_with_warmup, SchedulerType.COSINE: get_cosine_schedule_with_warmup, SchedulerType.COSINE_WITH_RESTARTS: get_cosine_with_hard_restarts_schedule_with_warmup, SchedulerType.POLYNOMIAL: get_polynomial_decay_schedule_with_warmup, SchedulerType.CONSTANT: get_constant_schedule, SchedulerType.CONSTANT_WITH_WARMUP: get_constant_schedule_with_warmup, SchedulerType.PIECEWISE_CONSTANT: get_piecewise_constant_schedule, } def a__ ( a__ , a__ , a__ = None , a__ = None , a__ = None , a__ = 1 , a__ = 1.0 , a__ = -1 , ): """simple docstring""" __SCREAMING_SNAKE_CASE = SchedulerType(a__ ) __SCREAMING_SNAKE_CASE = TYPE_TO_SCHEDULER_FUNCTION[name] if name == SchedulerType.CONSTANT: return schedule_func(a__ , last_epoch=a__ ) if name == SchedulerType.PIECEWISE_CONSTANT: return schedule_func(a__ , step_rules=a__ , last_epoch=a__ ) # All other schedulers require `num_warmup_steps` if num_warmup_steps is None: raise ValueError(F'{name} requires `num_warmup_steps`, please provide that argument.' ) if name == SchedulerType.CONSTANT_WITH_WARMUP: return schedule_func(a__ , num_warmup_steps=a__ , last_epoch=a__ ) # All other schedulers require `num_training_steps` if num_training_steps is None: raise ValueError(F'{name} requires `num_training_steps`, please provide that argument.' ) if name == SchedulerType.COSINE_WITH_RESTARTS: return schedule_func( a__ , num_warmup_steps=a__ , num_training_steps=a__ , num_cycles=a__ , last_epoch=a__ , ) if name == SchedulerType.POLYNOMIAL: return schedule_func( a__ , num_warmup_steps=a__ , num_training_steps=a__ , power=a__ , last_epoch=a__ , ) return schedule_func( a__ , num_warmup_steps=a__ , num_training_steps=a__ , last_epoch=a__ )
267
1
'''simple docstring''' import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionTextToImagePipeline from diffusers.utils.testing_utils import nightly, require_torch_gpu, torch_device UpperCAmelCase : str = False class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" pass @nightly @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : Union[str, Any] ) -> str: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase__ ( self : Any ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = VersatileDiffusionTextToImagePipeline.from_pretrained("""shi-labs/versatile-diffusion""" ) # remove text_unet pipe.remove_unused_weights() pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """A painting of a squirrel eating a burger """ __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( prompt=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , guidance_scale=7.5 , num_inference_steps=2 , output_type="""numpy""" ).images with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = VersatileDiffusionTextToImagePipeline.from_pretrained(__SCREAMING_SNAKE_CASE ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = generator.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( prompt=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , guidance_scale=7.5 , num_inference_steps=2 , output_type="""numpy""" ).images assert np.abs(image - new_image ).sum() < 1E-5, "Models don't have the same forward pass" def UpperCAmelCase__ ( self : Tuple ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = VersatileDiffusionTextToImagePipeline.from_pretrained( """shi-labs/versatile-diffusion""" , torch_dtype=torch.floataa ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """A painting of a squirrel eating a burger """ __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( prompt=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , guidance_scale=7.5 , num_inference_steps=50 , output_type="""numpy""" ).images __SCREAMING_SNAKE_CASE = image[0, 253:256, 253:256, -1] assert image.shape == (1, 512, 512, 3) __SCREAMING_SNAKE_CASE = np.array([0.3367, 0.3169, 0.2656, 0.3870, 0.4790, 0.3796, 0.4009, 0.4878, 0.4778] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
267
'''simple docstring''' import argparse import os from . import ( ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, BART_PRETRAINED_MODEL_ARCHIVE_LIST, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, AlbertConfig, BartConfig, BertConfig, CamembertConfig, CTRLConfig, DistilBertConfig, DPRConfig, ElectraConfig, FlaubertConfig, GPTaConfig, LayoutLMConfig, LxmertConfig, OpenAIGPTConfig, RobertaConfig, TaConfig, TFAlbertForPreTraining, TFBartForConditionalGeneration, TFBartForSequenceClassification, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFCamembertForMaskedLM, TFCTRLLMHeadModel, TFDistilBertForMaskedLM, TFDistilBertForQuestionAnswering, TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, TFElectraForPreTraining, TFFlaubertWithLMHeadModel, TFGPTaLMHeadModel, TFLayoutLMForMaskedLM, TFLxmertForPreTraining, TFLxmertVisualFeatureEncoder, TFOpenAIGPTLMHeadModel, TFRobertaForCausalLM, TFRobertaForMaskedLM, TFRobertaForSequenceClassification, TFTaForConditionalGeneration, TFTransfoXLLMHeadModel, TFWavaVecaModel, TFXLMRobertaForMaskedLM, TFXLMWithLMHeadModel, TFXLNetLMHeadModel, TransfoXLConfig, WavaVecaConfig, WavaVecaModel, XLMConfig, XLMRobertaConfig, XLNetConfig, is_torch_available, load_pytorch_checkpoint_in_tfa_model, ) from .utils import CONFIG_NAME, WEIGHTS_NAME, cached_file, logging if is_torch_available(): import numpy as np import torch from . import ( AlbertForPreTraining, BartForConditionalGeneration, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, CamembertForMaskedLM, CTRLLMHeadModel, DistilBertForMaskedLM, DistilBertForQuestionAnswering, DPRContextEncoder, DPRQuestionEncoder, DPRReader, ElectraForPreTraining, FlaubertWithLMHeadModel, GPTaLMHeadModel, LayoutLMForMaskedLM, LxmertForPreTraining, LxmertVisualFeatureEncoder, OpenAIGPTLMHeadModel, RobertaForMaskedLM, RobertaForSequenceClassification, TaForConditionalGeneration, TransfoXLLMHeadModel, XLMRobertaForMaskedLM, XLMWithLMHeadModel, XLNetLMHeadModel, ) logging.set_verbosity_info() UpperCAmelCase : Tuple = { 'bart': ( BartConfig, TFBartForConditionalGeneration, TFBartForSequenceClassification, BartForConditionalGeneration, BART_PRETRAINED_MODEL_ARCHIVE_LIST, ), 'bert': ( BertConfig, TFBertForPreTraining, BertForPreTraining, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'bert-large-uncased-whole-word-masking-finetuned-squad': ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'bert-large-cased-whole-word-masking-finetuned-squad': ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'bert-base-cased-finetuned-mrpc': ( BertConfig, TFBertForSequenceClassification, BertForSequenceClassification, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'dpr': ( DPRConfig, TFDPRQuestionEncoder, TFDPRContextEncoder, TFDPRReader, DPRQuestionEncoder, DPRContextEncoder, DPRReader, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ), 'gpt2': ( GPTaConfig, TFGPTaLMHeadModel, GPTaLMHeadModel, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'xlnet': ( XLNetConfig, TFXLNetLMHeadModel, XLNetLMHeadModel, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'xlm': ( XLMConfig, TFXLMWithLMHeadModel, XLMWithLMHeadModel, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'xlm-roberta': ( XLMRobertaConfig, TFXLMRobertaForMaskedLM, XLMRobertaForMaskedLM, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'transfo-xl': ( TransfoXLConfig, TFTransfoXLLMHeadModel, TransfoXLLMHeadModel, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'openai-gpt': ( OpenAIGPTConfig, TFOpenAIGPTLMHeadModel, OpenAIGPTLMHeadModel, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'roberta': ( RobertaConfig, TFRobertaForCausalLM, TFRobertaForMaskedLM, RobertaForMaskedLM, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'layoutlm': ( LayoutLMConfig, TFLayoutLMForMaskedLM, LayoutLMForMaskedLM, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, ), 'roberta-large-mnli': ( RobertaConfig, TFRobertaForSequenceClassification, RobertaForSequenceClassification, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'camembert': ( CamembertConfig, TFCamembertForMaskedLM, CamembertForMaskedLM, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'flaubert': ( FlaubertConfig, TFFlaubertWithLMHeadModel, FlaubertWithLMHeadModel, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'distilbert': ( DistilBertConfig, TFDistilBertForMaskedLM, DistilBertForMaskedLM, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'distilbert-base-distilled-squad': ( DistilBertConfig, TFDistilBertForQuestionAnswering, DistilBertForQuestionAnswering, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'lxmert': ( LxmertConfig, TFLxmertForPreTraining, LxmertForPreTraining, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'lxmert-visual-feature-encoder': ( LxmertConfig, TFLxmertVisualFeatureEncoder, LxmertVisualFeatureEncoder, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'ctrl': ( CTRLConfig, TFCTRLLMHeadModel, CTRLLMHeadModel, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'albert': ( AlbertConfig, TFAlbertForPreTraining, AlbertForPreTraining, ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 't5': ( TaConfig, TFTaForConditionalGeneration, TaForConditionalGeneration, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'electra': ( ElectraConfig, TFElectraForPreTraining, ElectraForPreTraining, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'wav2vec2': ( WavaVecaConfig, TFWavaVecaModel, WavaVecaModel, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), } def a__ ( a__ , a__ , a__ , a__ , a__=False , a__=True ): """simple docstring""" if model_type not in MODEL_CLASSES: raise ValueError(F'Unrecognized model type, should be one of {list(MODEL_CLASSES.keys() )}.' ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = MODEL_CLASSES[model_type] # Initialise TF model if config_file in aws_config_map: __SCREAMING_SNAKE_CASE = cached_file(a__ , a__ , force_download=not use_cached_models ) __SCREAMING_SNAKE_CASE = config_class.from_json_file(a__ ) __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = True print(F'Building TensorFlow model from configuration: {config}' ) __SCREAMING_SNAKE_CASE = model_class(a__ ) # Load weights from tf checkpoint if pytorch_checkpoint_path in aws_config_map.keys(): __SCREAMING_SNAKE_CASE = cached_file( a__ , a__ , force_download=not use_cached_models ) # Load PyTorch checkpoint in tf2 model: __SCREAMING_SNAKE_CASE = load_pytorch_checkpoint_in_tfa_model(a__ , a__ ) if compare_with_pt_model: __SCREAMING_SNAKE_CASE = tf_model(tf_model.dummy_inputs , training=a__ ) # build the network __SCREAMING_SNAKE_CASE = torch.load(a__ , map_location="""cpu""" ) __SCREAMING_SNAKE_CASE = pt_model_class.from_pretrained( pretrained_model_name_or_path=a__ , config=a__ , state_dict=a__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = pt_model(**pt_model.dummy_inputs ) __SCREAMING_SNAKE_CASE = pto[0].numpy() __SCREAMING_SNAKE_CASE = tfo[0].numpy() __SCREAMING_SNAKE_CASE = np.amax(np.abs(np_pt - np_tf ) ) print(F'Max absolute difference between models outputs {diff}' ) assert diff <= 2E-2, F'Error, model absolute difference is >2e-2: {diff}' # Save pytorch-model print(F'Save TensorFlow model to {tf_dump_path}' ) tf_model.save_weights(a__ , save_format="""h5""" ) def a__ ( a__ , a__ , a__=None , a__=None , a__=False , a__=False , a__=False , a__=False , ): """simple docstring""" if args_model_type is None: __SCREAMING_SNAKE_CASE = list(MODEL_CLASSES.keys() ) else: __SCREAMING_SNAKE_CASE = [args_model_type] for j, model_type in enumerate(a__ , start=1 ): print("""=""" * 1_00 ) print(F' Converting model type {j}/{len(a__ )}: {model_type}' ) print("""=""" * 1_00 ) if model_type not in MODEL_CLASSES: raise ValueError(F'Unrecognized model type {model_type}, should be one of {list(MODEL_CLASSES.keys() )}.' ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = MODEL_CLASSES[model_type] if model_shortcut_names_or_path is None: __SCREAMING_SNAKE_CASE = list(aws_model_maps.keys() ) if config_shortcut_names_or_path is None: __SCREAMING_SNAKE_CASE = model_shortcut_names_or_path for i, (model_shortcut_name, config_shortcut_name) in enumerate( zip(a__ , a__ ) , start=1 ): print("""-""" * 1_00 ) if "-squad" in model_shortcut_name or "-mrpc" in model_shortcut_name or "-mnli" in model_shortcut_name: if not only_convert_finetuned_models: print(F' Skipping finetuned checkpoint {model_shortcut_name}' ) continue __SCREAMING_SNAKE_CASE = model_shortcut_name elif only_convert_finetuned_models: print(F' Skipping not finetuned checkpoint {model_shortcut_name}' ) continue print( F' Converting checkpoint {i}/{len(a__ )}: {model_shortcut_name} - model_type {model_type}' ) print("""-""" * 1_00 ) if config_shortcut_name in aws_config_map: __SCREAMING_SNAKE_CASE = cached_file(a__ , a__ , force_download=not use_cached_models ) else: __SCREAMING_SNAKE_CASE = config_shortcut_name if model_shortcut_name in aws_model_maps: __SCREAMING_SNAKE_CASE = cached_file(a__ , a__ , force_download=not use_cached_models ) else: __SCREAMING_SNAKE_CASE = model_shortcut_name if os.path.isfile(a__ ): __SCREAMING_SNAKE_CASE = """converted_model""" convert_pt_checkpoint_to_tf( model_type=a__ , pytorch_checkpoint_path=a__ , config_file=a__ , tf_dump_path=os.path.join(a__ , model_shortcut_name + """-tf_model.h5""" ) , compare_with_pt_model=a__ , ) if remove_cached_files: os.remove(a__ ) os.remove(a__ ) if __name__ == "__main__": UpperCAmelCase : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--tf_dump_path', default=None, type=str, required=True, help='Path to the output Tensorflow dump file.' ) parser.add_argument( '--model_type', default=None, type=str, help=( f"""Model type selected in the list of {list(MODEL_CLASSES.keys())}. If not given, will download and """ 'convert all the models from AWS.' ), ) parser.add_argument( '--pytorch_checkpoint_path', default=None, type=str, help=( 'Path to the PyTorch checkpoint path or shortcut name to download from AWS. ' 'If not given, will download and convert all the checkpoints from AWS.' ), ) parser.add_argument( '--config_file', default=None, type=str, help=( 'The config json file corresponding to the pre-trained model. \n' 'This specifies the model architecture. If not given and ' '--pytorch_checkpoint_path is not given or is a shortcut name ' 'use the configuration associated to the shortcut name on the AWS' ), ) parser.add_argument( '--compare_with_pt_model', action='store_true', help='Compare Tensorflow and PyTorch model predictions.' ) parser.add_argument( '--use_cached_models', action='store_true', help='Use cached models if possible instead of updating to latest checkpoint versions.', ) parser.add_argument( '--remove_cached_files', action='store_true', help='Remove pytorch models after conversion (save memory when converting in batches).', ) parser.add_argument('--only_convert_finetuned_models', action='store_true', help='Only convert finetuned models.') UpperCAmelCase : List[Any] = parser.parse_args() # if args.pytorch_checkpoint_path is not None: # convert_pt_checkpoint_to_tf(args.model_type.lower(), # args.pytorch_checkpoint_path, # args.config_file if args.config_file is not None else args.pytorch_checkpoint_path, # args.tf_dump_path, # compare_with_pt_model=args.compare_with_pt_model, # use_cached_models=args.use_cached_models) # else: convert_all_pt_checkpoints_to_tf( args.model_type.lower() if args.model_type is not None else None, args.tf_dump_path, model_shortcut_names_or_path=[args.pytorch_checkpoint_path] if args.pytorch_checkpoint_path is not None else None, config_shortcut_names_or_path=[args.config_file] if args.config_file is not None else None, compare_with_pt_model=args.compare_with_pt_model, use_cached_models=args.use_cached_models, remove_cached_files=args.remove_cached_files, only_convert_finetuned_models=args.only_convert_finetuned_models, )
267
1
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_squeezebert import SqueezeBertTokenizer UpperCAmelCase : Tuple = logging.get_logger(__name__) UpperCAmelCase : Union[str, Any] = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} UpperCAmelCase : Optional[int] = { 'vocab_file': { 'squeezebert/squeezebert-uncased': ( 'https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/vocab.txt' ), 'squeezebert/squeezebert-mnli': 'https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/vocab.txt', 'squeezebert/squeezebert-mnli-headless': ( 'https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'squeezebert/squeezebert-uncased': ( 'https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/tokenizer.json' ), 'squeezebert/squeezebert-mnli': ( 'https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/tokenizer.json' ), 'squeezebert/squeezebert-mnli-headless': ( 'https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/tokenizer.json' ), }, } UpperCAmelCase : Optional[int] = { 'squeezebert/squeezebert-uncased': 5_1_2, 'squeezebert/squeezebert-mnli': 5_1_2, 'squeezebert/squeezebert-mnli-headless': 5_1_2, } UpperCAmelCase : Dict = { 'squeezebert/squeezebert-uncased': {'do_lower_case': True}, 'squeezebert/squeezebert-mnli': {'do_lower_case': True}, 'squeezebert/squeezebert-mnli-headless': {'do_lower_case': True}, } class lowerCAmelCase__ ( a ): """simple docstring""" lowerCAmelCase__ = VOCAB_FILES_NAMES lowerCAmelCase__ = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase__ = PRETRAINED_INIT_CONFIGURATION lowerCAmelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase__ = SqueezeBertTokenizer def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : Union[str, Any]=None , __SCREAMING_SNAKE_CASE : List[str]=None , __SCREAMING_SNAKE_CASE : Tuple=True , __SCREAMING_SNAKE_CASE : str="[UNK]" , __SCREAMING_SNAKE_CASE : str="[SEP]" , __SCREAMING_SNAKE_CASE : Tuple="[PAD]" , __SCREAMING_SNAKE_CASE : Any="[CLS]" , __SCREAMING_SNAKE_CASE : Union[str, Any]="[MASK]" , __SCREAMING_SNAKE_CASE : Union[str, Any]=True , __SCREAMING_SNAKE_CASE : Any=None , **__SCREAMING_SNAKE_CASE : Optional[int] , ) -> Optional[Any]: """simple docstring""" super().__init__( __SCREAMING_SNAKE_CASE , tokenizer_file=__SCREAMING_SNAKE_CASE , do_lower_case=__SCREAMING_SNAKE_CASE , unk_token=__SCREAMING_SNAKE_CASE , sep_token=__SCREAMING_SNAKE_CASE , pad_token=__SCREAMING_SNAKE_CASE , cls_token=__SCREAMING_SNAKE_CASE , mask_token=__SCREAMING_SNAKE_CASE , tokenize_chinese_chars=__SCREAMING_SNAKE_CASE , strip_accents=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) __SCREAMING_SNAKE_CASE = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""" , __SCREAMING_SNAKE_CASE ) != do_lower_case or normalizer_state.get("""strip_accents""" , __SCREAMING_SNAKE_CASE ) != strip_accents or normalizer_state.get("""handle_chinese_chars""" , __SCREAMING_SNAKE_CASE ) != tokenize_chinese_chars ): __SCREAMING_SNAKE_CASE = getattr(__SCREAMING_SNAKE_CASE , normalizer_state.pop("""type""" ) ) __SCREAMING_SNAKE_CASE = do_lower_case __SCREAMING_SNAKE_CASE = strip_accents __SCREAMING_SNAKE_CASE = tokenize_chinese_chars __SCREAMING_SNAKE_CASE = normalizer_class(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = do_lower_case def UpperCAmelCase__ ( self : str , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : str=None ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = [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 UpperCAmelCase__ ( self : List[Any] , __SCREAMING_SNAKE_CASE : List[int] , __SCREAMING_SNAKE_CASE : Optional[List[int]] = None ) -> List[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = [self.sep_token_id] __SCREAMING_SNAKE_CASE = [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 UpperCAmelCase__ ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Optional[str] = None ) -> Tuple[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self._tokenizer.model.save(__SCREAMING_SNAKE_CASE , name=__SCREAMING_SNAKE_CASE ) return tuple(__SCREAMING_SNAKE_CASE )
267
'''simple docstring''' def a__ ( a__ ): """simple docstring""" if isinstance(a__ , a__ ): raise TypeError("""'float' object cannot be interpreted as an integer""" ) if isinstance(a__ , a__ ): raise TypeError("""'str' object cannot be interpreted as an integer""" ) if num == 0: return "0b0" __SCREAMING_SNAKE_CASE = False if num < 0: __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = -num __SCREAMING_SNAKE_CASE = [] while num > 0: binary.insert(0 , num % 2 ) num >>= 1 if negative: return "-0b" + "".join(str(a__ ) for e in binary ) return "0b" + "".join(str(a__ ) for e in binary ) if __name__ == "__main__": import doctest doctest.testmod()
267
1
'''simple docstring''' from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging UpperCAmelCase : Optional[Any] = logging.get_logger(__name__) UpperCAmelCase : List[Any] = { 't5-small': 'https://huggingface.co/t5-small/resolve/main/config.json', 't5-base': 'https://huggingface.co/t5-base/resolve/main/config.json', 't5-large': 'https://huggingface.co/t5-large/resolve/main/config.json', 't5-3b': 'https://huggingface.co/t5-3b/resolve/main/config.json', 't5-11b': 'https://huggingface.co/t5-11b/resolve/main/config.json', } class lowerCAmelCase__ ( a ): """simple docstring""" lowerCAmelCase__ = "t5" lowerCAmelCase__ = ["past_key_values"] lowerCAmelCase__ = {"hidden_size": "d_model", "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers"} def __init__( self : Optional[int] , __SCREAMING_SNAKE_CASE : List[Any]=32_128 , __SCREAMING_SNAKE_CASE : Dict=512 , __SCREAMING_SNAKE_CASE : List[str]=64 , __SCREAMING_SNAKE_CASE : Tuple=2_048 , __SCREAMING_SNAKE_CASE : Tuple=6 , __SCREAMING_SNAKE_CASE : Tuple=None , __SCREAMING_SNAKE_CASE : Dict=8 , __SCREAMING_SNAKE_CASE : Union[str, Any]=32 , __SCREAMING_SNAKE_CASE : Optional[Any]=128 , __SCREAMING_SNAKE_CASE : List[str]=0.1 , __SCREAMING_SNAKE_CASE : Optional[Any]=1E-6 , __SCREAMING_SNAKE_CASE : Optional[Any]=1.0 , __SCREAMING_SNAKE_CASE : Any="relu" , __SCREAMING_SNAKE_CASE : List[Any]=True , __SCREAMING_SNAKE_CASE : Any=True , __SCREAMING_SNAKE_CASE : Dict=0 , __SCREAMING_SNAKE_CASE : Tuple=1 , **__SCREAMING_SNAKE_CASE : List[Any] , ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = d_model __SCREAMING_SNAKE_CASE = d_kv __SCREAMING_SNAKE_CASE = d_ff __SCREAMING_SNAKE_CASE = num_layers __SCREAMING_SNAKE_CASE = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry __SCREAMING_SNAKE_CASE = num_heads __SCREAMING_SNAKE_CASE = relative_attention_num_buckets __SCREAMING_SNAKE_CASE = relative_attention_max_distance __SCREAMING_SNAKE_CASE = dropout_rate __SCREAMING_SNAKE_CASE = layer_norm_epsilon __SCREAMING_SNAKE_CASE = initializer_factor __SCREAMING_SNAKE_CASE = feed_forward_proj __SCREAMING_SNAKE_CASE = use_cache __SCREAMING_SNAKE_CASE = self.feed_forward_proj.split("""-""" ) __SCREAMING_SNAKE_CASE = act_info[-1] __SCREAMING_SNAKE_CASE = act_info[0] == """gated""" if len(__SCREAMING_SNAKE_CASE ) > 1 and act_info[0] != "gated" or len(__SCREAMING_SNAKE_CASE ) > 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'""" ) # for backwards compatibility if feed_forward_proj == "gated-gelu": __SCREAMING_SNAKE_CASE = """gelu_new""" super().__init__( pad_token_id=__SCREAMING_SNAKE_CASE , eos_token_id=__SCREAMING_SNAKE_CASE , is_encoder_decoder=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) class lowerCAmelCase__ ( a ): """simple docstring""" @property def UpperCAmelCase__ ( self : Optional[int] ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" __SCREAMING_SNAKE_CASE = { """input_ids""": {0: """batch""", 1: """encoder_sequence"""}, """attention_mask""": {0: """batch""", 1: """encoder_sequence"""}, } if self.use_past: __SCREAMING_SNAKE_CASE = """past_encoder_sequence + sequence""" __SCREAMING_SNAKE_CASE = {0: """batch"""} __SCREAMING_SNAKE_CASE = {0: """batch""", 1: """past_decoder_sequence + sequence"""} else: __SCREAMING_SNAKE_CASE = {0: """batch""", 1: """decoder_sequence"""} __SCREAMING_SNAKE_CASE = {0: """batch""", 1: """decoder_sequence"""} if self.use_past: self.fill_with_past_key_values_(__SCREAMING_SNAKE_CASE , direction="""inputs""" ) return common_inputs @property def UpperCAmelCase__ ( self : int ) -> int: """simple docstring""" return 13
267
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices UpperCAmelCase : Optional[int] = logging.get_logger(__name__) UpperCAmelCase : str = { 'facebook/convnextv2-tiny-1k-224': 'https://huggingface.co/facebook/convnextv2-tiny-1k-224/resolve/main/config.json', } class lowerCAmelCase__ ( a , a ): """simple docstring""" lowerCAmelCase__ = "convnextv2" def __init__( self : Any , __SCREAMING_SNAKE_CASE : int=3 , __SCREAMING_SNAKE_CASE : Dict=4 , __SCREAMING_SNAKE_CASE : List[Any]=4 , __SCREAMING_SNAKE_CASE : Optional[int]=None , __SCREAMING_SNAKE_CASE : Dict=None , __SCREAMING_SNAKE_CASE : Optional[int]="gelu" , __SCREAMING_SNAKE_CASE : Union[str, Any]=0.02 , __SCREAMING_SNAKE_CASE : Dict=1E-12 , __SCREAMING_SNAKE_CASE : List[str]=0.0 , __SCREAMING_SNAKE_CASE : Optional[Any]=224 , __SCREAMING_SNAKE_CASE : Tuple=None , __SCREAMING_SNAKE_CASE : List[str]=None , **__SCREAMING_SNAKE_CASE : Union[str, Any] , ) -> Union[str, Any]: """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = patch_size __SCREAMING_SNAKE_CASE = num_stages __SCREAMING_SNAKE_CASE = [96, 192, 384, 768] if hidden_sizes is None else hidden_sizes __SCREAMING_SNAKE_CASE = [3, 3, 9, 3] if depths is None else depths __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = drop_path_rate __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = ["""stem"""] + [f'stage{idx}' for idx in range(1 , len(self.depths ) + 1 )] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = get_aligned_output_features_output_indices( out_features=__SCREAMING_SNAKE_CASE , out_indices=__SCREAMING_SNAKE_CASE , stage_names=self.stage_names )
267
1
'''simple docstring''' from ...utils import is_torch_available, is_transformers_available if is_transformers_available() and is_torch_available(): from .pipeline_vq_diffusion import LearnedClassifierFreeSamplingEmbeddings, VQDiffusionPipeline
267
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices UpperCAmelCase : List[str] = logging.get_logger(__name__) class lowerCAmelCase__ ( a , a ): """simple docstring""" lowerCAmelCase__ = "maskformer-swin" lowerCAmelCase__ = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self : str , __SCREAMING_SNAKE_CASE : Tuple=224 , __SCREAMING_SNAKE_CASE : str=4 , __SCREAMING_SNAKE_CASE : Union[str, Any]=3 , __SCREAMING_SNAKE_CASE : Optional[Any]=96 , __SCREAMING_SNAKE_CASE : Optional[Any]=[2, 2, 6, 2] , __SCREAMING_SNAKE_CASE : Any=[3, 6, 12, 24] , __SCREAMING_SNAKE_CASE : Dict=7 , __SCREAMING_SNAKE_CASE : Dict=4.0 , __SCREAMING_SNAKE_CASE : Dict=True , __SCREAMING_SNAKE_CASE : str=0.0 , __SCREAMING_SNAKE_CASE : int=0.0 , __SCREAMING_SNAKE_CASE : str=0.1 , __SCREAMING_SNAKE_CASE : List[Any]="gelu" , __SCREAMING_SNAKE_CASE : str=False , __SCREAMING_SNAKE_CASE : Optional[int]=0.02 , __SCREAMING_SNAKE_CASE : Optional[int]=1E-5 , __SCREAMING_SNAKE_CASE : Dict=None , __SCREAMING_SNAKE_CASE : Dict=None , **__SCREAMING_SNAKE_CASE : Tuple , ) -> Tuple: """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = patch_size __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = embed_dim __SCREAMING_SNAKE_CASE = depths __SCREAMING_SNAKE_CASE = len(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = num_heads __SCREAMING_SNAKE_CASE = window_size __SCREAMING_SNAKE_CASE = mlp_ratio __SCREAMING_SNAKE_CASE = qkv_bias __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = drop_path_rate __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = use_absolute_embeddings __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = initializer_range # we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model __SCREAMING_SNAKE_CASE = int(embed_dim * 2 ** (len(__SCREAMING_SNAKE_CASE ) - 1) ) __SCREAMING_SNAKE_CASE = ["""stem"""] + [f'stage{idx}' for idx in range(1 , len(__SCREAMING_SNAKE_CASE ) + 1 )] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = get_aligned_output_features_output_indices( out_features=__SCREAMING_SNAKE_CASE , out_indices=__SCREAMING_SNAKE_CASE , stage_names=self.stage_names )
267
1
'''simple docstring''' # Copyright 2021 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from packaging import version from .. import __version__ from .constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD from .doc import ( add_code_sample_docstrings, add_end_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, copy_func, replace_return_docstrings, ) from .generic import ( ContextManagers, ExplicitEnum, ModelOutput, PaddingStrategy, TensorType, add_model_info_to_auto_map, cached_property, can_return_loss, expand_dims, find_labels, flatten_dict, infer_framework, is_jax_tensor, is_numpy_array, is_tensor, is_tf_symbolic_tensor, is_tf_tensor, is_torch_device, is_torch_dtype, is_torch_tensor, reshape, squeeze, strtobool, tensor_size, to_numpy, to_py_obj, transpose, working_or_temp_dir, ) from .hub import ( CLOUDFRONT_DISTRIB_PREFIX, DISABLE_TELEMETRY, HF_MODULES_CACHE, HUGGINGFACE_CO_PREFIX, HUGGINGFACE_CO_RESOLVE_ENDPOINT, PYTORCH_PRETRAINED_BERT_CACHE, PYTORCH_TRANSFORMERS_CACHE, S3_BUCKET_PREFIX, TRANSFORMERS_CACHE, TRANSFORMERS_DYNAMIC_MODULE_NAME, EntryNotFoundError, PushToHubMixin, RepositoryNotFoundError, RevisionNotFoundError, cached_file, default_cache_path, define_sagemaker_information, download_url, extract_commit_hash, get_cached_models, get_file_from_repo, get_full_repo_name, has_file, http_user_agent, is_offline_mode, is_remote_url, move_cache, send_example_telemetry, try_to_load_from_cache, ) from .import_utils import ( ENV_VARS_TRUE_AND_AUTO_VALUES, ENV_VARS_TRUE_VALUES, TORCH_FX_REQUIRED_VERSION, USE_JAX, USE_TF, USE_TORCH, DummyObject, OptionalDependencyNotAvailable, _LazyModule, ccl_version, direct_transformers_import, get_torch_version, is_accelerate_available, is_apex_available, is_bitsandbytes_available, is_bsa_available, is_coloredlogs_available, is_cython_available, is_datasets_available, is_decord_available, is_detectrona_available, is_faiss_available, is_flax_available, is_ftfy_available, is_in_notebook, is_ipex_available, is_jieba_available, is_jumanpp_available, is_kenlm_available, is_keras_nlp_available, is_librosa_available, is_natten_available, is_ninja_available, is_onnx_available, is_openai_available, is_optimum_available, is_pandas_available, is_peft_available, is_phonemizer_available, is_protobuf_available, is_psutil_available, is_pyanvml_available, is_pyctcdecode_available, is_pytesseract_available, is_pytest_available, is_pytorch_quantization_available, is_rjieba_available, is_sacremoses_available, is_safetensors_available, is_sagemaker_dp_enabled, is_sagemaker_mp_enabled, is_scipy_available, is_sentencepiece_available, is_seqio_available, is_sklearn_available, is_soundfile_availble, is_spacy_available, is_speech_available, is_sudachi_available, is_tensorflow_probability_available, is_tensorflow_text_available, is_tfaonnx_available, is_tf_available, is_timm_available, is_tokenizers_available, is_torch_available, is_torch_bfaa_available, is_torch_bfaa_cpu_available, is_torch_bfaa_gpu_available, is_torch_compile_available, is_torch_cuda_available, is_torch_fx_available, is_torch_fx_proxy, is_torch_mps_available, is_torch_neuroncore_available, is_torch_tensorrt_fx_available, is_torch_tfaa_available, is_torch_tpu_available, is_torchaudio_available, is_torchdistx_available, is_torchdynamo_available, is_torchvision_available, is_training_run_on_sagemaker, is_vision_available, requires_backends, torch_only_method, ) UpperCAmelCase : str = 'pytorch_model.bin' UpperCAmelCase : Optional[int] = 'pytorch_model.bin.index.json' UpperCAmelCase : Optional[Any] = 'adapter_config.json' UpperCAmelCase : List[str] = 'adapter_model.bin' UpperCAmelCase : Optional[Any] = 'adapter_model.safetensors' UpperCAmelCase : List[Any] = 'tf_model.h5' UpperCAmelCase : int = 'tf_model.h5.index.json' UpperCAmelCase : Dict = 'model.ckpt' UpperCAmelCase : Tuple = 'flax_model.msgpack' UpperCAmelCase : List[Any] = 'flax_model.msgpack.index.json' UpperCAmelCase : Tuple = 'model.safetensors' UpperCAmelCase : int = 'model.safetensors.index.json' UpperCAmelCase : Optional[Any] = 'config.json' UpperCAmelCase : List[Any] = 'preprocessor_config.json' UpperCAmelCase : List[Any] = FEATURE_EXTRACTOR_NAME UpperCAmelCase : List[str] = 'generation_config.json' UpperCAmelCase : Optional[Any] = 'modelcard.json' UpperCAmelCase : int = '▁' UpperCAmelCase : List[str] = SENTENCEPIECE_UNDERLINE # Kept for backward compatibility UpperCAmelCase : int = [ [[0, 1, 0, 1], [1, 0, 0, 1]] ] * 2 # Needs to have 0s and 1s only since XLM uses it for langs too. UpperCAmelCase : int = [[7, 6, 0, 0, 1], [1, 2, 3, 0, 0], [0, 0, 0, 4, 5]] UpperCAmelCase : Tuple = [[1, 1, 1, 1, 1], [1, 1, 1, 0, 0], [0, 0, 0, 1, 1]] def a__ ( a__ ): """simple docstring""" if version.parse(a__ ) < version.parse(a__ ): if "dev" in min_version: __SCREAMING_SNAKE_CASE = ( """This example requires a source install from HuggingFace Transformers (see """ """`https://huggingface.co/docs/transformers/installation#install-from-source`),""" ) else: __SCREAMING_SNAKE_CASE = F'This example requires a minimum version of {min_version},' error_message += F' but the version found is {__version__}.\n' raise ImportError( error_message + """Check out https://github.com/huggingface/transformers/tree/main/examples#important-note for the examples corresponding to other """ """versions of HuggingFace Transformers.""" )
267
'''simple docstring''' class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : int ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = n __SCREAMING_SNAKE_CASE = [None] * self.n __SCREAMING_SNAKE_CASE = 0 # index of the first element __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 def __len__( self : Tuple ) -> int: """simple docstring""" return self.size def UpperCAmelCase__ ( self : Optional[Any] ) -> bool: """simple docstring""" return self.size == 0 def UpperCAmelCase__ ( self : Any ) -> int: """simple docstring""" return False if self.is_empty() else self.array[self.front] def UpperCAmelCase__ ( self : Dict , __SCREAMING_SNAKE_CASE : Union[str, Any] ) -> Dict: """simple docstring""" if self.size >= self.n: raise Exception("""QUEUE IS FULL""" ) __SCREAMING_SNAKE_CASE = data __SCREAMING_SNAKE_CASE = (self.rear + 1) % self.n self.size += 1 return self def UpperCAmelCase__ ( self : List[str] ) -> Optional[Any]: """simple docstring""" if self.size == 0: raise Exception("""UNDERFLOW""" ) __SCREAMING_SNAKE_CASE = self.array[self.front] __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = (self.front + 1) % self.n self.size -= 1 return temp
267
1
'''simple docstring''' import sys import webbrowser import requests from bsa import BeautifulSoup from fake_useragent import UserAgent if __name__ == "__main__": print('Googling.....') UpperCAmelCase : str = 'https://www.google.com/search?q=' + ' '.join(sys.argv[1:]) UpperCAmelCase : List[Any] = requests.get(url, headers={'UserAgent': UserAgent().random}) # res.raise_for_status() with open('project1a.html', 'wb') as out_file: # only for knowing the class for data in res.iter_content(1_0_0_0_0): out_file.write(data) UpperCAmelCase : Tuple = BeautifulSoup(res.text, 'html.parser') UpperCAmelCase : Optional[int] = list(soup.select('.eZt8xd'))[:5] print(len(links)) for link in links: if link.text == "Maps": webbrowser.open(link.get('href')) else: webbrowser.open(f"""https://google.com{link.get("href")}""")
267
'''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] ) -> Optional[int]: """simple docstring""" torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = 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 : List[Any] ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.dummy_uncond_unet __SCREAMING_SNAKE_CASE = PNDMScheduler() __SCREAMING_SNAKE_CASE = PNDMPipeline(unet=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE ) pndm.to(__SCREAMING_SNAKE_CASE ) pndm.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pndm(generator=__SCREAMING_SNAKE_CASE , num_inference_steps=20 , output_type="""numpy""" ).images __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pndm(generator=__SCREAMING_SNAKE_CASE , num_inference_steps=20 , output_type="""numpy""" , return_dict=__SCREAMING_SNAKE_CASE )[0] __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] __SCREAMING_SNAKE_CASE = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __SCREAMING_SNAKE_CASE = 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 : Optional[int] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = """google/ddpm-cifar10-32""" __SCREAMING_SNAKE_CASE = UNetaDModel.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = PNDMScheduler() __SCREAMING_SNAKE_CASE = PNDMPipeline(unet=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE ) pndm.to(__SCREAMING_SNAKE_CASE ) pndm.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pndm(generator=__SCREAMING_SNAKE_CASE , output_type="""numpy""" ).images __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __SCREAMING_SNAKE_CASE = np.array([0.1564, 0.14645, 0.1406, 0.14715, 0.12425, 0.14045, 0.13115, 0.12175, 0.125] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
267
1
'''simple docstring''' from __future__ import annotations def a__ ( a__ , a__ , a__ , ): """simple docstring""" if (electron_conc, hole_conc, intrinsic_conc).count(0 ) != 1: raise ValueError("""You cannot supply more or less than 2 values""" ) elif electron_conc < 0: raise ValueError("""Electron concentration cannot be negative in a semiconductor""" ) elif hole_conc < 0: raise ValueError("""Hole concentration cannot be negative in a semiconductor""" ) elif intrinsic_conc < 0: raise ValueError( """Intrinsic concentration cannot be negative in a semiconductor""" ) elif electron_conc == 0: return ( "electron_conc", intrinsic_conc**2 / hole_conc, ) elif hole_conc == 0: return ( "hole_conc", intrinsic_conc**2 / electron_conc, ) elif intrinsic_conc == 0: return ( "intrinsic_conc", (electron_conc * hole_conc) ** 0.5, ) else: return (-1, -1) if __name__ == "__main__": import doctest doctest.testmod()
267
'''simple docstring''' import unittest from transformers import ( MODEL_FOR_OBJECT_DETECTION_MAPPING, AutoFeatureExtractor, AutoModelForObjectDetection, ObjectDetectionPipeline, is_vision_available, pipeline, ) from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_pytesseract, require_tf, require_timm, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class lowerCAmelCase__ : """simple docstring""" @staticmethod def UpperCAmelCase__ ( *__SCREAMING_SNAKE_CASE : Tuple , **__SCREAMING_SNAKE_CASE : Union[str, Any] ) -> List[str]: """simple docstring""" pass @is_pipeline_test @require_vision @require_timm @require_torch class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = MODEL_FOR_OBJECT_DETECTION_MAPPING def UpperCAmelCase__ ( self : List[Any] , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Tuple ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = ObjectDetectionPipeline(model=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) return object_detector, ["./tests/fixtures/tests_samples/COCO/000000039769.png"] def UpperCAmelCase__ ( self : Optional[int] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : List[Any] ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = object_detector("""./tests/fixtures/tests_samples/COCO/000000039769.png""" , threshold=0.0 ) self.assertGreater(len(__SCREAMING_SNAKE_CASE ) , 0 ) for detected_object in outputs: self.assertEqual( __SCREAMING_SNAKE_CASE , { """score""": ANY(__SCREAMING_SNAKE_CASE ), """label""": ANY(__SCREAMING_SNAKE_CASE ), """box""": {"""xmin""": ANY(__SCREAMING_SNAKE_CASE ), """ymin""": ANY(__SCREAMING_SNAKE_CASE ), """xmax""": ANY(__SCREAMING_SNAKE_CASE ), """ymax""": ANY(__SCREAMING_SNAKE_CASE )}, } , ) import datasets __SCREAMING_SNAKE_CASE = datasets.load_dataset("""hf-internal-testing/fixtures_image_utils""" , """image""" , split="""test""" ) __SCREAMING_SNAKE_CASE = [ Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ), """http://images.cocodataset.org/val2017/000000039769.jpg""", # RGBA dataset[0]["""file"""], # LA dataset[1]["""file"""], # L dataset[2]["""file"""], ] __SCREAMING_SNAKE_CASE = object_detector(__SCREAMING_SNAKE_CASE , threshold=0.0 ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , len(__SCREAMING_SNAKE_CASE ) ) for outputs in batch_outputs: self.assertGreater(len(__SCREAMING_SNAKE_CASE ) , 0 ) for detected_object in outputs: self.assertEqual( __SCREAMING_SNAKE_CASE , { """score""": ANY(__SCREAMING_SNAKE_CASE ), """label""": ANY(__SCREAMING_SNAKE_CASE ), """box""": {"""xmin""": ANY(__SCREAMING_SNAKE_CASE ), """ymin""": ANY(__SCREAMING_SNAKE_CASE ), """xmax""": ANY(__SCREAMING_SNAKE_CASE ), """ymax""": ANY(__SCREAMING_SNAKE_CASE )}, } , ) @require_tf @unittest.skip("""Object detection not implemented in TF""" ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> str: """simple docstring""" pass @require_torch def UpperCAmelCase__ ( self : str ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = """hf-internal-testing/tiny-detr-mobilenetsv3""" __SCREAMING_SNAKE_CASE = AutoModelForObjectDetection.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = AutoFeatureExtractor.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = ObjectDetectionPipeline(model=__SCREAMING_SNAKE_CASE , feature_extractor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" , threshold=0.0 ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ] , ) __SCREAMING_SNAKE_CASE = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] , threshold=0.0 , ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ], [ {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ], ] , ) @require_torch @slow def UpperCAmelCase__ ( self : Optional[int] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = """facebook/detr-resnet-50""" __SCREAMING_SNAKE_CASE = AutoModelForObjectDetection.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = AutoFeatureExtractor.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = ObjectDetectionPipeline(model=__SCREAMING_SNAKE_CASE , feature_extractor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) __SCREAMING_SNAKE_CASE = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], ] , ) @require_torch @slow def UpperCAmelCase__ ( self : List[Any] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = """facebook/detr-resnet-50""" __SCREAMING_SNAKE_CASE = pipeline("""object-detection""" , model=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) __SCREAMING_SNAKE_CASE = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], ] , ) @require_torch @slow def UpperCAmelCase__ ( self : Dict ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = 0.9985 __SCREAMING_SNAKE_CASE = """facebook/detr-resnet-50""" __SCREAMING_SNAKE_CASE = pipeline("""object-detection""" , model=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" , threshold=__SCREAMING_SNAKE_CASE ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) @require_torch @require_pytesseract @slow def UpperCAmelCase__ ( self : int ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = """Narsil/layoutlmv3-finetuned-funsd""" __SCREAMING_SNAKE_CASE = 0.9993 __SCREAMING_SNAKE_CASE = pipeline("""object-detection""" , model=__SCREAMING_SNAKE_CASE , threshold=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector( """https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9993, """label""": """I-ANSWER""", """box""": {"""xmin""": 294, """ymin""": 254, """xmax""": 343, """ymax""": 264}}, {"""score""": 0.9993, """label""": """I-ANSWER""", """box""": {"""xmin""": 294, """ymin""": 254, """xmax""": 343, """ymax""": 264}}, ] , )
267
1
'''simple docstring''' import unittest from transformers import SPIECE_UNDERLINE from transformers.models.speechta import SpeechTaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.tokenization_utils import AddedToken from ...test_tokenization_common import TokenizerTesterMixin UpperCAmelCase : List[Any] = get_tests_dir('fixtures/test_sentencepiece_bpe_char.model') @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = SpeechTaTokenizer lowerCAmelCase__ = False lowerCAmelCase__ = True def UpperCAmelCase__ ( self : int ) -> Tuple: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing __SCREAMING_SNAKE_CASE = SpeechTaTokenizer(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = AddedToken("""<mask>""" , lstrip=__SCREAMING_SNAKE_CASE , rstrip=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = mask_token tokenizer.add_special_tokens({"""mask_token""": mask_token} ) tokenizer.add_tokens(["""<ctc_blank>"""] ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCAmelCase__ ( self : List[Any] , __SCREAMING_SNAKE_CASE : str ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = """this is a test""" __SCREAMING_SNAKE_CASE = """this is a test""" return input_text, output_text def UpperCAmelCase__ ( self : int , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Union[str, Any]=False , __SCREAMING_SNAKE_CASE : Dict=20 , __SCREAMING_SNAKE_CASE : int=5 ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.get_input_output_texts(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer.encode(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer.decode(__SCREAMING_SNAKE_CASE , clean_up_tokenization_spaces=__SCREAMING_SNAKE_CASE ) return text, ids def UpperCAmelCase__ ( self : Dict ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = """<pad>""" __SCREAMING_SNAKE_CASE = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : str ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """<s>""" ) self.assertEqual(vocab_keys[1] , """<pad>""" ) self.assertEqual(vocab_keys[-4] , """œ""" ) self.assertEqual(vocab_keys[-2] , """<mask>""" ) self.assertEqual(vocab_keys[-1] , """<ctc_blank>""" ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , 81 ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> Tuple: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 79 ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_tokenizers(do_lower_case=__SCREAMING_SNAKE_CASE ) for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): __SCREAMING_SNAKE_CASE = tokenizer.vocab_size __SCREAMING_SNAKE_CASE = len(__SCREAMING_SNAKE_CASE ) self.assertNotEqual(__SCREAMING_SNAKE_CASE , 0 ) # We usually have added tokens from the start in tests because our vocab fixtures are # smaller than the original vocabs - let's not assert this # self.assertEqual(vocab_size, all_size) __SCREAMING_SNAKE_CASE = ["""aaaaa bbbbbb""", """cccccccccdddddddd"""] __SCREAMING_SNAKE_CASE = tokenizer.add_tokens(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer.vocab_size __SCREAMING_SNAKE_CASE = len(__SCREAMING_SNAKE_CASE ) self.assertNotEqual(__SCREAMING_SNAKE_CASE , 0 ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , len(__SCREAMING_SNAKE_CASE ) ) self.assertEqual(__SCREAMING_SNAKE_CASE , all_size + len(__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = tokenizer.encode("""aaaaa bbbbbb low cccccccccdddddddd l""" , add_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertGreaterEqual(len(__SCREAMING_SNAKE_CASE ) , 4 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) __SCREAMING_SNAKE_CASE = {"""eos_token""": """>>>>|||<||<<|<<""", """pad_token""": """<<<<<|||>|>>>>|>"""} __SCREAMING_SNAKE_CASE = tokenizer.add_special_tokens(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer.vocab_size __SCREAMING_SNAKE_CASE = len(__SCREAMING_SNAKE_CASE ) self.assertNotEqual(__SCREAMING_SNAKE_CASE , 0 ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , len(__SCREAMING_SNAKE_CASE ) ) self.assertEqual(__SCREAMING_SNAKE_CASE , all_size_a + len(__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = tokenizer.encode( """>>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l""" , add_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertGreaterEqual(len(__SCREAMING_SNAKE_CASE ) , 6 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[0] , tokens[1] ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokens[-4] ) self.assertEqual(tokens[0] , tokenizer.eos_token_id ) self.assertEqual(tokens[-3] , tokenizer.pad_token_id ) def UpperCAmelCase__ ( self : Optional[int] ) -> Optional[int]: """simple docstring""" pass def UpperCAmelCase__ ( self : Dict ) -> Dict: """simple docstring""" pass def UpperCAmelCase__ ( self : Tuple ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = tokenizer.tokenize("""This is a test""" ) # fmt: off self.assertListEqual(__SCREAMING_SNAKE_CASE , [SPIECE_UNDERLINE, """T""", """h""", """i""", """s""", SPIECE_UNDERLINE, """i""", """s""", SPIECE_UNDERLINE, """a""", SPIECE_UNDERLINE, """t""", """e""", """s""", """t"""] ) # fmt: on self.assertListEqual( tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) , [4, 32, 11, 10, 12, 4, 10, 12, 4, 7, 4, 6, 5, 12, 6] , ) __SCREAMING_SNAKE_CASE = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [SPIECE_UNDERLINE, """I""", SPIECE_UNDERLINE, """w""", """a""", """s""", SPIECE_UNDERLINE, """b""", """o""", """r""", """n""", SPIECE_UNDERLINE, """i""", """n""", SPIECE_UNDERLINE, """92000""", """,""", SPIECE_UNDERLINE, """a""", """n""", """d""", SPIECE_UNDERLINE, """t""", """h""", """i""", """s""", SPIECE_UNDERLINE, """i""", """s""", SPIECE_UNDERLINE, """f""", """a""", """l""", """s""", """é""", """."""] ) __SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) # fmt: off self.assertListEqual(__SCREAMING_SNAKE_CASE , [4, 30, 4, 20, 7, 12, 4, 25, 8, 13, 9, 4, 10, 9, 4, 3, 23, 4, 7, 9, 14, 4, 6, 11, 10, 12, 4, 10, 12, 4, 19, 7, 15, 12, 73, 26] ) # fmt: on __SCREAMING_SNAKE_CASE = tokenizer.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [SPIECE_UNDERLINE, """I""", SPIECE_UNDERLINE, """w""", """a""", """s""", SPIECE_UNDERLINE, """b""", """o""", """r""", """n""", SPIECE_UNDERLINE, """i""", """n""", SPIECE_UNDERLINE, """<unk>""", """,""", SPIECE_UNDERLINE, """a""", """n""", """d""", SPIECE_UNDERLINE, """t""", """h""", """i""", """s""", SPIECE_UNDERLINE, """i""", """s""", SPIECE_UNDERLINE, """f""", """a""", """l""", """s""", """é""", """."""] ) @slow def UpperCAmelCase__ ( self : List[Any] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = [ """Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides """ """general-purpose architectures (BERT, GPT, RoBERTa, XLM, DistilBert, XLNet...) for Natural """ """Language Understanding (NLU) and Natural Language Generation (NLG) with over thirty-two pretrained """ """models in one hundred plus languages and deep interoperability between Jax, PyTorch and TensorFlow.""", """BERT is designed to pre-train deep bidirectional representations from unlabeled text by jointly """ """conditioning on both left and right context in all layers.""", """The quick brown fox jumps over the lazy dog.""", ] # fmt: off __SCREAMING_SNAKE_CASE = { """input_ids""": [ [4, 32, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 64, 19, 8, 13, 18, 5, 13, 15, 22, 4, 28, 9, 8, 20, 9, 4, 7, 12, 4, 24, 22, 6, 8, 13, 17, 11, 39, 6, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 7, 9, 14, 4, 24, 22, 6, 8, 13, 17, 11, 39, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 39, 25, 5, 13, 6, 63, 4, 24, 13, 8, 27, 10, 14, 5, 12, 4, 21, 5, 9, 5, 13, 7, 15, 39, 24, 16, 13, 24, 8, 12, 5, 4, 7, 13, 17, 11, 10, 6, 5, 17, 6, 16, 13, 5, 12, 4, 64, 40, 47, 54, 32, 23, 4, 53, 49, 32, 23, 4, 54, 8, 40, 47, 54, 32, 7, 23, 4, 69, 52, 43, 23, 4, 51, 10, 12, 6, 10, 15, 40, 5, 13, 6, 23, 4, 69, 52, 48, 5, 6, 26, 26, 26, 63, 4, 19, 8, 13, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 61, 9, 14, 5, 13, 12, 6, 7, 9, 14, 10, 9, 21, 4, 64, 48, 52, 61, 63, 4, 7, 9, 14, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 53, 5, 9, 5, 13, 7, 6, 10, 8, 9, 4, 64, 48, 52, 53, 63, 4, 20, 10, 6, 11, 4, 8, 27, 5, 13, 4, 6, 11, 10, 13, 6, 22, 39, 6, 20, 8, 4, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 4, 18, 8, 14, 5, 15, 12, 4, 10, 9, 4, 8, 9, 5, 4, 11, 16, 9, 14, 13, 5, 14, 4, 24, 15, 16, 12, 4, 15, 7, 9, 21, 16, 7, 21, 5, 12, 4, 7, 9, 14, 4, 14, 5, 5, 24, 4, 10, 9, 6, 5, 13, 8, 24, 5, 13, 7, 25, 10, 15, 10, 6, 22, 4, 25, 5, 6, 20, 5, 5, 9, 4, 58, 7, 37, 23, 4, 49, 22, 32, 8, 13, 17, 11, 4, 7, 9, 14, 4, 32, 5, 9, 12, 8, 13, 55, 15, 8, 20, 26, 2], [4, 40, 47, 54, 32, 4, 10, 12, 4, 14, 5, 12, 10, 21, 9, 5, 14, 4, 6, 8, 4, 24, 13, 5, 39, 6, 13, 7, 10, 9, 4, 14, 5, 5, 24, 4, 25, 10, 14, 10, 13, 5, 17, 6, 10, 8, 9, 7, 15, 4, 13, 5, 24, 13, 5, 12, 5, 9, 6, 7, 6, 10, 8, 9, 12, 4, 19, 13, 8, 18, 4, 16, 9, 15, 7, 25, 5, 15, 5, 14, 4, 6, 5, 37, 6, 4, 25, 22, 4, 46, 8, 10, 9, 6, 15, 22, 4, 17, 8, 9, 14, 10, 6, 10, 8, 9, 10, 9, 21, 4, 8, 9, 4, 25, 8, 6, 11, 4, 15, 5, 19, 6, 4, 7, 9, 14, 4, 13, 10, 21, 11, 6, 4, 17, 8, 9, 6, 5, 37, 6, 4, 10, 9, 4, 7, 15, 15, 4, 15, 7, 22, 5, 13, 12, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [4, 32, 11, 5, 4, 45, 16, 10, 17, 28, 4, 25, 13, 8, 20, 9, 4, 19, 8, 37, 4, 46, 16, 18, 24, 12, 4, 8, 27, 5, 13, 4, 6, 11, 5, 4, 15, 7, 57, 22, 4, 14, 8, 21, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], ], """attention_mask""": [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] } # fmt: on self.tokenizer_integration_test_util( expected_encoding=__SCREAMING_SNAKE_CASE , model_name="""microsoft/speecht5_asr""" , revision="""c5ef64c71905caeccde0e4462ef3f9077224c524""" , sequences=__SCREAMING_SNAKE_CASE , )
267
'''simple docstring''' import unittest from diffusers import FlaxAutoencoderKL from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax from .test_modeling_common_flax import FlaxModelTesterMixin if is_flax_available(): import jax @require_flax class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = FlaxAutoencoderKL @property def UpperCAmelCase__ ( self : Tuple ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = 4 __SCREAMING_SNAKE_CASE = 3 __SCREAMING_SNAKE_CASE = (32, 32) __SCREAMING_SNAKE_CASE = jax.random.PRNGKey(0 ) __SCREAMING_SNAKE_CASE = jax.random.uniform(__SCREAMING_SNAKE_CASE , ((batch_size, num_channels) + sizes) ) return {"sample": image, "prng_key": prng_key} def UpperCAmelCase__ ( self : Union[str, Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = { """block_out_channels""": [32, 64], """in_channels""": 3, """out_channels""": 3, """down_block_types""": ["""DownEncoderBlock2D""", """DownEncoderBlock2D"""], """up_block_types""": ["""UpDecoderBlock2D""", """UpDecoderBlock2D"""], """latent_channels""": 4, } __SCREAMING_SNAKE_CASE = self.dummy_input return init_dict, inputs_dict
267
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 a__ ( ): """simple docstring""" __SCREAMING_SNAKE_CASE = HfArgumentParser((ModelArguments,) ) ((__SCREAMING_SNAKE_CASE) , ) = parser.parse_args_into_dataclasses() # Load pretrained model and tokenizer # Use explicit specified encoder config if model_args.encoder_config_name: __SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(model_args.encoder_config_name ) # Use pretrained encoder model's config else: __SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(model_args.encoder_model_name_or_path ) # Use explicit specified decoder config if model_args.decoder_config_name: __SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(model_args.decoder_config_name ) # Use pretrained decoder model's config else: __SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(model_args.decoder_model_name_or_path ) # necessary for `from_encoder_decoder_pretrained` when `decoder_config` is passed __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = 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 __SCREAMING_SNAKE_CASE = decoder_config.decoder_start_token_id __SCREAMING_SNAKE_CASE = decoder_config.pad_token_id if decoder_start_token_id is None: __SCREAMING_SNAKE_CASE = decoder_config.bos_token_id if pad_token_id is None: __SCREAMING_SNAKE_CASE = decoder_config.eos_token_id # This is necessary to make Flax's generate() work __SCREAMING_SNAKE_CASE = decoder_config.eos_token_id __SCREAMING_SNAKE_CASE = decoder_start_token_id __SCREAMING_SNAKE_CASE = pad_token_id __SCREAMING_SNAKE_CASE = AutoImageProcessor.from_pretrained(model_args.encoder_model_name_or_path ) __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(model_args.decoder_model_name_or_path ) __SCREAMING_SNAKE_CASE = 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()
267
'''simple docstring''' import itertools import os import random import tempfile import unittest import numpy as np from datasets import load_dataset from transformers import is_speech_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_speech_available(): from transformers import WhisperFeatureExtractor if is_torch_available(): import torch UpperCAmelCase : int = random.Random() def a__ ( a__ , a__=1.0 , a__=None , a__=None ): """simple docstring""" if rng is None: __SCREAMING_SNAKE_CASE = global_rng __SCREAMING_SNAKE_CASE = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch @require_torchaudio class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __init__( self : str , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : str=7 , __SCREAMING_SNAKE_CASE : List[str]=400 , __SCREAMING_SNAKE_CASE : Any=2_000 , __SCREAMING_SNAKE_CASE : List[str]=10 , __SCREAMING_SNAKE_CASE : Optional[int]=160 , __SCREAMING_SNAKE_CASE : List[str]=8 , __SCREAMING_SNAKE_CASE : Optional[Any]=0.0 , __SCREAMING_SNAKE_CASE : Dict=4_000 , __SCREAMING_SNAKE_CASE : Optional[int]=False , __SCREAMING_SNAKE_CASE : List[Any]=True , ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = min_seq_length __SCREAMING_SNAKE_CASE = max_seq_length __SCREAMING_SNAKE_CASE = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) __SCREAMING_SNAKE_CASE = padding_value __SCREAMING_SNAKE_CASE = sampling_rate __SCREAMING_SNAKE_CASE = return_attention_mask __SCREAMING_SNAKE_CASE = do_normalize __SCREAMING_SNAKE_CASE = feature_size __SCREAMING_SNAKE_CASE = chunk_length __SCREAMING_SNAKE_CASE = hop_length def UpperCAmelCase__ ( self : Dict ) -> Dict: """simple docstring""" return { "feature_size": self.feature_size, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def UpperCAmelCase__ ( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : Union[str, Any]=False , __SCREAMING_SNAKE_CASE : Optional[Any]=False ) -> Union[str, Any]: """simple docstring""" def _flatten(__SCREAMING_SNAKE_CASE : Dict ): return list(itertools.chain(*__SCREAMING_SNAKE_CASE ) ) if equal_length: __SCREAMING_SNAKE_CASE = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size __SCREAMING_SNAKE_CASE = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = WhisperFeatureExtractor if is_speech_available() else None def UpperCAmelCase__ ( self : str ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = WhisperFeatureExtractionTester(self ) def UpperCAmelCase__ ( self : str ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE = feat_extract_first.save_pretrained(__SCREAMING_SNAKE_CASE )[0] check_json_file_has_correct_format(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.feature_extraction_class.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = feat_extract_first.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_second.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_first.mel_filters __SCREAMING_SNAKE_CASE = feat_extract_second.mel_filters self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[str] ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE = os.path.join(__SCREAMING_SNAKE_CASE , """feat_extract.json""" ) feat_extract_first.to_json_file(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.feature_extraction_class.from_json_file(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = feat_extract_first.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_second.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_first.mel_filters __SCREAMING_SNAKE_CASE = feat_extract_second.mel_filters self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[Any] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in range(800 , 1_400 , 200 )] __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs] # Test feature size __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , padding="""max_length""" , return_tensors="""np""" ).input_features self.assertTrue(input_features.ndim == 3 ) self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames ) self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size ) # Test not batched input __SCREAMING_SNAKE_CASE = feature_extractor(speech_inputs[0] , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(np_speech_inputs[0] , return_tensors="""np""" ).input_features self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test batched __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test 2-D numpy arrays are batched. __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in (800, 800, 800)] __SCREAMING_SNAKE_CASE = np.asarray(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test truncation required __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in range(200 , (feature_extractor.n_samples + 500) , 200 )] __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs] __SCREAMING_SNAKE_CASE = [x[: feature_extractor.n_samples] for x in speech_inputs] __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs_truncated] __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) def UpperCAmelCase__ ( self : Dict ) -> Optional[int]: """simple docstring""" import torch __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __SCREAMING_SNAKE_CASE = np.random.rand(100 , 32 ).astype(np.floataa ) __SCREAMING_SNAKE_CASE = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: __SCREAMING_SNAKE_CASE = feature_extractor.pad([{"""input_features""": inputs}] , return_tensors="""np""" ) self.assertTrue(np_processed.input_features.dtype == np.floataa ) __SCREAMING_SNAKE_CASE = feature_extractor.pad([{"""input_features""": inputs}] , return_tensors="""pt""" ) self.assertTrue(pt_processed.input_features.dtype == torch.floataa ) def UpperCAmelCase__ ( self : str , __SCREAMING_SNAKE_CASE : Tuple ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = load_dataset("""hf-internal-testing/librispeech_asr_dummy""" , """clean""" , split="""validation""" ) # automatic decoding with librispeech __SCREAMING_SNAKE_CASE = ds.sort("""id""" ).select(range(__SCREAMING_SNAKE_CASE ) )[:num_samples]["""audio"""] return [x["array"] for x in speech_samples] def UpperCAmelCase__ ( self : Tuple ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = torch.tensor( [ 0.1193, -0.0946, -0.1098, -0.0196, 0.0225, -0.0690, -0.1736, 0.0951, 0.0971, -0.0817, -0.0702, 0.0162, 0.0260, 0.0017, -0.0192, -0.1678, 0.0709, -0.1867, -0.0655, -0.0274, -0.0234, -0.1884, -0.0516, -0.0554, -0.0274, -0.1425, -0.1423, 0.0837, 0.0377, -0.0854 ] ) # fmt: on __SCREAMING_SNAKE_CASE = self._load_datasamples(1 ) __SCREAMING_SNAKE_CASE = WhisperFeatureExtractor() __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).input_features self.assertEqual(input_features.shape , (1, 80, 3_000) ) self.assertTrue(torch.allclose(input_features[0, 0, :30] , __SCREAMING_SNAKE_CASE , atol=1E-4 ) ) def UpperCAmelCase__ ( self : List[Any] ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __SCREAMING_SNAKE_CASE = self._load_datasamples(1 )[0] __SCREAMING_SNAKE_CASE = ((audio - audio.min()) / (audio.max() - audio.min())) * 65_535 # Rescale to [0, 65535] to show issue __SCREAMING_SNAKE_CASE = feat_extract.zero_mean_unit_var_norm([audio] , attention_mask=__SCREAMING_SNAKE_CASE )[0] self.assertTrue(np.all(np.mean(__SCREAMING_SNAKE_CASE ) < 1E-3 ) ) self.assertTrue(np.all(np.abs(np.var(__SCREAMING_SNAKE_CASE ) - 1 ) < 1E-3 ) )
267
1
'''simple docstring''' import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class lowerCAmelCase__ ( a ): """simple docstring""" lowerCAmelCase__ = ["image_processor", "tokenizer"] lowerCAmelCase__ = "CLIPImageProcessor" lowerCAmelCase__ = ("XLMRobertaTokenizer", "XLMRobertaTokenizerFast") def __init__( self : str , __SCREAMING_SNAKE_CASE : int=None , __SCREAMING_SNAKE_CASE : List[Any]=None , **__SCREAMING_SNAKE_CASE : Optional[int] ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = None if "feature_extractor" in kwargs: warnings.warn( """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`""" """ instead.""" , __SCREAMING_SNAKE_CASE , ) __SCREAMING_SNAKE_CASE = kwargs.pop("""feature_extractor""" ) __SCREAMING_SNAKE_CASE = 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__(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def __call__( self : List[str] , __SCREAMING_SNAKE_CASE : int=None , __SCREAMING_SNAKE_CASE : str=None , __SCREAMING_SNAKE_CASE : List[Any]=None , **__SCREAMING_SNAKE_CASE : List[Any] ) -> str: """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: __SCREAMING_SNAKE_CASE = self.tokenizer(__SCREAMING_SNAKE_CASE , return_tensors=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) if images is not None: __SCREAMING_SNAKE_CASE = self.image_processor(__SCREAMING_SNAKE_CASE , return_tensors=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) if text is not None and images is not None: __SCREAMING_SNAKE_CASE = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**__SCREAMING_SNAKE_CASE ) , tensor_type=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[str] , *__SCREAMING_SNAKE_CASE : Dict , **__SCREAMING_SNAKE_CASE : int ) -> Optional[Any]: """simple docstring""" return self.tokenizer.batch_decode(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : int , *__SCREAMING_SNAKE_CASE : Optional[Any] , **__SCREAMING_SNAKE_CASE : Any ) -> Union[str, Any]: """simple docstring""" return self.tokenizer.decode(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) @property def UpperCAmelCase__ ( self : Union[str, Any] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer.model_input_names __SCREAMING_SNAKE_CASE = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
267
'''simple docstring''' from __future__ import annotations def a__ ( a__ , a__ , a__ ): """simple docstring""" if len(a__ ) == 0: raise ValueError("""find_max() arg is an empty sequence""" ) if ( left >= len(a__ ) or left < -len(a__ ) or right >= len(a__ ) or right < -len(a__ ) ): raise IndexError("""list index out of range""" ) if left == right: return nums[left] __SCREAMING_SNAKE_CASE = (left + right) >> 1 # the middle __SCREAMING_SNAKE_CASE = find_max(a__ , a__ , a__ ) # find max in range[left, mid] __SCREAMING_SNAKE_CASE = find_max(a__ , mid + 1 , a__ ) # find max in range[mid + 1, right] return left_max if left_max >= right_max else right_max if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
267
1
'''simple docstring''' import math from typing import Callable, List, Optional, Union import numpy as np import PIL import torch from PIL import Image from transformers import CLIPTextModel, CLIPTokenizer from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline from diffusers.schedulers import DDIMScheduler, DDPMScheduler, LMSDiscreteScheduler, PNDMScheduler def a__ ( a__ , a__ , a__=[] ): """simple docstring""" __SCREAMING_SNAKE_CASE = size[0] - overlap_pixels * 2 __SCREAMING_SNAKE_CASE = size[1] - overlap_pixels * 2 for letter in ["l", "r"]: if letter in remove_borders: size_x += overlap_pixels for letter in ["t", "b"]: if letter in remove_borders: size_y += overlap_pixels __SCREAMING_SNAKE_CASE = np.ones((size_y, size_x) , dtype=np.uinta ) * 2_55 __SCREAMING_SNAKE_CASE = np.pad(a__ , mode="""linear_ramp""" , pad_width=a__ , end_values=0 ) if "l" in remove_borders: __SCREAMING_SNAKE_CASE = mask[:, overlap_pixels : mask.shape[1]] if "r" in remove_borders: __SCREAMING_SNAKE_CASE = mask[:, 0 : mask.shape[1] - overlap_pixels] if "t" in remove_borders: __SCREAMING_SNAKE_CASE = mask[overlap_pixels : mask.shape[0], :] if "b" in remove_borders: __SCREAMING_SNAKE_CASE = mask[0 : mask.shape[0] - overlap_pixels, :] return mask def a__ ( a__ , a__ , a__ ): """simple docstring""" return max(a__ , min(a__ , a__ ) ) def a__ ( a__ , a__ , a__ ): """simple docstring""" return ( clamp(rect[0] , min[0] , max[0] ), clamp(rect[1] , min[1] , max[1] ), clamp(rect[2] , min[0] , max[0] ), clamp(rect[3] , min[1] , max[1] ), ) def a__ ( a__ , a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = list(a__ ) rect[0] -= overlap rect[1] -= overlap rect[2] += overlap rect[3] += overlap __SCREAMING_SNAKE_CASE = clamp_rect(a__ , [0, 0] , [image_size[0], image_size[1]] ) return rect def a__ ( a__ , a__ , a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = Image.new("""RGB""" , (tile.size[0] + original_slice, tile.size[1]) ) result.paste( original_image.resize((tile.size[0], tile.size[1]) , Image.BICUBIC ).crop( (slice_x, 0, slice_x + original_slice, tile.size[1]) ) , (0, 0) , ) result.paste(a__ , (original_slice, 0) ) return result def a__ ( a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = (original_image_slice * 4, 0, tile.size[0], tile.size[1]) __SCREAMING_SNAKE_CASE = tile.crop(a__ ) return tile def a__ ( a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = n % d return n - divisor class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : AutoencoderKL , __SCREAMING_SNAKE_CASE : CLIPTextModel , __SCREAMING_SNAKE_CASE : CLIPTokenizer , __SCREAMING_SNAKE_CASE : UNetaDConditionModel , __SCREAMING_SNAKE_CASE : DDPMScheduler , __SCREAMING_SNAKE_CASE : Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] , __SCREAMING_SNAKE_CASE : int = 350 , ) -> int: """simple docstring""" super().__init__( vae=__SCREAMING_SNAKE_CASE , text_encoder=__SCREAMING_SNAKE_CASE , tokenizer=__SCREAMING_SNAKE_CASE , unet=__SCREAMING_SNAKE_CASE , low_res_scheduler=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE , max_noise_level=__SCREAMING_SNAKE_CASE , ) def UpperCAmelCase__ ( self : List[Any] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : int , **__SCREAMING_SNAKE_CASE : str ) -> List[Any]: """simple docstring""" torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = ( min(image.size[0] - (tile_size + original_image_slice) , x * tile_size ), min(image.size[1] - (tile_size + original_image_slice) , y * tile_size ), min(image.size[0] , (x + 1) * tile_size ), min(image.size[1] , (y + 1) * tile_size ), ) __SCREAMING_SNAKE_CASE = add_overlap_rect(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , image.size ) __SCREAMING_SNAKE_CASE = image.crop(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = ((crop_rect[0] + ((crop_rect[2] - crop_rect[0]) / 2)) / image.size[0]) * tile.size[0] __SCREAMING_SNAKE_CASE = translated_slice_x - (original_image_slice / 2) __SCREAMING_SNAKE_CASE = max(0 , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = squeeze_tile(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = to_input.size __SCREAMING_SNAKE_CASE = to_input.resize((tile_size, tile_size) , Image.BICUBIC ) __SCREAMING_SNAKE_CASE = super(__SCREAMING_SNAKE_CASE , self ).__call__(image=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ).images[0] __SCREAMING_SNAKE_CASE = upscaled_tile.resize((orig_input_size[0] * 4, orig_input_size[1] * 4) , Image.BICUBIC ) __SCREAMING_SNAKE_CASE = unsqueeze_tile(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = upscaled_tile.resize((tile.size[0] * 4, tile.size[1] * 4) , Image.BICUBIC ) __SCREAMING_SNAKE_CASE = [] if x == 0: remove_borders.append("""l""" ) elif crop_rect[2] == image.size[0]: remove_borders.append("""r""" ) if y == 0: remove_borders.append("""t""" ) elif crop_rect[3] == image.size[1]: remove_borders.append("""b""" ) __SCREAMING_SNAKE_CASE = Image.fromarray( make_transparency_mask( (upscaled_tile.size[0], upscaled_tile.size[1]) , tile_border * 4 , remove_borders=__SCREAMING_SNAKE_CASE ) , mode="""L""" , ) final_image.paste( __SCREAMING_SNAKE_CASE , (crop_rect_with_overlap[0] * 4, crop_rect_with_overlap[1] * 4) , __SCREAMING_SNAKE_CASE ) @torch.no_grad() def __call__( self : List[str] , __SCREAMING_SNAKE_CASE : Union[str, List[str]] , __SCREAMING_SNAKE_CASE : Union[PIL.Image.Image, List[PIL.Image.Image]] , __SCREAMING_SNAKE_CASE : int = 75 , __SCREAMING_SNAKE_CASE : float = 9.0 , __SCREAMING_SNAKE_CASE : int = 50 , __SCREAMING_SNAKE_CASE : Optional[Union[str, List[str]]] = None , __SCREAMING_SNAKE_CASE : Optional[int] = 1 , __SCREAMING_SNAKE_CASE : float = 0.0 , __SCREAMING_SNAKE_CASE : Optional[torch.Generator] = None , __SCREAMING_SNAKE_CASE : Optional[torch.FloatTensor] = None , __SCREAMING_SNAKE_CASE : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __SCREAMING_SNAKE_CASE : int = 1 , __SCREAMING_SNAKE_CASE : int = 128 , __SCREAMING_SNAKE_CASE : int = 32 , __SCREAMING_SNAKE_CASE : int = 32 , ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = Image.new("""RGB""" , (image.size[0] * 4, image.size[1] * 4) ) __SCREAMING_SNAKE_CASE = math.ceil(image.size[0] / tile_size ) __SCREAMING_SNAKE_CASE = math.ceil(image.size[1] / tile_size ) __SCREAMING_SNAKE_CASE = tcx * tcy __SCREAMING_SNAKE_CASE = 0 for y in range(__SCREAMING_SNAKE_CASE ): for x in range(__SCREAMING_SNAKE_CASE ): self._process_tile( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , prompt=__SCREAMING_SNAKE_CASE , num_inference_steps=__SCREAMING_SNAKE_CASE , guidance_scale=__SCREAMING_SNAKE_CASE , noise_level=__SCREAMING_SNAKE_CASE , negative_prompt=__SCREAMING_SNAKE_CASE , num_images_per_prompt=__SCREAMING_SNAKE_CASE , eta=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , latents=__SCREAMING_SNAKE_CASE , ) current_count += 1 if callback is not None: callback({"""progress""": current_count / total_tile_count, """image""": final_image} ) return final_image def a__ ( ): """simple docstring""" __SCREAMING_SNAKE_CASE = """stabilityai/stable-diffusion-x4-upscaler""" __SCREAMING_SNAKE_CASE = StableDiffusionTiledUpscalePipeline.from_pretrained(a__ , revision="""fp16""" , torch_dtype=torch.floataa ) __SCREAMING_SNAKE_CASE = pipe.to("""cuda""" ) __SCREAMING_SNAKE_CASE = Image.open("""../../docs/source/imgs/diffusers_library.jpg""" ) def callback(a__ ): print(F'progress: {obj["progress"]:.4f}' ) obj["image"].save("""diffusers_library_progress.jpg""" ) __SCREAMING_SNAKE_CASE = pipe(image=a__ , prompt="""Black font, white background, vector""" , noise_level=40 , callback=a__ ) final_image.save("""diffusers_library.jpg""" ) if __name__ == "__main__": main()
267
'''simple docstring''' def a__ ( a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) # Initialize Result __SCREAMING_SNAKE_CASE = [] # Traverse through all denomination for denomination in reversed(a__ ): # Find denominations while int(a__ ) >= int(a__ ): total_value -= int(a__ ) answer.append(a__ ) # Append the "answers" array return answer # Driver Code if __name__ == "__main__": UpperCAmelCase : Dict = [] UpperCAmelCase : List[str] = '0' if ( input('Do you want to enter your denominations ? (yY/n): ').strip().lower() == "y" ): UpperCAmelCase : List[str] = int(input('Enter the number of denominations you want to add: ').strip()) for i in range(0, n): denominations.append(int(input(f"""Denomination {i}: """).strip())) UpperCAmelCase : str = input('Enter the change you want to make in Indian Currency: ').strip() else: # All denominations of Indian Currency if user does not enter UpperCAmelCase : int = [1, 2, 5, 1_0, 2_0, 5_0, 1_0_0, 5_0_0, 2_0_0_0] UpperCAmelCase : Any = input('Enter the change you want to make: ').strip() if int(value) == 0 or int(value) < 0: print('The total value cannot be zero or negative.') else: print(f"""Following is minimal change for {value}: """) UpperCAmelCase : Any = find_minimum_change(denominations, value) # Print result for i in range(len(answer)): print(answer[i], end=' ')
267
1
'''simple docstring''' from __future__ import annotations import math from collections.abc import Callable def a__ ( a__ , a__ , a__ , a__ = 1_00 , ): """simple docstring""" __SCREAMING_SNAKE_CASE = x_start __SCREAMING_SNAKE_CASE = fnc(a__ ) __SCREAMING_SNAKE_CASE = 0.0 for _ in range(a__ ): # Approximates curve as a sequence of linear lines and sums their length __SCREAMING_SNAKE_CASE = (x_end - x_start) / steps + xa __SCREAMING_SNAKE_CASE = fnc(a__ ) length += math.hypot(xa - xa , fxa - fxa ) # Increment step __SCREAMING_SNAKE_CASE = xa __SCREAMING_SNAKE_CASE = fxa return length if __name__ == "__main__": def a__ ( a__ ): """simple docstring""" return math.sin(10 * x ) print('f(x) = sin(10 * x)') print('The length of the curve from x = -10 to x = 10 is:') UpperCAmelCase : Union[str, Any] = 1_0 while i <= 1_0_0_0_0_0: print(f"""With {i} steps: {line_length(f, -1_0, 1_0, i)}""") i *= 1_0
267
'''simple docstring''' # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse from ...utils.dataclasses import ( ComputeEnvironment, DistributedType, DynamoBackend, PrecisionType, SageMakerDistributedType, ) from ..menu import BulletMenu UpperCAmelCase : Any = [ 'EAGER', 'AOT_EAGER', 'INDUCTOR', 'NVFUSER', 'AOT_NVFUSER', 'AOT_CUDAGRAPHS', 'OFI', 'FX2TRT', 'ONNXRT', 'IPEX', ] def a__ ( a__ , a__=None , a__=None , a__=None ): """simple docstring""" __SCREAMING_SNAKE_CASE = True while ask_again: __SCREAMING_SNAKE_CASE = input(a__ ) try: if default is not None and len(a__ ) == 0: return default return convert_value(a__ ) if convert_value is not None else result except Exception: if error_message is not None: print(a__ ) def a__ ( a__ , a__=[] , a__=None , a__=0 ): """simple docstring""" __SCREAMING_SNAKE_CASE = BulletMenu(a__ , a__ ) __SCREAMING_SNAKE_CASE = menu.run(default_choice=a__ ) return convert_value(a__ ) if convert_value is not None else result def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return ComputeEnvironment(["""LOCAL_MACHINE""", """AMAZON_SAGEMAKER"""][value] ) def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return DistributedType(["""NO""", """MULTI_CPU""", """MULTI_XPU""", """MULTI_GPU""", """MULTI_NPU""", """TPU"""][value] ) def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return DynamoBackend(DYNAMO_BACKENDS[value] ).value def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return PrecisionType(["""no""", """fp16""", """bf16""", """fp8"""][value] ) def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return SageMakerDistributedType(["""NO""", """DATA_PARALLEL""", """MODEL_PARALLEL"""][value] ) def a__ ( a__ ): """simple docstring""" return {"yes": True, "no": False}[value.lower()] class lowerCAmelCase__ ( argparse.RawDescriptionHelpFormatter ): """simple docstring""" def UpperCAmelCase__ ( self : str , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : List[Any] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = super()._format_usage(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = usage.replace("""<command> [<args>] """ , """""" ) return usage
267
1
'''simple docstring''' from __future__ import annotations class lowerCAmelCase__ : """simple docstring""" def __init__( self : Optional[Any] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : str ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = text, pattern __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = len(__SCREAMING_SNAKE_CASE ), len(__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : int , __SCREAMING_SNAKE_CASE : str ) -> int: """simple docstring""" for i in range(self.patLen - 1 , -1 , -1 ): if char == self.pattern[i]: return i return -1 def UpperCAmelCase__ ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : int ) -> int: """simple docstring""" for i in range(self.patLen - 1 , -1 , -1 ): if self.pattern[i] != self.text[current_pos + i]: return current_pos + i return -1 def UpperCAmelCase__ ( self : Tuple ) -> list[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = [] for i in range(self.textLen - self.patLen + 1 ): __SCREAMING_SNAKE_CASE = self.mismatch_in_text(__SCREAMING_SNAKE_CASE ) if mismatch_index == -1: positions.append(__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = self.match_in_pattern(self.text[mismatch_index] ) __SCREAMING_SNAKE_CASE = ( mismatch_index - match_index ) # shifting index lgtm [py/multiple-definition] return positions UpperCAmelCase : Optional[Any] = 'ABAABA' UpperCAmelCase : Any = 'AB' UpperCAmelCase : List[str] = BoyerMooreSearch(text, pattern) UpperCAmelCase : List[str] = bms.bad_character_heuristic() if len(positions) == 0: print('No match found') else: print('Pattern found in following positions: ') print(positions)
267
'''simple docstring''' def a__ ( a__ , a__ ): """simple docstring""" _enforce_args(a__ , a__ ) if n == 0: return 0 __SCREAMING_SNAKE_CASE = float("""-inf""" ) for i in range(1 , n + 1 ): __SCREAMING_SNAKE_CASE = max( a__ , prices[i - 1] + naive_cut_rod_recursive(n - i , a__ ) ) return max_revue def a__ ( a__ , a__ ): """simple docstring""" _enforce_args(a__ , a__ ) __SCREAMING_SNAKE_CASE = [float("""-inf""" ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ ): """simple docstring""" if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: __SCREAMING_SNAKE_CASE = float("""-inf""" ) for i in range(1 , n + 1 ): __SCREAMING_SNAKE_CASE = max( a__ , prices[i - 1] + _top_down_cut_rod_recursive(n - i , a__ , a__ ) , ) __SCREAMING_SNAKE_CASE = max_revenue return max_rev[n] def a__ ( a__ , a__ ): """simple docstring""" _enforce_args(a__ , a__ ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. __SCREAMING_SNAKE_CASE = [float("""-inf""" ) for _ in range(n + 1 )] __SCREAMING_SNAKE_CASE = 0 for i in range(1 , n + 1 ): __SCREAMING_SNAKE_CASE = max_rev[i] for j in range(1 , i + 1 ): __SCREAMING_SNAKE_CASE = max(a__ , prices[j - 1] + max_rev[i - j] ) __SCREAMING_SNAKE_CASE = max_revenue_i return max_rev[n] def a__ ( a__ , a__ ): """simple docstring""" if n < 0: __SCREAMING_SNAKE_CASE = F'n must be greater than or equal to 0. Got n = {n}' raise ValueError(a__ ) if n > len(a__ ): __SCREAMING_SNAKE_CASE = ( """Each integral piece of rod must have a corresponding price. """ F'Got n = {n} but length of prices = {len(a__ )}' ) raise ValueError(a__ ) def a__ ( ): """simple docstring""" __SCREAMING_SNAKE_CASE = [6, 10, 12, 15, 20, 23] __SCREAMING_SNAKE_CASE = len(a__ ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. __SCREAMING_SNAKE_CASE = 36 __SCREAMING_SNAKE_CASE = top_down_cut_rod(a__ , a__ ) __SCREAMING_SNAKE_CASE = bottom_up_cut_rod(a__ , a__ ) __SCREAMING_SNAKE_CASE = naive_cut_rod_recursive(a__ , a__ ) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
267
1
'''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 a__ ( ): """simple docstring""" __SCREAMING_SNAKE_CASE = """https://storage.googleapis.com/sfr-vision-language-research/LAVIS/assets/merlion.png""" __SCREAMING_SNAKE_CASE = Image.open(requests.get(a__ , stream=a__ ).raw ).convert("""RGB""" ) return image def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = [] # 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 a__ ( a__ , a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = dct.pop(a__ ) __SCREAMING_SNAKE_CASE = val def a__ ( a__ , a__ ): """simple docstring""" for i in range(config.vision_config.num_hidden_layers ): # read in original q and v biases __SCREAMING_SNAKE_CASE = state_dict.pop(F'visual_encoder.blocks.{i}.attn.q_bias' ) __SCREAMING_SNAKE_CASE = state_dict.pop(F'visual_encoder.blocks.{i}.attn.v_bias' ) # next, set bias in the state dict __SCREAMING_SNAKE_CASE = torch.cat((q_bias, torch.zeros_like(a__ , requires_grad=a__ ), v_bias) ) __SCREAMING_SNAKE_CASE = qkv_bias def a__ ( a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = 3_64 if """coco""" in model_name else 2_24 __SCREAMING_SNAKE_CASE = BlipaVisionConfig(image_size=a__ ).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: __SCREAMING_SNAKE_CASE = OPTConfig.from_pretrained("""facebook/opt-2.7b""" , eos_token_id=a__ ).to_dict() elif "opt-6.7b" in model_name: __SCREAMING_SNAKE_CASE = OPTConfig.from_pretrained("""facebook/opt-6.7b""" , eos_token_id=a__ ).to_dict() elif "t5-xl" in model_name: __SCREAMING_SNAKE_CASE = TaConfig.from_pretrained("""google/flan-t5-xl""" , dense_act_fn="""gelu""" , bos_token_id=1 ).to_dict() elif "t5-xxl" in model_name: __SCREAMING_SNAKE_CASE = TaConfig.from_pretrained("""google/flan-t5-xxl""" , dense_act_fn="""gelu""" , bos_token_id=1 ).to_dict() __SCREAMING_SNAKE_CASE = BlipaConfig(vision_config=a__ , text_config=a__ ) return config, image_size @torch.no_grad() def a__ ( a__ , a__=None , a__=False ): """simple docstring""" __SCREAMING_SNAKE_CASE = ( AutoTokenizer.from_pretrained("""facebook/opt-2.7b""" ) if """opt""" in model_name else AutoTokenizer.from_pretrained("""google/flan-t5-xl""" ) ) __SCREAMING_SNAKE_CASE = tokenizer("""\n""" , add_special_tokens=a__ ).input_ids[0] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = get_blipa_config(a__ , eos_token_id=a__ ) __SCREAMING_SNAKE_CASE = BlipaForConditionalGeneration(a__ ).eval() __SCREAMING_SNAKE_CASE = { """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"""), } __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = model_name_to_original[model_name] # load original model print("""Loading original model...""" ) __SCREAMING_SNAKE_CASE = """cuda""" if torch.cuda.is_available() else """cpu""" __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = load_model_and_preprocess( name=a__ , model_type=a__ , is_eval=a__ , device=a__ ) original_model.eval() print("""Done!""" ) # update state dict keys __SCREAMING_SNAKE_CASE = original_model.state_dict() __SCREAMING_SNAKE_CASE = create_rename_keys(a__ ) for src, dest in rename_keys: rename_key(a__ , a__ , a__ ) # some keys can be renamed efficiently for key, val in state_dict.copy().items(): __SCREAMING_SNAKE_CASE = state_dict.pop(a__ ) if key.startswith("""Qformer.bert""" ): __SCREAMING_SNAKE_CASE = key.replace("""Qformer.bert""" , """qformer""" ) if "attention.self" in key: __SCREAMING_SNAKE_CASE = key.replace("""self""" , """attention""" ) if "opt_proj" in key: __SCREAMING_SNAKE_CASE = key.replace("""opt_proj""" , """language_projection""" ) if "t5_proj" in key: __SCREAMING_SNAKE_CASE = key.replace("""t5_proj""" , """language_projection""" ) if key.startswith("""opt""" ): __SCREAMING_SNAKE_CASE = key.replace("""opt""" , """language""" ) if key.startswith("""t5""" ): __SCREAMING_SNAKE_CASE = key.replace("""t5""" , """language""" ) __SCREAMING_SNAKE_CASE = val # read in qv biases read_in_q_v_bias(a__ , a__ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = hf_model.load_state_dict(a__ , strict=a__ ) assert len(a__ ) == 0 assert unexpected_keys == ["qformer.embeddings.position_ids"] __SCREAMING_SNAKE_CASE = load_demo_image() __SCREAMING_SNAKE_CASE = vis_processors["""eval"""](a__ ).unsqueeze(0 ).to(a__ ) __SCREAMING_SNAKE_CASE = tokenizer(["""\n"""] , return_tensors="""pt""" ).input_ids.to(a__ ) # create processor __SCREAMING_SNAKE_CASE = BlipImageProcessor( size={"""height""": image_size, """width""": image_size} , image_mean=a__ , image_std=a__ ) __SCREAMING_SNAKE_CASE = BlipaProcessor(image_processor=a__ , tokenizer=a__ ) __SCREAMING_SNAKE_CASE = processor(images=a__ , return_tensors="""pt""" ).pixel_values.to(a__ ) # make sure processor creates exact same pixel values assert torch.allclose(a__ , a__ ) original_model.to(a__ ) hf_model.to(a__ ) with torch.no_grad(): if "opt" in model_name: __SCREAMING_SNAKE_CASE = original_model({"""image""": original_pixel_values, """text_input""": [""""""]} ).logits __SCREAMING_SNAKE_CASE = hf_model(a__ , a__ ).logits else: __SCREAMING_SNAKE_CASE = original_model( {"""image""": original_pixel_values, """text_input""": ["""\n"""], """text_output""": ["""\n"""]} ).logits __SCREAMING_SNAKE_CASE = input_ids.masked_fill(input_ids == tokenizer.pad_token_id , -1_00 ) __SCREAMING_SNAKE_CASE = hf_model(a__ , a__ , labels=a__ ).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": __SCREAMING_SNAKE_CASE = torch.tensor( [[-41.5_850, -4.4_440, -8.9_922], [-47.4_322, -5.9_143, -1.7_340]] , device=a__ ) assert torch.allclose(logits[0, :3, :3] , a__ , atol=1E-4 ) elif model_name == "blip2-flan-t5-xl-coco": __SCREAMING_SNAKE_CASE = torch.tensor( [[-57.0_109, -9.8_967, -12.6_280], [-68.6_578, -12.7_191, -10.5_065]] , device=a__ ) else: # cast to same type __SCREAMING_SNAKE_CASE = logits.dtype assert torch.allclose(original_logits.to(a__ ) , a__ , atol=1E-2 ) print("""Looks ok!""" ) print("""Generating a caption...""" ) __SCREAMING_SNAKE_CASE = """""" __SCREAMING_SNAKE_CASE = tokenizer(a__ , return_tensors="""pt""" ).input_ids.to(a__ ) __SCREAMING_SNAKE_CASE = original_model.generate({"""image""": original_pixel_values} ) __SCREAMING_SNAKE_CASE = hf_model.generate( a__ , a__ , do_sample=a__ , num_beams=5 , max_length=30 , min_length=1 , top_p=0.9 , repetition_penalty=1.0 , length_penalty=1.0 , temperature=1 , ) print("""Original generation:""" , a__ ) __SCREAMING_SNAKE_CASE = input_ids.shape[1] __SCREAMING_SNAKE_CASE = processor.batch_decode(outputs[:, prompt_length:] , skip_special_tokens=a__ ) __SCREAMING_SNAKE_CASE = [text.strip() for text in output_text] print("""HF generation:""" , a__ ) if pytorch_dump_folder_path is not None: processor.save_pretrained(a__ ) hf_model.save_pretrained(a__ ) if push_to_hub: processor.push_to_hub(F'nielsr/{model_name}' ) hf_model.push_to_hub(F'nielsr/{model_name}' ) if __name__ == "__main__": UpperCAmelCase : str = argparse.ArgumentParser() UpperCAmelCase : str = [ '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', ) UpperCAmelCase : Optional[int] = parser.parse_args() convert_blipa_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
267
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase : Union[str, Any] = {'configuration_sew': ['SEW_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SEWConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Union[str, Any] = [ 'SEW_PRETRAINED_MODEL_ARCHIVE_LIST', 'SEWForCTC', 'SEWForSequenceClassification', 'SEWModel', 'SEWPreTrainedModel', ] if TYPE_CHECKING: from .configuration_sew import SEW_PRETRAINED_CONFIG_ARCHIVE_MAP, SEWConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_sew import ( SEW_PRETRAINED_MODEL_ARCHIVE_LIST, SEWForCTC, SEWForSequenceClassification, SEWModel, SEWPreTrainedModel, ) else: import sys UpperCAmelCase : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
267
1
'''simple docstring''' import numpy as np from scipy.spatial.distance import cdist from sklearn.metrics import fa_score import datasets UpperCAmelCase : int = '\\n @inproceedings{kakwani2020indicnlpsuite,\n title={{IndicNLPSuite: Monolingual Corpora, Evaluation Benchmarks and Pre-trained Multilingual Language Models for Indian Languages}},\n author={Divyanshu Kakwani and Anoop Kunchukuttan and Satish Golla and Gokul N.C. and Avik Bhattacharyya and Mitesh M. Khapra and Pratyush Kumar},\n year={2020},\n booktitle={Findings of EMNLP},\n}\n' UpperCAmelCase : Any = '\\n IndicGLUE is a natural language understanding benchmark for Indian languages. It contains a wide\n variety of tasks and covers 11 major Indian languages - as, bn, gu, hi, kn, ml, mr, or, pa, ta, te.\n' UpperCAmelCase : List[str] = '\nCompute IndicGLUE evaluation metric associated to each IndicGLUE dataset.\nArgs:\n predictions: list of predictions to score (as int64),\n except for \'cvit-mkb-clsr\' where each prediction is a vector (of float32).\n references: list of ground truth labels corresponding to the predictions (as int64),\n except for \'cvit-mkb-clsr\' where each reference is a vector (of float32).\nReturns: depending on the IndicGLUE subset, one or several of:\n "accuracy": Accuracy\n "f1": F1 score\n "precision": Precision@10\nExamples:\n\n >>> indic_glue_metric = datasets.load_metric(\'indic_glue\', \'wnli\') # \'wnli\' or any of ["copa", "sna", "csqa", "wstp", "inltkh", "bbca", "iitp-mr", "iitp-pr", "actsa-sc", "md"]\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = indic_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0}\n\n >>> indic_glue_metric = datasets.load_metric(\'indic_glue\', \'wiki-ner\')\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = indic_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0, \'f1\': 1.0}\n\n >>> indic_glue_metric = datasets.load_metric(\'indic_glue\', \'cvit-mkb-clsr\')\n >>> references = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]]\n >>> predictions = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]]\n >>> results = indic_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'precision@10\': 1.0}\n\n' def a__ ( a__ , a__ ): """simple docstring""" return float((preds == labels).mean() ) def a__ ( a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = simple_accuracy(a__ , a__ ) __SCREAMING_SNAKE_CASE = float(fa_score(y_true=a__ , y_pred=a__ ) ) return { "accuracy": acc, "f1": fa, } def a__ ( a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = np.array(a__ ) __SCREAMING_SNAKE_CASE = np.array(a__ ) __SCREAMING_SNAKE_CASE = en_sentvecs.shape[0] # mean centering __SCREAMING_SNAKE_CASE = en_sentvecs - np.mean(a__ , axis=0 ) __SCREAMING_SNAKE_CASE = in_sentvecs - np.mean(a__ , axis=0 ) __SCREAMING_SNAKE_CASE = cdist(a__ , a__ , """cosine""" ) __SCREAMING_SNAKE_CASE = np.array(range(a__ ) ) __SCREAMING_SNAKE_CASE = sim.argsort(axis=1 )[:, :10] __SCREAMING_SNAKE_CASE = np.any(preds == actual[:, None] , axis=1 ) return float(matches.mean() ) @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase__ ( datasets.Metric ): """simple docstring""" def UpperCAmelCase__ ( self : str ) -> Optional[int]: """simple docstring""" if self.config_name not in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", "wiki-ner", ]: raise KeyError( """You should supply a configuration name selected in """ """[\"wnli\", \"copa\", \"sna\", \"csqa\", \"wstp\", \"inltkh\", \"bbca\", """ """\"cvit-mkb-clsr\", \"iitp-mr\", \"iitp-pr\", \"actsa-sc\", \"md\", """ """\"wiki-ner\"]""" ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""int64""" ) if self.config_name != """cvit-mkb-clsr""" else datasets.Sequence(datasets.Value("""float32""" ) ), """references""": datasets.Value("""int64""" ) if self.config_name != """cvit-mkb-clsr""" else datasets.Sequence(datasets.Value("""float32""" ) ), } ) , codebase_urls=[] , reference_urls=[] , format="""numpy""" if self.config_name != """cvit-mkb-clsr""" else None , ) def UpperCAmelCase__ ( self : str , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : str ) -> List[str]: """simple docstring""" if self.config_name == "cvit-mkb-clsr": return {"precision@10": precision_at_aa(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )} elif self.config_name in ["wiki-ner"]: return acc_and_fa(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) elif self.config_name in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "iitp-mr", "iitp-pr", "actsa-sc", "md", ]: return {"accuracy": simple_accuracy(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )} else: raise KeyError( """You should supply a configuration name selected in """ """[\"wnli\", \"copa\", \"sna\", \"csqa\", \"wstp\", \"inltkh\", \"bbca\", """ """\"cvit-mkb-clsr\", \"iitp-mr\", \"iitp-pr\", \"actsa-sc\", \"md\", """ """\"wiki-ner\"]""" )
267
'''simple docstring''' class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Any ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = name __SCREAMING_SNAKE_CASE = value __SCREAMING_SNAKE_CASE = weight def __repr__( self : str ) -> Union[str, Any]: """simple docstring""" return f'{self.__class__.__name__}({self.name}, {self.value}, {self.weight})' def UpperCAmelCase__ ( self : List[Any] ) -> List[Any]: """simple docstring""" return self.value def UpperCAmelCase__ ( self : Any ) -> str: """simple docstring""" return self.name def UpperCAmelCase__ ( self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" return self.weight def UpperCAmelCase__ ( self : int ) -> Tuple: """simple docstring""" return self.value / self.weight def a__ ( a__ , a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = [] for i in range(len(a__ ) ): menu.append(Things(name[i] , value[i] , weight[i] ) ) return menu def a__ ( a__ , a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = sorted(a__ , key=a__ , reverse=a__ ) __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = 0.0, 0.0 for i in range(len(a__ ) ): if (total_cost + items_copy[i].get_weight()) <= max_cost: result.append(items_copy[i] ) total_cost += items_copy[i].get_weight() total_value += items_copy[i].get_value() return (result, total_value) def a__ ( ): """simple docstring""" if __name__ == "__main__": import doctest doctest.testmod()
267
1
'''simple docstring''' import torch from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward from transformers.models.bert.modeling_bert import ( BERT_INPUTS_DOCSTRING, BERT_START_DOCSTRING, BertEmbeddings, BertLayer, BertPooler, BertPreTrainedModel, ) def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = torch.exp(a__ ) __SCREAMING_SNAKE_CASE = torch.sum(a__ , dim=1 ) # sum of exp(x_i) __SCREAMING_SNAKE_CASE = torch.sum(x * exp_x , dim=1 ) # sum of x_i * exp(x_i) return torch.log(a__ ) - B / A class lowerCAmelCase__ ( nn.Module ): """simple docstring""" def __init__( self : Tuple , __SCREAMING_SNAKE_CASE : List[Any] ) -> Optional[int]: """simple docstring""" super().__init__() __SCREAMING_SNAKE_CASE = config.output_attentions __SCREAMING_SNAKE_CASE = config.output_hidden_states __SCREAMING_SNAKE_CASE = nn.ModuleList([BertLayer(__SCREAMING_SNAKE_CASE ) for _ in range(config.num_hidden_layers )] ) __SCREAMING_SNAKE_CASE = nn.ModuleList([BertHighway(__SCREAMING_SNAKE_CASE ) for _ in range(config.num_hidden_layers )] ) __SCREAMING_SNAKE_CASE = [-1 for _ in range(config.num_hidden_layers )] def UpperCAmelCase__ ( self : int , __SCREAMING_SNAKE_CASE : List[Any] ) -> int: """simple docstring""" if (type(__SCREAMING_SNAKE_CASE ) is float) or (type(__SCREAMING_SNAKE_CASE ) is int): for i in range(len(self.early_exit_entropy ) ): __SCREAMING_SNAKE_CASE = x else: __SCREAMING_SNAKE_CASE = x def UpperCAmelCase__ ( self : Tuple , __SCREAMING_SNAKE_CASE : int ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = pooler.state_dict() for highway in self.highway: for name, param in highway.pooler.state_dict().items(): param.copy_(loaded_model[name] ) def UpperCAmelCase__ ( self : Optional[int] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : str=None , __SCREAMING_SNAKE_CASE : Tuple=None , __SCREAMING_SNAKE_CASE : int=None , __SCREAMING_SNAKE_CASE : Union[str, Any]=None , ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = () __SCREAMING_SNAKE_CASE = () __SCREAMING_SNAKE_CASE = () for i, layer_module in enumerate(self.layer ): if self.output_hidden_states: __SCREAMING_SNAKE_CASE = all_hidden_states + (hidden_states,) __SCREAMING_SNAKE_CASE = layer_module( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , head_mask[i] , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = layer_outputs[0] if self.output_attentions: __SCREAMING_SNAKE_CASE = all_attentions + (layer_outputs[1],) __SCREAMING_SNAKE_CASE = (hidden_states,) if self.output_hidden_states: __SCREAMING_SNAKE_CASE = current_outputs + (all_hidden_states,) if self.output_attentions: __SCREAMING_SNAKE_CASE = current_outputs + (all_attentions,) __SCREAMING_SNAKE_CASE = self.highway[i](__SCREAMING_SNAKE_CASE ) # logits, pooled_output if not self.training: __SCREAMING_SNAKE_CASE = highway_exit[0] __SCREAMING_SNAKE_CASE = entropy(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = highway_exit + (highway_entropy,) # logits, hidden_states(?), entropy __SCREAMING_SNAKE_CASE = all_highway_exits + (highway_exit,) if highway_entropy < self.early_exit_entropy[i]: __SCREAMING_SNAKE_CASE = (highway_logits,) + current_outputs[1:] + (all_highway_exits,) raise HighwayException(__SCREAMING_SNAKE_CASE , i + 1 ) else: __SCREAMING_SNAKE_CASE = all_highway_exits + (highway_exit,) # Add last layer if self.output_hidden_states: __SCREAMING_SNAKE_CASE = all_hidden_states + (hidden_states,) __SCREAMING_SNAKE_CASE = (hidden_states,) if self.output_hidden_states: __SCREAMING_SNAKE_CASE = outputs + (all_hidden_states,) if self.output_attentions: __SCREAMING_SNAKE_CASE = outputs + (all_attentions,) __SCREAMING_SNAKE_CASE = outputs + (all_highway_exits,) return outputs # last-layer hidden state, (all hidden states), (all attentions), all highway exits @add_start_docstrings( "The Bert Model transformer with early exiting (DeeBERT). " , a , ) class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : Any ) -> Optional[int]: """simple docstring""" super().__init__(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = config __SCREAMING_SNAKE_CASE = BertEmbeddings(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = DeeBertEncoder(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = BertPooler(__SCREAMING_SNAKE_CASE ) self.init_weights() def UpperCAmelCase__ ( self : Any ) -> Optional[int]: """simple docstring""" self.encoder.init_highway_pooler(self.pooler ) def UpperCAmelCase__ ( self : Dict ) -> str: """simple docstring""" return self.embeddings.word_embeddings def UpperCAmelCase__ ( self : int , __SCREAMING_SNAKE_CASE : Union[str, Any] ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = value def UpperCAmelCase__ ( self : Dict , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> Optional[int]: """simple docstring""" for layer, heads in heads_to_prune.items(): self.encoder.layer[layer].attention.prune_heads(__SCREAMING_SNAKE_CASE ) @add_start_docstrings_to_model_forward(__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[Any] , __SCREAMING_SNAKE_CASE : int=None , __SCREAMING_SNAKE_CASE : Any=None , __SCREAMING_SNAKE_CASE : str=None , __SCREAMING_SNAKE_CASE : int=None , __SCREAMING_SNAKE_CASE : List[str]=None , __SCREAMING_SNAKE_CASE : List[str]=None , __SCREAMING_SNAKE_CASE : Optional[int]=None , __SCREAMING_SNAKE_CASE : Union[str, Any]=None , ) -> Optional[Any]: """simple docstring""" if input_ids is not None and inputs_embeds is not None: raise ValueError("""You cannot specify both input_ids and inputs_embeds at the same time""" ) elif input_ids is not None: __SCREAMING_SNAKE_CASE = input_ids.size() elif inputs_embeds is not None: __SCREAMING_SNAKE_CASE = inputs_embeds.size()[:-1] else: raise ValueError("""You have to specify either input_ids or inputs_embeds""" ) __SCREAMING_SNAKE_CASE = input_ids.device if input_ids is not None else inputs_embeds.device if attention_mask is None: __SCREAMING_SNAKE_CASE = torch.ones(__SCREAMING_SNAKE_CASE , device=__SCREAMING_SNAKE_CASE ) if encoder_attention_mask is None: __SCREAMING_SNAKE_CASE = torch.ones(__SCREAMING_SNAKE_CASE , device=__SCREAMING_SNAKE_CASE ) if token_type_ids is None: __SCREAMING_SNAKE_CASE = torch.zeros(__SCREAMING_SNAKE_CASE , dtype=torch.long , device=__SCREAMING_SNAKE_CASE ) # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] # ourselves in which case we just need to make it broadcastable to all heads. __SCREAMING_SNAKE_CASE = self.get_extended_attention_mask(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # If a 2D ou 3D attention mask is provided for the cross-attention # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length] if encoder_attention_mask.dim() == 3: __SCREAMING_SNAKE_CASE = encoder_attention_mask[:, None, :, :] if encoder_attention_mask.dim() == 2: __SCREAMING_SNAKE_CASE = encoder_attention_mask[:, None, None, :] __SCREAMING_SNAKE_CASE = encoder_extended_attention_mask.to( dtype=next(self.parameters() ).dtype ) # fp16 compatibility __SCREAMING_SNAKE_CASE = (1.0 - encoder_extended_attention_mask) * -10000.0 # Prepare head mask if needed # 1.0 in head_mask indicate we keep the head # attention_probs has shape bsz x n_heads x N x N # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length] __SCREAMING_SNAKE_CASE = self.get_head_mask(__SCREAMING_SNAKE_CASE , self.config.num_hidden_layers ) __SCREAMING_SNAKE_CASE = self.embeddings( input_ids=__SCREAMING_SNAKE_CASE , position_ids=__SCREAMING_SNAKE_CASE , token_type_ids=__SCREAMING_SNAKE_CASE , inputs_embeds=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.encoder( __SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , head_mask=__SCREAMING_SNAKE_CASE , encoder_hidden_states=__SCREAMING_SNAKE_CASE , encoder_attention_mask=__SCREAMING_SNAKE_CASE , ) __SCREAMING_SNAKE_CASE = encoder_outputs[0] __SCREAMING_SNAKE_CASE = self.pooler(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = ( sequence_output, pooled_output, ) + encoder_outputs[ 1: ] # add hidden_states and attentions if they are here return outputs # sequence_output, pooled_output, (hidden_states), (attentions), highway exits class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : str ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = message __SCREAMING_SNAKE_CASE = exit_layer # start from 1! class lowerCAmelCase__ ( nn.Module ): """simple docstring""" def __init__( self : Dict , __SCREAMING_SNAKE_CASE : int ) -> str: """simple docstring""" super().__init__() __SCREAMING_SNAKE_CASE = BertPooler(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = nn.Dropout(config.hidden_dropout_prob ) __SCREAMING_SNAKE_CASE = nn.Linear(config.hidden_size , config.num_labels ) def UpperCAmelCase__ ( self : Any , __SCREAMING_SNAKE_CASE : Union[str, Any] ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = encoder_outputs[0] __SCREAMING_SNAKE_CASE = self.pooler(__SCREAMING_SNAKE_CASE ) # "return" pooler_output # BertModel __SCREAMING_SNAKE_CASE = (pooler_input, pooler_output) + encoder_outputs[1:] # "return" bmodel_output # Dropout and classification __SCREAMING_SNAKE_CASE = bmodel_output[1] __SCREAMING_SNAKE_CASE = self.dropout(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.classifier(__SCREAMING_SNAKE_CASE ) return logits, pooled_output @add_start_docstrings( "Bert Model (with early exiting - DeeBERT) with a classifier on top,\n also takes care of multi-layer training. " , a , ) class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : List[str] ) -> Optional[Any]: """simple docstring""" super().__init__(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = config.num_labels __SCREAMING_SNAKE_CASE = config.num_hidden_layers __SCREAMING_SNAKE_CASE = DeeBertModel(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = nn.Dropout(config.hidden_dropout_prob ) __SCREAMING_SNAKE_CASE = nn.Linear(config.hidden_size , self.config.num_labels ) self.init_weights() @add_start_docstrings_to_model_forward(__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Tuple , __SCREAMING_SNAKE_CASE : List[Any]=None , __SCREAMING_SNAKE_CASE : Any=None , __SCREAMING_SNAKE_CASE : Any=None , __SCREAMING_SNAKE_CASE : Any=None , __SCREAMING_SNAKE_CASE : int=None , __SCREAMING_SNAKE_CASE : Optional[int]=None , __SCREAMING_SNAKE_CASE : str=None , __SCREAMING_SNAKE_CASE : Optional[int]=-1 , __SCREAMING_SNAKE_CASE : int=False , ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = self.num_layers try: __SCREAMING_SNAKE_CASE = self.bert( __SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , token_type_ids=__SCREAMING_SNAKE_CASE , position_ids=__SCREAMING_SNAKE_CASE , head_mask=__SCREAMING_SNAKE_CASE , inputs_embeds=__SCREAMING_SNAKE_CASE , ) # sequence_output, pooled_output, (hidden_states), (attentions), highway exits __SCREAMING_SNAKE_CASE = outputs[1] __SCREAMING_SNAKE_CASE = self.dropout(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.classifier(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = (logits,) + outputs[2:] # add hidden states and attention if they are here except HighwayException as e: __SCREAMING_SNAKE_CASE = e.message __SCREAMING_SNAKE_CASE = e.exit_layer __SCREAMING_SNAKE_CASE = outputs[0] if not self.training: __SCREAMING_SNAKE_CASE = entropy(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] if labels is not None: if self.num_labels == 1: # We are doing regression __SCREAMING_SNAKE_CASE = MSELoss() __SCREAMING_SNAKE_CASE = loss_fct(logits.view(-1 ) , labels.view(-1 ) ) else: __SCREAMING_SNAKE_CASE = CrossEntropyLoss() __SCREAMING_SNAKE_CASE = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) # work with highway exits __SCREAMING_SNAKE_CASE = [] for highway_exit in outputs[-1]: __SCREAMING_SNAKE_CASE = highway_exit[0] if not self.training: highway_logits_all.append(__SCREAMING_SNAKE_CASE ) highway_entropy.append(highway_exit[2] ) if self.num_labels == 1: # We are doing regression __SCREAMING_SNAKE_CASE = MSELoss() __SCREAMING_SNAKE_CASE = loss_fct(highway_logits.view(-1 ) , labels.view(-1 ) ) else: __SCREAMING_SNAKE_CASE = CrossEntropyLoss() __SCREAMING_SNAKE_CASE = loss_fct(highway_logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) highway_losses.append(__SCREAMING_SNAKE_CASE ) if train_highway: __SCREAMING_SNAKE_CASE = (sum(highway_losses[:-1] ),) + outputs # exclude the final highway, of course else: __SCREAMING_SNAKE_CASE = (loss,) + outputs if not self.training: __SCREAMING_SNAKE_CASE = outputs + ((original_entropy, highway_entropy), exit_layer) if output_layer >= 0: __SCREAMING_SNAKE_CASE = ( (outputs[0],) + (highway_logits_all[output_layer],) + outputs[2:] ) # use the highway of the last layer return outputs # (loss), logits, (hidden_states), (attentions), (highway_exits)
267
'''simple docstring''' import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import CLIPImageProcessor, CLIPProcessor @require_vision class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : Union[str, Any] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() # fmt: off __SCREAMING_SNAKE_CASE = ["""l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """lo""", """l</w>""", """w</w>""", """r</w>""", """t</w>""", """low</w>""", """er</w>""", """lowest</w>""", """newer</w>""", """wider""", """<unk>""", """<|startoftext|>""", """<|endoftext|>"""] # fmt: on __SCREAMING_SNAKE_CASE = dict(zip(__SCREAMING_SNAKE_CASE , range(len(__SCREAMING_SNAKE_CASE ) ) ) ) __SCREAMING_SNAKE_CASE = ["""#version: 0.2""", """l o""", """lo w</w>""", """e r</w>""", """"""] __SCREAMING_SNAKE_CASE = {"""unk_token""": """<unk>"""} __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) __SCREAMING_SNAKE_CASE = 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(__SCREAMING_SNAKE_CASE ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = { """do_resize""": True, """size""": 20, """do_center_crop""": True, """crop_size""": 18, """do_normalize""": True, """image_mean""": [0.48145466, 0.4578275, 0.40821073], """image_std""": [0.26862954, 0.26130258, 0.27577711], } __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , __SCREAMING_SNAKE_CASE ) with open(self.image_processor_file , """w""" , encoding="""utf-8""" ) as fp: json.dump(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] , **__SCREAMING_SNAKE_CASE : Optional[int] ) -> str: """simple docstring""" return CLIPTokenizer.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Tuple , **__SCREAMING_SNAKE_CASE : Any ) -> int: """simple docstring""" return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[Any] , **__SCREAMING_SNAKE_CASE : Optional[int] ) -> List[str]: """simple docstring""" return CLIPImageProcessor.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Tuple ) -> str: """simple docstring""" shutil.rmtree(self.tmpdirname ) def UpperCAmelCase__ ( self : Optional[Any] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __SCREAMING_SNAKE_CASE = [Image.fromarray(np.moveaxis(__SCREAMING_SNAKE_CASE , 0 , -1 ) ) for x in image_inputs] return image_inputs def UpperCAmelCase__ ( self : Optional[int] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = self.get_rust_tokenizer() __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) processor_slow.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = CLIPProcessor.from_pretrained(self.tmpdirname , use_fast=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) processor_fast.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = CLIPProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , __SCREAMING_SNAKE_CASE ) self.assertIsInstance(processor_fast.tokenizer , __SCREAMING_SNAKE_CASE ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , __SCREAMING_SNAKE_CASE ) self.assertIsInstance(processor_fast.image_processor , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) __SCREAMING_SNAKE_CASE = self.get_image_processor(do_normalize=__SCREAMING_SNAKE_CASE , padding_value=1.0 ) __SCREAMING_SNAKE_CASE = CLIPProcessor.from_pretrained( self.tmpdirname , bos_token="""(BOS)""" , eos_token="""(EOS)""" , do_normalize=__SCREAMING_SNAKE_CASE , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , __SCREAMING_SNAKE_CASE ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[str] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = image_processor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ) __SCREAMING_SNAKE_CASE = processor(images=__SCREAMING_SNAKE_CASE , return_tensors="""np""" ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1E-2 ) def UpperCAmelCase__ ( self : List[Any] ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """lower newer""" __SCREAMING_SNAKE_CASE = processor(text=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer(__SCREAMING_SNAKE_CASE ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def UpperCAmelCase__ ( self : Dict ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """lower newer""" __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = processor(text=__SCREAMING_SNAKE_CASE , images=__SCREAMING_SNAKE_CASE ) self.assertListEqual(list(inputs.keys() ) , ["""input_ids""", """attention_mask""", """pixel_values"""] ) # test if it raises when no input is passed with pytest.raises(__SCREAMING_SNAKE_CASE ): processor() def UpperCAmelCase__ ( self : List[str] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __SCREAMING_SNAKE_CASE = processor.batch_decode(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer.batch_decode(__SCREAMING_SNAKE_CASE ) self.assertListEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : int ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """lower newer""" __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = processor(text=__SCREAMING_SNAKE_CASE , images=__SCREAMING_SNAKE_CASE ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
267
1
'''simple docstring''' import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase : Optional[Any] = logging.get_logger(__name__) UpperCAmelCase : Dict = { 'RUCAIBox/mvp': 'https://huggingface.co/RUCAIBox/mvp/resolve/main/config.json', } class lowerCAmelCase__ ( a ): """simple docstring""" lowerCAmelCase__ = "mvp" lowerCAmelCase__ = ["past_key_values"] lowerCAmelCase__ = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"} def __init__( self : List[str] , __SCREAMING_SNAKE_CASE : Any=50_267 , __SCREAMING_SNAKE_CASE : List[str]=1_024 , __SCREAMING_SNAKE_CASE : str=12 , __SCREAMING_SNAKE_CASE : Tuple=4_096 , __SCREAMING_SNAKE_CASE : int=16 , __SCREAMING_SNAKE_CASE : int=12 , __SCREAMING_SNAKE_CASE : Union[str, Any]=4_096 , __SCREAMING_SNAKE_CASE : Any=16 , __SCREAMING_SNAKE_CASE : str=0.0 , __SCREAMING_SNAKE_CASE : Tuple=0.0 , __SCREAMING_SNAKE_CASE : Optional[Any]="gelu" , __SCREAMING_SNAKE_CASE : int=1_024 , __SCREAMING_SNAKE_CASE : Any=0.1 , __SCREAMING_SNAKE_CASE : Optional[Any]=0.0 , __SCREAMING_SNAKE_CASE : int=0.0 , __SCREAMING_SNAKE_CASE : Dict=0.02 , __SCREAMING_SNAKE_CASE : Optional[int]=0.0 , __SCREAMING_SNAKE_CASE : int=False , __SCREAMING_SNAKE_CASE : List[Any]=True , __SCREAMING_SNAKE_CASE : int=1 , __SCREAMING_SNAKE_CASE : Optional[int]=0 , __SCREAMING_SNAKE_CASE : Any=2 , __SCREAMING_SNAKE_CASE : int=True , __SCREAMING_SNAKE_CASE : Tuple=2 , __SCREAMING_SNAKE_CASE : List[str]=2 , __SCREAMING_SNAKE_CASE : List[Any]=False , __SCREAMING_SNAKE_CASE : int=100 , __SCREAMING_SNAKE_CASE : Any=800 , **__SCREAMING_SNAKE_CASE : List[Any] , ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = d_model __SCREAMING_SNAKE_CASE = encoder_ffn_dim __SCREAMING_SNAKE_CASE = encoder_layers __SCREAMING_SNAKE_CASE = encoder_attention_heads __SCREAMING_SNAKE_CASE = decoder_ffn_dim __SCREAMING_SNAKE_CASE = decoder_layers __SCREAMING_SNAKE_CASE = decoder_attention_heads __SCREAMING_SNAKE_CASE = dropout __SCREAMING_SNAKE_CASE = attention_dropout __SCREAMING_SNAKE_CASE = activation_dropout __SCREAMING_SNAKE_CASE = activation_function __SCREAMING_SNAKE_CASE = init_std __SCREAMING_SNAKE_CASE = encoder_layerdrop __SCREAMING_SNAKE_CASE = decoder_layerdrop __SCREAMING_SNAKE_CASE = classifier_dropout __SCREAMING_SNAKE_CASE = use_cache __SCREAMING_SNAKE_CASE = encoder_layers __SCREAMING_SNAKE_CASE = scale_embedding # scale factor will be sqrt(d_model) if True __SCREAMING_SNAKE_CASE = use_prompt __SCREAMING_SNAKE_CASE = prompt_length __SCREAMING_SNAKE_CASE = prompt_mid_dim super().__init__( pad_token_id=__SCREAMING_SNAKE_CASE , bos_token_id=__SCREAMING_SNAKE_CASE , eos_token_id=__SCREAMING_SNAKE_CASE , is_encoder_decoder=__SCREAMING_SNAKE_CASE , decoder_start_token_id=__SCREAMING_SNAKE_CASE , forced_eos_token_id=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) if self.forced_bos_token_id is None and kwargs.get("""force_bos_token_to_be_generated""" , __SCREAMING_SNAKE_CASE ): __SCREAMING_SNAKE_CASE = self.bos_token_id warnings.warn( f'Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions. ' """The config can simply be saved and uploaded again to be fixed.""" )
267
'''simple docstring''' import numpy as np def a__ ( a__ , a__ , a__ = 1E-1_2 , a__ = 1_00 , ): """simple docstring""" assert np.shape(a__ )[0] == np.shape(a__ )[1] # Ensure proper dimensionality. assert np.shape(a__ )[0] == np.shape(a__ )[0] # Ensure inputs are either both complex or both real assert np.iscomplexobj(a__ ) == np.iscomplexobj(a__ ) __SCREAMING_SNAKE_CASE = np.iscomplexobj(a__ ) if is_complex: # Ensure complex input_matrix is Hermitian assert np.array_equal(a__ , input_matrix.conj().T ) # Set convergence to False. Will define convergence when we exceed max_iterations # or when we have small changes from one iteration to next. __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 1E1_2 while not convergence: # Multiple matrix by the vector. __SCREAMING_SNAKE_CASE = np.dot(a__ , a__ ) # Normalize the resulting output vector. __SCREAMING_SNAKE_CASE = w / np.linalg.norm(a__ ) # Find rayleigh quotient # (faster than usual b/c we know vector is normalized already) __SCREAMING_SNAKE_CASE = vector.conj().T if is_complex else vector.T __SCREAMING_SNAKE_CASE = np.dot(a__ , np.dot(a__ , a__ ) ) # Check convergence. __SCREAMING_SNAKE_CASE = np.abs(lambda_ - lambda_previous ) / lambda_ iterations += 1 if error <= error_tol or iterations >= max_iterations: __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = lambda_ if is_complex: __SCREAMING_SNAKE_CASE = np.real(lambda_ ) return lambda_, vector def a__ ( ): """simple docstring""" __SCREAMING_SNAKE_CASE = np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]] ) __SCREAMING_SNAKE_CASE = np.array([41, 4, 20] ) __SCREAMING_SNAKE_CASE = real_input_matrix.astype(np.complexaaa ) __SCREAMING_SNAKE_CASE = np.triu(1J * complex_input_matrix , 1 ) complex_input_matrix += imag_matrix complex_input_matrix += -1 * imag_matrix.T __SCREAMING_SNAKE_CASE = np.array([41, 4, 20] ).astype(np.complexaaa ) for problem_type in ["real", "complex"]: if problem_type == "real": __SCREAMING_SNAKE_CASE = real_input_matrix __SCREAMING_SNAKE_CASE = real_vector elif problem_type == "complex": __SCREAMING_SNAKE_CASE = complex_input_matrix __SCREAMING_SNAKE_CASE = complex_vector # Our implementation. __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = power_iteration(a__ , a__ ) # Numpy implementation. # Get eigenvalues and eigenvectors using built-in numpy # eigh (eigh used for symmetric or hermetian matrices). __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = np.linalg.eigh(a__ ) # Last eigenvalue is the maximum one. __SCREAMING_SNAKE_CASE = eigen_values[-1] # Last column in this matrix is eigenvector corresponding to largest eigenvalue. __SCREAMING_SNAKE_CASE = eigen_vectors[:, -1] # Check our implementation and numpy gives close answers. assert np.abs(eigen_value - eigen_value_max ) <= 1E-6 # Take absolute values element wise of each eigenvector. # as they are only unique to a minus sign. assert np.linalg.norm(np.abs(a__ ) - np.abs(a__ ) ) <= 1E-6 if __name__ == "__main__": import doctest doctest.testmod() test_power_iteration()
267
1
'''simple docstring''' import fire from utils import calculate_rouge, save_json def a__ ( a__ , a__ , a__=None , **a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = [x.strip() for x in open(a__ ).readlines()] __SCREAMING_SNAKE_CASE = [x.strip() for x in open(a__ ).readlines()][: len(a__ )] __SCREAMING_SNAKE_CASE = calculate_rouge(a__ , a__ , **a__ ) if save_path is not None: save_json(a__ , a__ , indent=a__ ) return metrics # these print nicely if __name__ == "__main__": fire.Fire(calculate_rouge_path)
267
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowerCAmelCase__ ( a , a , a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = StableDiffusionInpaintPipeline lowerCAmelCase__ = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS lowerCAmelCase__ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS lowerCAmelCase__ = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess lowerCAmelCase__ = frozenset([] ) def UpperCAmelCase__ ( self : str ) -> List[Any]: """simple docstring""" torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=9 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=__SCREAMING_SNAKE_CASE , ) __SCREAMING_SNAKE_CASE = PNDMScheduler(skip_prk_steps=__SCREAMING_SNAKE_CASE ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act="""gelu""" , projection_dim=512 , ) __SCREAMING_SNAKE_CASE = CLIPTextModel(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) __SCREAMING_SNAKE_CASE = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def UpperCAmelCase__ ( self : Any , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : List[Any]=0 ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = floats_tensor((1, 3, 32, 32) , rng=random.Random(__SCREAMING_SNAKE_CASE ) ).to(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1 )[0] __SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(__SCREAMING_SNAKE_CASE ) ).convert("""RGB""" ).resize((64, 64) ) __SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(image + 4 ) ).convert("""RGB""" ).resize((64, 64) ) if str(__SCREAMING_SNAKE_CASE ).startswith("""mps""" ): __SCREAMING_SNAKE_CASE = torch.manual_seed(__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = torch.Generator(device=__SCREAMING_SNAKE_CASE ).manual_seed(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = { """prompt""": """A painting of a squirrel eating a burger""", """image""": init_image, """mask_image""": mask_image, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def UpperCAmelCase__ ( self : Union[str, Any] ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = """cpu""" # ensure determinism for the device-dependent torch.Generator __SCREAMING_SNAKE_CASE = self.get_dummy_components() __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = sd_pipe.to(__SCREAMING_SNAKE_CASE ) sd_pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.get_dummy_inputs(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = sd_pipe(**__SCREAMING_SNAKE_CASE ).images __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __SCREAMING_SNAKE_CASE = np.array([0.4727, 0.5735, 0.3941, 0.5446, 0.5926, 0.4394, 0.5062, 0.4654, 0.4476] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def UpperCAmelCase__ ( self : Tuple ) -> str: """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : List[Any] ) -> str: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase__ ( self : List[str] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) __SCREAMING_SNAKE_CASE = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench.npy""" ) __SCREAMING_SNAKE_CASE = """stabilityai/stable-diffusion-2-inpainting""" __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline.from_pretrained(__SCREAMING_SNAKE_CASE , safety_checker=__SCREAMING_SNAKE_CASE ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) pipe.enable_attention_slicing() __SCREAMING_SNAKE_CASE = """Face of a yellow cat, high resolution, sitting on a park bench""" __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , mask_image=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , output_type="""np""" , ) __SCREAMING_SNAKE_CASE = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 9E-3 def UpperCAmelCase__ ( self : List[Any] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) __SCREAMING_SNAKE_CASE = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench_fp16.npy""" ) __SCREAMING_SNAKE_CASE = """stabilityai/stable-diffusion-2-inpainting""" __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline.from_pretrained( __SCREAMING_SNAKE_CASE , torch_dtype=torch.floataa , safety_checker=__SCREAMING_SNAKE_CASE , ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) pipe.enable_attention_slicing() __SCREAMING_SNAKE_CASE = """Face of a yellow cat, high resolution, sitting on a park bench""" __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , mask_image=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , output_type="""np""" , ) __SCREAMING_SNAKE_CASE = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 5E-1 def UpperCAmelCase__ ( self : Tuple ) -> Any: """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) __SCREAMING_SNAKE_CASE = """stabilityai/stable-diffusion-2-inpainting""" __SCREAMING_SNAKE_CASE = PNDMScheduler.from_pretrained(__SCREAMING_SNAKE_CASE , subfolder="""scheduler""" ) __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline.from_pretrained( __SCREAMING_SNAKE_CASE , safety_checker=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE , torch_dtype=torch.floataa , ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() __SCREAMING_SNAKE_CASE = """Face of a yellow cat, high resolution, sitting on a park bench""" __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , mask_image=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , num_inference_steps=2 , output_type="""np""" , ) __SCREAMING_SNAKE_CASE = torch.cuda.max_memory_allocated() # make sure that less than 2.65 GB is allocated assert mem_bytes < 2.65 * 10**9
267
1
'''simple docstring''' import unittest from .lib import ( Matrix, Vector, axpy, square_zero_matrix, unit_basis_vector, zero_vector, ) class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : Dict ) -> None: """simple docstring""" __SCREAMING_SNAKE_CASE = Vector([1, 2, 3] ) self.assertEqual(x.component(0 ) , 1 ) self.assertEqual(x.component(2 ) , 3 ) __SCREAMING_SNAKE_CASE = Vector() def UpperCAmelCase__ ( self : Optional[Any] ) -> None: """simple docstring""" __SCREAMING_SNAKE_CASE = Vector([0, 0, 0, 0, 0, 1] ) self.assertEqual(str(__SCREAMING_SNAKE_CASE ) , """(0,0,0,0,0,1)""" ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> None: """simple docstring""" __SCREAMING_SNAKE_CASE = Vector([1, 2, 3, 4] ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , 4 ) def UpperCAmelCase__ ( self : int ) -> None: """simple docstring""" __SCREAMING_SNAKE_CASE = Vector([1, 2] ) __SCREAMING_SNAKE_CASE = Vector([1, 2, 3, 4, 5] ) __SCREAMING_SNAKE_CASE = Vector([0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ) __SCREAMING_SNAKE_CASE = Vector([1, -1, 1, -1, 2, -3, 4, -5] ) self.assertAlmostEqual(x.euclidean_length() , 2.236 , 3 ) self.assertAlmostEqual(y.euclidean_length() , 7.416 , 3 ) self.assertEqual(z.euclidean_length() , 0 ) self.assertAlmostEqual(w.euclidean_length() , 7.616 , 3 ) def UpperCAmelCase__ ( self : Tuple ) -> None: """simple docstring""" __SCREAMING_SNAKE_CASE = Vector([1, 2, 3] ) __SCREAMING_SNAKE_CASE = Vector([1, 1, 1] ) self.assertEqual((x + y).component(0 ) , 2 ) self.assertEqual((x + y).component(1 ) , 3 ) self.assertEqual((x + y).component(2 ) , 4 ) def UpperCAmelCase__ ( self : Optional[Any] ) -> None: """simple docstring""" __SCREAMING_SNAKE_CASE = Vector([1, 2, 3] ) __SCREAMING_SNAKE_CASE = Vector([1, 1, 1] ) self.assertEqual((x - y).component(0 ) , 0 ) self.assertEqual((x - y).component(1 ) , 1 ) self.assertEqual((x - y).component(2 ) , 2 ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> None: """simple docstring""" __SCREAMING_SNAKE_CASE = Vector([1, 2, 3] ) __SCREAMING_SNAKE_CASE = Vector([2, -1, 4] ) # for test of dot product __SCREAMING_SNAKE_CASE = Vector([1, -2, -1] ) self.assertEqual(str(x * 3.0 ) , """(3.0,6.0,9.0)""" ) self.assertEqual((a * b) , 0 ) def UpperCAmelCase__ ( self : Optional[int] ) -> None: """simple docstring""" self.assertEqual(str(zero_vector(10 ) ).count("""0""" ) , 10 ) def UpperCAmelCase__ ( self : Dict ) -> None: """simple docstring""" self.assertEqual(str(unit_basis_vector(3 , 1 ) ) , """(0,1,0)""" ) def UpperCAmelCase__ ( self : int ) -> None: """simple docstring""" __SCREAMING_SNAKE_CASE = Vector([1, 2, 3] ) __SCREAMING_SNAKE_CASE = Vector([1, 0, 1] ) self.assertEqual(str(axpy(2 , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) , """(3,4,7)""" ) def UpperCAmelCase__ ( self : List[str] ) -> None: """simple docstring""" __SCREAMING_SNAKE_CASE = Vector([1, 0, 0, 0, 0, 0] ) __SCREAMING_SNAKE_CASE = x.copy() self.assertEqual(str(__SCREAMING_SNAKE_CASE ) , str(__SCREAMING_SNAKE_CASE ) ) def UpperCAmelCase__ ( self : Optional[int] ) -> None: """simple docstring""" __SCREAMING_SNAKE_CASE = Vector([1, 0, 0] ) x.change_component(0 , 0 ) x.change_component(1 , 1 ) self.assertEqual(str(__SCREAMING_SNAKE_CASE ) , """(0,1,0)""" ) def UpperCAmelCase__ ( self : int ) -> None: """simple docstring""" __SCREAMING_SNAKE_CASE = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) self.assertEqual("""|1,2,3|\n|2,4,5|\n|6,7,8|\n""" , str(__SCREAMING_SNAKE_CASE ) ) def UpperCAmelCase__ ( self : int ) -> None: """simple docstring""" __SCREAMING_SNAKE_CASE = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) __SCREAMING_SNAKE_CASE = [[-3, -14, -10], [-5, -10, -5], [-2, -1, 0]] for x in range(a.height() ): for y in range(a.width() ): self.assertEqual(minors[x][y] , a.minor(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) def UpperCAmelCase__ ( self : Dict ) -> None: """simple docstring""" __SCREAMING_SNAKE_CASE = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) __SCREAMING_SNAKE_CASE = [[-3, 14, -10], [5, -10, 5], [-2, 1, 0]] for x in range(a.height() ): for y in range(a.width() ): self.assertEqual(cofactors[x][y] , a.cofactor(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) def UpperCAmelCase__ ( self : Dict ) -> None: """simple docstring""" __SCREAMING_SNAKE_CASE = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) self.assertEqual(-5 , a.determinant() ) def UpperCAmelCase__ ( self : List[str] ) -> None: """simple docstring""" __SCREAMING_SNAKE_CASE = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]] , 3 , 3 ) __SCREAMING_SNAKE_CASE = Vector([1, 2, 3] ) self.assertEqual("""(14,32,50)""" , str(a * x ) ) self.assertEqual("""|2,4,6|\n|8,10,12|\n|14,16,18|\n""" , str(a * 2 ) ) def UpperCAmelCase__ ( self : Dict ) -> None: """simple docstring""" __SCREAMING_SNAKE_CASE = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) a.change_component(0 , 2 , 5 ) self.assertEqual("""|1,2,5|\n|2,4,5|\n|6,7,8|\n""" , str(__SCREAMING_SNAKE_CASE ) ) def UpperCAmelCase__ ( self : Optional[int] ) -> None: """simple docstring""" __SCREAMING_SNAKE_CASE = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) self.assertEqual(7 , a.component(2 , 1 ) , 0.01 ) def UpperCAmelCase__ ( self : Dict ) -> None: """simple docstring""" __SCREAMING_SNAKE_CASE = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) __SCREAMING_SNAKE_CASE = Matrix([[1, 2, 7], [2, 4, 5], [6, 7, 10]] , 3 , 3 ) self.assertEqual("""|2,4,10|\n|4,8,10|\n|12,14,18|\n""" , str(a + b ) ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> None: """simple docstring""" __SCREAMING_SNAKE_CASE = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) __SCREAMING_SNAKE_CASE = Matrix([[1, 2, 7], [2, 4, 5], [6, 7, 10]] , 3 , 3 ) self.assertEqual("""|0,0,-4|\n|0,0,0|\n|0,0,-2|\n""" , str(a - b ) ) def UpperCAmelCase__ ( self : Optional[Any] ) -> None: """simple docstring""" self.assertEqual( """|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n""" , str(square_zero_matrix(5 ) ) , ) if __name__ == "__main__": unittest.main()
267
'''simple docstring''' from itertools import count def a__ ( a__ = 50 ): """simple docstring""" __SCREAMING_SNAKE_CASE = [1] * min_block_length for n in count(a__ ): fill_count_functions.append(1 ) for block_length in range(a__ , n + 1 ): for block_start in range(n - block_length ): fill_count_functions[n] += fill_count_functions[ n - block_start - block_length - 1 ] fill_count_functions[n] += 1 if fill_count_functions[n] > 1_00_00_00: break return n if __name__ == "__main__": print(f"""{solution() = }""")
267
1
'''simple docstring''' import logging import os import threading import time try: import warnings except ImportError: UpperCAmelCase : Optional[Any] = None try: import msvcrt except ImportError: UpperCAmelCase : List[Any] = None try: import fcntl except ImportError: UpperCAmelCase : int = None # Backward compatibility # ------------------------------------------------ try: TimeoutError except NameError: UpperCAmelCase : Union[str, Any] = OSError # Data # ------------------------------------------------ UpperCAmelCase : List[Any] = [ 'Timeout', 'BaseFileLock', 'WindowsFileLock', 'UnixFileLock', 'SoftFileLock', 'FileLock', ] UpperCAmelCase : Tuple = '3.0.12' UpperCAmelCase : str = None def a__ ( ): """simple docstring""" global _logger __SCREAMING_SNAKE_CASE = _logger or logging.getLogger(__name__ ) return _logger class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Any , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = lock_file return None def __str__( self : str ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = f'The file lock \'{self.lock_file}\' could not be acquired.' return temp class lowerCAmelCase__ : """simple docstring""" def __init__( self : Tuple , __SCREAMING_SNAKE_CASE : List[Any] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = lock return None def __enter__( self : List[str] ) -> List[Any]: """simple docstring""" return self.lock def __exit__( self : Tuple , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> List[str]: """simple docstring""" self.lock.release() return None class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : str=-1 , __SCREAMING_SNAKE_CASE : Optional[Any]=None ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = max_filename_length if max_filename_length is not None else 255 # Hash the filename if it's too long __SCREAMING_SNAKE_CASE = self.hash_filename_if_too_long(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # The path to the lock file. __SCREAMING_SNAKE_CASE = lock_file # The file descriptor for the *_lock_file* as it is returned by the # os.open() function. # This file lock is only NOT None, if the object currently holds the # lock. __SCREAMING_SNAKE_CASE = None # The default timeout value. __SCREAMING_SNAKE_CASE = timeout # We use this lock primarily for the lock counter. __SCREAMING_SNAKE_CASE = threading.Lock() # The lock counter is used for implementing the nested locking # mechanism. Whenever the lock is acquired, the counter is increased and # the lock is only released, when this value is 0 again. __SCREAMING_SNAKE_CASE = 0 return None @property def UpperCAmelCase__ ( self : List[Any] ) -> List[str]: """simple docstring""" return self._lock_file @property def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" return self._timeout @timeout.setter def UpperCAmelCase__ ( self : List[str] , __SCREAMING_SNAKE_CASE : Dict ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = float(__SCREAMING_SNAKE_CASE ) return None def UpperCAmelCase__ ( self : Optional[Any] ) -> List[Any]: """simple docstring""" raise NotImplementedError() def UpperCAmelCase__ ( self : Union[str, Any] ) -> Any: """simple docstring""" raise NotImplementedError() @property def UpperCAmelCase__ ( self : Union[str, Any] ) -> int: """simple docstring""" return self._lock_file_fd is not None def UpperCAmelCase__ ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[Any]=None , __SCREAMING_SNAKE_CASE : Optional[int]=0.05 ) -> Optional[Any]: """simple docstring""" if timeout is None: __SCREAMING_SNAKE_CASE = self.timeout # Increment the number right at the beginning. # We can still undo it, if something fails. with self._thread_lock: self._lock_counter += 1 __SCREAMING_SNAKE_CASE = id(self ) __SCREAMING_SNAKE_CASE = self._lock_file __SCREAMING_SNAKE_CASE = time.time() try: while True: with self._thread_lock: if not self.is_locked: logger().debug(f'Attempting to acquire lock {lock_id} on {lock_filename}' ) self._acquire() if self.is_locked: logger().debug(f'Lock {lock_id} acquired on {lock_filename}' ) break elif timeout >= 0 and time.time() - start_time > timeout: logger().debug(f'Timeout on acquiring lock {lock_id} on {lock_filename}' ) raise Timeout(self._lock_file ) else: logger().debug( f'Lock {lock_id} not acquired on {lock_filename}, waiting {poll_intervall} seconds ...' ) time.sleep(__SCREAMING_SNAKE_CASE ) except: # noqa # Something did go wrong, so decrement the counter. with self._thread_lock: __SCREAMING_SNAKE_CASE = max(0 , self._lock_counter - 1 ) raise return _Acquire_ReturnProxy(lock=self ) def UpperCAmelCase__ ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[Any]=False ) -> Dict: """simple docstring""" with self._thread_lock: if self.is_locked: self._lock_counter -= 1 if self._lock_counter == 0 or force: __SCREAMING_SNAKE_CASE = id(self ) __SCREAMING_SNAKE_CASE = self._lock_file logger().debug(f'Attempting to release lock {lock_id} on {lock_filename}' ) self._release() __SCREAMING_SNAKE_CASE = 0 logger().debug(f'Lock {lock_id} released on {lock_filename}' ) return None def __enter__( self : Union[str, Any] ) -> Optional[int]: """simple docstring""" self.acquire() return self def __exit__( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Any ) -> Tuple: """simple docstring""" self.release() return None def __del__( self : str ) -> Union[str, Any]: """simple docstring""" self.release(force=__SCREAMING_SNAKE_CASE ) return None def UpperCAmelCase__ ( self : Optional[int] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : int ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = os.path.basename(__SCREAMING_SNAKE_CASE ) if len(__SCREAMING_SNAKE_CASE ) > max_length and max_length > 0: __SCREAMING_SNAKE_CASE = os.path.dirname(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = str(hash(__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = filename[: max_length - len(__SCREAMING_SNAKE_CASE ) - 8] + """...""" + hashed_filename + """.lock""" return os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else: return path class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Tuple , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Dict=-1 , __SCREAMING_SNAKE_CASE : Dict=None ) -> List[Any]: """simple docstring""" from .file_utils import relative_to_absolute_path super().__init__(__SCREAMING_SNAKE_CASE , timeout=__SCREAMING_SNAKE_CASE , max_filename_length=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """\\\\?\\""" + relative_to_absolute_path(self.lock_file ) def UpperCAmelCase__ ( self : Dict ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = os.O_RDWR | os.O_CREAT | os.O_TRUNC try: __SCREAMING_SNAKE_CASE = os.open(self._lock_file , __SCREAMING_SNAKE_CASE ) except OSError: pass else: try: msvcrt.locking(__SCREAMING_SNAKE_CASE , msvcrt.LK_NBLCK , 1 ) except OSError: os.close(__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = fd return None def UpperCAmelCase__ ( self : Tuple ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self._lock_file_fd __SCREAMING_SNAKE_CASE = None msvcrt.locking(__SCREAMING_SNAKE_CASE , msvcrt.LK_UNLCK , 1 ) os.close(__SCREAMING_SNAKE_CASE ) try: os.remove(self._lock_file ) # Probably another instance of the application # that acquired the file lock. except OSError: pass return None class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Union[str, Any]=-1 , __SCREAMING_SNAKE_CASE : Optional[Any]=None ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = os.statvfs(os.path.dirname(__SCREAMING_SNAKE_CASE ) ).f_namemax super().__init__(__SCREAMING_SNAKE_CASE , timeout=__SCREAMING_SNAKE_CASE , max_filename_length=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = os.O_RDWR | os.O_CREAT | os.O_TRUNC __SCREAMING_SNAKE_CASE = os.open(self._lock_file , __SCREAMING_SNAKE_CASE ) try: fcntl.flock(__SCREAMING_SNAKE_CASE , fcntl.LOCK_EX | fcntl.LOCK_NB ) except OSError: os.close(__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = fd return None def UpperCAmelCase__ ( self : List[Any] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = self._lock_file_fd __SCREAMING_SNAKE_CASE = None fcntl.flock(__SCREAMING_SNAKE_CASE , fcntl.LOCK_UN ) os.close(__SCREAMING_SNAKE_CASE ) return None class lowerCAmelCase__ ( a ): """simple docstring""" def UpperCAmelCase__ ( self : List[str] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC try: __SCREAMING_SNAKE_CASE = os.open(self._lock_file , __SCREAMING_SNAKE_CASE ) except OSError: pass else: __SCREAMING_SNAKE_CASE = fd return None def UpperCAmelCase__ ( self : int ) -> Optional[int]: """simple docstring""" os.close(self._lock_file_fd ) __SCREAMING_SNAKE_CASE = None try: os.remove(self._lock_file ) # The file is already deleted and that's what we want. except OSError: pass return None UpperCAmelCase : Dict = None if msvcrt: UpperCAmelCase : Optional[int] = WindowsFileLock elif fcntl: UpperCAmelCase : Optional[Any] = UnixFileLock else: UpperCAmelCase : int = SoftFileLock if warnings is not None: warnings.warn('only soft file lock is available')
267
'''simple docstring''' import logging import os import threading import time try: import warnings except ImportError: UpperCAmelCase : Optional[Any] = None try: import msvcrt except ImportError: UpperCAmelCase : List[Any] = None try: import fcntl except ImportError: UpperCAmelCase : int = None # Backward compatibility # ------------------------------------------------ try: TimeoutError except NameError: UpperCAmelCase : Union[str, Any] = OSError # Data # ------------------------------------------------ UpperCAmelCase : List[Any] = [ 'Timeout', 'BaseFileLock', 'WindowsFileLock', 'UnixFileLock', 'SoftFileLock', 'FileLock', ] UpperCAmelCase : Tuple = '3.0.12' UpperCAmelCase : str = None def a__ ( ): """simple docstring""" global _logger __SCREAMING_SNAKE_CASE = _logger or logging.getLogger(__name__ ) return _logger class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Any , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = lock_file return None def __str__( self : str ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = f'The file lock \'{self.lock_file}\' could not be acquired.' return temp class lowerCAmelCase__ : """simple docstring""" def __init__( self : Tuple , __SCREAMING_SNAKE_CASE : List[Any] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = lock return None def __enter__( self : List[str] ) -> List[Any]: """simple docstring""" return self.lock def __exit__( self : Tuple , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> List[str]: """simple docstring""" self.lock.release() return None class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : str=-1 , __SCREAMING_SNAKE_CASE : Optional[Any]=None ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = max_filename_length if max_filename_length is not None else 255 # Hash the filename if it's too long __SCREAMING_SNAKE_CASE = self.hash_filename_if_too_long(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # The path to the lock file. __SCREAMING_SNAKE_CASE = lock_file # The file descriptor for the *_lock_file* as it is returned by the # os.open() function. # This file lock is only NOT None, if the object currently holds the # lock. __SCREAMING_SNAKE_CASE = None # The default timeout value. __SCREAMING_SNAKE_CASE = timeout # We use this lock primarily for the lock counter. __SCREAMING_SNAKE_CASE = threading.Lock() # The lock counter is used for implementing the nested locking # mechanism. Whenever the lock is acquired, the counter is increased and # the lock is only released, when this value is 0 again. __SCREAMING_SNAKE_CASE = 0 return None @property def UpperCAmelCase__ ( self : List[Any] ) -> List[str]: """simple docstring""" return self._lock_file @property def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" return self._timeout @timeout.setter def UpperCAmelCase__ ( self : List[str] , __SCREAMING_SNAKE_CASE : Dict ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = float(__SCREAMING_SNAKE_CASE ) return None def UpperCAmelCase__ ( self : Optional[Any] ) -> List[Any]: """simple docstring""" raise NotImplementedError() def UpperCAmelCase__ ( self : Union[str, Any] ) -> Any: """simple docstring""" raise NotImplementedError() @property def UpperCAmelCase__ ( self : Union[str, Any] ) -> int: """simple docstring""" return self._lock_file_fd is not None def UpperCAmelCase__ ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[Any]=None , __SCREAMING_SNAKE_CASE : Optional[int]=0.05 ) -> Optional[Any]: """simple docstring""" if timeout is None: __SCREAMING_SNAKE_CASE = self.timeout # Increment the number right at the beginning. # We can still undo it, if something fails. with self._thread_lock: self._lock_counter += 1 __SCREAMING_SNAKE_CASE = id(self ) __SCREAMING_SNAKE_CASE = self._lock_file __SCREAMING_SNAKE_CASE = time.time() try: while True: with self._thread_lock: if not self.is_locked: logger().debug(f'Attempting to acquire lock {lock_id} on {lock_filename}' ) self._acquire() if self.is_locked: logger().debug(f'Lock {lock_id} acquired on {lock_filename}' ) break elif timeout >= 0 and time.time() - start_time > timeout: logger().debug(f'Timeout on acquiring lock {lock_id} on {lock_filename}' ) raise Timeout(self._lock_file ) else: logger().debug( f'Lock {lock_id} not acquired on {lock_filename}, waiting {poll_intervall} seconds ...' ) time.sleep(__SCREAMING_SNAKE_CASE ) except: # noqa # Something did go wrong, so decrement the counter. with self._thread_lock: __SCREAMING_SNAKE_CASE = max(0 , self._lock_counter - 1 ) raise return _Acquire_ReturnProxy(lock=self ) def UpperCAmelCase__ ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[Any]=False ) -> Dict: """simple docstring""" with self._thread_lock: if self.is_locked: self._lock_counter -= 1 if self._lock_counter == 0 or force: __SCREAMING_SNAKE_CASE = id(self ) __SCREAMING_SNAKE_CASE = self._lock_file logger().debug(f'Attempting to release lock {lock_id} on {lock_filename}' ) self._release() __SCREAMING_SNAKE_CASE = 0 logger().debug(f'Lock {lock_id} released on {lock_filename}' ) return None def __enter__( self : Union[str, Any] ) -> Optional[int]: """simple docstring""" self.acquire() return self def __exit__( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Any ) -> Tuple: """simple docstring""" self.release() return None def __del__( self : str ) -> Union[str, Any]: """simple docstring""" self.release(force=__SCREAMING_SNAKE_CASE ) return None def UpperCAmelCase__ ( self : Optional[int] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : int ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = os.path.basename(__SCREAMING_SNAKE_CASE ) if len(__SCREAMING_SNAKE_CASE ) > max_length and max_length > 0: __SCREAMING_SNAKE_CASE = os.path.dirname(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = str(hash(__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = filename[: max_length - len(__SCREAMING_SNAKE_CASE ) - 8] + """...""" + hashed_filename + """.lock""" return os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else: return path class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Tuple , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Dict=-1 , __SCREAMING_SNAKE_CASE : Dict=None ) -> List[Any]: """simple docstring""" from .file_utils import relative_to_absolute_path super().__init__(__SCREAMING_SNAKE_CASE , timeout=__SCREAMING_SNAKE_CASE , max_filename_length=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """\\\\?\\""" + relative_to_absolute_path(self.lock_file ) def UpperCAmelCase__ ( self : Dict ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = os.O_RDWR | os.O_CREAT | os.O_TRUNC try: __SCREAMING_SNAKE_CASE = os.open(self._lock_file , __SCREAMING_SNAKE_CASE ) except OSError: pass else: try: msvcrt.locking(__SCREAMING_SNAKE_CASE , msvcrt.LK_NBLCK , 1 ) except OSError: os.close(__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = fd return None def UpperCAmelCase__ ( self : Tuple ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self._lock_file_fd __SCREAMING_SNAKE_CASE = None msvcrt.locking(__SCREAMING_SNAKE_CASE , msvcrt.LK_UNLCK , 1 ) os.close(__SCREAMING_SNAKE_CASE ) try: os.remove(self._lock_file ) # Probably another instance of the application # that acquired the file lock. except OSError: pass return None class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Union[str, Any]=-1 , __SCREAMING_SNAKE_CASE : Optional[Any]=None ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = os.statvfs(os.path.dirname(__SCREAMING_SNAKE_CASE ) ).f_namemax super().__init__(__SCREAMING_SNAKE_CASE , timeout=__SCREAMING_SNAKE_CASE , max_filename_length=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = os.O_RDWR | os.O_CREAT | os.O_TRUNC __SCREAMING_SNAKE_CASE = os.open(self._lock_file , __SCREAMING_SNAKE_CASE ) try: fcntl.flock(__SCREAMING_SNAKE_CASE , fcntl.LOCK_EX | fcntl.LOCK_NB ) except OSError: os.close(__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = fd return None def UpperCAmelCase__ ( self : List[Any] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = self._lock_file_fd __SCREAMING_SNAKE_CASE = None fcntl.flock(__SCREAMING_SNAKE_CASE , fcntl.LOCK_UN ) os.close(__SCREAMING_SNAKE_CASE ) return None class lowerCAmelCase__ ( a ): """simple docstring""" def UpperCAmelCase__ ( self : List[str] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC try: __SCREAMING_SNAKE_CASE = os.open(self._lock_file , __SCREAMING_SNAKE_CASE ) except OSError: pass else: __SCREAMING_SNAKE_CASE = fd return None def UpperCAmelCase__ ( self : int ) -> Optional[int]: """simple docstring""" os.close(self._lock_file_fd ) __SCREAMING_SNAKE_CASE = None try: os.remove(self._lock_file ) # The file is already deleted and that's what we want. except OSError: pass return None UpperCAmelCase : Dict = None if msvcrt: UpperCAmelCase : Optional[int] = WindowsFileLock elif fcntl: UpperCAmelCase : Optional[Any] = UnixFileLock else: UpperCAmelCase : int = SoftFileLock if warnings is not None: warnings.warn('only soft file lock is available')
267
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available UpperCAmelCase : Optional[int] = { 'configuration_rag': ['RagConfig'], 'retrieval_rag': ['RagRetriever'], 'tokenization_rag': ['RagTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : str = [ 'RagModel', 'RagPreTrainedModel', 'RagSequenceForGeneration', 'RagTokenForGeneration', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : List[str] = [ 'TFRagModel', 'TFRagPreTrainedModel', 'TFRagSequenceForGeneration', 'TFRagTokenForGeneration', ] if TYPE_CHECKING: from .configuration_rag import RagConfig from .retrieval_rag import RagRetriever from .tokenization_rag import RagTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_rag import RagModel, RagPreTrainedModel, RagSequenceForGeneration, RagTokenForGeneration try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_rag import ( TFRagModel, TFRagPreTrainedModel, TFRagSequenceForGeneration, TFRagTokenForGeneration, ) else: import sys UpperCAmelCase : Optional[int] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
267
'''simple docstring''' import shutil import tempfile import unittest from transformers import ( SPIECE_UNDERLINE, AddedToken, BatchEncoding, NllbTokenizer, NllbTokenizerFast, is_torch_available, ) from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...test_tokenization_common import TokenizerTesterMixin UpperCAmelCase : Optional[int] = get_tests_dir('fixtures/test_sentencepiece.model') if is_torch_available(): from transformers.models.mam_aaa.modeling_mam_aaa import shift_tokens_right UpperCAmelCase : Optional[int] = 2_5_6_0_4_7 UpperCAmelCase : Union[str, Any] = 2_5_6_1_4_5 @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = NllbTokenizer lowerCAmelCase__ = NllbTokenizerFast lowerCAmelCase__ = True lowerCAmelCase__ = True lowerCAmelCase__ = {} def UpperCAmelCase__ ( self : List[Any] ) -> int: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing __SCREAMING_SNAKE_CASE = NllbTokenizer(__SCREAMING_SNAKE_CASE , keep_accents=__SCREAMING_SNAKE_CASE ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCAmelCase__ ( self : Dict ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = NllbTokenizer(__SCREAMING_SNAKE_CASE , keep_accents=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(__SCREAMING_SNAKE_CASE , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) __SCREAMING_SNAKE_CASE = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ 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""", """é""", """.""", ] , ) __SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ 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] ] , ) __SCREAMING_SNAKE_CASE = tokenizer.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ 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>""", """.""", ] , ) def UpperCAmelCase__ ( self : Dict ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = (self.rust_tokenizer_class, """hf-internal-testing/tiny-random-nllb""", {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) __SCREAMING_SNAKE_CASE = tuple(f for f in tokenizer_r_files if """tokenizer.json""" not in f ) self.assertSequenceEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Checks everything loads correctly in the same way __SCREAMING_SNAKE_CASE = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) # Save tokenizer rust, legacy_format=True __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE , legacy_format=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it save with the same files self.assertSequenceEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Checks everything loads correctly in the same way __SCREAMING_SNAKE_CASE = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) # Save tokenizer rust, legacy_format=False __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE , legacy_format=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it saved the tokenizer.json file self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way __SCREAMING_SNAKE_CASE = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) @require_torch def UpperCAmelCase__ ( self : List[Any] ) -> Any: """simple docstring""" if not self.test_seqaseq: return __SCREAMING_SNAKE_CASE = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): # Longer text that will definitely require truncation. __SCREAMING_SNAKE_CASE = [ """ UN Chief Says There Is No Military Solution in Syria""", """ Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for""" """ Syria is that 'there is no military solution' to the nearly five-year conflict and more weapons""" """ will only worsen the violence and misery for millions of people.""", ] __SCREAMING_SNAKE_CASE = [ """Şeful ONU declară că nu există o soluţie militară în Siria""", """Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al""" """ Rusiei pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi""" """ că noi arme nu vor face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.""", ] try: __SCREAMING_SNAKE_CASE = tokenizer.prepare_seqaseq_batch( src_texts=__SCREAMING_SNAKE_CASE , tgt_texts=__SCREAMING_SNAKE_CASE , max_length=3 , max_target_length=10 , return_tensors="""pt""" , src_lang="""eng_Latn""" , tgt_lang="""ron_Latn""" , ) except NotImplementedError: return self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.labels.shape[1] , 10 ) # max_target_length will default to max_length if not specified __SCREAMING_SNAKE_CASE = tokenizer.prepare_seqaseq_batch( __SCREAMING_SNAKE_CASE , tgt_texts=__SCREAMING_SNAKE_CASE , max_length=3 , return_tensors="""pt""" ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.labels.shape[1] , 3 ) __SCREAMING_SNAKE_CASE = tokenizer.prepare_seqaseq_batch( src_texts=__SCREAMING_SNAKE_CASE , max_length=3 , max_target_length=10 , return_tensors="""pt""" ) self.assertEqual(batch_encoder_only.input_ids.shape[1] , 3 ) self.assertEqual(batch_encoder_only.attention_mask.shape[1] , 3 ) self.assertNotIn("""decoder_input_ids""" , __SCREAMING_SNAKE_CASE ) @unittest.skip("""Unfortunately way too slow to build a BPE with SentencePiece.""" ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" pass def UpperCAmelCase__ ( self : List[str] ) -> Dict: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): __SCREAMING_SNAKE_CASE = [AddedToken("""<special>""" , lstrip=__SCREAMING_SNAKE_CASE )] __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_r.encode("""Hey this is a <special> token""" ) __SCREAMING_SNAKE_CASE = tokenizer_r.encode("""<special>""" , add_special_tokens=__SCREAMING_SNAKE_CASE )[0] self.assertTrue(special_token_id in r_output ) if self.test_slow_tokenizer: __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.encode("""Hey this is a <special> token""" ) __SCREAMING_SNAKE_CASE = tokenizer_cr.encode("""Hey this is a <special> token""" ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertTrue(special_token_id in p_output ) self.assertTrue(special_token_id in cr_output ) @require_torch @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = "facebook/nllb-200-distilled-600M" lowerCAmelCase__ = [ " UN Chief Says There Is No Military Solution in Syria", " Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for Syria is that \"there is no military solution\" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.", ] lowerCAmelCase__ = [ "Şeful ONU declară că nu există o soluţie militară în Siria", "Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei" " pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi că noi arme nu vor" " face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.", ] lowerCAmelCase__ = [ 256047, 16297, 134408, 8165, 248066, 14734, 950, 1135, 105721, 3573, 83, 27352, 108, 49486, 2, ] @classmethod def UpperCAmelCase__ ( cls : List[Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = NllbTokenizer.from_pretrained( cls.checkpoint_name , src_lang="""eng_Latn""" , tgt_lang="""ron_Latn""" ) __SCREAMING_SNAKE_CASE = 1 return cls def UpperCAmelCase__ ( self : Union[str, Any] ) -> List[str]: """simple docstring""" self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ace_Arab"""] , 256_001 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ace_Latn"""] , 256_002 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""fra_Latn"""] , 256_057 ) def UpperCAmelCase__ ( self : Optional[int] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Any ) -> int: """simple docstring""" self.assertIn(__SCREAMING_SNAKE_CASE , self.tokenizer.all_special_ids ) # fmt: off __SCREAMING_SNAKE_CASE = [RO_CODE, 4_254, 98_068, 112_923, 39_072, 3_909, 713, 102_767, 26, 17_314, 35_642, 14_683, 33_118, 2_022, 66_987, 2, 256_047] # fmt: on __SCREAMING_SNAKE_CASE = self.tokenizer.decode(__SCREAMING_SNAKE_CASE , skip_special_tokens=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertNotIn(self.tokenizer.eos_token , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = ["""this is gunna be a long sentence """ * 20] assert isinstance(src_text[0] , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = 10 __SCREAMING_SNAKE_CASE = self.tokenizer(__SCREAMING_SNAKE_CASE , max_length=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE ).input_ids[0] self.assertEqual(ids[-1] , 2 ) self.assertEqual(ids[0] , __SCREAMING_SNAKE_CASE ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : int ) -> List[Any]: """simple docstring""" self.assertListEqual(self.tokenizer.convert_tokens_to_ids(["""<mask>""", """ar_AR"""] ) , [256_203, 3] ) def UpperCAmelCase__ ( self : str ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = NllbTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , __SCREAMING_SNAKE_CASE ) @require_torch def UpperCAmelCase__ ( self : str ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=len(self.expected_src_tokens ) , return_tensors="""pt""" , ) __SCREAMING_SNAKE_CASE = shift_tokens_right( batch["""labels"""] , self.tokenizer.pad_token_id , self.tokenizer.lang_code_to_id["""ron_Latn"""] ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertEqual((2, 15) , batch.input_ids.shape ) self.assertEqual((2, 15) , batch.attention_mask.shape ) __SCREAMING_SNAKE_CASE = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , __SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , batch.decoder_input_ids[0, 0] ) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [EN_CODE] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer(self.src_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=3 , return_tensors="""pt""" ) __SCREAMING_SNAKE_CASE = self.tokenizer( text_target=self.tgt_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=10 , return_tensors="""pt""" ) __SCREAMING_SNAKE_CASE = targets["""input_ids"""] __SCREAMING_SNAKE_CASE = shift_tokens_right( __SCREAMING_SNAKE_CASE , self.tokenizer.pad_token_id , decoder_start_token_id=self.tokenizer.lang_code_to_id[self.tokenizer.tgt_lang] , ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 10 ) @require_torch def UpperCAmelCase__ ( self : int ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer._build_translation_inputs( """A test""" , return_tensors="""pt""" , src_lang="""eng_Latn""" , tgt_lang="""fra_Latn""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE ) , { # A, test, EOS, en_XX """input_ids""": [[256_047, 70, 7_356, 2]], """attention_mask""": [[1, 1, 1, 1]], # ar_AR """forced_bos_token_id""": 256_057, } , ) @require_torch def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = self.tokenizer( """UN Chief says there is no military solution in Syria""" , src_lang="""eng_Latn""" , tgt_lang="""fra_Latn""" ) self.assertEqual( inputs.input_ids , [16_297, 134_408, 25_653, 6_370, 248, 254, 103_929, 94_995, 108, 49_486, 2, 256_047] ) __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = self.tokenizer( """UN Chief says there is no military solution in Syria""" , src_lang="""eng_Latn""" , tgt_lang="""fra_Latn""" ) self.assertEqual( inputs.input_ids , [256_047, 16_297, 134_408, 25_653, 6_370, 248, 254, 103_929, 94_995, 108, 49_486, 2] )
267
1
'''simple docstring''' import os import tempfile import unittest from transformers import NezhaConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, NezhaForMaskedLM, NezhaForMultipleChoice, NezhaForNextSentencePrediction, NezhaForPreTraining, NezhaForQuestionAnswering, NezhaForSequenceClassification, NezhaForTokenClassification, NezhaModel, ) from transformers.models.nezha.modeling_nezha import NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCAmelCase__ : """simple docstring""" def __init__( self : Optional[int] , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : List[Any]=13 , __SCREAMING_SNAKE_CASE : Optional[int]=7 , __SCREAMING_SNAKE_CASE : int=True , __SCREAMING_SNAKE_CASE : int=True , __SCREAMING_SNAKE_CASE : Optional[int]=True , __SCREAMING_SNAKE_CASE : str=True , __SCREAMING_SNAKE_CASE : Tuple=99 , __SCREAMING_SNAKE_CASE : Union[str, Any]=32 , __SCREAMING_SNAKE_CASE : int=5 , __SCREAMING_SNAKE_CASE : List[Any]=4 , __SCREAMING_SNAKE_CASE : Optional[Any]=37 , __SCREAMING_SNAKE_CASE : Optional[int]="gelu" , __SCREAMING_SNAKE_CASE : str=0.1 , __SCREAMING_SNAKE_CASE : Tuple=0.1 , __SCREAMING_SNAKE_CASE : Optional[Any]=128 , __SCREAMING_SNAKE_CASE : Any=32 , __SCREAMING_SNAKE_CASE : Tuple=16 , __SCREAMING_SNAKE_CASE : List[str]=2 , __SCREAMING_SNAKE_CASE : Tuple=0.02 , __SCREAMING_SNAKE_CASE : List[str]=3 , __SCREAMING_SNAKE_CASE : List[Any]=4 , __SCREAMING_SNAKE_CASE : Optional[int]=None , ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = seq_length __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_input_mask __SCREAMING_SNAKE_CASE = use_token_type_ids __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = type_vocab_size __SCREAMING_SNAKE_CASE = type_sequence_label_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = num_labels __SCREAMING_SNAKE_CASE = num_choices __SCREAMING_SNAKE_CASE = scope def UpperCAmelCase__ ( self : List[str] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE = None if self.use_input_mask: __SCREAMING_SNAKE_CASE = random_attention_mask([self.batch_size, self.seq_length] ) __SCREAMING_SNAKE_CASE = None if self.use_token_type_ids: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None if self.use_labels: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_choices ) __SCREAMING_SNAKE_CASE = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase__ ( self : int ) -> Union[str, Any]: """simple docstring""" return NezhaConfig( 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 , ) def UpperCAmelCase__ ( self : List[Any] ) -> str: """simple docstring""" ( ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ) = self.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def UpperCAmelCase__ ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : int ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = NezhaModel(config=__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , token_type_ids=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE , token_type_ids=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def UpperCAmelCase__ ( self : Dict , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Any , ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = NezhaModel(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() __SCREAMING_SNAKE_CASE = model( __SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , token_type_ids=__SCREAMING_SNAKE_CASE , encoder_hidden_states=__SCREAMING_SNAKE_CASE , encoder_attention_mask=__SCREAMING_SNAKE_CASE , ) __SCREAMING_SNAKE_CASE = model( __SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , token_type_ids=__SCREAMING_SNAKE_CASE , encoder_hidden_states=__SCREAMING_SNAKE_CASE , ) __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , token_type_ids=__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def UpperCAmelCase__ ( self : Dict , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : str ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = NezhaForMaskedLM(config=__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , token_type_ids=__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase__ ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : List[str] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = NezhaForNextSentencePrediction(config=__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() __SCREAMING_SNAKE_CASE = model( __SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , token_type_ids=__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def UpperCAmelCase__ ( self : Tuple , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : List[str] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = NezhaForPreTraining(config=__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() __SCREAMING_SNAKE_CASE = model( __SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , token_type_ids=__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE , next_sentence_label=__SCREAMING_SNAKE_CASE , ) self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.seq_relationship_logits.shape , (self.batch_size, 2) ) def UpperCAmelCase__ ( self : List[str] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : Union[str, Any] ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = NezhaForQuestionAnswering(config=__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() __SCREAMING_SNAKE_CASE = model( __SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , token_type_ids=__SCREAMING_SNAKE_CASE , start_positions=__SCREAMING_SNAKE_CASE , end_positions=__SCREAMING_SNAKE_CASE , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def UpperCAmelCase__ ( self : int , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Union[str, Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = NezhaForSequenceClassification(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , token_type_ids=__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCAmelCase__ ( self : int , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : int ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = NezhaForTokenClassification(config=__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , token_type_ids=__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase__ ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : int ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.num_choices __SCREAMING_SNAKE_CASE = NezhaForMultipleChoice(config=__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() __SCREAMING_SNAKE_CASE = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __SCREAMING_SNAKE_CASE = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __SCREAMING_SNAKE_CASE = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __SCREAMING_SNAKE_CASE = model( __SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , token_type_ids=__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCAmelCase__ ( self : Optional[int] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() ( ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ) = config_and_inputs __SCREAMING_SNAKE_CASE = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class lowerCAmelCase__ ( a , a , a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = ( ( NezhaModel, NezhaForMaskedLM, NezhaForMultipleChoice, NezhaForNextSentencePrediction, NezhaForPreTraining, NezhaForQuestionAnswering, NezhaForSequenceClassification, NezhaForTokenClassification, ) if is_torch_available() else () ) lowerCAmelCase__ = ( { "feature-extraction": NezhaModel, "fill-mask": NezhaForMaskedLM, "question-answering": NezhaForQuestionAnswering, "text-classification": NezhaForSequenceClassification, "token-classification": NezhaForTokenClassification, "zero-shot": NezhaForSequenceClassification, } if is_torch_available() else {} ) lowerCAmelCase__ = True def UpperCAmelCase__ ( self : Dict , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : Union[str, Any]=False ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = super()._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , return_labels=__SCREAMING_SNAKE_CASE ) if return_labels: if model_class in get_values(__SCREAMING_SNAKE_CASE ): __SCREAMING_SNAKE_CASE = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__SCREAMING_SNAKE_CASE ) return inputs_dict def UpperCAmelCase__ ( self : Tuple ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = NezhaModelTester(self ) __SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=__SCREAMING_SNAKE_CASE , hidden_size=37 ) def UpperCAmelCase__ ( self : List[str] ) -> Optional[int]: """simple docstring""" self.config_tester.run_common_tests() def UpperCAmelCase__ ( self : Optional[int] ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] ) -> Union[str, Any]: """simple docstring""" ( ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ) = self.model_tester.prepare_config_and_inputs_for_decoder() __SCREAMING_SNAKE_CASE = None self.model_tester.create_and_check_model_as_decoder( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , ) def UpperCAmelCase__ ( self : Dict ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Any ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : int ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_next_sequence_prediction(*__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Dict ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[Any] ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : int ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__SCREAMING_SNAKE_CASE ) @slow def UpperCAmelCase__ ( self : Union[str, Any] ) -> Tuple: """simple docstring""" for model_name in NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE = NezhaModel.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertIsNotNone(__SCREAMING_SNAKE_CASE ) @slow @require_torch_gpu def UpperCAmelCase__ ( self : Tuple ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # NezhaForMultipleChoice behaves incorrectly in JIT environments. if model_class == NezhaForMultipleChoice: return __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = model_class(config=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = torch.jit.trace( __SCREAMING_SNAKE_CASE , (inputs_dict["""input_ids"""].to("""cpu""" ), inputs_dict["""attention_mask"""].to("""cpu""" )) ) with tempfile.TemporaryDirectory() as tmp: torch.jit.save(__SCREAMING_SNAKE_CASE , os.path.join(__SCREAMING_SNAKE_CASE , """bert.pt""" ) ) __SCREAMING_SNAKE_CASE = torch.jit.load(os.path.join(__SCREAMING_SNAKE_CASE , """bert.pt""" ) , map_location=__SCREAMING_SNAKE_CASE ) loaded(inputs_dict["""input_ids"""].to(__SCREAMING_SNAKE_CASE ) , inputs_dict["""attention_mask"""].to(__SCREAMING_SNAKE_CASE ) ) @require_torch class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" @slow def UpperCAmelCase__ ( self : Union[str, Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = NezhaModel.from_pretrained("""sijunhe/nezha-cn-base""" ) __SCREAMING_SNAKE_CASE = torch.tensor([[0, 1, 2, 3, 4, 5]] ) __SCREAMING_SNAKE_CASE = torch.tensor([[0, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE )[0] __SCREAMING_SNAKE_CASE = torch.Size((1, 6, 768) ) self.assertEqual(output.shape , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = torch.tensor([[[0.0685, 0.2441, 0.1102], [0.0600, 0.1906, 0.1349], [0.0221, 0.0819, 0.0586]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , __SCREAMING_SNAKE_CASE , atol=1E-4 ) ) @slow def UpperCAmelCase__ ( self : Tuple ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = NezhaForMaskedLM.from_pretrained("""sijunhe/nezha-cn-base""" ) __SCREAMING_SNAKE_CASE = torch.tensor([[0, 1, 2, 3, 4, 5]] ) __SCREAMING_SNAKE_CASE = torch.tensor([[1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE )[0] __SCREAMING_SNAKE_CASE = torch.Size((1, 6, 21_128) ) self.assertEqual(output.shape , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = torch.tensor( [[-2.7939, -1.7902, -2.2189], [-2.8585, -1.8908, -2.3723], [-2.6499, -1.7750, -2.2558]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , __SCREAMING_SNAKE_CASE , atol=1E-4 ) )
267
'''simple docstring''' import math from enum import Enum from typing import Optional, Union from torch.optim import Optimizer from torch.optim.lr_scheduler import LambdaLR from .utils import logging UpperCAmelCase : str = logging.get_logger(__name__) class lowerCAmelCase__ ( a ): """simple docstring""" lowerCAmelCase__ = "linear" lowerCAmelCase__ = "cosine" lowerCAmelCase__ = "cosine_with_restarts" lowerCAmelCase__ = "polynomial" lowerCAmelCase__ = "constant" lowerCAmelCase__ = "constant_with_warmup" lowerCAmelCase__ = "piecewise_constant" def a__ ( a__ , a__ = -1 ): """simple docstring""" return LambdaLR(a__ , lambda a__ : 1 , last_epoch=a__ ) def a__ ( a__ , a__ , a__ = -1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1.0 , a__ ) ) return 1.0 return LambdaLR(a__ , a__ , last_epoch=a__ ) def a__ ( a__ , a__ , a__ = -1 ): """simple docstring""" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = step_rules.split(""",""" ) for rule_str in rule_list[:-1]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = rule_str.split(""":""" ) __SCREAMING_SNAKE_CASE = int(a__ ) __SCREAMING_SNAKE_CASE = float(a__ ) __SCREAMING_SNAKE_CASE = value __SCREAMING_SNAKE_CASE = float(rule_list[-1] ) def create_rules_function(a__ , a__ ): def rule_func(a__ ) -> float: __SCREAMING_SNAKE_CASE = sorted(rules_dict.keys() ) for i, sorted_step in enumerate(a__ ): if steps < sorted_step: return rules_dict[sorted_steps[i]] return last_lr_multiple return rule_func __SCREAMING_SNAKE_CASE = create_rules_function(a__ , a__ ) return LambdaLR(a__ , a__ , last_epoch=a__ ) def a__ ( a__ , a__ , a__ , a__=-1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) return max( 0.0 , float(num_training_steps - current_step ) / float(max(1 , num_training_steps - num_warmup_steps ) ) ) return LambdaLR(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ , a__ = 0.5 , a__ = -1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) __SCREAMING_SNAKE_CASE = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * float(a__ ) * 2.0 * progress )) ) return LambdaLR(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ , a__ = 1 , a__ = -1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) __SCREAMING_SNAKE_CASE = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) if progress >= 1.0: return 0.0 return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * ((float(a__ ) * progress) % 1.0) )) ) return LambdaLR(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ , a__=1E-7 , a__=1.0 , a__=-1 ): """simple docstring""" __SCREAMING_SNAKE_CASE = optimizer.defaults["""lr"""] if not (lr_init > lr_end): raise ValueError(F'lr_end ({lr_end}) must be be smaller than initial lr ({lr_init})' ) def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) elif current_step > num_training_steps: return lr_end / lr_init # as LambdaLR multiplies by lr_init else: __SCREAMING_SNAKE_CASE = lr_init - lr_end __SCREAMING_SNAKE_CASE = num_training_steps - num_warmup_steps __SCREAMING_SNAKE_CASE = 1 - (current_step - num_warmup_steps) / decay_steps __SCREAMING_SNAKE_CASE = lr_range * pct_remaining**power + lr_end return decay / lr_init # as LambdaLR multiplies by lr_init return LambdaLR(a__ , a__ , a__ ) UpperCAmelCase : Optional[Any] = { SchedulerType.LINEAR: get_linear_schedule_with_warmup, SchedulerType.COSINE: get_cosine_schedule_with_warmup, SchedulerType.COSINE_WITH_RESTARTS: get_cosine_with_hard_restarts_schedule_with_warmup, SchedulerType.POLYNOMIAL: get_polynomial_decay_schedule_with_warmup, SchedulerType.CONSTANT: get_constant_schedule, SchedulerType.CONSTANT_WITH_WARMUP: get_constant_schedule_with_warmup, SchedulerType.PIECEWISE_CONSTANT: get_piecewise_constant_schedule, } def a__ ( a__ , a__ , a__ = None , a__ = None , a__ = None , a__ = 1 , a__ = 1.0 , a__ = -1 , ): """simple docstring""" __SCREAMING_SNAKE_CASE = SchedulerType(a__ ) __SCREAMING_SNAKE_CASE = TYPE_TO_SCHEDULER_FUNCTION[name] if name == SchedulerType.CONSTANT: return schedule_func(a__ , last_epoch=a__ ) if name == SchedulerType.PIECEWISE_CONSTANT: return schedule_func(a__ , step_rules=a__ , last_epoch=a__ ) # All other schedulers require `num_warmup_steps` if num_warmup_steps is None: raise ValueError(F'{name} requires `num_warmup_steps`, please provide that argument.' ) if name == SchedulerType.CONSTANT_WITH_WARMUP: return schedule_func(a__ , num_warmup_steps=a__ , last_epoch=a__ ) # All other schedulers require `num_training_steps` if num_training_steps is None: raise ValueError(F'{name} requires `num_training_steps`, please provide that argument.' ) if name == SchedulerType.COSINE_WITH_RESTARTS: return schedule_func( a__ , num_warmup_steps=a__ , num_training_steps=a__ , num_cycles=a__ , last_epoch=a__ , ) if name == SchedulerType.POLYNOMIAL: return schedule_func( a__ , num_warmup_steps=a__ , num_training_steps=a__ , power=a__ , last_epoch=a__ , ) return schedule_func( a__ , num_warmup_steps=a__ , num_training_steps=a__ , last_epoch=a__ )
267
1
'''simple docstring''' from __future__ import annotations UpperCAmelCase : Dict = 'Muhammad Umer Farooq' UpperCAmelCase : Any = 'MIT' UpperCAmelCase : Tuple = '1.0.0' UpperCAmelCase : Optional[Any] = 'Muhammad Umer Farooq' UpperCAmelCase : Union[str, Any] = 'contact@muhammadumerfarooq.me' UpperCAmelCase : Dict = 'Alpha' import re from html.parser import HTMLParser from urllib import parse import requests class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : str ) -> None: """simple docstring""" super().__init__() __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = domain def UpperCAmelCase__ ( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : list[tuple[str, str | None]] ) -> None: """simple docstring""" if tag == "a": # Check the list of defined attributes. for name, value in attrs: # If href is defined, and not empty nor # print it. if name == "href" and value != "#" and value != "": # If not already in urls. if value not in self.urls: __SCREAMING_SNAKE_CASE = parse.urljoin(self.domain , __SCREAMING_SNAKE_CASE ) self.urls.append(__SCREAMING_SNAKE_CASE ) def a__ ( a__ ): """simple docstring""" return ".".join(get_sub_domain_name(a__ ).split(""".""" )[-2:] ) def a__ ( a__ ): """simple docstring""" return parse.urlparse(a__ ).netloc def a__ ( a__ = "https://github.com" ): """simple docstring""" __SCREAMING_SNAKE_CASE = get_domain_name(a__ ) # Initialize the parser __SCREAMING_SNAKE_CASE = Parser(a__ ) try: # Open URL __SCREAMING_SNAKE_CASE = requests.get(a__ ) # pass the raw HTML to the parser to get links parser.feed(r.text ) # Get links and loop through __SCREAMING_SNAKE_CASE = set() for link in parser.urls: # open URL. # read = requests.get(link) try: __SCREAMING_SNAKE_CASE = requests.get(a__ ) # Get the valid email. __SCREAMING_SNAKE_CASE = re.findall("""[a-zA-Z0-9]+@""" + domain , read.text ) # If not in list then append it. for email in emails: valid_emails.add(a__ ) except ValueError: pass except ValueError: raise SystemExit(1 ) # Finally return a sorted list of email addresses with no duplicates. return sorted(a__ ) if __name__ == "__main__": UpperCAmelCase : int = emails_from_url('https://github.com') print(f"""{len(emails)} emails found:""") print('\n'.join(sorted(emails)))
267
'''simple docstring''' import argparse import os from . import ( ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, BART_PRETRAINED_MODEL_ARCHIVE_LIST, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, AlbertConfig, BartConfig, BertConfig, CamembertConfig, CTRLConfig, DistilBertConfig, DPRConfig, ElectraConfig, FlaubertConfig, GPTaConfig, LayoutLMConfig, LxmertConfig, OpenAIGPTConfig, RobertaConfig, TaConfig, TFAlbertForPreTraining, TFBartForConditionalGeneration, TFBartForSequenceClassification, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFCamembertForMaskedLM, TFCTRLLMHeadModel, TFDistilBertForMaskedLM, TFDistilBertForQuestionAnswering, TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, TFElectraForPreTraining, TFFlaubertWithLMHeadModel, TFGPTaLMHeadModel, TFLayoutLMForMaskedLM, TFLxmertForPreTraining, TFLxmertVisualFeatureEncoder, TFOpenAIGPTLMHeadModel, TFRobertaForCausalLM, TFRobertaForMaskedLM, TFRobertaForSequenceClassification, TFTaForConditionalGeneration, TFTransfoXLLMHeadModel, TFWavaVecaModel, TFXLMRobertaForMaskedLM, TFXLMWithLMHeadModel, TFXLNetLMHeadModel, TransfoXLConfig, WavaVecaConfig, WavaVecaModel, XLMConfig, XLMRobertaConfig, XLNetConfig, is_torch_available, load_pytorch_checkpoint_in_tfa_model, ) from .utils import CONFIG_NAME, WEIGHTS_NAME, cached_file, logging if is_torch_available(): import numpy as np import torch from . import ( AlbertForPreTraining, BartForConditionalGeneration, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, CamembertForMaskedLM, CTRLLMHeadModel, DistilBertForMaskedLM, DistilBertForQuestionAnswering, DPRContextEncoder, DPRQuestionEncoder, DPRReader, ElectraForPreTraining, FlaubertWithLMHeadModel, GPTaLMHeadModel, LayoutLMForMaskedLM, LxmertForPreTraining, LxmertVisualFeatureEncoder, OpenAIGPTLMHeadModel, RobertaForMaskedLM, RobertaForSequenceClassification, TaForConditionalGeneration, TransfoXLLMHeadModel, XLMRobertaForMaskedLM, XLMWithLMHeadModel, XLNetLMHeadModel, ) logging.set_verbosity_info() UpperCAmelCase : Tuple = { 'bart': ( BartConfig, TFBartForConditionalGeneration, TFBartForSequenceClassification, BartForConditionalGeneration, BART_PRETRAINED_MODEL_ARCHIVE_LIST, ), 'bert': ( BertConfig, TFBertForPreTraining, BertForPreTraining, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'bert-large-uncased-whole-word-masking-finetuned-squad': ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'bert-large-cased-whole-word-masking-finetuned-squad': ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'bert-base-cased-finetuned-mrpc': ( BertConfig, TFBertForSequenceClassification, BertForSequenceClassification, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'dpr': ( DPRConfig, TFDPRQuestionEncoder, TFDPRContextEncoder, TFDPRReader, DPRQuestionEncoder, DPRContextEncoder, DPRReader, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ), 'gpt2': ( GPTaConfig, TFGPTaLMHeadModel, GPTaLMHeadModel, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'xlnet': ( XLNetConfig, TFXLNetLMHeadModel, XLNetLMHeadModel, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'xlm': ( XLMConfig, TFXLMWithLMHeadModel, XLMWithLMHeadModel, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'xlm-roberta': ( XLMRobertaConfig, TFXLMRobertaForMaskedLM, XLMRobertaForMaskedLM, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'transfo-xl': ( TransfoXLConfig, TFTransfoXLLMHeadModel, TransfoXLLMHeadModel, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'openai-gpt': ( OpenAIGPTConfig, TFOpenAIGPTLMHeadModel, OpenAIGPTLMHeadModel, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'roberta': ( RobertaConfig, TFRobertaForCausalLM, TFRobertaForMaskedLM, RobertaForMaskedLM, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'layoutlm': ( LayoutLMConfig, TFLayoutLMForMaskedLM, LayoutLMForMaskedLM, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, ), 'roberta-large-mnli': ( RobertaConfig, TFRobertaForSequenceClassification, RobertaForSequenceClassification, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'camembert': ( CamembertConfig, TFCamembertForMaskedLM, CamembertForMaskedLM, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'flaubert': ( FlaubertConfig, TFFlaubertWithLMHeadModel, FlaubertWithLMHeadModel, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'distilbert': ( DistilBertConfig, TFDistilBertForMaskedLM, DistilBertForMaskedLM, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'distilbert-base-distilled-squad': ( DistilBertConfig, TFDistilBertForQuestionAnswering, DistilBertForQuestionAnswering, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'lxmert': ( LxmertConfig, TFLxmertForPreTraining, LxmertForPreTraining, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'lxmert-visual-feature-encoder': ( LxmertConfig, TFLxmertVisualFeatureEncoder, LxmertVisualFeatureEncoder, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'ctrl': ( CTRLConfig, TFCTRLLMHeadModel, CTRLLMHeadModel, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'albert': ( AlbertConfig, TFAlbertForPreTraining, AlbertForPreTraining, ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 't5': ( TaConfig, TFTaForConditionalGeneration, TaForConditionalGeneration, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'electra': ( ElectraConfig, TFElectraForPreTraining, ElectraForPreTraining, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'wav2vec2': ( WavaVecaConfig, TFWavaVecaModel, WavaVecaModel, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), } def a__ ( a__ , a__ , a__ , a__ , a__=False , a__=True ): """simple docstring""" if model_type not in MODEL_CLASSES: raise ValueError(F'Unrecognized model type, should be one of {list(MODEL_CLASSES.keys() )}.' ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = MODEL_CLASSES[model_type] # Initialise TF model if config_file in aws_config_map: __SCREAMING_SNAKE_CASE = cached_file(a__ , a__ , force_download=not use_cached_models ) __SCREAMING_SNAKE_CASE = config_class.from_json_file(a__ ) __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = True print(F'Building TensorFlow model from configuration: {config}' ) __SCREAMING_SNAKE_CASE = model_class(a__ ) # Load weights from tf checkpoint if pytorch_checkpoint_path in aws_config_map.keys(): __SCREAMING_SNAKE_CASE = cached_file( a__ , a__ , force_download=not use_cached_models ) # Load PyTorch checkpoint in tf2 model: __SCREAMING_SNAKE_CASE = load_pytorch_checkpoint_in_tfa_model(a__ , a__ ) if compare_with_pt_model: __SCREAMING_SNAKE_CASE = tf_model(tf_model.dummy_inputs , training=a__ ) # build the network __SCREAMING_SNAKE_CASE = torch.load(a__ , map_location="""cpu""" ) __SCREAMING_SNAKE_CASE = pt_model_class.from_pretrained( pretrained_model_name_or_path=a__ , config=a__ , state_dict=a__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = pt_model(**pt_model.dummy_inputs ) __SCREAMING_SNAKE_CASE = pto[0].numpy() __SCREAMING_SNAKE_CASE = tfo[0].numpy() __SCREAMING_SNAKE_CASE = np.amax(np.abs(np_pt - np_tf ) ) print(F'Max absolute difference between models outputs {diff}' ) assert diff <= 2E-2, F'Error, model absolute difference is >2e-2: {diff}' # Save pytorch-model print(F'Save TensorFlow model to {tf_dump_path}' ) tf_model.save_weights(a__ , save_format="""h5""" ) def a__ ( a__ , a__ , a__=None , a__=None , a__=False , a__=False , a__=False , a__=False , ): """simple docstring""" if args_model_type is None: __SCREAMING_SNAKE_CASE = list(MODEL_CLASSES.keys() ) else: __SCREAMING_SNAKE_CASE = [args_model_type] for j, model_type in enumerate(a__ , start=1 ): print("""=""" * 1_00 ) print(F' Converting model type {j}/{len(a__ )}: {model_type}' ) print("""=""" * 1_00 ) if model_type not in MODEL_CLASSES: raise ValueError(F'Unrecognized model type {model_type}, should be one of {list(MODEL_CLASSES.keys() )}.' ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = MODEL_CLASSES[model_type] if model_shortcut_names_or_path is None: __SCREAMING_SNAKE_CASE = list(aws_model_maps.keys() ) if config_shortcut_names_or_path is None: __SCREAMING_SNAKE_CASE = model_shortcut_names_or_path for i, (model_shortcut_name, config_shortcut_name) in enumerate( zip(a__ , a__ ) , start=1 ): print("""-""" * 1_00 ) if "-squad" in model_shortcut_name or "-mrpc" in model_shortcut_name or "-mnli" in model_shortcut_name: if not only_convert_finetuned_models: print(F' Skipping finetuned checkpoint {model_shortcut_name}' ) continue __SCREAMING_SNAKE_CASE = model_shortcut_name elif only_convert_finetuned_models: print(F' Skipping not finetuned checkpoint {model_shortcut_name}' ) continue print( F' Converting checkpoint {i}/{len(a__ )}: {model_shortcut_name} - model_type {model_type}' ) print("""-""" * 1_00 ) if config_shortcut_name in aws_config_map: __SCREAMING_SNAKE_CASE = cached_file(a__ , a__ , force_download=not use_cached_models ) else: __SCREAMING_SNAKE_CASE = config_shortcut_name if model_shortcut_name in aws_model_maps: __SCREAMING_SNAKE_CASE = cached_file(a__ , a__ , force_download=not use_cached_models ) else: __SCREAMING_SNAKE_CASE = model_shortcut_name if os.path.isfile(a__ ): __SCREAMING_SNAKE_CASE = """converted_model""" convert_pt_checkpoint_to_tf( model_type=a__ , pytorch_checkpoint_path=a__ , config_file=a__ , tf_dump_path=os.path.join(a__ , model_shortcut_name + """-tf_model.h5""" ) , compare_with_pt_model=a__ , ) if remove_cached_files: os.remove(a__ ) os.remove(a__ ) if __name__ == "__main__": UpperCAmelCase : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--tf_dump_path', default=None, type=str, required=True, help='Path to the output Tensorflow dump file.' ) parser.add_argument( '--model_type', default=None, type=str, help=( f"""Model type selected in the list of {list(MODEL_CLASSES.keys())}. If not given, will download and """ 'convert all the models from AWS.' ), ) parser.add_argument( '--pytorch_checkpoint_path', default=None, type=str, help=( 'Path to the PyTorch checkpoint path or shortcut name to download from AWS. ' 'If not given, will download and convert all the checkpoints from AWS.' ), ) parser.add_argument( '--config_file', default=None, type=str, help=( 'The config json file corresponding to the pre-trained model. \n' 'This specifies the model architecture. If not given and ' '--pytorch_checkpoint_path is not given or is a shortcut name ' 'use the configuration associated to the shortcut name on the AWS' ), ) parser.add_argument( '--compare_with_pt_model', action='store_true', help='Compare Tensorflow and PyTorch model predictions.' ) parser.add_argument( '--use_cached_models', action='store_true', help='Use cached models if possible instead of updating to latest checkpoint versions.', ) parser.add_argument( '--remove_cached_files', action='store_true', help='Remove pytorch models after conversion (save memory when converting in batches).', ) parser.add_argument('--only_convert_finetuned_models', action='store_true', help='Only convert finetuned models.') UpperCAmelCase : List[Any] = parser.parse_args() # if args.pytorch_checkpoint_path is not None: # convert_pt_checkpoint_to_tf(args.model_type.lower(), # args.pytorch_checkpoint_path, # args.config_file if args.config_file is not None else args.pytorch_checkpoint_path, # args.tf_dump_path, # compare_with_pt_model=args.compare_with_pt_model, # use_cached_models=args.use_cached_models) # else: convert_all_pt_checkpoints_to_tf( args.model_type.lower() if args.model_type is not None else None, args.tf_dump_path, model_shortcut_names_or_path=[args.pytorch_checkpoint_path] if args.pytorch_checkpoint_path is not None else None, config_shortcut_names_or_path=[args.config_file] if args.config_file is not None else None, compare_with_pt_model=args.compare_with_pt_model, use_cached_models=args.use_cached_models, remove_cached_files=args.remove_cached_files, only_convert_finetuned_models=args.only_convert_finetuned_models, )
267
1
'''simple docstring''' class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Any ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = name __SCREAMING_SNAKE_CASE = value __SCREAMING_SNAKE_CASE = weight def __repr__( self : str ) -> Union[str, Any]: """simple docstring""" return f'{self.__class__.__name__}({self.name}, {self.value}, {self.weight})' def UpperCAmelCase__ ( self : List[Any] ) -> List[Any]: """simple docstring""" return self.value def UpperCAmelCase__ ( self : Any ) -> str: """simple docstring""" return self.name def UpperCAmelCase__ ( self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" return self.weight def UpperCAmelCase__ ( self : int ) -> Tuple: """simple docstring""" return self.value / self.weight def a__ ( a__ , a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = [] for i in range(len(a__ ) ): menu.append(Things(name[i] , value[i] , weight[i] ) ) return menu def a__ ( a__ , a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = sorted(a__ , key=a__ , reverse=a__ ) __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = 0.0, 0.0 for i in range(len(a__ ) ): if (total_cost + items_copy[i].get_weight()) <= max_cost: result.append(items_copy[i] ) total_cost += items_copy[i].get_weight() total_value += items_copy[i].get_value() return (result, total_value) def a__ ( ): """simple docstring""" if __name__ == "__main__": import doctest doctest.testmod()
267
'''simple docstring''' def a__ ( a__ ): """simple docstring""" if isinstance(a__ , a__ ): raise TypeError("""'float' object cannot be interpreted as an integer""" ) if isinstance(a__ , a__ ): raise TypeError("""'str' object cannot be interpreted as an integer""" ) if num == 0: return "0b0" __SCREAMING_SNAKE_CASE = False if num < 0: __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = -num __SCREAMING_SNAKE_CASE = [] while num > 0: binary.insert(0 , num % 2 ) num >>= 1 if negative: return "-0b" + "".join(str(a__ ) for e in binary ) return "0b" + "".join(str(a__ ) for e in binary ) if __name__ == "__main__": import doctest doctest.testmod()
267
1
'''simple docstring''' import tempfile import unittest from transformers import TaConfig, is_torch_available from transformers.testing_utils import ( require_sentencepiece, require_tokenizers, require_torch, slow, torch_device, ) from ...generation.test_utils import GenerationTesterMixin from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import AutoTokenizer, UMTaForConditionalGeneration, UMTaForQuestionAnswering, UMTaModel class lowerCAmelCase__ : """simple docstring""" def __init__( self : int , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Dict=99 , __SCREAMING_SNAKE_CASE : Dict=13 , __SCREAMING_SNAKE_CASE : str=7 , __SCREAMING_SNAKE_CASE : int=9 , __SCREAMING_SNAKE_CASE : List[Any]=True , __SCREAMING_SNAKE_CASE : Dict=True , __SCREAMING_SNAKE_CASE : Optional[int]=False , __SCREAMING_SNAKE_CASE : Union[str, Any]=32 , __SCREAMING_SNAKE_CASE : List[Any]=5 , __SCREAMING_SNAKE_CASE : Optional[Any]=4 , __SCREAMING_SNAKE_CASE : List[Any]=37 , __SCREAMING_SNAKE_CASE : Any=8 , __SCREAMING_SNAKE_CASE : Any=0.1 , __SCREAMING_SNAKE_CASE : Any=0.002 , __SCREAMING_SNAKE_CASE : List[str]=1 , __SCREAMING_SNAKE_CASE : Optional[int]=0 , __SCREAMING_SNAKE_CASE : str=0 , __SCREAMING_SNAKE_CASE : List[Any]=None , __SCREAMING_SNAKE_CASE : Optional[int]=None , ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = encoder_seq_length __SCREAMING_SNAKE_CASE = decoder_seq_length # For common tests __SCREAMING_SNAKE_CASE = self.decoder_seq_length __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_attention_mask __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = d_ff __SCREAMING_SNAKE_CASE = relative_attention_num_buckets __SCREAMING_SNAKE_CASE = dropout_rate __SCREAMING_SNAKE_CASE = initializer_factor __SCREAMING_SNAKE_CASE = eos_token_id __SCREAMING_SNAKE_CASE = pad_token_id __SCREAMING_SNAKE_CASE = decoder_start_token_id __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = decoder_layers def UpperCAmelCase__ ( self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" return TaConfig.from_pretrained("""google/umt5-base""" ) def UpperCAmelCase__ ( self : str , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : int=None , __SCREAMING_SNAKE_CASE : List[Any]=None , __SCREAMING_SNAKE_CASE : Any=None , __SCREAMING_SNAKE_CASE : List[str]=None , __SCREAMING_SNAKE_CASE : Optional[Any]=None , ) -> Tuple: """simple docstring""" if attention_mask is None: __SCREAMING_SNAKE_CASE = input_ids.ne(config.pad_token_id ) if decoder_attention_mask is None: __SCREAMING_SNAKE_CASE = decoder_input_ids.ne(config.pad_token_id ) if head_mask is None: __SCREAMING_SNAKE_CASE = torch.ones(config.num_hidden_layers , config.num_attention_heads , device=__SCREAMING_SNAKE_CASE ) if decoder_head_mask is None: __SCREAMING_SNAKE_CASE = torch.ones(config.num_decoder_layers , config.num_attention_heads , device=__SCREAMING_SNAKE_CASE ) if cross_attn_head_mask is None: __SCREAMING_SNAKE_CASE = torch.ones( config.num_decoder_layers , config.num_attention_heads , device=__SCREAMING_SNAKE_CASE ) 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, } def UpperCAmelCase__ ( self : List[Any] ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.encoder_seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size ) # we need to clamp the input ids here to avoid having pad token in between # this is because for NllbMoe the position_ids are prepared such that # all pad tokens have pos id = 2 and rest are between 2..seq_length # and the seq_length here is seq_length - num_pad_tokens # but when using past, there is no way of knowing if the past input ids had # pad tokens in them, which results in incorrect seq_lenth and which in turn results in # position_ids being off by num_pad_tokens in past input __SCREAMING_SNAKE_CASE = input_ids.clamp(self.pad_token_id + 1 ) __SCREAMING_SNAKE_CASE = decoder_input_ids.clamp(self.pad_token_id + 1 ) __SCREAMING_SNAKE_CASE = self.get_config() __SCREAMING_SNAKE_CASE = config.num_attention_heads __SCREAMING_SNAKE_CASE = self.prepare_inputs_dict(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) return config, input_dict def UpperCAmelCase__ ( self : Tuple ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() return config, inputs_dict def UpperCAmelCase__ ( self : Dict ) -> Any: """simple docstring""" return TaConfig( vocab_size=166 , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def UpperCAmelCase__ ( self : Optional[int] ) -> Optional[int]: """simple docstring""" return TaConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def UpperCAmelCase__ ( self : List[str] , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : List[str] , ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = UMTaModel(config=__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() __SCREAMING_SNAKE_CASE = model( input_ids=__SCREAMING_SNAKE_CASE , decoder_input_ids=__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , decoder_attention_mask=__SCREAMING_SNAKE_CASE , ) __SCREAMING_SNAKE_CASE = model(input_ids=__SCREAMING_SNAKE_CASE , decoder_input_ids=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = result.last_hidden_state __SCREAMING_SNAKE_CASE = result.past_key_values __SCREAMING_SNAKE_CASE = result.encoder_last_hidden_state self.parent.assertEqual(encoder_output.size() , (self.batch_size, self.encoder_seq_length, self.hidden_size) ) self.parent.assertEqual(decoder_output.size() , (self.batch_size, self.decoder_seq_length, self.hidden_size) ) # There should be `num_layers` key value embeddings stored in decoder_past self.parent.assertEqual(len(__SCREAMING_SNAKE_CASE ) , config.num_layers ) # There should be a self attn key, a self attn value, a cross attn key and a cross attn value stored in each decoder_past tuple self.parent.assertEqual(len(decoder_past[0] ) , 4 ) def UpperCAmelCase__ ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Optional[int] , ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = UMTaModel(config=__SCREAMING_SNAKE_CASE ).get_decoder().to(__SCREAMING_SNAKE_CASE ).eval() # first forward pass __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE , use_cache=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE , use_cache=__SCREAMING_SNAKE_CASE ) self.parent.assertTrue(len(__SCREAMING_SNAKE_CASE ) == len(__SCREAMING_SNAKE_CASE ) ) self.parent.assertTrue(len(__SCREAMING_SNAKE_CASE ) == len(__SCREAMING_SNAKE_CASE ) + 1 ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids __SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 1) , config.vocab_size ) # append to next input_ids and __SCREAMING_SNAKE_CASE = torch.cat([input_ids, next_tokens] , dim=-1 ) __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE )["""last_hidden_state"""] __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE , past_key_values=__SCREAMING_SNAKE_CASE )["""last_hidden_state"""] # select random slice __SCREAMING_SNAKE_CASE = ids_tensor((1,) , output_from_past.shape[-1] ).item() __SCREAMING_SNAKE_CASE = output_from_no_past[:, -1, random_slice_idx].detach() __SCREAMING_SNAKE_CASE = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) def UpperCAmelCase__ ( self : Tuple , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Tuple , ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = UMTaModel(config=__SCREAMING_SNAKE_CASE ).to(__SCREAMING_SNAKE_CASE ).half().eval() __SCREAMING_SNAKE_CASE = model(**__SCREAMING_SNAKE_CASE )["""last_hidden_state"""] self.parent.assertFalse(torch.isnan(__SCREAMING_SNAKE_CASE ).any().item() ) @require_torch class lowerCAmelCase__ ( a , a , a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = ( (UMTaModel, UMTaForConditionalGeneration, UMTaForQuestionAnswering) if is_torch_available() else () ) lowerCAmelCase__ = (UMTaForConditionalGeneration,) if is_torch_available() else () lowerCAmelCase__ = ( { "conversational": UMTaForConditionalGeneration, "feature-extraction": UMTaModel, "summarization": UMTaForConditionalGeneration, "text2text-generation": UMTaForConditionalGeneration, "translation": UMTaForConditionalGeneration, "question-answering": UMTaForQuestionAnswering, } if is_torch_available() else {} ) lowerCAmelCase__ = True lowerCAmelCase__ = False lowerCAmelCase__ = False lowerCAmelCase__ = True lowerCAmelCase__ = True # The small UMT5 model needs higher percentages for CPU/MP tests lowerCAmelCase__ = [0.8, 0.9] def UpperCAmelCase__ ( self : Optional[Any] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = UMTaModelTester(self ) @unittest.skip("""Test has a segmentation fault on torch 1.8.0""" ) def UpperCAmelCase__ ( self : str ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE = UMTaModel(config_and_inputs[0] ).to(__SCREAMING_SNAKE_CASE ) with tempfile.TemporaryDirectory() as tmpdirname: torch.onnx.export( __SCREAMING_SNAKE_CASE , (config_and_inputs[1], config_and_inputs[3], config_and_inputs[2]) , f'{tmpdirname}/t5_test.onnx' , export_params=__SCREAMING_SNAKE_CASE , opset_version=9 , input_names=["""input_ids""", """decoder_input_ids"""] , ) @unittest.skipIf(torch_device == """cpu""" , """Cant do half precision""" ) def UpperCAmelCase__ ( self : Any ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model_fpaa_forward(*__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Dict ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = ["""encoder_attentions""", """decoder_attentions""", """cross_attentions"""] __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE = config_and_inputs[0] __SCREAMING_SNAKE_CASE = UMTaForConditionalGeneration(__SCREAMING_SNAKE_CASE ).eval() model.to(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = { """head_mask""": torch.zeros(config.num_layers , config.num_heads , device=__SCREAMING_SNAKE_CASE ), """decoder_head_mask""": torch.zeros(config.num_decoder_layers , config.num_heads , device=__SCREAMING_SNAKE_CASE ), """cross_attn_head_mask""": torch.zeros(config.num_decoder_layers , config.num_heads , device=__SCREAMING_SNAKE_CASE ), } for attn_name, (name, mask) in zip(__SCREAMING_SNAKE_CASE , head_masking.items() ): __SCREAMING_SNAKE_CASE = {name: mask} # Explicitly pass decoder_head_mask as it is required from T5 model when head_mask specified if name == "head_mask": __SCREAMING_SNAKE_CASE = torch.ones( config.num_decoder_layers , config.num_heads , device=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = model.generate( config_and_inputs[1]["""input_ids"""] , num_beams=1 , max_length=3 , output_attentions=__SCREAMING_SNAKE_CASE , return_dict_in_generate=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) # We check the state of decoder_attentions and cross_attentions just from the last step __SCREAMING_SNAKE_CASE = out[attn_name] if attn_name == attention_names[0] else out[attn_name][-1] self.assertEqual(sum([w.sum().item() for w in attn_weights] ) , 0.0 ) @unittest.skip("""Does not work on the tiny model as we keep hitting edge cases.""" ) def UpperCAmelCase__ ( self : Optional[int] ) -> Optional[Any]: """simple docstring""" pass @require_torch @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" @slow @unittest.skip( """Unless we stop stripping left and right by default for all special tokens, the expected ids obtained here will not match the original ones. Wait for https://github.com/huggingface/transformers/pull/23909 to be merged""" ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = UMTaForConditionalGeneration.from_pretrained("""google/umt5-small""" , return_dict=__SCREAMING_SNAKE_CASE ).to(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("""google/umt5-small""" , use_fast=__SCREAMING_SNAKE_CASE , legacy=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = [ """Bonjour monsieur <extra_id_0> bien <extra_id_1>.""", """No se como puedo <extra_id_0>.""", """This is the reason why we <extra_id_0> them.""", """The <extra_id_0> walks in <extra_id_1>, seats""", """A <extra_id_0> walks into a bar and orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.""", ] __SCREAMING_SNAKE_CASE = tokenizer(__SCREAMING_SNAKE_CASE , return_tensors="""pt""" , padding=__SCREAMING_SNAKE_CASE ).input_ids # fmt: off __SCREAMING_SNAKE_CASE = torch.tensor( [ [ 38_530, 210_703, 256_299, 1_410, 256_298, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 826, 321, 671, 25_922, 256_299, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 1_460, 339, 312, 19_014, 10_620, 758, 256_299, 2_355,274, 1, 0, 0, 0, 0, 0, 0,0, 0], [ 517, 256_299, 14_869, 281, 301, 256_298, 275, 119_983,1, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 320, 256_299, 14_869, 281, 2_234, 289, 2_275, 333,61_391, 289, 256_298, 543, 256_297, 168_714, 329, 256_296,274, 1], ] ) # fmt: on torch.testing.assert_allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = model.generate(input_ids.to(__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = [ """<pad><extra_id_0> et<extra_id_1> [eod] <extra_id_2><extra_id_55>.. [eod] 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 <extra_id_56>ajšietosto<extra_id_56>lleux<extra_id_19><extra_id_6>ajšie</s>""", """<pad><extra_id_0>.<extra_id_1>.,<0x0A>...spech <0x0A><extra_id_20> <extra_id_21></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>""", """<pad><extra_id_0> are not going to be a part of the world. We are not going to be a part of<extra_id_1> and<extra_id_2><0x0A><extra_id_48>.<extra_id_48></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>""", """<pad><extra_id_0> door<extra_id_1>, the door<extra_id_2> 피해[/</s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>""", """<pad><extra_id_0>nyone who<extra_id_1> drink<extra_id_2> a<extra_id_3> alcohol<extra_id_4> A<extra_id_5> A. This<extra_id_6> I<extra_id_7><extra_id_52><extra_id_53></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>""", ] __SCREAMING_SNAKE_CASE = tokenizer.batch_decode(__SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
267
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices UpperCAmelCase : Optional[int] = logging.get_logger(__name__) UpperCAmelCase : str = { 'facebook/convnextv2-tiny-1k-224': 'https://huggingface.co/facebook/convnextv2-tiny-1k-224/resolve/main/config.json', } class lowerCAmelCase__ ( a , a ): """simple docstring""" lowerCAmelCase__ = "convnextv2" def __init__( self : Any , __SCREAMING_SNAKE_CASE : int=3 , __SCREAMING_SNAKE_CASE : Dict=4 , __SCREAMING_SNAKE_CASE : List[Any]=4 , __SCREAMING_SNAKE_CASE : Optional[int]=None , __SCREAMING_SNAKE_CASE : Dict=None , __SCREAMING_SNAKE_CASE : Optional[int]="gelu" , __SCREAMING_SNAKE_CASE : Union[str, Any]=0.02 , __SCREAMING_SNAKE_CASE : Dict=1E-12 , __SCREAMING_SNAKE_CASE : List[str]=0.0 , __SCREAMING_SNAKE_CASE : Optional[Any]=224 , __SCREAMING_SNAKE_CASE : Tuple=None , __SCREAMING_SNAKE_CASE : List[str]=None , **__SCREAMING_SNAKE_CASE : Union[str, Any] , ) -> Union[str, Any]: """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = patch_size __SCREAMING_SNAKE_CASE = num_stages __SCREAMING_SNAKE_CASE = [96, 192, 384, 768] if hidden_sizes is None else hidden_sizes __SCREAMING_SNAKE_CASE = [3, 3, 9, 3] if depths is None else depths __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = drop_path_rate __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = ["""stem"""] + [f'stage{idx}' for idx in range(1 , len(self.depths ) + 1 )] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = get_aligned_output_features_output_indices( out_features=__SCREAMING_SNAKE_CASE , out_indices=__SCREAMING_SNAKE_CASE , stage_names=self.stage_names )
267
1
'''simple docstring''' import unittest from diffusers.models.unet_ad_blocks import * # noqa F403 from diffusers.utils import torch_device from .test_unet_blocks_common import UNetBlockTesterMixin class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = DownBlockaD # noqa F405 lowerCAmelCase__ = "down" def UpperCAmelCase__ ( self : List[str] ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = [-0.0232, -0.9869, 0.8054, -0.0637, -0.1688, -1.4264, 0.4470, -1.3394, 0.0904] super().test_output(__SCREAMING_SNAKE_CASE ) class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = ResnetDownsampleBlockaD # noqa F405 lowerCAmelCase__ = "down" def UpperCAmelCase__ ( self : Any ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = [0.0710, 0.2410, -0.7320, -1.0757, -1.1343, 0.3540, -0.0133, -0.2576, 0.0948] super().test_output(__SCREAMING_SNAKE_CASE ) class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = AttnDownBlockaD # noqa F405 lowerCAmelCase__ = "down" def UpperCAmelCase__ ( self : List[str] ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = [0.0636, 0.8964, -0.6234, -1.0131, 0.0844, 0.4935, 0.3437, 0.0911, -0.2957] super().test_output(__SCREAMING_SNAKE_CASE ) class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = CrossAttnDownBlockaD # noqa F405 lowerCAmelCase__ = "down" def UpperCAmelCase__ ( self : Dict ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = super().prepare_init_args_and_inputs_for_common() __SCREAMING_SNAKE_CASE = 32 return init_dict, inputs_dict def UpperCAmelCase__ ( self : Any ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = [0.2238, -0.7396, -0.2255, -0.3829, 0.1925, 1.1665, 0.0603, -0.7295, 0.1983] super().test_output(__SCREAMING_SNAKE_CASE ) class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = SimpleCrossAttnDownBlockaD # noqa F405 lowerCAmelCase__ = "down" @property def UpperCAmelCase__ ( self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" return super().get_dummy_input(include_encoder_hidden_states=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = super().prepare_init_args_and_inputs_for_common() __SCREAMING_SNAKE_CASE = 32 return init_dict, inputs_dict @unittest.skipIf(torch_device == """mps""" , """MPS result is not consistent""" ) def UpperCAmelCase__ ( self : Optional[int] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = [0.7921, -0.0992, -0.1962, -0.7695, -0.4242, 0.7804, 0.4737, 0.2765, 0.3338] super().test_output(__SCREAMING_SNAKE_CASE ) class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = SkipDownBlockaD # noqa F405 lowerCAmelCase__ = "down" @property def UpperCAmelCase__ ( self : Union[str, Any] ) -> Dict: """simple docstring""" return super().get_dummy_input(include_skip_sample=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = [-0.0845, -0.2087, -0.2465, 0.0971, 0.1900, -0.0484, 0.2664, 0.4179, 0.5069] super().test_output(__SCREAMING_SNAKE_CASE ) class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = AttnSkipDownBlockaD # noqa F405 lowerCAmelCase__ = "down" @property def UpperCAmelCase__ ( self : List[str] ) -> str: """simple docstring""" return super().get_dummy_input(include_skip_sample=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[Any] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = [0.5539, 0.1609, 0.4924, 0.0537, -0.1995, 0.4050, 0.0979, -0.2721, -0.0642] super().test_output(__SCREAMING_SNAKE_CASE ) class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = DownEncoderBlockaD # noqa F405 lowerCAmelCase__ = "down" @property def UpperCAmelCase__ ( self : str ) -> Optional[int]: """simple docstring""" return super().get_dummy_input(include_temb=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : int ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = { """in_channels""": 32, """out_channels""": 32, } __SCREAMING_SNAKE_CASE = self.dummy_input return init_dict, inputs_dict def UpperCAmelCase__ ( self : str ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = [1.1102, 0.5302, 0.4872, -0.0023, -0.8042, 0.0483, -0.3489, -0.5632, 0.7626] super().test_output(__SCREAMING_SNAKE_CASE ) class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = AttnDownEncoderBlockaD # noqa F405 lowerCAmelCase__ = "down" @property def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" return super().get_dummy_input(include_temb=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Tuple ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = { """in_channels""": 32, """out_channels""": 32, } __SCREAMING_SNAKE_CASE = self.dummy_input return init_dict, inputs_dict def UpperCAmelCase__ ( self : int ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = [0.8966, -0.1486, 0.8568, 0.8141, -0.9046, -0.1342, -0.0972, -0.7417, 0.1538] super().test_output(__SCREAMING_SNAKE_CASE ) class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = UNetMidBlockaD # noqa F405 lowerCAmelCase__ = "mid" def UpperCAmelCase__ ( self : List[Any] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = { """in_channels""": 32, """temb_channels""": 128, } __SCREAMING_SNAKE_CASE = self.dummy_input return init_dict, inputs_dict def UpperCAmelCase__ ( self : int ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = [-0.1062, 1.7248, 0.3494, 1.4569, -0.0910, -1.2421, -0.9984, 0.6736, 1.0028] super().test_output(__SCREAMING_SNAKE_CASE ) class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = UNetMidBlockaDCrossAttn # noqa F405 lowerCAmelCase__ = "mid" def UpperCAmelCase__ ( self : List[Any] ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = super().prepare_init_args_and_inputs_for_common() __SCREAMING_SNAKE_CASE = 32 return init_dict, inputs_dict def UpperCAmelCase__ ( self : str ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = [0.0187, 2.4220, 0.4484, 1.1203, -0.6121, -1.5122, -0.8270, 0.7851, 1.8335] super().test_output(__SCREAMING_SNAKE_CASE ) class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = UNetMidBlockaDSimpleCrossAttn # noqa F405 lowerCAmelCase__ = "mid" @property def UpperCAmelCase__ ( self : Optional[Any] ) -> List[str]: """simple docstring""" return super().get_dummy_input(include_encoder_hidden_states=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[Any] ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = super().prepare_init_args_and_inputs_for_common() __SCREAMING_SNAKE_CASE = 32 return init_dict, inputs_dict def UpperCAmelCase__ ( self : str ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = [0.7143, 1.9974, 0.5448, 1.3977, 0.1282, -1.1237, -1.4238, 0.5530, 0.8880] super().test_output(__SCREAMING_SNAKE_CASE ) class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = UpBlockaD # noqa F405 lowerCAmelCase__ = "up" @property def UpperCAmelCase__ ( self : str ) -> Optional[int]: """simple docstring""" return super().get_dummy_input(include_res_hidden_states_tuple=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = [-0.2041, -0.4165, -0.3022, 0.0041, -0.6628, -0.7053, 0.1928, -0.0325, 0.0523] super().test_output(__SCREAMING_SNAKE_CASE ) class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = ResnetUpsampleBlockaD # noqa F405 lowerCAmelCase__ = "up" @property def UpperCAmelCase__ ( self : Optional[int] ) -> str: """simple docstring""" return super().get_dummy_input(include_res_hidden_states_tuple=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = [0.2287, 0.3549, -0.1346, 0.4797, -0.1715, -0.9649, 0.7305, -0.5864, -0.6244] super().test_output(__SCREAMING_SNAKE_CASE ) class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = CrossAttnUpBlockaD # noqa F405 lowerCAmelCase__ = "up" @property def UpperCAmelCase__ ( self : str ) -> Union[str, Any]: """simple docstring""" return super().get_dummy_input(include_res_hidden_states_tuple=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[str] ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = super().prepare_init_args_and_inputs_for_common() __SCREAMING_SNAKE_CASE = 32 return init_dict, inputs_dict def UpperCAmelCase__ ( self : Any ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = [-0.1403, -0.3515, -0.0420, -0.1425, 0.3167, 0.5094, -0.2181, 0.5931, 0.5582] super().test_output(__SCREAMING_SNAKE_CASE ) class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = SimpleCrossAttnUpBlockaD # noqa F405 lowerCAmelCase__ = "up" @property def UpperCAmelCase__ ( self : List[str] ) -> Dict: """simple docstring""" return super().get_dummy_input(include_res_hidden_states_tuple=__SCREAMING_SNAKE_CASE , include_encoder_hidden_states=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Any ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = super().prepare_init_args_and_inputs_for_common() __SCREAMING_SNAKE_CASE = 32 return init_dict, inputs_dict def UpperCAmelCase__ ( self : str ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = [0.2645, 0.1480, 0.0909, 0.8044, -0.9758, -0.9083, 0.0994, -1.1453, -0.7402] super().test_output(__SCREAMING_SNAKE_CASE ) class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = AttnUpBlockaD # noqa F405 lowerCAmelCase__ = "up" @property def UpperCAmelCase__ ( self : Union[str, Any] ) -> Tuple: """simple docstring""" return super().get_dummy_input(include_res_hidden_states_tuple=__SCREAMING_SNAKE_CASE ) @unittest.skipIf(torch_device == """mps""" , """MPS result is not consistent""" ) def UpperCAmelCase__ ( self : List[Any] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = [0.0979, 0.1326, 0.0021, 0.0659, 0.2249, 0.0059, 0.1132, 0.5952, 0.1033] super().test_output(__SCREAMING_SNAKE_CASE ) class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = SkipUpBlockaD # noqa F405 lowerCAmelCase__ = "up" @property def UpperCAmelCase__ ( self : Any ) -> int: """simple docstring""" return super().get_dummy_input(include_res_hidden_states_tuple=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[str] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = [-0.0893, -0.1234, -0.1506, -0.0332, 0.0123, -0.0211, 0.0566, 0.0143, 0.0362] super().test_output(__SCREAMING_SNAKE_CASE ) class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = AttnSkipUpBlockaD # noqa F405 lowerCAmelCase__ = "up" @property def UpperCAmelCase__ ( self : Optional[Any] ) -> int: """simple docstring""" return super().get_dummy_input(include_res_hidden_states_tuple=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = [0.0361, 0.0617, 0.2787, -0.0350, 0.0342, 0.3421, -0.0843, 0.0913, 0.3015] super().test_output(__SCREAMING_SNAKE_CASE ) class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = UpDecoderBlockaD # noqa F405 lowerCAmelCase__ = "up" @property def UpperCAmelCase__ ( self : Union[str, Any] ) -> List[str]: """simple docstring""" return super().get_dummy_input(include_temb=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Tuple ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = {"""in_channels""": 32, """out_channels""": 32} __SCREAMING_SNAKE_CASE = self.dummy_input return init_dict, inputs_dict def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = [0.4404, 0.1998, -0.9886, -0.3320, -0.3128, -0.7034, -0.6955, -0.2338, -0.3137] super().test_output(__SCREAMING_SNAKE_CASE ) class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = AttnUpDecoderBlockaD # noqa F405 lowerCAmelCase__ = "up" @property def UpperCAmelCase__ ( self : Optional[Any] ) -> Union[str, Any]: """simple docstring""" return super().get_dummy_input(include_temb=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = {"""in_channels""": 32, """out_channels""": 32} __SCREAMING_SNAKE_CASE = self.dummy_input return init_dict, inputs_dict def UpperCAmelCase__ ( self : List[Any] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = [0.6738, 0.4491, 0.1055, 1.0710, 0.7316, 0.3339, 0.3352, 0.1023, 0.3568] super().test_output(__SCREAMING_SNAKE_CASE )
267
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices UpperCAmelCase : List[str] = logging.get_logger(__name__) class lowerCAmelCase__ ( a , a ): """simple docstring""" lowerCAmelCase__ = "maskformer-swin" lowerCAmelCase__ = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self : str , __SCREAMING_SNAKE_CASE : Tuple=224 , __SCREAMING_SNAKE_CASE : str=4 , __SCREAMING_SNAKE_CASE : Union[str, Any]=3 , __SCREAMING_SNAKE_CASE : Optional[Any]=96 , __SCREAMING_SNAKE_CASE : Optional[Any]=[2, 2, 6, 2] , __SCREAMING_SNAKE_CASE : Any=[3, 6, 12, 24] , __SCREAMING_SNAKE_CASE : Dict=7 , __SCREAMING_SNAKE_CASE : Dict=4.0 , __SCREAMING_SNAKE_CASE : Dict=True , __SCREAMING_SNAKE_CASE : str=0.0 , __SCREAMING_SNAKE_CASE : int=0.0 , __SCREAMING_SNAKE_CASE : str=0.1 , __SCREAMING_SNAKE_CASE : List[Any]="gelu" , __SCREAMING_SNAKE_CASE : str=False , __SCREAMING_SNAKE_CASE : Optional[int]=0.02 , __SCREAMING_SNAKE_CASE : Optional[int]=1E-5 , __SCREAMING_SNAKE_CASE : Dict=None , __SCREAMING_SNAKE_CASE : Dict=None , **__SCREAMING_SNAKE_CASE : Tuple , ) -> Tuple: """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = patch_size __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = embed_dim __SCREAMING_SNAKE_CASE = depths __SCREAMING_SNAKE_CASE = len(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = num_heads __SCREAMING_SNAKE_CASE = window_size __SCREAMING_SNAKE_CASE = mlp_ratio __SCREAMING_SNAKE_CASE = qkv_bias __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = drop_path_rate __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = use_absolute_embeddings __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = initializer_range # we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model __SCREAMING_SNAKE_CASE = int(embed_dim * 2 ** (len(__SCREAMING_SNAKE_CASE ) - 1) ) __SCREAMING_SNAKE_CASE = ["""stem"""] + [f'stage{idx}' for idx in range(1 , len(__SCREAMING_SNAKE_CASE ) + 1 )] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = get_aligned_output_features_output_indices( out_features=__SCREAMING_SNAKE_CASE , out_indices=__SCREAMING_SNAKE_CASE , stage_names=self.stage_names )
267
1
'''simple docstring''' import os import warnings from typing import List, Optional from ...tokenization_utils_base import BatchEncoding from ...utils import logging from .configuration_rag import RagConfig UpperCAmelCase : Dict = logging.get_logger(__name__) class lowerCAmelCase__ : """simple docstring""" def __init__( self : int , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Tuple ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = question_encoder __SCREAMING_SNAKE_CASE = generator __SCREAMING_SNAKE_CASE = self.question_encoder def UpperCAmelCase__ ( self : Dict , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> Any: """simple docstring""" if os.path.isfile(__SCREAMING_SNAKE_CASE ): raise ValueError(f'Provided path ({save_directory}) should be a directory, not a file' ) os.makedirs(__SCREAMING_SNAKE_CASE , exist_ok=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = os.path.join(__SCREAMING_SNAKE_CASE , """question_encoder_tokenizer""" ) __SCREAMING_SNAKE_CASE = os.path.join(__SCREAMING_SNAKE_CASE , """generator_tokenizer""" ) self.question_encoder.save_pretrained(__SCREAMING_SNAKE_CASE ) self.generator.save_pretrained(__SCREAMING_SNAKE_CASE ) @classmethod def UpperCAmelCase__ ( cls : Tuple , __SCREAMING_SNAKE_CASE : Optional[int] , **__SCREAMING_SNAKE_CASE : int ) -> List[Any]: """simple docstring""" from ..auto.tokenization_auto import AutoTokenizer __SCREAMING_SNAKE_CASE = kwargs.pop("""config""" , __SCREAMING_SNAKE_CASE ) if config is None: __SCREAMING_SNAKE_CASE = RagConfig.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained( __SCREAMING_SNAKE_CASE , config=config.question_encoder , subfolder="""question_encoder_tokenizer""" ) __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained( __SCREAMING_SNAKE_CASE , config=config.generator , subfolder="""generator_tokenizer""" ) return cls(question_encoder=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE ) def __call__( self : Optional[int] , *__SCREAMING_SNAKE_CASE : Any , **__SCREAMING_SNAKE_CASE : Optional[int] ) -> List[str]: """simple docstring""" return self.current_tokenizer(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[Any] , *__SCREAMING_SNAKE_CASE : List[Any] , **__SCREAMING_SNAKE_CASE : str ) -> List[str]: """simple docstring""" return self.generator.batch_decode(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[Any] , *__SCREAMING_SNAKE_CASE : Dict , **__SCREAMING_SNAKE_CASE : List[str] ) -> Optional[Any]: """simple docstring""" return self.generator.decode(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.question_encoder def UpperCAmelCase__ ( self : Optional[int] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = self.generator def UpperCAmelCase__ ( self : Any , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Optional[List[str]] = None , __SCREAMING_SNAKE_CASE : Optional[int] = None , __SCREAMING_SNAKE_CASE : Optional[int] = None , __SCREAMING_SNAKE_CASE : str = "longest" , __SCREAMING_SNAKE_CASE : str = None , __SCREAMING_SNAKE_CASE : bool = True , **__SCREAMING_SNAKE_CASE : Tuple , ) -> BatchEncoding: """simple docstring""" warnings.warn( """`prepare_seq2seq_batch` is deprecated and will be removed in version 5 of 🤗 Transformers. Use the """ """regular `__call__` method to prepare your inputs and the tokenizer under the `with_target_tokenizer` """ """context manager to prepare your targets. See the documentation of your specific tokenizer for more """ """details""" , __SCREAMING_SNAKE_CASE , ) if max_length is None: __SCREAMING_SNAKE_CASE = self.current_tokenizer.model_max_length __SCREAMING_SNAKE_CASE = self( __SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , return_tensors=__SCREAMING_SNAKE_CASE , max_length=__SCREAMING_SNAKE_CASE , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) if tgt_texts is None: return model_inputs # Process tgt_texts if max_target_length is None: __SCREAMING_SNAKE_CASE = self.current_tokenizer.model_max_length __SCREAMING_SNAKE_CASE = self( text_target=__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , return_tensors=__SCREAMING_SNAKE_CASE , padding=__SCREAMING_SNAKE_CASE , max_length=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) __SCREAMING_SNAKE_CASE = labels["""input_ids"""] return model_inputs
267
'''simple docstring''' class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : int ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = n __SCREAMING_SNAKE_CASE = [None] * self.n __SCREAMING_SNAKE_CASE = 0 # index of the first element __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 def __len__( self : Tuple ) -> int: """simple docstring""" return self.size def UpperCAmelCase__ ( self : Optional[Any] ) -> bool: """simple docstring""" return self.size == 0 def UpperCAmelCase__ ( self : Any ) -> int: """simple docstring""" return False if self.is_empty() else self.array[self.front] def UpperCAmelCase__ ( self : Dict , __SCREAMING_SNAKE_CASE : Union[str, Any] ) -> Dict: """simple docstring""" if self.size >= self.n: raise Exception("""QUEUE IS FULL""" ) __SCREAMING_SNAKE_CASE = data __SCREAMING_SNAKE_CASE = (self.rear + 1) % self.n self.size += 1 return self def UpperCAmelCase__ ( self : List[str] ) -> Optional[Any]: """simple docstring""" if self.size == 0: raise Exception("""UNDERFLOW""" ) __SCREAMING_SNAKE_CASE = self.array[self.front] __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = (self.front + 1) % self.n self.size -= 1 return temp
267
1
'''simple docstring''' import shutil import tempfile import unittest from transformers import ( SPIECE_UNDERLINE, AddedToken, BatchEncoding, NllbTokenizer, NllbTokenizerFast, is_torch_available, ) from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...test_tokenization_common import TokenizerTesterMixin UpperCAmelCase : Optional[int] = get_tests_dir('fixtures/test_sentencepiece.model') if is_torch_available(): from transformers.models.mam_aaa.modeling_mam_aaa import shift_tokens_right UpperCAmelCase : Optional[int] = 2_5_6_0_4_7 UpperCAmelCase : Union[str, Any] = 2_5_6_1_4_5 @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = NllbTokenizer lowerCAmelCase__ = NllbTokenizerFast lowerCAmelCase__ = True lowerCAmelCase__ = True lowerCAmelCase__ = {} def UpperCAmelCase__ ( self : List[Any] ) -> int: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing __SCREAMING_SNAKE_CASE = NllbTokenizer(__SCREAMING_SNAKE_CASE , keep_accents=__SCREAMING_SNAKE_CASE ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCAmelCase__ ( self : Dict ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = NllbTokenizer(__SCREAMING_SNAKE_CASE , keep_accents=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(__SCREAMING_SNAKE_CASE , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) __SCREAMING_SNAKE_CASE = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ 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""", """é""", """.""", ] , ) __SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ 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] ] , ) __SCREAMING_SNAKE_CASE = tokenizer.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ 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>""", """.""", ] , ) def UpperCAmelCase__ ( self : Dict ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = (self.rust_tokenizer_class, """hf-internal-testing/tiny-random-nllb""", {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) __SCREAMING_SNAKE_CASE = tuple(f for f in tokenizer_r_files if """tokenizer.json""" not in f ) self.assertSequenceEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Checks everything loads correctly in the same way __SCREAMING_SNAKE_CASE = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) # Save tokenizer rust, legacy_format=True __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE , legacy_format=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it save with the same files self.assertSequenceEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Checks everything loads correctly in the same way __SCREAMING_SNAKE_CASE = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) # Save tokenizer rust, legacy_format=False __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE , legacy_format=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it saved the tokenizer.json file self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way __SCREAMING_SNAKE_CASE = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) @require_torch def UpperCAmelCase__ ( self : List[Any] ) -> Any: """simple docstring""" if not self.test_seqaseq: return __SCREAMING_SNAKE_CASE = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): # Longer text that will definitely require truncation. __SCREAMING_SNAKE_CASE = [ """ UN Chief Says There Is No Military Solution in Syria""", """ Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for""" """ Syria is that 'there is no military solution' to the nearly five-year conflict and more weapons""" """ will only worsen the violence and misery for millions of people.""", ] __SCREAMING_SNAKE_CASE = [ """Şeful ONU declară că nu există o soluţie militară în Siria""", """Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al""" """ Rusiei pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi""" """ că noi arme nu vor face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.""", ] try: __SCREAMING_SNAKE_CASE = tokenizer.prepare_seqaseq_batch( src_texts=__SCREAMING_SNAKE_CASE , tgt_texts=__SCREAMING_SNAKE_CASE , max_length=3 , max_target_length=10 , return_tensors="""pt""" , src_lang="""eng_Latn""" , tgt_lang="""ron_Latn""" , ) except NotImplementedError: return self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.labels.shape[1] , 10 ) # max_target_length will default to max_length if not specified __SCREAMING_SNAKE_CASE = tokenizer.prepare_seqaseq_batch( __SCREAMING_SNAKE_CASE , tgt_texts=__SCREAMING_SNAKE_CASE , max_length=3 , return_tensors="""pt""" ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.labels.shape[1] , 3 ) __SCREAMING_SNAKE_CASE = tokenizer.prepare_seqaseq_batch( src_texts=__SCREAMING_SNAKE_CASE , max_length=3 , max_target_length=10 , return_tensors="""pt""" ) self.assertEqual(batch_encoder_only.input_ids.shape[1] , 3 ) self.assertEqual(batch_encoder_only.attention_mask.shape[1] , 3 ) self.assertNotIn("""decoder_input_ids""" , __SCREAMING_SNAKE_CASE ) @unittest.skip("""Unfortunately way too slow to build a BPE with SentencePiece.""" ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" pass def UpperCAmelCase__ ( self : List[str] ) -> Dict: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): __SCREAMING_SNAKE_CASE = [AddedToken("""<special>""" , lstrip=__SCREAMING_SNAKE_CASE )] __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_r.encode("""Hey this is a <special> token""" ) __SCREAMING_SNAKE_CASE = tokenizer_r.encode("""<special>""" , add_special_tokens=__SCREAMING_SNAKE_CASE )[0] self.assertTrue(special_token_id in r_output ) if self.test_slow_tokenizer: __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.encode("""Hey this is a <special> token""" ) __SCREAMING_SNAKE_CASE = tokenizer_cr.encode("""Hey this is a <special> token""" ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertTrue(special_token_id in p_output ) self.assertTrue(special_token_id in cr_output ) @require_torch @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = "facebook/nllb-200-distilled-600M" lowerCAmelCase__ = [ " UN Chief Says There Is No Military Solution in Syria", " Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for Syria is that \"there is no military solution\" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.", ] lowerCAmelCase__ = [ "Şeful ONU declară că nu există o soluţie militară în Siria", "Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei" " pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi că noi arme nu vor" " face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.", ] lowerCAmelCase__ = [ 256047, 16297, 134408, 8165, 248066, 14734, 950, 1135, 105721, 3573, 83, 27352, 108, 49486, 2, ] @classmethod def UpperCAmelCase__ ( cls : List[Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = NllbTokenizer.from_pretrained( cls.checkpoint_name , src_lang="""eng_Latn""" , tgt_lang="""ron_Latn""" ) __SCREAMING_SNAKE_CASE = 1 return cls def UpperCAmelCase__ ( self : Union[str, Any] ) -> List[str]: """simple docstring""" self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ace_Arab"""] , 256_001 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ace_Latn"""] , 256_002 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""fra_Latn"""] , 256_057 ) def UpperCAmelCase__ ( self : Optional[int] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Any ) -> int: """simple docstring""" self.assertIn(__SCREAMING_SNAKE_CASE , self.tokenizer.all_special_ids ) # fmt: off __SCREAMING_SNAKE_CASE = [RO_CODE, 4_254, 98_068, 112_923, 39_072, 3_909, 713, 102_767, 26, 17_314, 35_642, 14_683, 33_118, 2_022, 66_987, 2, 256_047] # fmt: on __SCREAMING_SNAKE_CASE = self.tokenizer.decode(__SCREAMING_SNAKE_CASE , skip_special_tokens=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertNotIn(self.tokenizer.eos_token , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = ["""this is gunna be a long sentence """ * 20] assert isinstance(src_text[0] , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = 10 __SCREAMING_SNAKE_CASE = self.tokenizer(__SCREAMING_SNAKE_CASE , max_length=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE ).input_ids[0] self.assertEqual(ids[-1] , 2 ) self.assertEqual(ids[0] , __SCREAMING_SNAKE_CASE ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : int ) -> List[Any]: """simple docstring""" self.assertListEqual(self.tokenizer.convert_tokens_to_ids(["""<mask>""", """ar_AR"""] ) , [256_203, 3] ) def UpperCAmelCase__ ( self : str ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = NllbTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , __SCREAMING_SNAKE_CASE ) @require_torch def UpperCAmelCase__ ( self : str ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=len(self.expected_src_tokens ) , return_tensors="""pt""" , ) __SCREAMING_SNAKE_CASE = shift_tokens_right( batch["""labels"""] , self.tokenizer.pad_token_id , self.tokenizer.lang_code_to_id["""ron_Latn"""] ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertEqual((2, 15) , batch.input_ids.shape ) self.assertEqual((2, 15) , batch.attention_mask.shape ) __SCREAMING_SNAKE_CASE = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , __SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , batch.decoder_input_ids[0, 0] ) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [EN_CODE] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer(self.src_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=3 , return_tensors="""pt""" ) __SCREAMING_SNAKE_CASE = self.tokenizer( text_target=self.tgt_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=10 , return_tensors="""pt""" ) __SCREAMING_SNAKE_CASE = targets["""input_ids"""] __SCREAMING_SNAKE_CASE = shift_tokens_right( __SCREAMING_SNAKE_CASE , self.tokenizer.pad_token_id , decoder_start_token_id=self.tokenizer.lang_code_to_id[self.tokenizer.tgt_lang] , ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 10 ) @require_torch def UpperCAmelCase__ ( self : int ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer._build_translation_inputs( """A test""" , return_tensors="""pt""" , src_lang="""eng_Latn""" , tgt_lang="""fra_Latn""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE ) , { # A, test, EOS, en_XX """input_ids""": [[256_047, 70, 7_356, 2]], """attention_mask""": [[1, 1, 1, 1]], # ar_AR """forced_bos_token_id""": 256_057, } , ) @require_torch def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = self.tokenizer( """UN Chief says there is no military solution in Syria""" , src_lang="""eng_Latn""" , tgt_lang="""fra_Latn""" ) self.assertEqual( inputs.input_ids , [16_297, 134_408, 25_653, 6_370, 248, 254, 103_929, 94_995, 108, 49_486, 2, 256_047] ) __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = self.tokenizer( """UN Chief says there is no military solution in Syria""" , src_lang="""eng_Latn""" , tgt_lang="""fra_Latn""" ) self.assertEqual( inputs.input_ids , [256_047, 16_297, 134_408, 25_653, 6_370, 248, 254, 103_929, 94_995, 108, 49_486, 2] )
267
'''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] ) -> Optional[int]: """simple docstring""" torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = 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 : List[Any] ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.dummy_uncond_unet __SCREAMING_SNAKE_CASE = PNDMScheduler() __SCREAMING_SNAKE_CASE = PNDMPipeline(unet=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE ) pndm.to(__SCREAMING_SNAKE_CASE ) pndm.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pndm(generator=__SCREAMING_SNAKE_CASE , num_inference_steps=20 , output_type="""numpy""" ).images __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pndm(generator=__SCREAMING_SNAKE_CASE , num_inference_steps=20 , output_type="""numpy""" , return_dict=__SCREAMING_SNAKE_CASE )[0] __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] __SCREAMING_SNAKE_CASE = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __SCREAMING_SNAKE_CASE = 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 : Optional[int] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = """google/ddpm-cifar10-32""" __SCREAMING_SNAKE_CASE = UNetaDModel.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = PNDMScheduler() __SCREAMING_SNAKE_CASE = PNDMPipeline(unet=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE ) pndm.to(__SCREAMING_SNAKE_CASE ) pndm.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pndm(generator=__SCREAMING_SNAKE_CASE , output_type="""numpy""" ).images __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __SCREAMING_SNAKE_CASE = np.array([0.1564, 0.14645, 0.1406, 0.14715, 0.12425, 0.14045, 0.13115, 0.12175, 0.125] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
267
1
'''simple docstring''' import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv("TEST_SAGEMAKER" , "False" ) ) is not True , reason="Skipping test because should only be run when releasing minor transformers version" , ) @pytest.mark.usefixtures("sm_env" ) @parameterized_class( [ { "framework": "pytorch", "script": "run_glue.py", "model_name_or_path": "distilbert-base-cased", "instance_type": "ml.g4dn.xlarge", "results": {"train_runtime": 650, "eval_accuracy": 0.6, "eval_loss": 0.9}, }, { "framework": "tensorflow", "script": "run_tf.py", "model_name_or_path": "distilbert-base-cased", "instance_type": "ml.g4dn.xlarge", "results": {"train_runtime": 600, "eval_accuracy": 0.3, "eval_loss": 0.9}, }, ] ) class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : Optional[int] ) -> Optional[Any]: """simple docstring""" if self.framework == "pytorch": subprocess.run( f'cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py'.split() , encoding="""utf-8""" , check=__SCREAMING_SNAKE_CASE , ) assert hasattr(self , """env""" ) def UpperCAmelCase__ ( self : Optional[int] , __SCREAMING_SNAKE_CASE : List[Any]=1 ) -> Optional[Any]: """simple docstring""" return HuggingFace( entry_point=self.script , source_dir=self.env.test_path , role=self.env.role , image_uri=self.env.image_uri , base_job_name=f'{self.env.base_job_name}-single' , instance_count=__SCREAMING_SNAKE_CASE , instance_type=self.instance_type , debugger_hook_config=__SCREAMING_SNAKE_CASE , hyperparameters={**self.env.hyperparameters, """model_name_or_path""": self.model_name_or_path} , metric_definitions=self.env.metric_definitions , py_version="""py36""" , ) def UpperCAmelCase__ ( self : List[str] , __SCREAMING_SNAKE_CASE : List[Any] ) -> Dict: """simple docstring""" TrainingJobAnalytics(__SCREAMING_SNAKE_CASE ).export_csv(f'{self.env.test_path}/{job_name}_metrics.csv' ) def UpperCAmelCase__ ( self : int ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.create_estimator() # run training estimator.fit() # result dataframe __SCREAMING_SNAKE_CASE = TrainingJobAnalytics(estimator.latest_training_job.name ).dataframe() # extract kpis __SCREAMING_SNAKE_CASE = list(result_metrics_df[result_metrics_df.metric_name == """eval_accuracy"""]["""value"""] ) __SCREAMING_SNAKE_CASE = list(result_metrics_df[result_metrics_df.metric_name == """eval_loss"""]["""value"""] ) # get train time from SageMaker job, this includes starting, preprocessing, stopping __SCREAMING_SNAKE_CASE = ( Session().describe_training_job(estimator.latest_training_job.name ).get("""TrainingTimeInSeconds""" , 999_999 ) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results["""eval_accuracy"""] for t in eval_accuracy ) assert all(t <= self.results["""eval_loss"""] for t in eval_loss ) # dump tests result into json file to share in PR with open(f'{estimator.latest_training_job.name}.json' , """w""" ) as outfile: json.dump({"""train_time""": train_runtime, """eval_accuracy""": eval_accuracy, """eval_loss""": eval_loss} , __SCREAMING_SNAKE_CASE )
267
'''simple docstring''' import unittest from transformers import ( MODEL_FOR_OBJECT_DETECTION_MAPPING, AutoFeatureExtractor, AutoModelForObjectDetection, ObjectDetectionPipeline, is_vision_available, pipeline, ) from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_pytesseract, require_tf, require_timm, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class lowerCAmelCase__ : """simple docstring""" @staticmethod def UpperCAmelCase__ ( *__SCREAMING_SNAKE_CASE : Tuple , **__SCREAMING_SNAKE_CASE : Union[str, Any] ) -> List[str]: """simple docstring""" pass @is_pipeline_test @require_vision @require_timm @require_torch class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = MODEL_FOR_OBJECT_DETECTION_MAPPING def UpperCAmelCase__ ( self : List[Any] , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Tuple ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = ObjectDetectionPipeline(model=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) return object_detector, ["./tests/fixtures/tests_samples/COCO/000000039769.png"] def UpperCAmelCase__ ( self : Optional[int] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : List[Any] ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = object_detector("""./tests/fixtures/tests_samples/COCO/000000039769.png""" , threshold=0.0 ) self.assertGreater(len(__SCREAMING_SNAKE_CASE ) , 0 ) for detected_object in outputs: self.assertEqual( __SCREAMING_SNAKE_CASE , { """score""": ANY(__SCREAMING_SNAKE_CASE ), """label""": ANY(__SCREAMING_SNAKE_CASE ), """box""": {"""xmin""": ANY(__SCREAMING_SNAKE_CASE ), """ymin""": ANY(__SCREAMING_SNAKE_CASE ), """xmax""": ANY(__SCREAMING_SNAKE_CASE ), """ymax""": ANY(__SCREAMING_SNAKE_CASE )}, } , ) import datasets __SCREAMING_SNAKE_CASE = datasets.load_dataset("""hf-internal-testing/fixtures_image_utils""" , """image""" , split="""test""" ) __SCREAMING_SNAKE_CASE = [ Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ), """http://images.cocodataset.org/val2017/000000039769.jpg""", # RGBA dataset[0]["""file"""], # LA dataset[1]["""file"""], # L dataset[2]["""file"""], ] __SCREAMING_SNAKE_CASE = object_detector(__SCREAMING_SNAKE_CASE , threshold=0.0 ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , len(__SCREAMING_SNAKE_CASE ) ) for outputs in batch_outputs: self.assertGreater(len(__SCREAMING_SNAKE_CASE ) , 0 ) for detected_object in outputs: self.assertEqual( __SCREAMING_SNAKE_CASE , { """score""": ANY(__SCREAMING_SNAKE_CASE ), """label""": ANY(__SCREAMING_SNAKE_CASE ), """box""": {"""xmin""": ANY(__SCREAMING_SNAKE_CASE ), """ymin""": ANY(__SCREAMING_SNAKE_CASE ), """xmax""": ANY(__SCREAMING_SNAKE_CASE ), """ymax""": ANY(__SCREAMING_SNAKE_CASE )}, } , ) @require_tf @unittest.skip("""Object detection not implemented in TF""" ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> str: """simple docstring""" pass @require_torch def UpperCAmelCase__ ( self : str ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = """hf-internal-testing/tiny-detr-mobilenetsv3""" __SCREAMING_SNAKE_CASE = AutoModelForObjectDetection.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = AutoFeatureExtractor.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = ObjectDetectionPipeline(model=__SCREAMING_SNAKE_CASE , feature_extractor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" , threshold=0.0 ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ] , ) __SCREAMING_SNAKE_CASE = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] , threshold=0.0 , ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ], [ {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ], ] , ) @require_torch @slow def UpperCAmelCase__ ( self : Optional[int] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = """facebook/detr-resnet-50""" __SCREAMING_SNAKE_CASE = AutoModelForObjectDetection.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = AutoFeatureExtractor.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = ObjectDetectionPipeline(model=__SCREAMING_SNAKE_CASE , feature_extractor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) __SCREAMING_SNAKE_CASE = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], ] , ) @require_torch @slow def UpperCAmelCase__ ( self : List[Any] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = """facebook/detr-resnet-50""" __SCREAMING_SNAKE_CASE = pipeline("""object-detection""" , model=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) __SCREAMING_SNAKE_CASE = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], ] , ) @require_torch @slow def UpperCAmelCase__ ( self : Dict ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = 0.9985 __SCREAMING_SNAKE_CASE = """facebook/detr-resnet-50""" __SCREAMING_SNAKE_CASE = pipeline("""object-detection""" , model=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" , threshold=__SCREAMING_SNAKE_CASE ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) @require_torch @require_pytesseract @slow def UpperCAmelCase__ ( self : int ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = """Narsil/layoutlmv3-finetuned-funsd""" __SCREAMING_SNAKE_CASE = 0.9993 __SCREAMING_SNAKE_CASE = pipeline("""object-detection""" , model=__SCREAMING_SNAKE_CASE , threshold=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector( """https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9993, """label""": """I-ANSWER""", """box""": {"""xmin""": 294, """ymin""": 254, """xmax""": 343, """ymax""": 264}}, {"""score""": 0.9993, """label""": """I-ANSWER""", """box""": {"""xmin""": 294, """ymin""": 254, """xmax""": 343, """ymax""": 264}}, ] , )
267
1
'''simple docstring''' import argparse import os import torch from transformers import FlavaConfig, FlavaForPreTraining from transformers.models.flava.convert_dalle_to_flava_codebook import convert_dalle_checkpoint def a__ ( a__ ): """simple docstring""" return sum(param.float().sum() if """encoder.embeddings""" not in key else 0 for key, param in state_dict.items() ) def a__ ( a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = {} for key, value in state_dict.items(): if "text_encoder.embeddings" in key or "image_encoder.embeddings" in key: continue __SCREAMING_SNAKE_CASE = key.replace("""heads.cmd.mim_head.cls.predictions""" , """mmm_image_head""" ) __SCREAMING_SNAKE_CASE = key.replace("""heads.cmd.mlm_head.cls.predictions""" , """mmm_text_head""" ) __SCREAMING_SNAKE_CASE = key.replace("""heads.cmd.itm_head.cls""" , """itm_head""" ) __SCREAMING_SNAKE_CASE = key.replace("""heads.cmd.itm_head.pooler""" , """itm_head.pooler""" ) __SCREAMING_SNAKE_CASE = key.replace("""heads.cmd.clip_head.logit_scale""" , """flava.logit_scale""" ) __SCREAMING_SNAKE_CASE = key.replace("""heads.fairseq_mlm.cls.predictions""" , """mlm_head""" ) __SCREAMING_SNAKE_CASE = key.replace("""heads.imagenet.mim_head.cls.predictions""" , """mim_head""" ) __SCREAMING_SNAKE_CASE = key.replace("""mm_text_projection""" , """flava.text_to_mm_projection""" ) __SCREAMING_SNAKE_CASE = key.replace("""mm_image_projection""" , """flava.image_to_mm_projection""" ) __SCREAMING_SNAKE_CASE = key.replace("""image_encoder.module""" , """flava.image_model""" ) __SCREAMING_SNAKE_CASE = key.replace("""text_encoder.module""" , """flava.text_model""" ) __SCREAMING_SNAKE_CASE = key.replace("""mm_encoder.module.encoder.cls_token""" , """flava.multimodal_model.cls_token""" ) __SCREAMING_SNAKE_CASE = key.replace("""mm_encoder.module""" , """flava.multimodal_model""" ) __SCREAMING_SNAKE_CASE = key.replace("""text_projection""" , """flava.text_projection""" ) __SCREAMING_SNAKE_CASE = key.replace("""image_projection""" , """flava.image_projection""" ) __SCREAMING_SNAKE_CASE = value.float() for key, value in codebook_state_dict.items(): __SCREAMING_SNAKE_CASE = value return upgrade @torch.no_grad() def a__ ( a__ , a__ , a__ , a__=None ): """simple docstring""" if config_path is not None: __SCREAMING_SNAKE_CASE = FlavaConfig.from_pretrained(a__ ) else: __SCREAMING_SNAKE_CASE = FlavaConfig() __SCREAMING_SNAKE_CASE = FlavaForPreTraining(a__ ).eval() __SCREAMING_SNAKE_CASE = convert_dalle_checkpoint(a__ , a__ , save_checkpoint=a__ ) if os.path.exists(a__ ): __SCREAMING_SNAKE_CASE = torch.load(a__ , map_location="""cpu""" ) else: __SCREAMING_SNAKE_CASE = torch.hub.load_state_dict_from_url(a__ , map_location="""cpu""" ) __SCREAMING_SNAKE_CASE = upgrade_state_dict(a__ , a__ ) hf_model.load_state_dict(a__ ) __SCREAMING_SNAKE_CASE = hf_model.state_dict() __SCREAMING_SNAKE_CASE = count_parameters(a__ ) __SCREAMING_SNAKE_CASE = count_parameters(a__ ) + count_parameters(a__ ) assert torch.allclose(a__ , a__ , atol=1E-3 ) hf_model.save_pretrained(a__ ) if __name__ == "__main__": UpperCAmelCase : Optional[Any] = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to flava checkpoint') parser.add_argument('--codebook_path', default=None, type=str, help='Path to flava codebook checkpoint') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') UpperCAmelCase : Any = parser.parse_args() convert_flava_checkpoint(args.checkpoint_path, args.codebook_path, args.pytorch_dump_folder_path, args.config_path)
267
'''simple docstring''' import unittest from diffusers import FlaxAutoencoderKL from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax from .test_modeling_common_flax import FlaxModelTesterMixin if is_flax_available(): import jax @require_flax class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = FlaxAutoencoderKL @property def UpperCAmelCase__ ( self : Tuple ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = 4 __SCREAMING_SNAKE_CASE = 3 __SCREAMING_SNAKE_CASE = (32, 32) __SCREAMING_SNAKE_CASE = jax.random.PRNGKey(0 ) __SCREAMING_SNAKE_CASE = jax.random.uniform(__SCREAMING_SNAKE_CASE , ((batch_size, num_channels) + sizes) ) return {"sample": image, "prng_key": prng_key} def UpperCAmelCase__ ( self : Union[str, Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = { """block_out_channels""": [32, 64], """in_channels""": 3, """out_channels""": 3, """down_block_types""": ["""DownEncoderBlock2D""", """DownEncoderBlock2D"""], """up_block_types""": ["""UpDecoderBlock2D""", """UpDecoderBlock2D"""], """latent_channels""": 4, } __SCREAMING_SNAKE_CASE = self.dummy_input return init_dict, inputs_dict
267
1
'''simple docstring''' import math import tensorflow as tf from packaging import version def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = tf.convert_to_tensor(a__ ) __SCREAMING_SNAKE_CASE = 0.5 * (1.0 + tf.math.erf(x / tf.cast(tf.sqrt(2.0 ) , x.dtype ) )) return x * cdf def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = tf.convert_to_tensor(a__ ) __SCREAMING_SNAKE_CASE = tf.cast(math.pi , x.dtype ) __SCREAMING_SNAKE_CASE = tf.cast(0.044_715 , x.dtype ) __SCREAMING_SNAKE_CASE = 0.5 * (1.0 + tf.tanh(tf.sqrt(2.0 / pi ) * (x + coeff * tf.pow(a__ , 3 )) )) return x * cdf def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = tf.convert_to_tensor(a__ ) return x * tf.tanh(tf.math.softplus(a__ ) ) def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = tf.convert_to_tensor(a__ ) __SCREAMING_SNAKE_CASE = tf.cast(0.044_715 , x.dtype ) __SCREAMING_SNAKE_CASE = tf.cast(0.7_978_845_608 , x.dtype ) return 0.5 * x * (1.0 + tf.tanh(x * coeffa * (1.0 + coeffa * x * x) )) def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = tf.convert_to_tensor(a__ ) __SCREAMING_SNAKE_CASE = tf.cast(1.702 , x.dtype ) return x * tf.math.sigmoid(coeff * x ) def a__ ( a__ ): """simple docstring""" return tf.clip_by_value(_gelu(a__ ) , -10 , 10 ) def a__ ( a__ , a__=-1 ): """simple docstring""" __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = tf.split(a__ , 2 , axis=a__ ) return a * tf.math.sigmoid(a__ ) if version.parse(tf.version.VERSION) >= version.parse('2.4'): def a__ ( a__ ): """simple docstring""" return tf.keras.activations.gelu(a__ , approximate=a__ ) UpperCAmelCase : Union[str, Any] = tf.keras.activations.gelu UpperCAmelCase : str = approximate_gelu_wrap else: UpperCAmelCase : Optional[int] = _gelu UpperCAmelCase : Optional[int] = _gelu_new UpperCAmelCase : List[Any] = { 'gelu': gelu, 'gelu_10': gelu_aa, 'gelu_fast': gelu_fast, 'gelu_new': gelu_new, 'glu': glu, 'mish': mish, 'quick_gelu': quick_gelu, 'relu': tf.keras.activations.relu, 'sigmoid': tf.keras.activations.sigmoid, 'silu': tf.keras.activations.swish, 'swish': tf.keras.activations.swish, 'tanh': tf.keras.activations.tanh, } def a__ ( a__ ): """simple docstring""" if activation_string in ACTaFN: return ACTaFN[activation_string] else: raise KeyError(F'function {activation_string} not found in ACT2FN mapping {list(ACTaFN.keys() )}' )
267
'''simple docstring''' import itertools import os import random import tempfile import unittest import numpy as np from datasets import load_dataset from transformers import is_speech_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_speech_available(): from transformers import WhisperFeatureExtractor if is_torch_available(): import torch UpperCAmelCase : int = random.Random() def a__ ( a__ , a__=1.0 , a__=None , a__=None ): """simple docstring""" if rng is None: __SCREAMING_SNAKE_CASE = global_rng __SCREAMING_SNAKE_CASE = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch @require_torchaudio class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __init__( self : str , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : str=7 , __SCREAMING_SNAKE_CASE : List[str]=400 , __SCREAMING_SNAKE_CASE : Any=2_000 , __SCREAMING_SNAKE_CASE : List[str]=10 , __SCREAMING_SNAKE_CASE : Optional[int]=160 , __SCREAMING_SNAKE_CASE : List[str]=8 , __SCREAMING_SNAKE_CASE : Optional[Any]=0.0 , __SCREAMING_SNAKE_CASE : Dict=4_000 , __SCREAMING_SNAKE_CASE : Optional[int]=False , __SCREAMING_SNAKE_CASE : List[Any]=True , ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = min_seq_length __SCREAMING_SNAKE_CASE = max_seq_length __SCREAMING_SNAKE_CASE = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) __SCREAMING_SNAKE_CASE = padding_value __SCREAMING_SNAKE_CASE = sampling_rate __SCREAMING_SNAKE_CASE = return_attention_mask __SCREAMING_SNAKE_CASE = do_normalize __SCREAMING_SNAKE_CASE = feature_size __SCREAMING_SNAKE_CASE = chunk_length __SCREAMING_SNAKE_CASE = hop_length def UpperCAmelCase__ ( self : Dict ) -> Dict: """simple docstring""" return { "feature_size": self.feature_size, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def UpperCAmelCase__ ( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : Union[str, Any]=False , __SCREAMING_SNAKE_CASE : Optional[Any]=False ) -> Union[str, Any]: """simple docstring""" def _flatten(__SCREAMING_SNAKE_CASE : Dict ): return list(itertools.chain(*__SCREAMING_SNAKE_CASE ) ) if equal_length: __SCREAMING_SNAKE_CASE = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size __SCREAMING_SNAKE_CASE = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = WhisperFeatureExtractor if is_speech_available() else None def UpperCAmelCase__ ( self : str ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = WhisperFeatureExtractionTester(self ) def UpperCAmelCase__ ( self : str ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE = feat_extract_first.save_pretrained(__SCREAMING_SNAKE_CASE )[0] check_json_file_has_correct_format(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.feature_extraction_class.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = feat_extract_first.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_second.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_first.mel_filters __SCREAMING_SNAKE_CASE = feat_extract_second.mel_filters self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[str] ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE = os.path.join(__SCREAMING_SNAKE_CASE , """feat_extract.json""" ) feat_extract_first.to_json_file(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.feature_extraction_class.from_json_file(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = feat_extract_first.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_second.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_first.mel_filters __SCREAMING_SNAKE_CASE = feat_extract_second.mel_filters self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[Any] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in range(800 , 1_400 , 200 )] __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs] # Test feature size __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , padding="""max_length""" , return_tensors="""np""" ).input_features self.assertTrue(input_features.ndim == 3 ) self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames ) self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size ) # Test not batched input __SCREAMING_SNAKE_CASE = feature_extractor(speech_inputs[0] , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(np_speech_inputs[0] , return_tensors="""np""" ).input_features self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test batched __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test 2-D numpy arrays are batched. __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in (800, 800, 800)] __SCREAMING_SNAKE_CASE = np.asarray(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test truncation required __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in range(200 , (feature_extractor.n_samples + 500) , 200 )] __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs] __SCREAMING_SNAKE_CASE = [x[: feature_extractor.n_samples] for x in speech_inputs] __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs_truncated] __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) def UpperCAmelCase__ ( self : Dict ) -> Optional[int]: """simple docstring""" import torch __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __SCREAMING_SNAKE_CASE = np.random.rand(100 , 32 ).astype(np.floataa ) __SCREAMING_SNAKE_CASE = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: __SCREAMING_SNAKE_CASE = feature_extractor.pad([{"""input_features""": inputs}] , return_tensors="""np""" ) self.assertTrue(np_processed.input_features.dtype == np.floataa ) __SCREAMING_SNAKE_CASE = feature_extractor.pad([{"""input_features""": inputs}] , return_tensors="""pt""" ) self.assertTrue(pt_processed.input_features.dtype == torch.floataa ) def UpperCAmelCase__ ( self : str , __SCREAMING_SNAKE_CASE : Tuple ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = load_dataset("""hf-internal-testing/librispeech_asr_dummy""" , """clean""" , split="""validation""" ) # automatic decoding with librispeech __SCREAMING_SNAKE_CASE = ds.sort("""id""" ).select(range(__SCREAMING_SNAKE_CASE ) )[:num_samples]["""audio"""] return [x["array"] for x in speech_samples] def UpperCAmelCase__ ( self : Tuple ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = torch.tensor( [ 0.1193, -0.0946, -0.1098, -0.0196, 0.0225, -0.0690, -0.1736, 0.0951, 0.0971, -0.0817, -0.0702, 0.0162, 0.0260, 0.0017, -0.0192, -0.1678, 0.0709, -0.1867, -0.0655, -0.0274, -0.0234, -0.1884, -0.0516, -0.0554, -0.0274, -0.1425, -0.1423, 0.0837, 0.0377, -0.0854 ] ) # fmt: on __SCREAMING_SNAKE_CASE = self._load_datasamples(1 ) __SCREAMING_SNAKE_CASE = WhisperFeatureExtractor() __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).input_features self.assertEqual(input_features.shape , (1, 80, 3_000) ) self.assertTrue(torch.allclose(input_features[0, 0, :30] , __SCREAMING_SNAKE_CASE , atol=1E-4 ) ) def UpperCAmelCase__ ( self : List[Any] ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __SCREAMING_SNAKE_CASE = self._load_datasamples(1 )[0] __SCREAMING_SNAKE_CASE = ((audio - audio.min()) / (audio.max() - audio.min())) * 65_535 # Rescale to [0, 65535] to show issue __SCREAMING_SNAKE_CASE = feat_extract.zero_mean_unit_var_norm([audio] , attention_mask=__SCREAMING_SNAKE_CASE )[0] self.assertTrue(np.all(np.mean(__SCREAMING_SNAKE_CASE ) < 1E-3 ) ) self.assertTrue(np.all(np.abs(np.var(__SCREAMING_SNAKE_CASE ) - 1 ) < 1E-3 ) )
267
1
'''simple docstring''' from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase : Any = { 'configuration_trajectory_transformer': [ 'TRAJECTORY_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'TrajectoryTransformerConfig', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Dict = [ 'TRAJECTORY_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'TrajectoryTransformerModel', 'TrajectoryTransformerPreTrainedModel', 'load_tf_weights_in_trajectory_transformer', ] if TYPE_CHECKING: from .configuration_trajectory_transformer import ( TRAJECTORY_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TrajectoryTransformerConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_trajectory_transformer import ( TRAJECTORY_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TrajectoryTransformerModel, TrajectoryTransformerPreTrainedModel, load_tf_weights_in_trajectory_transformer, ) else: import sys UpperCAmelCase : Optional[int] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
267
'''simple docstring''' from __future__ import annotations def a__ ( a__ , a__ , a__ ): """simple docstring""" if len(a__ ) == 0: raise ValueError("""find_max() arg is an empty sequence""" ) if ( left >= len(a__ ) or left < -len(a__ ) or right >= len(a__ ) or right < -len(a__ ) ): raise IndexError("""list index out of range""" ) if left == right: return nums[left] __SCREAMING_SNAKE_CASE = (left + right) >> 1 # the middle __SCREAMING_SNAKE_CASE = find_max(a__ , a__ , a__ ) # find max in range[left, mid] __SCREAMING_SNAKE_CASE = find_max(a__ , mid + 1 , a__ ) # find max in range[mid + 1, right] return left_max if left_max >= right_max else right_max if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
267
1
'''simple docstring''' import flax.linen as nn import jax import jax.numpy as jnp class lowerCAmelCase__ ( nn.Module ): """simple docstring""" lowerCAmelCase__ = 42 lowerCAmelCase__ = jnp.floataa def UpperCAmelCase__ ( self : int ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = nn.Conv( self.out_channels , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) def __call__( self : Any , __SCREAMING_SNAKE_CASE : Union[str, Any] ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = hidden_states.shape __SCREAMING_SNAKE_CASE = jax.image.resize( __SCREAMING_SNAKE_CASE , shape=(batch, height * 2, width * 2, channels) , method="""nearest""" , ) __SCREAMING_SNAKE_CASE = self.conv(__SCREAMING_SNAKE_CASE ) return hidden_states class lowerCAmelCase__ ( nn.Module ): """simple docstring""" lowerCAmelCase__ = 42 lowerCAmelCase__ = jnp.floataa def UpperCAmelCase__ ( self : Any ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = nn.Conv( self.out_channels , kernel_size=(3, 3) , strides=(2, 2) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) def __call__( self : Any , __SCREAMING_SNAKE_CASE : Optional[int] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.conv(__SCREAMING_SNAKE_CASE ) return hidden_states class lowerCAmelCase__ ( nn.Module ): """simple docstring""" lowerCAmelCase__ = 42 lowerCAmelCase__ = None lowerCAmelCase__ = 0.0 lowerCAmelCase__ = None lowerCAmelCase__ = jnp.floataa def UpperCAmelCase__ ( self : Union[str, Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = self.in_channels if self.out_channels is None else self.out_channels __SCREAMING_SNAKE_CASE = nn.GroupNorm(num_groups=32 , epsilon=1E-5 ) __SCREAMING_SNAKE_CASE = nn.Conv( __SCREAMING_SNAKE_CASE , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) __SCREAMING_SNAKE_CASE = nn.Dense(__SCREAMING_SNAKE_CASE , dtype=self.dtype ) __SCREAMING_SNAKE_CASE = nn.GroupNorm(num_groups=32 , epsilon=1E-5 ) __SCREAMING_SNAKE_CASE = nn.Dropout(self.dropout_prob ) __SCREAMING_SNAKE_CASE = nn.Conv( __SCREAMING_SNAKE_CASE , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) __SCREAMING_SNAKE_CASE = self.in_channels != out_channels if self.use_nin_shortcut is None else self.use_nin_shortcut __SCREAMING_SNAKE_CASE = None if use_nin_shortcut: __SCREAMING_SNAKE_CASE = nn.Conv( __SCREAMING_SNAKE_CASE , kernel_size=(1, 1) , strides=(1, 1) , padding="""VALID""" , dtype=self.dtype , ) def __call__( self : List[str] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Union[str, Any]=True ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = hidden_states __SCREAMING_SNAKE_CASE = self.norma(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = nn.swish(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.conva(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.time_emb_proj(nn.swish(__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = jnp.expand_dims(jnp.expand_dims(__SCREAMING_SNAKE_CASE , 1 ) , 1 ) __SCREAMING_SNAKE_CASE = hidden_states + temb __SCREAMING_SNAKE_CASE = self.norma(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = nn.swish(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.dropout(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.conva(__SCREAMING_SNAKE_CASE ) if self.conv_shortcut is not None: __SCREAMING_SNAKE_CASE = self.conv_shortcut(__SCREAMING_SNAKE_CASE ) return hidden_states + residual
267
'''simple docstring''' def a__ ( a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) # Initialize Result __SCREAMING_SNAKE_CASE = [] # Traverse through all denomination for denomination in reversed(a__ ): # Find denominations while int(a__ ) >= int(a__ ): total_value -= int(a__ ) answer.append(a__ ) # Append the "answers" array return answer # Driver Code if __name__ == "__main__": UpperCAmelCase : Dict = [] UpperCAmelCase : List[str] = '0' if ( input('Do you want to enter your denominations ? (yY/n): ').strip().lower() == "y" ): UpperCAmelCase : List[str] = int(input('Enter the number of denominations you want to add: ').strip()) for i in range(0, n): denominations.append(int(input(f"""Denomination {i}: """).strip())) UpperCAmelCase : str = input('Enter the change you want to make in Indian Currency: ').strip() else: # All denominations of Indian Currency if user does not enter UpperCAmelCase : int = [1, 2, 5, 1_0, 2_0, 5_0, 1_0_0, 5_0_0, 2_0_0_0] UpperCAmelCase : Any = input('Enter the change you want to make: ').strip() if int(value) == 0 or int(value) < 0: print('The total value cannot be zero or negative.') else: print(f"""Following is minimal change for {value}: """) UpperCAmelCase : Any = find_minimum_change(denominations, value) # Print result for i in range(len(answer)): print(answer[i], end=' ')
267
1
'''simple docstring''' import requests from bsa import BeautifulSoup def a__ ( a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = BeautifulSoup(requests.get(a__ , params=a__ ).content , """html.parser""" ) __SCREAMING_SNAKE_CASE = soup.find("""div""" , attrs={"""class""": """gs_ri"""} ) __SCREAMING_SNAKE_CASE = div.find("""div""" , attrs={"""class""": """gs_fl"""} ).find_all("""a""" ) return anchors[2].get_text() if __name__ == "__main__": UpperCAmelCase : int = { 'title': ( 'Precisely geometry controlled microsupercapacitors for ultrahigh areal ' 'capacitance, volumetric capacitance, and energy density' ), 'journal': 'Chem. Mater.', 'volume': 3_0, 'pages': '3979-3990', 'year': 2_0_1_8, 'hl': 'en', } print(get_citation('https://scholar.google.com/scholar_lookup', params=params))
267
'''simple docstring''' # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse from ...utils.dataclasses import ( ComputeEnvironment, DistributedType, DynamoBackend, PrecisionType, SageMakerDistributedType, ) from ..menu import BulletMenu UpperCAmelCase : Any = [ 'EAGER', 'AOT_EAGER', 'INDUCTOR', 'NVFUSER', 'AOT_NVFUSER', 'AOT_CUDAGRAPHS', 'OFI', 'FX2TRT', 'ONNXRT', 'IPEX', ] def a__ ( a__ , a__=None , a__=None , a__=None ): """simple docstring""" __SCREAMING_SNAKE_CASE = True while ask_again: __SCREAMING_SNAKE_CASE = input(a__ ) try: if default is not None and len(a__ ) == 0: return default return convert_value(a__ ) if convert_value is not None else result except Exception: if error_message is not None: print(a__ ) def a__ ( a__ , a__=[] , a__=None , a__=0 ): """simple docstring""" __SCREAMING_SNAKE_CASE = BulletMenu(a__ , a__ ) __SCREAMING_SNAKE_CASE = menu.run(default_choice=a__ ) return convert_value(a__ ) if convert_value is not None else result def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return ComputeEnvironment(["""LOCAL_MACHINE""", """AMAZON_SAGEMAKER"""][value] ) def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return DistributedType(["""NO""", """MULTI_CPU""", """MULTI_XPU""", """MULTI_GPU""", """MULTI_NPU""", """TPU"""][value] ) def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return DynamoBackend(DYNAMO_BACKENDS[value] ).value def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return PrecisionType(["""no""", """fp16""", """bf16""", """fp8"""][value] ) def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return SageMakerDistributedType(["""NO""", """DATA_PARALLEL""", """MODEL_PARALLEL"""][value] ) def a__ ( a__ ): """simple docstring""" return {"yes": True, "no": False}[value.lower()] class lowerCAmelCase__ ( argparse.RawDescriptionHelpFormatter ): """simple docstring""" def UpperCAmelCase__ ( self : str , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : List[Any] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = super()._format_usage(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = usage.replace("""<command> [<args>] """ , """""" ) return usage
267
1
'''simple docstring''' import itertools import os import random import tempfile import unittest import numpy as np from datasets import load_dataset from transformers import is_speech_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_speech_available(): from transformers import WhisperFeatureExtractor if is_torch_available(): import torch UpperCAmelCase : int = random.Random() def a__ ( a__ , a__=1.0 , a__=None , a__=None ): """simple docstring""" if rng is None: __SCREAMING_SNAKE_CASE = global_rng __SCREAMING_SNAKE_CASE = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch @require_torchaudio class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __init__( self : str , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : str=7 , __SCREAMING_SNAKE_CASE : List[str]=400 , __SCREAMING_SNAKE_CASE : Any=2_000 , __SCREAMING_SNAKE_CASE : List[str]=10 , __SCREAMING_SNAKE_CASE : Optional[int]=160 , __SCREAMING_SNAKE_CASE : List[str]=8 , __SCREAMING_SNAKE_CASE : Optional[Any]=0.0 , __SCREAMING_SNAKE_CASE : Dict=4_000 , __SCREAMING_SNAKE_CASE : Optional[int]=False , __SCREAMING_SNAKE_CASE : List[Any]=True , ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = min_seq_length __SCREAMING_SNAKE_CASE = max_seq_length __SCREAMING_SNAKE_CASE = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) __SCREAMING_SNAKE_CASE = padding_value __SCREAMING_SNAKE_CASE = sampling_rate __SCREAMING_SNAKE_CASE = return_attention_mask __SCREAMING_SNAKE_CASE = do_normalize __SCREAMING_SNAKE_CASE = feature_size __SCREAMING_SNAKE_CASE = chunk_length __SCREAMING_SNAKE_CASE = hop_length def UpperCAmelCase__ ( self : Dict ) -> Dict: """simple docstring""" return { "feature_size": self.feature_size, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def UpperCAmelCase__ ( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : Union[str, Any]=False , __SCREAMING_SNAKE_CASE : Optional[Any]=False ) -> Union[str, Any]: """simple docstring""" def _flatten(__SCREAMING_SNAKE_CASE : Dict ): return list(itertools.chain(*__SCREAMING_SNAKE_CASE ) ) if equal_length: __SCREAMING_SNAKE_CASE = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size __SCREAMING_SNAKE_CASE = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = WhisperFeatureExtractor if is_speech_available() else None def UpperCAmelCase__ ( self : str ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = WhisperFeatureExtractionTester(self ) def UpperCAmelCase__ ( self : str ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE = feat_extract_first.save_pretrained(__SCREAMING_SNAKE_CASE )[0] check_json_file_has_correct_format(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.feature_extraction_class.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = feat_extract_first.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_second.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_first.mel_filters __SCREAMING_SNAKE_CASE = feat_extract_second.mel_filters self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[str] ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE = os.path.join(__SCREAMING_SNAKE_CASE , """feat_extract.json""" ) feat_extract_first.to_json_file(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.feature_extraction_class.from_json_file(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = feat_extract_first.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_second.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_first.mel_filters __SCREAMING_SNAKE_CASE = feat_extract_second.mel_filters self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[Any] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in range(800 , 1_400 , 200 )] __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs] # Test feature size __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , padding="""max_length""" , return_tensors="""np""" ).input_features self.assertTrue(input_features.ndim == 3 ) self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames ) self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size ) # Test not batched input __SCREAMING_SNAKE_CASE = feature_extractor(speech_inputs[0] , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(np_speech_inputs[0] , return_tensors="""np""" ).input_features self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test batched __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test 2-D numpy arrays are batched. __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in (800, 800, 800)] __SCREAMING_SNAKE_CASE = np.asarray(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test truncation required __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in range(200 , (feature_extractor.n_samples + 500) , 200 )] __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs] __SCREAMING_SNAKE_CASE = [x[: feature_extractor.n_samples] for x in speech_inputs] __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs_truncated] __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) def UpperCAmelCase__ ( self : Dict ) -> Optional[int]: """simple docstring""" import torch __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __SCREAMING_SNAKE_CASE = np.random.rand(100 , 32 ).astype(np.floataa ) __SCREAMING_SNAKE_CASE = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: __SCREAMING_SNAKE_CASE = feature_extractor.pad([{"""input_features""": inputs}] , return_tensors="""np""" ) self.assertTrue(np_processed.input_features.dtype == np.floataa ) __SCREAMING_SNAKE_CASE = feature_extractor.pad([{"""input_features""": inputs}] , return_tensors="""pt""" ) self.assertTrue(pt_processed.input_features.dtype == torch.floataa ) def UpperCAmelCase__ ( self : str , __SCREAMING_SNAKE_CASE : Tuple ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = load_dataset("""hf-internal-testing/librispeech_asr_dummy""" , """clean""" , split="""validation""" ) # automatic decoding with librispeech __SCREAMING_SNAKE_CASE = ds.sort("""id""" ).select(range(__SCREAMING_SNAKE_CASE ) )[:num_samples]["""audio"""] return [x["array"] for x in speech_samples] def UpperCAmelCase__ ( self : Tuple ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = torch.tensor( [ 0.1193, -0.0946, -0.1098, -0.0196, 0.0225, -0.0690, -0.1736, 0.0951, 0.0971, -0.0817, -0.0702, 0.0162, 0.0260, 0.0017, -0.0192, -0.1678, 0.0709, -0.1867, -0.0655, -0.0274, -0.0234, -0.1884, -0.0516, -0.0554, -0.0274, -0.1425, -0.1423, 0.0837, 0.0377, -0.0854 ] ) # fmt: on __SCREAMING_SNAKE_CASE = self._load_datasamples(1 ) __SCREAMING_SNAKE_CASE = WhisperFeatureExtractor() __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).input_features self.assertEqual(input_features.shape , (1, 80, 3_000) ) self.assertTrue(torch.allclose(input_features[0, 0, :30] , __SCREAMING_SNAKE_CASE , atol=1E-4 ) ) def UpperCAmelCase__ ( self : List[Any] ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __SCREAMING_SNAKE_CASE = self._load_datasamples(1 )[0] __SCREAMING_SNAKE_CASE = ((audio - audio.min()) / (audio.max() - audio.min())) * 65_535 # Rescale to [0, 65535] to show issue __SCREAMING_SNAKE_CASE = feat_extract.zero_mean_unit_var_norm([audio] , attention_mask=__SCREAMING_SNAKE_CASE )[0] self.assertTrue(np.all(np.mean(__SCREAMING_SNAKE_CASE ) < 1E-3 ) ) self.assertTrue(np.all(np.abs(np.var(__SCREAMING_SNAKE_CASE ) - 1 ) < 1E-3 ) )
267
'''simple docstring''' def a__ ( a__ , a__ ): """simple docstring""" _enforce_args(a__ , a__ ) if n == 0: return 0 __SCREAMING_SNAKE_CASE = float("""-inf""" ) for i in range(1 , n + 1 ): __SCREAMING_SNAKE_CASE = max( a__ , prices[i - 1] + naive_cut_rod_recursive(n - i , a__ ) ) return max_revue def a__ ( a__ , a__ ): """simple docstring""" _enforce_args(a__ , a__ ) __SCREAMING_SNAKE_CASE = [float("""-inf""" ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ ): """simple docstring""" if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: __SCREAMING_SNAKE_CASE = float("""-inf""" ) for i in range(1 , n + 1 ): __SCREAMING_SNAKE_CASE = max( a__ , prices[i - 1] + _top_down_cut_rod_recursive(n - i , a__ , a__ ) , ) __SCREAMING_SNAKE_CASE = max_revenue return max_rev[n] def a__ ( a__ , a__ ): """simple docstring""" _enforce_args(a__ , a__ ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. __SCREAMING_SNAKE_CASE = [float("""-inf""" ) for _ in range(n + 1 )] __SCREAMING_SNAKE_CASE = 0 for i in range(1 , n + 1 ): __SCREAMING_SNAKE_CASE = max_rev[i] for j in range(1 , i + 1 ): __SCREAMING_SNAKE_CASE = max(a__ , prices[j - 1] + max_rev[i - j] ) __SCREAMING_SNAKE_CASE = max_revenue_i return max_rev[n] def a__ ( a__ , a__ ): """simple docstring""" if n < 0: __SCREAMING_SNAKE_CASE = F'n must be greater than or equal to 0. Got n = {n}' raise ValueError(a__ ) if n > len(a__ ): __SCREAMING_SNAKE_CASE = ( """Each integral piece of rod must have a corresponding price. """ F'Got n = {n} but length of prices = {len(a__ )}' ) raise ValueError(a__ ) def a__ ( ): """simple docstring""" __SCREAMING_SNAKE_CASE = [6, 10, 12, 15, 20, 23] __SCREAMING_SNAKE_CASE = len(a__ ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. __SCREAMING_SNAKE_CASE = 36 __SCREAMING_SNAKE_CASE = top_down_cut_rod(a__ , a__ ) __SCREAMING_SNAKE_CASE = bottom_up_cut_rod(a__ , a__ ) __SCREAMING_SNAKE_CASE = naive_cut_rod_recursive(a__ , a__ ) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
267
1
'''simple docstring''' import inspect import math import tempfile import unittest import numpy as np from transformers import ViTMAEConfig 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 ViTMAEForPreTraining, ViTMAEModel from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class lowerCAmelCase__ : """simple docstring""" def __init__( self : Tuple , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Tuple=13 , __SCREAMING_SNAKE_CASE : Optional[Any]=30 , __SCREAMING_SNAKE_CASE : Dict=2 , __SCREAMING_SNAKE_CASE : Dict=3 , __SCREAMING_SNAKE_CASE : Dict=True , __SCREAMING_SNAKE_CASE : Tuple=True , __SCREAMING_SNAKE_CASE : int=32 , __SCREAMING_SNAKE_CASE : Any=5 , __SCREAMING_SNAKE_CASE : Any=4 , __SCREAMING_SNAKE_CASE : int=37 , __SCREAMING_SNAKE_CASE : List[Any]="gelu" , __SCREAMING_SNAKE_CASE : Any=0.1 , __SCREAMING_SNAKE_CASE : Dict=0.1 , __SCREAMING_SNAKE_CASE : Union[str, Any]=10 , __SCREAMING_SNAKE_CASE : Optional[Any]=0.02 , __SCREAMING_SNAKE_CASE : List[Any]=3 , __SCREAMING_SNAKE_CASE : Any=0.6 , __SCREAMING_SNAKE_CASE : List[str]=None , ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = patch_size __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = type_sequence_label_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = mask_ratio __SCREAMING_SNAKE_CASE = scope # in ViTMAE, the expected sequence length = (num_patches + 1) * (1 - config.mask_ratio), rounded above # (we add 1 for the [CLS] token) __SCREAMING_SNAKE_CASE = (image_size // patch_size) ** 2 __SCREAMING_SNAKE_CASE = int(math.ceil((1 - mask_ratio) * (num_patches + 1) ) ) def UpperCAmelCase__ ( self : List[str] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __SCREAMING_SNAKE_CASE = None if self.use_labels: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __SCREAMING_SNAKE_CASE = self.get_config() return config, pixel_values, labels def UpperCAmelCase__ ( self : List[Any] ) -> List[Any]: """simple docstring""" return ViTMAEConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=__SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , mask_ratio=self.mask_ratio , ) def UpperCAmelCase__ ( self : List[str] , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Optional[int] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = ViTMAEModel(config=__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase__ ( self : Dict , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Tuple ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = ViTMAEForPreTraining(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = (self.image_size // self.patch_size) ** 2 __SCREAMING_SNAKE_CASE = self.patch_size**2 * self.num_channels self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) ) # test greyscale images __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = ViTMAEForPreTraining(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() __SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.patch_size**2 self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) ) def UpperCAmelCase__ ( self : List[Any] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = config_and_inputs __SCREAMING_SNAKE_CASE = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class lowerCAmelCase__ ( a , a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = (ViTMAEModel, ViTMAEForPreTraining) if is_torch_available() else () lowerCAmelCase__ = {"feature-extraction": ViTMAEModel} if is_torch_available() else {} lowerCAmelCase__ = False lowerCAmelCase__ = False lowerCAmelCase__ = False lowerCAmelCase__ = False def UpperCAmelCase__ ( self : List[str] ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = ViTMAEModelTester(self ) __SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=__SCREAMING_SNAKE_CASE , has_text_modality=__SCREAMING_SNAKE_CASE , hidden_size=37 ) def UpperCAmelCase__ ( self : Dict ) -> int: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason="""ViTMAE does not use inputs_embeds""" ) def UpperCAmelCase__ ( self : Optional[Any] ) -> int: """simple docstring""" pass def UpperCAmelCase__ ( self : Tuple ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE = model_class(__SCREAMING_SNAKE_CASE ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) __SCREAMING_SNAKE_CASE = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__SCREAMING_SNAKE_CASE , nn.Linear ) ) def UpperCAmelCase__ ( self : Optional[int] ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE = model_class(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __SCREAMING_SNAKE_CASE = [*signature.parameters.keys()] __SCREAMING_SNAKE_CASE = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : int ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : int , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : List[Any] ) -> List[Any]: """simple docstring""" np.random.seed(2 ) __SCREAMING_SNAKE_CASE = int((pt_model.config.image_size // pt_model.config.patch_size) ** 2 ) __SCREAMING_SNAKE_CASE = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) __SCREAMING_SNAKE_CASE = torch.from_numpy(__SCREAMING_SNAKE_CASE ) # Add `noise` argument. # PT inputs will be prepared in `super().check_pt_tf_models()` with this added `noise` argument __SCREAMING_SNAKE_CASE = pt_noise super().check_pt_tf_models(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[str] ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE = model_class(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() # make random mask reproducible torch.manual_seed(2 ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = outputs[0].cpu().numpy() __SCREAMING_SNAKE_CASE = 0 with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = model_class.from_pretrained(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) # make random mask reproducible torch.manual_seed(2 ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) # Make sure we don't have nans __SCREAMING_SNAKE_CASE = after_outputs[0].cpu().numpy() __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(__SCREAMING_SNAKE_CASE , 1E-5 ) @unittest.skip( reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load to get deterministic results.""" ) def UpperCAmelCase__ ( self : Optional[int] ) -> List[str]: """simple docstring""" pass @unittest.skip( reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load to get deterministic results.""" ) def UpperCAmelCase__ ( self : Any ) -> Dict: """simple docstring""" pass @unittest.skip( reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load to get deterministic results.""" ) def UpperCAmelCase__ ( self : Dict ) -> int: """simple docstring""" pass @unittest.skip(reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load""" ) def UpperCAmelCase__ ( self : Optional[Any] ) -> int: """simple docstring""" pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def UpperCAmelCase__ ( self : Any ) -> Dict: """simple docstring""" pass @slow def UpperCAmelCase__ ( self : Optional[Any] ) -> Dict: """simple docstring""" for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE = ViTMAEModel.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertIsNotNone(__SCREAMING_SNAKE_CASE ) def a__ ( ): """simple docstring""" __SCREAMING_SNAKE_CASE = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" @cached_property def UpperCAmelCase__ ( self : str ) -> Dict: """simple docstring""" return ViTImageProcessor.from_pretrained("""facebook/vit-mae-base""" ) if is_vision_available() else None @slow def UpperCAmelCase__ ( self : Union[str, Any] ) -> str: """simple docstring""" np.random.seed(2 ) __SCREAMING_SNAKE_CASE = ViTMAEForPreTraining.from_pretrained("""facebook/vit-mae-base""" ).to(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.default_image_processor __SCREAMING_SNAKE_CASE = prepare_img() __SCREAMING_SNAKE_CASE = image_processor(images=__SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).to(__SCREAMING_SNAKE_CASE ) # prepare a noise vector that will be also used for testing the TF model # (this way we can ensure that the PT and TF models operate on the same inputs) __SCREAMING_SNAKE_CASE = ViTMAEConfig() __SCREAMING_SNAKE_CASE = int((vit_mae_config.image_size // vit_mae_config.patch_size) ** 2 ) __SCREAMING_SNAKE_CASE = np.random.uniform(size=(1, num_patches) ) # forward pass with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(**__SCREAMING_SNAKE_CASE , noise=torch.from_numpy(__SCREAMING_SNAKE_CASE ).to(device=__SCREAMING_SNAKE_CASE ) ) # verify the logits __SCREAMING_SNAKE_CASE = torch.Size((1, 196, 768) ) self.assertEqual(outputs.logits.shape , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = torch.tensor( [[-0.0548, -1.7023, -0.9325], [0.3721, -0.5670, -0.2233], [0.8235, -1.3878, -0.3524]] ) self.assertTrue(torch.allclose(outputs.logits[0, :3, :3] , expected_slice.to(__SCREAMING_SNAKE_CASE ) , atol=1E-4 ) )
267
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase : Union[str, Any] = {'configuration_sew': ['SEW_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SEWConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Union[str, Any] = [ 'SEW_PRETRAINED_MODEL_ARCHIVE_LIST', 'SEWForCTC', 'SEWForSequenceClassification', 'SEWModel', 'SEWPreTrainedModel', ] if TYPE_CHECKING: from .configuration_sew import SEW_PRETRAINED_CONFIG_ARCHIVE_MAP, SEWConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_sew import ( SEW_PRETRAINED_MODEL_ARCHIVE_LIST, SEWForCTC, SEWForSequenceClassification, SEWModel, SEWPreTrainedModel, ) else: import sys UpperCAmelCase : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
267
1
'''simple docstring''' import inspect import re from hashlib import shaaaa from typing import Dict, List from .arrow import arrow from .audiofolder import audiofolder from .csv import csv from .imagefolder import imagefolder from .json import json from .pandas import pandas from .parquet import parquet from .sql import sql # noqa F401 from .text import text def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = [] for line in lines: __SCREAMING_SNAKE_CASE = re.sub(R"""#.*""" , """""" , a__ ) # remove comments if line: filtered_lines.append(a__ ) __SCREAMING_SNAKE_CASE = """\n""".join(a__ ) # Make a hash from all this code __SCREAMING_SNAKE_CASE = full_str.encode("""utf-8""" ) return shaaaa(a__ ).hexdigest() # get importable module names and hash for caching UpperCAmelCase : Dict = { '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 UpperCAmelCase : str = { '.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}) UpperCAmelCase : List[Any] = {'imagefolder', 'audiofolder'} # Used to filter data files based on extensions given a module name UpperCAmelCase : 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')
267
'''simple docstring''' class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Any ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = name __SCREAMING_SNAKE_CASE = value __SCREAMING_SNAKE_CASE = weight def __repr__( self : str ) -> Union[str, Any]: """simple docstring""" return f'{self.__class__.__name__}({self.name}, {self.value}, {self.weight})' def UpperCAmelCase__ ( self : List[Any] ) -> List[Any]: """simple docstring""" return self.value def UpperCAmelCase__ ( self : Any ) -> str: """simple docstring""" return self.name def UpperCAmelCase__ ( self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" return self.weight def UpperCAmelCase__ ( self : int ) -> Tuple: """simple docstring""" return self.value / self.weight def a__ ( a__ , a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = [] for i in range(len(a__ ) ): menu.append(Things(name[i] , value[i] , weight[i] ) ) return menu def a__ ( a__ , a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = sorted(a__ , key=a__ , reverse=a__ ) __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = 0.0, 0.0 for i in range(len(a__ ) ): if (total_cost + items_copy[i].get_weight()) <= max_cost: result.append(items_copy[i] ) total_cost += items_copy[i].get_weight() total_value += items_copy[i].get_value() return (result, total_value) def a__ ( ): """simple docstring""" if __name__ == "__main__": import doctest doctest.testmod()
267
1
'''simple docstring''' import unittest from diffusers import FlaxAutoencoderKL from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax from .test_modeling_common_flax import FlaxModelTesterMixin if is_flax_available(): import jax @require_flax class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = FlaxAutoencoderKL @property def UpperCAmelCase__ ( self : Tuple ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = 4 __SCREAMING_SNAKE_CASE = 3 __SCREAMING_SNAKE_CASE = (32, 32) __SCREAMING_SNAKE_CASE = jax.random.PRNGKey(0 ) __SCREAMING_SNAKE_CASE = jax.random.uniform(__SCREAMING_SNAKE_CASE , ((batch_size, num_channels) + sizes) ) return {"sample": image, "prng_key": prng_key} def UpperCAmelCase__ ( self : Union[str, Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = { """block_out_channels""": [32, 64], """in_channels""": 3, """out_channels""": 3, """down_block_types""": ["""DownEncoderBlock2D""", """DownEncoderBlock2D"""], """up_block_types""": ["""UpDecoderBlock2D""", """UpDecoderBlock2D"""], """latent_channels""": 4, } __SCREAMING_SNAKE_CASE = self.dummy_input return init_dict, inputs_dict
267
'''simple docstring''' import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import CLIPImageProcessor, CLIPProcessor @require_vision class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : Union[str, Any] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() # fmt: off __SCREAMING_SNAKE_CASE = ["""l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """lo""", """l</w>""", """w</w>""", """r</w>""", """t</w>""", """low</w>""", """er</w>""", """lowest</w>""", """newer</w>""", """wider""", """<unk>""", """<|startoftext|>""", """<|endoftext|>"""] # fmt: on __SCREAMING_SNAKE_CASE = dict(zip(__SCREAMING_SNAKE_CASE , range(len(__SCREAMING_SNAKE_CASE ) ) ) ) __SCREAMING_SNAKE_CASE = ["""#version: 0.2""", """l o""", """lo w</w>""", """e r</w>""", """"""] __SCREAMING_SNAKE_CASE = {"""unk_token""": """<unk>"""} __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) __SCREAMING_SNAKE_CASE = 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(__SCREAMING_SNAKE_CASE ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = { """do_resize""": True, """size""": 20, """do_center_crop""": True, """crop_size""": 18, """do_normalize""": True, """image_mean""": [0.48145466, 0.4578275, 0.40821073], """image_std""": [0.26862954, 0.26130258, 0.27577711], } __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , __SCREAMING_SNAKE_CASE ) with open(self.image_processor_file , """w""" , encoding="""utf-8""" ) as fp: json.dump(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] , **__SCREAMING_SNAKE_CASE : Optional[int] ) -> str: """simple docstring""" return CLIPTokenizer.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Tuple , **__SCREAMING_SNAKE_CASE : Any ) -> int: """simple docstring""" return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[Any] , **__SCREAMING_SNAKE_CASE : Optional[int] ) -> List[str]: """simple docstring""" return CLIPImageProcessor.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Tuple ) -> str: """simple docstring""" shutil.rmtree(self.tmpdirname ) def UpperCAmelCase__ ( self : Optional[Any] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __SCREAMING_SNAKE_CASE = [Image.fromarray(np.moveaxis(__SCREAMING_SNAKE_CASE , 0 , -1 ) ) for x in image_inputs] return image_inputs def UpperCAmelCase__ ( self : Optional[int] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = self.get_rust_tokenizer() __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) processor_slow.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = CLIPProcessor.from_pretrained(self.tmpdirname , use_fast=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) processor_fast.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = CLIPProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , __SCREAMING_SNAKE_CASE ) self.assertIsInstance(processor_fast.tokenizer , __SCREAMING_SNAKE_CASE ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , __SCREAMING_SNAKE_CASE ) self.assertIsInstance(processor_fast.image_processor , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) __SCREAMING_SNAKE_CASE = self.get_image_processor(do_normalize=__SCREAMING_SNAKE_CASE , padding_value=1.0 ) __SCREAMING_SNAKE_CASE = CLIPProcessor.from_pretrained( self.tmpdirname , bos_token="""(BOS)""" , eos_token="""(EOS)""" , do_normalize=__SCREAMING_SNAKE_CASE , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , __SCREAMING_SNAKE_CASE ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[str] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = image_processor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ) __SCREAMING_SNAKE_CASE = processor(images=__SCREAMING_SNAKE_CASE , return_tensors="""np""" ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1E-2 ) def UpperCAmelCase__ ( self : List[Any] ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """lower newer""" __SCREAMING_SNAKE_CASE = processor(text=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer(__SCREAMING_SNAKE_CASE ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def UpperCAmelCase__ ( self : Dict ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """lower newer""" __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = processor(text=__SCREAMING_SNAKE_CASE , images=__SCREAMING_SNAKE_CASE ) self.assertListEqual(list(inputs.keys() ) , ["""input_ids""", """attention_mask""", """pixel_values"""] ) # test if it raises when no input is passed with pytest.raises(__SCREAMING_SNAKE_CASE ): processor() def UpperCAmelCase__ ( self : List[str] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __SCREAMING_SNAKE_CASE = processor.batch_decode(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer.batch_decode(__SCREAMING_SNAKE_CASE ) self.assertListEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : int ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """lower newer""" __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = processor(text=__SCREAMING_SNAKE_CASE , images=__SCREAMING_SNAKE_CASE ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
267
1
'''simple docstring''' import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, BatchEncoding, MBartTokenizer, MBartTokenizerFast, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...test_tokenization_common import TokenizerTesterMixin UpperCAmelCase : Any = get_tests_dir('fixtures/test_sentencepiece.model') if is_torch_available(): from transformers.models.mbart.modeling_mbart import shift_tokens_right UpperCAmelCase : Optional[Any] = 2_5_0_0_0_4 UpperCAmelCase : Union[str, Any] = 2_5_0_0_2_0 @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = MBartTokenizer lowerCAmelCase__ = MBartTokenizerFast lowerCAmelCase__ = True lowerCAmelCase__ = True def UpperCAmelCase__ ( self : str ) -> Any: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing __SCREAMING_SNAKE_CASE = MBartTokenizer(__SCREAMING_SNAKE_CASE , keep_accents=__SCREAMING_SNAKE_CASE ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCAmelCase__ ( self : int ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = MBartTokenizer(__SCREAMING_SNAKE_CASE , keep_accents=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(__SCREAMING_SNAKE_CASE , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) __SCREAMING_SNAKE_CASE = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ 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""", """é""", """.""", ] , ) __SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ 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] # ^ unk: 2 + 1 = 3 unk: 2 + 1 = 3 ^ ] , ) __SCREAMING_SNAKE_CASE = tokenizer.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ 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>""", """.""", ] , ) def UpperCAmelCase__ ( self : int ) -> Optional[Any]: """simple docstring""" if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return __SCREAMING_SNAKE_CASE = (self.rust_tokenizer_class, """hf-internal-testing/tiny-random-mbart""", {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) __SCREAMING_SNAKE_CASE = tuple(f for f in tokenizer_r_files if """tokenizer.json""" not in f ) self.assertSequenceEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Checks everything loads correctly in the same way __SCREAMING_SNAKE_CASE = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(__SCREAMING_SNAKE_CASE ) # Save tokenizer rust, legacy_format=True __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE , legacy_format=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it save with the same files self.assertSequenceEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Checks everything loads correctly in the same way __SCREAMING_SNAKE_CASE = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) # Save tokenizer rust, legacy_format=False __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE , legacy_format=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it saved the tokenizer.json file self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way __SCREAMING_SNAKE_CASE = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) @require_torch @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = "facebook/mbart-large-en-ro" lowerCAmelCase__ = [ " UN Chief Says There Is No Military Solution in Syria", " Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for Syria is that \"there is no military solution\" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.", ] lowerCAmelCase__ = [ "Şeful ONU declară că nu există o soluţie militară în Siria", "Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei" " pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi că noi arme nu vor" " face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.", ] lowerCAmelCase__ = [8274, 127873, 25916, 7, 8622, 2071, 438, 67485, 53, 187895, 23, 51712, 2, EN_CODE] @classmethod def UpperCAmelCase__ ( cls : List[str] ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = MBartTokenizer.from_pretrained( cls.checkpoint_name , src_lang="""en_XX""" , tgt_lang="""ro_RO""" ) __SCREAMING_SNAKE_CASE = 1 return cls def UpperCAmelCase__ ( self : str ) -> List[Any]: """simple docstring""" self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ar_AR"""] , 250_001 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""en_EN"""] , 250_004 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ro_RO"""] , 250_020 ) def UpperCAmelCase__ ( self : Dict ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Tuple: """simple docstring""" self.assertIn(__SCREAMING_SNAKE_CASE , self.tokenizer.all_special_ids ) __SCREAMING_SNAKE_CASE = [RO_CODE, 884, 9_019, 96, 9, 916, 86_792, 36, 18_743, 15_596, 5, 2] __SCREAMING_SNAKE_CASE = self.tokenizer.decode(__SCREAMING_SNAKE_CASE , skip_special_tokens=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertNotIn(self.tokenizer.eos_token , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = ["""this is gunna be a long sentence """ * 20] assert isinstance(src_text[0] , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = 10 __SCREAMING_SNAKE_CASE = self.tokenizer(__SCREAMING_SNAKE_CASE , max_length=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE ).input_ids[0] self.assertEqual(ids[-2] , 2 ) self.assertEqual(ids[-1] , __SCREAMING_SNAKE_CASE ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" self.assertListEqual(self.tokenizer.convert_tokens_to_ids(["""<mask>""", """ar_AR"""] ) , [250_026, 250_001] ) def UpperCAmelCase__ ( self : Optional[Any] ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = MBartTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , __SCREAMING_SNAKE_CASE ) @require_torch def UpperCAmelCase__ ( self : List[Any] ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=__SCREAMING_SNAKE_CASE , return_tensors="""pt""" ) __SCREAMING_SNAKE_CASE = shift_tokens_right(batch["""labels"""] , self.tokenizer.pad_token_id ) # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 assert batch.input_ids[1][-2:].tolist() == [2, EN_CODE] assert batch.decoder_input_ids[1][0].tolist() == RO_CODE assert batch.decoder_input_ids[1][-1] == 2 assert batch.labels[1][-2:].tolist() == [2, RO_CODE] @require_torch def UpperCAmelCase__ ( self : Optional[Any] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=len(self.expected_src_tokens ) , return_tensors="""pt""" , ) __SCREAMING_SNAKE_CASE = shift_tokens_right(batch["""labels"""] , self.tokenizer.pad_token_id ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertEqual((2, 14) , batch.input_ids.shape ) self.assertEqual((2, 14) , batch.attention_mask.shape ) __SCREAMING_SNAKE_CASE = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , __SCREAMING_SNAKE_CASE ) self.assertEqual(2 , batch.decoder_input_ids[0, -1] ) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id, EN_CODE] ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer(self.src_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=3 , return_tensors="""pt""" ) __SCREAMING_SNAKE_CASE = self.tokenizer( text_target=self.tgt_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=10 , return_tensors="""pt""" ) __SCREAMING_SNAKE_CASE = targets["""input_ids"""] __SCREAMING_SNAKE_CASE = shift_tokens_right(__SCREAMING_SNAKE_CASE , self.tokenizer.pad_token_id ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 10 ) @require_torch def UpperCAmelCase__ ( self : Tuple ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer._build_translation_inputs( """A test""" , return_tensors="""pt""" , src_lang="""en_XX""" , tgt_lang="""ar_AR""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE ) , { # A, test, EOS, en_XX """input_ids""": [[62, 3_034, 2, 250_004]], """attention_mask""": [[1, 1, 1, 1]], # ar_AR """forced_bos_token_id""": 250_001, } , )
267
'''simple docstring''' import numpy as np def a__ ( a__ , a__ , a__ = 1E-1_2 , a__ = 1_00 , ): """simple docstring""" assert np.shape(a__ )[0] == np.shape(a__ )[1] # Ensure proper dimensionality. assert np.shape(a__ )[0] == np.shape(a__ )[0] # Ensure inputs are either both complex or both real assert np.iscomplexobj(a__ ) == np.iscomplexobj(a__ ) __SCREAMING_SNAKE_CASE = np.iscomplexobj(a__ ) if is_complex: # Ensure complex input_matrix is Hermitian assert np.array_equal(a__ , input_matrix.conj().T ) # Set convergence to False. Will define convergence when we exceed max_iterations # or when we have small changes from one iteration to next. __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 1E1_2 while not convergence: # Multiple matrix by the vector. __SCREAMING_SNAKE_CASE = np.dot(a__ , a__ ) # Normalize the resulting output vector. __SCREAMING_SNAKE_CASE = w / np.linalg.norm(a__ ) # Find rayleigh quotient # (faster than usual b/c we know vector is normalized already) __SCREAMING_SNAKE_CASE = vector.conj().T if is_complex else vector.T __SCREAMING_SNAKE_CASE = np.dot(a__ , np.dot(a__ , a__ ) ) # Check convergence. __SCREAMING_SNAKE_CASE = np.abs(lambda_ - lambda_previous ) / lambda_ iterations += 1 if error <= error_tol or iterations >= max_iterations: __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = lambda_ if is_complex: __SCREAMING_SNAKE_CASE = np.real(lambda_ ) return lambda_, vector def a__ ( ): """simple docstring""" __SCREAMING_SNAKE_CASE = np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]] ) __SCREAMING_SNAKE_CASE = np.array([41, 4, 20] ) __SCREAMING_SNAKE_CASE = real_input_matrix.astype(np.complexaaa ) __SCREAMING_SNAKE_CASE = np.triu(1J * complex_input_matrix , 1 ) complex_input_matrix += imag_matrix complex_input_matrix += -1 * imag_matrix.T __SCREAMING_SNAKE_CASE = np.array([41, 4, 20] ).astype(np.complexaaa ) for problem_type in ["real", "complex"]: if problem_type == "real": __SCREAMING_SNAKE_CASE = real_input_matrix __SCREAMING_SNAKE_CASE = real_vector elif problem_type == "complex": __SCREAMING_SNAKE_CASE = complex_input_matrix __SCREAMING_SNAKE_CASE = complex_vector # Our implementation. __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = power_iteration(a__ , a__ ) # Numpy implementation. # Get eigenvalues and eigenvectors using built-in numpy # eigh (eigh used for symmetric or hermetian matrices). __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = np.linalg.eigh(a__ ) # Last eigenvalue is the maximum one. __SCREAMING_SNAKE_CASE = eigen_values[-1] # Last column in this matrix is eigenvector corresponding to largest eigenvalue. __SCREAMING_SNAKE_CASE = eigen_vectors[:, -1] # Check our implementation and numpy gives close answers. assert np.abs(eigen_value - eigen_value_max ) <= 1E-6 # Take absolute values element wise of each eigenvector. # as they are only unique to a minus sign. assert np.linalg.norm(np.abs(a__ ) - np.abs(a__ ) ) <= 1E-6 if __name__ == "__main__": import doctest doctest.testmod() test_power_iteration()
267
1
'''simple docstring''' import numpy as np from cva import COLOR_BGR2GRAY, CV_8UC3, cvtColor, filteraD, imread, imshow, waitKey def a__ ( a__ , a__ , a__ , a__ , a__ , a__ ): """simple docstring""" if (ksize % 2) == 0: __SCREAMING_SNAKE_CASE = ksize + 1 __SCREAMING_SNAKE_CASE = np.zeros((ksize, ksize) , dtype=np.floataa ) # each value for y in range(a__ ): for x in range(a__ ): # distance from center __SCREAMING_SNAKE_CASE = x - ksize // 2 __SCREAMING_SNAKE_CASE = y - ksize // 2 # degree to radiant __SCREAMING_SNAKE_CASE = theta / 1_80 * np.pi __SCREAMING_SNAKE_CASE = np.cos(_theta ) __SCREAMING_SNAKE_CASE = np.sin(_theta ) # get kernel x __SCREAMING_SNAKE_CASE = cos_theta * px + sin_theta * py # get kernel y __SCREAMING_SNAKE_CASE = -sin_theta * px + cos_theta * py # fill kernel __SCREAMING_SNAKE_CASE = 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 UpperCAmelCase : Optional[Any] = imread('../image_data/lena.jpg') # turn image in gray scale value UpperCAmelCase : List[Any] = cvtColor(img, COLOR_BGR2GRAY) # Apply multiple Kernel to detect edges UpperCAmelCase : int = np.zeros(gray.shape[:2]) for theta in [0, 3_0, 6_0, 9_0, 1_2_0, 1_5_0]: UpperCAmelCase : str = gabor_filter_kernel(1_0, 8, theta, 1_0, 0, 0) out += filteraD(gray, CV_8UC3, kernel_aa) UpperCAmelCase : str = out / out.max() * 2_5_5 UpperCAmelCase : List[str] = out.astype(np.uinta) imshow('Original', gray) imshow('Gabor filter with 20x20 mask and 6 directions', out) waitKey(0)
267
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowerCAmelCase__ ( a , a , a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = StableDiffusionInpaintPipeline lowerCAmelCase__ = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS lowerCAmelCase__ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS lowerCAmelCase__ = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess lowerCAmelCase__ = frozenset([] ) def UpperCAmelCase__ ( self : str ) -> List[Any]: """simple docstring""" torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=9 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=__SCREAMING_SNAKE_CASE , ) __SCREAMING_SNAKE_CASE = PNDMScheduler(skip_prk_steps=__SCREAMING_SNAKE_CASE ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act="""gelu""" , projection_dim=512 , ) __SCREAMING_SNAKE_CASE = CLIPTextModel(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) __SCREAMING_SNAKE_CASE = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def UpperCAmelCase__ ( self : Any , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : List[Any]=0 ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = floats_tensor((1, 3, 32, 32) , rng=random.Random(__SCREAMING_SNAKE_CASE ) ).to(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1 )[0] __SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(__SCREAMING_SNAKE_CASE ) ).convert("""RGB""" ).resize((64, 64) ) __SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(image + 4 ) ).convert("""RGB""" ).resize((64, 64) ) if str(__SCREAMING_SNAKE_CASE ).startswith("""mps""" ): __SCREAMING_SNAKE_CASE = torch.manual_seed(__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = torch.Generator(device=__SCREAMING_SNAKE_CASE ).manual_seed(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = { """prompt""": """A painting of a squirrel eating a burger""", """image""": init_image, """mask_image""": mask_image, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def UpperCAmelCase__ ( self : Union[str, Any] ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = """cpu""" # ensure determinism for the device-dependent torch.Generator __SCREAMING_SNAKE_CASE = self.get_dummy_components() __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = sd_pipe.to(__SCREAMING_SNAKE_CASE ) sd_pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.get_dummy_inputs(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = sd_pipe(**__SCREAMING_SNAKE_CASE ).images __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __SCREAMING_SNAKE_CASE = np.array([0.4727, 0.5735, 0.3941, 0.5446, 0.5926, 0.4394, 0.5062, 0.4654, 0.4476] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def UpperCAmelCase__ ( self : Tuple ) -> str: """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : List[Any] ) -> str: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase__ ( self : List[str] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) __SCREAMING_SNAKE_CASE = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench.npy""" ) __SCREAMING_SNAKE_CASE = """stabilityai/stable-diffusion-2-inpainting""" __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline.from_pretrained(__SCREAMING_SNAKE_CASE , safety_checker=__SCREAMING_SNAKE_CASE ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) pipe.enable_attention_slicing() __SCREAMING_SNAKE_CASE = """Face of a yellow cat, high resolution, sitting on a park bench""" __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , mask_image=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , output_type="""np""" , ) __SCREAMING_SNAKE_CASE = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 9E-3 def UpperCAmelCase__ ( self : List[Any] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) __SCREAMING_SNAKE_CASE = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench_fp16.npy""" ) __SCREAMING_SNAKE_CASE = """stabilityai/stable-diffusion-2-inpainting""" __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline.from_pretrained( __SCREAMING_SNAKE_CASE , torch_dtype=torch.floataa , safety_checker=__SCREAMING_SNAKE_CASE , ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) pipe.enable_attention_slicing() __SCREAMING_SNAKE_CASE = """Face of a yellow cat, high resolution, sitting on a park bench""" __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , mask_image=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , output_type="""np""" , ) __SCREAMING_SNAKE_CASE = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 5E-1 def UpperCAmelCase__ ( self : Tuple ) -> Any: """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) __SCREAMING_SNAKE_CASE = """stabilityai/stable-diffusion-2-inpainting""" __SCREAMING_SNAKE_CASE = PNDMScheduler.from_pretrained(__SCREAMING_SNAKE_CASE , subfolder="""scheduler""" ) __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline.from_pretrained( __SCREAMING_SNAKE_CASE , safety_checker=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE , torch_dtype=torch.floataa , ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() __SCREAMING_SNAKE_CASE = """Face of a yellow cat, high resolution, sitting on a park bench""" __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , mask_image=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , num_inference_steps=2 , output_type="""np""" , ) __SCREAMING_SNAKE_CASE = torch.cuda.max_memory_allocated() # make sure that less than 2.65 GB is allocated assert mem_bytes < 2.65 * 10**9
267
1
'''simple docstring''' import argparse import logging import os from pathlib import Path from typing import Any, Dict import pytorch_lightning as pl from pytorch_lightning.utilities import rank_zero_info from transformers import ( AdamW, AutoConfig, AutoModel, AutoModelForPreTraining, AutoModelForQuestionAnswering, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoModelForTokenClassification, AutoModelWithLMHead, AutoTokenizer, PretrainedConfig, PreTrainedTokenizer, ) from transformers.optimization import ( Adafactor, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) from transformers.utils.versions import require_version UpperCAmelCase : Any = logging.getLogger(__name__) require_version('pytorch_lightning>=1.0.4') UpperCAmelCase : Optional[Any] = { 'base': AutoModel, 'sequence-classification': AutoModelForSequenceClassification, 'question-answering': AutoModelForQuestionAnswering, 'pretraining': AutoModelForPreTraining, 'token-classification': AutoModelForTokenClassification, 'language-modeling': AutoModelWithLMHead, 'summarization': AutoModelForSeqaSeqLM, 'translation': AutoModelForSeqaSeqLM, } # update this and the import above to support new schedulers from transformers.optimization UpperCAmelCase : Optional[int] = { 'linear': get_linear_schedule_with_warmup, 'cosine': get_cosine_schedule_with_warmup, 'cosine_w_restarts': get_cosine_with_hard_restarts_schedule_with_warmup, 'polynomial': get_polynomial_decay_schedule_with_warmup, # '': get_constant_schedule, # not supported for now # '': get_constant_schedule_with_warmup, # not supported for now } UpperCAmelCase : Optional[int] = sorted(arg_to_scheduler.keys()) UpperCAmelCase : List[str] = '{' + ', '.join(arg_to_scheduler_choices) + '}' class lowerCAmelCase__ ( pl.LightningModule ): """simple docstring""" def __init__( self : Optional[Any] , __SCREAMING_SNAKE_CASE : argparse.Namespace , __SCREAMING_SNAKE_CASE : Tuple=None , __SCREAMING_SNAKE_CASE : int="base" , __SCREAMING_SNAKE_CASE : Optional[int]=None , __SCREAMING_SNAKE_CASE : List[Any]=None , __SCREAMING_SNAKE_CASE : Union[str, Any]=None , **__SCREAMING_SNAKE_CASE : Dict , ) -> List[str]: """simple docstring""" super().__init__() # TODO: move to self.save_hyperparameters() # self.save_hyperparameters() # can also expand arguments into trainer signature for easier reading self.save_hyperparameters(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = Path(self.hparams.output_dir ) __SCREAMING_SNAKE_CASE = self.hparams.cache_dir if self.hparams.cache_dir else None if config is None: __SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained( self.hparams.config_name if self.hparams.config_name else self.hparams.model_name_or_path , **({"""num_labels""": num_labels} if num_labels is not None else {}) , cache_dir=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) else: __SCREAMING_SNAKE_CASE = config __SCREAMING_SNAKE_CASE = ("""encoder_layerdrop""", """decoder_layerdrop""", """dropout""", """attention_dropout""") for p in extra_model_params: if getattr(self.hparams , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): assert hasattr(self.config , __SCREAMING_SNAKE_CASE ), f'model config doesn\'t have a `{p}` attribute' setattr(self.config , __SCREAMING_SNAKE_CASE , getattr(self.hparams , __SCREAMING_SNAKE_CASE ) ) if tokenizer is None: __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained( self.hparams.tokenizer_name if self.hparams.tokenizer_name else self.hparams.model_name_or_path , cache_dir=__SCREAMING_SNAKE_CASE , ) else: __SCREAMING_SNAKE_CASE = tokenizer __SCREAMING_SNAKE_CASE = MODEL_MODES[mode] if model is None: __SCREAMING_SNAKE_CASE = self.model_type.from_pretrained( self.hparams.model_name_or_path , from_tf=bool(""".ckpt""" in self.hparams.model_name_or_path ) , config=self.config , cache_dir=__SCREAMING_SNAKE_CASE , ) else: __SCREAMING_SNAKE_CASE = model def UpperCAmelCase__ ( self : List[Any] , *__SCREAMING_SNAKE_CASE : List[Any] , **__SCREAMING_SNAKE_CASE : str ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.model_type.from_pretrained(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[Any] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = arg_to_scheduler[self.hparams.lr_scheduler] __SCREAMING_SNAKE_CASE = get_schedule_func( self.opt , num_warmup_steps=self.hparams.warmup_steps , num_training_steps=self.total_steps() ) __SCREAMING_SNAKE_CASE = {"""scheduler""": scheduler, """interval""": """step""", """frequency""": 1} return scheduler def UpperCAmelCase__ ( self : Union[str, Any] ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = self.model __SCREAMING_SNAKE_CASE = ["""bias""", """LayerNorm.weight"""] __SCREAMING_SNAKE_CASE = [ { """params""": [ p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay ) ], # check this named paramters """weight_decay""": self.hparams.weight_decay, }, { """params""": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay )], """weight_decay""": 0.0, }, ] if self.hparams.adafactor: __SCREAMING_SNAKE_CASE = Adafactor( __SCREAMING_SNAKE_CASE , lr=self.hparams.learning_rate , scale_parameter=__SCREAMING_SNAKE_CASE , relative_step=__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = AdamW( __SCREAMING_SNAKE_CASE , lr=self.hparams.learning_rate , eps=self.hparams.adam_epsilon ) __SCREAMING_SNAKE_CASE = optimizer __SCREAMING_SNAKE_CASE = self.get_lr_scheduler() return [optimizer], [scheduler] def UpperCAmelCase__ ( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Dict ) -> Union[str, Any]: """simple docstring""" return self.validation_step(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Dict , __SCREAMING_SNAKE_CASE : List[Any] ) -> List[str]: """simple docstring""" return self.validation_end(__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[Any] ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = max(1 , self.hparams.gpus ) # TODO: consider num_tpu_cores __SCREAMING_SNAKE_CASE = self.hparams.train_batch_size * self.hparams.accumulate_grad_batches * num_devices return (self.dataset_size / effective_batch_size) * self.hparams.max_epochs def UpperCAmelCase__ ( self : str , __SCREAMING_SNAKE_CASE : List[Any] ) -> Tuple: """simple docstring""" if stage == "test": __SCREAMING_SNAKE_CASE = len(self.test_dataloader().dataset ) else: __SCREAMING_SNAKE_CASE = self.get_dataloader("""train""" , self.hparams.train_batch_size , shuffle=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = len(self.train_dataloader().dataset ) def UpperCAmelCase__ ( self : Tuple , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : bool = False ) -> Any: """simple docstring""" raise NotImplementedError("""You must implement this for your task""" ) def UpperCAmelCase__ ( self : str ) -> Union[str, Any]: """simple docstring""" return self.train_loader def UpperCAmelCase__ ( self : Tuple ) -> List[str]: """simple docstring""" return self.get_dataloader("""dev""" , self.hparams.eval_batch_size , shuffle=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Any ) -> Union[str, Any]: """simple docstring""" return self.get_dataloader("""test""" , self.hparams.eval_batch_size , shuffle=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : int , __SCREAMING_SNAKE_CASE : Any ) -> List[str]: """simple docstring""" return os.path.join( self.hparams.data_dir , """cached_{}_{}_{}""".format( __SCREAMING_SNAKE_CASE , list(filter(__SCREAMING_SNAKE_CASE , self.hparams.model_name_or_path.split("""/""" ) ) ).pop() , str(self.hparams.max_seq_length ) , ) , ) @pl.utilities.rank_zero_only def UpperCAmelCase__ ( self : List[str] , __SCREAMING_SNAKE_CASE : Dict[str, Any] ) -> None: """simple docstring""" __SCREAMING_SNAKE_CASE = self.output_dir.joinpath("""best_tfmr""" ) __SCREAMING_SNAKE_CASE = self.step_count self.model.save_pretrained(__SCREAMING_SNAKE_CASE ) self.tokenizer.save_pretrained(__SCREAMING_SNAKE_CASE ) @staticmethod def UpperCAmelCase__ ( __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : List[str] ) -> Optional[int]: """simple docstring""" parser.add_argument( """--model_name_or_path""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , required=__SCREAMING_SNAKE_CASE , help="""Path to pretrained model or model identifier from huggingface.co/models""" , ) parser.add_argument( """--config_name""" , default="""""" , type=__SCREAMING_SNAKE_CASE , help="""Pretrained config name or path if not the same as model_name""" ) parser.add_argument( """--tokenizer_name""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , help="""Pretrained tokenizer name or path if not the same as model_name""" , ) parser.add_argument( """--cache_dir""" , default=str(Path(__SCREAMING_SNAKE_CASE ).parent / """test_run""" / """cache""" ) , type=__SCREAMING_SNAKE_CASE , help="""Where do you want to store the pre-trained models downloaded from huggingface.co""" , ) parser.add_argument( """--encoder_layerdrop""" , type=__SCREAMING_SNAKE_CASE , help="""Encoder layer dropout probability (Optional). Goes into model.config""" , ) parser.add_argument( """--decoder_layerdrop""" , type=__SCREAMING_SNAKE_CASE , help="""Decoder layer dropout probability (Optional). Goes into model.config""" , ) parser.add_argument( """--dropout""" , type=__SCREAMING_SNAKE_CASE , help="""Dropout probability (Optional). Goes into model.config""" , ) parser.add_argument( """--attention_dropout""" , type=__SCREAMING_SNAKE_CASE , help="""Attention dropout probability (Optional). Goes into model.config""" , ) parser.add_argument("""--learning_rate""" , default=5E-5 , type=__SCREAMING_SNAKE_CASE , help="""The initial learning rate for Adam.""" ) parser.add_argument( """--lr_scheduler""" , default="""linear""" , choices=__SCREAMING_SNAKE_CASE , metavar=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , help="""Learning rate scheduler""" , ) parser.add_argument("""--weight_decay""" , default=0.0 , type=__SCREAMING_SNAKE_CASE , help="""Weight decay if we apply some.""" ) parser.add_argument("""--adam_epsilon""" , default=1E-8 , type=__SCREAMING_SNAKE_CASE , help="""Epsilon for Adam optimizer.""" ) parser.add_argument("""--warmup_steps""" , default=0 , type=__SCREAMING_SNAKE_CASE , help="""Linear warmup over warmup_steps.""" ) parser.add_argument("""--num_workers""" , default=4 , type=__SCREAMING_SNAKE_CASE , help="""kwarg passed to DataLoader""" ) parser.add_argument("""--num_train_epochs""" , dest="""max_epochs""" , default=3 , type=__SCREAMING_SNAKE_CASE ) parser.add_argument("""--train_batch_size""" , default=32 , type=__SCREAMING_SNAKE_CASE ) parser.add_argument("""--eval_batch_size""" , default=32 , type=__SCREAMING_SNAKE_CASE ) parser.add_argument("""--adafactor""" , action="""store_true""" ) class lowerCAmelCase__ ( pl.Callback ): """simple docstring""" def UpperCAmelCase__ ( self : int , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : List[str] ) -> Union[str, Any]: """simple docstring""" if ( trainer.is_global_zero and trainer.global_rank == 0 ): # we initialize the retriever only on master worker with RAY. In new pytorch-lightning accelorators are removed. pl_module.model.rag.retriever.init_retrieval() # better to use hook functions. class lowerCAmelCase__ ( pl.Callback ): """simple docstring""" def UpperCAmelCase__ ( self : Tuple , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Tuple ) -> int: """simple docstring""" for name, param in pl_module.model.rag.named_parameters(): if param.grad is None: print(__SCREAMING_SNAKE_CASE ) class lowerCAmelCase__ ( pl.Callback ): """simple docstring""" def UpperCAmelCase__ ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Union[str, Any] ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = trainer.lr_schedulers[0]["""scheduler"""] __SCREAMING_SNAKE_CASE = {f'lr_group_{i}': lr for i, lr in enumerate(lr_scheduler.get_lr() )} pl_module.logger.log_metrics(__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : str , __SCREAMING_SNAKE_CASE : pl.Trainer , __SCREAMING_SNAKE_CASE : pl.LightningModule ) -> Union[str, Any]: """simple docstring""" rank_zero_info("""***** Validation results *****""" ) __SCREAMING_SNAKE_CASE = trainer.callback_metrics # Log results for key in sorted(__SCREAMING_SNAKE_CASE ): if key not in ["log", "progress_bar"]: rank_zero_info("""{} = {}\n""".format(__SCREAMING_SNAKE_CASE , str(metrics[key] ) ) ) def UpperCAmelCase__ ( self : Optional[int] , __SCREAMING_SNAKE_CASE : pl.Trainer , __SCREAMING_SNAKE_CASE : pl.LightningModule ) -> int: """simple docstring""" rank_zero_info("""***** Test results *****""" ) __SCREAMING_SNAKE_CASE = trainer.callback_metrics # Log and save results to file __SCREAMING_SNAKE_CASE = os.path.join(pl_module.hparams.output_dir , """test_results.txt""" ) with open(__SCREAMING_SNAKE_CASE , """w""" ) as writer: for key in sorted(__SCREAMING_SNAKE_CASE ): if key not in ["log", "progress_bar"]: rank_zero_info("""{} = {}\n""".format(__SCREAMING_SNAKE_CASE , str(metrics[key] ) ) ) writer.write("""{} = {}\n""".format(__SCREAMING_SNAKE_CASE , str(metrics[key] ) ) ) def a__ ( a__ , a__ ): """simple docstring""" parser.add_argument( """--output_dir""" , default=str(Path(a__ ).parent / """test_run""" / """model_checkpoints""" ) , type=a__ , help="""The output directory where the model predictions and checkpoints will be written.""" , ) parser.add_argument( """--fp16""" , action="""store_true""" , help="""Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit""" , ) parser.add_argument( """--fp16_opt_level""" , type=a__ , default="""O2""" , help=( """For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3'].""" """See details at https://nvidia.github.io/apex/amp.html""" ) , ) parser.add_argument("""--n_tpu_cores""" , dest="""tpu_cores""" , type=a__ ) parser.add_argument("""--max_grad_norm""" , dest="""gradient_clip_val""" , default=1.0 , type=a__ , help="""Max gradient norm""" ) parser.add_argument("""--do_train""" , action="""store_true""" , help="""Whether to run training.""" ) parser.add_argument("""--do_predict""" , action="""store_true""" , help="""Whether to run predictions on the test set.""" ) parser.add_argument( """--gradient_accumulation_steps""" , dest="""accumulate_grad_batches""" , type=a__ , default=1 , help="""Number of updates steps to accumulate before performing a backward/update pass.""" , ) parser.add_argument("""--seed""" , type=a__ , default=42 , help="""random seed for initialization""" ) parser.add_argument( """--data_dir""" , default=str(Path(a__ ).parent / """test_run""" / """dummy-train-data""" ) , type=a__ , help="""The input data dir. Should contain the training files for the CoNLL-2003 NER task.""" , ) def a__ ( a__ , a__ , a__=None , a__=True , a__=[] , a__=None , a__=None , **a__ , ): """simple docstring""" pl.seed_everything(args.seed ) # init model __SCREAMING_SNAKE_CASE = Path(model.hparams.output_dir ) odir.mkdir(exist_ok=a__ ) # add custom checkpoints if checkpoint_callback is None: __SCREAMING_SNAKE_CASE = pl.callbacks.ModelCheckpoint( filepath=args.output_dir , prefix="""checkpoint""" , monitor="""val_loss""" , mode="""min""" , save_top_k=1 ) if early_stopping_callback: extra_callbacks.append(a__ ) if logging_callback is None: __SCREAMING_SNAKE_CASE = LoggingCallback() __SCREAMING_SNAKE_CASE = {} if args.fpaa: __SCREAMING_SNAKE_CASE = 16 if args.gpus > 1: __SCREAMING_SNAKE_CASE = """auto""" __SCREAMING_SNAKE_CASE = """ddp""" __SCREAMING_SNAKE_CASE = args.accumulate_grad_batches __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = """auto""" __SCREAMING_SNAKE_CASE = pl.Trainer.from_argparse_args( a__ , weights_summary=a__ , callbacks=[logging_callback] + extra_callbacks + [InitCallback()] + [checkpoint_callback] , logger=a__ , val_check_interval=1 , num_sanity_val_steps=2 , **a__ , ) if args.do_train: trainer.fit(a__ ) else: print("""RAG modeling tests with new set functions successfuly executed!""" ) return trainer
267
'''simple docstring''' from itertools import count def a__ ( a__ = 50 ): """simple docstring""" __SCREAMING_SNAKE_CASE = [1] * min_block_length for n in count(a__ ): fill_count_functions.append(1 ) for block_length in range(a__ , n + 1 ): for block_start in range(n - block_length ): fill_count_functions[n] += fill_count_functions[ n - block_start - block_length - 1 ] fill_count_functions[n] += 1 if fill_count_functions[n] > 1_00_00_00: break return n if __name__ == "__main__": print(f"""{solution() = }""")
267
1
'''simple docstring''' import argparse import fairseq import torch from torch import nn from transformers import ( MBartaaTokenizer, MBartConfig, MBartForCausalLM, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaModel, logging, ) logging.set_verbosity_info() UpperCAmelCase : Any = logging.get_logger(__name__) UpperCAmelCase : int = { 'post_extract_proj': 'feature_projection.projection', 'encoder.pos_conv.0': 'encoder.pos_conv_embed.conv', 'self_attn.k_proj': 'encoder.layers.*.attention.k_proj', 'self_attn.v_proj': 'encoder.layers.*.attention.v_proj', 'self_attn.q_proj': 'encoder.layers.*.attention.q_proj', 'self_attn.out_proj': 'encoder.layers.*.attention.out_proj', 'self_attn_layer_norm': 'encoder.layers.*.layer_norm', 'fc1': 'encoder.layers.*.feed_forward.intermediate_dense', 'fc2': 'encoder.layers.*.feed_forward.output_dense', 'final_layer_norm': 'encoder.layers.*.final_layer_norm', 'encoder.layer_norm': 'encoder.layer_norm', 'w2v_model.layer_norm': 'feature_projection.layer_norm', 'quantizer.weight_proj': 'quantizer.weight_proj', 'quantizer.vars': 'quantizer.codevectors', 'project_q': 'project_q', 'final_proj': 'project_hid', 'w2v_encoder.proj': 'lm_head', 'mask_emb': 'masked_spec_embed', } UpperCAmelCase : Union[str, Any] = [ 'lm_head', 'quantizer.weight_proj', 'quantizer.codevectors', 'project_q', 'project_hid', ] def a__ ( a__ , a__ , a__ , a__ , a__ ): """simple docstring""" for attribute in key.split(""".""" ): __SCREAMING_SNAKE_CASE = getattr(a__ , a__ ) if weight_type is not None: __SCREAMING_SNAKE_CASE = getattr(a__ , a__ ).shape else: __SCREAMING_SNAKE_CASE = hf_pointer.shape assert hf_shape == value.shape, ( F'Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be' F' {value.shape} for {full_name}' ) if weight_type == "weight": __SCREAMING_SNAKE_CASE = value elif weight_type == "weight_g": __SCREAMING_SNAKE_CASE = value elif weight_type == "weight_v": __SCREAMING_SNAKE_CASE = value elif weight_type == "bias": __SCREAMING_SNAKE_CASE = value else: __SCREAMING_SNAKE_CASE = value logger.info(F'{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.' ) def a__ ( a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = fairseq_model.state_dict() __SCREAMING_SNAKE_CASE = hf_model.feature_extractor __SCREAMING_SNAKE_CASE = hf_model.adapter for name, value in fairseq_dict.items(): __SCREAMING_SNAKE_CASE = False if "conv_layers" in name: load_conv_layer( a__ , a__ , a__ , a__ , hf_model.config.feat_extract_norm == """group""" , ) __SCREAMING_SNAKE_CASE = True elif any(x in name for x in ["""adaptor""", """w2v_encoder.proj.""", """w2v_proj_ln."""] ): load_adapter(a__ , a__ , a__ , a__ ) __SCREAMING_SNAKE_CASE = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0]: __SCREAMING_SNAKE_CASE = True if "*" in mapped_key: __SCREAMING_SNAKE_CASE = name.split(a__ )[0].split(""".""" )[-2] __SCREAMING_SNAKE_CASE = mapped_key.replace("""*""" , a__ ) if "weight_g" in name: __SCREAMING_SNAKE_CASE = """weight_g""" elif "weight_v" in name: __SCREAMING_SNAKE_CASE = """weight_v""" elif "bias" in name: __SCREAMING_SNAKE_CASE = """bias""" elif "weight" in name: __SCREAMING_SNAKE_CASE = """weight""" else: __SCREAMING_SNAKE_CASE = None set_recursively(a__ , a__ , a__ , a__ , a__ ) continue if not is_used: unused_weights.append(a__ ) logger.warning(F'Unused weights: {unused_weights}' ) def a__ ( a__ , a__ , a__ , a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = full_name.split("""conv_layers.""" )[-1] __SCREAMING_SNAKE_CASE = name.split(""".""" ) __SCREAMING_SNAKE_CASE = int(items[0] ) __SCREAMING_SNAKE_CASE = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( F'{full_name} has size {value.shape}, but' F' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.' ) __SCREAMING_SNAKE_CASE = value logger.info(F'Feat extract conv layer {layer_id} was initialized from {full_name}.' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( F'{full_name} has size {value.shape}, but' F' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.' ) __SCREAMING_SNAKE_CASE = value logger.info(F'Feat extract conv layer {layer_id} was initialized from {full_name}.' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( F'{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was' " found." ) __SCREAMING_SNAKE_CASE = value logger.info(F'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( F'{full_name} has size {value.shape}, but' F' {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.' ) __SCREAMING_SNAKE_CASE = value logger.info(F'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.' ) else: unused_weights.append(a__ ) def a__ ( a__ , a__ , a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = full_name.split("""adaptor.""" )[-1] __SCREAMING_SNAKE_CASE = name.split(""".""" ) if items[1].isdigit(): __SCREAMING_SNAKE_CASE = int(items[1] ) else: __SCREAMING_SNAKE_CASE = None if "adaptor" not in full_name: if "proj_ln" in full_name: # has to be layer norm if "bias" in name: assert ( value.shape == adapter.proj_layer_norm.bias.data.shape ), F'{full_name} has size {value.shape}, but {adapter.proj_layer_norm.bias.data.shape} was found.' __SCREAMING_SNAKE_CASE = value logger.info(F'Adapter proj layer norm bias was initialized from {full_name}.' ) if "weight" in name: assert ( value.shape == adapter.proj_layer_norm.weight.data.shape ), F'{full_name} has size {value.shape}, but {adapter.proj_layer_norm.weight.data.shape} was found.' __SCREAMING_SNAKE_CASE = value else: # has to be projection layer if "bias" in name: assert ( value.shape == adapter.proj.bias.data.shape ), F'{full_name} has size {value.shape}, but {adapter.proj.bias.data.shape} was found.' __SCREAMING_SNAKE_CASE = value logger.info(F'Adapter proj layer bias was initialized from {full_name}.' ) if "weight" in name: assert ( value.shape == adapter.proj.weight.data.shape ), F'{full_name} has size {value.shape}, but {adapter.proj.weight.data.shape} was found.' __SCREAMING_SNAKE_CASE = value logger.info(F'Adapter proj layer weight was initialized from {full_name}.' ) elif isinstance(a__ , a__ ): if "bias" in name: assert ( value.shape == adapter.layers[layer_id].conv.bias.data.shape ), F'{full_name} has size {value.shape}, but {adapter.layers[layer_id].conv.bias.data.shape} was found.' __SCREAMING_SNAKE_CASE = value logger.info(F'Adapter layer {layer_id} bias was initialized from {full_name}.' ) elif "weight" in name: assert ( value.shape == adapter.layers[layer_id].conv.weight.data.shape ), F'{full_name} has size {value.shape}, but {adapter.layers[layer_id].conv.weight.data.shape} was found.' __SCREAMING_SNAKE_CASE = value logger.info(F'Adapter layer {layer_id} bias was initialized from {full_name}.' ) else: unused_weights.append(a__ ) def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = emb.weight.shape __SCREAMING_SNAKE_CASE = nn.Linear(a__ , a__ , bias=a__ ) __SCREAMING_SNAKE_CASE = emb.weight.data return lin_layer @torch.no_grad() def a__ ( a__ , a__ , a__ , a__ , a__ , a__ , a__ , a__ , a__ , a__ , a__ , ): """simple docstring""" __SCREAMING_SNAKE_CASE = WavaVecaConfig.from_pretrained( a__ , add_adapter=a__ , adapter_stride=a__ , adapter_kernel_size=a__ , use_auth_token=a__ , output_hidden_size=a__ , ) __SCREAMING_SNAKE_CASE = MBartConfig.from_pretrained(a__ ) # load model __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={ """config_yaml""": config_yaml_path, """data""": """/""".join(dict_path.split("""/""" )[:-1] ), """w2v_path""": checkpoint_path, """load_pretrained_decoder_from""": None, } , ) __SCREAMING_SNAKE_CASE = model[0].eval() # load feature extractor __SCREAMING_SNAKE_CASE = WavaVecaFeatureExtractor.from_pretrained(a__ , use_auth_token=a__ ) # set weights for wav2vec2 encoder __SCREAMING_SNAKE_CASE = WavaVecaModel(a__ ) recursively_load_weights_wavaveca(model.encoder , a__ ) # load decoder weights __SCREAMING_SNAKE_CASE = MBartForCausalLM(a__ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict() , strict=a__ ) logger.warning(F'The following keys are missing when loading the decoder weights: {missing_keys}' ) logger.warning(F'The following keys are unexpected when loading the decoder weights: {unexpected_keys}' ) __SCREAMING_SNAKE_CASE = SpeechEncoderDecoderModel(encoder=a__ , decoder=a__ ) __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = MBartaaTokenizer(a__ ) tokenizer.save_pretrained(a__ ) __SCREAMING_SNAKE_CASE = hf_wavavec.config.to_dict() __SCREAMING_SNAKE_CASE = tokenizer.pad_token_id __SCREAMING_SNAKE_CASE = tokenizer.bos_token_id __SCREAMING_SNAKE_CASE = tokenizer.eos_token_id __SCREAMING_SNAKE_CASE = """mbart50""" __SCREAMING_SNAKE_CASE = """wav2vec2""" __SCREAMING_SNAKE_CASE = tokenizer.eos_token_id __SCREAMING_SNAKE_CASE = 25_00_04 __SCREAMING_SNAKE_CASE = tokenizer.eos_token_id __SCREAMING_SNAKE_CASE = SpeechEncoderDecoderConfig.from_dict(a__ ) hf_wavavec.save_pretrained(a__ ) feature_extractor.save_pretrained(a__ ) if __name__ == "__main__": UpperCAmelCase : Any = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint') parser.add_argument('--dict_path', default=None, type=str, help='Path to dict of fine-tuned model') parser.add_argument('--config_yaml_path', default=None, type=str, help='Path to yaml file of fine-tuned model') parser.add_argument( '--encoder_config_path', default='facebook/wav2vec2-xls-r-1b', type=str, help='Path to hf encoder wav2vec2 checkpoint config', ) parser.add_argument( '--decoder_config_path', default='facebook/mbart-large-50-one-to-many-mmt', type=str, help='Path to hf decoder checkpoint config', ) parser.add_argument('--add_adapter', default=True, type=bool, help='whethere to add model adapter layers') parser.add_argument('--adapter_stride', default=2, type=int, help='stride of adapter layers') parser.add_argument('--adapter_kernel_size', default=3, type=int, help='kernel size of adapter layers') parser.add_argument('--encoder_output_dim', default=1_0_2_4, type=int, help='encoder output dim') parser.add_argument('--start_token_id', default=2_5_0_0_0_4, type=int, help='`decoder_start_token_id` of model config') UpperCAmelCase : List[str] = parser.parse_args() convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.dict_path, args.config_yaml_path, encoder_config_path=args.encoder_config_path, decoder_config_path=args.decoder_config_path, add_adapter=args.add_adapter, adapter_kernel_size=args.adapter_kernel_size, adapter_stride=args.adapter_stride, decoder_start_token_id=args.start_token_id, encoder_output_dim=args.encoder_output_dim, )
267
'''simple docstring''' import logging import os import threading import time try: import warnings except ImportError: UpperCAmelCase : Optional[Any] = None try: import msvcrt except ImportError: UpperCAmelCase : List[Any] = None try: import fcntl except ImportError: UpperCAmelCase : int = None # Backward compatibility # ------------------------------------------------ try: TimeoutError except NameError: UpperCAmelCase : Union[str, Any] = OSError # Data # ------------------------------------------------ UpperCAmelCase : List[Any] = [ 'Timeout', 'BaseFileLock', 'WindowsFileLock', 'UnixFileLock', 'SoftFileLock', 'FileLock', ] UpperCAmelCase : Tuple = '3.0.12' UpperCAmelCase : str = None def a__ ( ): """simple docstring""" global _logger __SCREAMING_SNAKE_CASE = _logger or logging.getLogger(__name__ ) return _logger class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Any , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = lock_file return None def __str__( self : str ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = f'The file lock \'{self.lock_file}\' could not be acquired.' return temp class lowerCAmelCase__ : """simple docstring""" def __init__( self : Tuple , __SCREAMING_SNAKE_CASE : List[Any] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = lock return None def __enter__( self : List[str] ) -> List[Any]: """simple docstring""" return self.lock def __exit__( self : Tuple , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> List[str]: """simple docstring""" self.lock.release() return None class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : str=-1 , __SCREAMING_SNAKE_CASE : Optional[Any]=None ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = max_filename_length if max_filename_length is not None else 255 # Hash the filename if it's too long __SCREAMING_SNAKE_CASE = self.hash_filename_if_too_long(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # The path to the lock file. __SCREAMING_SNAKE_CASE = lock_file # The file descriptor for the *_lock_file* as it is returned by the # os.open() function. # This file lock is only NOT None, if the object currently holds the # lock. __SCREAMING_SNAKE_CASE = None # The default timeout value. __SCREAMING_SNAKE_CASE = timeout # We use this lock primarily for the lock counter. __SCREAMING_SNAKE_CASE = threading.Lock() # The lock counter is used for implementing the nested locking # mechanism. Whenever the lock is acquired, the counter is increased and # the lock is only released, when this value is 0 again. __SCREAMING_SNAKE_CASE = 0 return None @property def UpperCAmelCase__ ( self : List[Any] ) -> List[str]: """simple docstring""" return self._lock_file @property def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" return self._timeout @timeout.setter def UpperCAmelCase__ ( self : List[str] , __SCREAMING_SNAKE_CASE : Dict ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = float(__SCREAMING_SNAKE_CASE ) return None def UpperCAmelCase__ ( self : Optional[Any] ) -> List[Any]: """simple docstring""" raise NotImplementedError() def UpperCAmelCase__ ( self : Union[str, Any] ) -> Any: """simple docstring""" raise NotImplementedError() @property def UpperCAmelCase__ ( self : Union[str, Any] ) -> int: """simple docstring""" return self._lock_file_fd is not None def UpperCAmelCase__ ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[Any]=None , __SCREAMING_SNAKE_CASE : Optional[int]=0.05 ) -> Optional[Any]: """simple docstring""" if timeout is None: __SCREAMING_SNAKE_CASE = self.timeout # Increment the number right at the beginning. # We can still undo it, if something fails. with self._thread_lock: self._lock_counter += 1 __SCREAMING_SNAKE_CASE = id(self ) __SCREAMING_SNAKE_CASE = self._lock_file __SCREAMING_SNAKE_CASE = time.time() try: while True: with self._thread_lock: if not self.is_locked: logger().debug(f'Attempting to acquire lock {lock_id} on {lock_filename}' ) self._acquire() if self.is_locked: logger().debug(f'Lock {lock_id} acquired on {lock_filename}' ) break elif timeout >= 0 and time.time() - start_time > timeout: logger().debug(f'Timeout on acquiring lock {lock_id} on {lock_filename}' ) raise Timeout(self._lock_file ) else: logger().debug( f'Lock {lock_id} not acquired on {lock_filename}, waiting {poll_intervall} seconds ...' ) time.sleep(__SCREAMING_SNAKE_CASE ) except: # noqa # Something did go wrong, so decrement the counter. with self._thread_lock: __SCREAMING_SNAKE_CASE = max(0 , self._lock_counter - 1 ) raise return _Acquire_ReturnProxy(lock=self ) def UpperCAmelCase__ ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[Any]=False ) -> Dict: """simple docstring""" with self._thread_lock: if self.is_locked: self._lock_counter -= 1 if self._lock_counter == 0 or force: __SCREAMING_SNAKE_CASE = id(self ) __SCREAMING_SNAKE_CASE = self._lock_file logger().debug(f'Attempting to release lock {lock_id} on {lock_filename}' ) self._release() __SCREAMING_SNAKE_CASE = 0 logger().debug(f'Lock {lock_id} released on {lock_filename}' ) return None def __enter__( self : Union[str, Any] ) -> Optional[int]: """simple docstring""" self.acquire() return self def __exit__( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Any ) -> Tuple: """simple docstring""" self.release() return None def __del__( self : str ) -> Union[str, Any]: """simple docstring""" self.release(force=__SCREAMING_SNAKE_CASE ) return None def UpperCAmelCase__ ( self : Optional[int] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : int ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = os.path.basename(__SCREAMING_SNAKE_CASE ) if len(__SCREAMING_SNAKE_CASE ) > max_length and max_length > 0: __SCREAMING_SNAKE_CASE = os.path.dirname(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = str(hash(__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = filename[: max_length - len(__SCREAMING_SNAKE_CASE ) - 8] + """...""" + hashed_filename + """.lock""" return os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else: return path class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Tuple , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Dict=-1 , __SCREAMING_SNAKE_CASE : Dict=None ) -> List[Any]: """simple docstring""" from .file_utils import relative_to_absolute_path super().__init__(__SCREAMING_SNAKE_CASE , timeout=__SCREAMING_SNAKE_CASE , max_filename_length=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """\\\\?\\""" + relative_to_absolute_path(self.lock_file ) def UpperCAmelCase__ ( self : Dict ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = os.O_RDWR | os.O_CREAT | os.O_TRUNC try: __SCREAMING_SNAKE_CASE = os.open(self._lock_file , __SCREAMING_SNAKE_CASE ) except OSError: pass else: try: msvcrt.locking(__SCREAMING_SNAKE_CASE , msvcrt.LK_NBLCK , 1 ) except OSError: os.close(__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = fd return None def UpperCAmelCase__ ( self : Tuple ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self._lock_file_fd __SCREAMING_SNAKE_CASE = None msvcrt.locking(__SCREAMING_SNAKE_CASE , msvcrt.LK_UNLCK , 1 ) os.close(__SCREAMING_SNAKE_CASE ) try: os.remove(self._lock_file ) # Probably another instance of the application # that acquired the file lock. except OSError: pass return None class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Union[str, Any]=-1 , __SCREAMING_SNAKE_CASE : Optional[Any]=None ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = os.statvfs(os.path.dirname(__SCREAMING_SNAKE_CASE ) ).f_namemax super().__init__(__SCREAMING_SNAKE_CASE , timeout=__SCREAMING_SNAKE_CASE , max_filename_length=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = os.O_RDWR | os.O_CREAT | os.O_TRUNC __SCREAMING_SNAKE_CASE = os.open(self._lock_file , __SCREAMING_SNAKE_CASE ) try: fcntl.flock(__SCREAMING_SNAKE_CASE , fcntl.LOCK_EX | fcntl.LOCK_NB ) except OSError: os.close(__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = fd return None def UpperCAmelCase__ ( self : List[Any] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = self._lock_file_fd __SCREAMING_SNAKE_CASE = None fcntl.flock(__SCREAMING_SNAKE_CASE , fcntl.LOCK_UN ) os.close(__SCREAMING_SNAKE_CASE ) return None class lowerCAmelCase__ ( a ): """simple docstring""" def UpperCAmelCase__ ( self : List[str] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC try: __SCREAMING_SNAKE_CASE = os.open(self._lock_file , __SCREAMING_SNAKE_CASE ) except OSError: pass else: __SCREAMING_SNAKE_CASE = fd return None def UpperCAmelCase__ ( self : int ) -> Optional[int]: """simple docstring""" os.close(self._lock_file_fd ) __SCREAMING_SNAKE_CASE = None try: os.remove(self._lock_file ) # The file is already deleted and that's what we want. except OSError: pass return None UpperCAmelCase : Dict = None if msvcrt: UpperCAmelCase : Optional[int] = WindowsFileLock elif fcntl: UpperCAmelCase : Optional[Any] = UnixFileLock else: UpperCAmelCase : int = SoftFileLock if warnings is not None: warnings.warn('only soft file lock is available')
267
1
'''simple docstring''' import importlib.util import os import platform from argparse import ArgumentParser import huggingface_hub from .. import __version__ as version from ..utils import ( is_accelerate_available, is_flax_available, is_safetensors_available, is_tf_available, is_torch_available, ) from . import BaseTransformersCLICommand def a__ ( a__ ): """simple docstring""" return EnvironmentCommand() def a__ ( a__ ): """simple docstring""" return EnvironmentCommand(args.accelerate_config_file ) class lowerCAmelCase__ ( a ): """simple docstring""" @staticmethod def UpperCAmelCase__ ( __SCREAMING_SNAKE_CASE : ArgumentParser ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = parser.add_parser("""env""" ) download_parser.set_defaults(func=__SCREAMING_SNAKE_CASE ) download_parser.add_argument( """--accelerate-config_file""" , default=__SCREAMING_SNAKE_CASE , help="""The accelerate config file to use for the default values in the launching script.""" , ) download_parser.set_defaults(func=__SCREAMING_SNAKE_CASE ) def __init__( self : List[str] , __SCREAMING_SNAKE_CASE : Tuple , *__SCREAMING_SNAKE_CASE : int ) -> None: """simple docstring""" __SCREAMING_SNAKE_CASE = accelerate_config_file def UpperCAmelCase__ ( self : Optional[Any] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = """not installed""" if is_safetensors_available(): import safetensors __SCREAMING_SNAKE_CASE = safetensors.__version__ elif importlib.util.find_spec("""safetensors""" ) is not None: import safetensors __SCREAMING_SNAKE_CASE = f'{safetensors.__version__} but is ignored because of PyTorch version too old.' __SCREAMING_SNAKE_CASE = """not installed""" __SCREAMING_SNAKE_CASE = __SCREAMING_SNAKE_CASE = """not found""" if is_accelerate_available(): import accelerate from accelerate.commands.config import default_config_file, load_config_from_file __SCREAMING_SNAKE_CASE = accelerate.__version__ # Get the default from the config file. if self._accelerate_config_file is not None or os.path.isfile(__SCREAMING_SNAKE_CASE ): __SCREAMING_SNAKE_CASE = load_config_from_file(self._accelerate_config_file ).to_dict() __SCREAMING_SNAKE_CASE = ( """\n""".join([f'\t- {prop}: {val}' for prop, val in accelerate_config.items()] ) if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else f'\t{accelerate_config}' ) __SCREAMING_SNAKE_CASE = """not installed""" __SCREAMING_SNAKE_CASE = """NA""" if is_torch_available(): import torch __SCREAMING_SNAKE_CASE = torch.__version__ __SCREAMING_SNAKE_CASE = torch.cuda.is_available() __SCREAMING_SNAKE_CASE = """not installed""" __SCREAMING_SNAKE_CASE = """NA""" if is_tf_available(): import tensorflow as tf __SCREAMING_SNAKE_CASE = tf.__version__ try: # deprecated in v2.1 __SCREAMING_SNAKE_CASE = tf.test.is_gpu_available() except AttributeError: # returns list of devices, convert to bool __SCREAMING_SNAKE_CASE = bool(tf.config.list_physical_devices("""GPU""" ) ) __SCREAMING_SNAKE_CASE = """not installed""" __SCREAMING_SNAKE_CASE = """not installed""" __SCREAMING_SNAKE_CASE = """not installed""" __SCREAMING_SNAKE_CASE = """NA""" if is_flax_available(): import flax import jax import jaxlib __SCREAMING_SNAKE_CASE = flax.__version__ __SCREAMING_SNAKE_CASE = jax.__version__ __SCREAMING_SNAKE_CASE = jaxlib.__version__ __SCREAMING_SNAKE_CASE = jax.lib.xla_bridge.get_backend().platform __SCREAMING_SNAKE_CASE = { """`transformers` version""": version, """Platform""": platform.platform(), """Python version""": platform.python_version(), """Huggingface_hub version""": huggingface_hub.__version__, """Safetensors version""": f'{safetensors_version}', """Accelerate version""": f'{accelerate_version}', """Accelerate config""": f'{accelerate_config_str}', """PyTorch version (GPU?)""": f'{pt_version} ({pt_cuda_available})', """Tensorflow version (GPU?)""": f'{tf_version} ({tf_cuda_available})', """Flax version (CPU?/GPU?/TPU?)""": f'{flax_version} ({jax_backend})', """Jax version""": f'{jax_version}', """JaxLib version""": f'{jaxlib_version}', """Using GPU in script?""": """<fill in>""", """Using distributed or parallel set-up in script?""": """<fill in>""", } print("""\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n""" ) print(self.format_dict(__SCREAMING_SNAKE_CASE ) ) return info @staticmethod def UpperCAmelCase__ ( __SCREAMING_SNAKE_CASE : Any ) -> Dict: """simple docstring""" return "\n".join([f'- {prop}: {val}' for prop, val in d.items()] ) + "\n"
267
'''simple docstring''' import shutil import tempfile import unittest from transformers import ( SPIECE_UNDERLINE, AddedToken, BatchEncoding, NllbTokenizer, NllbTokenizerFast, is_torch_available, ) from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...test_tokenization_common import TokenizerTesterMixin UpperCAmelCase : Optional[int] = get_tests_dir('fixtures/test_sentencepiece.model') if is_torch_available(): from transformers.models.mam_aaa.modeling_mam_aaa import shift_tokens_right UpperCAmelCase : Optional[int] = 2_5_6_0_4_7 UpperCAmelCase : Union[str, Any] = 2_5_6_1_4_5 @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = NllbTokenizer lowerCAmelCase__ = NllbTokenizerFast lowerCAmelCase__ = True lowerCAmelCase__ = True lowerCAmelCase__ = {} def UpperCAmelCase__ ( self : List[Any] ) -> int: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing __SCREAMING_SNAKE_CASE = NllbTokenizer(__SCREAMING_SNAKE_CASE , keep_accents=__SCREAMING_SNAKE_CASE ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCAmelCase__ ( self : Dict ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = NllbTokenizer(__SCREAMING_SNAKE_CASE , keep_accents=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(__SCREAMING_SNAKE_CASE , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) __SCREAMING_SNAKE_CASE = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ 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""", """é""", """.""", ] , ) __SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ 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] ] , ) __SCREAMING_SNAKE_CASE = tokenizer.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ 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>""", """.""", ] , ) def UpperCAmelCase__ ( self : Dict ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = (self.rust_tokenizer_class, """hf-internal-testing/tiny-random-nllb""", {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) __SCREAMING_SNAKE_CASE = tuple(f for f in tokenizer_r_files if """tokenizer.json""" not in f ) self.assertSequenceEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Checks everything loads correctly in the same way __SCREAMING_SNAKE_CASE = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) # Save tokenizer rust, legacy_format=True __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE , legacy_format=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it save with the same files self.assertSequenceEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Checks everything loads correctly in the same way __SCREAMING_SNAKE_CASE = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) # Save tokenizer rust, legacy_format=False __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE , legacy_format=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it saved the tokenizer.json file self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way __SCREAMING_SNAKE_CASE = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) @require_torch def UpperCAmelCase__ ( self : List[Any] ) -> Any: """simple docstring""" if not self.test_seqaseq: return __SCREAMING_SNAKE_CASE = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): # Longer text that will definitely require truncation. __SCREAMING_SNAKE_CASE = [ """ UN Chief Says There Is No Military Solution in Syria""", """ Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for""" """ Syria is that 'there is no military solution' to the nearly five-year conflict and more weapons""" """ will only worsen the violence and misery for millions of people.""", ] __SCREAMING_SNAKE_CASE = [ """Şeful ONU declară că nu există o soluţie militară în Siria""", """Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al""" """ Rusiei pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi""" """ că noi arme nu vor face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.""", ] try: __SCREAMING_SNAKE_CASE = tokenizer.prepare_seqaseq_batch( src_texts=__SCREAMING_SNAKE_CASE , tgt_texts=__SCREAMING_SNAKE_CASE , max_length=3 , max_target_length=10 , return_tensors="""pt""" , src_lang="""eng_Latn""" , tgt_lang="""ron_Latn""" , ) except NotImplementedError: return self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.labels.shape[1] , 10 ) # max_target_length will default to max_length if not specified __SCREAMING_SNAKE_CASE = tokenizer.prepare_seqaseq_batch( __SCREAMING_SNAKE_CASE , tgt_texts=__SCREAMING_SNAKE_CASE , max_length=3 , return_tensors="""pt""" ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.labels.shape[1] , 3 ) __SCREAMING_SNAKE_CASE = tokenizer.prepare_seqaseq_batch( src_texts=__SCREAMING_SNAKE_CASE , max_length=3 , max_target_length=10 , return_tensors="""pt""" ) self.assertEqual(batch_encoder_only.input_ids.shape[1] , 3 ) self.assertEqual(batch_encoder_only.attention_mask.shape[1] , 3 ) self.assertNotIn("""decoder_input_ids""" , __SCREAMING_SNAKE_CASE ) @unittest.skip("""Unfortunately way too slow to build a BPE with SentencePiece.""" ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" pass def UpperCAmelCase__ ( self : List[str] ) -> Dict: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): __SCREAMING_SNAKE_CASE = [AddedToken("""<special>""" , lstrip=__SCREAMING_SNAKE_CASE )] __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_r.encode("""Hey this is a <special> token""" ) __SCREAMING_SNAKE_CASE = tokenizer_r.encode("""<special>""" , add_special_tokens=__SCREAMING_SNAKE_CASE )[0] self.assertTrue(special_token_id in r_output ) if self.test_slow_tokenizer: __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer_p.encode("""Hey this is a <special> token""" ) __SCREAMING_SNAKE_CASE = tokenizer_cr.encode("""Hey this is a <special> token""" ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertTrue(special_token_id in p_output ) self.assertTrue(special_token_id in cr_output ) @require_torch @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = "facebook/nllb-200-distilled-600M" lowerCAmelCase__ = [ " UN Chief Says There Is No Military Solution in Syria", " Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for Syria is that \"there is no military solution\" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.", ] lowerCAmelCase__ = [ "Şeful ONU declară că nu există o soluţie militară în Siria", "Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei" " pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi că noi arme nu vor" " face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.", ] lowerCAmelCase__ = [ 256047, 16297, 134408, 8165, 248066, 14734, 950, 1135, 105721, 3573, 83, 27352, 108, 49486, 2, ] @classmethod def UpperCAmelCase__ ( cls : List[Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = NllbTokenizer.from_pretrained( cls.checkpoint_name , src_lang="""eng_Latn""" , tgt_lang="""ron_Latn""" ) __SCREAMING_SNAKE_CASE = 1 return cls def UpperCAmelCase__ ( self : Union[str, Any] ) -> List[str]: """simple docstring""" self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ace_Arab"""] , 256_001 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ace_Latn"""] , 256_002 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""fra_Latn"""] , 256_057 ) def UpperCAmelCase__ ( self : Optional[int] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Any ) -> int: """simple docstring""" self.assertIn(__SCREAMING_SNAKE_CASE , self.tokenizer.all_special_ids ) # fmt: off __SCREAMING_SNAKE_CASE = [RO_CODE, 4_254, 98_068, 112_923, 39_072, 3_909, 713, 102_767, 26, 17_314, 35_642, 14_683, 33_118, 2_022, 66_987, 2, 256_047] # fmt: on __SCREAMING_SNAKE_CASE = self.tokenizer.decode(__SCREAMING_SNAKE_CASE , skip_special_tokens=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertNotIn(self.tokenizer.eos_token , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = ["""this is gunna be a long sentence """ * 20] assert isinstance(src_text[0] , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = 10 __SCREAMING_SNAKE_CASE = self.tokenizer(__SCREAMING_SNAKE_CASE , max_length=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE ).input_ids[0] self.assertEqual(ids[-1] , 2 ) self.assertEqual(ids[0] , __SCREAMING_SNAKE_CASE ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : int ) -> List[Any]: """simple docstring""" self.assertListEqual(self.tokenizer.convert_tokens_to_ids(["""<mask>""", """ar_AR"""] ) , [256_203, 3] ) def UpperCAmelCase__ ( self : str ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = NllbTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , __SCREAMING_SNAKE_CASE ) @require_torch def UpperCAmelCase__ ( self : str ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=len(self.expected_src_tokens ) , return_tensors="""pt""" , ) __SCREAMING_SNAKE_CASE = shift_tokens_right( batch["""labels"""] , self.tokenizer.pad_token_id , self.tokenizer.lang_code_to_id["""ron_Latn"""] ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertEqual((2, 15) , batch.input_ids.shape ) self.assertEqual((2, 15) , batch.attention_mask.shape ) __SCREAMING_SNAKE_CASE = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , __SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , batch.decoder_input_ids[0, 0] ) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [EN_CODE] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer(self.src_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=3 , return_tensors="""pt""" ) __SCREAMING_SNAKE_CASE = self.tokenizer( text_target=self.tgt_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=10 , return_tensors="""pt""" ) __SCREAMING_SNAKE_CASE = targets["""input_ids"""] __SCREAMING_SNAKE_CASE = shift_tokens_right( __SCREAMING_SNAKE_CASE , self.tokenizer.pad_token_id , decoder_start_token_id=self.tokenizer.lang_code_to_id[self.tokenizer.tgt_lang] , ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 10 ) @require_torch def UpperCAmelCase__ ( self : int ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer._build_translation_inputs( """A test""" , return_tensors="""pt""" , src_lang="""eng_Latn""" , tgt_lang="""fra_Latn""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE ) , { # A, test, EOS, en_XX """input_ids""": [[256_047, 70, 7_356, 2]], """attention_mask""": [[1, 1, 1, 1]], # ar_AR """forced_bos_token_id""": 256_057, } , ) @require_torch def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = self.tokenizer( """UN Chief says there is no military solution in Syria""" , src_lang="""eng_Latn""" , tgt_lang="""fra_Latn""" ) self.assertEqual( inputs.input_ids , [16_297, 134_408, 25_653, 6_370, 248, 254, 103_929, 94_995, 108, 49_486, 2, 256_047] ) __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = self.tokenizer( """UN Chief says there is no military solution in Syria""" , src_lang="""eng_Latn""" , tgt_lang="""fra_Latn""" ) self.assertEqual( inputs.input_ids , [256_047, 16_297, 134_408, 25_653, 6_370, 248, 254, 103_929, 94_995, 108, 49_486, 2] )
267
1
'''simple docstring''' from collections import deque class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[str] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : int ) -> None: """simple docstring""" __SCREAMING_SNAKE_CASE = process_name # process name __SCREAMING_SNAKE_CASE = arrival_time # arrival time of the process # completion time of finished process or last interrupted time __SCREAMING_SNAKE_CASE = arrival_time __SCREAMING_SNAKE_CASE = burst_time # remaining burst time __SCREAMING_SNAKE_CASE = 0 # total time of the process wait in ready queue __SCREAMING_SNAKE_CASE = 0 # time from arrival time to completion time class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : list[int] , __SCREAMING_SNAKE_CASE : deque[Process] , __SCREAMING_SNAKE_CASE : int , ) -> None: """simple docstring""" __SCREAMING_SNAKE_CASE = number_of_queues # time slice of queues that round robin algorithm applied __SCREAMING_SNAKE_CASE = time_slices # unfinished process is in this ready_queue __SCREAMING_SNAKE_CASE = queue # current time __SCREAMING_SNAKE_CASE = current_time # finished process is in this sequence queue __SCREAMING_SNAKE_CASE = deque() def UpperCAmelCase__ ( self : Dict ) -> list[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = [] for i in range(len(self.finish_queue ) ): sequence.append(self.finish_queue[i].process_name ) return sequence def UpperCAmelCase__ ( self : int , __SCREAMING_SNAKE_CASE : list[Process] ) -> list[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = [] for i in range(len(__SCREAMING_SNAKE_CASE ) ): waiting_times.append(queue[i].waiting_time ) return waiting_times def UpperCAmelCase__ ( self : Optional[int] , __SCREAMING_SNAKE_CASE : list[Process] ) -> list[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = [] for i in range(len(__SCREAMING_SNAKE_CASE ) ): turnaround_times.append(queue[i].turnaround_time ) return turnaround_times def UpperCAmelCase__ ( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : list[Process] ) -> list[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = [] for i in range(len(__SCREAMING_SNAKE_CASE ) ): completion_times.append(queue[i].stop_time ) return completion_times def UpperCAmelCase__ ( self : Dict , __SCREAMING_SNAKE_CASE : deque[Process] ) -> list[int]: """simple docstring""" return [q.burst_time for q in queue] def UpperCAmelCase__ ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Process ) -> int: """simple docstring""" process.waiting_time += self.current_time - process.stop_time return process.waiting_time def UpperCAmelCase__ ( self : int , __SCREAMING_SNAKE_CASE : deque[Process] ) -> deque[Process]: """simple docstring""" __SCREAMING_SNAKE_CASE = deque() # sequence deque of finished process while len(__SCREAMING_SNAKE_CASE ) != 0: __SCREAMING_SNAKE_CASE = ready_queue.popleft() # current process # if process's arrival time is later than current time, update current time if self.current_time < cp.arrival_time: self.current_time += cp.arrival_time # update waiting time of current process self.update_waiting_time(__SCREAMING_SNAKE_CASE ) # update current time self.current_time += cp.burst_time # finish the process and set the process's burst-time 0 __SCREAMING_SNAKE_CASE = 0 # set the process's turnaround time because it is finished __SCREAMING_SNAKE_CASE = self.current_time - cp.arrival_time # set the completion time __SCREAMING_SNAKE_CASE = self.current_time # add the process to queue that has finished queue finished.append(__SCREAMING_SNAKE_CASE ) self.finish_queue.extend(__SCREAMING_SNAKE_CASE ) # add finished process to finish queue # FCFS will finish all remaining processes return finished def UpperCAmelCase__ ( self : int , __SCREAMING_SNAKE_CASE : deque[Process] , __SCREAMING_SNAKE_CASE : int ) -> tuple[deque[Process], deque[Process]]: """simple docstring""" __SCREAMING_SNAKE_CASE = deque() # sequence deque of terminated process # just for 1 cycle and unfinished processes will go back to queue for _ in range(len(__SCREAMING_SNAKE_CASE ) ): __SCREAMING_SNAKE_CASE = ready_queue.popleft() # current process # if process's arrival time is later than current time, update current time if self.current_time < cp.arrival_time: self.current_time += cp.arrival_time # update waiting time of unfinished processes self.update_waiting_time(__SCREAMING_SNAKE_CASE ) # if the burst time of process is bigger than time-slice if cp.burst_time > time_slice: # use CPU for only time-slice self.current_time += time_slice # update remaining burst time cp.burst_time -= time_slice # update end point time __SCREAMING_SNAKE_CASE = self.current_time # locate the process behind the queue because it is not finished ready_queue.append(__SCREAMING_SNAKE_CASE ) else: # use CPU for remaining burst time self.current_time += cp.burst_time # set burst time 0 because the process is finished __SCREAMING_SNAKE_CASE = 0 # set the finish time __SCREAMING_SNAKE_CASE = self.current_time # update the process' turnaround time because it is finished __SCREAMING_SNAKE_CASE = self.current_time - cp.arrival_time # add the process to queue that has finished queue finished.append(__SCREAMING_SNAKE_CASE ) self.finish_queue.extend(__SCREAMING_SNAKE_CASE ) # add finished process to finish queue # return finished processes queue and remaining processes queue return finished, ready_queue def UpperCAmelCase__ ( self : Dict ) -> deque[Process]: """simple docstring""" for i in range(self.number_of_queues - 1 ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.round_robin( self.ready_queue , self.time_slices[i] ) # the last queue has first_come_first_served algorithm self.first_come_first_served(self.ready_queue ) return self.finish_queue if __name__ == "__main__": import doctest UpperCAmelCase : Tuple = Process('P1', 0, 5_3) UpperCAmelCase : List[Any] = Process('P2', 0, 1_7) UpperCAmelCase : List[Any] = Process('P3', 0, 6_8) UpperCAmelCase : List[str] = Process('P4', 0, 2_4) UpperCAmelCase : Dict = 3 UpperCAmelCase : Any = [1_7, 2_5] UpperCAmelCase : int = deque([Pa, Pa, Pa, Pa]) if len(time_slices) != number_of_queues - 1: raise SystemExit(0) doctest.testmod(extraglobs={'queue': deque([Pa, Pa, Pa, Pa])}) UpperCAmelCase : int = Process('P1', 0, 5_3) UpperCAmelCase : str = Process('P2', 0, 1_7) UpperCAmelCase : List[Any] = Process('P3', 0, 6_8) UpperCAmelCase : Dict = Process('P4', 0, 2_4) UpperCAmelCase : Any = 3 UpperCAmelCase : List[Any] = [1_7, 2_5] UpperCAmelCase : Union[str, Any] = deque([Pa, Pa, Pa, Pa]) UpperCAmelCase : List[Any] = MLFQ(number_of_queues, time_slices, queue, 0) UpperCAmelCase : int = mlfq.multi_level_feedback_queue() # print total waiting times of processes(P1, P2, P3, P4) print( f"""waiting time:\ \t\t\t{MLFQ.calculate_waiting_time(mlfq, [Pa, Pa, Pa, Pa])}""" ) # print completion times of processes(P1, P2, P3, P4) print( f"""completion time:\ \t\t{MLFQ.calculate_completion_time(mlfq, [Pa, Pa, Pa, Pa])}""" ) # print total turnaround times of processes(P1, P2, P3, P4) print( f"""turnaround time:\ \t\t{MLFQ.calculate_turnaround_time(mlfq, [Pa, Pa, Pa, Pa])}""" ) # print sequence of finished processes print( f"""sequence of finished processes:\ {mlfq.calculate_sequence_of_finish_queue()}""" )
267
'''simple docstring''' import math from enum import Enum from typing import Optional, Union from torch.optim import Optimizer from torch.optim.lr_scheduler import LambdaLR from .utils import logging UpperCAmelCase : str = logging.get_logger(__name__) class lowerCAmelCase__ ( a ): """simple docstring""" lowerCAmelCase__ = "linear" lowerCAmelCase__ = "cosine" lowerCAmelCase__ = "cosine_with_restarts" lowerCAmelCase__ = "polynomial" lowerCAmelCase__ = "constant" lowerCAmelCase__ = "constant_with_warmup" lowerCAmelCase__ = "piecewise_constant" def a__ ( a__ , a__ = -1 ): """simple docstring""" return LambdaLR(a__ , lambda a__ : 1 , last_epoch=a__ ) def a__ ( a__ , a__ , a__ = -1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1.0 , a__ ) ) return 1.0 return LambdaLR(a__ , a__ , last_epoch=a__ ) def a__ ( a__ , a__ , a__ = -1 ): """simple docstring""" __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = step_rules.split(""",""" ) for rule_str in rule_list[:-1]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = rule_str.split(""":""" ) __SCREAMING_SNAKE_CASE = int(a__ ) __SCREAMING_SNAKE_CASE = float(a__ ) __SCREAMING_SNAKE_CASE = value __SCREAMING_SNAKE_CASE = float(rule_list[-1] ) def create_rules_function(a__ , a__ ): def rule_func(a__ ) -> float: __SCREAMING_SNAKE_CASE = sorted(rules_dict.keys() ) for i, sorted_step in enumerate(a__ ): if steps < sorted_step: return rules_dict[sorted_steps[i]] return last_lr_multiple return rule_func __SCREAMING_SNAKE_CASE = create_rules_function(a__ , a__ ) return LambdaLR(a__ , a__ , last_epoch=a__ ) def a__ ( a__ , a__ , a__ , a__=-1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) return max( 0.0 , float(num_training_steps - current_step ) / float(max(1 , num_training_steps - num_warmup_steps ) ) ) return LambdaLR(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ , a__ = 0.5 , a__ = -1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) __SCREAMING_SNAKE_CASE = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * float(a__ ) * 2.0 * progress )) ) return LambdaLR(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ , a__ = 1 , a__ = -1 ): """simple docstring""" def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) __SCREAMING_SNAKE_CASE = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) if progress >= 1.0: return 0.0 return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * ((float(a__ ) * progress) % 1.0) )) ) return LambdaLR(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ , a__=1E-7 , a__=1.0 , a__=-1 ): """simple docstring""" __SCREAMING_SNAKE_CASE = optimizer.defaults["""lr"""] if not (lr_init > lr_end): raise ValueError(F'lr_end ({lr_end}) must be be smaller than initial lr ({lr_init})' ) def lr_lambda(a__ ): if current_step < num_warmup_steps: return float(a__ ) / float(max(1 , a__ ) ) elif current_step > num_training_steps: return lr_end / lr_init # as LambdaLR multiplies by lr_init else: __SCREAMING_SNAKE_CASE = lr_init - lr_end __SCREAMING_SNAKE_CASE = num_training_steps - num_warmup_steps __SCREAMING_SNAKE_CASE = 1 - (current_step - num_warmup_steps) / decay_steps __SCREAMING_SNAKE_CASE = lr_range * pct_remaining**power + lr_end return decay / lr_init # as LambdaLR multiplies by lr_init return LambdaLR(a__ , a__ , a__ ) UpperCAmelCase : Optional[Any] = { SchedulerType.LINEAR: get_linear_schedule_with_warmup, SchedulerType.COSINE: get_cosine_schedule_with_warmup, SchedulerType.COSINE_WITH_RESTARTS: get_cosine_with_hard_restarts_schedule_with_warmup, SchedulerType.POLYNOMIAL: get_polynomial_decay_schedule_with_warmup, SchedulerType.CONSTANT: get_constant_schedule, SchedulerType.CONSTANT_WITH_WARMUP: get_constant_schedule_with_warmup, SchedulerType.PIECEWISE_CONSTANT: get_piecewise_constant_schedule, } def a__ ( a__ , a__ , a__ = None , a__ = None , a__ = None , a__ = 1 , a__ = 1.0 , a__ = -1 , ): """simple docstring""" __SCREAMING_SNAKE_CASE = SchedulerType(a__ ) __SCREAMING_SNAKE_CASE = TYPE_TO_SCHEDULER_FUNCTION[name] if name == SchedulerType.CONSTANT: return schedule_func(a__ , last_epoch=a__ ) if name == SchedulerType.PIECEWISE_CONSTANT: return schedule_func(a__ , step_rules=a__ , last_epoch=a__ ) # All other schedulers require `num_warmup_steps` if num_warmup_steps is None: raise ValueError(F'{name} requires `num_warmup_steps`, please provide that argument.' ) if name == SchedulerType.CONSTANT_WITH_WARMUP: return schedule_func(a__ , num_warmup_steps=a__ , last_epoch=a__ ) # All other schedulers require `num_training_steps` if num_training_steps is None: raise ValueError(F'{name} requires `num_training_steps`, please provide that argument.' ) if name == SchedulerType.COSINE_WITH_RESTARTS: return schedule_func( a__ , num_warmup_steps=a__ , num_training_steps=a__ , num_cycles=a__ , last_epoch=a__ , ) if name == SchedulerType.POLYNOMIAL: return schedule_func( a__ , num_warmup_steps=a__ , num_training_steps=a__ , power=a__ , last_epoch=a__ , ) return schedule_func( a__ , num_warmup_steps=a__ , num_training_steps=a__ , last_epoch=a__ )
267
1
'''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] ) -> Optional[int]: """simple docstring""" torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = 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 : List[Any] ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.dummy_uncond_unet __SCREAMING_SNAKE_CASE = PNDMScheduler() __SCREAMING_SNAKE_CASE = PNDMPipeline(unet=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE ) pndm.to(__SCREAMING_SNAKE_CASE ) pndm.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pndm(generator=__SCREAMING_SNAKE_CASE , num_inference_steps=20 , output_type="""numpy""" ).images __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pndm(generator=__SCREAMING_SNAKE_CASE , num_inference_steps=20 , output_type="""numpy""" , return_dict=__SCREAMING_SNAKE_CASE )[0] __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] __SCREAMING_SNAKE_CASE = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __SCREAMING_SNAKE_CASE = 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 : Optional[int] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = """google/ddpm-cifar10-32""" __SCREAMING_SNAKE_CASE = UNetaDModel.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = PNDMScheduler() __SCREAMING_SNAKE_CASE = PNDMPipeline(unet=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE ) pndm.to(__SCREAMING_SNAKE_CASE ) pndm.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pndm(generator=__SCREAMING_SNAKE_CASE , output_type="""numpy""" ).images __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __SCREAMING_SNAKE_CASE = np.array([0.1564, 0.14645, 0.1406, 0.14715, 0.12425, 0.14045, 0.13115, 0.12175, 0.125] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
267
'''simple docstring''' import argparse import os from . import ( ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, BART_PRETRAINED_MODEL_ARCHIVE_LIST, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, AlbertConfig, BartConfig, BertConfig, CamembertConfig, CTRLConfig, DistilBertConfig, DPRConfig, ElectraConfig, FlaubertConfig, GPTaConfig, LayoutLMConfig, LxmertConfig, OpenAIGPTConfig, RobertaConfig, TaConfig, TFAlbertForPreTraining, TFBartForConditionalGeneration, TFBartForSequenceClassification, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFCamembertForMaskedLM, TFCTRLLMHeadModel, TFDistilBertForMaskedLM, TFDistilBertForQuestionAnswering, TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, TFElectraForPreTraining, TFFlaubertWithLMHeadModel, TFGPTaLMHeadModel, TFLayoutLMForMaskedLM, TFLxmertForPreTraining, TFLxmertVisualFeatureEncoder, TFOpenAIGPTLMHeadModel, TFRobertaForCausalLM, TFRobertaForMaskedLM, TFRobertaForSequenceClassification, TFTaForConditionalGeneration, TFTransfoXLLMHeadModel, TFWavaVecaModel, TFXLMRobertaForMaskedLM, TFXLMWithLMHeadModel, TFXLNetLMHeadModel, TransfoXLConfig, WavaVecaConfig, WavaVecaModel, XLMConfig, XLMRobertaConfig, XLNetConfig, is_torch_available, load_pytorch_checkpoint_in_tfa_model, ) from .utils import CONFIG_NAME, WEIGHTS_NAME, cached_file, logging if is_torch_available(): import numpy as np import torch from . import ( AlbertForPreTraining, BartForConditionalGeneration, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, CamembertForMaskedLM, CTRLLMHeadModel, DistilBertForMaskedLM, DistilBertForQuestionAnswering, DPRContextEncoder, DPRQuestionEncoder, DPRReader, ElectraForPreTraining, FlaubertWithLMHeadModel, GPTaLMHeadModel, LayoutLMForMaskedLM, LxmertForPreTraining, LxmertVisualFeatureEncoder, OpenAIGPTLMHeadModel, RobertaForMaskedLM, RobertaForSequenceClassification, TaForConditionalGeneration, TransfoXLLMHeadModel, XLMRobertaForMaskedLM, XLMWithLMHeadModel, XLNetLMHeadModel, ) logging.set_verbosity_info() UpperCAmelCase : Tuple = { 'bart': ( BartConfig, TFBartForConditionalGeneration, TFBartForSequenceClassification, BartForConditionalGeneration, BART_PRETRAINED_MODEL_ARCHIVE_LIST, ), 'bert': ( BertConfig, TFBertForPreTraining, BertForPreTraining, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'bert-large-uncased-whole-word-masking-finetuned-squad': ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'bert-large-cased-whole-word-masking-finetuned-squad': ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'bert-base-cased-finetuned-mrpc': ( BertConfig, TFBertForSequenceClassification, BertForSequenceClassification, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'dpr': ( DPRConfig, TFDPRQuestionEncoder, TFDPRContextEncoder, TFDPRReader, DPRQuestionEncoder, DPRContextEncoder, DPRReader, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ), 'gpt2': ( GPTaConfig, TFGPTaLMHeadModel, GPTaLMHeadModel, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'xlnet': ( XLNetConfig, TFXLNetLMHeadModel, XLNetLMHeadModel, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'xlm': ( XLMConfig, TFXLMWithLMHeadModel, XLMWithLMHeadModel, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'xlm-roberta': ( XLMRobertaConfig, TFXLMRobertaForMaskedLM, XLMRobertaForMaskedLM, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'transfo-xl': ( TransfoXLConfig, TFTransfoXLLMHeadModel, TransfoXLLMHeadModel, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'openai-gpt': ( OpenAIGPTConfig, TFOpenAIGPTLMHeadModel, OpenAIGPTLMHeadModel, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'roberta': ( RobertaConfig, TFRobertaForCausalLM, TFRobertaForMaskedLM, RobertaForMaskedLM, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'layoutlm': ( LayoutLMConfig, TFLayoutLMForMaskedLM, LayoutLMForMaskedLM, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, ), 'roberta-large-mnli': ( RobertaConfig, TFRobertaForSequenceClassification, RobertaForSequenceClassification, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'camembert': ( CamembertConfig, TFCamembertForMaskedLM, CamembertForMaskedLM, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'flaubert': ( FlaubertConfig, TFFlaubertWithLMHeadModel, FlaubertWithLMHeadModel, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'distilbert': ( DistilBertConfig, TFDistilBertForMaskedLM, DistilBertForMaskedLM, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'distilbert-base-distilled-squad': ( DistilBertConfig, TFDistilBertForQuestionAnswering, DistilBertForQuestionAnswering, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'lxmert': ( LxmertConfig, TFLxmertForPreTraining, LxmertForPreTraining, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'lxmert-visual-feature-encoder': ( LxmertConfig, TFLxmertVisualFeatureEncoder, LxmertVisualFeatureEncoder, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'ctrl': ( CTRLConfig, TFCTRLLMHeadModel, CTRLLMHeadModel, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'albert': ( AlbertConfig, TFAlbertForPreTraining, AlbertForPreTraining, ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 't5': ( TaConfig, TFTaForConditionalGeneration, TaForConditionalGeneration, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'electra': ( ElectraConfig, TFElectraForPreTraining, ElectraForPreTraining, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'wav2vec2': ( WavaVecaConfig, TFWavaVecaModel, WavaVecaModel, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), } def a__ ( a__ , a__ , a__ , a__ , a__=False , a__=True ): """simple docstring""" if model_type not in MODEL_CLASSES: raise ValueError(F'Unrecognized model type, should be one of {list(MODEL_CLASSES.keys() )}.' ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = MODEL_CLASSES[model_type] # Initialise TF model if config_file in aws_config_map: __SCREAMING_SNAKE_CASE = cached_file(a__ , a__ , force_download=not use_cached_models ) __SCREAMING_SNAKE_CASE = config_class.from_json_file(a__ ) __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = True print(F'Building TensorFlow model from configuration: {config}' ) __SCREAMING_SNAKE_CASE = model_class(a__ ) # Load weights from tf checkpoint if pytorch_checkpoint_path in aws_config_map.keys(): __SCREAMING_SNAKE_CASE = cached_file( a__ , a__ , force_download=not use_cached_models ) # Load PyTorch checkpoint in tf2 model: __SCREAMING_SNAKE_CASE = load_pytorch_checkpoint_in_tfa_model(a__ , a__ ) if compare_with_pt_model: __SCREAMING_SNAKE_CASE = tf_model(tf_model.dummy_inputs , training=a__ ) # build the network __SCREAMING_SNAKE_CASE = torch.load(a__ , map_location="""cpu""" ) __SCREAMING_SNAKE_CASE = pt_model_class.from_pretrained( pretrained_model_name_or_path=a__ , config=a__ , state_dict=a__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = pt_model(**pt_model.dummy_inputs ) __SCREAMING_SNAKE_CASE = pto[0].numpy() __SCREAMING_SNAKE_CASE = tfo[0].numpy() __SCREAMING_SNAKE_CASE = np.amax(np.abs(np_pt - np_tf ) ) print(F'Max absolute difference between models outputs {diff}' ) assert diff <= 2E-2, F'Error, model absolute difference is >2e-2: {diff}' # Save pytorch-model print(F'Save TensorFlow model to {tf_dump_path}' ) tf_model.save_weights(a__ , save_format="""h5""" ) def a__ ( a__ , a__ , a__=None , a__=None , a__=False , a__=False , a__=False , a__=False , ): """simple docstring""" if args_model_type is None: __SCREAMING_SNAKE_CASE = list(MODEL_CLASSES.keys() ) else: __SCREAMING_SNAKE_CASE = [args_model_type] for j, model_type in enumerate(a__ , start=1 ): print("""=""" * 1_00 ) print(F' Converting model type {j}/{len(a__ )}: {model_type}' ) print("""=""" * 1_00 ) if model_type not in MODEL_CLASSES: raise ValueError(F'Unrecognized model type {model_type}, should be one of {list(MODEL_CLASSES.keys() )}.' ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = MODEL_CLASSES[model_type] if model_shortcut_names_or_path is None: __SCREAMING_SNAKE_CASE = list(aws_model_maps.keys() ) if config_shortcut_names_or_path is None: __SCREAMING_SNAKE_CASE = model_shortcut_names_or_path for i, (model_shortcut_name, config_shortcut_name) in enumerate( zip(a__ , a__ ) , start=1 ): print("""-""" * 1_00 ) if "-squad" in model_shortcut_name or "-mrpc" in model_shortcut_name or "-mnli" in model_shortcut_name: if not only_convert_finetuned_models: print(F' Skipping finetuned checkpoint {model_shortcut_name}' ) continue __SCREAMING_SNAKE_CASE = model_shortcut_name elif only_convert_finetuned_models: print(F' Skipping not finetuned checkpoint {model_shortcut_name}' ) continue print( F' Converting checkpoint {i}/{len(a__ )}: {model_shortcut_name} - model_type {model_type}' ) print("""-""" * 1_00 ) if config_shortcut_name in aws_config_map: __SCREAMING_SNAKE_CASE = cached_file(a__ , a__ , force_download=not use_cached_models ) else: __SCREAMING_SNAKE_CASE = config_shortcut_name if model_shortcut_name in aws_model_maps: __SCREAMING_SNAKE_CASE = cached_file(a__ , a__ , force_download=not use_cached_models ) else: __SCREAMING_SNAKE_CASE = model_shortcut_name if os.path.isfile(a__ ): __SCREAMING_SNAKE_CASE = """converted_model""" convert_pt_checkpoint_to_tf( model_type=a__ , pytorch_checkpoint_path=a__ , config_file=a__ , tf_dump_path=os.path.join(a__ , model_shortcut_name + """-tf_model.h5""" ) , compare_with_pt_model=a__ , ) if remove_cached_files: os.remove(a__ ) os.remove(a__ ) if __name__ == "__main__": UpperCAmelCase : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--tf_dump_path', default=None, type=str, required=True, help='Path to the output Tensorflow dump file.' ) parser.add_argument( '--model_type', default=None, type=str, help=( f"""Model type selected in the list of {list(MODEL_CLASSES.keys())}. If not given, will download and """ 'convert all the models from AWS.' ), ) parser.add_argument( '--pytorch_checkpoint_path', default=None, type=str, help=( 'Path to the PyTorch checkpoint path or shortcut name to download from AWS. ' 'If not given, will download and convert all the checkpoints from AWS.' ), ) parser.add_argument( '--config_file', default=None, type=str, help=( 'The config json file corresponding to the pre-trained model. \n' 'This specifies the model architecture. If not given and ' '--pytorch_checkpoint_path is not given or is a shortcut name ' 'use the configuration associated to the shortcut name on the AWS' ), ) parser.add_argument( '--compare_with_pt_model', action='store_true', help='Compare Tensorflow and PyTorch model predictions.' ) parser.add_argument( '--use_cached_models', action='store_true', help='Use cached models if possible instead of updating to latest checkpoint versions.', ) parser.add_argument( '--remove_cached_files', action='store_true', help='Remove pytorch models after conversion (save memory when converting in batches).', ) parser.add_argument('--only_convert_finetuned_models', action='store_true', help='Only convert finetuned models.') UpperCAmelCase : List[Any] = parser.parse_args() # if args.pytorch_checkpoint_path is not None: # convert_pt_checkpoint_to_tf(args.model_type.lower(), # args.pytorch_checkpoint_path, # args.config_file if args.config_file is not None else args.pytorch_checkpoint_path, # args.tf_dump_path, # compare_with_pt_model=args.compare_with_pt_model, # use_cached_models=args.use_cached_models) # else: convert_all_pt_checkpoints_to_tf( args.model_type.lower() if args.model_type is not None else None, args.tf_dump_path, model_shortcut_names_or_path=[args.pytorch_checkpoint_path] if args.pytorch_checkpoint_path is not None else None, config_shortcut_names_or_path=[args.config_file] if args.config_file is not None else None, compare_with_pt_model=args.compare_with_pt_model, use_cached_models=args.use_cached_models, remove_cached_files=args.remove_cached_files, only_convert_finetuned_models=args.only_convert_finetuned_models, )
267
1
'''simple docstring''' import argparse import numpy as np import torch from transformers import SpeechTaHifiGan, SpeechTaHifiGanConfig, logging logging.set_verbosity_info() UpperCAmelCase : Optional[int] = logging.get_logger('transformers.models.speecht5') def a__ ( a__ , a__ , a__ ): """simple docstring""" hf_model.apply_weight_norm() __SCREAMING_SNAKE_CASE = checkpoint["""input_conv.weight_g"""] __SCREAMING_SNAKE_CASE = checkpoint["""input_conv.weight_v"""] __SCREAMING_SNAKE_CASE = checkpoint["""input_conv.bias"""] for i in range(len(config.upsample_rates ) ): __SCREAMING_SNAKE_CASE = checkpoint[F'upsamples.{i}.1.weight_g'] __SCREAMING_SNAKE_CASE = checkpoint[F'upsamples.{i}.1.weight_v'] __SCREAMING_SNAKE_CASE = checkpoint[F'upsamples.{i}.1.bias'] for i in range(len(config.upsample_rates ) * len(config.resblock_kernel_sizes ) ): for j in range(len(config.resblock_dilation_sizes ) ): __SCREAMING_SNAKE_CASE = checkpoint[F'blocks.{i}.convs1.{j}.1.weight_g'] __SCREAMING_SNAKE_CASE = checkpoint[F'blocks.{i}.convs1.{j}.1.weight_v'] __SCREAMING_SNAKE_CASE = checkpoint[F'blocks.{i}.convs1.{j}.1.bias'] __SCREAMING_SNAKE_CASE = checkpoint[F'blocks.{i}.convs2.{j}.1.weight_g'] __SCREAMING_SNAKE_CASE = checkpoint[F'blocks.{i}.convs2.{j}.1.weight_v'] __SCREAMING_SNAKE_CASE = checkpoint[F'blocks.{i}.convs2.{j}.1.bias'] __SCREAMING_SNAKE_CASE = checkpoint["""output_conv.1.weight_g"""] __SCREAMING_SNAKE_CASE = checkpoint["""output_conv.1.weight_v"""] __SCREAMING_SNAKE_CASE = checkpoint["""output_conv.1.bias"""] hf_model.remove_weight_norm() @torch.no_grad() def a__ ( a__ , a__ , a__ , a__=None , a__=None , ): """simple docstring""" if config_path is not None: __SCREAMING_SNAKE_CASE = SpeechTaHifiGanConfig.from_pretrained(a__ ) else: __SCREAMING_SNAKE_CASE = SpeechTaHifiGanConfig() __SCREAMING_SNAKE_CASE = SpeechTaHifiGan(a__ ) __SCREAMING_SNAKE_CASE = torch.load(a__ ) load_weights(orig_checkpoint["""model"""]["""generator"""] , a__ , a__ ) __SCREAMING_SNAKE_CASE = np.load(a__ ) __SCREAMING_SNAKE_CASE = stats[0].reshape(-1 ) __SCREAMING_SNAKE_CASE = stats[1].reshape(-1 ) __SCREAMING_SNAKE_CASE = torch.from_numpy(a__ ).float() __SCREAMING_SNAKE_CASE = torch.from_numpy(a__ ).float() model.save_pretrained(a__ ) if repo_id: print("""Pushing to the hub...""" ) model.push_to_hub(a__ ) if __name__ == "__main__": UpperCAmelCase : List[str] = argparse.ArgumentParser() parser.add_argument('--checkpoint_path', required=True, default=None, type=str, help='Path to original checkpoint') parser.add_argument('--stats_path', required=True, default=None, type=str, help='Path to stats.npy file') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') parser.add_argument( '--pytorch_dump_folder_path', required=True, default=None, type=str, help='Path to the output PyTorch model.' ) parser.add_argument( '--push_to_hub', default=None, type=str, help='Where to upload the converted model on the 🤗 hub.' ) UpperCAmelCase : Any = parser.parse_args() convert_hifigan_checkpoint( args.checkpoint_path, args.stats_path, args.pytorch_dump_folder_path, args.config_path, args.push_to_hub, )
267
'''simple docstring''' def a__ ( a__ ): """simple docstring""" if isinstance(a__ , a__ ): raise TypeError("""'float' object cannot be interpreted as an integer""" ) if isinstance(a__ , a__ ): raise TypeError("""'str' object cannot be interpreted as an integer""" ) if num == 0: return "0b0" __SCREAMING_SNAKE_CASE = False if num < 0: __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = -num __SCREAMING_SNAKE_CASE = [] while num > 0: binary.insert(0 , num % 2 ) num >>= 1 if negative: return "-0b" + "".join(str(a__ ) for e in binary ) return "0b" + "".join(str(a__ ) for e in binary ) if __name__ == "__main__": import doctest doctest.testmod()
267
1
'''simple docstring''' import inspect from typing import Callable, List, Optional, Union import torch from transformers import ( CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, WhisperForConditionalGeneration, WhisperProcessor, ) from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.utils import logging UpperCAmelCase : List[Any] = logging.get_logger(__name__) # pylint: disable=invalid-name class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : WhisperForConditionalGeneration , __SCREAMING_SNAKE_CASE : WhisperProcessor , __SCREAMING_SNAKE_CASE : AutoencoderKL , __SCREAMING_SNAKE_CASE : CLIPTextModel , __SCREAMING_SNAKE_CASE : CLIPTokenizer , __SCREAMING_SNAKE_CASE : UNetaDConditionModel , __SCREAMING_SNAKE_CASE : Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] , __SCREAMING_SNAKE_CASE : StableDiffusionSafetyChecker , __SCREAMING_SNAKE_CASE : CLIPImageProcessor , ) -> int: """simple docstring""" super().__init__() if safety_checker is None: logger.warning( f'You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure' """ that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered""" """ results in services or applications open to the public. Both the diffusers team and Hugging Face""" """ strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling""" """ it only for use-cases that involve analyzing network behavior or auditing its results. For more""" """ information, please have a look at https://github.com/huggingface/diffusers/pull/254 .""" ) self.register_modules( speech_model=__SCREAMING_SNAKE_CASE , speech_processor=__SCREAMING_SNAKE_CASE , vae=__SCREAMING_SNAKE_CASE , text_encoder=__SCREAMING_SNAKE_CASE , tokenizer=__SCREAMING_SNAKE_CASE , unet=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE , feature_extractor=__SCREAMING_SNAKE_CASE , ) def UpperCAmelCase__ ( self : Tuple , __SCREAMING_SNAKE_CASE : Optional[Union[str, int]] = "auto" ) -> int: """simple docstring""" if slice_size == "auto": __SCREAMING_SNAKE_CASE = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Dict ) -> Optional[Any]: """simple docstring""" self.enable_attention_slicing(__SCREAMING_SNAKE_CASE ) @torch.no_grad() def __call__( self : Optional[int] , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : Tuple=16_000 , __SCREAMING_SNAKE_CASE : int = 512 , __SCREAMING_SNAKE_CASE : int = 512 , __SCREAMING_SNAKE_CASE : int = 50 , __SCREAMING_SNAKE_CASE : float = 7.5 , __SCREAMING_SNAKE_CASE : Optional[Union[str, List[str]]] = None , __SCREAMING_SNAKE_CASE : Optional[int] = 1 , __SCREAMING_SNAKE_CASE : float = 0.0 , __SCREAMING_SNAKE_CASE : Optional[torch.Generator] = None , __SCREAMING_SNAKE_CASE : Optional[torch.FloatTensor] = None , __SCREAMING_SNAKE_CASE : Optional[str] = "pil" , __SCREAMING_SNAKE_CASE : bool = True , __SCREAMING_SNAKE_CASE : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __SCREAMING_SNAKE_CASE : int = 1 , **__SCREAMING_SNAKE_CASE : str , ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.speech_processor.feature_extractor( __SCREAMING_SNAKE_CASE , return_tensors="""pt""" , sampling_rate=__SCREAMING_SNAKE_CASE ).input_features.to(self.device ) __SCREAMING_SNAKE_CASE = self.speech_model.generate(__SCREAMING_SNAKE_CASE , max_length=480_000 ) __SCREAMING_SNAKE_CASE = self.speech_processor.tokenizer.batch_decode(__SCREAMING_SNAKE_CASE , skip_special_tokens=__SCREAMING_SNAKE_CASE , normalize=__SCREAMING_SNAKE_CASE )[ 0 ] if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): __SCREAMING_SNAKE_CASE = 1 elif isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): __SCREAMING_SNAKE_CASE = len(__SCREAMING_SNAKE_CASE ) else: raise ValueError(f'`prompt` has to be of type `str` or `list` but is {type(__SCREAMING_SNAKE_CASE )}' ) if height % 8 != 0 or width % 8 != 0: raise ValueError(f'`height` and `width` have to be divisible by 8 but are {height} and {width}.' ) if (callback_steps is None) or ( callback_steps is not None and (not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) or callback_steps <= 0) ): raise ValueError( f'`callback_steps` has to be a positive integer but is {callback_steps} of type' f' {type(__SCREAMING_SNAKE_CASE )}.' ) # get prompt text embeddings __SCREAMING_SNAKE_CASE = self.tokenizer( __SCREAMING_SNAKE_CASE , padding="""max_length""" , max_length=self.tokenizer.model_max_length , return_tensors="""pt""" , ) __SCREAMING_SNAKE_CASE = text_inputs.input_ids if text_input_ids.shape[-1] > self.tokenizer.model_max_length: __SCREAMING_SNAKE_CASE = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :] ) logger.warning( """The following part of your input was truncated because CLIP can only handle sequences up to""" f' {self.tokenizer.model_max_length} tokens: {removed_text}' ) __SCREAMING_SNAKE_CASE = text_input_ids[:, : self.tokenizer.model_max_length] __SCREAMING_SNAKE_CASE = self.text_encoder(text_input_ids.to(self.device ) )[0] # duplicate text embeddings for each generation per prompt, using mps friendly method __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = text_embeddings.shape __SCREAMING_SNAKE_CASE = text_embeddings.repeat(1 , __SCREAMING_SNAKE_CASE , 1 ) __SCREAMING_SNAKE_CASE = text_embeddings.view(bs_embed * num_images_per_prompt , __SCREAMING_SNAKE_CASE , -1 ) # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. __SCREAMING_SNAKE_CASE = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: __SCREAMING_SNAKE_CASE = 42 if negative_prompt is None: __SCREAMING_SNAKE_CASE = [""""""] * batch_size elif type(__SCREAMING_SNAKE_CASE ) is not type(__SCREAMING_SNAKE_CASE ): raise TypeError( f'`negative_prompt` should be the same type to `prompt`, but got {type(__SCREAMING_SNAKE_CASE )} !=' f' {type(__SCREAMING_SNAKE_CASE )}.' ) elif isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): __SCREAMING_SNAKE_CASE = [negative_prompt] elif batch_size != len(__SCREAMING_SNAKE_CASE ): raise ValueError( f'`negative_prompt`: {negative_prompt} has batch size {len(__SCREAMING_SNAKE_CASE )}, but `prompt`:' f' {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches' """ the batch size of `prompt`.""" ) else: __SCREAMING_SNAKE_CASE = negative_prompt __SCREAMING_SNAKE_CASE = text_input_ids.shape[-1] __SCREAMING_SNAKE_CASE = self.tokenizer( __SCREAMING_SNAKE_CASE , padding="""max_length""" , max_length=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , return_tensors="""pt""" , ) __SCREAMING_SNAKE_CASE = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt, using mps friendly method __SCREAMING_SNAKE_CASE = uncond_embeddings.shape[1] __SCREAMING_SNAKE_CASE = uncond_embeddings.repeat(1 , __SCREAMING_SNAKE_CASE , 1 ) __SCREAMING_SNAKE_CASE = uncond_embeddings.view(batch_size * num_images_per_prompt , __SCREAMING_SNAKE_CASE , -1 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes __SCREAMING_SNAKE_CASE = torch.cat([uncond_embeddings, text_embeddings] ) # get the initial random noise unless the user supplied it # Unlike in other pipelines, latents need to be generated in the target device # for 1-to-1 results reproducibility with the CompVis implementation. # However this currently doesn't work in `mps`. __SCREAMING_SNAKE_CASE = (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8) __SCREAMING_SNAKE_CASE = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not exist on mps __SCREAMING_SNAKE_CASE = torch.randn(__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , device="""cpu""" , dtype=__SCREAMING_SNAKE_CASE ).to( self.device ) else: __SCREAMING_SNAKE_CASE = torch.randn(__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , device=self.device , dtype=__SCREAMING_SNAKE_CASE ) else: if latents.shape != latents_shape: raise ValueError(f'Unexpected latents shape, got {latents.shape}, expected {latents_shape}' ) __SCREAMING_SNAKE_CASE = latents.to(self.device ) # set timesteps self.scheduler.set_timesteps(__SCREAMING_SNAKE_CASE ) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand __SCREAMING_SNAKE_CASE = self.scheduler.timesteps.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler __SCREAMING_SNAKE_CASE = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] __SCREAMING_SNAKE_CASE = """eta""" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) __SCREAMING_SNAKE_CASE = {} if accepts_eta: __SCREAMING_SNAKE_CASE = eta for i, t in enumerate(self.progress_bar(__SCREAMING_SNAKE_CASE ) ): # expand the latents if we are doing classifier free guidance __SCREAMING_SNAKE_CASE = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents __SCREAMING_SNAKE_CASE = self.scheduler.scale_model_input(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # predict the noise residual __SCREAMING_SNAKE_CASE = self.unet(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , encoder_hidden_states=__SCREAMING_SNAKE_CASE ).sample # perform guidance if do_classifier_free_guidance: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = noise_pred.chunk(2 ) __SCREAMING_SNAKE_CASE = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # compute the previous noisy sample x_t -> x_t-1 __SCREAMING_SNAKE_CASE = self.scheduler.step(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ).prev_sample # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = 1 / 0.18215 * latents __SCREAMING_SNAKE_CASE = self.vae.decode(__SCREAMING_SNAKE_CASE ).sample __SCREAMING_SNAKE_CASE = (image / 2 + 0.5).clamp(0 , 1 ) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 __SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": __SCREAMING_SNAKE_CASE = self.numpy_to_pil(__SCREAMING_SNAKE_CASE ) if not return_dict: return image return StableDiffusionPipelineOutput(images=__SCREAMING_SNAKE_CASE , nsfw_content_detected=__SCREAMING_SNAKE_CASE )
267
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices UpperCAmelCase : Optional[int] = logging.get_logger(__name__) UpperCAmelCase : str = { 'facebook/convnextv2-tiny-1k-224': 'https://huggingface.co/facebook/convnextv2-tiny-1k-224/resolve/main/config.json', } class lowerCAmelCase__ ( a , a ): """simple docstring""" lowerCAmelCase__ = "convnextv2" def __init__( self : Any , __SCREAMING_SNAKE_CASE : int=3 , __SCREAMING_SNAKE_CASE : Dict=4 , __SCREAMING_SNAKE_CASE : List[Any]=4 , __SCREAMING_SNAKE_CASE : Optional[int]=None , __SCREAMING_SNAKE_CASE : Dict=None , __SCREAMING_SNAKE_CASE : Optional[int]="gelu" , __SCREAMING_SNAKE_CASE : Union[str, Any]=0.02 , __SCREAMING_SNAKE_CASE : Dict=1E-12 , __SCREAMING_SNAKE_CASE : List[str]=0.0 , __SCREAMING_SNAKE_CASE : Optional[Any]=224 , __SCREAMING_SNAKE_CASE : Tuple=None , __SCREAMING_SNAKE_CASE : List[str]=None , **__SCREAMING_SNAKE_CASE : Union[str, Any] , ) -> Union[str, Any]: """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = patch_size __SCREAMING_SNAKE_CASE = num_stages __SCREAMING_SNAKE_CASE = [96, 192, 384, 768] if hidden_sizes is None else hidden_sizes __SCREAMING_SNAKE_CASE = [3, 3, 9, 3] if depths is None else depths __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = drop_path_rate __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = ["""stem"""] + [f'stage{idx}' for idx in range(1 , len(self.depths ) + 1 )] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = get_aligned_output_features_output_indices( out_features=__SCREAMING_SNAKE_CASE , out_indices=__SCREAMING_SNAKE_CASE , stage_names=self.stage_names )
267
1
'''simple docstring''' import inspect import unittest import torch import torch.nn as nn from accelerate.hooks import ( AlignDevicesHook, ModelHook, SequentialHook, add_hook_to_module, attach_align_device_hook, remove_hook_from_module, remove_hook_from_submodules, ) from accelerate.test_utils import require_multi_gpu class lowerCAmelCase__ ( nn.Module ): """simple docstring""" def __init__( self : Optional[Any] ) -> Optional[int]: """simple docstring""" super().__init__() __SCREAMING_SNAKE_CASE = nn.Linear(3 , 4 ) __SCREAMING_SNAKE_CASE = nn.BatchNormad(4 ) __SCREAMING_SNAKE_CASE = nn.Linear(4 , 5 ) def UpperCAmelCase__ ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> Dict: """simple docstring""" return self.lineara(self.batchnorm(self.lineara(__SCREAMING_SNAKE_CASE ) ) ) class lowerCAmelCase__ ( a ): """simple docstring""" def UpperCAmelCase__ ( self : Optional[int] , __SCREAMING_SNAKE_CASE : Dict , *__SCREAMING_SNAKE_CASE : str , **__SCREAMING_SNAKE_CASE : Optional[int] ) -> Optional[Any]: """simple docstring""" return (args[0] + 1,) + args[1:], kwargs class lowerCAmelCase__ ( a ): """simple docstring""" def UpperCAmelCase__ ( self : Tuple , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" return output + 1 class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : str ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = ModelForTest() __SCREAMING_SNAKE_CASE = ModelHook() add_hook_to_module(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertEqual(test_model._hf_hook , __SCREAMING_SNAKE_CASE ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """_old_forward""" ) ) # Check adding the hook did not change the name or the signature self.assertEqual(test_model.forward.__name__ , """forward""" ) self.assertListEqual(list(inspect.signature(test_model.forward ).parameters ) , ["""x"""] ) remove_hook_from_module(__SCREAMING_SNAKE_CASE ) self.assertFalse(hasattr(__SCREAMING_SNAKE_CASE , """_hf_hook""" ) ) self.assertFalse(hasattr(__SCREAMING_SNAKE_CASE , """_old_forward""" ) ) def UpperCAmelCase__ ( self : Tuple ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = ModelForTest() __SCREAMING_SNAKE_CASE = ModelHook() add_hook_to_module(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) add_hook_to_module(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , append=__SCREAMING_SNAKE_CASE ) self.assertEqual(isinstance(test_model._hf_hook , __SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) self.assertEqual(len(test_model._hf_hook.hooks ) , 2 ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """_old_forward""" ) ) # Check adding the hook did not change the name or the signature self.assertEqual(test_model.forward.__name__ , """forward""" ) self.assertListEqual(list(inspect.signature(test_model.forward ).parameters ) , ["""x"""] ) remove_hook_from_module(__SCREAMING_SNAKE_CASE ) self.assertFalse(hasattr(__SCREAMING_SNAKE_CASE , """_hf_hook""" ) ) self.assertFalse(hasattr(__SCREAMING_SNAKE_CASE , """_old_forward""" ) ) def UpperCAmelCase__ ( self : int ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = ModelForTest() __SCREAMING_SNAKE_CASE = torch.randn(2 , 3 ) __SCREAMING_SNAKE_CASE = test_model(x + 1 ) __SCREAMING_SNAKE_CASE = test_model(x + 2 ) __SCREAMING_SNAKE_CASE = PreForwardHook() add_hook_to_module(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = test_model(__SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-5 ) ) # Attaching a hook to a model when it already has one replaces, does not chain __SCREAMING_SNAKE_CASE = PreForwardHook() add_hook_to_module(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = test_model(__SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-5 ) ) # You need to use the sequential hook to chain two or more hooks __SCREAMING_SNAKE_CASE = SequentialHook(PreForwardHook() , PreForwardHook() ) add_hook_to_module(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = test_model(__SCREAMING_SNAKE_CASE ) assert torch.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-5 ) def UpperCAmelCase__ ( self : Optional[int] ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = ModelForTest() __SCREAMING_SNAKE_CASE = torch.randn(2 , 3 ) __SCREAMING_SNAKE_CASE = test_model(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = PostForwardHook() add_hook_to_module(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = test_model(__SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(__SCREAMING_SNAKE_CASE , output + 1 , atol=1E-5 ) ) # Attaching a hook to a model when it already has one replaces, does not chain __SCREAMING_SNAKE_CASE = PostForwardHook() add_hook_to_module(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = test_model(__SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(__SCREAMING_SNAKE_CASE , output + 1 , atol=1E-5 ) ) # You need to use the sequential hook to chain two or more hooks __SCREAMING_SNAKE_CASE = SequentialHook(PostForwardHook() , PostForwardHook() ) add_hook_to_module(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = test_model(__SCREAMING_SNAKE_CASE ) assert torch.allclose(__SCREAMING_SNAKE_CASE , output + 2 , atol=1E-5 ) def UpperCAmelCase__ ( self : List[str] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = ModelForTest() __SCREAMING_SNAKE_CASE = torch.randn(2 , 3 ) __SCREAMING_SNAKE_CASE = test_model(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = PostForwardHook() add_hook_to_module(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = test_model(__SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(__SCREAMING_SNAKE_CASE , output + 1 ) ) self.assertTrue(outputa.requires_grad ) __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = test_model(__SCREAMING_SNAKE_CASE ) self.assertFalse(outputa.requires_grad ) @require_multi_gpu def UpperCAmelCase__ ( self : List[Any] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = ModelForTest() # Everything is on CPU self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) # This will move each submodule on different devices add_hook_to_module(model.lineara , AlignDevicesHook(execution_device=0 ) ) add_hook_to_module(model.batchnorm , AlignDevicesHook(execution_device=0 ) ) add_hook_to_module(model.lineara , AlignDevicesHook(execution_device=1 ) ) self.assertEqual(model.lineara.weight.device , torch.device(0 ) ) self.assertEqual(model.batchnorm.weight.device , torch.device(0 ) ) self.assertEqual(model.batchnorm.running_mean.device , torch.device(0 ) ) self.assertEqual(model.lineara.weight.device , torch.device(1 ) ) # We can still make a forward pass. The input does not need to be on any particular device __SCREAMING_SNAKE_CASE = torch.randn(2 , 3 ) __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE ) self.assertEqual(output.device , torch.device(1 ) ) # We can add a general hook to put back output on same device as input. add_hook_to_module(__SCREAMING_SNAKE_CASE , AlignDevicesHook(io_same_device=__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = torch.randn(2 , 3 ).to(0 ) __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE ) self.assertEqual(output.device , torch.device(0 ) ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = ModelForTest() # Everything is on CPU self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) # This will move each submodule on different devices __SCREAMING_SNAKE_CASE = {"""execution_device""": 0 if torch.cuda.is_available() else """cpu""", """offload""": True} add_hook_to_module(model.lineara , AlignDevicesHook(**__SCREAMING_SNAKE_CASE ) ) add_hook_to_module(model.batchnorm , AlignDevicesHook(**__SCREAMING_SNAKE_CASE ) ) add_hook_to_module(model.lineara , AlignDevicesHook(**__SCREAMING_SNAKE_CASE ) ) # Parameters have been offloaded, so on the meta device self.assertEqual(model.lineara.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""meta""" ) ) # Buffers are not included in the offload by default, so are on the execution device __SCREAMING_SNAKE_CASE = torch.device(hook_kwargs["""execution_device"""] ) self.assertEqual(model.batchnorm.running_mean.device , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = torch.randn(2 , 3 ) __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE ) self.assertEqual(output.device , __SCREAMING_SNAKE_CASE ) # Removing hooks loads back the weights in the model. remove_hook_from_module(model.lineara ) remove_hook_from_module(model.batchnorm ) remove_hook_from_module(model.lineara ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) # Now test with buffers included in the offload __SCREAMING_SNAKE_CASE = { """execution_device""": 0 if torch.cuda.is_available() else """cpu""", """offload""": True, """offload_buffers""": True, } add_hook_to_module(model.lineara , AlignDevicesHook(**__SCREAMING_SNAKE_CASE ) ) add_hook_to_module(model.batchnorm , AlignDevicesHook(**__SCREAMING_SNAKE_CASE ) ) add_hook_to_module(model.lineara , AlignDevicesHook(**__SCREAMING_SNAKE_CASE ) ) # Parameters have been offloaded, so on the meta device, buffers included self.assertEqual(model.lineara.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.batchnorm.running_mean.device , torch.device("""meta""" ) ) __SCREAMING_SNAKE_CASE = torch.randn(2 , 3 ) __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE ) self.assertEqual(output.device , __SCREAMING_SNAKE_CASE ) # Removing hooks loads back the weights in the model. remove_hook_from_module(model.lineara ) remove_hook_from_module(model.batchnorm ) remove_hook_from_module(model.lineara ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = ModelForTest() # Everything is on CPU self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) # This will move each submodule on different devices __SCREAMING_SNAKE_CASE = 0 if torch.cuda.is_available() else """cpu""" attach_align_device_hook(__SCREAMING_SNAKE_CASE , execution_device=__SCREAMING_SNAKE_CASE , offload=__SCREAMING_SNAKE_CASE ) # Parameters have been offloaded, so on the meta device self.assertEqual(model.lineara.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""meta""" ) ) # Buffers are not included in the offload by default, so are on the execution device __SCREAMING_SNAKE_CASE = torch.device(__SCREAMING_SNAKE_CASE ) self.assertEqual(model.batchnorm.running_mean.device , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = torch.randn(2 , 3 ) __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE ) self.assertEqual(output.device , __SCREAMING_SNAKE_CASE ) # Removing hooks loads back the weights in the model. remove_hook_from_submodules(__SCREAMING_SNAKE_CASE ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) # Now test with buffers included in the offload attach_align_device_hook(__SCREAMING_SNAKE_CASE , execution_device=__SCREAMING_SNAKE_CASE , offload=__SCREAMING_SNAKE_CASE , offload_buffers=__SCREAMING_SNAKE_CASE ) # Parameters have been offloaded, so on the meta device, buffers included self.assertEqual(model.lineara.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.batchnorm.running_mean.device , torch.device("""meta""" ) ) __SCREAMING_SNAKE_CASE = torch.randn(2 , 3 ) __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE ) self.assertEqual(output.device , __SCREAMING_SNAKE_CASE ) # Removing hooks loads back the weights in the model. remove_hook_from_submodules(__SCREAMING_SNAKE_CASE ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) def UpperCAmelCase__ ( self : Any ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = ModelForTest() # Everything is on CPU self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) # This will move each submodule on different devices __SCREAMING_SNAKE_CASE = 0 if torch.cuda.is_available() else """cpu""" attach_align_device_hook( __SCREAMING_SNAKE_CASE , execution_device=__SCREAMING_SNAKE_CASE , offload=__SCREAMING_SNAKE_CASE , weights_map=model.state_dict() ) # Parameters have been offloaded, so on the meta device self.assertEqual(model.lineara.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""meta""" ) ) # Buffers are not included in the offload by default, so are on the execution device __SCREAMING_SNAKE_CASE = torch.device(__SCREAMING_SNAKE_CASE ) self.assertEqual(model.batchnorm.running_mean.device , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = torch.randn(2 , 3 ) __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE ) self.assertEqual(output.device , __SCREAMING_SNAKE_CASE ) # Removing hooks loads back the weights in the model. remove_hook_from_submodules(__SCREAMING_SNAKE_CASE ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) # Now test with buffers included in the offload attach_align_device_hook( __SCREAMING_SNAKE_CASE , execution_device=__SCREAMING_SNAKE_CASE , offload=__SCREAMING_SNAKE_CASE , weights_map=model.state_dict() , offload_buffers=__SCREAMING_SNAKE_CASE , ) # Parameters have been offloaded, so on the meta device, buffers included self.assertEqual(model.lineara.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.batchnorm.running_mean.device , torch.device("""meta""" ) ) __SCREAMING_SNAKE_CASE = torch.randn(2 , 3 ) __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE ) self.assertEqual(output.device , __SCREAMING_SNAKE_CASE ) # Removing hooks loads back the weights in the model. remove_hook_from_submodules(__SCREAMING_SNAKE_CASE ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) )
267
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices UpperCAmelCase : List[str] = logging.get_logger(__name__) class lowerCAmelCase__ ( a , a ): """simple docstring""" lowerCAmelCase__ = "maskformer-swin" lowerCAmelCase__ = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self : str , __SCREAMING_SNAKE_CASE : Tuple=224 , __SCREAMING_SNAKE_CASE : str=4 , __SCREAMING_SNAKE_CASE : Union[str, Any]=3 , __SCREAMING_SNAKE_CASE : Optional[Any]=96 , __SCREAMING_SNAKE_CASE : Optional[Any]=[2, 2, 6, 2] , __SCREAMING_SNAKE_CASE : Any=[3, 6, 12, 24] , __SCREAMING_SNAKE_CASE : Dict=7 , __SCREAMING_SNAKE_CASE : Dict=4.0 , __SCREAMING_SNAKE_CASE : Dict=True , __SCREAMING_SNAKE_CASE : str=0.0 , __SCREAMING_SNAKE_CASE : int=0.0 , __SCREAMING_SNAKE_CASE : str=0.1 , __SCREAMING_SNAKE_CASE : List[Any]="gelu" , __SCREAMING_SNAKE_CASE : str=False , __SCREAMING_SNAKE_CASE : Optional[int]=0.02 , __SCREAMING_SNAKE_CASE : Optional[int]=1E-5 , __SCREAMING_SNAKE_CASE : Dict=None , __SCREAMING_SNAKE_CASE : Dict=None , **__SCREAMING_SNAKE_CASE : Tuple , ) -> Tuple: """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = patch_size __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = embed_dim __SCREAMING_SNAKE_CASE = depths __SCREAMING_SNAKE_CASE = len(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = num_heads __SCREAMING_SNAKE_CASE = window_size __SCREAMING_SNAKE_CASE = mlp_ratio __SCREAMING_SNAKE_CASE = qkv_bias __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = drop_path_rate __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = use_absolute_embeddings __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = initializer_range # we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model __SCREAMING_SNAKE_CASE = int(embed_dim * 2 ** (len(__SCREAMING_SNAKE_CASE ) - 1) ) __SCREAMING_SNAKE_CASE = ["""stem"""] + [f'stage{idx}' for idx in range(1 , len(__SCREAMING_SNAKE_CASE ) + 1 )] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = get_aligned_output_features_output_indices( out_features=__SCREAMING_SNAKE_CASE , out_indices=__SCREAMING_SNAKE_CASE , stage_names=self.stage_names )
267
1
'''simple docstring''' from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_torch_available from ...utils import OptionalDependencyNotAvailable UpperCAmelCase : str = { 'configuration_gpt_neox_japanese': ['GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP', 'GPTNeoXJapaneseConfig'], 'tokenization_gpt_neox_japanese': ['GPTNeoXJapaneseTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Dict = [ 'GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST', 'GPTNeoXJapaneseForCausalLM', 'GPTNeoXJapaneseLayer', 'GPTNeoXJapaneseModel', 'GPTNeoXJapanesePreTrainedModel', ] if TYPE_CHECKING: from .configuration_gpt_neox_japanese import GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXJapaneseConfig from .tokenization_gpt_neox_japanese import GPTNeoXJapaneseTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox_japanese import ( GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXJapaneseForCausalLM, GPTNeoXJapaneseLayer, GPTNeoXJapaneseModel, GPTNeoXJapanesePreTrainedModel, ) else: import sys UpperCAmelCase : Optional[int] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
267
'''simple docstring''' class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : int ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = n __SCREAMING_SNAKE_CASE = [None] * self.n __SCREAMING_SNAKE_CASE = 0 # index of the first element __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 def __len__( self : Tuple ) -> int: """simple docstring""" return self.size def UpperCAmelCase__ ( self : Optional[Any] ) -> bool: """simple docstring""" return self.size == 0 def UpperCAmelCase__ ( self : Any ) -> int: """simple docstring""" return False if self.is_empty() else self.array[self.front] def UpperCAmelCase__ ( self : Dict , __SCREAMING_SNAKE_CASE : Union[str, Any] ) -> Dict: """simple docstring""" if self.size >= self.n: raise Exception("""QUEUE IS FULL""" ) __SCREAMING_SNAKE_CASE = data __SCREAMING_SNAKE_CASE = (self.rear + 1) % self.n self.size += 1 return self def UpperCAmelCase__ ( self : List[str] ) -> Optional[Any]: """simple docstring""" if self.size == 0: raise Exception("""UNDERFLOW""" ) __SCREAMING_SNAKE_CASE = self.array[self.front] __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = (self.front + 1) % self.n self.size -= 1 return temp
267
1
'''simple docstring''' from . import __version__ # Backward compatibility imports, to make sure all those objects can be found in file_utils from .utils import ( CLOUDFRONT_DISTRIB_PREFIX, CONFIG_NAME, DISABLE_TELEMETRY, DUMMY_INPUTS, DUMMY_MASK, ENV_VARS_TRUE_AND_AUTO_VALUES, ENV_VARS_TRUE_VALUES, FEATURE_EXTRACTOR_NAME, FLAX_WEIGHTS_NAME, HF_MODULES_CACHE, HUGGINGFACE_CO_PREFIX, HUGGINGFACE_CO_RESOLVE_ENDPOINT, MODEL_CARD_NAME, MULTIPLE_CHOICE_DUMMY_INPUTS, PYTORCH_PRETRAINED_BERT_CACHE, PYTORCH_TRANSFORMERS_CACHE, S3_BUCKET_PREFIX, SENTENCEPIECE_UNDERLINE, SPIECE_UNDERLINE, TF2_WEIGHTS_NAME, TF_WEIGHTS_NAME, TORCH_FX_REQUIRED_VERSION, TRANSFORMERS_CACHE, TRANSFORMERS_DYNAMIC_MODULE_NAME, USE_JAX, USE_TF, USE_TORCH, WEIGHTS_INDEX_NAME, WEIGHTS_NAME, ContextManagers, DummyObject, EntryNotFoundError, ExplicitEnum, ModelOutput, PaddingStrategy, PushToHubMixin, RepositoryNotFoundError, RevisionNotFoundError, TensorType, _LazyModule, add_code_sample_docstrings, add_end_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, cached_property, copy_func, default_cache_path, define_sagemaker_information, get_cached_models, get_file_from_repo, get_full_repo_name, get_torch_version, has_file, http_user_agent, is_apex_available, is_bsa_available, is_coloredlogs_available, is_datasets_available, is_detectrona_available, is_faiss_available, is_flax_available, is_ftfy_available, is_in_notebook, is_ipex_available, is_librosa_available, is_offline_mode, is_onnx_available, is_pandas_available, is_phonemizer_available, is_protobuf_available, is_psutil_available, is_pyanvml_available, is_pyctcdecode_available, is_pytesseract_available, is_pytorch_quantization_available, is_rjieba_available, is_sagemaker_dp_enabled, is_sagemaker_mp_enabled, is_scipy_available, is_sentencepiece_available, is_seqio_available, is_sklearn_available, is_soundfile_availble, is_spacy_available, is_speech_available, is_tensor, is_tensorflow_probability_available, is_tfaonnx_available, is_tf_available, is_timm_available, is_tokenizers_available, is_torch_available, is_torch_bfaa_available, is_torch_cuda_available, is_torch_fx_available, is_torch_fx_proxy, is_torch_mps_available, is_torch_tfaa_available, is_torch_tpu_available, is_torchaudio_available, is_training_run_on_sagemaker, is_vision_available, replace_return_docstrings, requires_backends, to_numpy, to_py_obj, torch_only_method, )
267
'''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] ) -> Optional[int]: """simple docstring""" torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = 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 : List[Any] ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.dummy_uncond_unet __SCREAMING_SNAKE_CASE = PNDMScheduler() __SCREAMING_SNAKE_CASE = PNDMPipeline(unet=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE ) pndm.to(__SCREAMING_SNAKE_CASE ) pndm.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pndm(generator=__SCREAMING_SNAKE_CASE , num_inference_steps=20 , output_type="""numpy""" ).images __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pndm(generator=__SCREAMING_SNAKE_CASE , num_inference_steps=20 , output_type="""numpy""" , return_dict=__SCREAMING_SNAKE_CASE )[0] __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] __SCREAMING_SNAKE_CASE = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __SCREAMING_SNAKE_CASE = 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 : Optional[int] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = """google/ddpm-cifar10-32""" __SCREAMING_SNAKE_CASE = UNetaDModel.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = PNDMScheduler() __SCREAMING_SNAKE_CASE = PNDMPipeline(unet=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE ) pndm.to(__SCREAMING_SNAKE_CASE ) pndm.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pndm(generator=__SCREAMING_SNAKE_CASE , output_type="""numpy""" ).images __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __SCREAMING_SNAKE_CASE = np.array([0.1564, 0.14645, 0.1406, 0.14715, 0.12425, 0.14045, 0.13115, 0.12175, 0.125] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
267
1
'''simple docstring''' def a__ ( a__ ): """simple docstring""" if not isinstance(a__ , a__ ): raise TypeError("""only integers accepted as input""" ) else: __SCREAMING_SNAKE_CASE = str(abs(a__ ) ) __SCREAMING_SNAKE_CASE = [list(a__ ) for char in range(len(a__ ) )] for index in range(len(a__ ) ): num_transpositions[index].pop(a__ ) return max( int("""""".join(list(a__ ) ) ) for transposition in num_transpositions ) if __name__ == "__main__": __import__('doctest').testmod()
267
'''simple docstring''' import unittest from transformers import ( MODEL_FOR_OBJECT_DETECTION_MAPPING, AutoFeatureExtractor, AutoModelForObjectDetection, ObjectDetectionPipeline, is_vision_available, pipeline, ) from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_pytesseract, require_tf, require_timm, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class lowerCAmelCase__ : """simple docstring""" @staticmethod def UpperCAmelCase__ ( *__SCREAMING_SNAKE_CASE : Tuple , **__SCREAMING_SNAKE_CASE : Union[str, Any] ) -> List[str]: """simple docstring""" pass @is_pipeline_test @require_vision @require_timm @require_torch class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = MODEL_FOR_OBJECT_DETECTION_MAPPING def UpperCAmelCase__ ( self : List[Any] , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Tuple ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = ObjectDetectionPipeline(model=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) return object_detector, ["./tests/fixtures/tests_samples/COCO/000000039769.png"] def UpperCAmelCase__ ( self : Optional[int] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : List[Any] ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = object_detector("""./tests/fixtures/tests_samples/COCO/000000039769.png""" , threshold=0.0 ) self.assertGreater(len(__SCREAMING_SNAKE_CASE ) , 0 ) for detected_object in outputs: self.assertEqual( __SCREAMING_SNAKE_CASE , { """score""": ANY(__SCREAMING_SNAKE_CASE ), """label""": ANY(__SCREAMING_SNAKE_CASE ), """box""": {"""xmin""": ANY(__SCREAMING_SNAKE_CASE ), """ymin""": ANY(__SCREAMING_SNAKE_CASE ), """xmax""": ANY(__SCREAMING_SNAKE_CASE ), """ymax""": ANY(__SCREAMING_SNAKE_CASE )}, } , ) import datasets __SCREAMING_SNAKE_CASE = datasets.load_dataset("""hf-internal-testing/fixtures_image_utils""" , """image""" , split="""test""" ) __SCREAMING_SNAKE_CASE = [ Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ), """http://images.cocodataset.org/val2017/000000039769.jpg""", # RGBA dataset[0]["""file"""], # LA dataset[1]["""file"""], # L dataset[2]["""file"""], ] __SCREAMING_SNAKE_CASE = object_detector(__SCREAMING_SNAKE_CASE , threshold=0.0 ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , len(__SCREAMING_SNAKE_CASE ) ) for outputs in batch_outputs: self.assertGreater(len(__SCREAMING_SNAKE_CASE ) , 0 ) for detected_object in outputs: self.assertEqual( __SCREAMING_SNAKE_CASE , { """score""": ANY(__SCREAMING_SNAKE_CASE ), """label""": ANY(__SCREAMING_SNAKE_CASE ), """box""": {"""xmin""": ANY(__SCREAMING_SNAKE_CASE ), """ymin""": ANY(__SCREAMING_SNAKE_CASE ), """xmax""": ANY(__SCREAMING_SNAKE_CASE ), """ymax""": ANY(__SCREAMING_SNAKE_CASE )}, } , ) @require_tf @unittest.skip("""Object detection not implemented in TF""" ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> str: """simple docstring""" pass @require_torch def UpperCAmelCase__ ( self : str ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = """hf-internal-testing/tiny-detr-mobilenetsv3""" __SCREAMING_SNAKE_CASE = AutoModelForObjectDetection.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = AutoFeatureExtractor.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = ObjectDetectionPipeline(model=__SCREAMING_SNAKE_CASE , feature_extractor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" , threshold=0.0 ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ] , ) __SCREAMING_SNAKE_CASE = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] , threshold=0.0 , ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ], [ {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, {"""score""": 0.3376, """label""": """LABEL_0""", """box""": {"""xmin""": 159, """ymin""": 120, """xmax""": 480, """ymax""": 359}}, ], ] , ) @require_torch @slow def UpperCAmelCase__ ( self : Optional[int] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = """facebook/detr-resnet-50""" __SCREAMING_SNAKE_CASE = AutoModelForObjectDetection.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = AutoFeatureExtractor.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = ObjectDetectionPipeline(model=__SCREAMING_SNAKE_CASE , feature_extractor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) __SCREAMING_SNAKE_CASE = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], ] , ) @require_torch @slow def UpperCAmelCase__ ( self : List[Any] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = """facebook/detr-resnet-50""" __SCREAMING_SNAKE_CASE = pipeline("""object-detection""" , model=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) __SCREAMING_SNAKE_CASE = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], [ {"""score""": 0.9982, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 175, """ymax""": 117}}, {"""score""": 0.9960, """label""": """remote""", """box""": {"""xmin""": 333, """ymin""": 72, """xmax""": 368, """ymax""": 187}}, {"""score""": 0.9955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 639, """ymax""": 473}}, {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ], ] , ) @require_torch @slow def UpperCAmelCase__ ( self : Dict ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = 0.9985 __SCREAMING_SNAKE_CASE = """facebook/detr-resnet-50""" __SCREAMING_SNAKE_CASE = pipeline("""object-detection""" , model=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" , threshold=__SCREAMING_SNAKE_CASE ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9988, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 314, """ymax""": 470}}, {"""score""": 0.9987, """label""": """cat""", """box""": {"""xmin""": 345, """ymin""": 23, """xmax""": 640, """ymax""": 368}}, ] , ) @require_torch @require_pytesseract @slow def UpperCAmelCase__ ( self : int ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = """Narsil/layoutlmv3-finetuned-funsd""" __SCREAMING_SNAKE_CASE = 0.9993 __SCREAMING_SNAKE_CASE = pipeline("""object-detection""" , model=__SCREAMING_SNAKE_CASE , threshold=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = object_detector( """https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9993, """label""": """I-ANSWER""", """box""": {"""xmin""": 294, """ymin""": 254, """xmax""": 343, """ymax""": 264}}, {"""score""": 0.9993, """label""": """I-ANSWER""", """box""": {"""xmin""": 294, """ymin""": 254, """xmax""": 343, """ymax""": 264}}, ] , )
267
1
'''simple docstring''' import logging import math from functools import partial from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple, Union import torch from .tensor_utils import tensor_tree_map, tree_map def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = [] if isinstance(a__ , a__ ): for v in tree.values(): shapes.extend(_fetch_dims(a__ ) ) elif isinstance(a__ , (list, tuple) ): for t in tree: shapes.extend(_fetch_dims(a__ ) ) elif isinstance(a__ , torch.Tensor ): shapes.append(tree.shape ) else: raise ValueError("""Not supported""" ) return shapes @torch.jit.ignore def a__ ( a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = [] for d in reversed(a__ ): idx.append(flat_idx % d ) __SCREAMING_SNAKE_CASE = flat_idx // d return tuple(reversed(a__ ) ) @torch.jit.ignore def a__ ( a__ , a__ , a__ , a__ = None , a__ = None , ): """simple docstring""" def reduce_edge_list(a__ ) -> None: __SCREAMING_SNAKE_CASE = True for i in range(len(a__ ) ): __SCREAMING_SNAKE_CASE = -1 * (i + 1) l[reversed_idx] &= tally __SCREAMING_SNAKE_CASE = l[reversed_idx] if start_edges is None: __SCREAMING_SNAKE_CASE = [s == 0 for s in start] reduce_edge_list(a__ ) if end_edges is None: __SCREAMING_SNAKE_CASE = [e == (d - 1) for e, d in zip(a__ , a__ )] reduce_edge_list(a__ ) # Base cases. Either start/end are empty and we're done, or the final, # one-dimensional tensor can be simply sliced if len(a__ ) == 0: return [()] elif len(a__ ) == 1: return [(slice(start[0] , end[0] + 1 ),)] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] # Dimensions common to start and end can be selected directly for s, e in zip(a__ , a__ ): if s == e: path_list.append(slice(a__ , s + 1 ) ) else: break __SCREAMING_SNAKE_CASE = tuple(a__ ) __SCREAMING_SNAKE_CASE = len(a__ ) # start == end, and we're done if divergence_idx == len(a__ ): return [path] def upper() -> Tuple[Tuple[slice, ...], ...]: assert start_edges is not None assert end_edges is not None __SCREAMING_SNAKE_CASE = start[divergence_idx] return tuple( path + (slice(a__ , sdi + 1 ),) + s for s in _get_minimal_slice_set( start[divergence_idx + 1 :] , [d - 1 for d in dims[divergence_idx + 1 :]] , dims[divergence_idx + 1 :] , start_edges=start_edges[divergence_idx + 1 :] , end_edges=[True for _ in end_edges[divergence_idx + 1 :]] , ) ) def lower() -> Tuple[Tuple[slice, ...], ...]: assert start_edges is not None assert end_edges is not None __SCREAMING_SNAKE_CASE = end[divergence_idx] return tuple( path + (slice(a__ , edi + 1 ),) + s for s in _get_minimal_slice_set( [0 for _ in start[divergence_idx + 1 :]] , end[divergence_idx + 1 :] , dims[divergence_idx + 1 :] , start_edges=[True for _ in start_edges[divergence_idx + 1 :]] , end_edges=end_edges[divergence_idx + 1 :] , ) ) # If both start and end are at the edges of the subtree rooted at # divergence_idx, we can just select the whole subtree at once if start_edges[divergence_idx] and end_edges[divergence_idx]: slices.append(path + (slice(start[divergence_idx] , end[divergence_idx] + 1 ),) ) # If just start is at the edge, we can grab almost all of the subtree, # treating only the ragged bottom edge as an edge case elif start_edges[divergence_idx]: slices.append(path + (slice(start[divergence_idx] , end[divergence_idx] ),) ) slices.extend(lower() ) # Analogous to the previous case, but the top is ragged this time elif end_edges[divergence_idx]: slices.extend(upper() ) slices.append(path + (slice(start[divergence_idx] + 1 , end[divergence_idx] + 1 ),) ) # If both sides of the range are ragged, we need to handle both sides # separately. If there's contiguous meat in between them, we can index it # in one big chunk else: slices.extend(upper() ) __SCREAMING_SNAKE_CASE = end[divergence_idx] - start[divergence_idx] if middle_ground > 1: slices.append(path + (slice(start[divergence_idx] + 1 , end[divergence_idx] ),) ) slices.extend(lower() ) return slices @torch.jit.ignore def a__ ( a__ , a__ , a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = t.shape[:no_batch_dims] __SCREAMING_SNAKE_CASE = list(_flat_idx_to_idx(a__ , a__ ) ) # _get_minimal_slice_set is inclusive __SCREAMING_SNAKE_CASE = list(_flat_idx_to_idx(flat_end - 1 , a__ ) ) # Get an ordered list of slices to perform __SCREAMING_SNAKE_CASE = _get_minimal_slice_set( a__ , a__ , a__ , ) __SCREAMING_SNAKE_CASE = [t[s] for s in slices] return torch.cat([s.view((-1,) + t.shape[no_batch_dims:] ) for s in sliced_tensors] ) def a__ ( a__ , a__ , a__ , a__ , a__ = False , a__ = None , a__ = False , ): """simple docstring""" if not (len(a__ ) > 0): raise ValueError("""Must provide at least one input""" ) __SCREAMING_SNAKE_CASE = [shape[:no_batch_dims] for shape in _fetch_dims(a__ )] __SCREAMING_SNAKE_CASE = tuple([max(a__ ) for s in zip(*a__ )] ) def _prep_inputs(a__ ) -> torch.Tensor: if not low_mem: if not sum(t.shape[:no_batch_dims] ) == no_batch_dims: __SCREAMING_SNAKE_CASE = t.expand(orig_batch_dims + t.shape[no_batch_dims:] ) __SCREAMING_SNAKE_CASE = t.reshape(-1 , *t.shape[no_batch_dims:] ) else: __SCREAMING_SNAKE_CASE = t.expand(orig_batch_dims + t.shape[no_batch_dims:] ) return t __SCREAMING_SNAKE_CASE = tensor_tree_map(_prep_inputs , a__ ) __SCREAMING_SNAKE_CASE = None if _out is not None: __SCREAMING_SNAKE_CASE = tensor_tree_map(lambda a__ : t.view([-1] + list(t.shape[no_batch_dims:] ) ) , _out ) __SCREAMING_SNAKE_CASE = 1 for d in orig_batch_dims: flat_batch_dim *= d __SCREAMING_SNAKE_CASE = flat_batch_dim // chunk_size + (flat_batch_dim % chunk_size != 0) def _select_chunk(a__ ) -> torch.Tensor: return t[i : i + chunk_size] if t.shape[0] != 1 else t __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = prepped_outputs for _ in range(a__ ): # Chunk the input if not low_mem: __SCREAMING_SNAKE_CASE = _select_chunk else: __SCREAMING_SNAKE_CASE = partial( _chunk_slice , flat_start=a__ , flat_end=min(a__ , i + chunk_size ) , no_batch_dims=len(a__ ) , ) __SCREAMING_SNAKE_CASE = tensor_tree_map(a__ , a__ ) # Run the layer on the chunk __SCREAMING_SNAKE_CASE = layer(**a__ ) # Allocate space for the output if out is None: __SCREAMING_SNAKE_CASE = tensor_tree_map(lambda a__ : t.new_zeros((flat_batch_dim,) + t.shape[1:] ) , a__ ) # Put the chunk in its pre-allocated space if isinstance(a__ , a__ ): def assign(a__ , a__ ) -> None: for k, v in da.items(): if isinstance(a__ , a__ ): assign(a__ , da[k] ) else: if _add_into_out: v[i : i + chunk_size] += da[k] else: __SCREAMING_SNAKE_CASE = da[k] assign(a__ , a__ ) elif isinstance(a__ , a__ ): for xa, xa in zip(a__ , a__ ): if _add_into_out: xa[i : i + chunk_size] += xa else: __SCREAMING_SNAKE_CASE = xa elif isinstance(a__ , torch.Tensor ): if _add_into_out: out[i : i + chunk_size] += output_chunk else: __SCREAMING_SNAKE_CASE = output_chunk else: raise ValueError("""Not supported""" ) i += chunk_size __SCREAMING_SNAKE_CASE = tensor_tree_map(lambda a__ : t.view(orig_batch_dims + t.shape[1:] ) , a__ ) return out class lowerCAmelCase__ : """simple docstring""" def __init__( self : str , __SCREAMING_SNAKE_CASE : int = 512 , ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = max_chunk_size __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None def UpperCAmelCase__ ( self : Optional[int] , __SCREAMING_SNAKE_CASE : Callable , __SCREAMING_SNAKE_CASE : tuple , __SCREAMING_SNAKE_CASE : int ) -> int: """simple docstring""" logging.info("""Tuning chunk size...""" ) if min_chunk_size >= self.max_chunk_size: return min_chunk_size __SCREAMING_SNAKE_CASE = [2**l for l in range(int(math.log(self.max_chunk_size , 2 ) ) + 1 )] __SCREAMING_SNAKE_CASE = [c for c in candidates if c > min_chunk_size] __SCREAMING_SNAKE_CASE = [min_chunk_size] + candidates candidates[-1] += 4 def test_chunk_size(__SCREAMING_SNAKE_CASE : int ) -> bool: try: with torch.no_grad(): fn(*__SCREAMING_SNAKE_CASE , chunk_size=__SCREAMING_SNAKE_CASE ) return True except RuntimeError: return False __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = len(__SCREAMING_SNAKE_CASE ) - 1 while i > min_viable_chunk_size_index: __SCREAMING_SNAKE_CASE = test_chunk_size(candidates[i] ) if not viable: __SCREAMING_SNAKE_CASE = (min_viable_chunk_size_index + i) // 2 else: __SCREAMING_SNAKE_CASE = i __SCREAMING_SNAKE_CASE = (i + len(__SCREAMING_SNAKE_CASE ) - 1) // 2 return candidates[min_viable_chunk_size_index] def UpperCAmelCase__ ( self : Any , __SCREAMING_SNAKE_CASE : Iterable , __SCREAMING_SNAKE_CASE : Iterable ) -> bool: """simple docstring""" __SCREAMING_SNAKE_CASE = True for aa, aa in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): assert type(__SCREAMING_SNAKE_CASE ) == type(__SCREAMING_SNAKE_CASE ) if isinstance(__SCREAMING_SNAKE_CASE , (list, tuple) ): consistent &= self._compare_arg_caches(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) elif isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): __SCREAMING_SNAKE_CASE = [v for _, v in sorted(aa.items() , key=lambda __SCREAMING_SNAKE_CASE : x[0] )] __SCREAMING_SNAKE_CASE = [v for _, v in sorted(aa.items() , key=lambda __SCREAMING_SNAKE_CASE : x[0] )] consistent &= self._compare_arg_caches(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else: consistent &= aa == aa return consistent def UpperCAmelCase__ ( self : List[Any] , __SCREAMING_SNAKE_CASE : Callable , __SCREAMING_SNAKE_CASE : tuple , __SCREAMING_SNAKE_CASE : int , ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = tree_map(lambda __SCREAMING_SNAKE_CASE : a.shape if isinstance(__SCREAMING_SNAKE_CASE , torch.Tensor ) else a , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if self.cached_arg_data is not None: # If args have changed shape/value, we need to re-tune assert len(self.cached_arg_data ) == len(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self._compare_arg_caches(self.cached_arg_data , __SCREAMING_SNAKE_CASE ) else: # Otherwise, we can reuse the precomputed value __SCREAMING_SNAKE_CASE = False if not consistent: __SCREAMING_SNAKE_CASE = self._determine_favorable_chunk_size( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , ) __SCREAMING_SNAKE_CASE = arg_data assert self.cached_chunk_size is not None return self.cached_chunk_size
267
'''simple docstring''' import unittest from diffusers import FlaxAutoencoderKL from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax from .test_modeling_common_flax import FlaxModelTesterMixin if is_flax_available(): import jax @require_flax class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = FlaxAutoencoderKL @property def UpperCAmelCase__ ( self : Tuple ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = 4 __SCREAMING_SNAKE_CASE = 3 __SCREAMING_SNAKE_CASE = (32, 32) __SCREAMING_SNAKE_CASE = jax.random.PRNGKey(0 ) __SCREAMING_SNAKE_CASE = jax.random.uniform(__SCREAMING_SNAKE_CASE , ((batch_size, num_channels) + sizes) ) return {"sample": image, "prng_key": prng_key} def UpperCAmelCase__ ( self : Union[str, Any] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = { """block_out_channels""": [32, 64], """in_channels""": 3, """out_channels""": 3, """down_block_types""": ["""DownEncoderBlock2D""", """DownEncoderBlock2D"""], """up_block_types""": ["""UpDecoderBlock2D""", """UpDecoderBlock2D"""], """latent_channels""": 4, } __SCREAMING_SNAKE_CASE = self.dummy_input return init_dict, inputs_dict
267
1
'''simple docstring''' from ... import PretrainedConfig UpperCAmelCase : Union[str, Any] = { 'sijunhe/nezha-cn-base': 'https://huggingface.co/sijunhe/nezha-cn-base/resolve/main/config.json', } class lowerCAmelCase__ ( a ): """simple docstring""" lowerCAmelCase__ = NEZHA_PRETRAINED_CONFIG_ARCHIVE_MAP lowerCAmelCase__ = "nezha" def __init__( self : str , __SCREAMING_SNAKE_CASE : List[Any]=21_128 , __SCREAMING_SNAKE_CASE : Union[str, Any]=768 , __SCREAMING_SNAKE_CASE : Dict=12 , __SCREAMING_SNAKE_CASE : Union[str, Any]=12 , __SCREAMING_SNAKE_CASE : int=3_072 , __SCREAMING_SNAKE_CASE : Tuple="gelu" , __SCREAMING_SNAKE_CASE : Dict=0.1 , __SCREAMING_SNAKE_CASE : Dict=0.1 , __SCREAMING_SNAKE_CASE : Tuple=512 , __SCREAMING_SNAKE_CASE : List[str]=64 , __SCREAMING_SNAKE_CASE : Any=2 , __SCREAMING_SNAKE_CASE : Optional[Any]=0.02 , __SCREAMING_SNAKE_CASE : Any=1E-12 , __SCREAMING_SNAKE_CASE : Dict=0.1 , __SCREAMING_SNAKE_CASE : Dict=0 , __SCREAMING_SNAKE_CASE : str=2 , __SCREAMING_SNAKE_CASE : Any=3 , __SCREAMING_SNAKE_CASE : int=True , **__SCREAMING_SNAKE_CASE : Dict , ) -> Union[str, Any]: """simple docstring""" super().__init__(pad_token_id=__SCREAMING_SNAKE_CASE , bos_token_id=__SCREAMING_SNAKE_CASE , eos_token_id=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) __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 = max_relative_position __SCREAMING_SNAKE_CASE = type_vocab_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = classifier_dropout __SCREAMING_SNAKE_CASE = use_cache
267
'''simple docstring''' import itertools import os import random import tempfile import unittest import numpy as np from datasets import load_dataset from transformers import is_speech_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_speech_available(): from transformers import WhisperFeatureExtractor if is_torch_available(): import torch UpperCAmelCase : int = random.Random() def a__ ( a__ , a__=1.0 , a__=None , a__=None ): """simple docstring""" if rng is None: __SCREAMING_SNAKE_CASE = global_rng __SCREAMING_SNAKE_CASE = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch @require_torchaudio class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __init__( self : str , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : str=7 , __SCREAMING_SNAKE_CASE : List[str]=400 , __SCREAMING_SNAKE_CASE : Any=2_000 , __SCREAMING_SNAKE_CASE : List[str]=10 , __SCREAMING_SNAKE_CASE : Optional[int]=160 , __SCREAMING_SNAKE_CASE : List[str]=8 , __SCREAMING_SNAKE_CASE : Optional[Any]=0.0 , __SCREAMING_SNAKE_CASE : Dict=4_000 , __SCREAMING_SNAKE_CASE : Optional[int]=False , __SCREAMING_SNAKE_CASE : List[Any]=True , ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = min_seq_length __SCREAMING_SNAKE_CASE = max_seq_length __SCREAMING_SNAKE_CASE = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) __SCREAMING_SNAKE_CASE = padding_value __SCREAMING_SNAKE_CASE = sampling_rate __SCREAMING_SNAKE_CASE = return_attention_mask __SCREAMING_SNAKE_CASE = do_normalize __SCREAMING_SNAKE_CASE = feature_size __SCREAMING_SNAKE_CASE = chunk_length __SCREAMING_SNAKE_CASE = hop_length def UpperCAmelCase__ ( self : Dict ) -> Dict: """simple docstring""" return { "feature_size": self.feature_size, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def UpperCAmelCase__ ( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : Union[str, Any]=False , __SCREAMING_SNAKE_CASE : Optional[Any]=False ) -> Union[str, Any]: """simple docstring""" def _flatten(__SCREAMING_SNAKE_CASE : Dict ): return list(itertools.chain(*__SCREAMING_SNAKE_CASE ) ) if equal_length: __SCREAMING_SNAKE_CASE = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size __SCREAMING_SNAKE_CASE = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = WhisperFeatureExtractor if is_speech_available() else None def UpperCAmelCase__ ( self : str ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = WhisperFeatureExtractionTester(self ) def UpperCAmelCase__ ( self : str ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE = feat_extract_first.save_pretrained(__SCREAMING_SNAKE_CASE )[0] check_json_file_has_correct_format(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.feature_extraction_class.from_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = feat_extract_first.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_second.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_first.mel_filters __SCREAMING_SNAKE_CASE = feat_extract_second.mel_filters self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[str] ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE = os.path.join(__SCREAMING_SNAKE_CASE , """feat_extract.json""" ) feat_extract_first.to_json_file(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.feature_extraction_class.from_json_file(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = feat_extract_first.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_second.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_first.mel_filters __SCREAMING_SNAKE_CASE = feat_extract_second.mel_filters self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[Any] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in range(800 , 1_400 , 200 )] __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs] # Test feature size __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , padding="""max_length""" , return_tensors="""np""" ).input_features self.assertTrue(input_features.ndim == 3 ) self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames ) self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size ) # Test not batched input __SCREAMING_SNAKE_CASE = feature_extractor(speech_inputs[0] , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(np_speech_inputs[0] , return_tensors="""np""" ).input_features self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test batched __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test 2-D numpy arrays are batched. __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in (800, 800, 800)] __SCREAMING_SNAKE_CASE = np.asarray(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) # Test truncation required __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in range(200 , (feature_extractor.n_samples + 500) , 200 )] __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs] __SCREAMING_SNAKE_CASE = [x[: feature_extractor.n_samples] for x in speech_inputs] __SCREAMING_SNAKE_CASE = [np.asarray(__SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs_truncated] __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 ) ) def UpperCAmelCase__ ( self : Dict ) -> Optional[int]: """simple docstring""" import torch __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __SCREAMING_SNAKE_CASE = np.random.rand(100 , 32 ).astype(np.floataa ) __SCREAMING_SNAKE_CASE = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: __SCREAMING_SNAKE_CASE = feature_extractor.pad([{"""input_features""": inputs}] , return_tensors="""np""" ) self.assertTrue(np_processed.input_features.dtype == np.floataa ) __SCREAMING_SNAKE_CASE = feature_extractor.pad([{"""input_features""": inputs}] , return_tensors="""pt""" ) self.assertTrue(pt_processed.input_features.dtype == torch.floataa ) def UpperCAmelCase__ ( self : str , __SCREAMING_SNAKE_CASE : Tuple ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = load_dataset("""hf-internal-testing/librispeech_asr_dummy""" , """clean""" , split="""validation""" ) # automatic decoding with librispeech __SCREAMING_SNAKE_CASE = ds.sort("""id""" ).select(range(__SCREAMING_SNAKE_CASE ) )[:num_samples]["""audio"""] return [x["array"] for x in speech_samples] def UpperCAmelCase__ ( self : Tuple ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = torch.tensor( [ 0.1193, -0.0946, -0.1098, -0.0196, 0.0225, -0.0690, -0.1736, 0.0951, 0.0971, -0.0817, -0.0702, 0.0162, 0.0260, 0.0017, -0.0192, -0.1678, 0.0709, -0.1867, -0.0655, -0.0274, -0.0234, -0.1884, -0.0516, -0.0554, -0.0274, -0.1425, -0.1423, 0.0837, 0.0377, -0.0854 ] ) # fmt: on __SCREAMING_SNAKE_CASE = self._load_datasamples(1 ) __SCREAMING_SNAKE_CASE = WhisperFeatureExtractor() __SCREAMING_SNAKE_CASE = feature_extractor(__SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).input_features self.assertEqual(input_features.shape , (1, 80, 3_000) ) self.assertTrue(torch.allclose(input_features[0, 0, :30] , __SCREAMING_SNAKE_CASE , atol=1E-4 ) ) def UpperCAmelCase__ ( self : List[Any] ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __SCREAMING_SNAKE_CASE = self._load_datasamples(1 )[0] __SCREAMING_SNAKE_CASE = ((audio - audio.min()) / (audio.max() - audio.min())) * 65_535 # Rescale to [0, 65535] to show issue __SCREAMING_SNAKE_CASE = feat_extract.zero_mean_unit_var_norm([audio] , attention_mask=__SCREAMING_SNAKE_CASE )[0] self.assertTrue(np.all(np.mean(__SCREAMING_SNAKE_CASE ) < 1E-3 ) ) self.assertTrue(np.all(np.abs(np.var(__SCREAMING_SNAKE_CASE ) - 1 ) < 1E-3 ) )
267
1
'''simple docstring''' def a__ ( a__ ): """simple docstring""" if isinstance(a__ , a__ ): raise TypeError("""'float' object cannot be interpreted as an integer""" ) if isinstance(a__ , a__ ): raise TypeError("""'str' object cannot be interpreted as an integer""" ) if num == 0: return "0b0" __SCREAMING_SNAKE_CASE = False if num < 0: __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = -num __SCREAMING_SNAKE_CASE = [] while num > 0: binary.insert(0 , num % 2 ) num >>= 1 if negative: return "-0b" + "".join(str(a__ ) for e in binary ) return "0b" + "".join(str(a__ ) for e in binary ) if __name__ == "__main__": import doctest doctest.testmod()
267
'''simple docstring''' from __future__ import annotations def a__ ( a__ , a__ , a__ ): """simple docstring""" if len(a__ ) == 0: raise ValueError("""find_max() arg is an empty sequence""" ) if ( left >= len(a__ ) or left < -len(a__ ) or right >= len(a__ ) or right < -len(a__ ) ): raise IndexError("""list index out of range""" ) if left == right: return nums[left] __SCREAMING_SNAKE_CASE = (left + right) >> 1 # the middle __SCREAMING_SNAKE_CASE = find_max(a__ , a__ , a__ ) # find max in range[left, mid] __SCREAMING_SNAKE_CASE = find_max(a__ , mid + 1 , a__ ) # find max in range[mid + 1, right] return left_max if left_max >= right_max else right_max if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
267
1
'''simple docstring''' from typing import List, Optional, Union from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class lowerCAmelCase__ ( a ): """simple docstring""" lowerCAmelCase__ = ["image_processor", "tokenizer"] lowerCAmelCase__ = "BlipImageProcessor" lowerCAmelCase__ = ("BertTokenizer", "BertTokenizerFast") def __init__( self : int , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = False super().__init__(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.image_processor def __call__( self : List[str] , __SCREAMING_SNAKE_CASE : ImageInput = None , __SCREAMING_SNAKE_CASE : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , __SCREAMING_SNAKE_CASE : bool = True , __SCREAMING_SNAKE_CASE : Union[bool, str, PaddingStrategy] = False , __SCREAMING_SNAKE_CASE : Union[bool, str, TruncationStrategy] = None , __SCREAMING_SNAKE_CASE : Optional[int] = None , __SCREAMING_SNAKE_CASE : int = 0 , __SCREAMING_SNAKE_CASE : Optional[int] = None , __SCREAMING_SNAKE_CASE : Optional[bool] = None , __SCREAMING_SNAKE_CASE : bool = False , __SCREAMING_SNAKE_CASE : bool = False , __SCREAMING_SNAKE_CASE : bool = False , __SCREAMING_SNAKE_CASE : bool = False , __SCREAMING_SNAKE_CASE : bool = False , __SCREAMING_SNAKE_CASE : bool = True , __SCREAMING_SNAKE_CASE : Optional[Union[str, TensorType]] = None , **__SCREAMING_SNAKE_CASE : List[Any] , ) -> BatchEncoding: """simple docstring""" if images is None and text is None: raise ValueError("""You have to specify either images or text.""" ) # Get only text if images is None: __SCREAMING_SNAKE_CASE = self.tokenizer __SCREAMING_SNAKE_CASE = self.tokenizer( text=__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=__SCREAMING_SNAKE_CASE , stride=__SCREAMING_SNAKE_CASE , pad_to_multiple_of=__SCREAMING_SNAKE_CASE , return_attention_mask=__SCREAMING_SNAKE_CASE , return_overflowing_tokens=__SCREAMING_SNAKE_CASE , return_special_tokens_mask=__SCREAMING_SNAKE_CASE , return_offsets_mapping=__SCREAMING_SNAKE_CASE , return_token_type_ids=__SCREAMING_SNAKE_CASE , return_length=__SCREAMING_SNAKE_CASE , verbose=__SCREAMING_SNAKE_CASE , return_tensors=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) return text_encoding # add pixel_values __SCREAMING_SNAKE_CASE = self.image_processor(__SCREAMING_SNAKE_CASE , return_tensors=__SCREAMING_SNAKE_CASE ) if text is not None: __SCREAMING_SNAKE_CASE = self.tokenizer( text=__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=__SCREAMING_SNAKE_CASE , stride=__SCREAMING_SNAKE_CASE , pad_to_multiple_of=__SCREAMING_SNAKE_CASE , return_attention_mask=__SCREAMING_SNAKE_CASE , return_overflowing_tokens=__SCREAMING_SNAKE_CASE , return_special_tokens_mask=__SCREAMING_SNAKE_CASE , return_offsets_mapping=__SCREAMING_SNAKE_CASE , return_token_type_ids=__SCREAMING_SNAKE_CASE , return_length=__SCREAMING_SNAKE_CASE , verbose=__SCREAMING_SNAKE_CASE , return_tensors=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) else: __SCREAMING_SNAKE_CASE = None if text_encoding is not None: encoding_image_processor.update(__SCREAMING_SNAKE_CASE ) return encoding_image_processor def UpperCAmelCase__ ( self : List[str] , *__SCREAMING_SNAKE_CASE : str , **__SCREAMING_SNAKE_CASE : List[Any] ) -> Dict: """simple docstring""" return self.tokenizer.batch_decode(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Dict , *__SCREAMING_SNAKE_CASE : Any , **__SCREAMING_SNAKE_CASE : Tuple ) -> str: """simple docstring""" return self.tokenizer.decode(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) @property def UpperCAmelCase__ ( self : List[Any] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.tokenizer.model_input_names __SCREAMING_SNAKE_CASE = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
267
'''simple docstring''' def a__ ( a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) # Initialize Result __SCREAMING_SNAKE_CASE = [] # Traverse through all denomination for denomination in reversed(a__ ): # Find denominations while int(a__ ) >= int(a__ ): total_value -= int(a__ ) answer.append(a__ ) # Append the "answers" array return answer # Driver Code if __name__ == "__main__": UpperCAmelCase : Dict = [] UpperCAmelCase : List[str] = '0' if ( input('Do you want to enter your denominations ? (yY/n): ').strip().lower() == "y" ): UpperCAmelCase : List[str] = int(input('Enter the number of denominations you want to add: ').strip()) for i in range(0, n): denominations.append(int(input(f"""Denomination {i}: """).strip())) UpperCAmelCase : str = input('Enter the change you want to make in Indian Currency: ').strip() else: # All denominations of Indian Currency if user does not enter UpperCAmelCase : int = [1, 2, 5, 1_0, 2_0, 5_0, 1_0_0, 5_0_0, 2_0_0_0] UpperCAmelCase : Any = input('Enter the change you want to make: ').strip() if int(value) == 0 or int(value) < 0: print('The total value cannot be zero or negative.') else: print(f"""Following is minimal change for {value}: """) UpperCAmelCase : Any = find_minimum_change(denominations, value) # Print result for i in range(len(answer)): print(answer[i], end=' ')
267
1
'''simple docstring''' import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Optional[Any]=13 , __SCREAMING_SNAKE_CASE : Dict=3 , __SCREAMING_SNAKE_CASE : List[Any]=224 , __SCREAMING_SNAKE_CASE : List[str]=30 , __SCREAMING_SNAKE_CASE : Tuple=400 , __SCREAMING_SNAKE_CASE : List[str]=True , __SCREAMING_SNAKE_CASE : Dict=None , __SCREAMING_SNAKE_CASE : List[str]=True , __SCREAMING_SNAKE_CASE : List[Any]=[0.5, 0.5, 0.5] , __SCREAMING_SNAKE_CASE : Dict=[0.5, 0.5, 0.5] , ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = size if size is not None else {"""height""": 18, """width""": 18} __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = min_resolution __SCREAMING_SNAKE_CASE = max_resolution __SCREAMING_SNAKE_CASE = do_resize __SCREAMING_SNAKE_CASE = size __SCREAMING_SNAKE_CASE = do_normalize __SCREAMING_SNAKE_CASE = image_mean __SCREAMING_SNAKE_CASE = image_std def UpperCAmelCase__ ( self : Optional[Any] ) -> int: """simple docstring""" return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, } @require_torch @require_vision class lowerCAmelCase__ ( a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = ViTImageProcessor if is_vision_available() else None def UpperCAmelCase__ ( self : Optional[int] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = EfficientFormerImageProcessorTester(self ) @property def UpperCAmelCase__ ( self : Optional[int] ) -> List[str]: """simple docstring""" return self.image_proc_tester.prepare_image_processor_dict() def UpperCAmelCase__ ( self : List[str] ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """image_mean""" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """image_std""" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """do_normalize""" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """do_resize""" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """size""" ) ) def UpperCAmelCase__ ( self : Dict ) -> str: """simple docstring""" pass def UpperCAmelCase__ ( self : str ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __SCREAMING_SNAKE_CASE = prepare_image_inputs(self.image_proc_tester , equal_resolution=__SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(__SCREAMING_SNAKE_CASE , Image.Image ) # Test not batched input __SCREAMING_SNAKE_CASE = image_processor(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size["""height"""], self.image_proc_tester.size["""width"""], ) , ) # Test batched __SCREAMING_SNAKE_CASE = image_processor(__SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size["""height"""], self.image_proc_tester.size["""width"""], ) , ) def UpperCAmelCase__ ( self : int ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __SCREAMING_SNAKE_CASE = prepare_image_inputs(self.image_proc_tester , equal_resolution=__SCREAMING_SNAKE_CASE , numpify=__SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(__SCREAMING_SNAKE_CASE , np.ndarray ) # Test not batched input __SCREAMING_SNAKE_CASE = image_processor(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size["""height"""], self.image_proc_tester.size["""width"""], ) , ) # Test batched __SCREAMING_SNAKE_CASE = image_processor(__SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size["""height"""], self.image_proc_tester.size["""width"""], ) , ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __SCREAMING_SNAKE_CASE = prepare_image_inputs(self.image_proc_tester , equal_resolution=__SCREAMING_SNAKE_CASE , torchify=__SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(__SCREAMING_SNAKE_CASE , torch.Tensor ) # Test not batched input __SCREAMING_SNAKE_CASE = image_processor(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size["""height"""], self.image_proc_tester.size["""width"""], ) , ) # Test batched __SCREAMING_SNAKE_CASE = image_processor(__SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size["""height"""], self.image_proc_tester.size["""width"""], ) , )
267
'''simple docstring''' # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse from ...utils.dataclasses import ( ComputeEnvironment, DistributedType, DynamoBackend, PrecisionType, SageMakerDistributedType, ) from ..menu import BulletMenu UpperCAmelCase : Any = [ 'EAGER', 'AOT_EAGER', 'INDUCTOR', 'NVFUSER', 'AOT_NVFUSER', 'AOT_CUDAGRAPHS', 'OFI', 'FX2TRT', 'ONNXRT', 'IPEX', ] def a__ ( a__ , a__=None , a__=None , a__=None ): """simple docstring""" __SCREAMING_SNAKE_CASE = True while ask_again: __SCREAMING_SNAKE_CASE = input(a__ ) try: if default is not None and len(a__ ) == 0: return default return convert_value(a__ ) if convert_value is not None else result except Exception: if error_message is not None: print(a__ ) def a__ ( a__ , a__=[] , a__=None , a__=0 ): """simple docstring""" __SCREAMING_SNAKE_CASE = BulletMenu(a__ , a__ ) __SCREAMING_SNAKE_CASE = menu.run(default_choice=a__ ) return convert_value(a__ ) if convert_value is not None else result def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return ComputeEnvironment(["""LOCAL_MACHINE""", """AMAZON_SAGEMAKER"""][value] ) def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return DistributedType(["""NO""", """MULTI_CPU""", """MULTI_XPU""", """MULTI_GPU""", """MULTI_NPU""", """TPU"""][value] ) def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return DynamoBackend(DYNAMO_BACKENDS[value] ).value def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return PrecisionType(["""no""", """fp16""", """bf16""", """fp8"""][value] ) def a__ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = int(a__ ) return SageMakerDistributedType(["""NO""", """DATA_PARALLEL""", """MODEL_PARALLEL"""][value] ) def a__ ( a__ ): """simple docstring""" return {"yes": True, "no": False}[value.lower()] class lowerCAmelCase__ ( argparse.RawDescriptionHelpFormatter ): """simple docstring""" def UpperCAmelCase__ ( self : str , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : List[Any] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = super()._format_usage(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = usage.replace("""<command> [<args>] """ , """""" ) return usage
267
1
'''simple docstring''' import math def a__ ( ): """simple docstring""" __SCREAMING_SNAKE_CASE = input("""Enter message: """ ) __SCREAMING_SNAKE_CASE = int(input(F'Enter key [2-{len(a__ ) - 1}]: ' ) ) __SCREAMING_SNAKE_CASE = input("""Encryption/Decryption [e/d]: """ ) if mode.lower().startswith("""e""" ): __SCREAMING_SNAKE_CASE = encrypt_message(a__ , a__ ) elif mode.lower().startswith("""d""" ): __SCREAMING_SNAKE_CASE = decrypt_message(a__ , a__ ) # Append pipe symbol (vertical bar) to identify spaces at the end. print(F'Output:\n{text + "|"}' ) def a__ ( a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = [""""""] * key for col in range(a__ ): __SCREAMING_SNAKE_CASE = col while pointer < len(a__ ): cipher_text[col] += message[pointer] pointer += key return "".join(a__ ) def a__ ( a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = math.ceil(len(a__ ) / key ) __SCREAMING_SNAKE_CASE = key __SCREAMING_SNAKE_CASE = (num_cols * num_rows) - len(a__ ) __SCREAMING_SNAKE_CASE = [""""""] * num_cols __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 for symbol in message: plain_text[col] += symbol col += 1 if ( (col == num_cols) or (col == num_cols - 1) and (row >= num_rows - num_shaded_boxes) ): __SCREAMING_SNAKE_CASE = 0 row += 1 return "".join(a__ ) if __name__ == "__main__": import doctest doctest.testmod() main()
267
'''simple docstring''' def a__ ( a__ , a__ ): """simple docstring""" _enforce_args(a__ , a__ ) if n == 0: return 0 __SCREAMING_SNAKE_CASE = float("""-inf""" ) for i in range(1 , n + 1 ): __SCREAMING_SNAKE_CASE = max( a__ , prices[i - 1] + naive_cut_rod_recursive(n - i , a__ ) ) return max_revue def a__ ( a__ , a__ ): """simple docstring""" _enforce_args(a__ , a__ ) __SCREAMING_SNAKE_CASE = [float("""-inf""" ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(a__ , a__ , a__ ) def a__ ( a__ , a__ , a__ ): """simple docstring""" if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: __SCREAMING_SNAKE_CASE = float("""-inf""" ) for i in range(1 , n + 1 ): __SCREAMING_SNAKE_CASE = max( a__ , prices[i - 1] + _top_down_cut_rod_recursive(n - i , a__ , a__ ) , ) __SCREAMING_SNAKE_CASE = max_revenue return max_rev[n] def a__ ( a__ , a__ ): """simple docstring""" _enforce_args(a__ , a__ ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. __SCREAMING_SNAKE_CASE = [float("""-inf""" ) for _ in range(n + 1 )] __SCREAMING_SNAKE_CASE = 0 for i in range(1 , n + 1 ): __SCREAMING_SNAKE_CASE = max_rev[i] for j in range(1 , i + 1 ): __SCREAMING_SNAKE_CASE = max(a__ , prices[j - 1] + max_rev[i - j] ) __SCREAMING_SNAKE_CASE = max_revenue_i return max_rev[n] def a__ ( a__ , a__ ): """simple docstring""" if n < 0: __SCREAMING_SNAKE_CASE = F'n must be greater than or equal to 0. Got n = {n}' raise ValueError(a__ ) if n > len(a__ ): __SCREAMING_SNAKE_CASE = ( """Each integral piece of rod must have a corresponding price. """ F'Got n = {n} but length of prices = {len(a__ )}' ) raise ValueError(a__ ) def a__ ( ): """simple docstring""" __SCREAMING_SNAKE_CASE = [6, 10, 12, 15, 20, 23] __SCREAMING_SNAKE_CASE = len(a__ ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. __SCREAMING_SNAKE_CASE = 36 __SCREAMING_SNAKE_CASE = top_down_cut_rod(a__ , a__ ) __SCREAMING_SNAKE_CASE = bottom_up_cut_rod(a__ , a__ ) __SCREAMING_SNAKE_CASE = naive_cut_rod_recursive(a__ , a__ ) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
267
1
'''simple docstring''' import argparse import datetime import json import time import warnings from logging import getLogger from pathlib import Path from typing import Dict, List import torch from tqdm import tqdm from transformers import AutoModelForSeqaSeqLM, AutoTokenizer from utils import calculate_bleu, calculate_rouge, chunks, parse_numeric_n_bool_cl_kwargs, use_task_specific_params UpperCAmelCase : List[str] = getLogger(__name__) UpperCAmelCase : int = 'cuda' if torch.cuda.is_available() else 'cpu' def a__ ( a__ , a__ , a__ , a__ = 8 , a__ = DEFAULT_DEVICE , a__=False , a__="summarization" , a__=None , **a__ , ): """simple docstring""" __SCREAMING_SNAKE_CASE = Path(a__ ).open("""w""" , encoding="""utf-8""" ) __SCREAMING_SNAKE_CASE = str(a__ ) __SCREAMING_SNAKE_CASE = AutoModelForSeqaSeqLM.from_pretrained(a__ ).to(a__ ) if fpaa: __SCREAMING_SNAKE_CASE = model.half() __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(a__ ) logger.info(F'Inferred tokenizer type: {tokenizer.__class__}' ) # if this is wrong, check config.model_type. __SCREAMING_SNAKE_CASE = time.time() # update config with task specific params use_task_specific_params(a__ , a__ ) if prefix is None: __SCREAMING_SNAKE_CASE = prefix or getattr(model.config , """prefix""" , """""" ) or """""" for examples_chunk in tqdm(list(chunks(a__ , a__ ) ) ): __SCREAMING_SNAKE_CASE = [prefix + text for text in examples_chunk] __SCREAMING_SNAKE_CASE = tokenizer(a__ , return_tensors="""pt""" , truncation=a__ , padding="""longest""" ).to(a__ ) __SCREAMING_SNAKE_CASE = model.generate( input_ids=batch.input_ids , attention_mask=batch.attention_mask , **a__ , ) __SCREAMING_SNAKE_CASE = tokenizer.batch_decode(a__ , skip_special_tokens=a__ , clean_up_tokenization_spaces=a__ ) for hypothesis in dec: fout.write(hypothesis + """\n""" ) fout.flush() fout.close() __SCREAMING_SNAKE_CASE = int(time.time() - start_time ) # seconds __SCREAMING_SNAKE_CASE = len(a__ ) return {"n_obs": n_obs, "runtime": runtime, "seconds_per_sample": round(runtime / n_obs , 4 )} def a__ ( ): """simple docstring""" return datetime.datetime.now().strftime("""%Y-%m-%d %H:%M:%S""" ) def a__ ( a__=True ): """simple docstring""" __SCREAMING_SNAKE_CASE = argparse.ArgumentParser() parser.add_argument("""model_name""" , type=a__ , help="""like facebook/bart-large-cnn,t5-base, etc.""" ) parser.add_argument("""input_path""" , type=a__ , help="""like cnn_dm/test.source""" ) parser.add_argument("""save_path""" , type=a__ , help="""where to save summaries""" ) parser.add_argument("""--reference_path""" , type=a__ , required=a__ , help="""like cnn_dm/test.target""" ) parser.add_argument("""--score_path""" , type=a__ , required=a__ , default="""metrics.json""" , help="""where to save metrics""" ) parser.add_argument("""--device""" , type=a__ , required=a__ , default=a__ , help="""cuda, cuda:1, cpu etc.""" ) parser.add_argument( """--prefix""" , type=a__ , required=a__ , default=a__ , help="""will be added to the begininng of src examples""" ) parser.add_argument("""--task""" , type=a__ , default="""summarization""" , help="""used for task_specific_params + metrics""" ) parser.add_argument("""--bs""" , type=a__ , default=8 , required=a__ , help="""batch size""" ) parser.add_argument( """--n_obs""" , type=a__ , default=-1 , required=a__ , help="""How many observations. Defaults to all.""" ) parser.add_argument("""--fp16""" , action="""store_true""" ) parser.add_argument("""--dump-args""" , action="""store_true""" , help="""print the custom hparams with the results""" ) parser.add_argument( """--info""" , nargs="""?""" , type=a__ , const=datetime_now() , help=( """use in conjunction w/ --dump-args to print with the results whatever other info you'd like, e.g.""" """ lang=en-ru. If no value is passed, the current datetime string will be used.""" ) , ) # Unspecified args like --num_beams=2 --decoder_start_token_id=4 are passed to model.generate __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = parser.parse_known_args() __SCREAMING_SNAKE_CASE = parse_numeric_n_bool_cl_kwargs(a__ ) if parsed_args and verbose: print(F'parsed the following generate kwargs: {parsed_args}' ) __SCREAMING_SNAKE_CASE = [""" """ + x.rstrip() if """t5""" in args.model_name else x.rstrip() for x in open(args.input_path ).readlines()] if args.n_obs > 0: __SCREAMING_SNAKE_CASE = examples[: args.n_obs] Path(args.save_path ).parent.mkdir(exist_ok=a__ ) if args.reference_path is None and Path(args.score_path ).exists(): warnings.warn(F'score_path {args.score_path} will be overwritten unless you type ctrl-c.' ) if args.device == "cpu" and args.fpaa: # this mix leads to RuntimeError: "threshold_cpu" not implemented for 'Half' raise ValueError("""Can't mix --fp16 and --device cpu""" ) __SCREAMING_SNAKE_CASE = generate_summaries_or_translations( a__ , args.save_path , args.model_name , batch_size=args.bs , device=args.device , fpaa=args.fpaa , task=args.task , prefix=args.prefix , **a__ , ) if args.reference_path is None: return {} # Compute scores __SCREAMING_SNAKE_CASE = calculate_bleu if """translation""" in args.task else calculate_rouge __SCREAMING_SNAKE_CASE = [x.rstrip() for x in open(args.save_path ).readlines()] __SCREAMING_SNAKE_CASE = [x.rstrip() for x in open(args.reference_path ).readlines()][: len(a__ )] __SCREAMING_SNAKE_CASE = score_fn(a__ , a__ ) scores.update(a__ ) if args.dump_args: scores.update(a__ ) if args.info: __SCREAMING_SNAKE_CASE = args.info if verbose: print(a__ ) if args.score_path is not None: json.dump(a__ , open(args.score_path , """w""" ) ) return scores if __name__ == "__main__": # Usage for MT: # python run_eval.py MODEL_NAME $DATA_DIR/test.source $save_dir/test_translations.txt --reference_path $DATA_DIR/test.target --score_path $save_dir/test_bleu.json --task translation $@ run_generate(verbose=True)
267
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase : Union[str, Any] = {'configuration_sew': ['SEW_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SEWConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Union[str, Any] = [ 'SEW_PRETRAINED_MODEL_ARCHIVE_LIST', 'SEWForCTC', 'SEWForSequenceClassification', 'SEWModel', 'SEWPreTrainedModel', ] if TYPE_CHECKING: from .configuration_sew import SEW_PRETRAINED_CONFIG_ARCHIVE_MAP, SEWConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_sew import ( SEW_PRETRAINED_MODEL_ARCHIVE_LIST, SEWForCTC, SEWForSequenceClassification, SEWModel, SEWPreTrainedModel, ) else: import sys UpperCAmelCase : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
267
1
'''simple docstring''' from __future__ import annotations import time UpperCAmelCase : Dict = list[tuple[int, int]] UpperCAmelCase : List[str] = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] UpperCAmelCase : List[str] = [[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right class lowerCAmelCase__ : """simple docstring""" def __init__( self : Optional[Any] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Node | None ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = pos_x __SCREAMING_SNAKE_CASE = pos_y __SCREAMING_SNAKE_CASE = (pos_y, pos_x) __SCREAMING_SNAKE_CASE = goal_x __SCREAMING_SNAKE_CASE = goal_y __SCREAMING_SNAKE_CASE = parent class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : tuple[int, int] , __SCREAMING_SNAKE_CASE : tuple[int, int] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = Node(start[1] , start[0] , goal[1] , goal[0] , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = Node(goal[1] , goal[0] , goal[1] , goal[0] , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = [self.start] __SCREAMING_SNAKE_CASE = False def UpperCAmelCase__ ( self : str ) -> Path | None: """simple docstring""" while self.node_queue: __SCREAMING_SNAKE_CASE = self.node_queue.pop(0 ) if current_node.pos == self.target.pos: __SCREAMING_SNAKE_CASE = True return self.retrace_path(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.get_successors(__SCREAMING_SNAKE_CASE ) for node in successors: self.node_queue.append(__SCREAMING_SNAKE_CASE ) if not self.reached: return [self.start.pos] return None def UpperCAmelCase__ ( self : Dict , __SCREAMING_SNAKE_CASE : Node ) -> list[Node]: """simple docstring""" __SCREAMING_SNAKE_CASE = [] for action in delta: __SCREAMING_SNAKE_CASE = parent.pos_x + action[1] __SCREAMING_SNAKE_CASE = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(__SCREAMING_SNAKE_CASE ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , self.target.pos_y , self.target.pos_x , __SCREAMING_SNAKE_CASE ) ) return successors def UpperCAmelCase__ ( self : List[str] , __SCREAMING_SNAKE_CASE : Node | None ) -> Path: """simple docstring""" __SCREAMING_SNAKE_CASE = node __SCREAMING_SNAKE_CASE = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) __SCREAMING_SNAKE_CASE = current_node.parent path.reverse() return path class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = BreadthFirstSearch(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = BreadthFirstSearch(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = False def UpperCAmelCase__ ( self : List[str] ) -> Path | None: """simple docstring""" while self.fwd_bfs.node_queue or self.bwd_bfs.node_queue: __SCREAMING_SNAKE_CASE = self.fwd_bfs.node_queue.pop(0 ) __SCREAMING_SNAKE_CASE = self.bwd_bfs.node_queue.pop(0 ) if current_bwd_node.pos == current_fwd_node.pos: __SCREAMING_SNAKE_CASE = True return self.retrace_bidirectional_path( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = current_bwd_node __SCREAMING_SNAKE_CASE = current_fwd_node __SCREAMING_SNAKE_CASE = { self.fwd_bfs: self.fwd_bfs.get_successors(__SCREAMING_SNAKE_CASE ), self.bwd_bfs: self.bwd_bfs.get_successors(__SCREAMING_SNAKE_CASE ), } for bfs in [self.fwd_bfs, self.bwd_bfs]: for node in successors[bfs]: bfs.node_queue.append(__SCREAMING_SNAKE_CASE ) if not self.reached: return [self.fwd_bfs.start.pos] return None def UpperCAmelCase__ ( self : Dict , __SCREAMING_SNAKE_CASE : Node , __SCREAMING_SNAKE_CASE : Node ) -> Path: """simple docstring""" __SCREAMING_SNAKE_CASE = self.fwd_bfs.retrace_path(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.bwd_bfs.retrace_path(__SCREAMING_SNAKE_CASE ) bwd_path.pop() bwd_path.reverse() __SCREAMING_SNAKE_CASE = fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] import doctest doctest.testmod() UpperCAmelCase : List[str] = (0, 0) UpperCAmelCase : Optional[Any] = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) UpperCAmelCase : Union[str, Any] = time.time() UpperCAmelCase : int = BreadthFirstSearch(init, goal) UpperCAmelCase : int = bfs.search() UpperCAmelCase : Optional[Any] = time.time() - start_bfs_time print('Unidirectional BFS computation time : ', bfs_time) UpperCAmelCase : Tuple = time.time() UpperCAmelCase : List[Any] = BidirectionalBreadthFirstSearch(init, goal) UpperCAmelCase : str = bd_bfs.search() UpperCAmelCase : Any = time.time() - start_bd_bfs_time print('Bidirectional BFS computation time : ', bd_bfs_time)
267
'''simple docstring''' class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Any ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = name __SCREAMING_SNAKE_CASE = value __SCREAMING_SNAKE_CASE = weight def __repr__( self : str ) -> Union[str, Any]: """simple docstring""" return f'{self.__class__.__name__}({self.name}, {self.value}, {self.weight})' def UpperCAmelCase__ ( self : List[Any] ) -> List[Any]: """simple docstring""" return self.value def UpperCAmelCase__ ( self : Any ) -> str: """simple docstring""" return self.name def UpperCAmelCase__ ( self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" return self.weight def UpperCAmelCase__ ( self : int ) -> Tuple: """simple docstring""" return self.value / self.weight def a__ ( a__ , a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = [] for i in range(len(a__ ) ): menu.append(Things(name[i] , value[i] , weight[i] ) ) return menu def a__ ( a__ , a__ , a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = sorted(a__ , key=a__ , reverse=a__ ) __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = 0.0, 0.0 for i in range(len(a__ ) ): if (total_cost + items_copy[i].get_weight()) <= max_cost: result.append(items_copy[i] ) total_cost += items_copy[i].get_weight() total_value += items_copy[i].get_value() return (result, total_value) def a__ ( ): """simple docstring""" if __name__ == "__main__": import doctest doctest.testmod()
267
1
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto.configuration_auto import CONFIG_MAPPING UpperCAmelCase : Optional[int] = logging.get_logger(__name__) class lowerCAmelCase__ ( a ): """simple docstring""" lowerCAmelCase__ = "upernet" def __init__( self : Any , __SCREAMING_SNAKE_CASE : Tuple=None , __SCREAMING_SNAKE_CASE : Dict=512 , __SCREAMING_SNAKE_CASE : List[Any]=0.02 , __SCREAMING_SNAKE_CASE : Optional[int]=[1, 2, 3, 6] , __SCREAMING_SNAKE_CASE : str=True , __SCREAMING_SNAKE_CASE : List[Any]=0.4 , __SCREAMING_SNAKE_CASE : List[str]=384 , __SCREAMING_SNAKE_CASE : List[Any]=256 , __SCREAMING_SNAKE_CASE : str=1 , __SCREAMING_SNAKE_CASE : Any=False , __SCREAMING_SNAKE_CASE : str=255 , **__SCREAMING_SNAKE_CASE : Optional[Any] , ) -> Optional[Any]: """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) if backbone_config is None: logger.info("""`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.""" ) __SCREAMING_SNAKE_CASE = CONFIG_MAPPING["""resnet"""](out_features=["""stage1""", """stage2""", """stage3""", """stage4"""] ) elif isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): __SCREAMING_SNAKE_CASE = backbone_config.get("""model_type""" ) __SCREAMING_SNAKE_CASE = CONFIG_MAPPING[backbone_model_type] __SCREAMING_SNAKE_CASE = config_class.from_dict(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = backbone_config __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = pool_scales __SCREAMING_SNAKE_CASE = use_auxiliary_head __SCREAMING_SNAKE_CASE = auxiliary_loss_weight __SCREAMING_SNAKE_CASE = auxiliary_in_channels __SCREAMING_SNAKE_CASE = auxiliary_channels __SCREAMING_SNAKE_CASE = auxiliary_num_convs __SCREAMING_SNAKE_CASE = auxiliary_concat_input __SCREAMING_SNAKE_CASE = loss_ignore_index def UpperCAmelCase__ ( self : str ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = copy.deepcopy(self.__dict__ ) __SCREAMING_SNAKE_CASE = self.backbone_config.to_dict() __SCREAMING_SNAKE_CASE = self.__class__.model_type return output
267
'''simple docstring''' import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import CLIPImageProcessor, CLIPProcessor @require_vision class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : Union[str, Any] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() # fmt: off __SCREAMING_SNAKE_CASE = ["""l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """lo""", """l</w>""", """w</w>""", """r</w>""", """t</w>""", """low</w>""", """er</w>""", """lowest</w>""", """newer</w>""", """wider""", """<unk>""", """<|startoftext|>""", """<|endoftext|>"""] # fmt: on __SCREAMING_SNAKE_CASE = dict(zip(__SCREAMING_SNAKE_CASE , range(len(__SCREAMING_SNAKE_CASE ) ) ) ) __SCREAMING_SNAKE_CASE = ["""#version: 0.2""", """l o""", """lo w</w>""", """e r</w>""", """"""] __SCREAMING_SNAKE_CASE = {"""unk_token""": """<unk>"""} __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) __SCREAMING_SNAKE_CASE = 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(__SCREAMING_SNAKE_CASE ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = { """do_resize""": True, """size""": 20, """do_center_crop""": True, """crop_size""": 18, """do_normalize""": True, """image_mean""": [0.48145466, 0.4578275, 0.40821073], """image_std""": [0.26862954, 0.26130258, 0.27577711], } __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , __SCREAMING_SNAKE_CASE ) with open(self.image_processor_file , """w""" , encoding="""utf-8""" ) as fp: json.dump(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] , **__SCREAMING_SNAKE_CASE : Optional[int] ) -> str: """simple docstring""" return CLIPTokenizer.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Tuple , **__SCREAMING_SNAKE_CASE : Any ) -> int: """simple docstring""" return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[Any] , **__SCREAMING_SNAKE_CASE : Optional[int] ) -> List[str]: """simple docstring""" return CLIPImageProcessor.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Tuple ) -> str: """simple docstring""" shutil.rmtree(self.tmpdirname ) def UpperCAmelCase__ ( self : Optional[Any] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __SCREAMING_SNAKE_CASE = [Image.fromarray(np.moveaxis(__SCREAMING_SNAKE_CASE , 0 , -1 ) ) for x in image_inputs] return image_inputs def UpperCAmelCase__ ( self : Optional[int] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = self.get_rust_tokenizer() __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) processor_slow.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = CLIPProcessor.from_pretrained(self.tmpdirname , use_fast=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) processor_fast.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = CLIPProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , __SCREAMING_SNAKE_CASE ) self.assertIsInstance(processor_fast.tokenizer , __SCREAMING_SNAKE_CASE ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , __SCREAMING_SNAKE_CASE ) self.assertIsInstance(processor_fast.image_processor , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) __SCREAMING_SNAKE_CASE = self.get_image_processor(do_normalize=__SCREAMING_SNAKE_CASE , padding_value=1.0 ) __SCREAMING_SNAKE_CASE = CLIPProcessor.from_pretrained( self.tmpdirname , bos_token="""(BOS)""" , eos_token="""(EOS)""" , do_normalize=__SCREAMING_SNAKE_CASE , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , __SCREAMING_SNAKE_CASE ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[str] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = image_processor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ) __SCREAMING_SNAKE_CASE = processor(images=__SCREAMING_SNAKE_CASE , return_tensors="""np""" ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1E-2 ) def UpperCAmelCase__ ( self : List[Any] ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """lower newer""" __SCREAMING_SNAKE_CASE = processor(text=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer(__SCREAMING_SNAKE_CASE ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def UpperCAmelCase__ ( self : Dict ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """lower newer""" __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = processor(text=__SCREAMING_SNAKE_CASE , images=__SCREAMING_SNAKE_CASE ) self.assertListEqual(list(inputs.keys() ) , ["""input_ids""", """attention_mask""", """pixel_values"""] ) # test if it raises when no input is passed with pytest.raises(__SCREAMING_SNAKE_CASE ): processor() def UpperCAmelCase__ ( self : List[str] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __SCREAMING_SNAKE_CASE = processor.batch_decode(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer.batch_decode(__SCREAMING_SNAKE_CASE ) self.assertListEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : int ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """lower newer""" __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = processor(text=__SCREAMING_SNAKE_CASE , images=__SCREAMING_SNAKE_CASE ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
267
1
'''simple docstring''' import torch from diffusers import DPMSolverSDEScheduler from diffusers.utils import torch_device from diffusers.utils.testing_utils import require_torchsde from .test_schedulers import SchedulerCommonTest @require_torchsde class lowerCAmelCase__ ( a ): """simple docstring""" lowerCAmelCase__ = (DPMSolverSDEScheduler,) lowerCAmelCase__ = 10 def UpperCAmelCase__ ( self : str , **__SCREAMING_SNAKE_CASE : Union[str, Any] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = { """num_train_timesteps""": 1_100, """beta_start""": 0.0001, """beta_end""": 0.02, """beta_schedule""": """linear""", """noise_sampler_seed""": 0, } config.update(**__SCREAMING_SNAKE_CASE ) return config def UpperCAmelCase__ ( self : str ) -> str: """simple docstring""" for timesteps in [10, 50, 100, 1_000]: self.check_over_configs(num_train_timesteps=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[Any] ) -> List[Any]: """simple docstring""" for beta_start, beta_end in zip([0.00001, 0.0001, 0.001] , [0.0002, 0.002, 0.02] ): self.check_over_configs(beta_start=__SCREAMING_SNAKE_CASE , beta_end=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Dict ) -> List[str]: """simple docstring""" for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = self.scheduler_classes[0] __SCREAMING_SNAKE_CASE = self.get_scheduler_config() __SCREAMING_SNAKE_CASE = scheduler_class(**__SCREAMING_SNAKE_CASE ) scheduler.set_timesteps(self.num_inference_steps ) __SCREAMING_SNAKE_CASE = self.dummy_model() __SCREAMING_SNAKE_CASE = self.dummy_sample_deter * scheduler.init_noise_sigma __SCREAMING_SNAKE_CASE = sample.to(__SCREAMING_SNAKE_CASE ) for i, t in enumerate(scheduler.timesteps ): __SCREAMING_SNAKE_CASE = scheduler.scale_model_input(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = scheduler.step(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = output.prev_sample __SCREAMING_SNAKE_CASE = torch.sum(torch.abs(__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = torch.mean(torch.abs(__SCREAMING_SNAKE_CASE ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 167.47821044921875 ) < 1E-2 assert abs(result_mean.item() - 0.2178705964565277 ) < 1E-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 171.59352111816406 ) < 1E-2 assert abs(result_mean.item() - 0.22342906892299652 ) < 1E-3 else: assert abs(result_sum.item() - 162.52383422851562 ) < 1E-2 assert abs(result_mean.item() - 0.211619570851326 ) < 1E-3 def UpperCAmelCase__ ( self : List[str] ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = self.scheduler_classes[0] __SCREAMING_SNAKE_CASE = self.get_scheduler_config(prediction_type="""v_prediction""" ) __SCREAMING_SNAKE_CASE = scheduler_class(**__SCREAMING_SNAKE_CASE ) scheduler.set_timesteps(self.num_inference_steps ) __SCREAMING_SNAKE_CASE = self.dummy_model() __SCREAMING_SNAKE_CASE = self.dummy_sample_deter * scheduler.init_noise_sigma __SCREAMING_SNAKE_CASE = sample.to(__SCREAMING_SNAKE_CASE ) for i, t in enumerate(scheduler.timesteps ): __SCREAMING_SNAKE_CASE = scheduler.scale_model_input(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = scheduler.step(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = output.prev_sample __SCREAMING_SNAKE_CASE = torch.sum(torch.abs(__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = torch.mean(torch.abs(__SCREAMING_SNAKE_CASE ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 124.77149200439453 ) < 1E-2 assert abs(result_mean.item() - 0.16226289014816284 ) < 1E-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 128.1663360595703 ) < 1E-2 assert abs(result_mean.item() - 0.16688326001167297 ) < 1E-3 else: assert abs(result_sum.item() - 119.8487548828125 ) < 1E-2 assert abs(result_mean.item() - 0.1560530662536621 ) < 1E-3 def UpperCAmelCase__ ( self : Dict ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.scheduler_classes[0] __SCREAMING_SNAKE_CASE = self.get_scheduler_config() __SCREAMING_SNAKE_CASE = scheduler_class(**__SCREAMING_SNAKE_CASE ) scheduler.set_timesteps(self.num_inference_steps , device=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.dummy_model() __SCREAMING_SNAKE_CASE = self.dummy_sample_deter.to(__SCREAMING_SNAKE_CASE ) * scheduler.init_noise_sigma for t in scheduler.timesteps: __SCREAMING_SNAKE_CASE = scheduler.scale_model_input(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = scheduler.step(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = output.prev_sample __SCREAMING_SNAKE_CASE = torch.sum(torch.abs(__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = torch.mean(torch.abs(__SCREAMING_SNAKE_CASE ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 167.46957397460938 ) < 1E-2 assert abs(result_mean.item() - 0.21805934607982635 ) < 1E-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 171.59353637695312 ) < 1E-2 assert abs(result_mean.item() - 0.22342908382415771 ) < 1E-3 else: assert abs(result_sum.item() - 162.52383422851562 ) < 1E-2 assert abs(result_mean.item() - 0.211619570851326 ) < 1E-3 def UpperCAmelCase__ ( self : Tuple ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.scheduler_classes[0] __SCREAMING_SNAKE_CASE = self.get_scheduler_config() __SCREAMING_SNAKE_CASE = scheduler_class(**__SCREAMING_SNAKE_CASE , use_karras_sigmas=__SCREAMING_SNAKE_CASE ) scheduler.set_timesteps(self.num_inference_steps , device=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.dummy_model() __SCREAMING_SNAKE_CASE = self.dummy_sample_deter.to(__SCREAMING_SNAKE_CASE ) * scheduler.init_noise_sigma __SCREAMING_SNAKE_CASE = sample.to(__SCREAMING_SNAKE_CASE ) for t in scheduler.timesteps: __SCREAMING_SNAKE_CASE = scheduler.scale_model_input(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = model(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = scheduler.step(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = output.prev_sample __SCREAMING_SNAKE_CASE = torch.sum(torch.abs(__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = torch.mean(torch.abs(__SCREAMING_SNAKE_CASE ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 176.66974135742188 ) < 1E-2 assert abs(result_mean.item() - 0.23003872730981811 ) < 1E-2 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 177.63653564453125 ) < 1E-2 assert abs(result_mean.item() - 0.23003872730981811 ) < 1E-2 else: assert abs(result_sum.item() - 170.3135223388672 ) < 1E-2 assert abs(result_mean.item() - 0.23003872730981811 ) < 1E-2
267
'''simple docstring''' import numpy as np def a__ ( a__ , a__ , a__ = 1E-1_2 , a__ = 1_00 , ): """simple docstring""" assert np.shape(a__ )[0] == np.shape(a__ )[1] # Ensure proper dimensionality. assert np.shape(a__ )[0] == np.shape(a__ )[0] # Ensure inputs are either both complex or both real assert np.iscomplexobj(a__ ) == np.iscomplexobj(a__ ) __SCREAMING_SNAKE_CASE = np.iscomplexobj(a__ ) if is_complex: # Ensure complex input_matrix is Hermitian assert np.array_equal(a__ , input_matrix.conj().T ) # Set convergence to False. Will define convergence when we exceed max_iterations # or when we have small changes from one iteration to next. __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 1E1_2 while not convergence: # Multiple matrix by the vector. __SCREAMING_SNAKE_CASE = np.dot(a__ , a__ ) # Normalize the resulting output vector. __SCREAMING_SNAKE_CASE = w / np.linalg.norm(a__ ) # Find rayleigh quotient # (faster than usual b/c we know vector is normalized already) __SCREAMING_SNAKE_CASE = vector.conj().T if is_complex else vector.T __SCREAMING_SNAKE_CASE = np.dot(a__ , np.dot(a__ , a__ ) ) # Check convergence. __SCREAMING_SNAKE_CASE = np.abs(lambda_ - lambda_previous ) / lambda_ iterations += 1 if error <= error_tol or iterations >= max_iterations: __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = lambda_ if is_complex: __SCREAMING_SNAKE_CASE = np.real(lambda_ ) return lambda_, vector def a__ ( ): """simple docstring""" __SCREAMING_SNAKE_CASE = np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]] ) __SCREAMING_SNAKE_CASE = np.array([41, 4, 20] ) __SCREAMING_SNAKE_CASE = real_input_matrix.astype(np.complexaaa ) __SCREAMING_SNAKE_CASE = np.triu(1J * complex_input_matrix , 1 ) complex_input_matrix += imag_matrix complex_input_matrix += -1 * imag_matrix.T __SCREAMING_SNAKE_CASE = np.array([41, 4, 20] ).astype(np.complexaaa ) for problem_type in ["real", "complex"]: if problem_type == "real": __SCREAMING_SNAKE_CASE = real_input_matrix __SCREAMING_SNAKE_CASE = real_vector elif problem_type == "complex": __SCREAMING_SNAKE_CASE = complex_input_matrix __SCREAMING_SNAKE_CASE = complex_vector # Our implementation. __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = power_iteration(a__ , a__ ) # Numpy implementation. # Get eigenvalues and eigenvectors using built-in numpy # eigh (eigh used for symmetric or hermetian matrices). __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = np.linalg.eigh(a__ ) # Last eigenvalue is the maximum one. __SCREAMING_SNAKE_CASE = eigen_values[-1] # Last column in this matrix is eigenvector corresponding to largest eigenvalue. __SCREAMING_SNAKE_CASE = eigen_vectors[:, -1] # Check our implementation and numpy gives close answers. assert np.abs(eigen_value - eigen_value_max ) <= 1E-6 # Take absolute values element wise of each eigenvector. # as they are only unique to a minus sign. assert np.linalg.norm(np.abs(a__ ) - np.abs(a__ ) ) <= 1E-6 if __name__ == "__main__": import doctest doctest.testmod() test_power_iteration()
267
1
import argparse import json import os from collections import OrderedDict import numpy as np import tensorflow as tf import torch def _a ( a :Union[str, Any] ) -> List[str]: a = os.path.join(args.tf_model_dir , '''parameters.json''' ) a = json.loads(open(a ).read() ) if not params: raise ValueError( F"""It seems that the json file at {parameter_file} is empty. Make sure you have a correct json file.""" ) if not args.output.endswith('''.pt''' ): a = args.output + '''.pt''' a = OrderedDict() with tf.device('''/CPU:0''' ): a = tf.train.load_checkpoint(args.tf_model_dir ) a = reader.get_variable_to_shape_map() for key_name in shapes.keys(): a = reader.get_tensor(a ).astype(np.floataa ) if key_name.endswith('''/adam_m''' ) or key_name.endswith('''/adam_v''' ): continue if key_name.startswith('''pasts/''' ): if key_name.startswith('''pasts/mlp''' ): a = int(key_name[9] ) elif key_name.startswith('''pasts/out''' ): a = 8 a = '''model.sqout.%d.weight''' % (player * 2) # enter to nn.Sequencial with Tanh, so 2 at a time a = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix a = torch.tensor(a ) elif key_name.startswith('''model/moe''' ): a = int(key_name[9:].split('''/''' )[0] ) if key_name.endswith('''/switch_gating/kernel''' ): a = '''model.blocks.%d.feed_forward.mlp.router.classifier.weight''' % player a = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix a = torch.tensor(a ) elif key_name.endswith('''/softmlp/kernel''' ): a = '''model.blocks.%d.feed_forward.soft_bypass_mlp.weight''' % player a = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix a = torch.tensor(a ) elif key_name.endswith('''/wo/kernel''' ) or key_name.endswith('''/wi/kernel''' ): a = key_name[-9:-7] for i in range(16 ): a = '''model.blocks.%d.feed_forward.mlp.experts.expert_%d.%s.weight''' % (player, i, nlayer) a = ( vnp[i].transpose([1, 0] ).copy() ) # In Mesh-Tensorflow, it is one array, so it is divided a = torch.tensor(a ) elif key_name.startswith('''model/mlp''' ): a = int(key_name[9:].split('''/''' )[0] ) if key_name.endswith('''/p1/kernel''' ): a = '''model.blocks.%d.feed_forward.mlp.wi.weight''' % player a = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix a = torch.tensor(a ) elif key_name.endswith('''/p1/bias''' ): a = '''model.blocks.%d.feed_forward.mlp.wi.bias''' % player a = vnp.copy() # same because it is one dimensional a = torch.tensor(a ) elif key_name.endswith('''/p2/kernel''' ): a = '''model.blocks.%d.feed_forward.mlp.wo.weight''' % player a = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix a = torch.tensor(a ) elif key_name.endswith('''/p2/bias''' ): a = '''model.blocks.%d.feed_forward.mlp.wo.bias''' % player a = vnp.copy() # same because it is one dimensional a = torch.tensor(a ) elif key_name.startswith('''model/ln''' ): a = int(key_name[8:].split('''/''' )[0] ) if key_name.endswith('''/b''' ): a = '''model.blocks.%d.feed_forward.norm.bias''' % player a = vnp.copy() # same because it is one dimensional a = torch.tensor(a ) elif key_name.endswith('''/g''' ): a = '''model.blocks.%d.feed_forward.norm.weight''' % player a = vnp.copy() # same because it is one dimensional a = torch.tensor(a ) elif key_name.startswith('''model/att''' ): a = int(key_name[9:].split('''/''' )[0] ) if key_name.endswith('''/qkv/kernel''' ): a = vnp.copy() # Compute same dimension as Mesh-tensorflow using einsum a = state[:, 0, :, :] a = state[:, 1, :, :] a = state[:, 2, :, :] a = ( state_q.reshape([state_q.shape[0], state_q.shape[1] * state_q.shape[2]] ) .transpose([1, 0] ) .copy() ) # Mesh-Tensorflow is a diagonal matrix a = ( state_k.reshape([state_k.shape[0], state_k.shape[1] * state_k.shape[2]] ) .transpose([1, 0] ) .copy() ) # Mesh-Tensorflow is a diagonal matrix a = ( state_v.reshape([state_v.shape[0], state_v.shape[1] * state_v.shape[2]] ) .transpose([1, 0] ) .copy() ) # Mesh-Tensorflow is a diagonal matrix a = '''model.blocks.%d.self_attn.self_attn.q_proj.weight''' % player a = torch.tensor(a ) a = '''model.blocks.%d.self_attn.self_attn.k_proj.weight''' % player a = torch.tensor(a ) a = '''model.blocks.%d.self_attn.self_attn.v_proj.weight''' % player a = torch.tensor(a ) elif key_name.endswith('''/o/kernel''' ): a = '''model.blocks.%d.self_attn.self_attn.out_proj.weight''' % player a = ( vnp.reshape([vnp.shape[0] * vnp.shape[1], vnp.shape[2]] ).transpose([1, 0] ).copy() ) # Mesh-Tensorflow is a diagonal matrix a = torch.tensor(a ) elif key_name.startswith('''model/an''' ): a = int(key_name[8:].split('''/''' )[0] ) if key_name.endswith('''/b''' ): a = '''model.blocks.%d.self_attn.norm.bias''' % player a = vnp.copy() # same because it is one dimensional a = torch.tensor(a ) elif key_name.endswith('''/g''' ): a = '''model.blocks.%d.self_attn.norm.weight''' % player a = vnp.copy() # same because it is one dimensional a = torch.tensor(a ) elif ( key_name.startswith('''model/wte''' ) or key_name.startswith('''model/wpe''' ) or key_name.startswith('''model/ete''' ) ): a = {'''wte''': '''embed_tokens''', '''wpe''': '''position_embeddings''', '''ete''': '''extra_position_embeddings'''}[ key_name[-3:] ] a = '''model.%s.weight''' % nlayer a = vnp.copy() # same in embedded a = torch.tensor(a ) if key_name.startswith('''model/wte''' ): a = '''lm_head.weight''' a = vnp.copy() # same in embedded a = torch.tensor(a ) elif key_name.startswith('''model/wob''' ): a = '''final_logits_bias''' a = vnp.copy() # same in embedded a = state.reshape((1, -1) ) a = torch.tensor(a ) elif key_name == "model/dense/kernel": a = '''model.last_project.weight''' a = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix a = torch.tensor(a ) elif key_name == "model/dense_1/bias": a = '''model.last_project.bias''' a = vnp.copy() # same because it is one dimensional a = torch.tensor(a ) torch.save(a , args.output ) if __name__ == "__main__": UpperCAmelCase__ = argparse.ArgumentParser( description="model converter.", formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument("--tf_model_dir", metavar="PATH", type=str, required=True, help="import model") parser.add_argument("--output", metavar="PATH", type=str, required=True, help="output model") UpperCAmelCase__ = parser.parse_args() convert_tf_gptsan_to_pt(args)
0
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowerCAmelCase__ ( a , a , a , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = StableDiffusionInpaintPipeline lowerCAmelCase__ = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS lowerCAmelCase__ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS lowerCAmelCase__ = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess lowerCAmelCase__ = frozenset([] ) def UpperCAmelCase__ ( self : str ) -> List[Any]: """simple docstring""" torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=9 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=__SCREAMING_SNAKE_CASE , ) __SCREAMING_SNAKE_CASE = PNDMScheduler(skip_prk_steps=__SCREAMING_SNAKE_CASE ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act="""gelu""" , projection_dim=512 , ) __SCREAMING_SNAKE_CASE = CLIPTextModel(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) __SCREAMING_SNAKE_CASE = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def UpperCAmelCase__ ( self : Any , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : List[Any]=0 ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = floats_tensor((1, 3, 32, 32) , rng=random.Random(__SCREAMING_SNAKE_CASE ) ).to(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1 )[0] __SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(__SCREAMING_SNAKE_CASE ) ).convert("""RGB""" ).resize((64, 64) ) __SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(image + 4 ) ).convert("""RGB""" ).resize((64, 64) ) if str(__SCREAMING_SNAKE_CASE ).startswith("""mps""" ): __SCREAMING_SNAKE_CASE = torch.manual_seed(__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = torch.Generator(device=__SCREAMING_SNAKE_CASE ).manual_seed(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = { """prompt""": """A painting of a squirrel eating a burger""", """image""": init_image, """mask_image""": mask_image, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def UpperCAmelCase__ ( self : Union[str, Any] ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = """cpu""" # ensure determinism for the device-dependent torch.Generator __SCREAMING_SNAKE_CASE = self.get_dummy_components() __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = sd_pipe.to(__SCREAMING_SNAKE_CASE ) sd_pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.get_dummy_inputs(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = sd_pipe(**__SCREAMING_SNAKE_CASE ).images __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __SCREAMING_SNAKE_CASE = np.array([0.4727, 0.5735, 0.3941, 0.5446, 0.5926, 0.4394, 0.5062, 0.4654, 0.4476] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def UpperCAmelCase__ ( self : Tuple ) -> str: """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : List[Any] ) -> str: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase__ ( self : List[str] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) __SCREAMING_SNAKE_CASE = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench.npy""" ) __SCREAMING_SNAKE_CASE = """stabilityai/stable-diffusion-2-inpainting""" __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline.from_pretrained(__SCREAMING_SNAKE_CASE , safety_checker=__SCREAMING_SNAKE_CASE ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) pipe.enable_attention_slicing() __SCREAMING_SNAKE_CASE = """Face of a yellow cat, high resolution, sitting on a park bench""" __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , mask_image=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , output_type="""np""" , ) __SCREAMING_SNAKE_CASE = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 9E-3 def UpperCAmelCase__ ( self : List[Any] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) __SCREAMING_SNAKE_CASE = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench_fp16.npy""" ) __SCREAMING_SNAKE_CASE = """stabilityai/stable-diffusion-2-inpainting""" __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline.from_pretrained( __SCREAMING_SNAKE_CASE , torch_dtype=torch.floataa , safety_checker=__SCREAMING_SNAKE_CASE , ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) pipe.enable_attention_slicing() __SCREAMING_SNAKE_CASE = """Face of a yellow cat, high resolution, sitting on a park bench""" __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , mask_image=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , output_type="""np""" , ) __SCREAMING_SNAKE_CASE = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 5E-1 def UpperCAmelCase__ ( self : Tuple ) -> Any: """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) __SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) __SCREAMING_SNAKE_CASE = """stabilityai/stable-diffusion-2-inpainting""" __SCREAMING_SNAKE_CASE = PNDMScheduler.from_pretrained(__SCREAMING_SNAKE_CASE , subfolder="""scheduler""" ) __SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline.from_pretrained( __SCREAMING_SNAKE_CASE , safety_checker=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE , torch_dtype=torch.floataa , ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() __SCREAMING_SNAKE_CASE = """Face of a yellow cat, high resolution, sitting on a park bench""" __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , mask_image=__SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , num_inference_steps=2 , output_type="""np""" , ) __SCREAMING_SNAKE_CASE = torch.cuda.max_memory_allocated() # make sure that less than 2.65 GB is allocated assert mem_bytes < 2.65 * 10**9
267
0