code
stringlengths
81
54k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str ) -> list: """simple docstring""" SCREAMING_SNAKE_CASE_ : int = [0] * len(SCREAMING_SNAKE_CASE_ ) for i in range(1 , len(SCREAMING_SNAKE_CASE_ ) ): # use last results for better performance - dynamic programming SCREAMING_SNAKE_CASE_ : Optional[int] = prefix_result[i - 1] while j > 0 and input_string[i] != input_string[j]: SCREAMING_SNAKE_CASE_ : Optional[int] = prefix_result[j - 1] if input_string[i] == input_string[j]: j += 1 SCREAMING_SNAKE_CASE_ : Optional[int] = j return prefix_result def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str ) -> int: """simple docstring""" return max(prefix_function(SCREAMING_SNAKE_CASE_ ) ) if __name__ == "__main__": import doctest doctest.testmod()
68
'''simple docstring''' import logging import os import sys from pathlib import Path from unittest.mock import patch from parameterized import parameterized from run_eval import run_generate from run_eval_search import run_search from transformers.testing_utils import CaptureStdout, TestCasePlus, slow from utils import ROUGE_KEYS logging.basicConfig(level=logging.DEBUG) snake_case_ = logging.getLogger() def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Path , SCREAMING_SNAKE_CASE_ : list ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = "\n".join(SCREAMING_SNAKE_CASE_ ) Path(SCREAMING_SNAKE_CASE_ ).open("w" ).writelines(SCREAMING_SNAKE_CASE_ ) snake_case_ = 'patrickvonplaten/t5-tiny-random' snake_case_ = 'sshleifer/bart-tiny-random' snake_case_ = 'sshleifer/tiny-mbart' snake_case_ = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) logging.disable(logging.CRITICAL) # remove noisy download output from tracebacks class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = Path(self.get_auto_remove_tmp_dir() ) / "utest_input.source" SCREAMING_SNAKE_CASE_ : List[str] = input_file_name.parent / "utest_output.txt" assert not output_file_name.exists() SCREAMING_SNAKE_CASE_ : Dict = [" New York (CNN)When Liana Barrientos was 23 years old, she got married in Westchester County."] _dump_articles(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : Tuple = str(Path(self.get_auto_remove_tmp_dir() ) / "scores.json" ) SCREAMING_SNAKE_CASE_ : Tuple = "translation_en_to_de" if model == T5_TINY else "summarization" SCREAMING_SNAKE_CASE_ : Dict = F"\n run_eval_search.py\n {model}\n {input_file_name}\n {output_file_name}\n --score_path {score_path}\n --task {task}\n --num_beams 2\n --length_penalty 2.0\n ".split() with patch.object(lowercase__ , "argv" , lowercase__ ): run_generate() assert Path(lowercase__ ).exists() # os.remove(Path(output_file_name)) def __lowerCamelCase ( self ): """simple docstring""" self.run_eval_tester(lowercase__ ) @parameterized.expand([BART_TINY, MBART_TINY] ) @slow def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" self.run_eval_tester(lowercase__ ) @parameterized.expand([T5_TINY, MBART_TINY] ) @slow def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = Path(self.get_auto_remove_tmp_dir() ) / "utest_input.source" SCREAMING_SNAKE_CASE_ : Optional[Any] = input_file_name.parent / "utest_output.txt" assert not output_file_name.exists() SCREAMING_SNAKE_CASE_ : List[Any] = { "en": ["Machine learning is great, isn't it?", "I like to eat bananas", "Tomorrow is another great day!"], "de": [ "Maschinelles Lernen ist großartig, oder?", "Ich esse gerne Bananen", "Morgen ist wieder ein toller Tag!", ], } SCREAMING_SNAKE_CASE_ : Dict = Path(self.get_auto_remove_tmp_dir() ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = str(tmp_dir / "scores.json" ) SCREAMING_SNAKE_CASE_ : List[Any] = str(tmp_dir / "val.target" ) _dump_articles(lowercase__ , text["en"] ) _dump_articles(lowercase__ , text["de"] ) SCREAMING_SNAKE_CASE_ : List[Any] = "translation_en_to_de" if model == T5_TINY else "summarization" SCREAMING_SNAKE_CASE_ : List[str] = F"\n run_eval_search.py\n {model}\n {str(lowercase__ )}\n {str(lowercase__ )}\n --score_path {score_path}\n --reference_path {reference_path}\n --task {task}\n ".split() testargs.extend(["--search", "num_beams=1:2 length_penalty=0.9:1.0"] ) with patch.object(lowercase__ , "argv" , lowercase__ ): with CaptureStdout() as cs: run_search() SCREAMING_SNAKE_CASE_ : Union[str, Any] = [" num_beams | length_penalty", model, "Best score args"] SCREAMING_SNAKE_CASE_ : Optional[Any] = ["Info"] if "translation" in task: expected_strings.append("bleu" ) else: expected_strings.extend(lowercase__ ) for w in expected_strings: assert w in cs.out for w in un_expected_strings: assert w not in cs.out assert Path(lowercase__ ).exists() os.remove(Path(lowercase__ ) )
68
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices snake_case_ = logging.get_logger(__name__) snake_case_ = { 'google/bit-50': 'https://huggingface.co/google/bit-50/resolve/main/config.json', } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,_UpperCAmelCase ): _A = "bit" _A = ["preactivation", "bottleneck"] _A = ["SAME", "VALID"] def __init__( self , lowercase__=3 , lowercase__=64 , lowercase__=[256, 512, 1024, 2048] , lowercase__=[3, 4, 6, 3] , lowercase__="preactivation" , lowercase__="relu" , lowercase__=None , lowercase__=32 , lowercase__=0.0 , lowercase__=False , lowercase__=32 , lowercase__=1 , lowercase__=None , lowercase__=None , **lowercase__ , ): """simple docstring""" super().__init__(**lowercase__ ) if layer_type not in self.layer_types: raise ValueError(F"layer_type={layer_type} is not one of {','.join(self.layer_types )}" ) if global_padding is not None: if global_padding.upper() in self.supported_padding: SCREAMING_SNAKE_CASE_ : int = global_padding.upper() else: raise ValueError(F"Padding strategy {global_padding} not supported" ) SCREAMING_SNAKE_CASE_ : Optional[int] = num_channels SCREAMING_SNAKE_CASE_ : Any = embedding_size SCREAMING_SNAKE_CASE_ : List[str] = hidden_sizes SCREAMING_SNAKE_CASE_ : Optional[int] = depths SCREAMING_SNAKE_CASE_ : str = layer_type SCREAMING_SNAKE_CASE_ : List[str] = hidden_act SCREAMING_SNAKE_CASE_ : Union[str, Any] = global_padding SCREAMING_SNAKE_CASE_ : Optional[int] = num_groups SCREAMING_SNAKE_CASE_ : List[str] = drop_path_rate SCREAMING_SNAKE_CASE_ : List[str] = embedding_dynamic_padding SCREAMING_SNAKE_CASE_ : Tuple = output_stride SCREAMING_SNAKE_CASE_ : int = width_factor SCREAMING_SNAKE_CASE_ : Tuple = ["stem"] + [F"stage{idx}" for idx in range(1 , len(lowercase__ ) + 1 )] SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[Any] = get_aligned_output_features_output_indices( out_features=lowercase__ , out_indices=lowercase__ , stage_names=self.stage_names )
68
'''simple docstring''' from __future__ import annotations import numpy as np from numpy import floataa from numpy.typing import NDArray def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : NDArray[floataa] , SCREAMING_SNAKE_CASE_ : NDArray[floataa] , SCREAMING_SNAKE_CASE_ : list[int] , SCREAMING_SNAKE_CASE_ : int , ) -> list[float]: """simple docstring""" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : str = coefficient_matrix.shape SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : List[Any] = constant_matrix.shape if rowsa != colsa: SCREAMING_SNAKE_CASE_ : Union[str, Any] = F"Coefficient matrix dimensions must be nxn but received {rowsa}x{colsa}" raise ValueError(SCREAMING_SNAKE_CASE_ ) if colsa != 1: SCREAMING_SNAKE_CASE_ : List[Any] = F"Constant matrix must be nx1 but received {rowsa}x{colsa}" raise ValueError(SCREAMING_SNAKE_CASE_ ) if rowsa != rowsa: SCREAMING_SNAKE_CASE_ : Any = ( "Coefficient and constant matrices dimensions must be nxn and nx1 but " F"received {rowsa}x{colsa} and {rowsa}x{colsa}" ) raise ValueError(SCREAMING_SNAKE_CASE_ ) if len(SCREAMING_SNAKE_CASE_ ) != rowsa: SCREAMING_SNAKE_CASE_ : int = ( "Number of initial values must be equal to number of rows in coefficient " F"matrix but received {len(SCREAMING_SNAKE_CASE_ )} and {rowsa}" ) raise ValueError(SCREAMING_SNAKE_CASE_ ) if iterations <= 0: raise ValueError("Iterations must be at least 1" ) SCREAMING_SNAKE_CASE_ : NDArray[floataa] = np.concatenate( (coefficient_matrix, constant_matrix) , axis=1 ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Any = table.shape strictly_diagonally_dominant(SCREAMING_SNAKE_CASE_ ) # Iterates the whole matrix for given number of times for _ in range(SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ : Tuple = [] for row in range(SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ : Any = 0 for col in range(SCREAMING_SNAKE_CASE_ ): if col == row: SCREAMING_SNAKE_CASE_ : Any = table[row][col] elif col == cols - 1: SCREAMING_SNAKE_CASE_ : Dict = table[row][col] else: temp += (-1) * table[row][col] * init_val[col] SCREAMING_SNAKE_CASE_ : Optional[Any] = (temp + val) / denom new_val.append(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = new_val return [float(SCREAMING_SNAKE_CASE_ ) for i in new_val] def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : NDArray[floataa] ) -> bool: """simple docstring""" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = table.shape SCREAMING_SNAKE_CASE_ : Tuple = True for i in range(0 , SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ : int = 0 for j in range(0 , cols - 1 ): if i == j: continue else: total += table[i][j] if table[i][i] <= total: raise ValueError("Coefficient matrix is not strictly diagonally dominant" ) return is_diagonally_dominant # Test Cases if __name__ == "__main__": import doctest doctest.testmod()
68
1
'''simple docstring''' from manim import * class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = Rectangle(height=0.5 , width=0.5 ) SCREAMING_SNAKE_CASE_ : int = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0 ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = Rectangle(height=0.25 , width=0.25 ) SCREAMING_SNAKE_CASE_ : List[str] = [mem.copy() for i in range(6 )] SCREAMING_SNAKE_CASE_ : Any = [mem.copy() for i in range(6 )] SCREAMING_SNAKE_CASE_ : List[Any] = VGroup(*lowercase__ ).arrange(lowercase__ , buff=0 ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = VGroup(*lowercase__ ).arrange(lowercase__ , buff=0 ) SCREAMING_SNAKE_CASE_ : Optional[int] = VGroup(lowercase__ , lowercase__ ).arrange(lowercase__ , buff=0 ) SCREAMING_SNAKE_CASE_ : List[str] = Text("CPU" , font_size=24 ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = Group(lowercase__ , lowercase__ ).arrange(lowercase__ , buff=0.5 , aligned_edge=lowercase__ ) cpu.move_to([-2.5, -0.5, 0] ) self.add(lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = [mem.copy() for i in range(4 )] SCREAMING_SNAKE_CASE_ : Union[str, Any] = VGroup(*lowercase__ ).arrange(lowercase__ , buff=0 ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = Text("GPU" , font_size=24 ) SCREAMING_SNAKE_CASE_ : Any = Group(lowercase__ , lowercase__ ).arrange(lowercase__ , buff=0.5 , aligned_edge=lowercase__ ) gpu.move_to([-1, -1, 0] ) self.add(lowercase__ ) SCREAMING_SNAKE_CASE_ : str = [mem.copy() for i in range(6 )] SCREAMING_SNAKE_CASE_ : Tuple = VGroup(*lowercase__ ).arrange(lowercase__ , buff=0 ) SCREAMING_SNAKE_CASE_ : Any = Text("Model" , font_size=24 ) SCREAMING_SNAKE_CASE_ : str = Group(lowercase__ , lowercase__ ).arrange(lowercase__ , buff=0.5 , aligned_edge=lowercase__ ) model.move_to([3, -1.0, 0] ) self.add(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = [] SCREAMING_SNAKE_CASE_ : List[str] = [] for i, rect in enumerate(lowercase__ ): SCREAMING_SNAKE_CASE_ : Any = fill.copy().set_fill(lowercase__ , opacity=0.8 ) target.move_to(lowercase__ ) model_arr.append(lowercase__ ) SCREAMING_SNAKE_CASE_ : int = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0.0 ).set_fill(lowercase__ , opacity=0.8 ) cpu_target.move_to(cpu_left_col_base[i] ) model_cpu_arr.append(lowercase__ ) self.add(*lowercase__ , *lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = [meta_mem.copy() for i in range(6 )] SCREAMING_SNAKE_CASE_ : Optional[int] = [meta_mem.copy() for i in range(6 )] SCREAMING_SNAKE_CASE_ : List[str] = VGroup(*lowercase__ ).arrange(lowercase__ , buff=0 ) SCREAMING_SNAKE_CASE_ : Dict = VGroup(*lowercase__ ).arrange(lowercase__ , buff=0 ) SCREAMING_SNAKE_CASE_ : Dict = VGroup(lowercase__ , lowercase__ ).arrange(lowercase__ , buff=0 ) SCREAMING_SNAKE_CASE_ : int = Text("Disk" , font_size=24 ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = Group(lowercase__ , lowercase__ ).arrange(lowercase__ , buff=0.5 , aligned_edge=lowercase__ ) disk.move_to([-4, -1.25, 0] ) self.add(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) SCREAMING_SNAKE_CASE_ : List[Any] = 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(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = MarkupText( F"<span fgcolor='{BLUE}'>●</span> Checkpoint" , font_size=18 , ) blue_text.next_to(lowercase__ , DOWN * 2.4 , aligned_edge=key_text.get_left() ) self.add(lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = 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(lowercase__ ) ) SCREAMING_SNAKE_CASE_ : Optional[int] = Square(0.3 ) input.set_fill(lowercase__ , opacity=1.0 ) input.set_stroke(width=0.0 ) input.next_to(model_base[0] , lowercase__ , buff=0.5 ) self.play(Write(lowercase__ ) ) input.generate_target() input.target.next_to(model_arr[0] , direction=lowercase__ , buff=0.02 ) self.play(MoveToTarget(lowercase__ ) ) self.play(FadeOut(lowercase__ ) ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = Arrow(start=lowercase__ , end=lowercase__ , color=lowercase__ , buff=0.5 ) a.next_to(model_arr[0].get_left() , lowercase__ , buff=0.2 ) model_cpu_arr[0].generate_target() model_cpu_arr[0].target.move_to(gpu_rect[0] ) SCREAMING_SNAKE_CASE_ : Optional[int] = 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(lowercase__ , run_time=3 ) ) SCREAMING_SNAKE_CASE_ : int = {"run_time": 1, "fade_in": True, "fade_out": True, "buff": 0.02} self.play( Write(lowercase__ ) , Circumscribe(model_arr[0] , color=lowercase__ , **lowercase__ ) , Circumscribe(model_cpu_arr[0] , color=lowercase__ , **lowercase__ ) , Circumscribe(gpu_rect[0] , color=lowercase__ , **lowercase__ ) , ) self.play(MoveToTarget(model_cpu_arr[0] ) ) SCREAMING_SNAKE_CASE_ : List[Any] = a.copy() for i in range(6 ): a_c.next_to(model_arr[i].get_right() + 0.02 , lowercase__ , buff=0.2 ) input.generate_target() input.target.move_to(model_arr[i].get_right() + 0.02 ) SCREAMING_SNAKE_CASE_ : Optional[int] = AnimationGroup( FadeOut(lowercase__ , run_time=0.5 ) , MoveToTarget(lowercase__ , run_time=0.5 ) , FadeIn(lowercase__ , run_time=0.5 ) , lag_ratio=0.2 ) self.play(lowercase__ ) 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_ : Any = 0.7 self.play( Circumscribe(model_arr[i] , **lowercase__ ) , Circumscribe(cpu_left_col_base[i] , **lowercase__ ) , Circumscribe(cpu_left_col_base[i + 1] , color=lowercase__ , **lowercase__ ) , Circumscribe(gpu_rect[0] , color=lowercase__ , **lowercase__ ) , Circumscribe(model_arr[i + 1] , color=lowercase__ , **lowercase__ ) , ) 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=lowercase__ , **lowercase__ ) , Circumscribe(cpu_left_col_base[-1] , color=lowercase__ , **lowercase__ ) , Circumscribe(gpu_rect[0] , color=lowercase__ , **lowercase__ ) , ) self.play(MoveToTarget(model_cpu_arr[i] ) ) SCREAMING_SNAKE_CASE_ : Dict = a_c SCREAMING_SNAKE_CASE_ : List[str] = a_c.copy() input.generate_target() input.target.next_to(model_base[-1] , RIGHT + 0.02 , buff=0.5 ) self.play( FadeOut(lowercase__ ) , FadeOut(lowercase__ , run_time=0.5 ) , ) SCREAMING_SNAKE_CASE_ : Tuple = 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(lowercase__ , run_time=3 ) , MoveToTarget(lowercase__ ) ) self.wait()
68
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int ) -> int: """simple docstring""" return 1 if input_a == input_a else 0 def __lowerCamelCase ( ) -> None: """simple docstring""" assert xnor_gate(0 , 0 ) == 1 assert xnor_gate(0 , 1 ) == 0 assert xnor_gate(1 , 0 ) == 0 assert xnor_gate(1 , 1 ) == 1 if __name__ == "__main__": print(xnor_gate(0, 0)) print(xnor_gate(0, 1)) print(xnor_gate(1, 0)) print(xnor_gate(1, 1))
68
1
'''simple docstring''' import argparse import copy def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Optional[Any] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = {} with open(SCREAMING_SNAKE_CASE_ ) as f: for line in f: if line.split()[0] not in dict_of_neighbours: SCREAMING_SNAKE_CASE_ : Tuple = [] _list.append([line.split()[1], line.split()[2]] ) SCREAMING_SNAKE_CASE_ : Dict = _list else: dict_of_neighbours[line.split()[0]].append( [line.split()[1], line.split()[2]] ) if line.split()[1] not in dict_of_neighbours: SCREAMING_SNAKE_CASE_ : List[Any] = [] _list.append([line.split()[0], line.split()[2]] ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = _list else: dict_of_neighbours[line.split()[1]].append( [line.split()[0], line.split()[2]] ) return dict_of_neighbours def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Any ) -> Dict: """simple docstring""" with open(SCREAMING_SNAKE_CASE_ ) as f: SCREAMING_SNAKE_CASE_ : Optional[Any] = f.read(1 ) SCREAMING_SNAKE_CASE_ : Any = start_node SCREAMING_SNAKE_CASE_ : Dict = [] SCREAMING_SNAKE_CASE_ : Tuple = start_node SCREAMING_SNAKE_CASE_ : Dict = 0 while visiting not in first_solution: SCREAMING_SNAKE_CASE_ : List[Any] = 1_0_0_0_0 for k in dict_of_neighbours[visiting]: if int(k[1] ) < int(SCREAMING_SNAKE_CASE_ ) and k[0] not in first_solution: SCREAMING_SNAKE_CASE_ : Dict = k[1] SCREAMING_SNAKE_CASE_ : Tuple = k[0] first_solution.append(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Tuple = distance_of_first_solution + int(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : int = best_node first_solution.append(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = 0 for k in dict_of_neighbours[first_solution[-2]]: if k[0] == start_node: break position += 1 SCREAMING_SNAKE_CASE_ : int = ( distance_of_first_solution + int(dict_of_neighbours[first_solution[-2]][position][1] ) - 1_0_0_0_0 ) return first_solution, distance_of_first_solution def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Union[str, Any] ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : int = [] for n in solution[1:-1]: SCREAMING_SNAKE_CASE_ : List[str] = solution.index(SCREAMING_SNAKE_CASE_ ) for kn in solution[1:-1]: SCREAMING_SNAKE_CASE_ : Optional[Any] = solution.index(SCREAMING_SNAKE_CASE_ ) if n == kn: continue SCREAMING_SNAKE_CASE_ : str = copy.deepcopy(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Tuple = kn SCREAMING_SNAKE_CASE_ : Union[str, Any] = n SCREAMING_SNAKE_CASE_ : Optional[Any] = 0 for k in _tmp[:-1]: SCREAMING_SNAKE_CASE_ : Optional[Any] = _tmp[_tmp.index(SCREAMING_SNAKE_CASE_ ) + 1] for i in dict_of_neighbours[k]: if i[0] == next_node: SCREAMING_SNAKE_CASE_ : Optional[int] = distance + int(i[1] ) _tmp.append(SCREAMING_SNAKE_CASE_ ) if _tmp not in neighborhood_of_solution: neighborhood_of_solution.append(_tmp ) SCREAMING_SNAKE_CASE_ : Tuple = len(neighborhood_of_solution[0] ) - 1 neighborhood_of_solution.sort(key=lambda SCREAMING_SNAKE_CASE_ : x[index_of_last_item_in_the_list] ) return neighborhood_of_solution def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Any ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = 1 SCREAMING_SNAKE_CASE_ : int = first_solution SCREAMING_SNAKE_CASE_ : Optional[Any] = [] SCREAMING_SNAKE_CASE_ : int = distance_of_first_solution SCREAMING_SNAKE_CASE_ : int = solution while count <= iters: SCREAMING_SNAKE_CASE_ : str = find_neighborhood(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : int = 0 SCREAMING_SNAKE_CASE_ : Dict = neighborhood[index_of_best_solution] SCREAMING_SNAKE_CASE_ : Optional[Any] = len(SCREAMING_SNAKE_CASE_ ) - 1 SCREAMING_SNAKE_CASE_ : Dict = False while not found: SCREAMING_SNAKE_CASE_ : List[str] = 0 while i < len(SCREAMING_SNAKE_CASE_ ): if best_solution[i] != solution[i]: SCREAMING_SNAKE_CASE_ : Dict = best_solution[i] SCREAMING_SNAKE_CASE_ : Optional[Any] = solution[i] break SCREAMING_SNAKE_CASE_ : int = i + 1 if [first_exchange_node, second_exchange_node] not in tabu_list and [ second_exchange_node, first_exchange_node, ] not in tabu_list: tabu_list.append([first_exchange_node, second_exchange_node] ) SCREAMING_SNAKE_CASE_ : Optional[Any] = True SCREAMING_SNAKE_CASE_ : Any = best_solution[:-1] SCREAMING_SNAKE_CASE_ : Optional[int] = neighborhood[index_of_best_solution][best_cost_index] if cost < best_cost: SCREAMING_SNAKE_CASE_ : Dict = cost SCREAMING_SNAKE_CASE_ : Dict = solution else: SCREAMING_SNAKE_CASE_ : List[Any] = index_of_best_solution + 1 SCREAMING_SNAKE_CASE_ : Tuple = neighborhood[index_of_best_solution] if len(SCREAMING_SNAKE_CASE_ ) >= size: tabu_list.pop(0 ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = count + 1 return best_solution_ever, best_cost def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str=None ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : int = generate_neighbours(args.File ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = generate_first_solution( args.File , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : str = tabu_search( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , args.Iterations , args.Size , ) print(F"Best solution: {best_sol}, with total distance: {best_cost}." ) if __name__ == "__main__": snake_case_ = argparse.ArgumentParser(description='Tabu Search') parser.add_argument( '-f', '--File', type=str, help='Path to the file containing the data', required=True, ) parser.add_argument( '-i', '--Iterations', type=int, help='How many iterations the algorithm should perform', required=True, ) parser.add_argument( '-s', '--Size', type=int, help='Size of the tabu list', required=True ) # Pass the arguments to main method main(parser.parse_args())
68
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , ) -> float: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = [redshift, radiation_density, matter_density, dark_energy] if any(p < 0 for p in parameters ): raise ValueError("All input parameters must be positive" ) if any(p > 1 for p in parameters[1:4] ): raise ValueError("Relative densities cannot be greater than one" ) else: SCREAMING_SNAKE_CASE_ : int = 1 - (matter_density + radiation_density + dark_energy) SCREAMING_SNAKE_CASE_ : List[Any] = ( radiation_density * (redshift + 1) ** 4 + matter_density * (redshift + 1) ** 3 + curvature * (redshift + 1) ** 2 + dark_energy ) SCREAMING_SNAKE_CASE_ : Dict = hubble_constant * e_a ** (1 / 2) return hubble if __name__ == "__main__": import doctest # run doctest doctest.testmod() # demo LCDM approximation snake_case_ = 0.3 print( hubble_parameter( hubble_constant=6_8.3, radiation_density=1E-4, matter_density=matter_density, dark_energy=1 - matter_density, redshift=0, ) )
68
1
'''simple docstring''' import json import os import tempfile from unittest.mock import patch import torch from torch.utils.data import DataLoader, TensorDataset from accelerate import DistributedType, infer_auto_device_map, init_empty_weights from accelerate.accelerator import Accelerator from accelerate.state import GradientState, PartialState from accelerate.test_utils import require_bnb, require_multi_gpu, slow from accelerate.test_utils.testing import AccelerateTestCase, require_cuda from accelerate.utils import patch_environment def __lowerCamelCase ( ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = torch.nn.Linear(2 , 4 ) SCREAMING_SNAKE_CASE_ : List[Any] = torch.optim.AdamW(model.parameters() , lr=1.0 ) SCREAMING_SNAKE_CASE_ : Any = torch.optim.lr_scheduler.OneCycleLR(SCREAMING_SNAKE_CASE_ , max_lr=0.01 , steps_per_epoch=2 , epochs=1 ) SCREAMING_SNAKE_CASE_ : Dict = DataLoader(TensorDataset(torch.tensor([1, 2, 3] ) ) ) SCREAMING_SNAKE_CASE_ : Tuple = DataLoader(TensorDataset(torch.tensor([4, 5, 6] ) ) ) return model, optimizer, scheduler, train_dl, valid_dl def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : List[str] ) -> Tuple: """simple docstring""" return (model.weight.abs().sum() + model.bias.abs().sum()).item() def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Any ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : str = torch.nn.Linear(*tuple(model.weight.T.shape ) ).state_dict() model.load_state_dict(SCREAMING_SNAKE_CASE_ ) class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): @require_cuda def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = Accelerator() assert PartialState._shared_state["_cpu"] is False assert PartialState._shared_state["device"].type == "cuda" with self.assertRaises(lowercase__ ): SCREAMING_SNAKE_CASE_ : List[Any] = Accelerator(cpu=lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = Accelerator() SCREAMING_SNAKE_CASE_ : Any = GradientState() assert state.num_steps == 1 SCREAMING_SNAKE_CASE_ : Union[str, Any] = 4 assert state.num_steps == 4 assert state.sync_gradients is True SCREAMING_SNAKE_CASE_ : Optional[int] = False assert state.sync_gradients is False GradientState._reset_state() def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[int] = create_components() ( ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ) : Optional[Any] = accelerator.prepare(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) self.assertTrue(prepared_model in accelerator._models ) self.assertTrue(prepared_optimizer in accelerator._optimizers ) self.assertTrue(prepared_scheduler in accelerator._schedulers ) self.assertTrue(prepared_train_dl in accelerator._dataloaders ) self.assertTrue(prepared_valid_dl in accelerator._dataloaders ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : str = create_components() accelerator.prepare(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) accelerator.free_memory() self.assertTrue(len(accelerator._models ) == 0 ) self.assertTrue(len(accelerator._optimizers ) == 0 ) self.assertTrue(len(accelerator._schedulers ) == 0 ) self.assertTrue(len(accelerator._dataloaders ) == 0 ) def __lowerCamelCase ( self ): """simple docstring""" PartialState._reset_state() # Mock torch.cuda.set_device to avoid an exception as the device doesn't exist def noop(*lowercase__ , **lowercase__ ): pass with patch("torch.cuda.set_device" , lowercase__ ), patch_environment(ACCELERATE_TORCH_DEVICE="cuda:64" ): SCREAMING_SNAKE_CASE_ : List[str] = Accelerator() self.assertEqual(str(accelerator.state.device ) , "cuda:64" ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = create_components() accelerator.prepare(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = get_signature(lowercase__ ) with tempfile.TemporaryDirectory() as tmpdirname: accelerator.save_state(lowercase__ ) # make sure random weights don't match load_random_weights(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) > 1e-3 ) # make sure loaded weights match accelerator.load_state(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) < 1e-3 ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[int] = create_components() accelerator.prepare(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = get_signature(lowercase__ ) # saving hook def save_config(lowercase__ , lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE_ : Optional[Any] = {"class_name": models[0].__class__.__name__} with open(os.path.join(lowercase__ , "data.json" ) , "w" ) as f: json.dump(lowercase__ , lowercase__ ) # loading hook def load_config(lowercase__ , lowercase__ ): with open(os.path.join(lowercase__ , "data.json" ) , "r" ) as f: SCREAMING_SNAKE_CASE_ : Any = json.load(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = config["class_name"] SCREAMING_SNAKE_CASE_ : Dict = accelerator.register_save_state_pre_hook(lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = accelerator.register_load_state_pre_hook(lowercase__ ) with tempfile.TemporaryDirectory() as tmpdirname: accelerator.save_state(lowercase__ ) # make sure random weights don't match with hooks load_random_weights(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) > 1e-3 ) # random class name to verify correct one is loaded SCREAMING_SNAKE_CASE_ : Union[str, Any] = "random" # make sure loaded weights match with hooks accelerator.load_state(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) < 1e-3 ) # mode.class_name is loaded from config self.assertTrue(model.class_name == model.__class__.__name__ ) # remove hooks save_hook.remove() load_hook.remove() with tempfile.TemporaryDirectory() as tmpdirname: accelerator.save_state(lowercase__ ) # make sure random weights don't match with hooks removed load_random_weights(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) > 1e-3 ) # random class name to verify correct one is loaded SCREAMING_SNAKE_CASE_ : Tuple = "random" # make sure loaded weights match with hooks removed accelerator.load_state(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) < 1e-3 ) # mode.class_name is NOT loaded from config self.assertTrue(model.class_name != model.__class__.__name__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Tuple = create_components() SCREAMING_SNAKE_CASE_ : Union[str, Any] = None # This should work SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[int] = accelerator.prepare( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) self.assertTrue(dummy_obj is None ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = create_components() SCREAMING_SNAKE_CASE_ : Union[str, Any] = [1, 2, 3] # This should work SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : int = accelerator.prepare( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Dummy object should have `_is_accelerate_prepared` set to `True`" , ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Model is missing `_is_accelerator_prepared` or is set to `False`" , ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Optimizer is missing `_is_accelerator_prepared` or is set to `False`" , ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Scheduler is missing `_is_accelerator_prepared` or is set to `False`" , ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Train Dataloader is missing `_is_accelerator_prepared` or is set to `False`" , ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Valid Dataloader is missing `_is_accelerator_prepared` or is set to `False`" , ) @slow @require_bnb def __lowerCamelCase ( self ): """simple docstring""" from transformers import AutoModelForCausalLM SCREAMING_SNAKE_CASE_ : Optional[int] = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , load_in_abit=lowercase__ , device_map={"": 0} , ) SCREAMING_SNAKE_CASE_ : Optional[int] = Accelerator() # This should work SCREAMING_SNAKE_CASE_ : List[Any] = accelerator.prepare(lowercase__ ) @slow @require_bnb def __lowerCamelCase ( self ): """simple docstring""" from transformers import AutoModelForCausalLM SCREAMING_SNAKE_CASE_ : Optional[Any] = Accelerator() with init_empty_weights(): SCREAMING_SNAKE_CASE_ : Tuple = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , ) model.tie_weights() SCREAMING_SNAKE_CASE_ : Optional[Any] = infer_auto_device_map(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = "cpu" SCREAMING_SNAKE_CASE_ : Tuple = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , device_map=lowercase__ , load_in_abit=lowercase__ , llm_inta_enable_fpaa_cpu_offload=lowercase__ ) # This should not work and get value error with self.assertRaises(lowercase__ ): SCREAMING_SNAKE_CASE_ : str = accelerator.prepare(lowercase__ ) @slow @require_bnb @require_multi_gpu def __lowerCamelCase ( self ): """simple docstring""" from transformers import AutoModelForCausalLM SCREAMING_SNAKE_CASE_ : str = {"distributed_type": DistributedType.MULTI_GPU} with init_empty_weights(): SCREAMING_SNAKE_CASE_ : Optional[int] = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , ) model.tie_weights() SCREAMING_SNAKE_CASE_ : str = infer_auto_device_map(lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = 1 SCREAMING_SNAKE_CASE_ : str = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , load_in_abit=lowercase__ , device_map=lowercase__ , ) SCREAMING_SNAKE_CASE_ : Any = Accelerator() # This should not work and get value error with self.assertRaises(lowercase__ ): SCREAMING_SNAKE_CASE_ : Tuple = accelerator.prepare(lowercase__ ) PartialState._reset_state() @slow @require_bnb @require_multi_gpu def __lowerCamelCase ( self ): """simple docstring""" from transformers import AutoModelForCausalLM with init_empty_weights(): SCREAMING_SNAKE_CASE_ : Optional[int] = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , ) SCREAMING_SNAKE_CASE_ : Optional[Any] = infer_auto_device_map(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = 1 SCREAMING_SNAKE_CASE_ : str = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , load_in_abit=lowercase__ , device_map=lowercase__ , ) SCREAMING_SNAKE_CASE_ : Any = Accelerator() # This should work SCREAMING_SNAKE_CASE_ : Optional[int] = accelerator.prepare(lowercase__ ) @require_cuda def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = torch.nn.Linear(10 , 10 ) SCREAMING_SNAKE_CASE_ : Optional[int] = torch.optim.SGD(model.parameters() , lr=0.01 ) SCREAMING_SNAKE_CASE_ : Tuple = Accelerator(cpu=lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = accelerator.prepare(lowercase__ )
68
'''simple docstring''' import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.generation import DisjunctiveConstraint @require_torch class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = [[1, 2, 4], [1, 2, 3, 4]] SCREAMING_SNAKE_CASE_ : Any = DisjunctiveConstraint(lowercase__ ) self.assertTrue(isinstance(dc.token_ids , lowercase__ ) ) with self.assertRaises(lowercase__ ): DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]] ) ) with self.assertRaises(lowercase__ ): DisjunctiveConstraint([torch.LongTensor([1, 2, 4] ), torch.LongTensor([1, 2, 3, 4, 5] )] ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = [[1, 2], [1, 2, 3, 4]] with self.assertRaises(lowercase__ ): DisjunctiveConstraint(lowercase__ ) # fails here def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = [[1, 2, 3], [1, 2, 4]] SCREAMING_SNAKE_CASE_ : Optional[Any] = DisjunctiveConstraint(lowercase__ ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = dc.update(1 ) SCREAMING_SNAKE_CASE_ : Optional[int] = stepped is True and completed is False and reset is False self.assertTrue(lowercase__ ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Tuple = dc.update(2 ) SCREAMING_SNAKE_CASE_ : Tuple = stepped is True and completed is False and reset is False self.assertTrue(lowercase__ ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Any = dc.update(3 ) SCREAMING_SNAKE_CASE_ : Tuple = stepped is True and completed is True and reset is False self.assertTrue(lowercase__ ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 3] ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]] SCREAMING_SNAKE_CASE_ : Dict = DisjunctiveConstraint(lowercase__ ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : List[Any] = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = dc.update(4 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2, 4] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : List[Any] = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 4, 5] ) dc.reset() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Tuple = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 3 ) self.assertTrue(dc.current_seq == [1] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : str = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 2 ) self.assertTrue(dc.current_seq == [1, 2] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : str = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.remaining() == 0 ) self.assertTrue(dc.current_seq == [1, 2, 5] )
68
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 SCREAMING_SNAKE_CASE__ : def __init__( self , lowercase__ , lowercase__=99 , lowercase__=13 , lowercase__=7 , lowercase__=9 , lowercase__=True , lowercase__=True , lowercase__=False , lowercase__=32 , lowercase__=5 , lowercase__=4 , lowercase__=37 , lowercase__=8 , lowercase__=0.1 , lowercase__=0.002 , lowercase__=1 , lowercase__=0 , lowercase__=0 , lowercase__=None , lowercase__=None , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = parent SCREAMING_SNAKE_CASE_ : int = batch_size SCREAMING_SNAKE_CASE_ : str = encoder_seq_length SCREAMING_SNAKE_CASE_ : str = decoder_seq_length # For common tests SCREAMING_SNAKE_CASE_ : str = self.decoder_seq_length SCREAMING_SNAKE_CASE_ : Optional[int] = is_training SCREAMING_SNAKE_CASE_ : str = use_attention_mask SCREAMING_SNAKE_CASE_ : Optional[int] = use_labels SCREAMING_SNAKE_CASE_ : Tuple = vocab_size SCREAMING_SNAKE_CASE_ : Any = hidden_size SCREAMING_SNAKE_CASE_ : List[str] = num_hidden_layers SCREAMING_SNAKE_CASE_ : Dict = num_attention_heads SCREAMING_SNAKE_CASE_ : Union[str, Any] = d_ff SCREAMING_SNAKE_CASE_ : Optional[int] = relative_attention_num_buckets SCREAMING_SNAKE_CASE_ : Dict = dropout_rate SCREAMING_SNAKE_CASE_ : Tuple = initializer_factor SCREAMING_SNAKE_CASE_ : Dict = eos_token_id SCREAMING_SNAKE_CASE_ : int = pad_token_id SCREAMING_SNAKE_CASE_ : int = decoder_start_token_id SCREAMING_SNAKE_CASE_ : Dict = None SCREAMING_SNAKE_CASE_ : Dict = decoder_layers def __lowerCamelCase ( self ): """simple docstring""" return TaConfig.from_pretrained("google/umt5-base" ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__=None , lowercase__=None , lowercase__=None , lowercase__=None , lowercase__=None , ): """simple docstring""" if attention_mask is None: SCREAMING_SNAKE_CASE_ : Tuple = input_ids.ne(config.pad_token_id ) if decoder_attention_mask is None: SCREAMING_SNAKE_CASE_ : Union[str, Any] = decoder_input_ids.ne(config.pad_token_id ) if head_mask is None: SCREAMING_SNAKE_CASE_ : Dict = torch.ones(config.num_hidden_layers , config.num_attention_heads , device=lowercase__ ) if decoder_head_mask is None: SCREAMING_SNAKE_CASE_ : List[str] = torch.ones(config.num_decoder_layers , config.num_attention_heads , device=lowercase__ ) if cross_attn_head_mask is None: SCREAMING_SNAKE_CASE_ : Optional[int] = torch.ones( config.num_decoder_layers , config.num_attention_heads , device=lowercase__ ) 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 __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = ids_tensor([self.batch_size, self.encoder_seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE_ : Dict = 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_ : Optional[Any] = input_ids.clamp(self.pad_token_id + 1 ) SCREAMING_SNAKE_CASE_ : List[Any] = decoder_input_ids.clamp(self.pad_token_id + 1 ) SCREAMING_SNAKE_CASE_ : Any = self.get_config() SCREAMING_SNAKE_CASE_ : int = config.num_attention_heads SCREAMING_SNAKE_CASE_ : int = self.prepare_inputs_dict(lowercase__ , lowercase__ , lowercase__ ) return config, input_dict def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : str = self.prepare_config_and_inputs() return config, inputs_dict def __lowerCamelCase ( self ): """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 __lowerCamelCase ( self ): """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 __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = UMTaModel(config=lowercase__ ) model.to(lowercase__ ) model.eval() SCREAMING_SNAKE_CASE_ : Optional[Any] = model( input_ids=lowercase__ , decoder_input_ids=lowercase__ , attention_mask=lowercase__ , decoder_attention_mask=lowercase__ , ) SCREAMING_SNAKE_CASE_ : Optional[int] = model(input_ids=lowercase__ , decoder_input_ids=lowercase__ ) SCREAMING_SNAKE_CASE_ : int = result.last_hidden_state SCREAMING_SNAKE_CASE_ : Any = result.past_key_values SCREAMING_SNAKE_CASE_ : int = 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(lowercase__ ) , 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 __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = UMTaModel(config=lowercase__ ).get_decoder().to(lowercase__ ).eval() # first forward pass SCREAMING_SNAKE_CASE_ : Dict = model(lowercase__ , use_cache=lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = model(lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = model(lowercase__ , use_cache=lowercase__ ) self.parent.assertTrue(len(lowercase__ ) == len(lowercase__ ) ) self.parent.assertTrue(len(lowercase__ ) == len(lowercase__ ) + 1 ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[Any] = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids SCREAMING_SNAKE_CASE_ : Dict = ids_tensor((self.batch_size, 1) , config.vocab_size ) # append to next input_ids and SCREAMING_SNAKE_CASE_ : int = torch.cat([input_ids, next_tokens] , dim=-1 ) SCREAMING_SNAKE_CASE_ : Optional[int] = model(lowercase__ )["last_hidden_state"] SCREAMING_SNAKE_CASE_ : Tuple = model(lowercase__ , past_key_values=lowercase__ )["last_hidden_state"] # select random slice SCREAMING_SNAKE_CASE_ : int = ids_tensor((1,) , output_from_past.shape[-1] ).item() SCREAMING_SNAKE_CASE_ : Dict = output_from_no_past[:, -1, random_slice_idx].detach() SCREAMING_SNAKE_CASE_ : Tuple = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(lowercase__ , lowercase__ , atol=1e-3 ) ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = UMTaModel(config=lowercase__ ).to(lowercase__ ).half().eval() SCREAMING_SNAKE_CASE_ : Union[str, Any] = model(**lowercase__ )["last_hidden_state"] self.parent.assertFalse(torch.isnan(lowercase__ ).any().item() ) @require_torch class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,_UpperCAmelCase,_UpperCAmelCase,unittest.TestCase ): _A = ( (UMTaModel, UMTaForConditionalGeneration, UMTaForQuestionAnswering) if is_torch_available() else () ) _A = (UMTaForConditionalGeneration,) if is_torch_available() else () _A = ( { "conversational": UMTaForConditionalGeneration, "feature-extraction": UMTaModel, "summarization": UMTaForConditionalGeneration, "text2text-generation": UMTaForConditionalGeneration, "translation": UMTaForConditionalGeneration, "question-answering": UMTaForQuestionAnswering, } if is_torch_available() else {} ) _A = True _A = False _A = False _A = True _A = True # The small UMT5 model needs higher percentages for CPU/MP tests _A = [0.8, 0.9] def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = UMTaModelTester(self ) @unittest.skip("Test has a segmentation fault on torch 1.8.0" ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = self.model_tester.prepare_config_and_inputs() SCREAMING_SNAKE_CASE_ : Tuple = UMTaModel(config_and_inputs[0] ).to(lowercase__ ) with tempfile.TemporaryDirectory() as tmpdirname: torch.onnx.export( lowercase__ , (config_and_inputs[1], config_and_inputs[3], config_and_inputs[2]) , F"{tmpdirname}/t5_test.onnx" , export_params=lowercase__ , opset_version=9 , input_names=["input_ids", "decoder_input_ids"] , ) @unittest.skipIf(torch_device == "cpu" , "Cant do half precision" ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model_fpaa_forward(*lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = ["encoder_attentions", "decoder_attentions", "cross_attentions"] SCREAMING_SNAKE_CASE_ : Dict = self.model_tester.prepare_config_and_inputs() SCREAMING_SNAKE_CASE_ : Tuple = config_and_inputs[0] SCREAMING_SNAKE_CASE_ : str = UMTaForConditionalGeneration(lowercase__ ).eval() model.to(lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = { "head_mask": torch.zeros(config.num_layers , config.num_heads , device=lowercase__ ), "decoder_head_mask": torch.zeros(config.num_decoder_layers , config.num_heads , device=lowercase__ ), "cross_attn_head_mask": torch.zeros(config.num_decoder_layers , config.num_heads , device=lowercase__ ), } for attn_name, (name, mask) in zip(lowercase__ , head_masking.items() ): SCREAMING_SNAKE_CASE_ : Tuple = {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_ : str = torch.ones( config.num_decoder_layers , config.num_heads , device=lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = model.generate( config_and_inputs[1]["input_ids"] , num_beams=1 , max_length=3 , output_attentions=lowercase__ , return_dict_in_generate=lowercase__ , **lowercase__ , ) # We check the state of decoder_attentions and cross_attentions just from the last step SCREAMING_SNAKE_CASE_ : Optional[int] = 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 __lowerCamelCase ( self ): """simple docstring""" pass @require_torch @require_sentencepiece @require_tokenizers class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): @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 __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = UMTaForConditionalGeneration.from_pretrained("google/umt5-small" , return_dict=lowercase__ ).to(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = AutoTokenizer.from_pretrained("google/umt5-small" , use_fast=lowercase__ , legacy=lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = [ "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_ : Dict = tokenizer(lowercase__ , return_tensors="pt" , padding=lowercase__ ).input_ids # fmt: off SCREAMING_SNAKE_CASE_ : Optional[Any] = torch.tensor( [ [ 3_8530, 21_0703, 25_6299, 1410, 25_6298, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 826, 321, 671, 2_5922, 25_6299, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 1460, 339, 312, 1_9014, 1_0620, 758, 25_6299, 2355,274, 1, 0, 0, 0, 0, 0, 0,0, 0], [ 517, 25_6299, 1_4869, 281, 301, 25_6298, 275, 11_9983,1, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 320, 25_6299, 1_4869, 281, 2234, 289, 2275, 333,6_1391, 289, 25_6298, 543, 25_6297, 16_8714, 329, 25_6296,274, 1], ] ) # fmt: on torch.testing.assert_allclose(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = model.generate(input_ids.to(lowercase__ ) ) SCREAMING_SNAKE_CASE_ : Dict = [ "<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_ : List[Any] = tokenizer.batch_decode(lowercase__ ) self.assertEqual(lowercase__ , lowercase__ )
68
'''simple docstring''' import unittest import torch from diffusers import VQModel from diffusers.utils import floats_tensor, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,_UpperCAmelCase,unittest.TestCase ): _A = VQModel _A = "sample" @property def __lowerCamelCase ( self , lowercase__=(32, 32) ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = 4 SCREAMING_SNAKE_CASE_ : str = 3 SCREAMING_SNAKE_CASE_ : str = floats_tensor((batch_size, num_channels) + sizes ).to(lowercase__ ) return {"sample": image} @property def __lowerCamelCase ( self ): """simple docstring""" return (3, 32, 32) @property def __lowerCamelCase ( self ): """simple docstring""" return (3, 32, 32) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = { "block_out_channels": [32, 64], "in_channels": 3, "out_channels": 3, "down_block_types": ["DownEncoderBlock2D", "DownEncoderBlock2D"], "up_block_types": ["UpDecoderBlock2D", "UpDecoderBlock2D"], "latent_channels": 3, } SCREAMING_SNAKE_CASE_ : int = self.dummy_input return init_dict, inputs_dict def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : int = VQModel.from_pretrained("fusing/vqgan-dummy" , output_loading_info=lowercase__ ) self.assertIsNotNone(lowercase__ ) self.assertEqual(len(loading_info["missing_keys"] ) , 0 ) model.to(lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = VQModel.from_pretrained("fusing/vqgan-dummy" ) model.to(lowercase__ ).eval() torch.manual_seed(0 ) if torch.cuda.is_available(): torch.cuda.manual_seed_all(0 ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.randn(1 , model.config.in_channels , model.config.sample_size , model.config.sample_size ) SCREAMING_SNAKE_CASE_ : str = image.to(lowercase__ ) with torch.no_grad(): SCREAMING_SNAKE_CASE_ : int = model(lowercase__ ).sample SCREAMING_SNAKE_CASE_ : Any = output[0, -1, -3:, -3:].flatten().cpu() # fmt: off SCREAMING_SNAKE_CASE_ : Optional[Any] = torch.tensor([-0.0153, -0.4044, -0.1880, -0.5161, -0.2418, -0.4072, -0.1612, -0.0633, -0.0143] ) # fmt: on self.assertTrue(torch.allclose(lowercase__ , lowercase__ , atol=1e-3 ) )
68
1
'''simple docstring''' class SCREAMING_SNAKE_CASE__ : def __init__( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = set_counts SCREAMING_SNAKE_CASE_ : Dict = max(lowercase__ ) SCREAMING_SNAKE_CASE_ : int = len(lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = [1] * num_sets SCREAMING_SNAKE_CASE_ : Any = list(range(lowercase__ ) ) def __lowerCamelCase ( self , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int = self.get_parent(lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = self.get_parent(lowercase__ ) if src_parent == dst_parent: return False if self.ranks[dst_parent] >= self.ranks[src_parent]: self.set_counts[dst_parent] += self.set_counts[src_parent] SCREAMING_SNAKE_CASE_ : int = 0 SCREAMING_SNAKE_CASE_ : int = dst_parent if self.ranks[dst_parent] == self.ranks[src_parent]: self.ranks[dst_parent] += 1 SCREAMING_SNAKE_CASE_ : List[Any] = self.set_counts[dst_parent] else: self.set_counts[src_parent] += self.set_counts[dst_parent] SCREAMING_SNAKE_CASE_ : Optional[int] = 0 SCREAMING_SNAKE_CASE_ : Dict = src_parent SCREAMING_SNAKE_CASE_ : int = self.set_counts[src_parent] SCREAMING_SNAKE_CASE_ : List[str] = max(self.max_set , lowercase__ ) return True def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" if self.parents[disj_set] == disj_set: return disj_set SCREAMING_SNAKE_CASE_ : Any = self.get_parent(self.parents[disj_set] ) return self.parents[disj_set]
68
'''simple docstring''' import os import unittest from huggingface_hub.utils import are_progress_bars_disabled import transformers.models.bart.tokenization_bart from transformers import logging from transformers.testing_utils import CaptureLogger, mockenv, mockenv_context from transformers.utils.logging import disable_progress_bar, enable_progress_bar class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = logging.get_logger() # the current default level is logging.WARNING SCREAMING_SNAKE_CASE_ : Optional[int] = logging.get_verbosity() logging.set_verbosity_error() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_warning() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_info() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_debug() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) # restore to the original level logging.set_verbosity(lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = logging.get_verbosity() SCREAMING_SNAKE_CASE_ : List[Any] = logging.get_logger("transformers.models.bart.tokenization_bart" ) SCREAMING_SNAKE_CASE_ : List[Any] = "Testing 1, 2, 3" # should be able to log warnings (if default settings weren't overridden by `pytest --log-level-all`) if level_origin <= logging.WARNING: with CaptureLogger(lowercase__ ) as cl: logger.warning(lowercase__ ) self.assertEqual(cl.out , msg + "\n" ) # this is setting the level for all of `transformers.*` loggers logging.set_verbosity_error() # should not be able to log warnings with CaptureLogger(lowercase__ ) as cl: logger.warning(lowercase__ ) self.assertEqual(cl.out , "" ) # should be able to log warnings again logging.set_verbosity_warning() with CaptureLogger(lowercase__ ) as cl: logger.warning(lowercase__ ) self.assertEqual(cl.out , msg + "\n" ) # restore to the original level logging.set_verbosity(lowercase__ ) @mockenv(TRANSFORMERS_VERBOSITY="error" ) def __lowerCamelCase ( self ): """simple docstring""" transformers.utils.logging._reset_library_root_logger() # this action activates the env var SCREAMING_SNAKE_CASE_ : Tuple = logging.get_logger("transformers.models.bart.tokenization_bart" ) SCREAMING_SNAKE_CASE_ : int = os.getenv("TRANSFORMERS_VERBOSITY" , lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = logging.log_levels[env_level_str] SCREAMING_SNAKE_CASE_ : str = logging.get_verbosity() self.assertEqual( lowercase__ , lowercase__ , F"TRANSFORMERS_VERBOSITY={env_level_str}/{env_level}, but internal verbosity is {current_level}" , ) # restore to the original level SCREAMING_SNAKE_CASE_ : Optional[int] = "" transformers.utils.logging._reset_library_root_logger() @mockenv(TRANSFORMERS_VERBOSITY="super-error" ) def __lowerCamelCase ( self ): """simple docstring""" transformers.utils.logging._reset_library_root_logger() SCREAMING_SNAKE_CASE_ : List[Any] = logging.logging.getLogger() with CaptureLogger(lowercase__ ) as cl: # this action activates the env var logging.get_logger("transformers.models.bart.tokenization_bart" ) self.assertIn("Unknown option TRANSFORMERS_VERBOSITY=super-error" , cl.out ) # no need to restore as nothing was changed def __lowerCamelCase ( self ): """simple docstring""" transformers.utils.logging._reset_library_root_logger() SCREAMING_SNAKE_CASE_ : str = logging.get_logger("transformers.models.bart.tokenization_bart" ) SCREAMING_SNAKE_CASE_ : List[Any] = "Testing 1, 2, 3" with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS="1" ): # nothing should be logged as env var disables this method with CaptureLogger(lowercase__ ) as cl: logger.warning_advice(lowercase__ ) self.assertEqual(cl.out , "" ) with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS="" ): # should log normally as TRANSFORMERS_NO_ADVISORY_WARNINGS is unset with CaptureLogger(lowercase__ ) as cl: logger.warning_advice(lowercase__ ) self.assertEqual(cl.out , msg + "\n" ) def __lowerCamelCase ( ) -> Optional[int]: """simple docstring""" disable_progress_bar() assert are_progress_bars_disabled() enable_progress_bar() assert not are_progress_bars_disabled()
68
1
'''simple docstring''' from collections import OrderedDict from ...utils import logging from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update from .configuration_auto import CONFIG_MAPPING_NAMES snake_case_ = logging.get_logger(__name__) snake_case_ = OrderedDict( [ # Base model mapping ('albert', 'FlaxAlbertModel'), ('bart', 'FlaxBartModel'), ('beit', 'FlaxBeitModel'), ('bert', 'FlaxBertModel'), ('big_bird', 'FlaxBigBirdModel'), ('blenderbot', 'FlaxBlenderbotModel'), ('blenderbot-small', 'FlaxBlenderbotSmallModel'), ('clip', 'FlaxCLIPModel'), ('distilbert', 'FlaxDistilBertModel'), ('electra', 'FlaxElectraModel'), ('gpt-sw3', 'FlaxGPT2Model'), ('gpt2', 'FlaxGPT2Model'), ('gpt_neo', 'FlaxGPTNeoModel'), ('gptj', 'FlaxGPTJModel'), ('longt5', 'FlaxLongT5Model'), ('marian', 'FlaxMarianModel'), ('mbart', 'FlaxMBartModel'), ('mt5', 'FlaxMT5Model'), ('opt', 'FlaxOPTModel'), ('pegasus', 'FlaxPegasusModel'), ('regnet', 'FlaxRegNetModel'), ('resnet', 'FlaxResNetModel'), ('roberta', 'FlaxRobertaModel'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormModel'), ('roformer', 'FlaxRoFormerModel'), ('t5', 'FlaxT5Model'), ('vision-text-dual-encoder', 'FlaxVisionTextDualEncoderModel'), ('vit', 'FlaxViTModel'), ('wav2vec2', 'FlaxWav2Vec2Model'), ('whisper', 'FlaxWhisperModel'), ('xglm', 'FlaxXGLMModel'), ('xlm-roberta', 'FlaxXLMRobertaModel'), ] ) snake_case_ = OrderedDict( [ # Model for pre-training mapping ('albert', 'FlaxAlbertForPreTraining'), ('bart', 'FlaxBartForConditionalGeneration'), ('bert', 'FlaxBertForPreTraining'), ('big_bird', 'FlaxBigBirdForPreTraining'), ('electra', 'FlaxElectraForPreTraining'), ('longt5', 'FlaxLongT5ForConditionalGeneration'), ('mbart', 'FlaxMBartForConditionalGeneration'), ('mt5', 'FlaxMT5ForConditionalGeneration'), ('roberta', 'FlaxRobertaForMaskedLM'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForMaskedLM'), ('roformer', 'FlaxRoFormerForMaskedLM'), ('t5', 'FlaxT5ForConditionalGeneration'), ('wav2vec2', 'FlaxWav2Vec2ForPreTraining'), ('whisper', 'FlaxWhisperForConditionalGeneration'), ('xlm-roberta', 'FlaxXLMRobertaForMaskedLM'), ] ) snake_case_ = OrderedDict( [ # Model for Masked LM mapping ('albert', 'FlaxAlbertForMaskedLM'), ('bart', 'FlaxBartForConditionalGeneration'), ('bert', 'FlaxBertForMaskedLM'), ('big_bird', 'FlaxBigBirdForMaskedLM'), ('distilbert', 'FlaxDistilBertForMaskedLM'), ('electra', 'FlaxElectraForMaskedLM'), ('mbart', 'FlaxMBartForConditionalGeneration'), ('roberta', 'FlaxRobertaForMaskedLM'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForMaskedLM'), ('roformer', 'FlaxRoFormerForMaskedLM'), ('xlm-roberta', 'FlaxXLMRobertaForMaskedLM'), ] ) snake_case_ = OrderedDict( [ # Model for Seq2Seq Causal LM mapping ('bart', 'FlaxBartForConditionalGeneration'), ('blenderbot', 'FlaxBlenderbotForConditionalGeneration'), ('blenderbot-small', 'FlaxBlenderbotSmallForConditionalGeneration'), ('encoder-decoder', 'FlaxEncoderDecoderModel'), ('longt5', 'FlaxLongT5ForConditionalGeneration'), ('marian', 'FlaxMarianMTModel'), ('mbart', 'FlaxMBartForConditionalGeneration'), ('mt5', 'FlaxMT5ForConditionalGeneration'), ('pegasus', 'FlaxPegasusForConditionalGeneration'), ('t5', 'FlaxT5ForConditionalGeneration'), ] ) snake_case_ = OrderedDict( [ # Model for Image-classsification ('beit', 'FlaxBeitForImageClassification'), ('regnet', 'FlaxRegNetForImageClassification'), ('resnet', 'FlaxResNetForImageClassification'), ('vit', 'FlaxViTForImageClassification'), ] ) snake_case_ = OrderedDict( [ ('vision-encoder-decoder', 'FlaxVisionEncoderDecoderModel'), ] ) snake_case_ = OrderedDict( [ # Model for Causal LM mapping ('bart', 'FlaxBartForCausalLM'), ('bert', 'FlaxBertForCausalLM'), ('big_bird', 'FlaxBigBirdForCausalLM'), ('electra', 'FlaxElectraForCausalLM'), ('gpt-sw3', 'FlaxGPT2LMHeadModel'), ('gpt2', 'FlaxGPT2LMHeadModel'), ('gpt_neo', 'FlaxGPTNeoForCausalLM'), ('gptj', 'FlaxGPTJForCausalLM'), ('opt', 'FlaxOPTForCausalLM'), ('roberta', 'FlaxRobertaForCausalLM'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForCausalLM'), ('xglm', 'FlaxXGLMForCausalLM'), ('xlm-roberta', 'FlaxXLMRobertaForCausalLM'), ] ) snake_case_ = OrderedDict( [ # Model for Sequence Classification mapping ('albert', 'FlaxAlbertForSequenceClassification'), ('bart', 'FlaxBartForSequenceClassification'), ('bert', 'FlaxBertForSequenceClassification'), ('big_bird', 'FlaxBigBirdForSequenceClassification'), ('distilbert', 'FlaxDistilBertForSequenceClassification'), ('electra', 'FlaxElectraForSequenceClassification'), ('mbart', 'FlaxMBartForSequenceClassification'), ('roberta', 'FlaxRobertaForSequenceClassification'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForSequenceClassification'), ('roformer', 'FlaxRoFormerForSequenceClassification'), ('xlm-roberta', 'FlaxXLMRobertaForSequenceClassification'), ] ) snake_case_ = OrderedDict( [ # Model for Question Answering mapping ('albert', 'FlaxAlbertForQuestionAnswering'), ('bart', 'FlaxBartForQuestionAnswering'), ('bert', 'FlaxBertForQuestionAnswering'), ('big_bird', 'FlaxBigBirdForQuestionAnswering'), ('distilbert', 'FlaxDistilBertForQuestionAnswering'), ('electra', 'FlaxElectraForQuestionAnswering'), ('mbart', 'FlaxMBartForQuestionAnswering'), ('roberta', 'FlaxRobertaForQuestionAnswering'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForQuestionAnswering'), ('roformer', 'FlaxRoFormerForQuestionAnswering'), ('xlm-roberta', 'FlaxXLMRobertaForQuestionAnswering'), ] ) snake_case_ = OrderedDict( [ # Model for Token Classification mapping ('albert', 'FlaxAlbertForTokenClassification'), ('bert', 'FlaxBertForTokenClassification'), ('big_bird', 'FlaxBigBirdForTokenClassification'), ('distilbert', 'FlaxDistilBertForTokenClassification'), ('electra', 'FlaxElectraForTokenClassification'), ('roberta', 'FlaxRobertaForTokenClassification'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForTokenClassification'), ('roformer', 'FlaxRoFormerForTokenClassification'), ('xlm-roberta', 'FlaxXLMRobertaForTokenClassification'), ] ) snake_case_ = OrderedDict( [ # Model for Multiple Choice mapping ('albert', 'FlaxAlbertForMultipleChoice'), ('bert', 'FlaxBertForMultipleChoice'), ('big_bird', 'FlaxBigBirdForMultipleChoice'), ('distilbert', 'FlaxDistilBertForMultipleChoice'), ('electra', 'FlaxElectraForMultipleChoice'), ('roberta', 'FlaxRobertaForMultipleChoice'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForMultipleChoice'), ('roformer', 'FlaxRoFormerForMultipleChoice'), ('xlm-roberta', 'FlaxXLMRobertaForMultipleChoice'), ] ) snake_case_ = OrderedDict( [ ('bert', 'FlaxBertForNextSentencePrediction'), ] ) snake_case_ = OrderedDict( [ ('speech-encoder-decoder', 'FlaxSpeechEncoderDecoderModel'), ('whisper', 'FlaxWhisperForConditionalGeneration'), ] ) snake_case_ = OrderedDict( [ ('whisper', 'FlaxWhisperForAudioClassification'), ] ) snake_case_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES) snake_case_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES) snake_case_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES) snake_case_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES ) snake_case_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES ) snake_case_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES) snake_case_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES) snake_case_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES ) snake_case_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES ) snake_case_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES ) snake_case_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES ) snake_case_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES ) snake_case_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES ) snake_case_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES ) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): _A = FLAX_MODEL_MAPPING snake_case_ = auto_class_update(FlaxAutoModel) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): _A = FLAX_MODEL_FOR_PRETRAINING_MAPPING snake_case_ = auto_class_update(FlaxAutoModelForPreTraining, head_doc='pretraining') class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): _A = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING snake_case_ = auto_class_update(FlaxAutoModelForCausalLM, head_doc='causal language modeling') class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): _A = FLAX_MODEL_FOR_MASKED_LM_MAPPING snake_case_ = auto_class_update(FlaxAutoModelForMaskedLM, head_doc='masked language modeling') class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): _A = FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING snake_case_ = auto_class_update( FlaxAutoModelForSeqaSeqLM, head_doc='sequence-to-sequence language modeling', checkpoint_for_example='t5-base' ) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): _A = FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING snake_case_ = auto_class_update( FlaxAutoModelForSequenceClassification, head_doc='sequence classification' ) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): _A = FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING snake_case_ = auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc='question answering') class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): _A = FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING snake_case_ = auto_class_update( FlaxAutoModelForTokenClassification, head_doc='token classification' ) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): _A = FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING snake_case_ = auto_class_update(FlaxAutoModelForMultipleChoice, head_doc='multiple choice') class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): _A = FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING snake_case_ = auto_class_update( FlaxAutoModelForNextSentencePrediction, head_doc='next sentence prediction' ) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): _A = FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING snake_case_ = auto_class_update( FlaxAutoModelForImageClassification, head_doc='image classification' ) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): _A = FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING snake_case_ = auto_class_update(FlaxAutoModelForVisionaSeq, head_doc='vision-to-text modeling') class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): _A = FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING snake_case_ = auto_class_update( FlaxAutoModelForSpeechSeqaSeq, head_doc='sequence-to-sequence speech-to-text modeling' )
68
'''simple docstring''' import json import os import tempfile from unittest.mock import patch import torch from torch.utils.data import DataLoader, TensorDataset from accelerate import DistributedType, infer_auto_device_map, init_empty_weights from accelerate.accelerator import Accelerator from accelerate.state import GradientState, PartialState from accelerate.test_utils import require_bnb, require_multi_gpu, slow from accelerate.test_utils.testing import AccelerateTestCase, require_cuda from accelerate.utils import patch_environment def __lowerCamelCase ( ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = torch.nn.Linear(2 , 4 ) SCREAMING_SNAKE_CASE_ : List[Any] = torch.optim.AdamW(model.parameters() , lr=1.0 ) SCREAMING_SNAKE_CASE_ : Any = torch.optim.lr_scheduler.OneCycleLR(SCREAMING_SNAKE_CASE_ , max_lr=0.01 , steps_per_epoch=2 , epochs=1 ) SCREAMING_SNAKE_CASE_ : Dict = DataLoader(TensorDataset(torch.tensor([1, 2, 3] ) ) ) SCREAMING_SNAKE_CASE_ : Tuple = DataLoader(TensorDataset(torch.tensor([4, 5, 6] ) ) ) return model, optimizer, scheduler, train_dl, valid_dl def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : List[str] ) -> Tuple: """simple docstring""" return (model.weight.abs().sum() + model.bias.abs().sum()).item() def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Any ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : str = torch.nn.Linear(*tuple(model.weight.T.shape ) ).state_dict() model.load_state_dict(SCREAMING_SNAKE_CASE_ ) class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): @require_cuda def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = Accelerator() assert PartialState._shared_state["_cpu"] is False assert PartialState._shared_state["device"].type == "cuda" with self.assertRaises(lowercase__ ): SCREAMING_SNAKE_CASE_ : List[Any] = Accelerator(cpu=lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = Accelerator() SCREAMING_SNAKE_CASE_ : Any = GradientState() assert state.num_steps == 1 SCREAMING_SNAKE_CASE_ : Union[str, Any] = 4 assert state.num_steps == 4 assert state.sync_gradients is True SCREAMING_SNAKE_CASE_ : Optional[int] = False assert state.sync_gradients is False GradientState._reset_state() def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[int] = create_components() ( ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ) : Optional[Any] = accelerator.prepare(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) self.assertTrue(prepared_model in accelerator._models ) self.assertTrue(prepared_optimizer in accelerator._optimizers ) self.assertTrue(prepared_scheduler in accelerator._schedulers ) self.assertTrue(prepared_train_dl in accelerator._dataloaders ) self.assertTrue(prepared_valid_dl in accelerator._dataloaders ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : str = create_components() accelerator.prepare(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) accelerator.free_memory() self.assertTrue(len(accelerator._models ) == 0 ) self.assertTrue(len(accelerator._optimizers ) == 0 ) self.assertTrue(len(accelerator._schedulers ) == 0 ) self.assertTrue(len(accelerator._dataloaders ) == 0 ) def __lowerCamelCase ( self ): """simple docstring""" PartialState._reset_state() # Mock torch.cuda.set_device to avoid an exception as the device doesn't exist def noop(*lowercase__ , **lowercase__ ): pass with patch("torch.cuda.set_device" , lowercase__ ), patch_environment(ACCELERATE_TORCH_DEVICE="cuda:64" ): SCREAMING_SNAKE_CASE_ : List[str] = Accelerator() self.assertEqual(str(accelerator.state.device ) , "cuda:64" ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = create_components() accelerator.prepare(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = get_signature(lowercase__ ) with tempfile.TemporaryDirectory() as tmpdirname: accelerator.save_state(lowercase__ ) # make sure random weights don't match load_random_weights(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) > 1e-3 ) # make sure loaded weights match accelerator.load_state(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) < 1e-3 ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[int] = create_components() accelerator.prepare(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = get_signature(lowercase__ ) # saving hook def save_config(lowercase__ , lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE_ : Optional[Any] = {"class_name": models[0].__class__.__name__} with open(os.path.join(lowercase__ , "data.json" ) , "w" ) as f: json.dump(lowercase__ , lowercase__ ) # loading hook def load_config(lowercase__ , lowercase__ ): with open(os.path.join(lowercase__ , "data.json" ) , "r" ) as f: SCREAMING_SNAKE_CASE_ : Any = json.load(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = config["class_name"] SCREAMING_SNAKE_CASE_ : Dict = accelerator.register_save_state_pre_hook(lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = accelerator.register_load_state_pre_hook(lowercase__ ) with tempfile.TemporaryDirectory() as tmpdirname: accelerator.save_state(lowercase__ ) # make sure random weights don't match with hooks load_random_weights(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) > 1e-3 ) # random class name to verify correct one is loaded SCREAMING_SNAKE_CASE_ : Union[str, Any] = "random" # make sure loaded weights match with hooks accelerator.load_state(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) < 1e-3 ) # mode.class_name is loaded from config self.assertTrue(model.class_name == model.__class__.__name__ ) # remove hooks save_hook.remove() load_hook.remove() with tempfile.TemporaryDirectory() as tmpdirname: accelerator.save_state(lowercase__ ) # make sure random weights don't match with hooks removed load_random_weights(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) > 1e-3 ) # random class name to verify correct one is loaded SCREAMING_SNAKE_CASE_ : Tuple = "random" # make sure loaded weights match with hooks removed accelerator.load_state(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) < 1e-3 ) # mode.class_name is NOT loaded from config self.assertTrue(model.class_name != model.__class__.__name__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Tuple = create_components() SCREAMING_SNAKE_CASE_ : Union[str, Any] = None # This should work SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[int] = accelerator.prepare( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) self.assertTrue(dummy_obj is None ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = create_components() SCREAMING_SNAKE_CASE_ : Union[str, Any] = [1, 2, 3] # This should work SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : int = accelerator.prepare( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Dummy object should have `_is_accelerate_prepared` set to `True`" , ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Model is missing `_is_accelerator_prepared` or is set to `False`" , ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Optimizer is missing `_is_accelerator_prepared` or is set to `False`" , ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Scheduler is missing `_is_accelerator_prepared` or is set to `False`" , ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Train Dataloader is missing `_is_accelerator_prepared` or is set to `False`" , ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Valid Dataloader is missing `_is_accelerator_prepared` or is set to `False`" , ) @slow @require_bnb def __lowerCamelCase ( self ): """simple docstring""" from transformers import AutoModelForCausalLM SCREAMING_SNAKE_CASE_ : Optional[int] = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , load_in_abit=lowercase__ , device_map={"": 0} , ) SCREAMING_SNAKE_CASE_ : Optional[int] = Accelerator() # This should work SCREAMING_SNAKE_CASE_ : List[Any] = accelerator.prepare(lowercase__ ) @slow @require_bnb def __lowerCamelCase ( self ): """simple docstring""" from transformers import AutoModelForCausalLM SCREAMING_SNAKE_CASE_ : Optional[Any] = Accelerator() with init_empty_weights(): SCREAMING_SNAKE_CASE_ : Tuple = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , ) model.tie_weights() SCREAMING_SNAKE_CASE_ : Optional[Any] = infer_auto_device_map(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = "cpu" SCREAMING_SNAKE_CASE_ : Tuple = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , device_map=lowercase__ , load_in_abit=lowercase__ , llm_inta_enable_fpaa_cpu_offload=lowercase__ ) # This should not work and get value error with self.assertRaises(lowercase__ ): SCREAMING_SNAKE_CASE_ : str = accelerator.prepare(lowercase__ ) @slow @require_bnb @require_multi_gpu def __lowerCamelCase ( self ): """simple docstring""" from transformers import AutoModelForCausalLM SCREAMING_SNAKE_CASE_ : str = {"distributed_type": DistributedType.MULTI_GPU} with init_empty_weights(): SCREAMING_SNAKE_CASE_ : Optional[int] = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , ) model.tie_weights() SCREAMING_SNAKE_CASE_ : str = infer_auto_device_map(lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = 1 SCREAMING_SNAKE_CASE_ : str = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , load_in_abit=lowercase__ , device_map=lowercase__ , ) SCREAMING_SNAKE_CASE_ : Any = Accelerator() # This should not work and get value error with self.assertRaises(lowercase__ ): SCREAMING_SNAKE_CASE_ : Tuple = accelerator.prepare(lowercase__ ) PartialState._reset_state() @slow @require_bnb @require_multi_gpu def __lowerCamelCase ( self ): """simple docstring""" from transformers import AutoModelForCausalLM with init_empty_weights(): SCREAMING_SNAKE_CASE_ : Optional[int] = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , ) SCREAMING_SNAKE_CASE_ : Optional[Any] = infer_auto_device_map(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = 1 SCREAMING_SNAKE_CASE_ : str = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , load_in_abit=lowercase__ , device_map=lowercase__ , ) SCREAMING_SNAKE_CASE_ : Any = Accelerator() # This should work SCREAMING_SNAKE_CASE_ : Optional[int] = accelerator.prepare(lowercase__ ) @require_cuda def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = torch.nn.Linear(10 , 10 ) SCREAMING_SNAKE_CASE_ : Optional[int] = torch.optim.SGD(model.parameters() , lr=0.01 ) SCREAMING_SNAKE_CASE_ : Tuple = Accelerator(cpu=lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = accelerator.prepare(lowercase__ )
68
1
'''simple docstring''' import os import unittest from transformers.models.cpmant.tokenization_cpmant import VOCAB_FILES_NAMES, CpmAntTokenizer from transformers.testing_utils import require_jieba, tooslow from ...test_tokenization_common import TokenizerTesterMixin @require_jieba class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,unittest.TestCase ): _A = CpmAntTokenizer _A = False def __lowerCamelCase ( self ): """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE_ : Union[str, Any] = [ "<d>", "</d>", "<s>", "</s>", "</_>", "<unk>", "<pad>", "</n>", "我", "是", "C", "P", "M", "A", "n", "t", ] SCREAMING_SNAKE_CASE_ : List[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) @tooslow def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = CpmAntTokenizer.from_pretrained("openbmb/cpm-ant-10b" ) SCREAMING_SNAKE_CASE_ : Optional[Any] = "今天天气真好!" SCREAMING_SNAKE_CASE_ : List[Any] = ["今天", "天气", "真", "好", "!"] SCREAMING_SNAKE_CASE_ : Tuple = tokenizer.tokenize(lowercase__ ) self.assertListEqual(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : str = "今天天气真好!" SCREAMING_SNAKE_CASE_ : Tuple = [tokenizer.bos_token] + tokens SCREAMING_SNAKE_CASE_ : str = [6, 9802, 1_4962, 2082, 831, 244] self.assertListEqual(tokenizer.convert_tokens_to_ids(lowercase__ ) , lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = tokenizer.decode(lowercase__ ) self.assertEqual(lowercase__ , lowercase__ )
68
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging snake_case_ = logging.get_logger(__name__) snake_case_ = { 'facebook/xmod-base': 'https://huggingface.co/facebook/xmod-base/resolve/main/config.json', 'facebook/xmod-large-prenorm': 'https://huggingface.co/facebook/xmod-large-prenorm/resolve/main/config.json', 'facebook/xmod-base-13-125k': 'https://huggingface.co/facebook/xmod-base-13-125k/resolve/main/config.json', 'facebook/xmod-base-30-125k': 'https://huggingface.co/facebook/xmod-base-30-125k/resolve/main/config.json', 'facebook/xmod-base-30-195k': 'https://huggingface.co/facebook/xmod-base-30-195k/resolve/main/config.json', 'facebook/xmod-base-60-125k': 'https://huggingface.co/facebook/xmod-base-60-125k/resolve/main/config.json', 'facebook/xmod-base-60-265k': 'https://huggingface.co/facebook/xmod-base-60-265k/resolve/main/config.json', 'facebook/xmod-base-75-125k': 'https://huggingface.co/facebook/xmod-base-75-125k/resolve/main/config.json', 'facebook/xmod-base-75-269k': 'https://huggingface.co/facebook/xmod-base-75-269k/resolve/main/config.json', } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = "xmod" def __init__( self , lowercase__=3_0522 , lowercase__=768 , lowercase__=12 , lowercase__=12 , lowercase__=3072 , lowercase__="gelu" , lowercase__=0.1 , lowercase__=0.1 , lowercase__=512 , lowercase__=2 , lowercase__=0.02 , lowercase__=1e-12 , lowercase__=1 , lowercase__=0 , lowercase__=2 , lowercase__="absolute" , lowercase__=True , lowercase__=None , lowercase__=False , lowercase__=2 , lowercase__=False , lowercase__=True , lowercase__=True , lowercase__=("en_XX",) , lowercase__=None , **lowercase__ , ): """simple docstring""" super().__init__(pad_token_id=lowercase__ , bos_token_id=lowercase__ , eos_token_id=lowercase__ , **lowercase__ ) SCREAMING_SNAKE_CASE_ : Tuple = vocab_size SCREAMING_SNAKE_CASE_ : Optional[Any] = hidden_size SCREAMING_SNAKE_CASE_ : Tuple = num_hidden_layers SCREAMING_SNAKE_CASE_ : Optional[int] = num_attention_heads SCREAMING_SNAKE_CASE_ : List[str] = hidden_act SCREAMING_SNAKE_CASE_ : Optional[int] = intermediate_size SCREAMING_SNAKE_CASE_ : Tuple = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : int = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE_ : Dict = type_vocab_size SCREAMING_SNAKE_CASE_ : str = initializer_range SCREAMING_SNAKE_CASE_ : List[str] = layer_norm_eps SCREAMING_SNAKE_CASE_ : Tuple = position_embedding_type SCREAMING_SNAKE_CASE_ : str = use_cache SCREAMING_SNAKE_CASE_ : Optional[int] = classifier_dropout SCREAMING_SNAKE_CASE_ : int = pre_norm SCREAMING_SNAKE_CASE_ : Optional[int] = adapter_reduction_factor SCREAMING_SNAKE_CASE_ : List[str] = adapter_layer_norm SCREAMING_SNAKE_CASE_ : List[str] = adapter_reuse_layer_norm SCREAMING_SNAKE_CASE_ : int = ln_before_adapter SCREAMING_SNAKE_CASE_ : List[Any] = list(lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = default_language class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): @property def __lowerCamelCase ( self ): """simple docstring""" if self.task == "multiple-choice": SCREAMING_SNAKE_CASE_ : Tuple = {0: "batch", 1: "choice", 2: "sequence"} else: SCREAMING_SNAKE_CASE_ : Optional[int] = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
68
1
'''simple docstring''' from PIL import Image def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Image , SCREAMING_SNAKE_CASE_ : int ) -> Image: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = (2_5_9 * (level + 2_5_5)) / (2_5_5 * (2_5_9 - level)) def contrast(SCREAMING_SNAKE_CASE_ : int ) -> int: return int(1_2_8 + factor * (c - 1_2_8) ) return img.point(SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": # Load image with Image.open('image_data/lena.jpg') as img: # Change contrast to 170 snake_case_ = change_contrast(img, 1_7_0) cont_img.save('image_data/lena_high_contrast.png', format='png')
68
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int ) -> int: """simple docstring""" return int((input_a, input_a).count(1 ) != 0 ) def __lowerCamelCase ( ) -> None: """simple docstring""" assert or_gate(0 , 0 ) == 0 assert or_gate(0 , 1 ) == 1 assert or_gate(1 , 0 ) == 1 assert or_gate(1 , 1 ) == 1 if __name__ == "__main__": print(or_gate(0, 1)) print(or_gate(1, 0)) print(or_gate(0, 0)) print(or_gate(1, 1))
68
1
'''simple docstring''' class SCREAMING_SNAKE_CASE__ : def __init__( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = {} def __lowerCamelCase ( self ): """simple docstring""" print(self.vertex ) for i in self.vertex: print(lowercase__ , " -> " , " -> ".join([str(lowercase__ ) for j in self.vertex[i]] ) ) def __lowerCamelCase ( self , lowercase__ , lowercase__ ): """simple docstring""" if from_vertex in self.vertex: self.vertex[from_vertex].append(lowercase__ ) else: # else make a new vertex SCREAMING_SNAKE_CASE_ : Tuple = [to_vertex] def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = [False] * len(self.vertex ) # call the recursive helper function for i in range(len(self.vertex ) ): if not visited[i]: self.dfs_recursive(lowercase__ , lowercase__ ) def __lowerCamelCase ( self , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = True print(lowercase__ , end=" " ) # Recur for all the vertices that are adjacent to this node for i in self.vertex: if not visited[i]: self.dfs_recursive(lowercase__ , lowercase__ ) if __name__ == "__main__": snake_case_ = Graph() g.add_edge(0, 1) g.add_edge(0, 2) g.add_edge(1, 2) g.add_edge(2, 0) g.add_edge(2, 3) g.add_edge(3, 3) g.print_graph() print('DFS:') g.dfs() # OUTPUT: # 0 -> 1 -> 2 # 1 -> 2 # 2 -> 0 -> 3 # 3 -> 3 # DFS: # 0 1 2 3
68
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..bit import BitConfig snake_case_ = logging.get_logger(__name__) snake_case_ = { 'Intel/dpt-large': 'https://huggingface.co/Intel/dpt-large/resolve/main/config.json', # See all DPT models at https://huggingface.co/models?filter=dpt } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = "dpt" def __init__( self , lowercase__=768 , lowercase__=12 , lowercase__=12 , lowercase__=3072 , lowercase__="gelu" , lowercase__=0.0 , lowercase__=0.0 , lowercase__=0.02 , lowercase__=1e-12 , lowercase__=384 , lowercase__=16 , lowercase__=3 , lowercase__=False , lowercase__=True , lowercase__=[2, 5, 8, 11] , lowercase__="project" , lowercase__=[4, 2, 1, 0.5] , lowercase__=[96, 192, 384, 768] , lowercase__=256 , lowercase__=-1 , lowercase__=False , lowercase__=True , lowercase__=0.4 , lowercase__=255 , lowercase__=0.1 , lowercase__=[1, 1024, 24, 24] , lowercase__=[0, 1] , lowercase__=None , **lowercase__ , ): """simple docstring""" super().__init__(**lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = hidden_size SCREAMING_SNAKE_CASE_ : Union[str, Any] = is_hybrid if self.is_hybrid: if backbone_config is None: logger.info("Initializing the config with a `BiT` backbone." ) SCREAMING_SNAKE_CASE_ : Tuple = { "global_padding": "same", "layer_type": "bottleneck", "depths": [3, 4, 9], "out_features": ["stage1", "stage2", "stage3"], "embedding_dynamic_padding": True, } SCREAMING_SNAKE_CASE_ : Union[str, Any] = BitConfig(**lowercase__ ) elif isinstance(lowercase__ , lowercase__ ): logger.info("Initializing the config with a `BiT` backbone." ) SCREAMING_SNAKE_CASE_ : Dict = BitConfig(**lowercase__ ) elif isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE_ : Optional[int] = backbone_config else: raise ValueError( F"backbone_config must be a dictionary or a `PretrainedConfig`, got {backbone_config.__class__}." ) SCREAMING_SNAKE_CASE_ : List[Any] = backbone_featmap_shape SCREAMING_SNAKE_CASE_ : Union[str, Any] = neck_ignore_stages if readout_type != "project": raise ValueError("Readout type must be 'project' when using `DPT-hybrid` mode." ) else: SCREAMING_SNAKE_CASE_ : Optional[Any] = None SCREAMING_SNAKE_CASE_ : int = None SCREAMING_SNAKE_CASE_ : List[Any] = [] SCREAMING_SNAKE_CASE_ : int = num_hidden_layers SCREAMING_SNAKE_CASE_ : Union[str, Any] = num_attention_heads SCREAMING_SNAKE_CASE_ : Tuple = intermediate_size SCREAMING_SNAKE_CASE_ : Optional[int] = hidden_act SCREAMING_SNAKE_CASE_ : Dict = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : str = initializer_range SCREAMING_SNAKE_CASE_ : List[Any] = layer_norm_eps SCREAMING_SNAKE_CASE_ : Any = image_size SCREAMING_SNAKE_CASE_ : Union[str, Any] = patch_size SCREAMING_SNAKE_CASE_ : Union[str, Any] = num_channels SCREAMING_SNAKE_CASE_ : Union[str, Any] = qkv_bias SCREAMING_SNAKE_CASE_ : Optional[Any] = backbone_out_indices if readout_type not in ["ignore", "add", "project"]: raise ValueError("Readout_type must be one of ['ignore', 'add', 'project']" ) SCREAMING_SNAKE_CASE_ : Any = readout_type SCREAMING_SNAKE_CASE_ : Optional[Any] = reassemble_factors SCREAMING_SNAKE_CASE_ : str = neck_hidden_sizes SCREAMING_SNAKE_CASE_ : Union[str, Any] = fusion_hidden_size SCREAMING_SNAKE_CASE_ : Any = head_in_index SCREAMING_SNAKE_CASE_ : str = use_batch_norm_in_fusion_residual # auxiliary head attributes (semantic segmentation) SCREAMING_SNAKE_CASE_ : List[Any] = use_auxiliary_head SCREAMING_SNAKE_CASE_ : int = auxiliary_loss_weight SCREAMING_SNAKE_CASE_ : Union[str, Any] = semantic_loss_ignore_index SCREAMING_SNAKE_CASE_ : Any = semantic_classifier_dropout def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = copy.deepcopy(self.__dict__ ) if output["backbone_config"] is not None: SCREAMING_SNAKE_CASE_ : List[str] = self.backbone_config.to_dict() SCREAMING_SNAKE_CASE_ : Optional[int] = self.__class__.model_type return output
68
1
'''simple docstring''' import logging 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, BertEncoder, BertModel, BertPreTrainedModel, ) snake_case_ = logging.getLogger(__name__) class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__=None , lowercase__=None ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.layer[current_layer](lowercase__ , lowercase__ , head_mask[current_layer] ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = layer_outputs[0] return hidden_states @add_start_docstrings( "The bare Bert Model transformer with PABEE outputting raw hidden-states without any specific head on top.",_UpperCAmelCase,) class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): def __init__( self , lowercase__ ): """simple docstring""" super().__init__(lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = BertEncoderWithPabee(lowercase__ ) self.init_weights() SCREAMING_SNAKE_CASE_ : List[Any] = 0 SCREAMING_SNAKE_CASE_ : Tuple = 0 SCREAMING_SNAKE_CASE_ : Optional[int] = 0 SCREAMING_SNAKE_CASE_ : Any = 0 def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = threshold def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = patience def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = 0 SCREAMING_SNAKE_CASE_ : List[str] = 0 def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.inference_layers_num / self.inference_instances_num SCREAMING_SNAKE_CASE_ : Union[str, Any] = ( F"*** Patience = {self.patience} Avg. Inference Layers = {avg_inf_layers:.2f} Speed Up =" F" {1 - avg_inf_layers / self.config.num_hidden_layers:.2f} ***" ) print(lowercase__ ) @add_start_docstrings_to_model_forward(lowercase__ ) def __lowerCamelCase ( self , lowercase__=None , lowercase__=None , lowercase__=None , lowercase__=None , lowercase__=None , lowercase__=None , lowercase__=None , lowercase__=None , lowercase__=None , lowercase__=None , lowercase__=False , ): """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_ : Dict = input_ids.size() elif inputs_embeds is not None: SCREAMING_SNAKE_CASE_ : List[Any] = inputs_embeds.size()[:-1] else: raise ValueError("You have to specify either input_ids or inputs_embeds" ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = input_ids.device if input_ids is not None else inputs_embeds.device if attention_mask is None: SCREAMING_SNAKE_CASE_ : int = torch.ones(lowercase__ , device=lowercase__ ) if token_type_ids is None: SCREAMING_SNAKE_CASE_ : Any = torch.zeros(lowercase__ , dtype=torch.long , device=lowercase__ ) # 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_ : torch.Tensor = self.get_extended_attention_mask(lowercase__ , lowercase__ , lowercase__ ) # 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 self.config.is_decoder and encoder_hidden_states is not None: SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[int] = encoder_hidden_states.size() SCREAMING_SNAKE_CASE_ : Tuple = (encoder_batch_size, encoder_sequence_length) if encoder_attention_mask is None: SCREAMING_SNAKE_CASE_ : List[Any] = torch.ones(lowercase__ , device=lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = self.invert_attention_mask(lowercase__ ) else: SCREAMING_SNAKE_CASE_ : Optional[Any] = None # 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_ : List[Any] = self.get_head_mask(lowercase__ , self.config.num_hidden_layers ) SCREAMING_SNAKE_CASE_ : Any = self.embeddings( input_ids=lowercase__ , position_ids=lowercase__ , token_type_ids=lowercase__ , inputs_embeds=lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = embedding_output if self.training: SCREAMING_SNAKE_CASE_ : int = [] for i in range(self.config.num_hidden_layers ): SCREAMING_SNAKE_CASE_ : Tuple = self.encoder.adaptive_forward( lowercase__ , current_layer=lowercase__ , attention_mask=lowercase__ , head_mask=lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = self.pooler(lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = output_layers[i](output_dropout(lowercase__ ) ) res.append(lowercase__ ) elif self.patience == 0: # Use all layers for inference SCREAMING_SNAKE_CASE_ : List[str] = self.encoder( lowercase__ , attention_mask=lowercase__ , head_mask=lowercase__ , encoder_hidden_states=lowercase__ , encoder_attention_mask=lowercase__ , ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.pooler(encoder_outputs[0] ) SCREAMING_SNAKE_CASE_ : List[Any] = [output_layers[self.config.num_hidden_layers - 1](lowercase__ )] else: SCREAMING_SNAKE_CASE_ : Union[str, Any] = 0 SCREAMING_SNAKE_CASE_ : Union[str, Any] = None SCREAMING_SNAKE_CASE_ : str = 0 for i in range(self.config.num_hidden_layers ): calculated_layer_num += 1 SCREAMING_SNAKE_CASE_ : Optional[Any] = self.encoder.adaptive_forward( lowercase__ , current_layer=lowercase__ , attention_mask=lowercase__ , head_mask=lowercase__ ) SCREAMING_SNAKE_CASE_ : int = self.pooler(lowercase__ ) SCREAMING_SNAKE_CASE_ : str = output_layers[i](lowercase__ ) if regression: SCREAMING_SNAKE_CASE_ : str = logits.detach() if patient_result is not None: SCREAMING_SNAKE_CASE_ : Any = patient_result.detach() if (patient_result is not None) and torch.abs(patient_result - labels ) < self.regression_threshold: patient_counter += 1 else: SCREAMING_SNAKE_CASE_ : int = 0 else: SCREAMING_SNAKE_CASE_ : Tuple = logits.detach().argmax(dim=1 ) if patient_result is not None: SCREAMING_SNAKE_CASE_ : Union[str, Any] = patient_result.detach().argmax(dim=1 ) if (patient_result is not None) and torch.all(labels.eq(lowercase__ ) ): patient_counter += 1 else: SCREAMING_SNAKE_CASE_ : int = 0 SCREAMING_SNAKE_CASE_ : List[Any] = logits if patient_counter == self.patience: break SCREAMING_SNAKE_CASE_ : Dict = [patient_result] self.inference_layers_num += calculated_layer_num self.inference_instances_num += 1 return res @add_start_docstrings( "Bert Model transformer with PABEE and a sequence classification/regression head on top (a linear layer on top of\n the pooled output) e.g. for GLUE tasks. ",_UpperCAmelCase,) class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): def __init__( self , lowercase__ ): """simple docstring""" super().__init__(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = config.num_labels SCREAMING_SNAKE_CASE_ : Tuple = BertModelWithPabee(lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = nn.Dropout(config.hidden_dropout_prob ) SCREAMING_SNAKE_CASE_ : Any = nn.ModuleList( [nn.Linear(config.hidden_size , self.config.num_labels ) for _ in range(config.num_hidden_layers )] ) self.init_weights() @add_start_docstrings_to_model_forward(lowercase__ ) def __lowerCamelCase ( self , lowercase__=None , lowercase__=None , lowercase__=None , lowercase__=None , lowercase__=None , lowercase__=None , lowercase__=None , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = self.bert( input_ids=lowercase__ , attention_mask=lowercase__ , token_type_ids=lowercase__ , position_ids=lowercase__ , head_mask=lowercase__ , inputs_embeds=lowercase__ , output_dropout=self.dropout , output_layers=self.classifiers , regression=self.num_labels == 1 , ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = (logits[-1],) if labels is not None: SCREAMING_SNAKE_CASE_ : Any = None SCREAMING_SNAKE_CASE_ : Union[str, Any] = 0 for ix, logits_item in enumerate(lowercase__ ): if self.num_labels == 1: # We are doing regression SCREAMING_SNAKE_CASE_ : List[Any] = MSELoss() SCREAMING_SNAKE_CASE_ : Optional[int] = loss_fct(logits_item.view(-1 ) , labels.view(-1 ) ) else: SCREAMING_SNAKE_CASE_ : str = CrossEntropyLoss() SCREAMING_SNAKE_CASE_ : Optional[Any] = loss_fct(logits_item.view(-1 , self.num_labels ) , labels.view(-1 ) ) if total_loss is None: SCREAMING_SNAKE_CASE_ : List[Any] = loss else: total_loss += loss * (ix + 1) total_weights += ix + 1 SCREAMING_SNAKE_CASE_ : List[str] = (total_loss / total_weights,) + outputs return outputs
68
'''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 if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ChineseCLIPImageProcessor class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __init__( self , lowercase__ , lowercase__=7 , lowercase__=3 , lowercase__=18 , lowercase__=30 , lowercase__=400 , lowercase__=True , lowercase__=None , lowercase__=True , lowercase__=None , lowercase__=True , lowercase__=[0.48145466, 0.4578275, 0.40821073] , lowercase__=[0.26862954, 0.26130258, 0.27577711] , lowercase__=True , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = size if size is not None else {"height": 224, "width": 224} SCREAMING_SNAKE_CASE_ : Optional[Any] = crop_size if crop_size is not None else {"height": 18, "width": 18} SCREAMING_SNAKE_CASE_ : str = parent SCREAMING_SNAKE_CASE_ : List[Any] = batch_size SCREAMING_SNAKE_CASE_ : Dict = num_channels SCREAMING_SNAKE_CASE_ : Any = image_size SCREAMING_SNAKE_CASE_ : Tuple = min_resolution SCREAMING_SNAKE_CASE_ : Optional[Any] = max_resolution SCREAMING_SNAKE_CASE_ : Tuple = do_resize SCREAMING_SNAKE_CASE_ : List[str] = size SCREAMING_SNAKE_CASE_ : str = do_center_crop SCREAMING_SNAKE_CASE_ : List[str] = crop_size SCREAMING_SNAKE_CASE_ : int = do_normalize SCREAMING_SNAKE_CASE_ : Optional[int] = image_mean SCREAMING_SNAKE_CASE_ : Dict = image_std SCREAMING_SNAKE_CASE_ : List[Any] = do_convert_rgb def __lowerCamelCase ( self ): """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_convert_rgb": self.do_convert_rgb, } def __lowerCamelCase ( self , lowercase__=False , lowercase__=False , lowercase__=False ): """simple docstring""" assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time" if equal_resolution: SCREAMING_SNAKE_CASE_ : Optional[int] = [] for i in range(self.batch_size ): image_inputs.append( np.random.randint( 255 , size=(self.num_channels, self.max_resolution, self.max_resolution) , dtype=np.uinta ) ) else: SCREAMING_SNAKE_CASE_ : str = [] for i in range(self.batch_size ): SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[Any] = np.random.choice(np.arange(self.min_resolution , self.max_resolution ) , 2 ) image_inputs.append(np.random.randint(255 , size=(self.num_channels, width, height) , dtype=np.uinta ) ) if not numpify and not torchify: # PIL expects the channel dimension as last dimension SCREAMING_SNAKE_CASE_ : str = [Image.fromarray(np.moveaxis(lowercase__ , 0 , -1 ) ) for x in image_inputs] if torchify: SCREAMING_SNAKE_CASE_ : List[str] = [torch.from_numpy(lowercase__ ) for x in image_inputs] return image_inputs @require_torch @require_vision class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,unittest.TestCase ): _A = ChineseCLIPImageProcessor if is_vision_available() else None def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = ChineseCLIPImageProcessingTester(self , do_center_crop=lowercase__ ) @property def __lowerCamelCase ( self ): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowercase__ , "do_resize" ) ) self.assertTrue(hasattr(lowercase__ , "size" ) ) self.assertTrue(hasattr(lowercase__ , "do_center_crop" ) ) self.assertTrue(hasattr(lowercase__ , "center_crop" ) ) self.assertTrue(hasattr(lowercase__ , "do_normalize" ) ) self.assertTrue(hasattr(lowercase__ , "image_mean" ) ) self.assertTrue(hasattr(lowercase__ , "image_std" ) ) self.assertTrue(hasattr(lowercase__ , "do_convert_rgb" ) ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"height": 224, "width": 224} ) self.assertEqual(image_processor.crop_size , {"height": 18, "width": 18} ) SCREAMING_SNAKE_CASE_ : str = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 ) self.assertEqual(image_processor.size , {"shortest_edge": 42} ) self.assertEqual(image_processor.crop_size , {"height": 84, "width": 84} ) def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE_ : Tuple = self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__ ) for image in image_inputs: self.assertIsInstance(lowercase__ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE_ : Dict = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE_ : Optional[int] = image_processing(lowercase__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__ , numpify=lowercase__ ) for image in image_inputs: self.assertIsInstance(lowercase__ , np.ndarray ) # Test not batched input SCREAMING_SNAKE_CASE_ : Optional[int] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE_ : List[str] = image_processing(lowercase__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors SCREAMING_SNAKE_CASE_ : List[str] = self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__ , torchify=lowercase__ ) for image in image_inputs: self.assertIsInstance(lowercase__ , torch.Tensor ) # Test not batched input SCREAMING_SNAKE_CASE_ : Union[str, Any] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE_ : int = image_processing(lowercase__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) @require_torch @require_vision class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,unittest.TestCase ): _A = ChineseCLIPImageProcessor if is_vision_available() else None def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int = ChineseCLIPImageProcessingTester(self , num_channels=4 , do_center_crop=lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = 3 @property def __lowerCamelCase ( self ): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowercase__ , "do_resize" ) ) self.assertTrue(hasattr(lowercase__ , "size" ) ) self.assertTrue(hasattr(lowercase__ , "do_center_crop" ) ) self.assertTrue(hasattr(lowercase__ , "center_crop" ) ) self.assertTrue(hasattr(lowercase__ , "do_normalize" ) ) self.assertTrue(hasattr(lowercase__ , "image_mean" ) ) self.assertTrue(hasattr(lowercase__ , "image_std" ) ) self.assertTrue(hasattr(lowercase__ , "do_convert_rgb" ) ) def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE_ : Optional[int] = self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__ ) for image in image_inputs: self.assertIsInstance(lowercase__ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE_ : Optional[Any] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE_ : List[str] = image_processing(lowercase__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , )
68
1
'''simple docstring''' import os from itertools import chain from random import randrange, shuffle import pytest from .sola import PokerHand snake_case_ = ( '4S 3H 2C 7S 5H', '9D 8H 2C 6S 7H', '2D 6D 9D TH 7D', 'TC 8C 2S JH 6C', 'JH 8S TH AH QH', 'TS KS 5S 9S AC', 'KD 6S 9D TH AD', 'KS 8D 4D 9S 4S', # pair '8C 4S KH JS 4D', # pair 'QH 8H KD JH 8S', # pair 'KC 4H KS 2H 8D', # pair 'KD 4S KC 3H 8S', # pair 'AH 8S AS KC JH', # pair '3H 4C 4H 3S 2H', # 2 pairs '5S 5D 2C KH KH', # 2 pairs '3C KH 5D 5S KH', # 2 pairs 'AS 3C KH AD KH', # 2 pairs '7C 7S 3S 7H 5S', # 3 of a kind '7C 7S KH 2H 7H', # 3 of a kind 'AC KH QH AH AS', # 3 of a kind '2H 4D 3C AS 5S', # straight (low ace) '3C 5C 4C 2C 6H', # straight '6S 8S 7S 5H 9H', # straight 'JS QS 9H TS KH', # straight 'QC KH TS JS AH', # straight (high ace) '8C 9C 5C 3C TC', # flush '3S 8S 9S 5S KS', # flush '4C 5C 9C 8C KC', # flush 'JH 8H AH KH QH', # flush '3D 2H 3H 2C 2D', # full house '2H 2C 3S 3H 3D', # full house 'KH KC 3S 3H 3D', # full house 'JC 6H JS JD JH', # 4 of a kind 'JC 7H JS JD JH', # 4 of a kind 'JC KH JS JD JH', # 4 of a kind '2S AS 4S 5S 3S', # straight flush (low ace) '2D 6D 3D 4D 5D', # straight flush '5C 6C 3C 7C 4C', # straight flush 'JH 9H TH KH QH', # straight flush 'JH AH TH KH QH', # royal flush (high ace straight flush) ) snake_case_ = ( ('2H 3H 4H 5H 6H', 'KS AS TS QS JS', 'Loss'), ('2H 3H 4H 5H 6H', 'AS AD AC AH JD', 'Win'), ('AS AH 2H AD AC', 'JS JD JC JH 3D', 'Win'), ('2S AH 2H AS AC', 'JS JD JC JH AD', 'Loss'), ('2S AH 2H AS AC', '2H 3H 5H 6H 7H', 'Win'), ('AS 3S 4S 8S 2S', '2H 3H 5H 6H 7H', 'Win'), ('2H 3H 5H 6H 7H', '2S 3H 4H 5S 6C', 'Win'), ('2S 3H 4H 5S 6C', '3D 4C 5H 6H 2S', 'Tie'), ('2S 3H 4H 5S 6C', 'AH AC 5H 6H AS', 'Win'), ('2S 2H 4H 5S 4C', 'AH AC 5H 6H AS', 'Loss'), ('2S 2H 4H 5S 4C', 'AH AC 5H 6H 7S', 'Win'), ('6S AD 7H 4S AS', 'AH AC 5H 6H 7S', 'Loss'), ('2S AH 4H 5S KC', 'AH AC 5H 6H 7S', 'Loss'), ('2S 3H 6H 7S 9C', '7H 3C TH 6H 9S', 'Loss'), ('4S 5H 6H TS AC', '3S 5H 6H TS AC', 'Win'), ('2S AH 4H 5S 6C', 'AD 4C 5H 6H 2C', 'Tie'), ('AS AH 3H AD AC', 'AS AH 2H AD AC', 'Win'), ('AH AC 5H 5C QS', 'AH AC 5H 5C KS', 'Loss'), ('AH AC 5H 5C QS', 'KH KC 5H 5C QS', 'Win'), ('7C 7S KH 2H 7H', '3C 3S AH 2H 3H', 'Win'), ('3C 3S AH 2H 3H', '7C 7S KH 2H 7H', 'Loss'), ('6H 5H 4H 3H 2H', '5H 4H 3H 2H AH', 'Win'), ('5H 4H 3H 2H AH', '5H 4H 3H 2H AH', 'Tie'), ('5H 4H 3H 2H AH', '6H 5H 4H 3H 2H', 'Loss'), ('AH AD KS KC AC', 'AH KD KH AC KC', 'Win'), ('2H 4D 3C AS 5S', '2H 4D 3C 6S 5S', 'Loss'), ('2H 3S 3C 3H 2S', '3S 3C 2S 2H 2D', 'Win'), ('4D 6D 5D 2D JH', '3S 8S 3H TC KH', 'Loss'), ('4S 6C 8S 3S 7S', 'AD KS 2D 7D 7C', 'Loss'), ('6S 4C 7H 8C 3H', '5H JC AH 9D 9C', 'Loss'), ('9D 9H JH TC QH', '3C 2S JS 5C 7H', 'Win'), ('2H TC 8S AD 9S', '4H TS 7H 2C 5C', 'Win'), ('9D 3S 2C 7S 7C', 'JC TD 3C TC 9H', 'Loss'), ) snake_case_ = ( ('2H 3H 4H 5H 6H', True), ('AS AH 2H AD AC', False), ('2H 3H 5H 6H 7H', True), ('KS AS TS QS JS', True), ('8H 9H QS JS TH', False), ('AS 3S 4S 8S 2S', True), ) snake_case_ = ( ('2H 3H 4H 5H 6H', True), ('AS AH 2H AD AC', False), ('2H 3H 5H 6H 7H', False), ('KS AS TS QS JS', True), ('8H 9H QS JS TH', True), ) snake_case_ = ( ('2H 4D 3C AS 5S', True, [5, 4, 3, 2, 1_4]), ('2H 5D 3C AS 5S', False, [1_4, 5, 5, 3, 2]), ('JH QD KC AS TS', False, [1_4, 1_3, 1_2, 1_1, 1_0]), ('9D 3S 2C 7S 7C', False, [9, 7, 7, 3, 2]), ) snake_case_ = ( ('JH AH TH KH QH', 0), ('JH 9H TH KH QH', 0), ('JC KH JS JD JH', 7), ('KH KC 3S 3H 3D', 6), ('8C 9C 5C 3C TC', 0), ('JS QS 9H TS KH', 0), ('7C 7S KH 2H 7H', 3), ('3C KH 5D 5S KH', 2), ('QH 8H KD JH 8S', 1), ('2D 6D 9D TH 7D', 0), ) snake_case_ = ( ('JH AH TH KH QH', 2_3), ('JH 9H TH KH QH', 2_2), ('JC KH JS JD JH', 2_1), ('KH KC 3S 3H 3D', 2_0), ('8C 9C 5C 3C TC', 1_9), ('JS QS 9H TS KH', 1_8), ('7C 7S KH 2H 7H', 1_7), ('3C KH 5D 5S KH', 1_6), ('QH 8H KD JH 8S', 1_5), ('2D 6D 9D TH 7D', 1_4), ) def __lowerCamelCase ( ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[Any] = randrange(len(SCREAMING_SNAKE_CASE_ ) ), randrange(len(SCREAMING_SNAKE_CASE_ ) ) SCREAMING_SNAKE_CASE_ : List[Any] = ["Loss", "Tie", "Win"][(play >= oppo) + (play > oppo)] SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[int] = SORTED_HANDS[play], SORTED_HANDS[oppo] return hand, other, expected def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int = 1_0_0 ) -> Any: """simple docstring""" return (generate_random_hand() for _ in range(SCREAMING_SNAKE_CASE_ )) @pytest.mark.parametrize("hand, expected" , SCREAMING_SNAKE_CASE_ ) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : Union[str, Any] ) -> int: """simple docstring""" assert PokerHand(SCREAMING_SNAKE_CASE_ )._is_flush() == expected @pytest.mark.parametrize("hand, expected" , SCREAMING_SNAKE_CASE_ ) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Dict ) -> List[str]: """simple docstring""" assert PokerHand(SCREAMING_SNAKE_CASE_ )._is_straight() == expected @pytest.mark.parametrize("hand, expected, card_values" , SCREAMING_SNAKE_CASE_ ) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Optional[Any] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = PokerHand(SCREAMING_SNAKE_CASE_ ) assert player._is_five_high_straight() == expected assert player._card_values == card_values @pytest.mark.parametrize("hand, expected" , SCREAMING_SNAKE_CASE_ ) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : List[str] ) -> Optional[Any]: """simple docstring""" assert PokerHand(SCREAMING_SNAKE_CASE_ )._is_same_kind() == expected @pytest.mark.parametrize("hand, expected" , SCREAMING_SNAKE_CASE_ ) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : Optional[int] ) -> Union[str, Any]: """simple docstring""" assert PokerHand(SCREAMING_SNAKE_CASE_ )._hand_type == expected @pytest.mark.parametrize("hand, other, expected" , SCREAMING_SNAKE_CASE_ ) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Optional[Any] ) -> List[Any]: """simple docstring""" assert PokerHand(SCREAMING_SNAKE_CASE_ ).compare_with(PokerHand(SCREAMING_SNAKE_CASE_ ) ) == expected @pytest.mark.parametrize("hand, other, expected" , generate_random_hands() ) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : int ) -> str: """simple docstring""" assert PokerHand(SCREAMING_SNAKE_CASE_ ).compare_with(PokerHand(SCREAMING_SNAKE_CASE_ ) ) == expected def __lowerCamelCase ( ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = [PokerHand(SCREAMING_SNAKE_CASE_ ) for hand in SORTED_HANDS] SCREAMING_SNAKE_CASE_ : Optional[int] = poker_hands.copy() shuffle(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Optional[int] = chain(sorted(SCREAMING_SNAKE_CASE_ ) ) for index, hand in enumerate(SCREAMING_SNAKE_CASE_ ): assert hand == poker_hands[index] def __lowerCamelCase ( ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = [PokerHand("2D AC 3H 4H 5S" ), PokerHand("2S 3H 4H 5S 6C" )] pokerhands.sort(reverse=SCREAMING_SNAKE_CASE_ ) assert pokerhands[0].__str__() == "2S 3H 4H 5S 6C" def __lowerCamelCase ( ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = PokerHand("2C 4S AS 3D 5C" ) SCREAMING_SNAKE_CASE_ : List[Any] = True SCREAMING_SNAKE_CASE_ : Tuple = [5, 4, 3, 2, 1_4] for _ in range(1_0 ): assert pokerhand._is_five_high_straight() == expected assert pokerhand._card_values == expected_card_values def __lowerCamelCase ( ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = 0 SCREAMING_SNAKE_CASE_ : List[str] = os.path.abspath(os.path.dirname(SCREAMING_SNAKE_CASE_ ) ) SCREAMING_SNAKE_CASE_ : Optional[int] = os.path.join(SCREAMING_SNAKE_CASE_ , "poker_hands.txt" ) with open(SCREAMING_SNAKE_CASE_ ) as file_hand: for line in file_hand: SCREAMING_SNAKE_CASE_ : str = line[:1_4].strip() SCREAMING_SNAKE_CASE_ : Optional[int] = line[1_5:].strip() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : str = PokerHand(SCREAMING_SNAKE_CASE_ ), PokerHand(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Tuple = player.compare_with(SCREAMING_SNAKE_CASE_ ) if output == "Win": answer += 1 assert answer == 3_7_6
68
'''simple docstring''' from __future__ import annotations def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int ) -> bool: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = str(SCREAMING_SNAKE_CASE_ ) return len(SCREAMING_SNAKE_CASE_ ) == 9 and set(SCREAMING_SNAKE_CASE_ ) == set("123456789" ) def __lowerCamelCase ( ) -> int | None: """simple docstring""" for base_num in range(9_9_9_9 , 4_9_9_9 , -1 ): SCREAMING_SNAKE_CASE_ : int = 1_0_0_0_0_2 * base_num if is_9_pandigital(SCREAMING_SNAKE_CASE_ ): return candidate for base_num in range(3_3_3 , 9_9 , -1 ): SCREAMING_SNAKE_CASE_ : List[str] = 1_0_0_2_0_0_3 * base_num if is_9_pandigital(SCREAMING_SNAKE_CASE_ ): return candidate return None if __name__ == "__main__": print(F'''{solution() = }''')
68
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging snake_case_ = logging.get_logger(__name__) snake_case_ = { 'facebook/vit-mae-base': 'https://huggingface.co/facebook/vit-mae-base/resolve/main/config.json', # See all ViT MAE models at https://huggingface.co/models?filter=vit-mae } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = "vit_mae" def __init__( self , lowercase__=768 , lowercase__=12 , lowercase__=12 , lowercase__=3072 , lowercase__="gelu" , lowercase__=0.0 , lowercase__=0.0 , lowercase__=0.02 , lowercase__=1e-12 , lowercase__=224 , lowercase__=16 , lowercase__=3 , lowercase__=True , lowercase__=16 , lowercase__=512 , lowercase__=8 , lowercase__=2048 , lowercase__=0.75 , lowercase__=False , **lowercase__ , ): """simple docstring""" super().__init__(**lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = hidden_size SCREAMING_SNAKE_CASE_ : Dict = num_hidden_layers SCREAMING_SNAKE_CASE_ : Tuple = num_attention_heads SCREAMING_SNAKE_CASE_ : Tuple = intermediate_size SCREAMING_SNAKE_CASE_ : List[Any] = hidden_act SCREAMING_SNAKE_CASE_ : Tuple = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : List[str] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : Union[str, Any] = initializer_range SCREAMING_SNAKE_CASE_ : List[Any] = layer_norm_eps SCREAMING_SNAKE_CASE_ : Dict = image_size SCREAMING_SNAKE_CASE_ : Dict = patch_size SCREAMING_SNAKE_CASE_ : List[str] = num_channels SCREAMING_SNAKE_CASE_ : Optional[int] = qkv_bias SCREAMING_SNAKE_CASE_ : str = decoder_num_attention_heads SCREAMING_SNAKE_CASE_ : Tuple = decoder_hidden_size SCREAMING_SNAKE_CASE_ : Any = decoder_num_hidden_layers SCREAMING_SNAKE_CASE_ : Union[str, Any] = decoder_intermediate_size SCREAMING_SNAKE_CASE_ : int = mask_ratio SCREAMING_SNAKE_CASE_ : Any = norm_pix_loss
68
'''simple docstring''' from typing import Optional import pyspark from .. import Features, NamedSplit from ..download import DownloadMode from ..packaged_modules.spark.spark import Spark from .abc import AbstractDatasetReader class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): def __init__( self , lowercase__ , lowercase__ = None , lowercase__ = None , lowercase__ = True , lowercase__ = None , lowercase__ = False , lowercase__ = None , lowercase__ = True , lowercase__ = "arrow" , **lowercase__ , ): """simple docstring""" super().__init__( split=lowercase__ , features=lowercase__ , cache_dir=lowercase__ , keep_in_memory=lowercase__ , streaming=lowercase__ , **lowercase__ , ) SCREAMING_SNAKE_CASE_ : Any = load_from_cache_file SCREAMING_SNAKE_CASE_ : Optional[int] = file_format SCREAMING_SNAKE_CASE_ : List[Any] = Spark( df=lowercase__ , features=lowercase__ , cache_dir=lowercase__ , working_dir=lowercase__ , **lowercase__ , ) def __lowerCamelCase ( self ): """simple docstring""" if self.streaming: return self.builder.as_streaming_dataset(split=self.split ) SCREAMING_SNAKE_CASE_ : Optional[int] = None if self._load_from_cache_file else DownloadMode.FORCE_REDOWNLOAD self.builder.download_and_prepare( download_mode=lowercase__ , file_format=self._file_format , ) return self.builder.as_dataset(split=self.split )
68
1
'''simple docstring''' import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_xlnet import XLNetTokenizer else: snake_case_ = None snake_case_ = logging.get_logger(__name__) snake_case_ = {'vocab_file': 'spiece.model', 'tokenizer_file': 'tokenizer.json'} snake_case_ = { 'vocab_file': { 'xlnet-base-cased': 'https://huggingface.co/xlnet-base-cased/resolve/main/spiece.model', 'xlnet-large-cased': 'https://huggingface.co/xlnet-large-cased/resolve/main/spiece.model', }, 'tokenizer_file': { 'xlnet-base-cased': 'https://huggingface.co/xlnet-base-cased/resolve/main/tokenizer.json', 'xlnet-large-cased': 'https://huggingface.co/xlnet-large-cased/resolve/main/tokenizer.json', }, } snake_case_ = { 'xlnet-base-cased': None, 'xlnet-large-cased': None, } snake_case_ = '▁' # Segments (not really needed) snake_case_ = 0 snake_case_ = 1 snake_case_ = 2 snake_case_ = 3 snake_case_ = 4 class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = VOCAB_FILES_NAMES _A = PRETRAINED_VOCAB_FILES_MAP _A = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _A = "left" _A = XLNetTokenizer def __init__( self , lowercase__=None , lowercase__=None , lowercase__=False , lowercase__=True , lowercase__=False , lowercase__="<s>" , lowercase__="</s>" , lowercase__="<unk>" , lowercase__="<sep>" , lowercase__="<pad>" , lowercase__="<cls>" , lowercase__="<mask>" , lowercase__=["<eop>", "<eod>"] , **lowercase__ , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int = AddedToken(lowercase__ , lstrip=lowercase__ , rstrip=lowercase__ ) if isinstance(lowercase__ , lowercase__ ) else mask_token super().__init__( vocab_file=lowercase__ , tokenizer_file=lowercase__ , do_lower_case=lowercase__ , remove_space=lowercase__ , keep_accents=lowercase__ , bos_token=lowercase__ , eos_token=lowercase__ , unk_token=lowercase__ , sep_token=lowercase__ , pad_token=lowercase__ , cls_token=lowercase__ , mask_token=lowercase__ , additional_special_tokens=lowercase__ , **lowercase__ , ) SCREAMING_SNAKE_CASE_ : Optional[int] = 3 SCREAMING_SNAKE_CASE_ : List[Any] = do_lower_case SCREAMING_SNAKE_CASE_ : str = remove_space SCREAMING_SNAKE_CASE_ : Any = keep_accents SCREAMING_SNAKE_CASE_ : int = vocab_file SCREAMING_SNAKE_CASE_ : Optional[Any] = False if not self.vocab_file else True def __lowerCamelCase ( self , lowercase__ , lowercase__ = None ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int = [self.sep_token_id] SCREAMING_SNAKE_CASE_ : List[str] = [self.cls_token_id] if token_ids_a is None: return token_ids_a + sep + cls return token_ids_a + sep + token_ids_a + sep + cls def __lowerCamelCase ( self , lowercase__ , lowercase__ = None ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = [self.sep_token_id] SCREAMING_SNAKE_CASE_ : str = [2] if token_ids_a is None: return len(token_ids_a + sep ) * [0] + cls_segment_id return len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] + cls_segment_id def __lowerCamelCase ( self , lowercase__ , lowercase__ = None ): """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(lowercase__ ): logger.error(F"Vocabulary path ({save_directory}) should be a directory" ) return SCREAMING_SNAKE_CASE_ : int = os.path.join( lowercase__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(lowercase__ ): copyfile(self.vocab_file , lowercase__ ) return (out_vocab_file,)
68
'''simple docstring''' import re import string import numpy as np import datasets snake_case_ = '\nReturns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list.\n' snake_case_ = '\nArgs:\n predictions: List of predicted texts.\n references: List of reference texts.\n regexes_to_ignore: List, defaults to None. Regex expressions of characters to\n ignore when calculating the exact matches. Note: these regexes are removed\n from the input data before the changes based on the options below (e.g. ignore_case,\n ignore_punctuation, ignore_numbers) are applied.\n ignore_case: Boolean, defaults to False. If true, turns everything\n to lowercase so that capitalization differences are ignored.\n ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\n ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\nReturns:\n exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive.\nExamples:\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results["exact_match"], 1))\n 25.0\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results["exact_match"], 1))\n 50.0\n\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results["exact_match"], 1))\n 75.0\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True)\n >>> print(round(results["exact_match"], 1))\n 100.0\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["The cat sat on the mat.", "Theaters are great.", "It\'s like comparing oranges and apples."]\n >>> preds = ["The cat sat on the mat?", "Theaters are great.", "It\'s like comparing apples and oranges."]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results["exact_match"], 1))\n 33.3\n\n' snake_case_ = '\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION,_KWARGS_DESCRIPTION ) class SCREAMING_SNAKE_CASE__ ( datasets.Metric ): def __lowerCamelCase ( self ): """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Value("string" , id="sequence" ), "references": datasets.Value("string" , id="sequence" ), } ) , reference_urls=[] , ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__=None , lowercase__=False , lowercase__=False , lowercase__=False , ): """simple docstring""" if regexes_to_ignore is not None: for s in regexes_to_ignore: SCREAMING_SNAKE_CASE_ : Optional[Any] = np.array([re.sub(lowercase__ , "" , lowercase__ ) for x in predictions] ) SCREAMING_SNAKE_CASE_ : List[Any] = np.array([re.sub(lowercase__ , "" , lowercase__ ) for x in references] ) else: SCREAMING_SNAKE_CASE_ : int = np.asarray(lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = np.asarray(lowercase__ ) if ignore_case: SCREAMING_SNAKE_CASE_ : Dict = np.char.lower(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = np.char.lower(lowercase__ ) if ignore_punctuation: SCREAMING_SNAKE_CASE_ : Optional[int] = string.punctuation.maketrans("" , "" , string.punctuation ) SCREAMING_SNAKE_CASE_ : int = np.char.translate(lowercase__ , table=lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = np.char.translate(lowercase__ , table=lowercase__ ) if ignore_numbers: SCREAMING_SNAKE_CASE_ : Optional[int] = string.digits.maketrans("" , "" , string.digits ) SCREAMING_SNAKE_CASE_ : Dict = np.char.translate(lowercase__ , table=lowercase__ ) SCREAMING_SNAKE_CASE_ : int = np.char.translate(lowercase__ , table=lowercase__ ) SCREAMING_SNAKE_CASE_ : str = predictions == references return {"exact_match": np.mean(lowercase__ ) * 100}
68
1
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int ) -> int: """simple docstring""" return 1 if input_a == input_a else 0 def __lowerCamelCase ( ) -> None: """simple docstring""" assert xnor_gate(0 , 0 ) == 1 assert xnor_gate(0 , 1 ) == 0 assert xnor_gate(1 , 0 ) == 0 assert xnor_gate(1 , 1 ) == 1 if __name__ == "__main__": print(xnor_gate(0, 0)) print(xnor_gate(0, 1)) print(xnor_gate(1, 0)) print(xnor_gate(1, 1))
68
'''simple docstring''' import os import re import unicodedata from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import is_torch_available, logging if is_torch_available(): import torch if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation snake_case_ = logging.get_logger(__name__) snake_case_ = {'vocab_file': 'spiece.model'} snake_case_ = { 'vocab_file': { 'AI-Sweden/gpt-sw3-126m': 'https://huggingface.co/AI-Sweden/gpt-sw3-126m/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-350m': 'https://huggingface.co/AI-Sweden/gpt-sw3-350m/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-1.6b': 'https://huggingface.co/AI-Sweden/gpt-sw3-1.6b/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-6.7b': 'https://huggingface.co/AI-Sweden/gpt-sw3-6.7b/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-20b': 'https://huggingface.co/AI-Sweden/gpt-sw3-20b/resolve/main/spiece.model', } } snake_case_ = { 'AI-Sweden/gpt-sw3-126m': 2_0_4_8, 'AI-Sweden/gpt-sw3-350m': 2_0_4_8, 'AI-Sweden/gpt-sw3-1.6b': 2_0_4_8, 'AI-Sweden/gpt-sw3-6.7b': 2_0_4_8, 'AI-Sweden/gpt-sw3-20b': 2_0_4_8, } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = VOCAB_FILES_NAMES _A = PRETRAINED_VOCAB_FILES_MAP _A = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _A = ["input_ids", "attention_mask"] def __init__( self , lowercase__ , lowercase__=False , lowercase__=False , lowercase__=False , lowercase__=None , lowercase__=None , lowercase__=None , lowercase__=None , lowercase__ = None , **lowercase__ , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = {} if sp_model_kwargs is None else sp_model_kwargs SCREAMING_SNAKE_CASE_ : Dict = kwargs.get("name_or_path" ) if name_or_path is None: logger.warning( "name_or_path not provided, will work for all GPTSw3 models except gpt-sw3-7b," " you are testing the model, this can safely be ignored" ) SCREAMING_SNAKE_CASE_ : str = "None" # Default definitions for our 2 tokenizer versions, with None-checks to enable proper testing SCREAMING_SNAKE_CASE_ : List[Any] = "<|endoftext|>" if eos_token is None else eos_token SCREAMING_SNAKE_CASE_ : Dict = "<unk>" if unk_token is None else unk_token if "gpt-sw3-7b" in name_or_path: SCREAMING_SNAKE_CASE_ : Tuple = unk_token if pad_token is None else pad_token SCREAMING_SNAKE_CASE_ : Optional[Any] = eos_token if bos_token is None else bos_token else: SCREAMING_SNAKE_CASE_ : int = "<pad>" if pad_token is None else pad_token SCREAMING_SNAKE_CASE_ : Any = "<s>" if bos_token is None else bos_token super().__init__( do_lower_case=lowercase__ , remove_space=lowercase__ , keep_accents=lowercase__ , bos_token=lowercase__ , eos_token=lowercase__ , unk_token=lowercase__ , pad_token=lowercase__ , sp_model_kwargs=self.sp_model_kwargs , **lowercase__ , ) SCREAMING_SNAKE_CASE_ : Optional[Any] = do_lower_case SCREAMING_SNAKE_CASE_ : Optional[int] = remove_space SCREAMING_SNAKE_CASE_ : int = keep_accents SCREAMING_SNAKE_CASE_ : List[Any] = vocab_file SCREAMING_SNAKE_CASE_ : List[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(lowercase__ ) # Used for whitespace normalization in input texts # fmt : off SCREAMING_SNAKE_CASE_ : int = {" ", " ", " ", " ", " ", " ", " ", " ", " ", " ", "", "„"} # fmt : on # Regular expression to remove non-printing characters (e.g. some unicode control chars) in preprocessing SCREAMING_SNAKE_CASE_ : List[str] = re.compile( F"[{''.join(map(lowercase__ , list(range(0 , 9 ) ) + list(range(11 , 32 ) ) + list(range(127 , 160 ) ) + [160, 173, 8203] ) )}]" ) def __getstate__( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = self.__dict__.copy() SCREAMING_SNAKE_CASE_ : Dict = None return state def __setstate__( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): SCREAMING_SNAKE_CASE_ : Union[str, Any] = {} SCREAMING_SNAKE_CASE_ : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) @property # Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.vocab_size def __lowerCamelCase ( self ): """simple docstring""" return len(self.sp_model ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.non_printing_characters_re.sub("" , lowercase__ ) # Normalize whitespaces SCREAMING_SNAKE_CASE_ : List[str] = "".join([char if char not in self.whitespaces else " " for char in text] ) # NFC Unicode normalization SCREAMING_SNAKE_CASE_ : List[Any] = unicodedata.normalize("NFC" , lowercase__ ) return text def __lowerCamelCase ( self , lowercase__ , **lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = self.preprocess_text(lowercase__ ) return self.sp_model.encode(lowercase__ , out_type=lowercase__ ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" return self.sp_model.PieceToId(lowercase__ ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" return self.sp_model.IdToPiece(lowercase__ ) @staticmethod def __lowerCamelCase ( lowercase__ ): """simple docstring""" return out_string def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = [] SCREAMING_SNAKE_CASE_ : Any = "" SCREAMING_SNAKE_CASE_ : Dict = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: # TODO: Check if this is needed, as it ensures that decode(encode(doc)) != doc by adding extra whitespace in the decoded document if not prev_is_special: out_string += " " out_string += self.sp_model.decode(lowercase__ ) + token SCREAMING_SNAKE_CASE_ : Union[str, Any] = True SCREAMING_SNAKE_CASE_ : int = [] else: current_sub_tokens.append(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = False out_string += self.sp_model.decode(lowercase__ ) return out_string def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = {self.convert_ids_to_tokens(lowercase__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __lowerCamelCase ( self , lowercase__ , lowercase__ = None ): """simple docstring""" if not os.path.isdir(lowercase__ ): logger.error(F"Vocabulary path ({save_directory}) should be a directory" ) return SCREAMING_SNAKE_CASE_ : Any = os.path.join( lowercase__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(lowercase__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , lowercase__ ) elif not os.path.isfile(self.vocab_file ): with open(lowercase__ , "wb" ) as fi: SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.sp_model.serialized_model_proto() fi.write(lowercase__ ) return (out_vocab_file,) def __lowerCamelCase ( self , lowercase__ , lowercase__ = False ): """simple docstring""" if isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE_ : List[Any] = self.preprocess_text(lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = self.sp_model.encode(lowercase__ ) else: SCREAMING_SNAKE_CASE_ : str = [self.preprocess_text(lowercase__ ) for t in text] SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.sp_model.encode(lowercase__ ) if return_tensors is True or return_tensors == "pt": SCREAMING_SNAKE_CASE_ : str = torch.tensor(lowercase__ ) return token_ids def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" return self.sp_model.decode(lowercase__ ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = [F"User: {text}" if is_user else F"Bot: {text}" for is_user, text in conversation.iter_texts()] SCREAMING_SNAKE_CASE_ : List[str] = ( F"{self.eos_token}{self.bos_token}" + F"{self.bos_token}".join(lowercase__ ) + F"{self.bos_token}Bot:" ) return self.encode(text=lowercase__ )
68
1
'''simple docstring''' from __future__ import annotations from sys import maxsize from typing import Generic, TypeVar snake_case_ = TypeVar('T') def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int ) -> int: """simple docstring""" return (position - 1) // 2 def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int ) -> int: """simple docstring""" return (2 * position) + 1 def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int ) -> int: """simple docstring""" return (2 * position) + 2 class SCREAMING_SNAKE_CASE__ ( Generic[T] ): def __init__( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : list[tuple[T, int]] = [] SCREAMING_SNAKE_CASE_ : dict[T, int] = {} SCREAMING_SNAKE_CASE_ : int = 0 def __len__( self ): """simple docstring""" return self.elements def __repr__( self ): """simple docstring""" return str(self.heap ) def __lowerCamelCase ( self ): """simple docstring""" return self.elements == 0 def __lowerCamelCase ( self , lowercase__ , lowercase__ ): """simple docstring""" self.heap.append((elem, weight) ) SCREAMING_SNAKE_CASE_ : Optional[Any] = self.elements self.elements += 1 self._bubble_up(lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" if self.elements > 1: self._swap_nodes(0 , self.elements - 1 ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : int = self.heap.pop() del self.position_map[elem] self.elements -= 1 if self.elements > 0: SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : List[Any] = self.heap[0] self._bubble_down(lowercase__ ) return elem def __lowerCamelCase ( self , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.position_map[elem] SCREAMING_SNAKE_CASE_ : Tuple = (elem, weight) if position > 0: SCREAMING_SNAKE_CASE_ : Tuple = get_parent_position(lowercase__ ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : List[Any] = self.heap[parent_position] if parent_weight > weight: self._bubble_up(lowercase__ ) else: self._bubble_down(lowercase__ ) else: self._bubble_down(lowercase__ ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int = self.position_map[elem] if curr_pos == 0: return None SCREAMING_SNAKE_CASE_ : Optional[int] = get_parent_position(lowercase__ ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : List[Any] = self.heap[curr_pos] SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : int = self.heap[parent_position] if parent_weight > weight: self._swap_nodes(lowercase__ , lowercase__ ) return self._bubble_up(lowercase__ ) return None def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int = self.position_map[elem] SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[Any] = self.heap[curr_pos] SCREAMING_SNAKE_CASE_ : int = get_child_left_position(lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = get_child_right_position(lowercase__ ) if child_left_position < self.elements and child_right_position < self.elements: SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : str = self.heap[child_left_position] SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[Any] = self.heap[child_right_position] if child_right_weight < child_left_weight and child_right_weight < weight: self._swap_nodes(lowercase__ , lowercase__ ) return self._bubble_down(lowercase__ ) if child_left_position < self.elements: SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[int] = self.heap[child_left_position] if child_left_weight < weight: self._swap_nodes(lowercase__ , lowercase__ ) return self._bubble_down(lowercase__ ) else: return None if child_right_position < self.elements: SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : List[Any] = self.heap[child_right_position] if child_right_weight < weight: self._swap_nodes(lowercase__ , lowercase__ ) return self._bubble_down(lowercase__ ) return None def __lowerCamelCase ( self , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.heap[nodea_pos][0] SCREAMING_SNAKE_CASE_ : List[Any] = self.heap[nodea_pos][0] SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[Any] = ( self.heap[nodea_pos], self.heap[nodea_pos], ) SCREAMING_SNAKE_CASE_ : Dict = nodea_pos SCREAMING_SNAKE_CASE_ : List[str] = nodea_pos class SCREAMING_SNAKE_CASE__ ( Generic[T] ): def __init__( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : dict[T, dict[T, int]] = {} SCREAMING_SNAKE_CASE_ : int = 0 def __repr__( self ): """simple docstring""" return str(self.connections ) def __len__( self ): """simple docstring""" return self.nodes def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" if node not in self.connections: SCREAMING_SNAKE_CASE_ : List[str] = {} self.nodes += 1 def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" self.add_node(lowercase__ ) self.add_node(lowercase__ ) SCREAMING_SNAKE_CASE_ : int = weight SCREAMING_SNAKE_CASE_ : Any = weight def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : GraphUndirectedWeighted[T] , ) -> tuple[dict[T, int], dict[T, T | None]]: """simple docstring""" SCREAMING_SNAKE_CASE_ : dict[T, int] = {node: maxsize for node in graph.connections} SCREAMING_SNAKE_CASE_ : dict[T, T | None] = {node: None for node in graph.connections} SCREAMING_SNAKE_CASE_ : MinPriorityQueue[T] = MinPriorityQueue() for node, weight in dist.items(): priority_queue.push(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if priority_queue.is_empty(): return dist, parent # initialization SCREAMING_SNAKE_CASE_ : Union[str, Any] = priority_queue.extract_min() SCREAMING_SNAKE_CASE_ : int = 0 for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: SCREAMING_SNAKE_CASE_ : Tuple = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(SCREAMING_SNAKE_CASE_ , dist[neighbour] ) SCREAMING_SNAKE_CASE_ : Dict = node # running prim's algorithm while not priority_queue.is_empty(): SCREAMING_SNAKE_CASE_ : List[str] = priority_queue.extract_min() for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: SCREAMING_SNAKE_CASE_ : Dict = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(SCREAMING_SNAKE_CASE_ , dist[neighbour] ) SCREAMING_SNAKE_CASE_ : List[Any] = node return dist, parent
68
'''simple docstring''' import re from filelock import FileLock try: import nltk snake_case_ = True except (ImportError, ModuleNotFoundError): snake_case_ = False if NLTK_AVAILABLE: with FileLock('.lock') as lock: nltk.download('punkt', quiet=True) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str ) -> str: """simple docstring""" re.sub("<n>" , "" , SCREAMING_SNAKE_CASE_ ) # remove pegasus newline char assert NLTK_AVAILABLE, "nltk must be installed to separate newlines between sentences. (pip install nltk)" return "\n".join(nltk.sent_tokenize(SCREAMING_SNAKE_CASE_ ) )
68
1
'''simple docstring''' from __future__ import annotations snake_case_ = 8.988E9 # units = N * m^s * C^-2 def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float ) -> dict[str, float]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = abs(chargea * chargea ) if (force, chargea, chargea, distance).count(0 ) != 1: raise ValueError("One and only one argument must be 0" ) if distance < 0: raise ValueError("Distance cannot be negative" ) if force == 0: SCREAMING_SNAKE_CASE_ : Tuple = COULOMBS_CONSTANT * charge_product / (distance**2) return {"force": force} elif chargea == 0: SCREAMING_SNAKE_CASE_ : Optional[Any] = abs(SCREAMING_SNAKE_CASE_ ) * (distance**2) / (COULOMBS_CONSTANT * chargea) return {"charge1": chargea} elif chargea == 0: SCREAMING_SNAKE_CASE_ : int = abs(SCREAMING_SNAKE_CASE_ ) * (distance**2) / (COULOMBS_CONSTANT * chargea) return {"charge2": chargea} elif distance == 0: SCREAMING_SNAKE_CASE_ : List[Any] = (COULOMBS_CONSTANT * charge_product / abs(SCREAMING_SNAKE_CASE_ )) ** 0.5 return {"distance": distance} raise ValueError("Exactly one argument must be 0" ) if __name__ == "__main__": import doctest doctest.testmod()
68
'''simple docstring''' from __future__ import annotations import copy import inspect import unittest import numpy as np from transformers import is_tf_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_tf, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, TFLayoutLMvaModel, ) if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class SCREAMING_SNAKE_CASE__ : def __init__( self , lowercase__ , lowercase__=2 , lowercase__=3 , lowercase__=4 , lowercase__=2 , lowercase__=7 , lowercase__=True , lowercase__=True , lowercase__=True , lowercase__=True , lowercase__=99 , lowercase__=36 , lowercase__=2 , lowercase__=4 , lowercase__=37 , lowercase__="gelu" , lowercase__=0.1 , lowercase__=0.1 , lowercase__=512 , lowercase__=16 , lowercase__=2 , lowercase__=0.02 , lowercase__=6 , lowercase__=6 , lowercase__=3 , lowercase__=4 , lowercase__=None , lowercase__=1000 , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = parent SCREAMING_SNAKE_CASE_ : Optional[int] = batch_size SCREAMING_SNAKE_CASE_ : Dict = num_channels SCREAMING_SNAKE_CASE_ : Union[str, Any] = image_size SCREAMING_SNAKE_CASE_ : Optional[int] = patch_size SCREAMING_SNAKE_CASE_ : str = is_training SCREAMING_SNAKE_CASE_ : str = use_input_mask SCREAMING_SNAKE_CASE_ : Any = use_token_type_ids SCREAMING_SNAKE_CASE_ : int = use_labels SCREAMING_SNAKE_CASE_ : Union[str, Any] = vocab_size SCREAMING_SNAKE_CASE_ : Optional[Any] = hidden_size SCREAMING_SNAKE_CASE_ : Dict = num_hidden_layers SCREAMING_SNAKE_CASE_ : Any = num_attention_heads SCREAMING_SNAKE_CASE_ : Optional[Any] = intermediate_size SCREAMING_SNAKE_CASE_ : str = hidden_act SCREAMING_SNAKE_CASE_ : int = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : Tuple = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : Union[str, Any] = max_position_embeddings SCREAMING_SNAKE_CASE_ : Dict = type_vocab_size SCREAMING_SNAKE_CASE_ : List[Any] = type_sequence_label_size SCREAMING_SNAKE_CASE_ : Tuple = initializer_range SCREAMING_SNAKE_CASE_ : List[str] = coordinate_size SCREAMING_SNAKE_CASE_ : Optional[Any] = shape_size SCREAMING_SNAKE_CASE_ : List[str] = num_labels SCREAMING_SNAKE_CASE_ : Optional[int] = num_choices SCREAMING_SNAKE_CASE_ : Union[str, Any] = scope SCREAMING_SNAKE_CASE_ : Dict = 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_ : Union[str, Any] = text_seq_length SCREAMING_SNAKE_CASE_ : Tuple = (image_size // patch_size) ** 2 + 1 SCREAMING_SNAKE_CASE_ : Optional[int] = self.text_seq_length + self.image_seq_length def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE_ : Optional[Any] = ids_tensor([self.batch_size, self.text_seq_length, 4] , self.range_bbox ) SCREAMING_SNAKE_CASE_ : Dict = bbox.numpy() # 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_ : Optional[int] = bbox[i, j, 3] SCREAMING_SNAKE_CASE_ : str = bbox[i, j, 1] SCREAMING_SNAKE_CASE_ : Dict = tmp_coordinate if bbox[i, j, 2] < bbox[i, j, 0]: SCREAMING_SNAKE_CASE_ : List[Any] = bbox[i, j, 2] SCREAMING_SNAKE_CASE_ : Dict = bbox[i, j, 0] SCREAMING_SNAKE_CASE_ : Tuple = tmp_coordinate SCREAMING_SNAKE_CASE_ : Dict = tf.constant(lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE_ : Dict = None if self.use_input_mask: SCREAMING_SNAKE_CASE_ : Any = random_attention_mask([self.batch_size, self.text_seq_length] ) SCREAMING_SNAKE_CASE_ : List[str] = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE_ : Dict = ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE_ : Dict = None SCREAMING_SNAKE_CASE_ : Tuple = None if self.use_labels: SCREAMING_SNAKE_CASE_ : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE_ : List[str] = ids_tensor([self.batch_size, self.text_seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE_ : str = 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 __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = TFLayoutLMvaModel(config=lowercase__ ) # text + image SCREAMING_SNAKE_CASE_ : int = model(lowercase__ , pixel_values=lowercase__ , training=lowercase__ ) SCREAMING_SNAKE_CASE_ : str = model( lowercase__ , bbox=lowercase__ , pixel_values=lowercase__ , attention_mask=lowercase__ , token_type_ids=lowercase__ , training=lowercase__ , ) SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase__ , bbox=lowercase__ , pixel_values=lowercase__ , training=lowercase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # text only SCREAMING_SNAKE_CASE_ : Tuple = model(lowercase__ , training=lowercase__ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size) ) # image only SCREAMING_SNAKE_CASE_ : int = model({"pixel_values": pixel_values} , training=lowercase__ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size) ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = self.num_labels SCREAMING_SNAKE_CASE_ : Union[str, Any] = TFLayoutLMvaForSequenceClassification(config=lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = model( lowercase__ , bbox=lowercase__ , pixel_values=lowercase__ , attention_mask=lowercase__ , token_type_ids=lowercase__ , labels=lowercase__ , training=lowercase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.num_labels SCREAMING_SNAKE_CASE_ : Any = TFLayoutLMvaForTokenClassification(config=lowercase__ ) SCREAMING_SNAKE_CASE_ : int = model( lowercase__ , bbox=lowercase__ , pixel_values=lowercase__ , attention_mask=lowercase__ , token_type_ids=lowercase__ , labels=lowercase__ , training=lowercase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels) ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = 2 SCREAMING_SNAKE_CASE_ : List[Any] = TFLayoutLMvaForQuestionAnswering(config=lowercase__ ) SCREAMING_SNAKE_CASE_ : int = model( lowercase__ , bbox=lowercase__ , pixel_values=lowercase__ , attention_mask=lowercase__ , token_type_ids=lowercase__ , start_positions=lowercase__ , end_positions=lowercase__ , training=lowercase__ , ) 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 __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = 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_)) : Any = config_and_inputs SCREAMING_SNAKE_CASE_ : Optional[Any] = { "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_tf class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,_UpperCAmelCase,unittest.TestCase ): _A = ( ( TFLayoutLMvaModel, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, ) if is_tf_available() else () ) _A = ( {"document-question-answering": TFLayoutLMvaForQuestionAnswering, "feature-extraction": TFLayoutLMvaModel} if is_tf_available() else {} ) _A = False _A = False _A = False def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" return True def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__=False ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = copy.deepcopy(lowercase__ ) if model_class in get_values(lowercase__ ): SCREAMING_SNAKE_CASE_ : str = { k: tf.tile(tf.expand_dims(lowercase__ , 1 ) , (1, self.model_tester.num_choices) + (1,) * (v.ndim - 1) ) if isinstance(lowercase__ , tf.Tensor ) and v.ndim > 0 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(lowercase__ ): SCREAMING_SNAKE_CASE_ : Tuple = tf.ones(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(lowercase__ ): SCREAMING_SNAKE_CASE_ : Any = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) SCREAMING_SNAKE_CASE_ : List[Any] = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(lowercase__ ): SCREAMING_SNAKE_CASE_ : List[str] = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(lowercase__ ): SCREAMING_SNAKE_CASE_ : Optional[Any] = tf.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=tf.intaa ) return inputs_dict def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = TFLayoutLMvaModelTester(self ) SCREAMING_SNAKE_CASE_ : int = ConfigTester(self , config_class=lowercase__ , hidden_size=37 ) def __lowerCamelCase ( self ): """simple docstring""" self.config_tester.run_common_tests() def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ : int = model_class(lowercase__ ) if getattr(lowercase__ , "hf_compute_loss" , lowercase__ ): # The number of elements in the loss should be the same as the number of elements in the label SCREAMING_SNAKE_CASE_ : Dict = self._prepare_for_class(inputs_dict.copy() , lowercase__ , return_labels=lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = prepared_for_class[ sorted(prepared_for_class.keys() - inputs_dict.keys() , reverse=lowercase__ )[0] ] SCREAMING_SNAKE_CASE_ : Any = added_label.shape.as_list()[:1] # Test that model correctly compute the loss with kwargs SCREAMING_SNAKE_CASE_ : Dict = self._prepare_for_class(inputs_dict.copy() , lowercase__ , return_labels=lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = prepared_for_class.pop("input_ids" ) SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase__ , **lowercase__ )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss when we mask some positions SCREAMING_SNAKE_CASE_ : List[Any] = self._prepare_for_class(inputs_dict.copy() , lowercase__ , return_labels=lowercase__ ) SCREAMING_SNAKE_CASE_ : int = prepared_for_class.pop("input_ids" ) if "labels" in prepared_for_class: SCREAMING_SNAKE_CASE_ : str = prepared_for_class["labels"].numpy() if len(labels.shape ) > 1 and labels.shape[1] != 1: SCREAMING_SNAKE_CASE_ : str = -100 SCREAMING_SNAKE_CASE_ : str = tf.convert_to_tensor(lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = model(lowercase__ , **lowercase__ )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) self.assertTrue(not np.any(np.isnan(loss.numpy() ) ) ) # Test that model correctly compute the loss with a dict SCREAMING_SNAKE_CASE_ : List[Any] = self._prepare_for_class(inputs_dict.copy() , lowercase__ , return_labels=lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = model(lowercase__ )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss with a tuple SCREAMING_SNAKE_CASE_ : Optional[Any] = self._prepare_for_class(inputs_dict.copy() , lowercase__ , return_labels=lowercase__ ) # Get keys that were added with the _prepare_for_class function SCREAMING_SNAKE_CASE_ : int = prepared_for_class.keys() - inputs_dict.keys() SCREAMING_SNAKE_CASE_ : Optional[int] = inspect.signature(model.call ).parameters SCREAMING_SNAKE_CASE_ : Tuple = list(signature.keys() ) # Create a dictionary holding the location of the tensors in the tuple SCREAMING_SNAKE_CASE_ : List[Any] = {0: "input_ids"} for label_key in label_keys: SCREAMING_SNAKE_CASE_ : Optional[int] = signature_names.index(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = label_key SCREAMING_SNAKE_CASE_ : List[str] = sorted(tuple_index_mapping.items() ) # Initialize a list with their default values, update the values and convert to a tuple SCREAMING_SNAKE_CASE_ : List[str] = [] for name in signature_names: if name != "kwargs": list_input.append(signature[name].default ) for index, value in sorted_tuple_index_mapping: SCREAMING_SNAKE_CASE_ : List[str] = prepared_for_class[value] SCREAMING_SNAKE_CASE_ : List[Any] = tuple(lowercase__ ) # Send to model SCREAMING_SNAKE_CASE_ : int = model(tuple_input[:-1] )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) def __lowerCamelCase ( self ): """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_ ), ) : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) def __lowerCamelCase ( self ): """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_ ), ) : Optional[Any] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE_ : List[str] = type self.model_tester.create_and_check_model(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) def __lowerCamelCase ( self ): """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_ ), ) : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) def __lowerCamelCase ( self ): """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_ ), ) : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) def __lowerCamelCase ( self ): """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_ ), ) : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) @slow def __lowerCamelCase ( self ): """simple docstring""" for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE_ : Union[str, Any] = TFLayoutLMvaModel.from_pretrained(lowercase__ ) self.assertIsNotNone(lowercase__ ) def __lowerCamelCase ( ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : str = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_tf class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): @cached_property def __lowerCamelCase ( self ): """simple docstring""" return LayoutLMvaImageProcessor(apply_ocr=lowercase__ ) if is_vision_available() else None @slow def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = TFLayoutLMvaModel.from_pretrained("microsoft/layoutlmv3-base" ) SCREAMING_SNAKE_CASE_ : Any = self.default_image_processor SCREAMING_SNAKE_CASE_ : Optional[int] = prepare_img() SCREAMING_SNAKE_CASE_ : Optional[Any] = image_processor(images=lowercase__ , return_tensors="tf" ).pixel_values SCREAMING_SNAKE_CASE_ : Dict = tf.constant([[1, 2]] ) SCREAMING_SNAKE_CASE_ : Any = tf.expand_dims(tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]] ) , axis=0 ) # forward pass SCREAMING_SNAKE_CASE_ : List[Any] = model(input_ids=lowercase__ , bbox=lowercase__ , pixel_values=lowercase__ , training=lowercase__ ) # verify the logits SCREAMING_SNAKE_CASE_ : Tuple = (1, 199, 768) self.assertEqual(outputs.last_hidden_state.shape , lowercase__ ) SCREAMING_SNAKE_CASE_ : int = tf.constant( [[-0.0529, 0.3618, 0.1632], [-0.1587, -0.1667, -0.0400], [-0.1557, -0.1671, -0.0505]] ) self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3] , lowercase__ , atol=1e-4 ) )
68
1
'''simple docstring''' from statistics import mean, stdev def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : list , SCREAMING_SNAKE_CASE_ : int = 3 ) -> list: """simple docstring""" SCREAMING_SNAKE_CASE_ : str = min(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Optional[int] = max(SCREAMING_SNAKE_CASE_ ) # normalize data return [round((x - x_min) / (x_max - x_min) , SCREAMING_SNAKE_CASE_ ) for x in data] def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : list , SCREAMING_SNAKE_CASE_ : int = 3 ) -> list: """simple docstring""" SCREAMING_SNAKE_CASE_ : int = mean(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : int = stdev(SCREAMING_SNAKE_CASE_ ) # standardize data return [round((x - mu) / (sigma) , SCREAMING_SNAKE_CASE_ ) for x in data]
68
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Tuple ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = [1] for i in range(2 , SCREAMING_SNAKE_CASE_ ): factorials.append(factorials[-1] * i ) assert 0 <= k < factorials[-1] * n, "k out of bounds" SCREAMING_SNAKE_CASE_ : Union[str, Any] = [] SCREAMING_SNAKE_CASE_ : Dict = list(range(SCREAMING_SNAKE_CASE_ ) ) # Find permutation while factorials: SCREAMING_SNAKE_CASE_ : Any = factorials.pop() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[int] = divmod(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) permutation.append(elements[number] ) elements.remove(elements[number] ) permutation.append(elements[0] ) return permutation if __name__ == "__main__": import doctest doctest.testmod()
68
1
'''simple docstring''' import numpy as np import qiskit def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int = 8 , SCREAMING_SNAKE_CASE_ : int | None = None ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE_ : str = np.random.default_rng(seed=SCREAMING_SNAKE_CASE_ ) # Roughly 25% of the qubits will contribute to the key. # So we take more than we need. SCREAMING_SNAKE_CASE_ : int = 6 * key_len # Measurement basis for Alice's qubits. SCREAMING_SNAKE_CASE_ : Optional[Any] = rng.integers(2 , size=SCREAMING_SNAKE_CASE_ ) # The set of states Alice will prepare. SCREAMING_SNAKE_CASE_ : Optional[int] = rng.integers(2 , size=SCREAMING_SNAKE_CASE_ ) # Measurement basis for Bob's qubits. SCREAMING_SNAKE_CASE_ : Union[str, Any] = rng.integers(2 , size=SCREAMING_SNAKE_CASE_ ) # Quantum Circuit to simulate BB84 SCREAMING_SNAKE_CASE_ : int = qiskit.QuantumCircuit(SCREAMING_SNAKE_CASE_ , name="BB84" ) # Alice prepares her qubits according to rules above. for index, _ in enumerate(SCREAMING_SNAKE_CASE_ ): if alice_state[index] == 1: bbaa_circ.x(SCREAMING_SNAKE_CASE_ ) if alice_basis[index] == 1: bbaa_circ.h(SCREAMING_SNAKE_CASE_ ) bbaa_circ.barrier() # Bob measures the received qubits according to rules above. for index, _ in enumerate(SCREAMING_SNAKE_CASE_ ): if bob_basis[index] == 1: bbaa_circ.h(SCREAMING_SNAKE_CASE_ ) bbaa_circ.barrier() bbaa_circ.measure_all() # Simulate the quantum circuit. SCREAMING_SNAKE_CASE_ : List[str] = qiskit.Aer.get_backend("aer_simulator" ) # We only need to run one shot because the key is unique. # Multiple shots will produce the same key. SCREAMING_SNAKE_CASE_ : Union[str, Any] = qiskit.execute(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , shots=1 , seed_simulator=SCREAMING_SNAKE_CASE_ ) # Returns the result of measurement. SCREAMING_SNAKE_CASE_ : int = job.result().get_counts(SCREAMING_SNAKE_CASE_ ).most_frequent() # Extracting the generated key from the simulation results. # Only keep measurement results where Alice and Bob chose the same basis. SCREAMING_SNAKE_CASE_ : Optional[Any] = "".join( [ result_bit for alice_basis_bit, bob_basis_bit, result_bit in zip( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if alice_basis_bit == bob_basis_bit ] ) # Get final key. Pad with 0 if too short, otherwise truncate. SCREAMING_SNAKE_CASE_ : Tuple = gen_key[:key_len] if len(SCREAMING_SNAKE_CASE_ ) >= key_len else gen_key.ljust(SCREAMING_SNAKE_CASE_ , "0" ) return key if __name__ == "__main__": print(F'''The generated key is : {bbaa(8, seed=0)}''') from doctest import testmod testmod()
68
'''simple docstring''' import argparse from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_controlnet_from_original_ckpt if __name__ == "__main__": snake_case_ = argparse.ArgumentParser() parser.add_argument( '--checkpoint_path', default=None, type=str, required=True, help='Path to the checkpoint to convert.' ) parser.add_argument( '--original_config_file', type=str, required=True, help='The YAML config file corresponding to the original architecture.', ) parser.add_argument( '--num_in_channels', default=None, type=int, help='The number of input channels. If `None` number of input channels will be automatically inferred.', ) parser.add_argument( '--image_size', default=5_1_2, type=int, help=( 'The image size that the model was trained on. Use 512 for Stable Diffusion v1.X and Stable Siffusion v2' ' Base. Use 768 for Stable Diffusion v2.' ), ) parser.add_argument( '--extract_ema', action='store_true', help=( 'Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights' ' or not. Defaults to `False`. Add `--extract_ema` to extract the EMA weights. EMA weights usually yield' ' higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning.' ), ) parser.add_argument( '--upcast_attention', action='store_true', help=( 'Whether the attention computation should always be upcasted. This is necessary when running stable' ' diffusion 2.1.' ), ) parser.add_argument( '--from_safetensors', action='store_true', help='If `--checkpoint_path` is in `safetensors` format, load checkpoint with safetensors instead of PyTorch.', ) parser.add_argument( '--to_safetensors', action='store_true', help='Whether to store pipeline in safetensors format or not.', ) parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.') parser.add_argument('--device', type=str, help='Device to use (e.g. cpu, cuda:0, cuda:1, etc.)') def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Optional[int] ) -> Dict: """simple docstring""" if string == "True": return True elif string == "False": return False else: raise ValueError(F"could not parse string as bool {string}" ) parser.add_argument( '--use_linear_projection', help='Override for use linear projection', required=False, type=parse_bool ) parser.add_argument('--cross_attention_dim', help='Override for cross attention_dim', required=False, type=int) snake_case_ = parser.parse_args() snake_case_ = download_controlnet_from_original_ckpt( checkpoint_path=args.checkpoint_path, original_config_file=args.original_config_file, image_size=args.image_size, extract_ema=args.extract_ema, num_in_channels=args.num_in_channels, upcast_attention=args.upcast_attention, from_safetensors=args.from_safetensors, device=args.device, use_linear_projection=args.use_linear_projection, cross_attention_dim=args.cross_attention_dim, ) controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
68
1
'''simple docstring''' from json import JSONDecodeError # Workaround for requests.exceptions.JSONDecodeError import requests def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str = "isbn/0140328726" ) -> dict: """simple docstring""" SCREAMING_SNAKE_CASE_ : int = olid.strip().strip("/" ) # Remove leading/trailing whitespace & slashes if new_olid.count("/" ) != 1: SCREAMING_SNAKE_CASE_ : Union[str, Any] = F"{olid} is not a valid Open Library olid" raise ValueError(SCREAMING_SNAKE_CASE_ ) return requests.get(F"https://openlibrary.org/{new_olid}.json" ).json() def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : dict ) -> dict: """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = { "title": "Title", "publish_date": "Publish date", "authors": "Authors", "number_of_pages": "Number of pages:", "first_sentence": "First sentence", "isbn_10": "ISBN (10)", "isbn_13": "ISBN (13)", } SCREAMING_SNAKE_CASE_ : int = {better_key: ol_book_data[key] for key, better_key in desired_keys.items()} SCREAMING_SNAKE_CASE_ : Optional[int] = [ get_openlibrary_data(author["key"] )["name"] for author in data["Authors"] ] SCREAMING_SNAKE_CASE_ : List[str] = data["First sentence"]["value"] for key, value in data.items(): if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ : List[str] = ", ".join(SCREAMING_SNAKE_CASE_ ) return data if __name__ == "__main__": import doctest doctest.testmod() while True: snake_case_ = input('\nEnter the ISBN code to search (or \'quit\' to stop): ').strip() if isbn.lower() in ("", "q", "quit", "exit", "stop"): break if len(isbn) not in (1_0, 1_3) or not isbn.isdigit(): print(F'''Sorry, {isbn} is not a valid ISBN. Please, input a valid ISBN.''') continue print(F'''\nSearching Open Library for ISBN: {isbn}...\n''') try: snake_case_ = summarize_book(get_openlibrary_data(F'''isbn/{isbn}''')) print('\n'.join(F'''{key}: {value}''' for key, value in book_summary.items())) except JSONDecodeError: # Workaround for requests.exceptions.RequestException: print(F'''Sorry, there are no results for ISBN: {isbn}.''')
68
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging snake_case_ = logging.get_logger(__name__) snake_case_ = { 'camembert-base': 'https://huggingface.co/camembert-base/resolve/main/config.json', 'umberto-commoncrawl-cased-v1': ( 'https://huggingface.co/Musixmatch/umberto-commoncrawl-cased-v1/resolve/main/config.json' ), 'umberto-wikipedia-uncased-v1': ( 'https://huggingface.co/Musixmatch/umberto-wikipedia-uncased-v1/resolve/main/config.json' ), } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = "camembert" def __init__( self , lowercase__=3_0522 , lowercase__=768 , lowercase__=12 , lowercase__=12 , lowercase__=3072 , lowercase__="gelu" , lowercase__=0.1 , lowercase__=0.1 , lowercase__=512 , lowercase__=2 , lowercase__=0.02 , lowercase__=1e-12 , lowercase__=1 , lowercase__=0 , lowercase__=2 , lowercase__="absolute" , lowercase__=True , lowercase__=None , **lowercase__ , ): """simple docstring""" super().__init__(pad_token_id=lowercase__ , bos_token_id=lowercase__ , eos_token_id=lowercase__ , **lowercase__ ) SCREAMING_SNAKE_CASE_ : Tuple = vocab_size SCREAMING_SNAKE_CASE_ : str = hidden_size SCREAMING_SNAKE_CASE_ : str = num_hidden_layers SCREAMING_SNAKE_CASE_ : Dict = num_attention_heads SCREAMING_SNAKE_CASE_ : Any = hidden_act SCREAMING_SNAKE_CASE_ : Optional[int] = intermediate_size SCREAMING_SNAKE_CASE_ : Optional[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : List[str] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : Optional[Any] = max_position_embeddings SCREAMING_SNAKE_CASE_ : List[str] = type_vocab_size SCREAMING_SNAKE_CASE_ : Tuple = initializer_range SCREAMING_SNAKE_CASE_ : List[Any] = layer_norm_eps SCREAMING_SNAKE_CASE_ : List[Any] = position_embedding_type SCREAMING_SNAKE_CASE_ : Any = use_cache SCREAMING_SNAKE_CASE_ : Optional[int] = classifier_dropout class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): @property def __lowerCamelCase ( self ): """simple docstring""" if self.task == "multiple-choice": SCREAMING_SNAKE_CASE_ : Optional[int] = {0: "batch", 1: "choice", 2: "sequence"} else: SCREAMING_SNAKE_CASE_ : Any = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
68
1
'''simple docstring''' import pytest import requests from datasets.utils.file_utils import http_head from .utils import OfflineSimulationMode, RequestWouldHangIndefinitelyError, offline @pytest.mark.integration def __lowerCamelCase ( ) -> List[str]: """simple docstring""" with offline(OfflineSimulationMode.CONNECTION_TIMES_OUT ): with pytest.raises(SCREAMING_SNAKE_CASE_ ): requests.request("GET" , "https://huggingface.co" ) with pytest.raises(requests.exceptions.ConnectTimeout ): requests.request("GET" , "https://huggingface.co" , timeout=1.0 ) @pytest.mark.integration def __lowerCamelCase ( ) -> Dict: """simple docstring""" with offline(OfflineSimulationMode.CONNECTION_FAILS ): with pytest.raises(requests.exceptions.ConnectionError ): requests.request("GET" , "https://huggingface.co" ) def __lowerCamelCase ( ) -> Any: """simple docstring""" with offline(OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1 ): with pytest.raises(SCREAMING_SNAKE_CASE_ ): http_head("https://huggingface.co" )
68
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : list[int] ) -> list[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = len(SCREAMING_SNAKE_CASE_ ) for i in range(SCREAMING_SNAKE_CASE_ ): for j in range(i + 1 , SCREAMING_SNAKE_CASE_ ): if numbers[j] < numbers[i]: SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Tuple = numbers[j], numbers[i] return numbers if __name__ == "__main__": snake_case_ = input('Enter numbers separated by a comma:\n').strip() snake_case_ = [int(item) for item in user_input.split(',')] print(exchange_sort(unsorted))
68
1
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Tuple ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = [1] for i in range(2 , SCREAMING_SNAKE_CASE_ ): factorials.append(factorials[-1] * i ) assert 0 <= k < factorials[-1] * n, "k out of bounds" SCREAMING_SNAKE_CASE_ : Union[str, Any] = [] SCREAMING_SNAKE_CASE_ : Dict = list(range(SCREAMING_SNAKE_CASE_ ) ) # Find permutation while factorials: SCREAMING_SNAKE_CASE_ : Any = factorials.pop() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[int] = divmod(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) permutation.append(elements[number] ) elements.remove(elements[number] ) permutation.append(elements[0] ) return permutation if __name__ == "__main__": import doctest doctest.testmod()
68
'''simple docstring''' import logging import os import sys from pathlib import Path from unittest.mock import patch from parameterized import parameterized from run_eval import run_generate from run_eval_search import run_search from transformers.testing_utils import CaptureStdout, TestCasePlus, slow from utils import ROUGE_KEYS logging.basicConfig(level=logging.DEBUG) snake_case_ = logging.getLogger() def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Path , SCREAMING_SNAKE_CASE_ : list ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = "\n".join(SCREAMING_SNAKE_CASE_ ) Path(SCREAMING_SNAKE_CASE_ ).open("w" ).writelines(SCREAMING_SNAKE_CASE_ ) snake_case_ = 'patrickvonplaten/t5-tiny-random' snake_case_ = 'sshleifer/bart-tiny-random' snake_case_ = 'sshleifer/tiny-mbart' snake_case_ = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) logging.disable(logging.CRITICAL) # remove noisy download output from tracebacks class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = Path(self.get_auto_remove_tmp_dir() ) / "utest_input.source" SCREAMING_SNAKE_CASE_ : List[str] = input_file_name.parent / "utest_output.txt" assert not output_file_name.exists() SCREAMING_SNAKE_CASE_ : Dict = [" New York (CNN)When Liana Barrientos was 23 years old, she got married in Westchester County."] _dump_articles(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : Tuple = str(Path(self.get_auto_remove_tmp_dir() ) / "scores.json" ) SCREAMING_SNAKE_CASE_ : Tuple = "translation_en_to_de" if model == T5_TINY else "summarization" SCREAMING_SNAKE_CASE_ : Dict = F"\n run_eval_search.py\n {model}\n {input_file_name}\n {output_file_name}\n --score_path {score_path}\n --task {task}\n --num_beams 2\n --length_penalty 2.0\n ".split() with patch.object(lowercase__ , "argv" , lowercase__ ): run_generate() assert Path(lowercase__ ).exists() # os.remove(Path(output_file_name)) def __lowerCamelCase ( self ): """simple docstring""" self.run_eval_tester(lowercase__ ) @parameterized.expand([BART_TINY, MBART_TINY] ) @slow def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" self.run_eval_tester(lowercase__ ) @parameterized.expand([T5_TINY, MBART_TINY] ) @slow def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = Path(self.get_auto_remove_tmp_dir() ) / "utest_input.source" SCREAMING_SNAKE_CASE_ : Optional[Any] = input_file_name.parent / "utest_output.txt" assert not output_file_name.exists() SCREAMING_SNAKE_CASE_ : List[Any] = { "en": ["Machine learning is great, isn't it?", "I like to eat bananas", "Tomorrow is another great day!"], "de": [ "Maschinelles Lernen ist großartig, oder?", "Ich esse gerne Bananen", "Morgen ist wieder ein toller Tag!", ], } SCREAMING_SNAKE_CASE_ : Dict = Path(self.get_auto_remove_tmp_dir() ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = str(tmp_dir / "scores.json" ) SCREAMING_SNAKE_CASE_ : List[Any] = str(tmp_dir / "val.target" ) _dump_articles(lowercase__ , text["en"] ) _dump_articles(lowercase__ , text["de"] ) SCREAMING_SNAKE_CASE_ : List[Any] = "translation_en_to_de" if model == T5_TINY else "summarization" SCREAMING_SNAKE_CASE_ : List[str] = F"\n run_eval_search.py\n {model}\n {str(lowercase__ )}\n {str(lowercase__ )}\n --score_path {score_path}\n --reference_path {reference_path}\n --task {task}\n ".split() testargs.extend(["--search", "num_beams=1:2 length_penalty=0.9:1.0"] ) with patch.object(lowercase__ , "argv" , lowercase__ ): with CaptureStdout() as cs: run_search() SCREAMING_SNAKE_CASE_ : Union[str, Any] = [" num_beams | length_penalty", model, "Best score args"] SCREAMING_SNAKE_CASE_ : Optional[Any] = ["Info"] if "translation" in task: expected_strings.append("bleu" ) else: expected_strings.extend(lowercase__ ) for w in expected_strings: assert w in cs.out for w in un_expected_strings: assert w not in cs.out assert Path(lowercase__ ).exists() os.remove(Path(lowercase__ ) )
68
1
'''simple docstring''' from ..utils import DummyObject, requires_backends class SCREAMING_SNAKE_CASE__ ( metaclass=_UpperCAmelCase ): _A = ["torch", "torchsde"] def __init__( self , *lowercase__ , **lowercase__ ): """simple docstring""" requires_backends(self , ["torch", "torchsde"] ) @classmethod def __lowerCamelCase ( cls , *lowercase__ , **lowercase__ ): """simple docstring""" requires_backends(cls , ["torch", "torchsde"] ) @classmethod def __lowerCamelCase ( cls , *lowercase__ , **lowercase__ ): """simple docstring""" requires_backends(cls , ["torch", "torchsde"] )
68
'''simple docstring''' from __future__ import annotations import numpy as np from numpy import floataa from numpy.typing import NDArray def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : NDArray[floataa] , SCREAMING_SNAKE_CASE_ : NDArray[floataa] , SCREAMING_SNAKE_CASE_ : list[int] , SCREAMING_SNAKE_CASE_ : int , ) -> list[float]: """simple docstring""" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : str = coefficient_matrix.shape SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : List[Any] = constant_matrix.shape if rowsa != colsa: SCREAMING_SNAKE_CASE_ : Union[str, Any] = F"Coefficient matrix dimensions must be nxn but received {rowsa}x{colsa}" raise ValueError(SCREAMING_SNAKE_CASE_ ) if colsa != 1: SCREAMING_SNAKE_CASE_ : List[Any] = F"Constant matrix must be nx1 but received {rowsa}x{colsa}" raise ValueError(SCREAMING_SNAKE_CASE_ ) if rowsa != rowsa: SCREAMING_SNAKE_CASE_ : Any = ( "Coefficient and constant matrices dimensions must be nxn and nx1 but " F"received {rowsa}x{colsa} and {rowsa}x{colsa}" ) raise ValueError(SCREAMING_SNAKE_CASE_ ) if len(SCREAMING_SNAKE_CASE_ ) != rowsa: SCREAMING_SNAKE_CASE_ : int = ( "Number of initial values must be equal to number of rows in coefficient " F"matrix but received {len(SCREAMING_SNAKE_CASE_ )} and {rowsa}" ) raise ValueError(SCREAMING_SNAKE_CASE_ ) if iterations <= 0: raise ValueError("Iterations must be at least 1" ) SCREAMING_SNAKE_CASE_ : NDArray[floataa] = np.concatenate( (coefficient_matrix, constant_matrix) , axis=1 ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Any = table.shape strictly_diagonally_dominant(SCREAMING_SNAKE_CASE_ ) # Iterates the whole matrix for given number of times for _ in range(SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ : Tuple = [] for row in range(SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ : Any = 0 for col in range(SCREAMING_SNAKE_CASE_ ): if col == row: SCREAMING_SNAKE_CASE_ : Any = table[row][col] elif col == cols - 1: SCREAMING_SNAKE_CASE_ : Dict = table[row][col] else: temp += (-1) * table[row][col] * init_val[col] SCREAMING_SNAKE_CASE_ : Optional[Any] = (temp + val) / denom new_val.append(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = new_val return [float(SCREAMING_SNAKE_CASE_ ) for i in new_val] def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : NDArray[floataa] ) -> bool: """simple docstring""" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = table.shape SCREAMING_SNAKE_CASE_ : Tuple = True for i in range(0 , SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ : int = 0 for j in range(0 , cols - 1 ): if i == j: continue else: total += table[i][j] if table[i][i] <= total: raise ValueError("Coefficient matrix is not strictly diagonally dominant" ) return is_diagonally_dominant # Test Cases if __name__ == "__main__": import doctest doctest.testmod()
68
1
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : int = len(SCREAMING_SNAKE_CASE_ ) for i in range(length - 1 ): SCREAMING_SNAKE_CASE_ : Any = i for k in range(i + 1 , SCREAMING_SNAKE_CASE_ ): if collection[k] < collection[least]: SCREAMING_SNAKE_CASE_ : Any = k if least != i: SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : List[Any] = (collection[i], collection[least]) return collection if __name__ == "__main__": snake_case_ = input('Enter numbers separated by a comma:\n').strip() snake_case_ = [int(item) for item in user_input.split(',')] print(selection_sort(unsorted))
68
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int ) -> int: """simple docstring""" return 1 if input_a == input_a else 0 def __lowerCamelCase ( ) -> None: """simple docstring""" assert xnor_gate(0 , 0 ) == 1 assert xnor_gate(0 , 1 ) == 0 assert xnor_gate(1 , 0 ) == 0 assert xnor_gate(1 , 1 ) == 1 if __name__ == "__main__": print(xnor_gate(0, 0)) print(xnor_gate(0, 1)) print(xnor_gate(1, 0)) print(xnor_gate(1, 1))
68
1
'''simple docstring''' from typing import List, Union import numpy as np from ..tokenization_utils import TruncationStrategy from ..utils import add_end_docstrings, logging from .base import PIPELINE_INIT_ARGS, ArgumentHandler, ChunkPipeline snake_case_ = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" if isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE_ : Union[str, Any] = [label.strip() for label in labels.split("," ) if label.strip()] return labels def __call__( self , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" if len(lowercase__ ) == 0 or len(lowercase__ ) == 0: raise ValueError("You must include at least one label and at least one sequence." ) if hypothesis_template.format(labels[0] ) == hypothesis_template: raise ValueError( ( "The provided hypothesis_template \"{}\" was not able to be formatted with the target labels. " "Make sure the passed template includes formatting syntax such as {{}} where the label should go." ).format(lowercase__ ) ) if isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE_ : Optional[int] = [sequences] SCREAMING_SNAKE_CASE_ : Optional[Any] = [] for sequence in sequences: sequence_pairs.extend([[sequence, hypothesis_template.format(lowercase__ )] for label in labels] ) return sequence_pairs, sequences @add_end_docstrings(_UpperCAmelCase ) class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): def __init__( self , lowercase__=ZeroShotClassificationArgumentHandler() , *lowercase__ , **lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = args_parser super().__init__(*lowercase__ , **lowercase__ ) if self.entailment_id == -1: logger.warning( "Failed to determine 'entailment' label id from the label2id mapping in the model config. Setting to " "-1. Define a descriptive label2id mapping in the model config to ensure correct outputs." ) @property def __lowerCamelCase ( self ): """simple docstring""" for label, ind in self.model.config.labelaid.items(): if label.lower().startswith("entail" ): return ind return -1 def __lowerCamelCase ( self , lowercase__ , lowercase__=True , lowercase__=True , lowercase__=TruncationStrategy.ONLY_FIRST , **lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = self.framework if self.tokenizer.pad_token is None: # Override for tokenizers not supporting padding logger.error( "Tokenizer was not supporting padding necessary for zero-shot, attempting to use " " `pad_token=eos_token`" ) SCREAMING_SNAKE_CASE_ : Optional[int] = self.tokenizer.eos_token try: SCREAMING_SNAKE_CASE_ : Optional[int] = self.tokenizer( lowercase__ , add_special_tokens=lowercase__ , return_tensors=lowercase__ , padding=lowercase__ , truncation=lowercase__ , ) except Exception as e: if "too short" in str(lowercase__ ): # tokenizers might yell that we want to truncate # to a value that is not even reached by the input. # In that case we don't want to truncate. # It seems there's not a really better way to catch that # exception. SCREAMING_SNAKE_CASE_ : Optional[Any] = self.tokenizer( lowercase__ , add_special_tokens=lowercase__ , return_tensors=lowercase__ , padding=lowercase__ , truncation=TruncationStrategy.DO_NOT_TRUNCATE , ) else: raise e return inputs def __lowerCamelCase ( self , **lowercase__ ): """simple docstring""" if kwargs.get("multi_class" , lowercase__ ) is not None: SCREAMING_SNAKE_CASE_ : Optional[int] = kwargs["multi_class"] logger.warning( "The `multi_class` argument has been deprecated and renamed to `multi_label`. " "`multi_class` will be removed in a future version of Transformers." ) SCREAMING_SNAKE_CASE_ : Optional[int] = {} if "candidate_labels" in kwargs: SCREAMING_SNAKE_CASE_ : Union[str, Any] = self._args_parser._parse_labels(kwargs["candidate_labels"] ) if "hypothesis_template" in kwargs: SCREAMING_SNAKE_CASE_ : int = kwargs["hypothesis_template"] SCREAMING_SNAKE_CASE_ : List[Any] = {} if "multi_label" in kwargs: SCREAMING_SNAKE_CASE_ : Tuple = kwargs["multi_label"] return preprocess_params, {}, postprocess_params def __call__( self , lowercase__ , *lowercase__ , **lowercase__ , ): """simple docstring""" if len(lowercase__ ) == 0: pass elif len(lowercase__ ) == 1 and "candidate_labels" not in kwargs: SCREAMING_SNAKE_CASE_ : Any = args[0] else: raise ValueError(F"Unable to understand extra arguments {args}" ) return super().__call__(lowercase__ , **lowercase__ ) def __lowerCamelCase ( self , lowercase__ , lowercase__=None , lowercase__="This example is {}." ): """simple docstring""" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : List[Any] = self._args_parser(lowercase__ , lowercase__ , lowercase__ ) for i, (candidate_label, sequence_pair) in enumerate(zip(lowercase__ , lowercase__ ) ): SCREAMING_SNAKE_CASE_ : Dict = self._parse_and_tokenize([sequence_pair] ) yield { "candidate_label": candidate_label, "sequence": sequences[0], "is_last": i == len(lowercase__ ) - 1, **model_input, } def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = inputs["candidate_label"] SCREAMING_SNAKE_CASE_ : Union[str, Any] = inputs["sequence"] SCREAMING_SNAKE_CASE_ : Any = {k: inputs[k] for k in self.tokenizer.model_input_names} SCREAMING_SNAKE_CASE_ : List[Any] = self.model(**lowercase__ ) SCREAMING_SNAKE_CASE_ : str = { "candidate_label": candidate_label, "sequence": sequence, "is_last": inputs["is_last"], **outputs, } return model_outputs def __lowerCamelCase ( self , lowercase__ , lowercase__=False ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = [outputs["candidate_label"] for outputs in model_outputs] SCREAMING_SNAKE_CASE_ : Tuple = [outputs["sequence"] for outputs in model_outputs] SCREAMING_SNAKE_CASE_ : Optional[Any] = np.concatenate([output["logits"].numpy() for output in model_outputs] ) SCREAMING_SNAKE_CASE_ : Any = logits.shape[0] SCREAMING_SNAKE_CASE_ : str = len(lowercase__ ) SCREAMING_SNAKE_CASE_ : str = N // n SCREAMING_SNAKE_CASE_ : List[str] = logits.reshape((num_sequences, n, -1) ) if multi_label or len(lowercase__ ) == 1: # softmax over the entailment vs. contradiction dim for each label independently SCREAMING_SNAKE_CASE_ : Optional[Any] = self.entailment_id SCREAMING_SNAKE_CASE_ : Optional[Any] = -1 if entailment_id == 0 else 0 SCREAMING_SNAKE_CASE_ : str = reshaped_outputs[..., [contradiction_id, entailment_id]] SCREAMING_SNAKE_CASE_ : Optional[int] = np.exp(lowercase__ ) / np.exp(lowercase__ ).sum(-1 , keepdims=lowercase__ ) SCREAMING_SNAKE_CASE_ : Tuple = scores[..., 1] else: # softmax the "entailment" logits over all candidate labels SCREAMING_SNAKE_CASE_ : List[Any] = reshaped_outputs[..., self.entailment_id] SCREAMING_SNAKE_CASE_ : List[Any] = np.exp(lowercase__ ) / np.exp(lowercase__ ).sum(-1 , keepdims=lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = list(reversed(scores[0].argsort() ) ) return { "sequence": sequences[0], "labels": [candidate_labels[i] for i in top_inds], "scores": scores[0, top_inds].tolist(), }
68
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , ) -> float: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = [redshift, radiation_density, matter_density, dark_energy] if any(p < 0 for p in parameters ): raise ValueError("All input parameters must be positive" ) if any(p > 1 for p in parameters[1:4] ): raise ValueError("Relative densities cannot be greater than one" ) else: SCREAMING_SNAKE_CASE_ : int = 1 - (matter_density + radiation_density + dark_energy) SCREAMING_SNAKE_CASE_ : List[Any] = ( radiation_density * (redshift + 1) ** 4 + matter_density * (redshift + 1) ** 3 + curvature * (redshift + 1) ** 2 + dark_energy ) SCREAMING_SNAKE_CASE_ : Dict = hubble_constant * e_a ** (1 / 2) return hubble if __name__ == "__main__": import doctest # run doctest doctest.testmod() # demo LCDM approximation snake_case_ = 0.3 print( hubble_parameter( hubble_constant=6_8.3, radiation_density=1E-4, matter_density=matter_density, dark_energy=1 - matter_density, redshift=0, ) )
68
1
'''simple docstring''' from __future__ import annotations import sys from collections import deque from typing import Generic, TypeVar snake_case_ = TypeVar('T') class SCREAMING_SNAKE_CASE__ ( Generic[T] ): _A = 42 # Cache store of keys _A = 42 # References of the keys in cache _A = 10 # Maximum capacity of cache def __init__( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = deque() SCREAMING_SNAKE_CASE_ : Any = set() if not n: SCREAMING_SNAKE_CASE_ : List[Any] = sys.maxsize elif n < 0: raise ValueError("n should be an integer greater than 0." ) else: SCREAMING_SNAKE_CASE_ : str = n def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" if x not in self.key_reference: if len(self.dq_store ) == LRUCache._MAX_CAPACITY: SCREAMING_SNAKE_CASE_ : Any = self.dq_store.pop() self.key_reference.remove(lowercase__ ) else: self.dq_store.remove(lowercase__ ) self.dq_store.appendleft(lowercase__ ) self.key_reference.add(lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" for k in self.dq_store: print(lowercase__ ) def __repr__( self ): """simple docstring""" return F"LRUCache({self._MAX_CAPACITY}) => {list(self.dq_store )}" if __name__ == "__main__": import doctest doctest.testmod() snake_case_ = LRUCache(4) lru_cache.refer('A') lru_cache.refer(2) lru_cache.refer(3) lru_cache.refer('A') lru_cache.refer(4) lru_cache.refer(5) lru_cache.display() print(lru_cache) assert str(lru_cache) == "LRUCache(4) => [5, 4, 'A', 3]"
68
'''simple docstring''' import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.generation import DisjunctiveConstraint @require_torch class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = [[1, 2, 4], [1, 2, 3, 4]] SCREAMING_SNAKE_CASE_ : Any = DisjunctiveConstraint(lowercase__ ) self.assertTrue(isinstance(dc.token_ids , lowercase__ ) ) with self.assertRaises(lowercase__ ): DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]] ) ) with self.assertRaises(lowercase__ ): DisjunctiveConstraint([torch.LongTensor([1, 2, 4] ), torch.LongTensor([1, 2, 3, 4, 5] )] ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = [[1, 2], [1, 2, 3, 4]] with self.assertRaises(lowercase__ ): DisjunctiveConstraint(lowercase__ ) # fails here def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = [[1, 2, 3], [1, 2, 4]] SCREAMING_SNAKE_CASE_ : Optional[Any] = DisjunctiveConstraint(lowercase__ ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = dc.update(1 ) SCREAMING_SNAKE_CASE_ : Optional[int] = stepped is True and completed is False and reset is False self.assertTrue(lowercase__ ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Tuple = dc.update(2 ) SCREAMING_SNAKE_CASE_ : Tuple = stepped is True and completed is False and reset is False self.assertTrue(lowercase__ ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Any = dc.update(3 ) SCREAMING_SNAKE_CASE_ : Tuple = stepped is True and completed is True and reset is False self.assertTrue(lowercase__ ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 3] ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]] SCREAMING_SNAKE_CASE_ : Dict = DisjunctiveConstraint(lowercase__ ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : List[Any] = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = dc.update(4 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2, 4] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : List[Any] = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 4, 5] ) dc.reset() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Tuple = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 3 ) self.assertTrue(dc.current_seq == [1] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : str = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 2 ) self.assertTrue(dc.current_seq == [1, 2] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : str = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.remaining() == 0 ) self.assertTrue(dc.current_seq == [1, 2, 5] )
68
1
'''simple docstring''' import os import re import unicodedata from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import is_torch_available, logging if is_torch_available(): import torch if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation snake_case_ = logging.get_logger(__name__) snake_case_ = {'vocab_file': 'spiece.model'} snake_case_ = { 'vocab_file': { 'AI-Sweden/gpt-sw3-126m': 'https://huggingface.co/AI-Sweden/gpt-sw3-126m/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-350m': 'https://huggingface.co/AI-Sweden/gpt-sw3-350m/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-1.6b': 'https://huggingface.co/AI-Sweden/gpt-sw3-1.6b/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-6.7b': 'https://huggingface.co/AI-Sweden/gpt-sw3-6.7b/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-20b': 'https://huggingface.co/AI-Sweden/gpt-sw3-20b/resolve/main/spiece.model', } } snake_case_ = { 'AI-Sweden/gpt-sw3-126m': 2_0_4_8, 'AI-Sweden/gpt-sw3-350m': 2_0_4_8, 'AI-Sweden/gpt-sw3-1.6b': 2_0_4_8, 'AI-Sweden/gpt-sw3-6.7b': 2_0_4_8, 'AI-Sweden/gpt-sw3-20b': 2_0_4_8, } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = VOCAB_FILES_NAMES _A = PRETRAINED_VOCAB_FILES_MAP _A = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _A = ["input_ids", "attention_mask"] def __init__( self , lowercase__ , lowercase__=False , lowercase__=False , lowercase__=False , lowercase__=None , lowercase__=None , lowercase__=None , lowercase__=None , lowercase__ = None , **lowercase__ , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = {} if sp_model_kwargs is None else sp_model_kwargs SCREAMING_SNAKE_CASE_ : Dict = kwargs.get("name_or_path" ) if name_or_path is None: logger.warning( "name_or_path not provided, will work for all GPTSw3 models except gpt-sw3-7b," " you are testing the model, this can safely be ignored" ) SCREAMING_SNAKE_CASE_ : str = "None" # Default definitions for our 2 tokenizer versions, with None-checks to enable proper testing SCREAMING_SNAKE_CASE_ : List[Any] = "<|endoftext|>" if eos_token is None else eos_token SCREAMING_SNAKE_CASE_ : Dict = "<unk>" if unk_token is None else unk_token if "gpt-sw3-7b" in name_or_path: SCREAMING_SNAKE_CASE_ : Tuple = unk_token if pad_token is None else pad_token SCREAMING_SNAKE_CASE_ : Optional[Any] = eos_token if bos_token is None else bos_token else: SCREAMING_SNAKE_CASE_ : int = "<pad>" if pad_token is None else pad_token SCREAMING_SNAKE_CASE_ : Any = "<s>" if bos_token is None else bos_token super().__init__( do_lower_case=lowercase__ , remove_space=lowercase__ , keep_accents=lowercase__ , bos_token=lowercase__ , eos_token=lowercase__ , unk_token=lowercase__ , pad_token=lowercase__ , sp_model_kwargs=self.sp_model_kwargs , **lowercase__ , ) SCREAMING_SNAKE_CASE_ : Optional[Any] = do_lower_case SCREAMING_SNAKE_CASE_ : Optional[int] = remove_space SCREAMING_SNAKE_CASE_ : int = keep_accents SCREAMING_SNAKE_CASE_ : List[Any] = vocab_file SCREAMING_SNAKE_CASE_ : List[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(lowercase__ ) # Used for whitespace normalization in input texts # fmt : off SCREAMING_SNAKE_CASE_ : int = {" ", " ", " ", " ", " ", " ", " ", " ", " ", " ", "", "„"} # fmt : on # Regular expression to remove non-printing characters (e.g. some unicode control chars) in preprocessing SCREAMING_SNAKE_CASE_ : List[str] = re.compile( F"[{''.join(map(lowercase__ , list(range(0 , 9 ) ) + list(range(11 , 32 ) ) + list(range(127 , 160 ) ) + [160, 173, 8203] ) )}]" ) def __getstate__( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = self.__dict__.copy() SCREAMING_SNAKE_CASE_ : Dict = None return state def __setstate__( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): SCREAMING_SNAKE_CASE_ : Union[str, Any] = {} SCREAMING_SNAKE_CASE_ : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) @property # Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.vocab_size def __lowerCamelCase ( self ): """simple docstring""" return len(self.sp_model ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.non_printing_characters_re.sub("" , lowercase__ ) # Normalize whitespaces SCREAMING_SNAKE_CASE_ : List[str] = "".join([char if char not in self.whitespaces else " " for char in text] ) # NFC Unicode normalization SCREAMING_SNAKE_CASE_ : List[Any] = unicodedata.normalize("NFC" , lowercase__ ) return text def __lowerCamelCase ( self , lowercase__ , **lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = self.preprocess_text(lowercase__ ) return self.sp_model.encode(lowercase__ , out_type=lowercase__ ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" return self.sp_model.PieceToId(lowercase__ ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" return self.sp_model.IdToPiece(lowercase__ ) @staticmethod def __lowerCamelCase ( lowercase__ ): """simple docstring""" return out_string def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = [] SCREAMING_SNAKE_CASE_ : Any = "" SCREAMING_SNAKE_CASE_ : Dict = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: # TODO: Check if this is needed, as it ensures that decode(encode(doc)) != doc by adding extra whitespace in the decoded document if not prev_is_special: out_string += " " out_string += self.sp_model.decode(lowercase__ ) + token SCREAMING_SNAKE_CASE_ : Union[str, Any] = True SCREAMING_SNAKE_CASE_ : int = [] else: current_sub_tokens.append(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = False out_string += self.sp_model.decode(lowercase__ ) return out_string def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = {self.convert_ids_to_tokens(lowercase__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __lowerCamelCase ( self , lowercase__ , lowercase__ = None ): """simple docstring""" if not os.path.isdir(lowercase__ ): logger.error(F"Vocabulary path ({save_directory}) should be a directory" ) return SCREAMING_SNAKE_CASE_ : Any = os.path.join( lowercase__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(lowercase__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , lowercase__ ) elif not os.path.isfile(self.vocab_file ): with open(lowercase__ , "wb" ) as fi: SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.sp_model.serialized_model_proto() fi.write(lowercase__ ) return (out_vocab_file,) def __lowerCamelCase ( self , lowercase__ , lowercase__ = False ): """simple docstring""" if isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE_ : List[Any] = self.preprocess_text(lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = self.sp_model.encode(lowercase__ ) else: SCREAMING_SNAKE_CASE_ : str = [self.preprocess_text(lowercase__ ) for t in text] SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.sp_model.encode(lowercase__ ) if return_tensors is True or return_tensors == "pt": SCREAMING_SNAKE_CASE_ : str = torch.tensor(lowercase__ ) return token_ids def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" return self.sp_model.decode(lowercase__ ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = [F"User: {text}" if is_user else F"Bot: {text}" for is_user, text in conversation.iter_texts()] SCREAMING_SNAKE_CASE_ : List[str] = ( F"{self.eos_token}{self.bos_token}" + F"{self.bos_token}".join(lowercase__ ) + F"{self.bos_token}Bot:" ) return self.encode(text=lowercase__ )
68
'''simple docstring''' import unittest import torch from diffusers import VQModel from diffusers.utils import floats_tensor, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,_UpperCAmelCase,unittest.TestCase ): _A = VQModel _A = "sample" @property def __lowerCamelCase ( self , lowercase__=(32, 32) ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = 4 SCREAMING_SNAKE_CASE_ : str = 3 SCREAMING_SNAKE_CASE_ : str = floats_tensor((batch_size, num_channels) + sizes ).to(lowercase__ ) return {"sample": image} @property def __lowerCamelCase ( self ): """simple docstring""" return (3, 32, 32) @property def __lowerCamelCase ( self ): """simple docstring""" return (3, 32, 32) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = { "block_out_channels": [32, 64], "in_channels": 3, "out_channels": 3, "down_block_types": ["DownEncoderBlock2D", "DownEncoderBlock2D"], "up_block_types": ["UpDecoderBlock2D", "UpDecoderBlock2D"], "latent_channels": 3, } SCREAMING_SNAKE_CASE_ : int = self.dummy_input return init_dict, inputs_dict def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : int = VQModel.from_pretrained("fusing/vqgan-dummy" , output_loading_info=lowercase__ ) self.assertIsNotNone(lowercase__ ) self.assertEqual(len(loading_info["missing_keys"] ) , 0 ) model.to(lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = VQModel.from_pretrained("fusing/vqgan-dummy" ) model.to(lowercase__ ).eval() torch.manual_seed(0 ) if torch.cuda.is_available(): torch.cuda.manual_seed_all(0 ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.randn(1 , model.config.in_channels , model.config.sample_size , model.config.sample_size ) SCREAMING_SNAKE_CASE_ : str = image.to(lowercase__ ) with torch.no_grad(): SCREAMING_SNAKE_CASE_ : int = model(lowercase__ ).sample SCREAMING_SNAKE_CASE_ : Any = output[0, -1, -3:, -3:].flatten().cpu() # fmt: off SCREAMING_SNAKE_CASE_ : Optional[Any] = torch.tensor([-0.0153, -0.4044, -0.1880, -0.5161, -0.2418, -0.4072, -0.1612, -0.0633, -0.0143] ) # fmt: on self.assertTrue(torch.allclose(lowercase__ , lowercase__ , atol=1e-3 ) )
68
1
'''simple docstring''' import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing the experiment tracking capability, # and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To help focus on the differences in the code, building `DataLoaders` # was refactored into its own function. # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## snake_case_ = 1_6 snake_case_ = 3_2 def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Accelerator , SCREAMING_SNAKE_CASE_ : int = 1_6 ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = AutoTokenizer.from_pretrained("bert-base-cased" ) SCREAMING_SNAKE_CASE_ : List[str] = load_dataset("glue" , "mrpc" ) def tokenize_function(SCREAMING_SNAKE_CASE_ : Optional[int] ): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE_ : List[Any] = tokenizer(examples["sentence1"] , examples["sentence2"] , truncation=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): SCREAMING_SNAKE_CASE_ : Union[str, Any] = datasets.map( SCREAMING_SNAKE_CASE_ , batched=SCREAMING_SNAKE_CASE_ , remove_columns=["idx", "sentence1", "sentence2"] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library SCREAMING_SNAKE_CASE_ : Union[str, Any] = tokenized_datasets.rename_column("label" , "labels" ) def collate_fn(SCREAMING_SNAKE_CASE_ : List[str] ): # On TPU it's best to pad everything to the same length or training will be very slow. SCREAMING_SNAKE_CASE_ : List[str] = 1_2_8 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": SCREAMING_SNAKE_CASE_ : Tuple = 1_6 elif accelerator.mixed_precision != "no": SCREAMING_SNAKE_CASE_ : List[str] = 8 else: SCREAMING_SNAKE_CASE_ : Optional[Any] = None return tokenizer.pad( SCREAMING_SNAKE_CASE_ , padding="longest" , max_length=SCREAMING_SNAKE_CASE_ , pad_to_multiple_of=SCREAMING_SNAKE_CASE_ , return_tensors="pt" , ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE_ : Any = DataLoader( tokenized_datasets["train"] , shuffle=SCREAMING_SNAKE_CASE_ , collate_fn=SCREAMING_SNAKE_CASE_ , batch_size=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : List[str] = DataLoader( tokenized_datasets["validation"] , shuffle=SCREAMING_SNAKE_CASE_ , collate_fn=SCREAMING_SNAKE_CASE_ , batch_size=SCREAMING_SNAKE_CASE_ ) return train_dataloader, eval_dataloader # For testing only if os.environ.get('TESTING_MOCKED_DATALOADERS', None) == "1": from accelerate.test_utils.training import mocked_dataloaders snake_case_ = mocked_dataloaders # noqa: F811 def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : str ) -> str: """simple docstring""" if os.environ.get("TESTING_MOCKED_DATALOADERS" , SCREAMING_SNAKE_CASE_ ) == "1": SCREAMING_SNAKE_CASE_ : Optional[int] = 2 # Initialize Accelerator # New Code # # We pass in "all" to `log_with` to grab all available trackers in the environment # Note: If using a custom `Tracker` class, should be passed in here such as: # >>> log_with = ["all", MyCustomTrackerClassInstance()] if args.with_tracking: SCREAMING_SNAKE_CASE_ : int = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , log_with="all" , project_dir=args.project_dir ) else: SCREAMING_SNAKE_CASE_ : Tuple = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs SCREAMING_SNAKE_CASE_ : Optional[Any] = config["lr"] SCREAMING_SNAKE_CASE_ : Optional[Any] = int(config["num_epochs"] ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = int(config["seed"] ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = int(config["batch_size"] ) set_seed(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : int = get_dataloaders(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = evaluate.load("glue" , "mrpc" ) # If the batch size is too big we use gradient accumulation SCREAMING_SNAKE_CASE_ : str = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: SCREAMING_SNAKE_CASE_ : List[str] = batch_size // MAX_GPU_BATCH_SIZE SCREAMING_SNAKE_CASE_ : int = MAX_GPU_BATCH_SIZE # Instantiate the model (we build the model here so that the seed also control new weights initialization) SCREAMING_SNAKE_CASE_ : str = AutoModelForSequenceClassification.from_pretrained("bert-base-cased" , return_dict=SCREAMING_SNAKE_CASE_ ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). SCREAMING_SNAKE_CASE_ : Tuple = model.to(accelerator.device ) # Instantiate optimizer SCREAMING_SNAKE_CASE_ : Tuple = AdamW(params=model.parameters() , lr=SCREAMING_SNAKE_CASE_ ) # Instantiate scheduler SCREAMING_SNAKE_CASE_ : Any = get_linear_schedule_with_warmup( optimizer=SCREAMING_SNAKE_CASE_ , num_warmup_steps=1_0_0 , num_training_steps=(len(SCREAMING_SNAKE_CASE_ ) * num_epochs) // gradient_accumulation_steps , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : int = accelerator.prepare( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # New Code # # We need to initialize the trackers we use. Overall configurations can also be stored if args.with_tracking: SCREAMING_SNAKE_CASE_ : Optional[int] = os.path.split(SCREAMING_SNAKE_CASE_ )[-1].split("." )[0] accelerator.init_trackers(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Now we train the model for epoch in range(SCREAMING_SNAKE_CASE_ ): model.train() # New Code # # For our tracking example, we will log the total loss of each epoch if args.with_tracking: SCREAMING_SNAKE_CASE_ : Optional[int] = 0 for step, batch in enumerate(SCREAMING_SNAKE_CASE_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) SCREAMING_SNAKE_CASE_ : str = model(**SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Dict = outputs.loss # New Code # if args.with_tracking: total_loss += loss.detach().float() SCREAMING_SNAKE_CASE_ : Optional[Any] = loss / gradient_accumulation_steps accelerator.backward(SCREAMING_SNAKE_CASE_ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(SCREAMING_SNAKE_CASE_ ): # We could avoid this line since we set the accelerator with `device_placement=True` (the default). batch.to(accelerator.device ) with torch.no_grad(): SCREAMING_SNAKE_CASE_ : str = model(**SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Any = outputs.logits.argmax(dim=-1 ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[Any] = accelerator.gather_for_metrics((predictions, batch["labels"]) ) metric.add_batch( predictions=SCREAMING_SNAKE_CASE_ , references=SCREAMING_SNAKE_CASE_ , ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F"epoch {epoch}:" , SCREAMING_SNAKE_CASE_ ) # New Code # # To actually log, we call `Accelerator.log` # The values passed can be of `str`, `int`, `float` or `dict` of `str` to `float`/`int` if args.with_tracking: accelerator.log( { "accuracy": eval_metric["accuracy"], "f1": eval_metric["f1"], "train_loss": total_loss.item() / len(SCREAMING_SNAKE_CASE_ ), "epoch": epoch, } , step=SCREAMING_SNAKE_CASE_ , ) # New Code # # When a run is finished, you should call `accelerator.end_training()` # to close all of the open trackers if args.with_tracking: accelerator.end_training() def __lowerCamelCase ( ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : str = argparse.ArgumentParser(description="Simple example of training script." ) parser.add_argument( "--mixed_precision" , type=SCREAMING_SNAKE_CASE_ , default=SCREAMING_SNAKE_CASE_ , choices=["no", "fp16", "bf16", "fp8"] , help="Whether to use mixed precision. Choose" "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10." "and an Nvidia Ampere GPU." , ) parser.add_argument("--cpu" , action="store_true" , help="If passed, will train on the CPU." ) parser.add_argument( "--with_tracking" , action="store_true" , help="Whether to load in all available experiment trackers from the environment and use them for logging." , ) parser.add_argument( "--project_dir" , type=SCREAMING_SNAKE_CASE_ , default="logs" , help="Location on where to store experiment tracking logs` and relevent project information" , ) SCREAMING_SNAKE_CASE_ : List[str] = parser.parse_args() SCREAMING_SNAKE_CASE_ : Dict = {"lr": 2E-5, "num_epochs": 3, "seed": 4_2, "batch_size": 1_6} training_function(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": main()
68
'''simple docstring''' import os import unittest from huggingface_hub.utils import are_progress_bars_disabled import transformers.models.bart.tokenization_bart from transformers import logging from transformers.testing_utils import CaptureLogger, mockenv, mockenv_context from transformers.utils.logging import disable_progress_bar, enable_progress_bar class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = logging.get_logger() # the current default level is logging.WARNING SCREAMING_SNAKE_CASE_ : Optional[int] = logging.get_verbosity() logging.set_verbosity_error() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_warning() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_info() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_debug() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) # restore to the original level logging.set_verbosity(lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = logging.get_verbosity() SCREAMING_SNAKE_CASE_ : List[Any] = logging.get_logger("transformers.models.bart.tokenization_bart" ) SCREAMING_SNAKE_CASE_ : List[Any] = "Testing 1, 2, 3" # should be able to log warnings (if default settings weren't overridden by `pytest --log-level-all`) if level_origin <= logging.WARNING: with CaptureLogger(lowercase__ ) as cl: logger.warning(lowercase__ ) self.assertEqual(cl.out , msg + "\n" ) # this is setting the level for all of `transformers.*` loggers logging.set_verbosity_error() # should not be able to log warnings with CaptureLogger(lowercase__ ) as cl: logger.warning(lowercase__ ) self.assertEqual(cl.out , "" ) # should be able to log warnings again logging.set_verbosity_warning() with CaptureLogger(lowercase__ ) as cl: logger.warning(lowercase__ ) self.assertEqual(cl.out , msg + "\n" ) # restore to the original level logging.set_verbosity(lowercase__ ) @mockenv(TRANSFORMERS_VERBOSITY="error" ) def __lowerCamelCase ( self ): """simple docstring""" transformers.utils.logging._reset_library_root_logger() # this action activates the env var SCREAMING_SNAKE_CASE_ : Tuple = logging.get_logger("transformers.models.bart.tokenization_bart" ) SCREAMING_SNAKE_CASE_ : int = os.getenv("TRANSFORMERS_VERBOSITY" , lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = logging.log_levels[env_level_str] SCREAMING_SNAKE_CASE_ : str = logging.get_verbosity() self.assertEqual( lowercase__ , lowercase__ , F"TRANSFORMERS_VERBOSITY={env_level_str}/{env_level}, but internal verbosity is {current_level}" , ) # restore to the original level SCREAMING_SNAKE_CASE_ : Optional[int] = "" transformers.utils.logging._reset_library_root_logger() @mockenv(TRANSFORMERS_VERBOSITY="super-error" ) def __lowerCamelCase ( self ): """simple docstring""" transformers.utils.logging._reset_library_root_logger() SCREAMING_SNAKE_CASE_ : List[Any] = logging.logging.getLogger() with CaptureLogger(lowercase__ ) as cl: # this action activates the env var logging.get_logger("transformers.models.bart.tokenization_bart" ) self.assertIn("Unknown option TRANSFORMERS_VERBOSITY=super-error" , cl.out ) # no need to restore as nothing was changed def __lowerCamelCase ( self ): """simple docstring""" transformers.utils.logging._reset_library_root_logger() SCREAMING_SNAKE_CASE_ : str = logging.get_logger("transformers.models.bart.tokenization_bart" ) SCREAMING_SNAKE_CASE_ : List[Any] = "Testing 1, 2, 3" with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS="1" ): # nothing should be logged as env var disables this method with CaptureLogger(lowercase__ ) as cl: logger.warning_advice(lowercase__ ) self.assertEqual(cl.out , "" ) with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS="" ): # should log normally as TRANSFORMERS_NO_ADVISORY_WARNINGS is unset with CaptureLogger(lowercase__ ) as cl: logger.warning_advice(lowercase__ ) self.assertEqual(cl.out , msg + "\n" ) def __lowerCamelCase ( ) -> Optional[int]: """simple docstring""" disable_progress_bar() assert are_progress_bars_disabled() enable_progress_bar() assert not are_progress_bars_disabled()
68
1
'''simple docstring''' import unittest import numpy as np from transformers import RobertaConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): from transformers.models.roberta.modeling_flax_roberta import ( FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaModel, ) class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __init__( self , lowercase__ , lowercase__=13 , lowercase__=7 , lowercase__=True , lowercase__=True , lowercase__=True , lowercase__=True , lowercase__=99 , lowercase__=32 , lowercase__=5 , lowercase__=4 , lowercase__=37 , lowercase__="gelu" , lowercase__=0.1 , lowercase__=0.1 , lowercase__=512 , lowercase__=16 , lowercase__=2 , lowercase__=0.02 , lowercase__=4 , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = parent SCREAMING_SNAKE_CASE_ : Union[str, Any] = batch_size SCREAMING_SNAKE_CASE_ : List[str] = seq_length SCREAMING_SNAKE_CASE_ : List[str] = is_training SCREAMING_SNAKE_CASE_ : str = use_attention_mask SCREAMING_SNAKE_CASE_ : Dict = use_token_type_ids SCREAMING_SNAKE_CASE_ : int = use_labels SCREAMING_SNAKE_CASE_ : str = vocab_size SCREAMING_SNAKE_CASE_ : Any = hidden_size SCREAMING_SNAKE_CASE_ : int = num_hidden_layers SCREAMING_SNAKE_CASE_ : Tuple = num_attention_heads SCREAMING_SNAKE_CASE_ : str = intermediate_size SCREAMING_SNAKE_CASE_ : Union[str, Any] = hidden_act SCREAMING_SNAKE_CASE_ : Any = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : Tuple = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : Optional[int] = max_position_embeddings SCREAMING_SNAKE_CASE_ : int = type_vocab_size SCREAMING_SNAKE_CASE_ : Dict = type_sequence_label_size SCREAMING_SNAKE_CASE_ : List[Any] = initializer_range SCREAMING_SNAKE_CASE_ : List[str] = num_choices def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE_ : Dict = None if self.use_attention_mask: SCREAMING_SNAKE_CASE_ : Tuple = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE_ : List[str] = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE_ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE_ : List[str] = RobertaConfig( 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=lowercase__ , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : List[Any] = config_and_inputs SCREAMING_SNAKE_CASE_ : Any = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": attention_mask} return config, inputs_dict def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : List[str] = config_and_inputs SCREAMING_SNAKE_CASE_ : str = True SCREAMING_SNAKE_CASE_ : List[str] = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) SCREAMING_SNAKE_CASE_ : Dict = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, encoder_hidden_states, encoder_attention_mask, ) @require_flax class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,unittest.TestCase ): _A = True _A = ( ( FlaxRobertaModel, FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, ) if is_flax_available() else () ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = FlaxRobertaModelTester(self ) @slow def __lowerCamelCase ( self ): """simple docstring""" for model_class_name in self.all_model_classes: SCREAMING_SNAKE_CASE_ : List[str] = model_class_name.from_pretrained("roberta-base" , from_pt=lowercase__ ) SCREAMING_SNAKE_CASE_ : str = model(np.ones((1, 1) ) ) self.assertIsNotNone(lowercase__ )
68
'''simple docstring''' import json import os import tempfile from unittest.mock import patch import torch from torch.utils.data import DataLoader, TensorDataset from accelerate import DistributedType, infer_auto_device_map, init_empty_weights from accelerate.accelerator import Accelerator from accelerate.state import GradientState, PartialState from accelerate.test_utils import require_bnb, require_multi_gpu, slow from accelerate.test_utils.testing import AccelerateTestCase, require_cuda from accelerate.utils import patch_environment def __lowerCamelCase ( ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = torch.nn.Linear(2 , 4 ) SCREAMING_SNAKE_CASE_ : List[Any] = torch.optim.AdamW(model.parameters() , lr=1.0 ) SCREAMING_SNAKE_CASE_ : Any = torch.optim.lr_scheduler.OneCycleLR(SCREAMING_SNAKE_CASE_ , max_lr=0.01 , steps_per_epoch=2 , epochs=1 ) SCREAMING_SNAKE_CASE_ : Dict = DataLoader(TensorDataset(torch.tensor([1, 2, 3] ) ) ) SCREAMING_SNAKE_CASE_ : Tuple = DataLoader(TensorDataset(torch.tensor([4, 5, 6] ) ) ) return model, optimizer, scheduler, train_dl, valid_dl def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : List[str] ) -> Tuple: """simple docstring""" return (model.weight.abs().sum() + model.bias.abs().sum()).item() def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Any ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : str = torch.nn.Linear(*tuple(model.weight.T.shape ) ).state_dict() model.load_state_dict(SCREAMING_SNAKE_CASE_ ) class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): @require_cuda def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = Accelerator() assert PartialState._shared_state["_cpu"] is False assert PartialState._shared_state["device"].type == "cuda" with self.assertRaises(lowercase__ ): SCREAMING_SNAKE_CASE_ : List[Any] = Accelerator(cpu=lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = Accelerator() SCREAMING_SNAKE_CASE_ : Any = GradientState() assert state.num_steps == 1 SCREAMING_SNAKE_CASE_ : Union[str, Any] = 4 assert state.num_steps == 4 assert state.sync_gradients is True SCREAMING_SNAKE_CASE_ : Optional[int] = False assert state.sync_gradients is False GradientState._reset_state() def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[int] = create_components() ( ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ) : Optional[Any] = accelerator.prepare(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) self.assertTrue(prepared_model in accelerator._models ) self.assertTrue(prepared_optimizer in accelerator._optimizers ) self.assertTrue(prepared_scheduler in accelerator._schedulers ) self.assertTrue(prepared_train_dl in accelerator._dataloaders ) self.assertTrue(prepared_valid_dl in accelerator._dataloaders ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : str = create_components() accelerator.prepare(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) accelerator.free_memory() self.assertTrue(len(accelerator._models ) == 0 ) self.assertTrue(len(accelerator._optimizers ) == 0 ) self.assertTrue(len(accelerator._schedulers ) == 0 ) self.assertTrue(len(accelerator._dataloaders ) == 0 ) def __lowerCamelCase ( self ): """simple docstring""" PartialState._reset_state() # Mock torch.cuda.set_device to avoid an exception as the device doesn't exist def noop(*lowercase__ , **lowercase__ ): pass with patch("torch.cuda.set_device" , lowercase__ ), patch_environment(ACCELERATE_TORCH_DEVICE="cuda:64" ): SCREAMING_SNAKE_CASE_ : List[str] = Accelerator() self.assertEqual(str(accelerator.state.device ) , "cuda:64" ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = create_components() accelerator.prepare(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = get_signature(lowercase__ ) with tempfile.TemporaryDirectory() as tmpdirname: accelerator.save_state(lowercase__ ) # make sure random weights don't match load_random_weights(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) > 1e-3 ) # make sure loaded weights match accelerator.load_state(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) < 1e-3 ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[int] = create_components() accelerator.prepare(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = get_signature(lowercase__ ) # saving hook def save_config(lowercase__ , lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE_ : Optional[Any] = {"class_name": models[0].__class__.__name__} with open(os.path.join(lowercase__ , "data.json" ) , "w" ) as f: json.dump(lowercase__ , lowercase__ ) # loading hook def load_config(lowercase__ , lowercase__ ): with open(os.path.join(lowercase__ , "data.json" ) , "r" ) as f: SCREAMING_SNAKE_CASE_ : Any = json.load(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = config["class_name"] SCREAMING_SNAKE_CASE_ : Dict = accelerator.register_save_state_pre_hook(lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = accelerator.register_load_state_pre_hook(lowercase__ ) with tempfile.TemporaryDirectory() as tmpdirname: accelerator.save_state(lowercase__ ) # make sure random weights don't match with hooks load_random_weights(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) > 1e-3 ) # random class name to verify correct one is loaded SCREAMING_SNAKE_CASE_ : Union[str, Any] = "random" # make sure loaded weights match with hooks accelerator.load_state(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) < 1e-3 ) # mode.class_name is loaded from config self.assertTrue(model.class_name == model.__class__.__name__ ) # remove hooks save_hook.remove() load_hook.remove() with tempfile.TemporaryDirectory() as tmpdirname: accelerator.save_state(lowercase__ ) # make sure random weights don't match with hooks removed load_random_weights(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) > 1e-3 ) # random class name to verify correct one is loaded SCREAMING_SNAKE_CASE_ : Tuple = "random" # make sure loaded weights match with hooks removed accelerator.load_state(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) < 1e-3 ) # mode.class_name is NOT loaded from config self.assertTrue(model.class_name != model.__class__.__name__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Tuple = create_components() SCREAMING_SNAKE_CASE_ : Union[str, Any] = None # This should work SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[int] = accelerator.prepare( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) self.assertTrue(dummy_obj is None ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = create_components() SCREAMING_SNAKE_CASE_ : Union[str, Any] = [1, 2, 3] # This should work SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : int = accelerator.prepare( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Dummy object should have `_is_accelerate_prepared` set to `True`" , ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Model is missing `_is_accelerator_prepared` or is set to `False`" , ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Optimizer is missing `_is_accelerator_prepared` or is set to `False`" , ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Scheduler is missing `_is_accelerator_prepared` or is set to `False`" , ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Train Dataloader is missing `_is_accelerator_prepared` or is set to `False`" , ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Valid Dataloader is missing `_is_accelerator_prepared` or is set to `False`" , ) @slow @require_bnb def __lowerCamelCase ( self ): """simple docstring""" from transformers import AutoModelForCausalLM SCREAMING_SNAKE_CASE_ : Optional[int] = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , load_in_abit=lowercase__ , device_map={"": 0} , ) SCREAMING_SNAKE_CASE_ : Optional[int] = Accelerator() # This should work SCREAMING_SNAKE_CASE_ : List[Any] = accelerator.prepare(lowercase__ ) @slow @require_bnb def __lowerCamelCase ( self ): """simple docstring""" from transformers import AutoModelForCausalLM SCREAMING_SNAKE_CASE_ : Optional[Any] = Accelerator() with init_empty_weights(): SCREAMING_SNAKE_CASE_ : Tuple = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , ) model.tie_weights() SCREAMING_SNAKE_CASE_ : Optional[Any] = infer_auto_device_map(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = "cpu" SCREAMING_SNAKE_CASE_ : Tuple = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , device_map=lowercase__ , load_in_abit=lowercase__ , llm_inta_enable_fpaa_cpu_offload=lowercase__ ) # This should not work and get value error with self.assertRaises(lowercase__ ): SCREAMING_SNAKE_CASE_ : str = accelerator.prepare(lowercase__ ) @slow @require_bnb @require_multi_gpu def __lowerCamelCase ( self ): """simple docstring""" from transformers import AutoModelForCausalLM SCREAMING_SNAKE_CASE_ : str = {"distributed_type": DistributedType.MULTI_GPU} with init_empty_weights(): SCREAMING_SNAKE_CASE_ : Optional[int] = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , ) model.tie_weights() SCREAMING_SNAKE_CASE_ : str = infer_auto_device_map(lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = 1 SCREAMING_SNAKE_CASE_ : str = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , load_in_abit=lowercase__ , device_map=lowercase__ , ) SCREAMING_SNAKE_CASE_ : Any = Accelerator() # This should not work and get value error with self.assertRaises(lowercase__ ): SCREAMING_SNAKE_CASE_ : Tuple = accelerator.prepare(lowercase__ ) PartialState._reset_state() @slow @require_bnb @require_multi_gpu def __lowerCamelCase ( self ): """simple docstring""" from transformers import AutoModelForCausalLM with init_empty_weights(): SCREAMING_SNAKE_CASE_ : Optional[int] = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , ) SCREAMING_SNAKE_CASE_ : Optional[Any] = infer_auto_device_map(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = 1 SCREAMING_SNAKE_CASE_ : str = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , load_in_abit=lowercase__ , device_map=lowercase__ , ) SCREAMING_SNAKE_CASE_ : Any = Accelerator() # This should work SCREAMING_SNAKE_CASE_ : Optional[int] = accelerator.prepare(lowercase__ ) @require_cuda def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = torch.nn.Linear(10 , 10 ) SCREAMING_SNAKE_CASE_ : Optional[int] = torch.optim.SGD(model.parameters() , lr=0.01 ) SCREAMING_SNAKE_CASE_ : Tuple = Accelerator(cpu=lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = accelerator.prepare(lowercase__ )
68
1
'''simple docstring''' import re import string import numpy as np import datasets snake_case_ = '\nReturns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list.\n' snake_case_ = '\nArgs:\n predictions: List of predicted texts.\n references: List of reference texts.\n regexes_to_ignore: List, defaults to None. Regex expressions of characters to\n ignore when calculating the exact matches. Note: these regexes are removed\n from the input data before the changes based on the options below (e.g. ignore_case,\n ignore_punctuation, ignore_numbers) are applied.\n ignore_case: Boolean, defaults to False. If true, turns everything\n to lowercase so that capitalization differences are ignored.\n ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\n ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\nReturns:\n exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive.\nExamples:\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results["exact_match"], 1))\n 25.0\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results["exact_match"], 1))\n 50.0\n\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results["exact_match"], 1))\n 75.0\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True)\n >>> print(round(results["exact_match"], 1))\n 100.0\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["The cat sat on the mat.", "Theaters are great.", "It\'s like comparing oranges and apples."]\n >>> preds = ["The cat sat on the mat?", "Theaters are great.", "It\'s like comparing apples and oranges."]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results["exact_match"], 1))\n 33.3\n\n' snake_case_ = '\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION,_KWARGS_DESCRIPTION ) class SCREAMING_SNAKE_CASE__ ( datasets.Metric ): def __lowerCamelCase ( self ): """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Value("string" , id="sequence" ), "references": datasets.Value("string" , id="sequence" ), } ) , reference_urls=[] , ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__=None , lowercase__=False , lowercase__=False , lowercase__=False , ): """simple docstring""" if regexes_to_ignore is not None: for s in regexes_to_ignore: SCREAMING_SNAKE_CASE_ : Optional[Any] = np.array([re.sub(lowercase__ , "" , lowercase__ ) for x in predictions] ) SCREAMING_SNAKE_CASE_ : List[Any] = np.array([re.sub(lowercase__ , "" , lowercase__ ) for x in references] ) else: SCREAMING_SNAKE_CASE_ : int = np.asarray(lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = np.asarray(lowercase__ ) if ignore_case: SCREAMING_SNAKE_CASE_ : Dict = np.char.lower(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = np.char.lower(lowercase__ ) if ignore_punctuation: SCREAMING_SNAKE_CASE_ : Optional[int] = string.punctuation.maketrans("" , "" , string.punctuation ) SCREAMING_SNAKE_CASE_ : int = np.char.translate(lowercase__ , table=lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = np.char.translate(lowercase__ , table=lowercase__ ) if ignore_numbers: SCREAMING_SNAKE_CASE_ : Optional[int] = string.digits.maketrans("" , "" , string.digits ) SCREAMING_SNAKE_CASE_ : Dict = np.char.translate(lowercase__ , table=lowercase__ ) SCREAMING_SNAKE_CASE_ : int = np.char.translate(lowercase__ , table=lowercase__ ) SCREAMING_SNAKE_CASE_ : str = predictions == references return {"exact_match": np.mean(lowercase__ ) * 100}
68
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging snake_case_ = logging.get_logger(__name__) snake_case_ = { 'facebook/xmod-base': 'https://huggingface.co/facebook/xmod-base/resolve/main/config.json', 'facebook/xmod-large-prenorm': 'https://huggingface.co/facebook/xmod-large-prenorm/resolve/main/config.json', 'facebook/xmod-base-13-125k': 'https://huggingface.co/facebook/xmod-base-13-125k/resolve/main/config.json', 'facebook/xmod-base-30-125k': 'https://huggingface.co/facebook/xmod-base-30-125k/resolve/main/config.json', 'facebook/xmod-base-30-195k': 'https://huggingface.co/facebook/xmod-base-30-195k/resolve/main/config.json', 'facebook/xmod-base-60-125k': 'https://huggingface.co/facebook/xmod-base-60-125k/resolve/main/config.json', 'facebook/xmod-base-60-265k': 'https://huggingface.co/facebook/xmod-base-60-265k/resolve/main/config.json', 'facebook/xmod-base-75-125k': 'https://huggingface.co/facebook/xmod-base-75-125k/resolve/main/config.json', 'facebook/xmod-base-75-269k': 'https://huggingface.co/facebook/xmod-base-75-269k/resolve/main/config.json', } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = "xmod" def __init__( self , lowercase__=3_0522 , lowercase__=768 , lowercase__=12 , lowercase__=12 , lowercase__=3072 , lowercase__="gelu" , lowercase__=0.1 , lowercase__=0.1 , lowercase__=512 , lowercase__=2 , lowercase__=0.02 , lowercase__=1e-12 , lowercase__=1 , lowercase__=0 , lowercase__=2 , lowercase__="absolute" , lowercase__=True , lowercase__=None , lowercase__=False , lowercase__=2 , lowercase__=False , lowercase__=True , lowercase__=True , lowercase__=("en_XX",) , lowercase__=None , **lowercase__ , ): """simple docstring""" super().__init__(pad_token_id=lowercase__ , bos_token_id=lowercase__ , eos_token_id=lowercase__ , **lowercase__ ) SCREAMING_SNAKE_CASE_ : Tuple = vocab_size SCREAMING_SNAKE_CASE_ : Optional[Any] = hidden_size SCREAMING_SNAKE_CASE_ : Tuple = num_hidden_layers SCREAMING_SNAKE_CASE_ : Optional[int] = num_attention_heads SCREAMING_SNAKE_CASE_ : List[str] = hidden_act SCREAMING_SNAKE_CASE_ : Optional[int] = intermediate_size SCREAMING_SNAKE_CASE_ : Tuple = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : int = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE_ : Dict = type_vocab_size SCREAMING_SNAKE_CASE_ : str = initializer_range SCREAMING_SNAKE_CASE_ : List[str] = layer_norm_eps SCREAMING_SNAKE_CASE_ : Tuple = position_embedding_type SCREAMING_SNAKE_CASE_ : str = use_cache SCREAMING_SNAKE_CASE_ : Optional[int] = classifier_dropout SCREAMING_SNAKE_CASE_ : int = pre_norm SCREAMING_SNAKE_CASE_ : Optional[int] = adapter_reduction_factor SCREAMING_SNAKE_CASE_ : List[str] = adapter_layer_norm SCREAMING_SNAKE_CASE_ : List[str] = adapter_reuse_layer_norm SCREAMING_SNAKE_CASE_ : int = ln_before_adapter SCREAMING_SNAKE_CASE_ : List[Any] = list(lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = default_language class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): @property def __lowerCamelCase ( self ): """simple docstring""" if self.task == "multiple-choice": SCREAMING_SNAKE_CASE_ : Tuple = {0: "batch", 1: "choice", 2: "sequence"} else: SCREAMING_SNAKE_CASE_ : Optional[int] = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
68
1
'''simple docstring''' import argparse from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_controlnet_from_original_ckpt if __name__ == "__main__": snake_case_ = argparse.ArgumentParser() parser.add_argument( '--checkpoint_path', default=None, type=str, required=True, help='Path to the checkpoint to convert.' ) parser.add_argument( '--original_config_file', type=str, required=True, help='The YAML config file corresponding to the original architecture.', ) parser.add_argument( '--num_in_channels', default=None, type=int, help='The number of input channels. If `None` number of input channels will be automatically inferred.', ) parser.add_argument( '--image_size', default=5_1_2, type=int, help=( 'The image size that the model was trained on. Use 512 for Stable Diffusion v1.X and Stable Siffusion v2' ' Base. Use 768 for Stable Diffusion v2.' ), ) parser.add_argument( '--extract_ema', action='store_true', help=( 'Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights' ' or not. Defaults to `False`. Add `--extract_ema` to extract the EMA weights. EMA weights usually yield' ' higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning.' ), ) parser.add_argument( '--upcast_attention', action='store_true', help=( 'Whether the attention computation should always be upcasted. This is necessary when running stable' ' diffusion 2.1.' ), ) parser.add_argument( '--from_safetensors', action='store_true', help='If `--checkpoint_path` is in `safetensors` format, load checkpoint with safetensors instead of PyTorch.', ) parser.add_argument( '--to_safetensors', action='store_true', help='Whether to store pipeline in safetensors format or not.', ) parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.') parser.add_argument('--device', type=str, help='Device to use (e.g. cpu, cuda:0, cuda:1, etc.)') def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Optional[int] ) -> Dict: """simple docstring""" if string == "True": return True elif string == "False": return False else: raise ValueError(F"could not parse string as bool {string}" ) parser.add_argument( '--use_linear_projection', help='Override for use linear projection', required=False, type=parse_bool ) parser.add_argument('--cross_attention_dim', help='Override for cross attention_dim', required=False, type=int) snake_case_ = parser.parse_args() snake_case_ = download_controlnet_from_original_ckpt( checkpoint_path=args.checkpoint_path, original_config_file=args.original_config_file, image_size=args.image_size, extract_ema=args.extract_ema, num_in_channels=args.num_in_channels, upcast_attention=args.upcast_attention, from_safetensors=args.from_safetensors, device=args.device, use_linear_projection=args.use_linear_projection, cross_attention_dim=args.cross_attention_dim, ) controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
68
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int ) -> int: """simple docstring""" return int((input_a, input_a).count(1 ) != 0 ) def __lowerCamelCase ( ) -> None: """simple docstring""" assert or_gate(0 , 0 ) == 0 assert or_gate(0 , 1 ) == 1 assert or_gate(1 , 0 ) == 1 assert or_gate(1 , 1 ) == 1 if __name__ == "__main__": print(or_gate(0, 1)) print(or_gate(1, 0)) print(or_gate(0, 0)) print(or_gate(1, 1))
68
1
'''simple docstring''' from ....configuration_utils import PretrainedConfig from ....utils import logging snake_case_ = logging.get_logger(__name__) # TODO: upload to AWS snake_case_ = { 'yjernite/retribert-base-uncased': ( 'https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/config.json' ), } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = "retribert" def __init__( self , lowercase__=3_0522 , lowercase__=768 , lowercase__=8 , lowercase__=12 , lowercase__=3072 , lowercase__="gelu" , lowercase__=0.1 , lowercase__=0.1 , lowercase__=512 , lowercase__=2 , lowercase__=0.02 , lowercase__=1e-12 , lowercase__=True , lowercase__=128 , lowercase__=0 , **lowercase__ , ): """simple docstring""" super().__init__(pad_token_id=lowercase__ , **lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = vocab_size SCREAMING_SNAKE_CASE_ : List[Any] = hidden_size SCREAMING_SNAKE_CASE_ : Dict = num_hidden_layers SCREAMING_SNAKE_CASE_ : Union[str, Any] = num_attention_heads SCREAMING_SNAKE_CASE_ : Optional[int] = hidden_act SCREAMING_SNAKE_CASE_ : Optional[int] = intermediate_size SCREAMING_SNAKE_CASE_ : str = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : int = max_position_embeddings SCREAMING_SNAKE_CASE_ : Any = type_vocab_size SCREAMING_SNAKE_CASE_ : List[str] = initializer_range SCREAMING_SNAKE_CASE_ : Tuple = layer_norm_eps SCREAMING_SNAKE_CASE_ : List[Any] = share_encoders SCREAMING_SNAKE_CASE_ : Union[str, Any] = projection_dim
68
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..bit import BitConfig snake_case_ = logging.get_logger(__name__) snake_case_ = { 'Intel/dpt-large': 'https://huggingface.co/Intel/dpt-large/resolve/main/config.json', # See all DPT models at https://huggingface.co/models?filter=dpt } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = "dpt" def __init__( self , lowercase__=768 , lowercase__=12 , lowercase__=12 , lowercase__=3072 , lowercase__="gelu" , lowercase__=0.0 , lowercase__=0.0 , lowercase__=0.02 , lowercase__=1e-12 , lowercase__=384 , lowercase__=16 , lowercase__=3 , lowercase__=False , lowercase__=True , lowercase__=[2, 5, 8, 11] , lowercase__="project" , lowercase__=[4, 2, 1, 0.5] , lowercase__=[96, 192, 384, 768] , lowercase__=256 , lowercase__=-1 , lowercase__=False , lowercase__=True , lowercase__=0.4 , lowercase__=255 , lowercase__=0.1 , lowercase__=[1, 1024, 24, 24] , lowercase__=[0, 1] , lowercase__=None , **lowercase__ , ): """simple docstring""" super().__init__(**lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = hidden_size SCREAMING_SNAKE_CASE_ : Union[str, Any] = is_hybrid if self.is_hybrid: if backbone_config is None: logger.info("Initializing the config with a `BiT` backbone." ) SCREAMING_SNAKE_CASE_ : Tuple = { "global_padding": "same", "layer_type": "bottleneck", "depths": [3, 4, 9], "out_features": ["stage1", "stage2", "stage3"], "embedding_dynamic_padding": True, } SCREAMING_SNAKE_CASE_ : Union[str, Any] = BitConfig(**lowercase__ ) elif isinstance(lowercase__ , lowercase__ ): logger.info("Initializing the config with a `BiT` backbone." ) SCREAMING_SNAKE_CASE_ : Dict = BitConfig(**lowercase__ ) elif isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE_ : Optional[int] = backbone_config else: raise ValueError( F"backbone_config must be a dictionary or a `PretrainedConfig`, got {backbone_config.__class__}." ) SCREAMING_SNAKE_CASE_ : List[Any] = backbone_featmap_shape SCREAMING_SNAKE_CASE_ : Union[str, Any] = neck_ignore_stages if readout_type != "project": raise ValueError("Readout type must be 'project' when using `DPT-hybrid` mode." ) else: SCREAMING_SNAKE_CASE_ : Optional[Any] = None SCREAMING_SNAKE_CASE_ : int = None SCREAMING_SNAKE_CASE_ : List[Any] = [] SCREAMING_SNAKE_CASE_ : int = num_hidden_layers SCREAMING_SNAKE_CASE_ : Union[str, Any] = num_attention_heads SCREAMING_SNAKE_CASE_ : Tuple = intermediate_size SCREAMING_SNAKE_CASE_ : Optional[int] = hidden_act SCREAMING_SNAKE_CASE_ : Dict = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : str = initializer_range SCREAMING_SNAKE_CASE_ : List[Any] = layer_norm_eps SCREAMING_SNAKE_CASE_ : Any = image_size SCREAMING_SNAKE_CASE_ : Union[str, Any] = patch_size SCREAMING_SNAKE_CASE_ : Union[str, Any] = num_channels SCREAMING_SNAKE_CASE_ : Union[str, Any] = qkv_bias SCREAMING_SNAKE_CASE_ : Optional[Any] = backbone_out_indices if readout_type not in ["ignore", "add", "project"]: raise ValueError("Readout_type must be one of ['ignore', 'add', 'project']" ) SCREAMING_SNAKE_CASE_ : Any = readout_type SCREAMING_SNAKE_CASE_ : Optional[Any] = reassemble_factors SCREAMING_SNAKE_CASE_ : str = neck_hidden_sizes SCREAMING_SNAKE_CASE_ : Union[str, Any] = fusion_hidden_size SCREAMING_SNAKE_CASE_ : Any = head_in_index SCREAMING_SNAKE_CASE_ : str = use_batch_norm_in_fusion_residual # auxiliary head attributes (semantic segmentation) SCREAMING_SNAKE_CASE_ : List[Any] = use_auxiliary_head SCREAMING_SNAKE_CASE_ : int = auxiliary_loss_weight SCREAMING_SNAKE_CASE_ : Union[str, Any] = semantic_loss_ignore_index SCREAMING_SNAKE_CASE_ : Any = semantic_classifier_dropout def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = copy.deepcopy(self.__dict__ ) if output["backbone_config"] is not None: SCREAMING_SNAKE_CASE_ : List[str] = self.backbone_config.to_dict() SCREAMING_SNAKE_CASE_ : Optional[int] = self.__class__.model_type return output
68
1
'''simple docstring''' import os import torch from ..logging import get_logger from .constants import FSDP_PYTORCH_VERSION, MODEL_NAME, OPTIMIZER_NAME from .versions import is_torch_version if is_torch_version('>=', FSDP_PYTORCH_VERSION): import torch.distributed.checkpoint as dist_cp from torch.distributed.checkpoint.default_planner import DefaultLoadPlanner, DefaultSavePlanner from torch.distributed.checkpoint.optimizer import load_sharded_optimizer_state_dict from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType snake_case_ = get_logger(__name__) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : Dict=0 ) -> Optional[int]: """simple docstring""" os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) with FSDP.state_dict_type( SCREAMING_SNAKE_CASE_ , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): SCREAMING_SNAKE_CASE_ : Optional[Any] = model.state_dict() if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: SCREAMING_SNAKE_CASE_ : List[Any] = F"{MODEL_NAME}.bin" if model_index == 0 else F"{MODEL_NAME}_{model_index}.bin" SCREAMING_SNAKE_CASE_ : Tuple = os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if accelerator.process_index == 0: logger.info(F"Saving model to {output_model_file}" ) torch.save(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F"Model saved to {output_model_file}" ) elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT: SCREAMING_SNAKE_CASE_ : Union[str, Any] = ( F"{MODEL_NAME}_rank{accelerator.process_index}.bin" if model_index == 0 else F"{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin" ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F"Saving model to {output_model_file}" ) torch.save(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F"Model saved to {output_model_file}" ) elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT: SCREAMING_SNAKE_CASE_ : Optional[int] = os.path.join(SCREAMING_SNAKE_CASE_ , F"{MODEL_NAME}_{model_index}" ) os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) logger.info(F"Saving model to {ckpt_dir}" ) SCREAMING_SNAKE_CASE_ : Optional[int] = {"model": state_dict} dist_cp.save_state_dict( state_dict=SCREAMING_SNAKE_CASE_ , storage_writer=dist_cp.FileSystemWriter(SCREAMING_SNAKE_CASE_ ) , planner=DefaultSavePlanner() , ) logger.info(F"Model saved to {ckpt_dir}" ) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : Tuple=0 ) -> Any: """simple docstring""" accelerator.wait_for_everyone() with FSDP.state_dict_type( SCREAMING_SNAKE_CASE_ , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: if type(SCREAMING_SNAKE_CASE_ ) != FSDP and accelerator.process_index != 0: if not fsdp_plugin.sync_module_states: raise ValueError( "Set the `sync_module_states` flag to `True` so that model states are synced across processes when " "initializing FSDP object" ) return SCREAMING_SNAKE_CASE_ : Optional[Any] = F"{MODEL_NAME}.bin" if model_index == 0 else F"{MODEL_NAME}_{model_index}.bin" SCREAMING_SNAKE_CASE_ : int = os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F"Loading model from {input_model_file}" ) SCREAMING_SNAKE_CASE_ : int = torch.load(SCREAMING_SNAKE_CASE_ ) logger.info(F"Model loaded from {input_model_file}" ) elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT: SCREAMING_SNAKE_CASE_ : List[Any] = ( F"{MODEL_NAME}_rank{accelerator.process_index}.bin" if model_index == 0 else F"{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin" ) SCREAMING_SNAKE_CASE_ : str = os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F"Loading model from {input_model_file}" ) SCREAMING_SNAKE_CASE_ : Optional[Any] = torch.load(SCREAMING_SNAKE_CASE_ ) logger.info(F"Model loaded from {input_model_file}" ) elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT: SCREAMING_SNAKE_CASE_ : Dict = ( os.path.join(SCREAMING_SNAKE_CASE_ , F"{MODEL_NAME}_{model_index}" ) if F"{MODEL_NAME}" not in input_dir else input_dir ) logger.info(F"Loading model from {ckpt_dir}" ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = {"model": model.state_dict()} dist_cp.load_state_dict( state_dict=SCREAMING_SNAKE_CASE_ , storage_reader=dist_cp.FileSystemReader(SCREAMING_SNAKE_CASE_ ) , planner=DefaultLoadPlanner() , ) SCREAMING_SNAKE_CASE_ : Dict = state_dict["model"] logger.info(F"Model loaded from {ckpt_dir}" ) model.load_state_dict(SCREAMING_SNAKE_CASE_ ) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Optional[int]=0 ) -> Tuple: """simple docstring""" os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) with FSDP.state_dict_type( SCREAMING_SNAKE_CASE_ , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): SCREAMING_SNAKE_CASE_ : List[Any] = FSDP.optim_state_dict(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: if accelerator.process_index == 0: SCREAMING_SNAKE_CASE_ : Union[str, Any] = ( F"{OPTIMIZER_NAME}.bin" if optimizer_index == 0 else F"{OPTIMIZER_NAME}_{optimizer_index}.bin" ) SCREAMING_SNAKE_CASE_ : Any = os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F"Saving Optimizer state to {output_optimizer_file}" ) torch.save(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F"Optimizer state saved in {output_optimizer_file}" ) else: SCREAMING_SNAKE_CASE_ : Any = os.path.join(SCREAMING_SNAKE_CASE_ , F"{OPTIMIZER_NAME}_{optimizer_index}" ) os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) logger.info(F"Saving Optimizer state to {ckpt_dir}" ) dist_cp.save_state_dict( state_dict={"optimizer": optim_state} , storage_writer=dist_cp.FileSystemWriter(SCREAMING_SNAKE_CASE_ ) , planner=DefaultSavePlanner() , ) logger.info(F"Optimizer state saved in {ckpt_dir}" ) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Optional[Any]=0 ) -> Tuple: """simple docstring""" accelerator.wait_for_everyone() with FSDP.state_dict_type( SCREAMING_SNAKE_CASE_ , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: SCREAMING_SNAKE_CASE_ : int = None # below check should work but currently it isn't working (mostly opytorch issue), # in the meantime disabling it at the cost of excess memory usage # if accelerator.process_index == 0 or not fsdp_plugin.optim_state_dict_config.rank0_only: SCREAMING_SNAKE_CASE_ : Tuple = ( F"{OPTIMIZER_NAME}.bin" if optimizer_index == 0 else F"{OPTIMIZER_NAME}_{optimizer_index}.bin" ) SCREAMING_SNAKE_CASE_ : Dict = os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F"Loading Optimizer state from {input_optimizer_file}" ) SCREAMING_SNAKE_CASE_ : Optional[Any] = torch.load(SCREAMING_SNAKE_CASE_ ) logger.info(F"Optimizer state loaded from {input_optimizer_file}" ) else: SCREAMING_SNAKE_CASE_ : Tuple = ( os.path.join(SCREAMING_SNAKE_CASE_ , F"{OPTIMIZER_NAME}_{optimizer_index}" ) if F"{OPTIMIZER_NAME}" not in input_dir else input_dir ) logger.info(F"Loading Optimizer from {ckpt_dir}" ) SCREAMING_SNAKE_CASE_ : Dict = load_sharded_optimizer_state_dict( model_state_dict=model.state_dict() , optimizer_key="optimizer" , storage_reader=dist_cp.FileSystemReader(SCREAMING_SNAKE_CASE_ ) , ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = optim_state["optimizer"] logger.info(F"Optimizer loaded from {ckpt_dir}" ) SCREAMING_SNAKE_CASE_ : int = FSDP.optim_state_dict_to_load(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) optimizer.load_state_dict(SCREAMING_SNAKE_CASE_ )
68
'''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 if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ChineseCLIPImageProcessor class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __init__( self , lowercase__ , lowercase__=7 , lowercase__=3 , lowercase__=18 , lowercase__=30 , lowercase__=400 , lowercase__=True , lowercase__=None , lowercase__=True , lowercase__=None , lowercase__=True , lowercase__=[0.48145466, 0.4578275, 0.40821073] , lowercase__=[0.26862954, 0.26130258, 0.27577711] , lowercase__=True , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = size if size is not None else {"height": 224, "width": 224} SCREAMING_SNAKE_CASE_ : Optional[Any] = crop_size if crop_size is not None else {"height": 18, "width": 18} SCREAMING_SNAKE_CASE_ : str = parent SCREAMING_SNAKE_CASE_ : List[Any] = batch_size SCREAMING_SNAKE_CASE_ : Dict = num_channels SCREAMING_SNAKE_CASE_ : Any = image_size SCREAMING_SNAKE_CASE_ : Tuple = min_resolution SCREAMING_SNAKE_CASE_ : Optional[Any] = max_resolution SCREAMING_SNAKE_CASE_ : Tuple = do_resize SCREAMING_SNAKE_CASE_ : List[str] = size SCREAMING_SNAKE_CASE_ : str = do_center_crop SCREAMING_SNAKE_CASE_ : List[str] = crop_size SCREAMING_SNAKE_CASE_ : int = do_normalize SCREAMING_SNAKE_CASE_ : Optional[int] = image_mean SCREAMING_SNAKE_CASE_ : Dict = image_std SCREAMING_SNAKE_CASE_ : List[Any] = do_convert_rgb def __lowerCamelCase ( self ): """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_convert_rgb": self.do_convert_rgb, } def __lowerCamelCase ( self , lowercase__=False , lowercase__=False , lowercase__=False ): """simple docstring""" assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time" if equal_resolution: SCREAMING_SNAKE_CASE_ : Optional[int] = [] for i in range(self.batch_size ): image_inputs.append( np.random.randint( 255 , size=(self.num_channels, self.max_resolution, self.max_resolution) , dtype=np.uinta ) ) else: SCREAMING_SNAKE_CASE_ : str = [] for i in range(self.batch_size ): SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[Any] = np.random.choice(np.arange(self.min_resolution , self.max_resolution ) , 2 ) image_inputs.append(np.random.randint(255 , size=(self.num_channels, width, height) , dtype=np.uinta ) ) if not numpify and not torchify: # PIL expects the channel dimension as last dimension SCREAMING_SNAKE_CASE_ : str = [Image.fromarray(np.moveaxis(lowercase__ , 0 , -1 ) ) for x in image_inputs] if torchify: SCREAMING_SNAKE_CASE_ : List[str] = [torch.from_numpy(lowercase__ ) for x in image_inputs] return image_inputs @require_torch @require_vision class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,unittest.TestCase ): _A = ChineseCLIPImageProcessor if is_vision_available() else None def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = ChineseCLIPImageProcessingTester(self , do_center_crop=lowercase__ ) @property def __lowerCamelCase ( self ): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowercase__ , "do_resize" ) ) self.assertTrue(hasattr(lowercase__ , "size" ) ) self.assertTrue(hasattr(lowercase__ , "do_center_crop" ) ) self.assertTrue(hasattr(lowercase__ , "center_crop" ) ) self.assertTrue(hasattr(lowercase__ , "do_normalize" ) ) self.assertTrue(hasattr(lowercase__ , "image_mean" ) ) self.assertTrue(hasattr(lowercase__ , "image_std" ) ) self.assertTrue(hasattr(lowercase__ , "do_convert_rgb" ) ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"height": 224, "width": 224} ) self.assertEqual(image_processor.crop_size , {"height": 18, "width": 18} ) SCREAMING_SNAKE_CASE_ : str = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 ) self.assertEqual(image_processor.size , {"shortest_edge": 42} ) self.assertEqual(image_processor.crop_size , {"height": 84, "width": 84} ) def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE_ : Tuple = self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__ ) for image in image_inputs: self.assertIsInstance(lowercase__ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE_ : Dict = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE_ : Optional[int] = image_processing(lowercase__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__ , numpify=lowercase__ ) for image in image_inputs: self.assertIsInstance(lowercase__ , np.ndarray ) # Test not batched input SCREAMING_SNAKE_CASE_ : Optional[int] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE_ : List[str] = image_processing(lowercase__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors SCREAMING_SNAKE_CASE_ : List[str] = self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__ , torchify=lowercase__ ) for image in image_inputs: self.assertIsInstance(lowercase__ , torch.Tensor ) # Test not batched input SCREAMING_SNAKE_CASE_ : Union[str, Any] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE_ : int = image_processing(lowercase__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) @require_torch @require_vision class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,unittest.TestCase ): _A = ChineseCLIPImageProcessor if is_vision_available() else None def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int = ChineseCLIPImageProcessingTester(self , num_channels=4 , do_center_crop=lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = 3 @property def __lowerCamelCase ( self ): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowercase__ , "do_resize" ) ) self.assertTrue(hasattr(lowercase__ , "size" ) ) self.assertTrue(hasattr(lowercase__ , "do_center_crop" ) ) self.assertTrue(hasattr(lowercase__ , "center_crop" ) ) self.assertTrue(hasattr(lowercase__ , "do_normalize" ) ) self.assertTrue(hasattr(lowercase__ , "image_mean" ) ) self.assertTrue(hasattr(lowercase__ , "image_std" ) ) self.assertTrue(hasattr(lowercase__ , "do_convert_rgb" ) ) def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE_ : Optional[int] = self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__ ) for image in image_inputs: self.assertIsInstance(lowercase__ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE_ : Optional[Any] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE_ : List[str] = image_processing(lowercase__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , )
68
1
'''simple docstring''' import copy from typing import Any, Dict, List, Optional, Union import numpy as np 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 snake_case_ = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = ["input_features"] def __init__( self , lowercase__=80 , lowercase__=1_6000 , lowercase__=160 , lowercase__=30 , lowercase__=400 , lowercase__=0.0 , lowercase__=False , **lowercase__ , ): """simple docstring""" super().__init__( feature_size=lowercase__ , sampling_rate=lowercase__ , padding_value=lowercase__ , return_attention_mask=lowercase__ , **lowercase__ , ) SCREAMING_SNAKE_CASE_ : Optional[int] = n_fft SCREAMING_SNAKE_CASE_ : int = hop_length SCREAMING_SNAKE_CASE_ : Any = chunk_length SCREAMING_SNAKE_CASE_ : List[Any] = chunk_length * sampling_rate SCREAMING_SNAKE_CASE_ : Optional[Any] = self.n_samples // hop_length SCREAMING_SNAKE_CASE_ : Optional[Any] = sampling_rate SCREAMING_SNAKE_CASE_ : Any = mel_filter_bank( num_frequency_bins=1 + n_fft // 2 , num_mel_filters=lowercase__ , min_frequency=0.0 , max_frequency=8000.0 , sampling_rate=lowercase__ , norm="slaney" , mel_scale="slaney" , ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = spectrogram( lowercase__ , window_function(self.n_fft , "hann" ) , frame_length=self.n_fft , hop_length=self.hop_length , power=2.0 , mel_filters=self.mel_filters , log_mel="log10" , ) SCREAMING_SNAKE_CASE_ : Dict = log_spec[:, :-1] SCREAMING_SNAKE_CASE_ : List[Any] = np.maximum(lowercase__ , log_spec.max() - 8.0 ) SCREAMING_SNAKE_CASE_ : Optional[Any] = (log_spec + 4.0) / 4.0 return log_spec @staticmethod # Copied from transformers.models.wav2vec2.feature_extraction_wav2vec2.Wav2Vec2FeatureExtractor.zero_mean_unit_var_norm def __lowerCamelCase ( lowercase__ , lowercase__ , lowercase__ = 0.0 ): """simple docstring""" if attention_mask is not None: SCREAMING_SNAKE_CASE_ : List[str] = np.array(lowercase__ , np.intaa ) SCREAMING_SNAKE_CASE_ : Optional[Any] = [] for vector, length in zip(lowercase__ , attention_mask.sum(-1 ) ): SCREAMING_SNAKE_CASE_ : Dict = (vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1e-7 ) if length < normed_slice.shape[0]: SCREAMING_SNAKE_CASE_ : Tuple = padding_value normed_input_values.append(lowercase__ ) else: SCREAMING_SNAKE_CASE_ : Any = [(x - x.mean()) / np.sqrt(x.var() + 1e-7 ) for x in input_values] return normed_input_values def __call__( self , lowercase__ , lowercase__ = True , lowercase__ = None , lowercase__ = None , lowercase__ = None , lowercase__ = "max_length" , lowercase__ = None , lowercase__ = None , lowercase__ = None , **lowercase__ , ): """simple docstring""" if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( F"The model corresponding to this feature extractor: {self.__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_ : Any = isinstance(lowercase__ , 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_ : Tuple = is_batched_numpy or ( isinstance(lowercase__ , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: SCREAMING_SNAKE_CASE_ : Any = [np.asarray([speech] , dtype=np.floataa ).T for speech in raw_speech] elif not is_batched and not isinstance(lowercase__ , np.ndarray ): SCREAMING_SNAKE_CASE_ : Optional[int] = np.asarray(lowercase__ , dtype=np.floataa ) elif isinstance(lowercase__ , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): SCREAMING_SNAKE_CASE_ : int = raw_speech.astype(np.floataa ) # always return batch if not is_batched: SCREAMING_SNAKE_CASE_ : List[str] = [np.asarray([raw_speech] ).T] SCREAMING_SNAKE_CASE_ : Optional[Any] = BatchFeature({"input_features": raw_speech} ) # convert into correct format for padding SCREAMING_SNAKE_CASE_ : Any = self.pad( lowercase__ , padding=lowercase__ , max_length=max_length if max_length else self.n_samples , truncation=lowercase__ , pad_to_multiple_of=lowercase__ , return_attention_mask=return_attention_mask or do_normalize , ) # zero-mean and unit-variance normalization if do_normalize: SCREAMING_SNAKE_CASE_ : str = self.zero_mean_unit_var_norm( padded_inputs["input_features"] , attention_mask=padded_inputs["attention_mask"] , padding_value=self.padding_value , ) SCREAMING_SNAKE_CASE_ : List[str] = np.stack(padded_inputs["input_features"] , axis=0 ) # make sure list is in array format SCREAMING_SNAKE_CASE_ : Optional[Any] = padded_inputs.get("input_features" ).transpose(2 , 0 , 1 ) SCREAMING_SNAKE_CASE_ : str = [self._np_extract_fbank_features(lowercase__ ) for waveform in input_features[0]] if isinstance(input_features[0] , lowercase__ ): SCREAMING_SNAKE_CASE_ : str = [np.asarray(lowercase__ , dtype=np.floataa ) for feature in input_features] else: SCREAMING_SNAKE_CASE_ : Optional[int] = input_features if return_attention_mask: # rescale from sample (48000) to feature (3000) SCREAMING_SNAKE_CASE_ : Tuple = padded_inputs["attention_mask"][:, :: self.hop_length] if return_tensors is not None: SCREAMING_SNAKE_CASE_ : Tuple = padded_inputs.convert_to_tensors(lowercase__ ) return padded_inputs def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE_ : Tuple = self.__class__.__name__ if "mel_filters" in output: del output["mel_filters"] return output
68
'''simple docstring''' from __future__ import annotations def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int ) -> bool: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = str(SCREAMING_SNAKE_CASE_ ) return len(SCREAMING_SNAKE_CASE_ ) == 9 and set(SCREAMING_SNAKE_CASE_ ) == set("123456789" ) def __lowerCamelCase ( ) -> int | None: """simple docstring""" for base_num in range(9_9_9_9 , 4_9_9_9 , -1 ): SCREAMING_SNAKE_CASE_ : int = 1_0_0_0_0_2 * base_num if is_9_pandigital(SCREAMING_SNAKE_CASE_ ): return candidate for base_num in range(3_3_3 , 9_9 , -1 ): SCREAMING_SNAKE_CASE_ : List[str] = 1_0_0_2_0_0_3 * base_num if is_9_pandigital(SCREAMING_SNAKE_CASE_ ): return candidate return None if __name__ == "__main__": print(F'''{solution() = }''')
68
1
'''simple docstring''' from collections.abc import Callable import numpy as np def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Callable , SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float ) -> np.array: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = int(np.ceil((x_end - xa) / step_size ) ) SCREAMING_SNAKE_CASE_ : Tuple = np.zeros((n + 1,) ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = ya SCREAMING_SNAKE_CASE_ : str = xa for k in range(SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ : List[Any] = y[k] + step_size * ode_func(SCREAMING_SNAKE_CASE_ , y[k] ) SCREAMING_SNAKE_CASE_ : Optional[Any] = y[k] + ( (step_size / 2) * (ode_func(SCREAMING_SNAKE_CASE_ , y[k] ) + ode_func(x + step_size , SCREAMING_SNAKE_CASE_ )) ) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
68
'''simple docstring''' from typing import Optional import pyspark from .. import Features, NamedSplit from ..download import DownloadMode from ..packaged_modules.spark.spark import Spark from .abc import AbstractDatasetReader class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): def __init__( self , lowercase__ , lowercase__ = None , lowercase__ = None , lowercase__ = True , lowercase__ = None , lowercase__ = False , lowercase__ = None , lowercase__ = True , lowercase__ = "arrow" , **lowercase__ , ): """simple docstring""" super().__init__( split=lowercase__ , features=lowercase__ , cache_dir=lowercase__ , keep_in_memory=lowercase__ , streaming=lowercase__ , **lowercase__ , ) SCREAMING_SNAKE_CASE_ : Any = load_from_cache_file SCREAMING_SNAKE_CASE_ : Optional[int] = file_format SCREAMING_SNAKE_CASE_ : List[Any] = Spark( df=lowercase__ , features=lowercase__ , cache_dir=lowercase__ , working_dir=lowercase__ , **lowercase__ , ) def __lowerCamelCase ( self ): """simple docstring""" if self.streaming: return self.builder.as_streaming_dataset(split=self.split ) SCREAMING_SNAKE_CASE_ : Optional[int] = None if self._load_from_cache_file else DownloadMode.FORCE_REDOWNLOAD self.builder.download_and_prepare( download_mode=lowercase__ , file_format=self._file_format , ) return self.builder.as_dataset(split=self.split )
68
1
'''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 json import os from ...utils.constants import SAGEMAKER_PARALLEL_EC2_INSTANCES, TORCH_DYNAMO_MODES from ...utils.dataclasses import ComputeEnvironment, SageMakerDistributedType from ...utils.imports import is_botoa_available from .config_args import SageMakerConfig from .config_utils import ( DYNAMO_BACKENDS, _ask_field, _ask_options, _convert_dynamo_backend, _convert_mixed_precision, _convert_sagemaker_distributed_mode, _convert_yes_no_to_bool, ) if is_botoa_available(): import botoa # noqa: F401 def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : List[Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : int = botoa.client("iam" ) SCREAMING_SNAKE_CASE_ : List[Any] = { "Version": "2012-10-17", "Statement": [ {"Effect": "Allow", "Principal": {"Service": "sagemaker.amazonaws.com"}, "Action": "sts:AssumeRole"} ], } try: # create the role, associated with the chosen trust policy iam_client.create_role( RoleName=SCREAMING_SNAKE_CASE_ , AssumeRolePolicyDocument=json.dumps(SCREAMING_SNAKE_CASE_ , indent=2 ) ) SCREAMING_SNAKE_CASE_ : Tuple = { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "sagemaker:*", "ecr:GetDownloadUrlForLayer", "ecr:BatchGetImage", "ecr:BatchCheckLayerAvailability", "ecr:GetAuthorizationToken", "cloudwatch:PutMetricData", "cloudwatch:GetMetricData", "cloudwatch:GetMetricStatistics", "cloudwatch:ListMetrics", "logs:CreateLogGroup", "logs:CreateLogStream", "logs:DescribeLogStreams", "logs:PutLogEvents", "logs:GetLogEvents", "s3:CreateBucket", "s3:ListBucket", "s3:GetBucketLocation", "s3:GetObject", "s3:PutObject", ], "Resource": "*", } ], } # attach policy to role iam_client.put_role_policy( RoleName=SCREAMING_SNAKE_CASE_ , PolicyName=F"{role_name}_policy_permission" , PolicyDocument=json.dumps(SCREAMING_SNAKE_CASE_ , indent=2 ) , ) except iam_client.exceptions.EntityAlreadyExistsException: print(F"role {role_name} already exists. Using existing one" ) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Union[str, Any] ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = botoa.client("iam" ) return iam_client.get_role(RoleName=SCREAMING_SNAKE_CASE_ )["Role"]["Arn"] def __lowerCamelCase ( ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = _ask_options( "How do you want to authorize?" , ["AWS Profile", "Credentials (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) "] , SCREAMING_SNAKE_CASE_ , ) SCREAMING_SNAKE_CASE_ : Optional[int] = None if credentials_configuration == 0: SCREAMING_SNAKE_CASE_ : Dict = _ask_field("Enter your AWS Profile name: [default] " , default="default" ) SCREAMING_SNAKE_CASE_ : Dict = aws_profile else: print( "Note you will need to provide AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY when you launch you training script with," "`accelerate launch --aws_access_key_id XXX --aws_secret_access_key YYY`" ) SCREAMING_SNAKE_CASE_ : Optional[int] = _ask_field("AWS Access Key ID: " ) SCREAMING_SNAKE_CASE_ : Optional[Any] = aws_access_key_id SCREAMING_SNAKE_CASE_ : Tuple = _ask_field("AWS Secret Access Key: " ) SCREAMING_SNAKE_CASE_ : Dict = aws_secret_access_key SCREAMING_SNAKE_CASE_ : Any = _ask_field("Enter your AWS Region: [us-east-1]" , default="us-east-1" ) SCREAMING_SNAKE_CASE_ : Any = aws_region SCREAMING_SNAKE_CASE_ : List[Any] = _ask_options( "Do you already have an IAM Role for executing Amazon SageMaker Training Jobs?" , ["Provide IAM Role name", "Create new IAM role using credentials"] , SCREAMING_SNAKE_CASE_ , ) if role_management == 0: SCREAMING_SNAKE_CASE_ : List[Any] = _ask_field("Enter your IAM role name: " ) else: SCREAMING_SNAKE_CASE_ : Tuple = "accelerate_sagemaker_execution_role" print(F"Accelerate will create an iam role \"{iam_role_name}\" using the provided credentials" ) _create_iam_role_for_sagemaker(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Any = _ask_field( "Do you want to use custom Docker image? [yes/NO]: " , _convert_yes_no_to_bool , default=SCREAMING_SNAKE_CASE_ , error_message="Please enter yes or no." , ) SCREAMING_SNAKE_CASE_ : Optional[Any] = None if is_custom_docker_image: SCREAMING_SNAKE_CASE_ : Any = _ask_field("Enter your Docker image: " , lambda SCREAMING_SNAKE_CASE_ : str(SCREAMING_SNAKE_CASE_ ).lower() ) SCREAMING_SNAKE_CASE_ : str = _ask_field( "Do you want to provide SageMaker input channels with data locations? [yes/NO]: " , _convert_yes_no_to_bool , default=SCREAMING_SNAKE_CASE_ , error_message="Please enter yes or no." , ) SCREAMING_SNAKE_CASE_ : Tuple = None if is_sagemaker_inputs_enabled: SCREAMING_SNAKE_CASE_ : List[Any] = _ask_field( "Enter the path to the SageMaker inputs TSV file with columns (channel_name, data_location): " , lambda SCREAMING_SNAKE_CASE_ : str(SCREAMING_SNAKE_CASE_ ).lower() , ) SCREAMING_SNAKE_CASE_ : Any = _ask_field( "Do you want to enable SageMaker metrics? [yes/NO]: " , _convert_yes_no_to_bool , default=SCREAMING_SNAKE_CASE_ , error_message="Please enter yes or no." , ) SCREAMING_SNAKE_CASE_ : Tuple = None if is_sagemaker_metrics_enabled: SCREAMING_SNAKE_CASE_ : int = _ask_field( "Enter the path to the SageMaker metrics TSV file with columns (metric_name, metric_regex): " , lambda SCREAMING_SNAKE_CASE_ : str(SCREAMING_SNAKE_CASE_ ).lower() , ) SCREAMING_SNAKE_CASE_ : int = _ask_options( "What is the distributed mode?" , ["No distributed training", "Data parallelism"] , _convert_sagemaker_distributed_mode , ) SCREAMING_SNAKE_CASE_ : Any = {} SCREAMING_SNAKE_CASE_ : str = _ask_field( "Do you wish to optimize your script with torch dynamo?[yes/NO]:" , _convert_yes_no_to_bool , default=SCREAMING_SNAKE_CASE_ , error_message="Please enter yes or no." , ) if use_dynamo: SCREAMING_SNAKE_CASE_ : Union[str, Any] = "dynamo_" SCREAMING_SNAKE_CASE_ : Dict = _ask_options( "Which dynamo backend would you like to use?" , [x.lower() for x in DYNAMO_BACKENDS] , _convert_dynamo_backend , default=2 , ) SCREAMING_SNAKE_CASE_ : int = _ask_field( "Do you want to customize the defaults sent to torch.compile? [yes/NO]: " , _convert_yes_no_to_bool , default=SCREAMING_SNAKE_CASE_ , error_message="Please enter yes or no." , ) if use_custom_options: SCREAMING_SNAKE_CASE_ : Union[str, Any] = _ask_options( "Which mode do you want to use?" , SCREAMING_SNAKE_CASE_ , lambda SCREAMING_SNAKE_CASE_ : TORCH_DYNAMO_MODES[int(SCREAMING_SNAKE_CASE_ )] , default="default" , ) SCREAMING_SNAKE_CASE_ : Tuple = _ask_field( "Do you want the fullgraph mode or it is ok to break model into several subgraphs? [yes/NO]: " , _convert_yes_no_to_bool , default=SCREAMING_SNAKE_CASE_ , error_message="Please enter yes or no." , ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = _ask_field( "Do you want to enable dynamic shape tracing? [yes/NO]: " , _convert_yes_no_to_bool , default=SCREAMING_SNAKE_CASE_ , error_message="Please enter yes or no." , ) SCREAMING_SNAKE_CASE_ : Dict = "Which EC2 instance type you want to use for your training?" if distributed_type != SageMakerDistributedType.NO: SCREAMING_SNAKE_CASE_ : List[str] = _ask_options( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , lambda SCREAMING_SNAKE_CASE_ : SAGEMAKER_PARALLEL_EC2_INSTANCES[int(SCREAMING_SNAKE_CASE_ )] ) else: eca_instance_query += "? [ml.p3.2xlarge]:" SCREAMING_SNAKE_CASE_ : Optional[int] = _ask_field(SCREAMING_SNAKE_CASE_ , lambda SCREAMING_SNAKE_CASE_ : str(SCREAMING_SNAKE_CASE_ ).lower() , default="ml.p3.2xlarge" ) SCREAMING_SNAKE_CASE_ : Optional[int] = 1 if distributed_type in (SageMakerDistributedType.DATA_PARALLEL, SageMakerDistributedType.MODEL_PARALLEL): SCREAMING_SNAKE_CASE_ : Optional[Any] = _ask_field( "How many machines do you want use? [1]: " , SCREAMING_SNAKE_CASE_ , default=1 , ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = _ask_options( "Do you wish to use FP16 or BF16 (mixed precision)?" , ["no", "fp16", "bf16", "fp8"] , _convert_mixed_precision , ) if use_dynamo and mixed_precision == "no": print( "Torch dynamo used without mixed precision requires TF32 to be efficient. Accelerate will enable it by default when launching your scripts." ) return SageMakerConfig( image_uri=SCREAMING_SNAKE_CASE_ , compute_environment=ComputeEnvironment.AMAZON_SAGEMAKER , distributed_type=SCREAMING_SNAKE_CASE_ , use_cpu=SCREAMING_SNAKE_CASE_ , dynamo_config=SCREAMING_SNAKE_CASE_ , eca_instance_type=SCREAMING_SNAKE_CASE_ , profile=SCREAMING_SNAKE_CASE_ , region=SCREAMING_SNAKE_CASE_ , iam_role_name=SCREAMING_SNAKE_CASE_ , mixed_precision=SCREAMING_SNAKE_CASE_ , num_machines=SCREAMING_SNAKE_CASE_ , sagemaker_inputs_file=SCREAMING_SNAKE_CASE_ , sagemaker_metrics_file=SCREAMING_SNAKE_CASE_ , )
68
'''simple docstring''' import re import string import numpy as np import datasets snake_case_ = '\nReturns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list.\n' snake_case_ = '\nArgs:\n predictions: List of predicted texts.\n references: List of reference texts.\n regexes_to_ignore: List, defaults to None. Regex expressions of characters to\n ignore when calculating the exact matches. Note: these regexes are removed\n from the input data before the changes based on the options below (e.g. ignore_case,\n ignore_punctuation, ignore_numbers) are applied.\n ignore_case: Boolean, defaults to False. If true, turns everything\n to lowercase so that capitalization differences are ignored.\n ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\n ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\nReturns:\n exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive.\nExamples:\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results["exact_match"], 1))\n 25.0\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results["exact_match"], 1))\n 50.0\n\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results["exact_match"], 1))\n 75.0\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True)\n >>> print(round(results["exact_match"], 1))\n 100.0\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["The cat sat on the mat.", "Theaters are great.", "It\'s like comparing oranges and apples."]\n >>> preds = ["The cat sat on the mat?", "Theaters are great.", "It\'s like comparing apples and oranges."]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results["exact_match"], 1))\n 33.3\n\n' snake_case_ = '\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION,_KWARGS_DESCRIPTION ) class SCREAMING_SNAKE_CASE__ ( datasets.Metric ): def __lowerCamelCase ( self ): """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Value("string" , id="sequence" ), "references": datasets.Value("string" , id="sequence" ), } ) , reference_urls=[] , ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__=None , lowercase__=False , lowercase__=False , lowercase__=False , ): """simple docstring""" if regexes_to_ignore is not None: for s in regexes_to_ignore: SCREAMING_SNAKE_CASE_ : Optional[Any] = np.array([re.sub(lowercase__ , "" , lowercase__ ) for x in predictions] ) SCREAMING_SNAKE_CASE_ : List[Any] = np.array([re.sub(lowercase__ , "" , lowercase__ ) for x in references] ) else: SCREAMING_SNAKE_CASE_ : int = np.asarray(lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = np.asarray(lowercase__ ) if ignore_case: SCREAMING_SNAKE_CASE_ : Dict = np.char.lower(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = np.char.lower(lowercase__ ) if ignore_punctuation: SCREAMING_SNAKE_CASE_ : Optional[int] = string.punctuation.maketrans("" , "" , string.punctuation ) SCREAMING_SNAKE_CASE_ : int = np.char.translate(lowercase__ , table=lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = np.char.translate(lowercase__ , table=lowercase__ ) if ignore_numbers: SCREAMING_SNAKE_CASE_ : Optional[int] = string.digits.maketrans("" , "" , string.digits ) SCREAMING_SNAKE_CASE_ : Dict = np.char.translate(lowercase__ , table=lowercase__ ) SCREAMING_SNAKE_CASE_ : int = np.char.translate(lowercase__ , table=lowercase__ ) SCREAMING_SNAKE_CASE_ : str = predictions == references return {"exact_match": np.mean(lowercase__ ) * 100}
68
1
'''simple docstring''' import unittest import numpy as np from transformers import is_flax_available from transformers.testing_utils import require_flax from ..test_modeling_flax_common import ids_tensor if is_flax_available(): import jax import jax.numpy as jnp from transformers.generation import ( FlaxForcedBOSTokenLogitsProcessor, FlaxForcedEOSTokenLogitsProcessor, FlaxLogitsProcessorList, FlaxMinLengthLogitsProcessor, FlaxTemperatureLogitsWarper, FlaxTopKLogitsWarper, FlaxTopPLogitsWarper, ) @require_flax class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __lowerCamelCase ( self , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = jnp.ones((batch_size, length) ) / length return scores def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = None SCREAMING_SNAKE_CASE_ : List[str] = 20 SCREAMING_SNAKE_CASE_ : Union[str, Any] = self._get_uniform_logits(batch_size=2 , length=lowercase__ ) # tweak scores to not be uniform anymore SCREAMING_SNAKE_CASE_ : str = scores.at[1, 5].set((1 / length) + 0.1 ) # peak, 1st batch SCREAMING_SNAKE_CASE_ : Union[str, Any] = scores.at[1, 10].set((1 / length) - 0.4 ) # valley, 1st batch # compute softmax SCREAMING_SNAKE_CASE_ : Optional[Any] = jax.nn.softmax(lowercase__ , axis=-1 ) SCREAMING_SNAKE_CASE_ : Optional[int] = FlaxTemperatureLogitsWarper(temperature=0.5 ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = FlaxTemperatureLogitsWarper(temperature=1.3 ) SCREAMING_SNAKE_CASE_ : Dict = jax.nn.softmax(temp_dist_warper_sharper(lowercase__ , scores.copy() , cur_len=lowercase__ ) , axis=-1 ) SCREAMING_SNAKE_CASE_ : Optional[Any] = jax.nn.softmax(temp_dist_warper_smoother(lowercase__ , scores.copy() , cur_len=lowercase__ ) , axis=-1 ) # uniform distribution stays uniform self.assertTrue(jnp.allclose(probs[0, :] , warped_prob_sharp[0, :] , atol=1e-3 ) ) self.assertTrue(jnp.allclose(probs[0, :] , warped_prob_smooth[0, :] , atol=1e-3 ) ) # sharp peaks get higher, valleys get lower self.assertLess(probs[1, :].max() , warped_prob_sharp[1, :].max() ) self.assertGreater(probs[1, :].min() , warped_prob_sharp[1, :].min() ) # smooth peaks get lower, valleys get higher self.assertGreater(probs[1, :].max() , warped_prob_smooth[1, :].max() ) self.assertLess(probs[1, :].min() , warped_prob_smooth[1, :].min() ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = None SCREAMING_SNAKE_CASE_ : Any = 10 SCREAMING_SNAKE_CASE_ : List[str] = 2 # create ramp distribution SCREAMING_SNAKE_CASE_ : Tuple = np.broadcast_to(np.arange(lowercase__ )[None, :] , (batch_size, vocab_size) ).copy() SCREAMING_SNAKE_CASE_ : Optional[Any] = ramp_logits[1:, : vocab_size // 2] + vocab_size SCREAMING_SNAKE_CASE_ : Optional[Any] = FlaxTopKLogitsWarper(3 ) SCREAMING_SNAKE_CASE_ : Any = top_k_warp(lowercase__ , lowercase__ , cur_len=lowercase__ ) # check that correct tokens are filtered self.assertListEqual(jnp.isinf(scores[0] ).tolist() , 7 * [True] + 3 * [False] ) self.assertListEqual(jnp.isinf(scores[1] ).tolist() , 2 * [True] + 3 * [False] + 5 * [True] ) # check special case SCREAMING_SNAKE_CASE_ : Tuple = 5 SCREAMING_SNAKE_CASE_ : List[Any] = FlaxTopKLogitsWarper(top_k=1 , filter_value=0.0 , min_tokens_to_keep=3 ) SCREAMING_SNAKE_CASE_ : Tuple = np.broadcast_to(np.arange(lowercase__ )[None, :] , (batch_size, length) ).copy() SCREAMING_SNAKE_CASE_ : Union[str, Any] = top_k_warp_safety_check(lowercase__ , lowercase__ , cur_len=lowercase__ ) # min_tokens overwrites k: 3 tokens are kept => 2 tokens are nullified self.assertListEqual((scores == 0.0).sum(axis=-1 ).tolist() , [2, 2] ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = None SCREAMING_SNAKE_CASE_ : List[str] = 10 SCREAMING_SNAKE_CASE_ : Dict = 2 # create distribution and take log (inverse to Softmax as taken in TopPLogitsWarper) SCREAMING_SNAKE_CASE_ : Optional[Any] = np.log(np.array([[0.3, 0.1, 0.1, 0.5], [0.15, 0.3, 0.3, 0.25]] ) ) SCREAMING_SNAKE_CASE_ : int = FlaxTopPLogitsWarper(0.8 ) SCREAMING_SNAKE_CASE_ : int = np.exp(top_p_warp(lowercase__ , lowercase__ , cur_len=lowercase__ ) ) # dist should be filtered to keep min num values so that sum is >= top_p # exp (-inf) => 0 SCREAMING_SNAKE_CASE_ : List[str] = np.array([[0.3, 0.0, 0.0, 0.5], [0.0, 0.3, 0.3, 0.25]] ) self.assertTrue(np.allclose(lowercase__ , lowercase__ , atol=1e-3 ) ) # check edge cases with negative and extreme logits SCREAMING_SNAKE_CASE_ : Optional[Any] = np.broadcast_to(np.arange(lowercase__ )[None, :] , (batch_size, vocab_size) ).copy() - ( vocab_size // 2 ) # make ramp_logits more extreme SCREAMING_SNAKE_CASE_ : List[str] = ramp_logits[1] * 100.0 # make sure at least 2 tokens are kept SCREAMING_SNAKE_CASE_ : List[str] = FlaxTopPLogitsWarper(0.9 , min_tokens_to_keep=2 , filter_value=0.0 ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = top_p_warp(lowercase__ , lowercase__ , cur_len=lowercase__ ) # first batch should keep three tokens, second batch would keep only 1, but due to `min_tokens_to_keep=2` keeps 2. self.assertListEqual((filtered_dist != 0.0).sum(axis=-1 ).tolist() , [3, 2] ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = 20 SCREAMING_SNAKE_CASE_ : Optional[int] = 4 SCREAMING_SNAKE_CASE_ : Tuple = 0 SCREAMING_SNAKE_CASE_ : List[str] = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=lowercase__ ) # check that min length is applied at length 5 SCREAMING_SNAKE_CASE_ : str = ids_tensor((batch_size, 20) , vocab_size=20 ) SCREAMING_SNAKE_CASE_ : Optional[Any] = 5 SCREAMING_SNAKE_CASE_ : Tuple = self._get_uniform_logits(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : str = min_dist_processor(lowercase__ , lowercase__ , cur_len=lowercase__ ) self.assertListEqual(scores_before_min_length[:, eos_token_id].tolist() , 4 * [-float("inf" )] ) # check that min length is not applied anymore at length 15 SCREAMING_SNAKE_CASE_ : Optional[Any] = self._get_uniform_logits(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = 15 SCREAMING_SNAKE_CASE_ : Dict = min_dist_processor(lowercase__ , lowercase__ , cur_len=lowercase__ ) self.assertFalse(jnp.isinf(lowercase__ ).any() ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = 20 SCREAMING_SNAKE_CASE_ : Any = 4 SCREAMING_SNAKE_CASE_ : Dict = 0 SCREAMING_SNAKE_CASE_ : List[Any] = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=lowercase__ ) # check that all scores are -inf except the bos_token_id score SCREAMING_SNAKE_CASE_ : List[Any] = ids_tensor((batch_size, 1) , vocab_size=20 ) SCREAMING_SNAKE_CASE_ : List[str] = 1 SCREAMING_SNAKE_CASE_ : Dict = self._get_uniform_logits(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : int = logits_processor(lowercase__ , lowercase__ , cur_len=lowercase__ ) self.assertTrue(jnp.isneginf(scores[:, bos_token_id + 1 :] ).all() ) self.assertListEqual(scores[:, bos_token_id].tolist() , 4 * [0] ) # score for bos_token_id shold be zero # check that bos_token_id is not forced if current length is greater than 1 SCREAMING_SNAKE_CASE_ : List[Any] = 3 SCREAMING_SNAKE_CASE_ : Dict = self._get_uniform_logits(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : Tuple = logits_processor(lowercase__ , lowercase__ , cur_len=lowercase__ ) self.assertFalse(jnp.isinf(lowercase__ ).any() ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = 20 SCREAMING_SNAKE_CASE_ : Dict = 4 SCREAMING_SNAKE_CASE_ : Any = 0 SCREAMING_SNAKE_CASE_ : List[str] = 5 SCREAMING_SNAKE_CASE_ : int = FlaxForcedEOSTokenLogitsProcessor(max_length=lowercase__ , eos_token_id=lowercase__ ) # check that all scores are -inf except the eos_token_id when max_length is reached SCREAMING_SNAKE_CASE_ : List[str] = ids_tensor((batch_size, 4) , vocab_size=20 ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = 4 SCREAMING_SNAKE_CASE_ : List[str] = self._get_uniform_logits(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = logits_processor(lowercase__ , lowercase__ , cur_len=lowercase__ ) self.assertTrue(jnp.isneginf(scores[:, eos_token_id + 1 :] ).all() ) self.assertListEqual(scores[:, eos_token_id].tolist() , 4 * [0] ) # score for eos_token_id should be zero # check that eos_token_id is not forced if max_length is not reached SCREAMING_SNAKE_CASE_ : List[str] = 3 SCREAMING_SNAKE_CASE_ : Union[str, Any] = self._get_uniform_logits(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = logits_processor(lowercase__ , lowercase__ , cur_len=lowercase__ ) self.assertFalse(jnp.isinf(lowercase__ ).any() ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int = 4 SCREAMING_SNAKE_CASE_ : int = 10 SCREAMING_SNAKE_CASE_ : int = 15 SCREAMING_SNAKE_CASE_ : Tuple = 2 SCREAMING_SNAKE_CASE_ : Any = 1 SCREAMING_SNAKE_CASE_ : Tuple = 15 # dummy input_ids and scores SCREAMING_SNAKE_CASE_ : List[str] = ids_tensor((batch_size, sequence_length) , lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = input_ids.copy() SCREAMING_SNAKE_CASE_ : List[str] = self._get_uniform_logits(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = scores.copy() # instantiate all dist processors SCREAMING_SNAKE_CASE_ : Union[str, Any] = FlaxTemperatureLogitsWarper(temperature=0.5 ) SCREAMING_SNAKE_CASE_ : Tuple = FlaxTopKLogitsWarper(3 ) SCREAMING_SNAKE_CASE_ : Optional[Any] = FlaxTopPLogitsWarper(0.8 ) # instantiate all logits processors SCREAMING_SNAKE_CASE_ : List[Any] = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=lowercase__ ) SCREAMING_SNAKE_CASE_ : str = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = FlaxForcedEOSTokenLogitsProcessor(max_length=lowercase__ , eos_token_id=lowercase__ ) SCREAMING_SNAKE_CASE_ : str = 10 # no processor list SCREAMING_SNAKE_CASE_ : Tuple = temp_dist_warp(lowercase__ , lowercase__ , cur_len=lowercase__ ) SCREAMING_SNAKE_CASE_ : str = top_k_warp(lowercase__ , lowercase__ , cur_len=lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = top_p_warp(lowercase__ , lowercase__ , cur_len=lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = min_dist_proc(lowercase__ , lowercase__ , cur_len=lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = bos_dist_proc(lowercase__ , lowercase__ , cur_len=lowercase__ ) SCREAMING_SNAKE_CASE_ : str = eos_dist_proc(lowercase__ , lowercase__ , cur_len=lowercase__ ) # with processor list SCREAMING_SNAKE_CASE_ : int = FlaxLogitsProcessorList( [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc] ) SCREAMING_SNAKE_CASE_ : Optional[int] = processor(lowercase__ , lowercase__ , cur_len=lowercase__ ) # scores should be equal self.assertTrue(jnp.allclose(lowercase__ , lowercase__ , atol=1e-3 ) ) # input_ids should never be changed self.assertListEqual(input_ids.tolist() , input_ids_comp.tolist() ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = 4 SCREAMING_SNAKE_CASE_ : Dict = 10 SCREAMING_SNAKE_CASE_ : Tuple = 15 SCREAMING_SNAKE_CASE_ : str = 2 SCREAMING_SNAKE_CASE_ : Optional[int] = 1 SCREAMING_SNAKE_CASE_ : Dict = 15 # dummy input_ids and scores SCREAMING_SNAKE_CASE_ : Tuple = ids_tensor((batch_size, sequence_length) , lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = input_ids.copy() SCREAMING_SNAKE_CASE_ : str = self._get_uniform_logits(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = scores.copy() # instantiate all dist processors SCREAMING_SNAKE_CASE_ : Tuple = FlaxTemperatureLogitsWarper(temperature=0.5 ) SCREAMING_SNAKE_CASE_ : Tuple = FlaxTopKLogitsWarper(3 ) SCREAMING_SNAKE_CASE_ : Tuple = FlaxTopPLogitsWarper(0.8 ) # instantiate all logits processors SCREAMING_SNAKE_CASE_ : str = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=lowercase__ ) SCREAMING_SNAKE_CASE_ : Tuple = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = FlaxForcedEOSTokenLogitsProcessor(max_length=lowercase__ , eos_token_id=lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = 10 # no processor list def run_no_processor_list(lowercase__ , lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE_ : List[Any] = temp_dist_warp(lowercase__ , lowercase__ , cur_len=lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = top_k_warp(lowercase__ , lowercase__ , cur_len=lowercase__ ) SCREAMING_SNAKE_CASE_ : Tuple = top_p_warp(lowercase__ , lowercase__ , cur_len=lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = min_dist_proc(lowercase__ , lowercase__ , cur_len=lowercase__ ) SCREAMING_SNAKE_CASE_ : str = bos_dist_proc(lowercase__ , lowercase__ , cur_len=lowercase__ ) SCREAMING_SNAKE_CASE_ : str = eos_dist_proc(lowercase__ , lowercase__ , cur_len=lowercase__ ) return scores # with processor list def run_processor_list(lowercase__ , lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE_ : int = FlaxLogitsProcessorList( [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc] ) SCREAMING_SNAKE_CASE_ : Tuple = processor(lowercase__ , lowercase__ , cur_len=lowercase__ ) return scores SCREAMING_SNAKE_CASE_ : int = jax.jit(lowercase__ ) SCREAMING_SNAKE_CASE_ : str = jax.jit(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = jitted_run_no_processor_list(lowercase__ , lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = jitted_run_processor_list(lowercase__ , lowercase__ , lowercase__ ) # scores should be equal self.assertTrue(jnp.allclose(lowercase__ , lowercase__ , atol=1e-3 ) ) # input_ids should never be changed self.assertListEqual(input_ids.tolist() , input_ids_comp.tolist() )
68
'''simple docstring''' import os import re import unicodedata from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import is_torch_available, logging if is_torch_available(): import torch if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation snake_case_ = logging.get_logger(__name__) snake_case_ = {'vocab_file': 'spiece.model'} snake_case_ = { 'vocab_file': { 'AI-Sweden/gpt-sw3-126m': 'https://huggingface.co/AI-Sweden/gpt-sw3-126m/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-350m': 'https://huggingface.co/AI-Sweden/gpt-sw3-350m/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-1.6b': 'https://huggingface.co/AI-Sweden/gpt-sw3-1.6b/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-6.7b': 'https://huggingface.co/AI-Sweden/gpt-sw3-6.7b/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-20b': 'https://huggingface.co/AI-Sweden/gpt-sw3-20b/resolve/main/spiece.model', } } snake_case_ = { 'AI-Sweden/gpt-sw3-126m': 2_0_4_8, 'AI-Sweden/gpt-sw3-350m': 2_0_4_8, 'AI-Sweden/gpt-sw3-1.6b': 2_0_4_8, 'AI-Sweden/gpt-sw3-6.7b': 2_0_4_8, 'AI-Sweden/gpt-sw3-20b': 2_0_4_8, } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = VOCAB_FILES_NAMES _A = PRETRAINED_VOCAB_FILES_MAP _A = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _A = ["input_ids", "attention_mask"] def __init__( self , lowercase__ , lowercase__=False , lowercase__=False , lowercase__=False , lowercase__=None , lowercase__=None , lowercase__=None , lowercase__=None , lowercase__ = None , **lowercase__ , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = {} if sp_model_kwargs is None else sp_model_kwargs SCREAMING_SNAKE_CASE_ : Dict = kwargs.get("name_or_path" ) if name_or_path is None: logger.warning( "name_or_path not provided, will work for all GPTSw3 models except gpt-sw3-7b," " you are testing the model, this can safely be ignored" ) SCREAMING_SNAKE_CASE_ : str = "None" # Default definitions for our 2 tokenizer versions, with None-checks to enable proper testing SCREAMING_SNAKE_CASE_ : List[Any] = "<|endoftext|>" if eos_token is None else eos_token SCREAMING_SNAKE_CASE_ : Dict = "<unk>" if unk_token is None else unk_token if "gpt-sw3-7b" in name_or_path: SCREAMING_SNAKE_CASE_ : Tuple = unk_token if pad_token is None else pad_token SCREAMING_SNAKE_CASE_ : Optional[Any] = eos_token if bos_token is None else bos_token else: SCREAMING_SNAKE_CASE_ : int = "<pad>" if pad_token is None else pad_token SCREAMING_SNAKE_CASE_ : Any = "<s>" if bos_token is None else bos_token super().__init__( do_lower_case=lowercase__ , remove_space=lowercase__ , keep_accents=lowercase__ , bos_token=lowercase__ , eos_token=lowercase__ , unk_token=lowercase__ , pad_token=lowercase__ , sp_model_kwargs=self.sp_model_kwargs , **lowercase__ , ) SCREAMING_SNAKE_CASE_ : Optional[Any] = do_lower_case SCREAMING_SNAKE_CASE_ : Optional[int] = remove_space SCREAMING_SNAKE_CASE_ : int = keep_accents SCREAMING_SNAKE_CASE_ : List[Any] = vocab_file SCREAMING_SNAKE_CASE_ : List[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(lowercase__ ) # Used for whitespace normalization in input texts # fmt : off SCREAMING_SNAKE_CASE_ : int = {" ", " ", " ", " ", " ", " ", " ", " ", " ", " ", "", "„"} # fmt : on # Regular expression to remove non-printing characters (e.g. some unicode control chars) in preprocessing SCREAMING_SNAKE_CASE_ : List[str] = re.compile( F"[{''.join(map(lowercase__ , list(range(0 , 9 ) ) + list(range(11 , 32 ) ) + list(range(127 , 160 ) ) + [160, 173, 8203] ) )}]" ) def __getstate__( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = self.__dict__.copy() SCREAMING_SNAKE_CASE_ : Dict = None return state def __setstate__( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): SCREAMING_SNAKE_CASE_ : Union[str, Any] = {} SCREAMING_SNAKE_CASE_ : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) @property # Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.vocab_size def __lowerCamelCase ( self ): """simple docstring""" return len(self.sp_model ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.non_printing_characters_re.sub("" , lowercase__ ) # Normalize whitespaces SCREAMING_SNAKE_CASE_ : List[str] = "".join([char if char not in self.whitespaces else " " for char in text] ) # NFC Unicode normalization SCREAMING_SNAKE_CASE_ : List[Any] = unicodedata.normalize("NFC" , lowercase__ ) return text def __lowerCamelCase ( self , lowercase__ , **lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = self.preprocess_text(lowercase__ ) return self.sp_model.encode(lowercase__ , out_type=lowercase__ ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" return self.sp_model.PieceToId(lowercase__ ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" return self.sp_model.IdToPiece(lowercase__ ) @staticmethod def __lowerCamelCase ( lowercase__ ): """simple docstring""" return out_string def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = [] SCREAMING_SNAKE_CASE_ : Any = "" SCREAMING_SNAKE_CASE_ : Dict = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: # TODO: Check if this is needed, as it ensures that decode(encode(doc)) != doc by adding extra whitespace in the decoded document if not prev_is_special: out_string += " " out_string += self.sp_model.decode(lowercase__ ) + token SCREAMING_SNAKE_CASE_ : Union[str, Any] = True SCREAMING_SNAKE_CASE_ : int = [] else: current_sub_tokens.append(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = False out_string += self.sp_model.decode(lowercase__ ) return out_string def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = {self.convert_ids_to_tokens(lowercase__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __lowerCamelCase ( self , lowercase__ , lowercase__ = None ): """simple docstring""" if not os.path.isdir(lowercase__ ): logger.error(F"Vocabulary path ({save_directory}) should be a directory" ) return SCREAMING_SNAKE_CASE_ : Any = os.path.join( lowercase__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(lowercase__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , lowercase__ ) elif not os.path.isfile(self.vocab_file ): with open(lowercase__ , "wb" ) as fi: SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.sp_model.serialized_model_proto() fi.write(lowercase__ ) return (out_vocab_file,) def __lowerCamelCase ( self , lowercase__ , lowercase__ = False ): """simple docstring""" if isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE_ : List[Any] = self.preprocess_text(lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = self.sp_model.encode(lowercase__ ) else: SCREAMING_SNAKE_CASE_ : str = [self.preprocess_text(lowercase__ ) for t in text] SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.sp_model.encode(lowercase__ ) if return_tensors is True or return_tensors == "pt": SCREAMING_SNAKE_CASE_ : str = torch.tensor(lowercase__ ) return token_ids def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" return self.sp_model.decode(lowercase__ ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = [F"User: {text}" if is_user else F"Bot: {text}" for is_user, text in conversation.iter_texts()] SCREAMING_SNAKE_CASE_ : List[str] = ( F"{self.eos_token}{self.bos_token}" + F"{self.bos_token}".join(lowercase__ ) + F"{self.bos_token}Bot:" ) return self.encode(text=lowercase__ )
68
1
'''simple docstring''' import inspect import os import unittest from dataclasses import dataclass import torch from accelerate import Accelerator, DistributedDataParallelKwargs, GradScalerKwargs from accelerate.state import AcceleratorState from accelerate.test_utils import execute_subprocess_async, require_cuda, require_multi_gpu from accelerate.utils import KwargsHandler @dataclass class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = 0 _A = False _A = 3.0 class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __lowerCamelCase ( self ): """simple docstring""" self.assertDictEqual(MockClass().to_kwargs() , {} ) self.assertDictEqual(MockClass(a=2 ).to_kwargs() , {"a": 2} ) self.assertDictEqual(MockClass(a=2 , b=lowercase__ ).to_kwargs() , {"a": 2, "b": True} ) self.assertDictEqual(MockClass(a=2 , c=2.25 ).to_kwargs() , {"a": 2, "c": 2.25} ) @require_cuda def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = GradScalerKwargs(init_scale=1024 , growth_factor=2 ) AcceleratorState._reset_state() SCREAMING_SNAKE_CASE_ : List[Any] = Accelerator(mixed_precision="fp16" , kwargs_handlers=[scaler_handler] ) print(accelerator.use_fpaa ) SCREAMING_SNAKE_CASE_ : List[str] = accelerator.scaler # Check the kwargs have been applied self.assertEqual(scaler._init_scale , 1024.0 ) self.assertEqual(scaler._growth_factor , 2.0 ) # Check the other values are at the default self.assertEqual(scaler._backoff_factor , 0.5 ) self.assertEqual(scaler._growth_interval , 2000 ) self.assertEqual(scaler._enabled , lowercase__ ) @require_multi_gpu def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int = ["torchrun", F"--nproc_per_node={torch.cuda.device_count()}", inspect.getfile(self.__class__ )] execute_subprocess_async(lowercase__ , env=os.environ.copy() ) if __name__ == "__main__": snake_case_ = DistributedDataParallelKwargs(bucket_cap_mb=1_5, find_unused_parameters=True) snake_case_ = Accelerator(kwargs_handlers=[ddp_scaler]) snake_case_ = torch.nn.Linear(1_0_0, 2_0_0) snake_case_ = accelerator.prepare(model) # Check the values changed in kwargs snake_case_ = '' snake_case_ = model.bucket_bytes_cap // (1_0_2_4 * 1_0_2_4) if observed_bucket_cap_map != 1_5: error_msg += F"Kwargs badly passed, should have `15` but found {observed_bucket_cap_map}.\n" if model.find_unused_parameters is not True: error_msg += F"Kwargs badly passed, should have `True` but found {model.find_unused_parameters}.\n" # Check the values of the defaults if model.dim != 0: error_msg += F"Default value not respected, should have `0` but found {model.dim}.\n" if model.broadcast_buffers is not True: error_msg += F"Default value not respected, should have `True` but found {model.broadcast_buffers}.\n" if model.gradient_as_bucket_view is not False: error_msg += F"Default value not respected, should have `False` but found {model.gradient_as_bucket_view}.\n" # Raise error at the end to make sure we don't stop at the first failure. if len(error_msg) > 0: raise ValueError(error_msg)
68
'''simple docstring''' import re from filelock import FileLock try: import nltk snake_case_ = True except (ImportError, ModuleNotFoundError): snake_case_ = False if NLTK_AVAILABLE: with FileLock('.lock') as lock: nltk.download('punkt', quiet=True) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str ) -> str: """simple docstring""" re.sub("<n>" , "" , SCREAMING_SNAKE_CASE_ ) # remove pegasus newline char assert NLTK_AVAILABLE, "nltk must be installed to separate newlines between sentences. (pip install nltk)" return "\n".join(nltk.sent_tokenize(SCREAMING_SNAKE_CASE_ ) )
68
1
'''simple docstring''' from typing import Optional import pyspark from .. import Features, NamedSplit from ..download import DownloadMode from ..packaged_modules.spark.spark import Spark from .abc import AbstractDatasetReader class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): def __init__( self , lowercase__ , lowercase__ = None , lowercase__ = None , lowercase__ = True , lowercase__ = None , lowercase__ = False , lowercase__ = None , lowercase__ = True , lowercase__ = "arrow" , **lowercase__ , ): """simple docstring""" super().__init__( split=lowercase__ , features=lowercase__ , cache_dir=lowercase__ , keep_in_memory=lowercase__ , streaming=lowercase__ , **lowercase__ , ) SCREAMING_SNAKE_CASE_ : Any = load_from_cache_file SCREAMING_SNAKE_CASE_ : Optional[int] = file_format SCREAMING_SNAKE_CASE_ : List[Any] = Spark( df=lowercase__ , features=lowercase__ , cache_dir=lowercase__ , working_dir=lowercase__ , **lowercase__ , ) def __lowerCamelCase ( self ): """simple docstring""" if self.streaming: return self.builder.as_streaming_dataset(split=self.split ) SCREAMING_SNAKE_CASE_ : Optional[int] = None if self._load_from_cache_file else DownloadMode.FORCE_REDOWNLOAD self.builder.download_and_prepare( download_mode=lowercase__ , file_format=self._file_format , ) return self.builder.as_dataset(split=self.split )
68
'''simple docstring''' from __future__ import annotations import copy import inspect import unittest import numpy as np from transformers import is_tf_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_tf, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, TFLayoutLMvaModel, ) if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class SCREAMING_SNAKE_CASE__ : def __init__( self , lowercase__ , lowercase__=2 , lowercase__=3 , lowercase__=4 , lowercase__=2 , lowercase__=7 , lowercase__=True , lowercase__=True , lowercase__=True , lowercase__=True , lowercase__=99 , lowercase__=36 , lowercase__=2 , lowercase__=4 , lowercase__=37 , lowercase__="gelu" , lowercase__=0.1 , lowercase__=0.1 , lowercase__=512 , lowercase__=16 , lowercase__=2 , lowercase__=0.02 , lowercase__=6 , lowercase__=6 , lowercase__=3 , lowercase__=4 , lowercase__=None , lowercase__=1000 , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = parent SCREAMING_SNAKE_CASE_ : Optional[int] = batch_size SCREAMING_SNAKE_CASE_ : Dict = num_channels SCREAMING_SNAKE_CASE_ : Union[str, Any] = image_size SCREAMING_SNAKE_CASE_ : Optional[int] = patch_size SCREAMING_SNAKE_CASE_ : str = is_training SCREAMING_SNAKE_CASE_ : str = use_input_mask SCREAMING_SNAKE_CASE_ : Any = use_token_type_ids SCREAMING_SNAKE_CASE_ : int = use_labels SCREAMING_SNAKE_CASE_ : Union[str, Any] = vocab_size SCREAMING_SNAKE_CASE_ : Optional[Any] = hidden_size SCREAMING_SNAKE_CASE_ : Dict = num_hidden_layers SCREAMING_SNAKE_CASE_ : Any = num_attention_heads SCREAMING_SNAKE_CASE_ : Optional[Any] = intermediate_size SCREAMING_SNAKE_CASE_ : str = hidden_act SCREAMING_SNAKE_CASE_ : int = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : Tuple = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : Union[str, Any] = max_position_embeddings SCREAMING_SNAKE_CASE_ : Dict = type_vocab_size SCREAMING_SNAKE_CASE_ : List[Any] = type_sequence_label_size SCREAMING_SNAKE_CASE_ : Tuple = initializer_range SCREAMING_SNAKE_CASE_ : List[str] = coordinate_size SCREAMING_SNAKE_CASE_ : Optional[Any] = shape_size SCREAMING_SNAKE_CASE_ : List[str] = num_labels SCREAMING_SNAKE_CASE_ : Optional[int] = num_choices SCREAMING_SNAKE_CASE_ : Union[str, Any] = scope SCREAMING_SNAKE_CASE_ : Dict = 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_ : Union[str, Any] = text_seq_length SCREAMING_SNAKE_CASE_ : Tuple = (image_size // patch_size) ** 2 + 1 SCREAMING_SNAKE_CASE_ : Optional[int] = self.text_seq_length + self.image_seq_length def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE_ : Optional[Any] = ids_tensor([self.batch_size, self.text_seq_length, 4] , self.range_bbox ) SCREAMING_SNAKE_CASE_ : Dict = bbox.numpy() # 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_ : Optional[int] = bbox[i, j, 3] SCREAMING_SNAKE_CASE_ : str = bbox[i, j, 1] SCREAMING_SNAKE_CASE_ : Dict = tmp_coordinate if bbox[i, j, 2] < bbox[i, j, 0]: SCREAMING_SNAKE_CASE_ : List[Any] = bbox[i, j, 2] SCREAMING_SNAKE_CASE_ : Dict = bbox[i, j, 0] SCREAMING_SNAKE_CASE_ : Tuple = tmp_coordinate SCREAMING_SNAKE_CASE_ : Dict = tf.constant(lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE_ : Dict = None if self.use_input_mask: SCREAMING_SNAKE_CASE_ : Any = random_attention_mask([self.batch_size, self.text_seq_length] ) SCREAMING_SNAKE_CASE_ : List[str] = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE_ : Dict = ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE_ : Dict = None SCREAMING_SNAKE_CASE_ : Tuple = None if self.use_labels: SCREAMING_SNAKE_CASE_ : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE_ : List[str] = ids_tensor([self.batch_size, self.text_seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE_ : str = 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 __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = TFLayoutLMvaModel(config=lowercase__ ) # text + image SCREAMING_SNAKE_CASE_ : int = model(lowercase__ , pixel_values=lowercase__ , training=lowercase__ ) SCREAMING_SNAKE_CASE_ : str = model( lowercase__ , bbox=lowercase__ , pixel_values=lowercase__ , attention_mask=lowercase__ , token_type_ids=lowercase__ , training=lowercase__ , ) SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase__ , bbox=lowercase__ , pixel_values=lowercase__ , training=lowercase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # text only SCREAMING_SNAKE_CASE_ : Tuple = model(lowercase__ , training=lowercase__ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size) ) # image only SCREAMING_SNAKE_CASE_ : int = model({"pixel_values": pixel_values} , training=lowercase__ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size) ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = self.num_labels SCREAMING_SNAKE_CASE_ : Union[str, Any] = TFLayoutLMvaForSequenceClassification(config=lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = model( lowercase__ , bbox=lowercase__ , pixel_values=lowercase__ , attention_mask=lowercase__ , token_type_ids=lowercase__ , labels=lowercase__ , training=lowercase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.num_labels SCREAMING_SNAKE_CASE_ : Any = TFLayoutLMvaForTokenClassification(config=lowercase__ ) SCREAMING_SNAKE_CASE_ : int = model( lowercase__ , bbox=lowercase__ , pixel_values=lowercase__ , attention_mask=lowercase__ , token_type_ids=lowercase__ , labels=lowercase__ , training=lowercase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels) ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = 2 SCREAMING_SNAKE_CASE_ : List[Any] = TFLayoutLMvaForQuestionAnswering(config=lowercase__ ) SCREAMING_SNAKE_CASE_ : int = model( lowercase__ , bbox=lowercase__ , pixel_values=lowercase__ , attention_mask=lowercase__ , token_type_ids=lowercase__ , start_positions=lowercase__ , end_positions=lowercase__ , training=lowercase__ , ) 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 __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = 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_)) : Any = config_and_inputs SCREAMING_SNAKE_CASE_ : Optional[Any] = { "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_tf class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,_UpperCAmelCase,unittest.TestCase ): _A = ( ( TFLayoutLMvaModel, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, ) if is_tf_available() else () ) _A = ( {"document-question-answering": TFLayoutLMvaForQuestionAnswering, "feature-extraction": TFLayoutLMvaModel} if is_tf_available() else {} ) _A = False _A = False _A = False def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" return True def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__=False ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = copy.deepcopy(lowercase__ ) if model_class in get_values(lowercase__ ): SCREAMING_SNAKE_CASE_ : str = { k: tf.tile(tf.expand_dims(lowercase__ , 1 ) , (1, self.model_tester.num_choices) + (1,) * (v.ndim - 1) ) if isinstance(lowercase__ , tf.Tensor ) and v.ndim > 0 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(lowercase__ ): SCREAMING_SNAKE_CASE_ : Tuple = tf.ones(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(lowercase__ ): SCREAMING_SNAKE_CASE_ : Any = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) SCREAMING_SNAKE_CASE_ : List[Any] = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(lowercase__ ): SCREAMING_SNAKE_CASE_ : List[str] = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(lowercase__ ): SCREAMING_SNAKE_CASE_ : Optional[Any] = tf.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=tf.intaa ) return inputs_dict def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = TFLayoutLMvaModelTester(self ) SCREAMING_SNAKE_CASE_ : int = ConfigTester(self , config_class=lowercase__ , hidden_size=37 ) def __lowerCamelCase ( self ): """simple docstring""" self.config_tester.run_common_tests() def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ : int = model_class(lowercase__ ) if getattr(lowercase__ , "hf_compute_loss" , lowercase__ ): # The number of elements in the loss should be the same as the number of elements in the label SCREAMING_SNAKE_CASE_ : Dict = self._prepare_for_class(inputs_dict.copy() , lowercase__ , return_labels=lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = prepared_for_class[ sorted(prepared_for_class.keys() - inputs_dict.keys() , reverse=lowercase__ )[0] ] SCREAMING_SNAKE_CASE_ : Any = added_label.shape.as_list()[:1] # Test that model correctly compute the loss with kwargs SCREAMING_SNAKE_CASE_ : Dict = self._prepare_for_class(inputs_dict.copy() , lowercase__ , return_labels=lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = prepared_for_class.pop("input_ids" ) SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase__ , **lowercase__ )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss when we mask some positions SCREAMING_SNAKE_CASE_ : List[Any] = self._prepare_for_class(inputs_dict.copy() , lowercase__ , return_labels=lowercase__ ) SCREAMING_SNAKE_CASE_ : int = prepared_for_class.pop("input_ids" ) if "labels" in prepared_for_class: SCREAMING_SNAKE_CASE_ : str = prepared_for_class["labels"].numpy() if len(labels.shape ) > 1 and labels.shape[1] != 1: SCREAMING_SNAKE_CASE_ : str = -100 SCREAMING_SNAKE_CASE_ : str = tf.convert_to_tensor(lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = model(lowercase__ , **lowercase__ )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) self.assertTrue(not np.any(np.isnan(loss.numpy() ) ) ) # Test that model correctly compute the loss with a dict SCREAMING_SNAKE_CASE_ : List[Any] = self._prepare_for_class(inputs_dict.copy() , lowercase__ , return_labels=lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = model(lowercase__ )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss with a tuple SCREAMING_SNAKE_CASE_ : Optional[Any] = self._prepare_for_class(inputs_dict.copy() , lowercase__ , return_labels=lowercase__ ) # Get keys that were added with the _prepare_for_class function SCREAMING_SNAKE_CASE_ : int = prepared_for_class.keys() - inputs_dict.keys() SCREAMING_SNAKE_CASE_ : Optional[int] = inspect.signature(model.call ).parameters SCREAMING_SNAKE_CASE_ : Tuple = list(signature.keys() ) # Create a dictionary holding the location of the tensors in the tuple SCREAMING_SNAKE_CASE_ : List[Any] = {0: "input_ids"} for label_key in label_keys: SCREAMING_SNAKE_CASE_ : Optional[int] = signature_names.index(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = label_key SCREAMING_SNAKE_CASE_ : List[str] = sorted(tuple_index_mapping.items() ) # Initialize a list with their default values, update the values and convert to a tuple SCREAMING_SNAKE_CASE_ : List[str] = [] for name in signature_names: if name != "kwargs": list_input.append(signature[name].default ) for index, value in sorted_tuple_index_mapping: SCREAMING_SNAKE_CASE_ : List[str] = prepared_for_class[value] SCREAMING_SNAKE_CASE_ : List[Any] = tuple(lowercase__ ) # Send to model SCREAMING_SNAKE_CASE_ : int = model(tuple_input[:-1] )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) def __lowerCamelCase ( self ): """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_ ), ) : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) def __lowerCamelCase ( self ): """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_ ), ) : Optional[Any] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE_ : List[str] = type self.model_tester.create_and_check_model(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) def __lowerCamelCase ( self ): """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_ ), ) : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) def __lowerCamelCase ( self ): """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_ ), ) : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) def __lowerCamelCase ( self ): """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_ ), ) : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) @slow def __lowerCamelCase ( self ): """simple docstring""" for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE_ : Union[str, Any] = TFLayoutLMvaModel.from_pretrained(lowercase__ ) self.assertIsNotNone(lowercase__ ) def __lowerCamelCase ( ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : str = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_tf class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): @cached_property def __lowerCamelCase ( self ): """simple docstring""" return LayoutLMvaImageProcessor(apply_ocr=lowercase__ ) if is_vision_available() else None @slow def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = TFLayoutLMvaModel.from_pretrained("microsoft/layoutlmv3-base" ) SCREAMING_SNAKE_CASE_ : Any = self.default_image_processor SCREAMING_SNAKE_CASE_ : Optional[int] = prepare_img() SCREAMING_SNAKE_CASE_ : Optional[Any] = image_processor(images=lowercase__ , return_tensors="tf" ).pixel_values SCREAMING_SNAKE_CASE_ : Dict = tf.constant([[1, 2]] ) SCREAMING_SNAKE_CASE_ : Any = tf.expand_dims(tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]] ) , axis=0 ) # forward pass SCREAMING_SNAKE_CASE_ : List[Any] = model(input_ids=lowercase__ , bbox=lowercase__ , pixel_values=lowercase__ , training=lowercase__ ) # verify the logits SCREAMING_SNAKE_CASE_ : Tuple = (1, 199, 768) self.assertEqual(outputs.last_hidden_state.shape , lowercase__ ) SCREAMING_SNAKE_CASE_ : int = tf.constant( [[-0.0529, 0.3618, 0.1632], [-0.1587, -0.1667, -0.0400], [-0.1557, -0.1671, -0.0505]] ) self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3] , lowercase__ , atol=1e-4 ) )
68
1
'''simple docstring''' from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ShapEPipeline else: from .camera import create_pan_cameras from .pipeline_shap_e import ShapEPipeline from .pipeline_shap_e_img2img import ShapEImgaImgPipeline from .renderer import ( BoundingBoxVolume, ImportanceRaySampler, MLPNeRFModelOutput, MLPNeRSTFModel, ShapEParamsProjModel, ShapERenderer, StratifiedRaySampler, VoidNeRFModel, )
68
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Tuple ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = [1] for i in range(2 , SCREAMING_SNAKE_CASE_ ): factorials.append(factorials[-1] * i ) assert 0 <= k < factorials[-1] * n, "k out of bounds" SCREAMING_SNAKE_CASE_ : Union[str, Any] = [] SCREAMING_SNAKE_CASE_ : Dict = list(range(SCREAMING_SNAKE_CASE_ ) ) # Find permutation while factorials: SCREAMING_SNAKE_CASE_ : Any = factorials.pop() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[int] = divmod(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) permutation.append(elements[number] ) elements.remove(elements[number] ) permutation.append(elements[0] ) return permutation if __name__ == "__main__": import doctest doctest.testmod()
68
1
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str ) -> list: """simple docstring""" return [ txt[:a] + txt[a].upper() + txt[a + 1 :] for a in range(len(SCREAMING_SNAKE_CASE_ ) ) if txt[a].isalpha() ] if __name__ == "__main__": __import__('doctest').testmod()
68
'''simple docstring''' import argparse from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_controlnet_from_original_ckpt if __name__ == "__main__": snake_case_ = argparse.ArgumentParser() parser.add_argument( '--checkpoint_path', default=None, type=str, required=True, help='Path to the checkpoint to convert.' ) parser.add_argument( '--original_config_file', type=str, required=True, help='The YAML config file corresponding to the original architecture.', ) parser.add_argument( '--num_in_channels', default=None, type=int, help='The number of input channels. If `None` number of input channels will be automatically inferred.', ) parser.add_argument( '--image_size', default=5_1_2, type=int, help=( 'The image size that the model was trained on. Use 512 for Stable Diffusion v1.X and Stable Siffusion v2' ' Base. Use 768 for Stable Diffusion v2.' ), ) parser.add_argument( '--extract_ema', action='store_true', help=( 'Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights' ' or not. Defaults to `False`. Add `--extract_ema` to extract the EMA weights. EMA weights usually yield' ' higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning.' ), ) parser.add_argument( '--upcast_attention', action='store_true', help=( 'Whether the attention computation should always be upcasted. This is necessary when running stable' ' diffusion 2.1.' ), ) parser.add_argument( '--from_safetensors', action='store_true', help='If `--checkpoint_path` is in `safetensors` format, load checkpoint with safetensors instead of PyTorch.', ) parser.add_argument( '--to_safetensors', action='store_true', help='Whether to store pipeline in safetensors format or not.', ) parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.') parser.add_argument('--device', type=str, help='Device to use (e.g. cpu, cuda:0, cuda:1, etc.)') def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Optional[int] ) -> Dict: """simple docstring""" if string == "True": return True elif string == "False": return False else: raise ValueError(F"could not parse string as bool {string}" ) parser.add_argument( '--use_linear_projection', help='Override for use linear projection', required=False, type=parse_bool ) parser.add_argument('--cross_attention_dim', help='Override for cross attention_dim', required=False, type=int) snake_case_ = parser.parse_args() snake_case_ = download_controlnet_from_original_ckpt( checkpoint_path=args.checkpoint_path, original_config_file=args.original_config_file, image_size=args.image_size, extract_ema=args.extract_ema, num_in_channels=args.num_in_channels, upcast_attention=args.upcast_attention, from_safetensors=args.from_safetensors, device=args.device, use_linear_projection=args.use_linear_projection, cross_attention_dim=args.cross_attention_dim, ) controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
68
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 if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ChineseCLIPImageProcessor class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __init__( self , lowercase__ , lowercase__=7 , lowercase__=3 , lowercase__=18 , lowercase__=30 , lowercase__=400 , lowercase__=True , lowercase__=None , lowercase__=True , lowercase__=None , lowercase__=True , lowercase__=[0.48145466, 0.4578275, 0.40821073] , lowercase__=[0.26862954, 0.26130258, 0.27577711] , lowercase__=True , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = size if size is not None else {"height": 224, "width": 224} SCREAMING_SNAKE_CASE_ : Optional[Any] = crop_size if crop_size is not None else {"height": 18, "width": 18} SCREAMING_SNAKE_CASE_ : str = parent SCREAMING_SNAKE_CASE_ : List[Any] = batch_size SCREAMING_SNAKE_CASE_ : Dict = num_channels SCREAMING_SNAKE_CASE_ : Any = image_size SCREAMING_SNAKE_CASE_ : Tuple = min_resolution SCREAMING_SNAKE_CASE_ : Optional[Any] = max_resolution SCREAMING_SNAKE_CASE_ : Tuple = do_resize SCREAMING_SNAKE_CASE_ : List[str] = size SCREAMING_SNAKE_CASE_ : str = do_center_crop SCREAMING_SNAKE_CASE_ : List[str] = crop_size SCREAMING_SNAKE_CASE_ : int = do_normalize SCREAMING_SNAKE_CASE_ : Optional[int] = image_mean SCREAMING_SNAKE_CASE_ : Dict = image_std SCREAMING_SNAKE_CASE_ : List[Any] = do_convert_rgb def __lowerCamelCase ( self ): """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_convert_rgb": self.do_convert_rgb, } def __lowerCamelCase ( self , lowercase__=False , lowercase__=False , lowercase__=False ): """simple docstring""" assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time" if equal_resolution: SCREAMING_SNAKE_CASE_ : Optional[int] = [] for i in range(self.batch_size ): image_inputs.append( np.random.randint( 255 , size=(self.num_channels, self.max_resolution, self.max_resolution) , dtype=np.uinta ) ) else: SCREAMING_SNAKE_CASE_ : str = [] for i in range(self.batch_size ): SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[Any] = np.random.choice(np.arange(self.min_resolution , self.max_resolution ) , 2 ) image_inputs.append(np.random.randint(255 , size=(self.num_channels, width, height) , dtype=np.uinta ) ) if not numpify and not torchify: # PIL expects the channel dimension as last dimension SCREAMING_SNAKE_CASE_ : str = [Image.fromarray(np.moveaxis(lowercase__ , 0 , -1 ) ) for x in image_inputs] if torchify: SCREAMING_SNAKE_CASE_ : List[str] = [torch.from_numpy(lowercase__ ) for x in image_inputs] return image_inputs @require_torch @require_vision class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,unittest.TestCase ): _A = ChineseCLIPImageProcessor if is_vision_available() else None def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = ChineseCLIPImageProcessingTester(self , do_center_crop=lowercase__ ) @property def __lowerCamelCase ( self ): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowercase__ , "do_resize" ) ) self.assertTrue(hasattr(lowercase__ , "size" ) ) self.assertTrue(hasattr(lowercase__ , "do_center_crop" ) ) self.assertTrue(hasattr(lowercase__ , "center_crop" ) ) self.assertTrue(hasattr(lowercase__ , "do_normalize" ) ) self.assertTrue(hasattr(lowercase__ , "image_mean" ) ) self.assertTrue(hasattr(lowercase__ , "image_std" ) ) self.assertTrue(hasattr(lowercase__ , "do_convert_rgb" ) ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"height": 224, "width": 224} ) self.assertEqual(image_processor.crop_size , {"height": 18, "width": 18} ) SCREAMING_SNAKE_CASE_ : str = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 ) self.assertEqual(image_processor.size , {"shortest_edge": 42} ) self.assertEqual(image_processor.crop_size , {"height": 84, "width": 84} ) def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE_ : Tuple = self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__ ) for image in image_inputs: self.assertIsInstance(lowercase__ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE_ : Dict = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE_ : Optional[int] = image_processing(lowercase__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__ , numpify=lowercase__ ) for image in image_inputs: self.assertIsInstance(lowercase__ , np.ndarray ) # Test not batched input SCREAMING_SNAKE_CASE_ : Optional[int] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE_ : List[str] = image_processing(lowercase__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors SCREAMING_SNAKE_CASE_ : List[str] = self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__ , torchify=lowercase__ ) for image in image_inputs: self.assertIsInstance(lowercase__ , torch.Tensor ) # Test not batched input SCREAMING_SNAKE_CASE_ : Union[str, Any] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE_ : int = image_processing(lowercase__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) @require_torch @require_vision class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,unittest.TestCase ): _A = ChineseCLIPImageProcessor if is_vision_available() else None def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int = ChineseCLIPImageProcessingTester(self , num_channels=4 , do_center_crop=lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = 3 @property def __lowerCamelCase ( self ): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowercase__ , "do_resize" ) ) self.assertTrue(hasattr(lowercase__ , "size" ) ) self.assertTrue(hasattr(lowercase__ , "do_center_crop" ) ) self.assertTrue(hasattr(lowercase__ , "center_crop" ) ) self.assertTrue(hasattr(lowercase__ , "do_normalize" ) ) self.assertTrue(hasattr(lowercase__ , "image_mean" ) ) self.assertTrue(hasattr(lowercase__ , "image_std" ) ) self.assertTrue(hasattr(lowercase__ , "do_convert_rgb" ) ) def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE_ : Optional[int] = self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__ ) for image in image_inputs: self.assertIsInstance(lowercase__ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE_ : Optional[Any] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE_ : List[str] = image_processing(lowercase__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , )
68
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging snake_case_ = logging.get_logger(__name__) snake_case_ = { 'camembert-base': 'https://huggingface.co/camembert-base/resolve/main/config.json', 'umberto-commoncrawl-cased-v1': ( 'https://huggingface.co/Musixmatch/umberto-commoncrawl-cased-v1/resolve/main/config.json' ), 'umberto-wikipedia-uncased-v1': ( 'https://huggingface.co/Musixmatch/umberto-wikipedia-uncased-v1/resolve/main/config.json' ), } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = "camembert" def __init__( self , lowercase__=3_0522 , lowercase__=768 , lowercase__=12 , lowercase__=12 , lowercase__=3072 , lowercase__="gelu" , lowercase__=0.1 , lowercase__=0.1 , lowercase__=512 , lowercase__=2 , lowercase__=0.02 , lowercase__=1e-12 , lowercase__=1 , lowercase__=0 , lowercase__=2 , lowercase__="absolute" , lowercase__=True , lowercase__=None , **lowercase__ , ): """simple docstring""" super().__init__(pad_token_id=lowercase__ , bos_token_id=lowercase__ , eos_token_id=lowercase__ , **lowercase__ ) SCREAMING_SNAKE_CASE_ : Tuple = vocab_size SCREAMING_SNAKE_CASE_ : str = hidden_size SCREAMING_SNAKE_CASE_ : str = num_hidden_layers SCREAMING_SNAKE_CASE_ : Dict = num_attention_heads SCREAMING_SNAKE_CASE_ : Any = hidden_act SCREAMING_SNAKE_CASE_ : Optional[int] = intermediate_size SCREAMING_SNAKE_CASE_ : Optional[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : List[str] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : Optional[Any] = max_position_embeddings SCREAMING_SNAKE_CASE_ : List[str] = type_vocab_size SCREAMING_SNAKE_CASE_ : Tuple = initializer_range SCREAMING_SNAKE_CASE_ : List[Any] = layer_norm_eps SCREAMING_SNAKE_CASE_ : List[Any] = position_embedding_type SCREAMING_SNAKE_CASE_ : Any = use_cache SCREAMING_SNAKE_CASE_ : Optional[int] = classifier_dropout class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): @property def __lowerCamelCase ( self ): """simple docstring""" if self.task == "multiple-choice": SCREAMING_SNAKE_CASE_ : Optional[int] = {0: "batch", 1: "choice", 2: "sequence"} else: SCREAMING_SNAKE_CASE_ : Any = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
68
1
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging snake_case_ = logging.get_logger(__name__) snake_case_ = { 'facebook/xmod-base': 'https://huggingface.co/facebook/xmod-base/resolve/main/config.json', 'facebook/xmod-large-prenorm': 'https://huggingface.co/facebook/xmod-large-prenorm/resolve/main/config.json', 'facebook/xmod-base-13-125k': 'https://huggingface.co/facebook/xmod-base-13-125k/resolve/main/config.json', 'facebook/xmod-base-30-125k': 'https://huggingface.co/facebook/xmod-base-30-125k/resolve/main/config.json', 'facebook/xmod-base-30-195k': 'https://huggingface.co/facebook/xmod-base-30-195k/resolve/main/config.json', 'facebook/xmod-base-60-125k': 'https://huggingface.co/facebook/xmod-base-60-125k/resolve/main/config.json', 'facebook/xmod-base-60-265k': 'https://huggingface.co/facebook/xmod-base-60-265k/resolve/main/config.json', 'facebook/xmod-base-75-125k': 'https://huggingface.co/facebook/xmod-base-75-125k/resolve/main/config.json', 'facebook/xmod-base-75-269k': 'https://huggingface.co/facebook/xmod-base-75-269k/resolve/main/config.json', } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = "xmod" def __init__( self , lowercase__=3_0522 , lowercase__=768 , lowercase__=12 , lowercase__=12 , lowercase__=3072 , lowercase__="gelu" , lowercase__=0.1 , lowercase__=0.1 , lowercase__=512 , lowercase__=2 , lowercase__=0.02 , lowercase__=1e-12 , lowercase__=1 , lowercase__=0 , lowercase__=2 , lowercase__="absolute" , lowercase__=True , lowercase__=None , lowercase__=False , lowercase__=2 , lowercase__=False , lowercase__=True , lowercase__=True , lowercase__=("en_XX",) , lowercase__=None , **lowercase__ , ): """simple docstring""" super().__init__(pad_token_id=lowercase__ , bos_token_id=lowercase__ , eos_token_id=lowercase__ , **lowercase__ ) SCREAMING_SNAKE_CASE_ : Tuple = vocab_size SCREAMING_SNAKE_CASE_ : Optional[Any] = hidden_size SCREAMING_SNAKE_CASE_ : Tuple = num_hidden_layers SCREAMING_SNAKE_CASE_ : Optional[int] = num_attention_heads SCREAMING_SNAKE_CASE_ : List[str] = hidden_act SCREAMING_SNAKE_CASE_ : Optional[int] = intermediate_size SCREAMING_SNAKE_CASE_ : Tuple = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : int = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE_ : Dict = type_vocab_size SCREAMING_SNAKE_CASE_ : str = initializer_range SCREAMING_SNAKE_CASE_ : List[str] = layer_norm_eps SCREAMING_SNAKE_CASE_ : Tuple = position_embedding_type SCREAMING_SNAKE_CASE_ : str = use_cache SCREAMING_SNAKE_CASE_ : Optional[int] = classifier_dropout SCREAMING_SNAKE_CASE_ : int = pre_norm SCREAMING_SNAKE_CASE_ : Optional[int] = adapter_reduction_factor SCREAMING_SNAKE_CASE_ : List[str] = adapter_layer_norm SCREAMING_SNAKE_CASE_ : List[str] = adapter_reuse_layer_norm SCREAMING_SNAKE_CASE_ : int = ln_before_adapter SCREAMING_SNAKE_CASE_ : List[Any] = list(lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = default_language class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): @property def __lowerCamelCase ( self ): """simple docstring""" if self.task == "multiple-choice": SCREAMING_SNAKE_CASE_ : Tuple = {0: "batch", 1: "choice", 2: "sequence"} else: SCREAMING_SNAKE_CASE_ : Optional[int] = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
68
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : list[int] ) -> list[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = len(SCREAMING_SNAKE_CASE_ ) for i in range(SCREAMING_SNAKE_CASE_ ): for j in range(i + 1 , SCREAMING_SNAKE_CASE_ ): if numbers[j] < numbers[i]: SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Tuple = numbers[j], numbers[i] return numbers if __name__ == "__main__": snake_case_ = input('Enter numbers separated by a comma:\n').strip() snake_case_ = [int(item) for item in user_input.split(',')] print(exchange_sort(unsorted))
68
1
'''simple docstring''' import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DetrConfig, DetrForObjectDetection, DetrForSegmentation, DetrImageProcessor, ResNetConfig from transformers.utils import logging logging.set_verbosity_info() snake_case_ = logging.get_logger(__name__) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : List[Any] ) -> List[Any]: """simple docstring""" if "resnet-50" in model_name: SCREAMING_SNAKE_CASE_ : Union[str, Any] = ResNetConfig.from_pretrained("microsoft/resnet-50" ) elif "resnet-101" in model_name: SCREAMING_SNAKE_CASE_ : Dict = ResNetConfig.from_pretrained("microsoft/resnet-101" ) else: raise ValueError("Model name should include either resnet50 or resnet101" ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = DetrConfig(use_timm_backbone=SCREAMING_SNAKE_CASE_ , backbone_config=SCREAMING_SNAKE_CASE_ ) # set label attributes SCREAMING_SNAKE_CASE_ : Union[str, Any] = "panoptic" in model_name if is_panoptic: SCREAMING_SNAKE_CASE_ : Union[str, Any] = 2_5_0 else: SCREAMING_SNAKE_CASE_ : Optional[int] = 9_1 SCREAMING_SNAKE_CASE_ : Union[str, Any] = "huggingface/label-files" SCREAMING_SNAKE_CASE_ : Dict = "coco-detection-id2label.json" SCREAMING_SNAKE_CASE_ : Dict = json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , repo_type="dataset" ) , "r" ) ) SCREAMING_SNAKE_CASE_ : Dict = {int(SCREAMING_SNAKE_CASE_ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE_ : int = idalabel SCREAMING_SNAKE_CASE_ : str = {v: k for k, v in idalabel.items()} return config, is_panoptic def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : List[Any] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = [] # stem # fmt: off rename_keys.append(("backbone.0.body.conv1.weight", "backbone.conv_encoder.model.embedder.embedder.convolution.weight") ) rename_keys.append(("backbone.0.body.bn1.weight", "backbone.conv_encoder.model.embedder.embedder.normalization.weight") ) rename_keys.append(("backbone.0.body.bn1.bias", "backbone.conv_encoder.model.embedder.embedder.normalization.bias") ) rename_keys.append(("backbone.0.body.bn1.running_mean", "backbone.conv_encoder.model.embedder.embedder.normalization.running_mean") ) rename_keys.append(("backbone.0.body.bn1.running_var", "backbone.conv_encoder.model.embedder.embedder.normalization.running_var") ) # stages for stage_idx in range(len(config.backbone_config.depths ) ): for layer_idx in range(config.backbone_config.depths[stage_idx] ): # shortcut if layer_idx == 0: rename_keys.append( ( F"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.0.weight", F"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.convolution.weight", ) ) rename_keys.append( ( F"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.weight", F"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.weight", ) ) rename_keys.append( ( F"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.bias", F"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.bias", ) ) rename_keys.append( ( F"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.running_mean", F"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.running_mean", ) ) rename_keys.append( ( F"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.running_var", F"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.running_var", ) ) # 3 convs for i in range(3 ): rename_keys.append( ( F"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.conv{i+1}.weight", F"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.convolution.weight", ) ) rename_keys.append( ( F"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.weight", F"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.weight", ) ) rename_keys.append( ( F"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.bias", F"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.bias", ) ) rename_keys.append( ( F"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.running_mean", F"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.running_mean", ) ) rename_keys.append( ( F"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.running_var", F"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.running_var", ) ) # fmt: on for i in range(config.encoder_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append( ( F"transformer.encoder.layers.{i}.self_attn.out_proj.weight", F"encoder.layers.{i}.self_attn.out_proj.weight", ) ) rename_keys.append( (F"transformer.encoder.layers.{i}.self_attn.out_proj.bias", F"encoder.layers.{i}.self_attn.out_proj.bias") ) rename_keys.append((F"transformer.encoder.layers.{i}.linear1.weight", F"encoder.layers.{i}.fc1.weight") ) rename_keys.append((F"transformer.encoder.layers.{i}.linear1.bias", F"encoder.layers.{i}.fc1.bias") ) rename_keys.append((F"transformer.encoder.layers.{i}.linear2.weight", F"encoder.layers.{i}.fc2.weight") ) rename_keys.append((F"transformer.encoder.layers.{i}.linear2.bias", F"encoder.layers.{i}.fc2.bias") ) rename_keys.append( (F"transformer.encoder.layers.{i}.norm1.weight", F"encoder.layers.{i}.self_attn_layer_norm.weight") ) rename_keys.append( (F"transformer.encoder.layers.{i}.norm1.bias", F"encoder.layers.{i}.self_attn_layer_norm.bias") ) rename_keys.append( (F"transformer.encoder.layers.{i}.norm2.weight", F"encoder.layers.{i}.final_layer_norm.weight") ) rename_keys.append((F"transformer.encoder.layers.{i}.norm2.bias", F"encoder.layers.{i}.final_layer_norm.bias") ) # decoder layers: 2 times output projection, 2 feedforward neural networks and 3 layernorms rename_keys.append( ( F"transformer.decoder.layers.{i}.self_attn.out_proj.weight", F"decoder.layers.{i}.self_attn.out_proj.weight", ) ) rename_keys.append( (F"transformer.decoder.layers.{i}.self_attn.out_proj.bias", F"decoder.layers.{i}.self_attn.out_proj.bias") ) rename_keys.append( ( F"transformer.decoder.layers.{i}.multihead_attn.out_proj.weight", F"decoder.layers.{i}.encoder_attn.out_proj.weight", ) ) rename_keys.append( ( F"transformer.decoder.layers.{i}.multihead_attn.out_proj.bias", F"decoder.layers.{i}.encoder_attn.out_proj.bias", ) ) rename_keys.append((F"transformer.decoder.layers.{i}.linear1.weight", F"decoder.layers.{i}.fc1.weight") ) rename_keys.append((F"transformer.decoder.layers.{i}.linear1.bias", F"decoder.layers.{i}.fc1.bias") ) rename_keys.append((F"transformer.decoder.layers.{i}.linear2.weight", F"decoder.layers.{i}.fc2.weight") ) rename_keys.append((F"transformer.decoder.layers.{i}.linear2.bias", F"decoder.layers.{i}.fc2.bias") ) rename_keys.append( (F"transformer.decoder.layers.{i}.norm1.weight", F"decoder.layers.{i}.self_attn_layer_norm.weight") ) rename_keys.append( (F"transformer.decoder.layers.{i}.norm1.bias", F"decoder.layers.{i}.self_attn_layer_norm.bias") ) rename_keys.append( (F"transformer.decoder.layers.{i}.norm2.weight", F"decoder.layers.{i}.encoder_attn_layer_norm.weight") ) rename_keys.append( (F"transformer.decoder.layers.{i}.norm2.bias", F"decoder.layers.{i}.encoder_attn_layer_norm.bias") ) rename_keys.append( (F"transformer.decoder.layers.{i}.norm3.weight", F"decoder.layers.{i}.final_layer_norm.weight") ) rename_keys.append((F"transformer.decoder.layers.{i}.norm3.bias", F"decoder.layers.{i}.final_layer_norm.bias") ) # convolutional projection + query embeddings + layernorm of decoder + class and bounding box heads rename_keys.extend( [ ("input_proj.weight", "input_projection.weight"), ("input_proj.bias", "input_projection.bias"), ("query_embed.weight", "query_position_embeddings.weight"), ("transformer.decoder.norm.weight", "decoder.layernorm.weight"), ("transformer.decoder.norm.bias", "decoder.layernorm.bias"), ("class_embed.weight", "class_labels_classifier.weight"), ("class_embed.bias", "class_labels_classifier.bias"), ("bbox_embed.layers.0.weight", "bbox_predictor.layers.0.weight"), ("bbox_embed.layers.0.bias", "bbox_predictor.layers.0.bias"), ("bbox_embed.layers.1.weight", "bbox_predictor.layers.1.weight"), ("bbox_embed.layers.1.bias", "bbox_predictor.layers.1.bias"), ("bbox_embed.layers.2.weight", "bbox_predictor.layers.2.weight"), ("bbox_embed.layers.2.bias", "bbox_predictor.layers.2.bias"), ] ) return rename_keys def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : str ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE_ : str = state_dict.pop(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : List[Any] = val def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : str=False ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = "" if is_panoptic: SCREAMING_SNAKE_CASE_ : Tuple = "detr." # first: transformer encoder for i in range(6 ): # read in weights + bias of input projection layer (in PyTorch's MultiHeadAttention, this is a single matrix + bias) SCREAMING_SNAKE_CASE_ : int = state_dict.pop(F"{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight" ) SCREAMING_SNAKE_CASE_ : Any = state_dict.pop(F"{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_bias" ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE_ : List[Any] = in_proj_weight[:2_5_6, :] SCREAMING_SNAKE_CASE_ : Dict = in_proj_bias[:2_5_6] SCREAMING_SNAKE_CASE_ : Tuple = in_proj_weight[2_5_6:5_1_2, :] SCREAMING_SNAKE_CASE_ : Any = in_proj_bias[2_5_6:5_1_2] SCREAMING_SNAKE_CASE_ : Optional[Any] = in_proj_weight[-2_5_6:, :] SCREAMING_SNAKE_CASE_ : Union[str, Any] = in_proj_bias[-2_5_6:] # next: transformer decoder (which is a bit more complex because it also includes cross-attention) for i in range(6 ): # read in weights + bias of input projection layer of self-attention SCREAMING_SNAKE_CASE_ : Dict = state_dict.pop(F"{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_weight" ) SCREAMING_SNAKE_CASE_ : Optional[int] = state_dict.pop(F"{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_bias" ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE_ : Any = in_proj_weight[:2_5_6, :] SCREAMING_SNAKE_CASE_ : int = in_proj_bias[:2_5_6] SCREAMING_SNAKE_CASE_ : List[str] = in_proj_weight[2_5_6:5_1_2, :] SCREAMING_SNAKE_CASE_ : Optional[int] = in_proj_bias[2_5_6:5_1_2] SCREAMING_SNAKE_CASE_ : Tuple = in_proj_weight[-2_5_6:, :] SCREAMING_SNAKE_CASE_ : Union[str, Any] = in_proj_bias[-2_5_6:] # read in weights + bias of input projection layer of cross-attention SCREAMING_SNAKE_CASE_ : Dict = state_dict.pop( F"{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_weight" ) SCREAMING_SNAKE_CASE_ : Optional[Any] = state_dict.pop(F"{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_bias" ) # next, add query, keys and values (in that order) of cross-attention to the state dict SCREAMING_SNAKE_CASE_ : int = in_proj_weight_cross_attn[:2_5_6, :] SCREAMING_SNAKE_CASE_ : Tuple = in_proj_bias_cross_attn[:2_5_6] SCREAMING_SNAKE_CASE_ : Dict = in_proj_weight_cross_attn[2_5_6:5_1_2, :] SCREAMING_SNAKE_CASE_ : List[str] = in_proj_bias_cross_attn[2_5_6:5_1_2] SCREAMING_SNAKE_CASE_ : Optional[int] = in_proj_weight_cross_attn[-2_5_6:, :] SCREAMING_SNAKE_CASE_ : Optional[Any] = in_proj_bias_cross_attn[-2_5_6:] def __lowerCamelCase ( ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : int = "http://images.cocodataset.org/val2017/000000039769.jpg" SCREAMING_SNAKE_CASE_ : Union[str, Any] = Image.open(requests.get(SCREAMING_SNAKE_CASE_ , stream=SCREAMING_SNAKE_CASE_ ).raw ) return im @torch.no_grad() def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : List[Any]=None , SCREAMING_SNAKE_CASE_ : Union[str, Any]=False ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : List[Any] = get_detr_config(SCREAMING_SNAKE_CASE_ ) # load original model from torch hub SCREAMING_SNAKE_CASE_ : Tuple = { "detr-resnet-50": "detr_resnet50", "detr-resnet-101": "detr_resnet101", } logger.info(F"Converting model {model_name}..." ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.hub.load("facebookresearch/detr" , model_name_to_original_name[model_name] , pretrained=SCREAMING_SNAKE_CASE_ ).eval() SCREAMING_SNAKE_CASE_ : List[str] = detr.state_dict() # rename keys for src, dest in create_rename_keys(SCREAMING_SNAKE_CASE_ ): if is_panoptic: SCREAMING_SNAKE_CASE_ : Dict = "detr." + src rename_key(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # query, key and value matrices need special treatment read_in_q_k_v(SCREAMING_SNAKE_CASE_ , is_panoptic=SCREAMING_SNAKE_CASE_ ) # important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them SCREAMING_SNAKE_CASE_ : Optional[int] = "detr.model." if is_panoptic else "model." for key in state_dict.copy().keys(): if is_panoptic: if ( key.startswith("detr" ) and not key.startswith("class_labels_classifier" ) and not key.startswith("bbox_predictor" ) ): SCREAMING_SNAKE_CASE_ : Optional[int] = state_dict.pop(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = val elif "class_labels_classifier" in key or "bbox_predictor" in key: SCREAMING_SNAKE_CASE_ : str = state_dict.pop(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : List[str] = val elif key.startswith("bbox_attention" ) or key.startswith("mask_head" ): continue else: SCREAMING_SNAKE_CASE_ : List[str] = state_dict.pop(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : int = val else: if not key.startswith("class_labels_classifier" ) and not key.startswith("bbox_predictor" ): SCREAMING_SNAKE_CASE_ : List[Any] = state_dict.pop(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Optional[int] = val # finally, create HuggingFace model and load state dict SCREAMING_SNAKE_CASE_ : Tuple = DetrForSegmentation(SCREAMING_SNAKE_CASE_ ) if is_panoptic else DetrForObjectDetection(SCREAMING_SNAKE_CASE_ ) model.load_state_dict(SCREAMING_SNAKE_CASE_ ) model.eval() # verify our conversion on an image SCREAMING_SNAKE_CASE_ : List[Any] = "coco_panoptic" if is_panoptic else "coco_detection" SCREAMING_SNAKE_CASE_ : Optional[Any] = DetrImageProcessor(format=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Any = processor(images=prepare_img() , return_tensors="pt" ) SCREAMING_SNAKE_CASE_ : Dict = encoding["pixel_values"] SCREAMING_SNAKE_CASE_ : List[str] = detr(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Tuple = model(SCREAMING_SNAKE_CASE_ ) assert torch.allclose(outputs.logits , original_outputs["pred_logits"] , atol=1E-3 ) assert torch.allclose(outputs.pred_boxes , original_outputs["pred_boxes"] , atol=1E-3 ) if is_panoptic: assert torch.allclose(outputs.pred_masks , original_outputs["pred_masks"] , atol=1E-4 ) print("Looks ok!" ) if pytorch_dump_folder_path is not None: # Save model and image processor logger.info(F"Saving PyTorch model and image processor to {pytorch_dump_folder_path}..." ) Path(SCREAMING_SNAKE_CASE_ ).mkdir(exist_ok=SCREAMING_SNAKE_CASE_ ) model.save_pretrained(SCREAMING_SNAKE_CASE_ ) processor.save_pretrained(SCREAMING_SNAKE_CASE_ ) if push_to_hub: # Upload model and image processor to the hub logger.info("Uploading PyTorch model and image processor to the hub..." ) model.push_to_hub(F"nielsr/{model_name}" ) processor.push_to_hub(F"nielsr/{model_name}" ) if __name__ == "__main__": snake_case_ = argparse.ArgumentParser() parser.add_argument( '--model_name', default='detr-resnet-50', type=str, choices=['detr-resnet-50', 'detr-resnet-101'], help='Name of the DETR model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the folder to output PyTorch model.' ) parser.add_argument('--push_to_hub', action='store_true', help='Whether to push the model to the hub or not.') snake_case_ = parser.parse_args() convert_detr_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
68
'''simple docstring''' import logging import os import sys from pathlib import Path from unittest.mock import patch from parameterized import parameterized from run_eval import run_generate from run_eval_search import run_search from transformers.testing_utils import CaptureStdout, TestCasePlus, slow from utils import ROUGE_KEYS logging.basicConfig(level=logging.DEBUG) snake_case_ = logging.getLogger() def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Path , SCREAMING_SNAKE_CASE_ : list ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = "\n".join(SCREAMING_SNAKE_CASE_ ) Path(SCREAMING_SNAKE_CASE_ ).open("w" ).writelines(SCREAMING_SNAKE_CASE_ ) snake_case_ = 'patrickvonplaten/t5-tiny-random' snake_case_ = 'sshleifer/bart-tiny-random' snake_case_ = 'sshleifer/tiny-mbart' snake_case_ = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) logging.disable(logging.CRITICAL) # remove noisy download output from tracebacks class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = Path(self.get_auto_remove_tmp_dir() ) / "utest_input.source" SCREAMING_SNAKE_CASE_ : List[str] = input_file_name.parent / "utest_output.txt" assert not output_file_name.exists() SCREAMING_SNAKE_CASE_ : Dict = [" New York (CNN)When Liana Barrientos was 23 years old, she got married in Westchester County."] _dump_articles(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : Tuple = str(Path(self.get_auto_remove_tmp_dir() ) / "scores.json" ) SCREAMING_SNAKE_CASE_ : Tuple = "translation_en_to_de" if model == T5_TINY else "summarization" SCREAMING_SNAKE_CASE_ : Dict = F"\n run_eval_search.py\n {model}\n {input_file_name}\n {output_file_name}\n --score_path {score_path}\n --task {task}\n --num_beams 2\n --length_penalty 2.0\n ".split() with patch.object(lowercase__ , "argv" , lowercase__ ): run_generate() assert Path(lowercase__ ).exists() # os.remove(Path(output_file_name)) def __lowerCamelCase ( self ): """simple docstring""" self.run_eval_tester(lowercase__ ) @parameterized.expand([BART_TINY, MBART_TINY] ) @slow def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" self.run_eval_tester(lowercase__ ) @parameterized.expand([T5_TINY, MBART_TINY] ) @slow def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = Path(self.get_auto_remove_tmp_dir() ) / "utest_input.source" SCREAMING_SNAKE_CASE_ : Optional[Any] = input_file_name.parent / "utest_output.txt" assert not output_file_name.exists() SCREAMING_SNAKE_CASE_ : List[Any] = { "en": ["Machine learning is great, isn't it?", "I like to eat bananas", "Tomorrow is another great day!"], "de": [ "Maschinelles Lernen ist großartig, oder?", "Ich esse gerne Bananen", "Morgen ist wieder ein toller Tag!", ], } SCREAMING_SNAKE_CASE_ : Dict = Path(self.get_auto_remove_tmp_dir() ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = str(tmp_dir / "scores.json" ) SCREAMING_SNAKE_CASE_ : List[Any] = str(tmp_dir / "val.target" ) _dump_articles(lowercase__ , text["en"] ) _dump_articles(lowercase__ , text["de"] ) SCREAMING_SNAKE_CASE_ : List[Any] = "translation_en_to_de" if model == T5_TINY else "summarization" SCREAMING_SNAKE_CASE_ : List[str] = F"\n run_eval_search.py\n {model}\n {str(lowercase__ )}\n {str(lowercase__ )}\n --score_path {score_path}\n --reference_path {reference_path}\n --task {task}\n ".split() testargs.extend(["--search", "num_beams=1:2 length_penalty=0.9:1.0"] ) with patch.object(lowercase__ , "argv" , lowercase__ ): with CaptureStdout() as cs: run_search() SCREAMING_SNAKE_CASE_ : Union[str, Any] = [" num_beams | length_penalty", model, "Best score args"] SCREAMING_SNAKE_CASE_ : Optional[Any] = ["Info"] if "translation" in task: expected_strings.append("bleu" ) else: expected_strings.extend(lowercase__ ) for w in expected_strings: assert w in cs.out for w in un_expected_strings: assert w not in cs.out assert Path(lowercase__ ).exists() os.remove(Path(lowercase__ ) )
68
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available snake_case_ = { 'configuration_bridgetower': [ 'BRIDGETOWER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BridgeTowerConfig', 'BridgeTowerTextConfig', 'BridgeTowerVisionConfig', ], 'processing_bridgetower': ['BridgeTowerProcessor'], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ = ['BridgeTowerImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ = [ 'BRIDGETOWER_PRETRAINED_MODEL_ARCHIVE_LIST', 'BridgeTowerForContrastiveLearning', 'BridgeTowerForImageAndTextRetrieval', 'BridgeTowerForMaskedLM', 'BridgeTowerModel', 'BridgeTowerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_bridgetower import ( BRIDGETOWER_PRETRAINED_CONFIG_ARCHIVE_MAP, BridgeTowerConfig, BridgeTowerTextConfig, BridgeTowerVisionConfig, ) from .processing_bridgetower import BridgeTowerProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_bridgetower import BridgeTowerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bridgetower import ( BRIDGETOWER_PRETRAINED_MODEL_ARCHIVE_LIST, BridgeTowerForContrastiveLearning, BridgeTowerForImageAndTextRetrieval, BridgeTowerForMaskedLM, BridgeTowerModel, BridgeTowerPreTrainedModel, ) else: import sys snake_case_ = _LazyModule(__name__, globals()['__file__'], _import_structure)
68
'''simple docstring''' from __future__ import annotations import numpy as np from numpy import floataa from numpy.typing import NDArray def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : NDArray[floataa] , SCREAMING_SNAKE_CASE_ : NDArray[floataa] , SCREAMING_SNAKE_CASE_ : list[int] , SCREAMING_SNAKE_CASE_ : int , ) -> list[float]: """simple docstring""" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : str = coefficient_matrix.shape SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : List[Any] = constant_matrix.shape if rowsa != colsa: SCREAMING_SNAKE_CASE_ : Union[str, Any] = F"Coefficient matrix dimensions must be nxn but received {rowsa}x{colsa}" raise ValueError(SCREAMING_SNAKE_CASE_ ) if colsa != 1: SCREAMING_SNAKE_CASE_ : List[Any] = F"Constant matrix must be nx1 but received {rowsa}x{colsa}" raise ValueError(SCREAMING_SNAKE_CASE_ ) if rowsa != rowsa: SCREAMING_SNAKE_CASE_ : Any = ( "Coefficient and constant matrices dimensions must be nxn and nx1 but " F"received {rowsa}x{colsa} and {rowsa}x{colsa}" ) raise ValueError(SCREAMING_SNAKE_CASE_ ) if len(SCREAMING_SNAKE_CASE_ ) != rowsa: SCREAMING_SNAKE_CASE_ : int = ( "Number of initial values must be equal to number of rows in coefficient " F"matrix but received {len(SCREAMING_SNAKE_CASE_ )} and {rowsa}" ) raise ValueError(SCREAMING_SNAKE_CASE_ ) if iterations <= 0: raise ValueError("Iterations must be at least 1" ) SCREAMING_SNAKE_CASE_ : NDArray[floataa] = np.concatenate( (coefficient_matrix, constant_matrix) , axis=1 ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Any = table.shape strictly_diagonally_dominant(SCREAMING_SNAKE_CASE_ ) # Iterates the whole matrix for given number of times for _ in range(SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ : Tuple = [] for row in range(SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ : Any = 0 for col in range(SCREAMING_SNAKE_CASE_ ): if col == row: SCREAMING_SNAKE_CASE_ : Any = table[row][col] elif col == cols - 1: SCREAMING_SNAKE_CASE_ : Dict = table[row][col] else: temp += (-1) * table[row][col] * init_val[col] SCREAMING_SNAKE_CASE_ : Optional[Any] = (temp + val) / denom new_val.append(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = new_val return [float(SCREAMING_SNAKE_CASE_ ) for i in new_val] def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : NDArray[floataa] ) -> bool: """simple docstring""" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = table.shape SCREAMING_SNAKE_CASE_ : Tuple = True for i in range(0 , SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ : int = 0 for j in range(0 , cols - 1 ): if i == j: continue else: total += table[i][j] if table[i][i] <= total: raise ValueError("Coefficient matrix is not strictly diagonally dominant" ) return is_diagonally_dominant # Test Cases if __name__ == "__main__": import doctest doctest.testmod()
68
1
'''simple docstring''' from __future__ import annotations snake_case_ = [ [-1, 0], # left [0, -1], # down [1, 0], # right [0, 1], # up ] def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : list[list[int]] , SCREAMING_SNAKE_CASE_ : list[int] , SCREAMING_SNAKE_CASE_ : list[int] , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : list[list[int]] , ) -> tuple[list[list[int]], list[list[int]]]: """simple docstring""" SCREAMING_SNAKE_CASE_ : str = [ [0 for col in range(len(grid[0] ) )] for row in range(len(SCREAMING_SNAKE_CASE_ ) ) ] # the reference grid SCREAMING_SNAKE_CASE_ : Optional[int] = 1 SCREAMING_SNAKE_CASE_ : Any = [ [0 for col in range(len(grid[0] ) )] for row in range(len(SCREAMING_SNAKE_CASE_ ) ) ] # the action grid SCREAMING_SNAKE_CASE_ : str = init[0] SCREAMING_SNAKE_CASE_ : Optional[int] = init[1] SCREAMING_SNAKE_CASE_ : Tuple = 0 SCREAMING_SNAKE_CASE_ : Dict = g + heuristic[x][y] # cost from starting cell to destination cell SCREAMING_SNAKE_CASE_ : Union[str, Any] = [[f, g, x, y]] SCREAMING_SNAKE_CASE_ : List[Any] = False # flag that is set when search is complete SCREAMING_SNAKE_CASE_ : Any = False # flag set if we can't find expand while not found and not resign: if len(SCREAMING_SNAKE_CASE_ ) == 0: raise ValueError("Algorithm is unable to find solution" ) else: # to choose the least costliest action so as to move closer to the goal cell.sort() cell.reverse() SCREAMING_SNAKE_CASE_ : int = cell.pop() SCREAMING_SNAKE_CASE_ : Optional[int] = next_cell[2] SCREAMING_SNAKE_CASE_ : List[Any] = next_cell[3] SCREAMING_SNAKE_CASE_ : str = next_cell[1] if x == goal[0] and y == goal[1]: SCREAMING_SNAKE_CASE_ : Optional[int] = True else: for i in range(len(SCREAMING_SNAKE_CASE_ ) ): # to try out different valid actions SCREAMING_SNAKE_CASE_ : Dict = x + DIRECTIONS[i][0] SCREAMING_SNAKE_CASE_ : List[str] = y + DIRECTIONS[i][1] if xa >= 0 and xa < len(SCREAMING_SNAKE_CASE_ ) and ya >= 0 and ya < len(grid[0] ): if closed[xa][ya] == 0 and grid[xa][ya] == 0: SCREAMING_SNAKE_CASE_ : int = g + cost SCREAMING_SNAKE_CASE_ : List[str] = ga + heuristic[xa][ya] cell.append([fa, ga, xa, ya] ) SCREAMING_SNAKE_CASE_ : List[str] = 1 SCREAMING_SNAKE_CASE_ : Any = i SCREAMING_SNAKE_CASE_ : List[str] = [] SCREAMING_SNAKE_CASE_ : Any = goal[0] SCREAMING_SNAKE_CASE_ : Union[str, Any] = goal[1] invpath.append([x, y] ) # we get the reverse path from here while x != init[0] or y != init[1]: SCREAMING_SNAKE_CASE_ : Dict = x - DIRECTIONS[action[x][y]][0] SCREAMING_SNAKE_CASE_ : Union[str, Any] = y - DIRECTIONS[action[x][y]][1] SCREAMING_SNAKE_CASE_ : Optional[Any] = xa SCREAMING_SNAKE_CASE_ : List[Any] = ya invpath.append([x, y] ) SCREAMING_SNAKE_CASE_ : List[Any] = [] for i in range(len(SCREAMING_SNAKE_CASE_ ) ): path.append(invpath[len(SCREAMING_SNAKE_CASE_ ) - 1 - i] ) return path, action if __name__ == "__main__": snake_case_ = [ [0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0], [0, 0, 0, 0, 1, 0], ] snake_case_ = [0, 0] # all coordinates are given in format [y,x] snake_case_ = [len(grid) - 1, len(grid[0]) - 1] snake_case_ = 1 # the cost map which pushes the path closer to the goal snake_case_ = [[0 for row in range(len(grid[0]))] for col in range(len(grid))] for i in range(len(grid)): for j in range(len(grid[0])): snake_case_ = abs(i - goal[0]) + abs(j - goal[1]) if grid[i][j] == 1: # added extra penalty in the heuristic map snake_case_ = 9_9 snake_case_ , snake_case_ = search(grid, init, goal, cost, heuristic) print('ACTION MAP') for i in range(len(action)): print(action[i]) for i in range(len(path)): print(path[i])
68
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int ) -> int: """simple docstring""" return 1 if input_a == input_a else 0 def __lowerCamelCase ( ) -> None: """simple docstring""" assert xnor_gate(0 , 0 ) == 1 assert xnor_gate(0 , 1 ) == 0 assert xnor_gate(1 , 0 ) == 0 assert xnor_gate(1 , 1 ) == 1 if __name__ == "__main__": print(xnor_gate(0, 0)) print(xnor_gate(0, 1)) print(xnor_gate(1, 0)) print(xnor_gate(1, 1))
68
1
'''simple docstring''' import numpy as np import torch from torch.utils.data import Dataset from utils import logger class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): def __init__( self , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int = params SCREAMING_SNAKE_CASE_ : Optional[int] = np.array(lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = np.array([len(lowercase__ ) for t in data] ) self.check() self.remove_long_sequences() self.remove_empty_sequences() self.remove_unknown_sequences() self.check() self.print_statistics() def __getitem__( self , lowercase__ ): """simple docstring""" return (self.token_ids[index], self.lengths[index]) def __len__( self ): """simple docstring""" return len(self.lengths ) def __lowerCamelCase ( self ): """simple docstring""" assert len(self.token_ids ) == len(self.lengths ) assert all(self.lengths[i] == len(self.token_ids[i] ) for i in range(len(self.lengths ) ) ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.params.max_model_input_size SCREAMING_SNAKE_CASE_ : List[str] = self.lengths > max_len logger.info(F"Splitting {sum(lowercase__ )} too long sequences." ) def divide_chunks(lowercase__ , lowercase__ ): return [l[i : i + n] for i in range(0 , len(lowercase__ ) , lowercase__ )] SCREAMING_SNAKE_CASE_ : Optional[Any] = [] SCREAMING_SNAKE_CASE_ : Union[str, Any] = [] if self.params.mlm: SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Tuple = self.params.special_tok_ids["cls_token"], self.params.special_tok_ids["sep_token"] else: SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : List[str] = self.params.special_tok_ids["bos_token"], self.params.special_tok_ids["eos_token"] for seq_, len_ in zip(self.token_ids , self.lengths ): assert (seq_[0] == cls_id) and (seq_[-1] == sep_id), seq_ if len_ <= max_len: new_tok_ids.append(seq_ ) new_lengths.append(len_ ) else: SCREAMING_SNAKE_CASE_ : int = [] for sub_s in divide_chunks(seq_ , max_len - 2 ): if sub_s[0] != cls_id: SCREAMING_SNAKE_CASE_ : List[Any] = np.insert(lowercase__ , 0 , lowercase__ ) if sub_s[-1] != sep_id: SCREAMING_SNAKE_CASE_ : Optional[int] = np.insert(lowercase__ , len(lowercase__ ) , lowercase__ ) assert len(lowercase__ ) <= max_len assert (sub_s[0] == cls_id) and (sub_s[-1] == sep_id), sub_s sub_seqs.append(lowercase__ ) new_tok_ids.extend(lowercase__ ) new_lengths.extend([len(lowercase__ ) for l in sub_seqs] ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = np.array(lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = np.array(lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = len(self ) SCREAMING_SNAKE_CASE_ : Optional[int] = self.lengths > 11 SCREAMING_SNAKE_CASE_ : int = self.token_ids[indices] SCREAMING_SNAKE_CASE_ : int = self.lengths[indices] SCREAMING_SNAKE_CASE_ : Union[str, Any] = len(self ) logger.info(F"Remove {init_size - new_size} too short (<=11 tokens) sequences." ) def __lowerCamelCase ( self ): """simple docstring""" if "unk_token" not in self.params.special_tok_ids: return else: SCREAMING_SNAKE_CASE_ : Optional[Any] = self.params.special_tok_ids["unk_token"] SCREAMING_SNAKE_CASE_ : Optional[Any] = len(self ) SCREAMING_SNAKE_CASE_ : int = np.array([np.count_nonzero(a == unk_token_id ) for a in self.token_ids] ) SCREAMING_SNAKE_CASE_ : List[Any] = (unk_occs / self.lengths) < 0.5 SCREAMING_SNAKE_CASE_ : int = self.token_ids[indices] SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.lengths[indices] SCREAMING_SNAKE_CASE_ : Any = len(self ) logger.info(F"Remove {init_size - new_size} sequences with a high level of unknown tokens (50%)." ) def __lowerCamelCase ( self ): """simple docstring""" if not self.params.is_master: return logger.info(F"{len(self )} sequences" ) # data_len = sum(self.lengths) # nb_unique_tokens = len(Counter(list(chain(*self.token_ids)))) # logger.info(f'{data_len} tokens ({nb_unique_tokens} unique)') # unk_idx = self.params.special_tok_ids['unk_token'] # nb_unknown = sum([(t==unk_idx).sum() for t in self.token_ids]) # logger.info(f'{nb_unknown} unknown tokens (covering {100*nb_unknown/data_len:.2f}% of the data)') def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int = [t[0] for t in batch] SCREAMING_SNAKE_CASE_ : Dict = [t[1] for t in batch] assert len(lowercase__ ) == len(lowercase__ ) # Max for paddings SCREAMING_SNAKE_CASE_ : List[Any] = max(lowercase__ ) # Pad token ids if self.params.mlm: SCREAMING_SNAKE_CASE_ : Any = self.params.special_tok_ids["pad_token"] else: SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.params.special_tok_ids["unk_token"] SCREAMING_SNAKE_CASE_ : Any = [list(t.astype(lowercase__ ) ) + [pad_idx] * (max_seq_len_ - len(lowercase__ )) for t in token_ids] assert len(tk_ ) == len(lowercase__ ) assert all(len(lowercase__ ) == max_seq_len_ for t in tk_ ) SCREAMING_SNAKE_CASE_ : List[str] = torch.tensor(tk_ ) # (bs, max_seq_len_) SCREAMING_SNAKE_CASE_ : str = torch.tensor(lowercase__ ) # (bs) return tk_t, lg_t
68
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , ) -> float: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = [redshift, radiation_density, matter_density, dark_energy] if any(p < 0 for p in parameters ): raise ValueError("All input parameters must be positive" ) if any(p > 1 for p in parameters[1:4] ): raise ValueError("Relative densities cannot be greater than one" ) else: SCREAMING_SNAKE_CASE_ : int = 1 - (matter_density + radiation_density + dark_energy) SCREAMING_SNAKE_CASE_ : List[Any] = ( radiation_density * (redshift + 1) ** 4 + matter_density * (redshift + 1) ** 3 + curvature * (redshift + 1) ** 2 + dark_energy ) SCREAMING_SNAKE_CASE_ : Dict = hubble_constant * e_a ** (1 / 2) return hubble if __name__ == "__main__": import doctest # run doctest doctest.testmod() # demo LCDM approximation snake_case_ = 0.3 print( hubble_parameter( hubble_constant=6_8.3, radiation_density=1E-4, matter_density=matter_density, dark_energy=1 - matter_density, redshift=0, ) )
68
1
'''simple docstring''' import comet # From: unbabel-comet import torch import datasets snake_case_ = datasets.logging.get_logger(__name__) snake_case_ = '\\n@inproceedings{rei-EtAl:2020:WMT,\n author = {Rei, Ricardo and Stewart, Craig and Farinha, Ana C and Lavie, Alon},\n title = {Unbabel\'s Participation in the WMT20 Metrics Shared Task},\n booktitle = {Proceedings of the Fifth Conference on Machine Translation},\n month = {November},\n year = {2020},\n address = {Online},\n publisher = {Association for Computational Linguistics},\n pages = {909--918},\n}\n@inproceedings{rei-etal-2020-comet,\n title = "{COMET}: A Neural Framework for {MT} Evaluation",\n author = "Rei, Ricardo and\n Stewart, Craig and\n Farinha, Ana C and\n Lavie, Alon",\n booktitle = "Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing (EMNLP)",\n month = nov,\n year = "2020",\n address = "Online",\n publisher = "Association for Computational Linguistics",\n url = "https://www.aclweb.org/anthology/2020.emnlp-main.213",\n pages = "2685--2702",\n}\n' snake_case_ = '\\nCrosslingual Optimized Metric for Evaluation of Translation (COMET) is an open-source framework used to train Machine Translation metrics that achieve high levels of correlation with different types of human judgments (HTER, DA\'s or MQM).\nWith the release of the framework the authors also released fully trained models that were used to compete in the WMT20 Metrics Shared Task achieving SOTA in that years competition.\n\nSee the [README.md] file at https://unbabel.github.io/COMET/html/models.html for more information.\n' snake_case_ = '\nCOMET score.\n\nArgs:\n\n`sources` (list of str): Source sentences\n`predictions` (list of str): candidate translations\n`references` (list of str): reference translations\n`cuda` (bool): If set to True, runs COMET using GPU\n`show_progress` (bool): Shows progress\n`model`: COMET model to be used. Will default to `wmt-large-da-estimator-1719` if None.\n\nReturns:\n `samples`: List of dictionaries with `src`, `mt`, `ref` and `score`.\n `scores`: List of scores.\n\nExamples:\n\n >>> comet_metric = datasets.load_metric(\'comet\')\n >>> # comet_metric = load_metric(\'comet\', \'wmt20-comet-da\') # you can also choose which model to use\n >>> source = ["Dem Feuer konnte Einhalt geboten werden", "Schulen und Kindergärten wurden eröffnet."]\n >>> hypothesis = ["The fire could be stopped", "Schools and kindergartens were open"]\n >>> reference = ["They were able to control the fire.", "Schools and kindergartens opened"]\n >>> results = comet_metric.compute(predictions=hypothesis, references=reference, sources=source)\n >>> print([round(v, 2) for v in results["scores"]])\n [0.19, 0.92]\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION,_KWARGS_DESCRIPTION ) class SCREAMING_SNAKE_CASE__ ( datasets.Metric ): def __lowerCamelCase ( self ): """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage="https://unbabel.github.io/COMET/html/index.html" , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "sources": datasets.Value("string" , id="sequence" ), "predictions": datasets.Value("string" , id="sequence" ), "references": datasets.Value("string" , id="sequence" ), } ) , codebase_urls=["https://github.com/Unbabel/COMET"] , reference_urls=[ "https://github.com/Unbabel/COMET", "https://www.aclweb.org/anthology/2020.emnlp-main.213/", "http://www.statmt.org/wmt20/pdf/2020.wmt-1.101.pdf6", ] , ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" if self.config_name == "default": SCREAMING_SNAKE_CASE_ : Any = comet.load_from_checkpoint(comet.download_model("wmt20-comet-da" ) ) else: SCREAMING_SNAKE_CASE_ : Tuple = comet.load_from_checkpoint(comet.download_model(self.config_name ) ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__=None , lowercase__=False ): """simple docstring""" if gpus is None: SCREAMING_SNAKE_CASE_ : List[Any] = 1 if torch.cuda.is_available() else 0 SCREAMING_SNAKE_CASE_ : Tuple = {"src": sources, "mt": predictions, "ref": references} SCREAMING_SNAKE_CASE_ : List[str] = [dict(zip(lowercase__ , lowercase__ ) ) for t in zip(*data.values() )] SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : str = self.scorer.predict(lowercase__ , gpus=lowercase__ , progress_bar=lowercase__ ) return {"mean_score": mean_score, "scores": scores}
68
'''simple docstring''' import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.generation import DisjunctiveConstraint @require_torch class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = [[1, 2, 4], [1, 2, 3, 4]] SCREAMING_SNAKE_CASE_ : Any = DisjunctiveConstraint(lowercase__ ) self.assertTrue(isinstance(dc.token_ids , lowercase__ ) ) with self.assertRaises(lowercase__ ): DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]] ) ) with self.assertRaises(lowercase__ ): DisjunctiveConstraint([torch.LongTensor([1, 2, 4] ), torch.LongTensor([1, 2, 3, 4, 5] )] ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = [[1, 2], [1, 2, 3, 4]] with self.assertRaises(lowercase__ ): DisjunctiveConstraint(lowercase__ ) # fails here def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = [[1, 2, 3], [1, 2, 4]] SCREAMING_SNAKE_CASE_ : Optional[Any] = DisjunctiveConstraint(lowercase__ ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = dc.update(1 ) SCREAMING_SNAKE_CASE_ : Optional[int] = stepped is True and completed is False and reset is False self.assertTrue(lowercase__ ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Tuple = dc.update(2 ) SCREAMING_SNAKE_CASE_ : Tuple = stepped is True and completed is False and reset is False self.assertTrue(lowercase__ ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Any = dc.update(3 ) SCREAMING_SNAKE_CASE_ : Tuple = stepped is True and completed is True and reset is False self.assertTrue(lowercase__ ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 3] ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]] SCREAMING_SNAKE_CASE_ : Dict = DisjunctiveConstraint(lowercase__ ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : List[Any] = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = dc.update(4 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2, 4] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : List[Any] = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 4, 5] ) dc.reset() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Tuple = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 3 ) self.assertTrue(dc.current_seq == [1] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : str = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 2 ) self.assertTrue(dc.current_seq == [1, 2] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : str = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.remaining() == 0 ) self.assertTrue(dc.current_seq == [1, 2, 5] )
68
1
'''simple docstring''' from __future__ import annotations import math from collections.abc import Callable def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Callable[[int | float], int | float] , SCREAMING_SNAKE_CASE_ : int | float , SCREAMING_SNAKE_CASE_ : int | float , SCREAMING_SNAKE_CASE_ : int = 1_0_0 , ) -> float: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = x_start SCREAMING_SNAKE_CASE_ : Tuple = fnc(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : List[Any] = 0.0 for _ in range(SCREAMING_SNAKE_CASE_ ): # Approximates curve as a sequence of linear lines and sums their length SCREAMING_SNAKE_CASE_ : int = (x_end - x_start) / steps + xa SCREAMING_SNAKE_CASE_ : Any = fnc(SCREAMING_SNAKE_CASE_ ) length += math.hypot(xa - xa , fxa - fxa ) # Increment step SCREAMING_SNAKE_CASE_ : List[str] = xa SCREAMING_SNAKE_CASE_ : str = fxa return length if __name__ == "__main__": def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Optional[Any] ) -> str: """simple docstring""" return math.sin(1_0 * x ) print('f(x) = sin(10 * x)') print('The length of the curve from x = -10 to x = 10 is:') snake_case_ = 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
68
'''simple docstring''' import unittest import torch from diffusers import VQModel from diffusers.utils import floats_tensor, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,_UpperCAmelCase,unittest.TestCase ): _A = VQModel _A = "sample" @property def __lowerCamelCase ( self , lowercase__=(32, 32) ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = 4 SCREAMING_SNAKE_CASE_ : str = 3 SCREAMING_SNAKE_CASE_ : str = floats_tensor((batch_size, num_channels) + sizes ).to(lowercase__ ) return {"sample": image} @property def __lowerCamelCase ( self ): """simple docstring""" return (3, 32, 32) @property def __lowerCamelCase ( self ): """simple docstring""" return (3, 32, 32) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = { "block_out_channels": [32, 64], "in_channels": 3, "out_channels": 3, "down_block_types": ["DownEncoderBlock2D", "DownEncoderBlock2D"], "up_block_types": ["UpDecoderBlock2D", "UpDecoderBlock2D"], "latent_channels": 3, } SCREAMING_SNAKE_CASE_ : int = self.dummy_input return init_dict, inputs_dict def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : int = VQModel.from_pretrained("fusing/vqgan-dummy" , output_loading_info=lowercase__ ) self.assertIsNotNone(lowercase__ ) self.assertEqual(len(loading_info["missing_keys"] ) , 0 ) model.to(lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = VQModel.from_pretrained("fusing/vqgan-dummy" ) model.to(lowercase__ ).eval() torch.manual_seed(0 ) if torch.cuda.is_available(): torch.cuda.manual_seed_all(0 ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.randn(1 , model.config.in_channels , model.config.sample_size , model.config.sample_size ) SCREAMING_SNAKE_CASE_ : str = image.to(lowercase__ ) with torch.no_grad(): SCREAMING_SNAKE_CASE_ : int = model(lowercase__ ).sample SCREAMING_SNAKE_CASE_ : Any = output[0, -1, -3:, -3:].flatten().cpu() # fmt: off SCREAMING_SNAKE_CASE_ : Optional[Any] = torch.tensor([-0.0153, -0.4044, -0.1880, -0.5161, -0.2418, -0.4072, -0.1612, -0.0633, -0.0143] ) # fmt: on self.assertTrue(torch.allclose(lowercase__ , lowercase__ , atol=1e-3 ) )
68
1
'''simple docstring''' from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available snake_case_ = { 'configuration_informer': [ 'INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'InformerConfig', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ = [ 'INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'InformerForPrediction', 'InformerModel', 'InformerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_informer import INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, InformerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_informer import ( INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, InformerForPrediction, InformerModel, InformerPreTrainedModel, ) else: import sys snake_case_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
68
'''simple docstring''' import os import unittest from huggingface_hub.utils import are_progress_bars_disabled import transformers.models.bart.tokenization_bart from transformers import logging from transformers.testing_utils import CaptureLogger, mockenv, mockenv_context from transformers.utils.logging import disable_progress_bar, enable_progress_bar class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = logging.get_logger() # the current default level is logging.WARNING SCREAMING_SNAKE_CASE_ : Optional[int] = logging.get_verbosity() logging.set_verbosity_error() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_warning() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_info() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_debug() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) # restore to the original level logging.set_verbosity(lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = logging.get_verbosity() SCREAMING_SNAKE_CASE_ : List[Any] = logging.get_logger("transformers.models.bart.tokenization_bart" ) SCREAMING_SNAKE_CASE_ : List[Any] = "Testing 1, 2, 3" # should be able to log warnings (if default settings weren't overridden by `pytest --log-level-all`) if level_origin <= logging.WARNING: with CaptureLogger(lowercase__ ) as cl: logger.warning(lowercase__ ) self.assertEqual(cl.out , msg + "\n" ) # this is setting the level for all of `transformers.*` loggers logging.set_verbosity_error() # should not be able to log warnings with CaptureLogger(lowercase__ ) as cl: logger.warning(lowercase__ ) self.assertEqual(cl.out , "" ) # should be able to log warnings again logging.set_verbosity_warning() with CaptureLogger(lowercase__ ) as cl: logger.warning(lowercase__ ) self.assertEqual(cl.out , msg + "\n" ) # restore to the original level logging.set_verbosity(lowercase__ ) @mockenv(TRANSFORMERS_VERBOSITY="error" ) def __lowerCamelCase ( self ): """simple docstring""" transformers.utils.logging._reset_library_root_logger() # this action activates the env var SCREAMING_SNAKE_CASE_ : Tuple = logging.get_logger("transformers.models.bart.tokenization_bart" ) SCREAMING_SNAKE_CASE_ : int = os.getenv("TRANSFORMERS_VERBOSITY" , lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = logging.log_levels[env_level_str] SCREAMING_SNAKE_CASE_ : str = logging.get_verbosity() self.assertEqual( lowercase__ , lowercase__ , F"TRANSFORMERS_VERBOSITY={env_level_str}/{env_level}, but internal verbosity is {current_level}" , ) # restore to the original level SCREAMING_SNAKE_CASE_ : Optional[int] = "" transformers.utils.logging._reset_library_root_logger() @mockenv(TRANSFORMERS_VERBOSITY="super-error" ) def __lowerCamelCase ( self ): """simple docstring""" transformers.utils.logging._reset_library_root_logger() SCREAMING_SNAKE_CASE_ : List[Any] = logging.logging.getLogger() with CaptureLogger(lowercase__ ) as cl: # this action activates the env var logging.get_logger("transformers.models.bart.tokenization_bart" ) self.assertIn("Unknown option TRANSFORMERS_VERBOSITY=super-error" , cl.out ) # no need to restore as nothing was changed def __lowerCamelCase ( self ): """simple docstring""" transformers.utils.logging._reset_library_root_logger() SCREAMING_SNAKE_CASE_ : str = logging.get_logger("transformers.models.bart.tokenization_bart" ) SCREAMING_SNAKE_CASE_ : List[Any] = "Testing 1, 2, 3" with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS="1" ): # nothing should be logged as env var disables this method with CaptureLogger(lowercase__ ) as cl: logger.warning_advice(lowercase__ ) self.assertEqual(cl.out , "" ) with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS="" ): # should log normally as TRANSFORMERS_NO_ADVISORY_WARNINGS is unset with CaptureLogger(lowercase__ ) as cl: logger.warning_advice(lowercase__ ) self.assertEqual(cl.out , msg + "\n" ) def __lowerCamelCase ( ) -> Optional[int]: """simple docstring""" disable_progress_bar() assert are_progress_bars_disabled() enable_progress_bar() assert not are_progress_bars_disabled()
68
1
'''simple docstring''' from __future__ import annotations import collections import tempfile import unittest import numpy as np from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import is_tf_available, is_vision_available from ...test_modeling_tf_common import floats_tensor, ids_tensor, random_attention_mask from ..bert.test_modeling_tf_bert import TFBertModelTester from ..clip.test_modeling_tf_clip import TFCLIPVisionModelTester from ..deit.test_modeling_tf_deit import TFDeiTModelTester from ..roberta.test_modeling_tf_roberta import TFRobertaModelTester from ..vit.test_modeling_tf_vit import TFViTModelTester if is_tf_available(): from transformers import ( TFBertModel, TFCLIPVisionModel, TFDeiTModel, TFRobertaModel, TFVisionTextDualEncoderModel, TFViTModel, VisionTextDualEncoderConfig, ) if is_vision_available(): from PIL import Image from transformers import VisionTextDualEncoderProcessor def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Union[str, Any] ) -> Optional[Any]: """simple docstring""" if isinstance(SCREAMING_SNAKE_CASE_ , collections.abc.Iterable ): return x return (x, x) @require_tf class SCREAMING_SNAKE_CASE__ : def __lowerCamelCase ( self , lowercase__ , lowercase__ ): """simple docstring""" pass def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__=None , **lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = VisionTextDualEncoderConfig.from_vision_text_configs(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = TFVisionTextDualEncoderModel(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = model(input_ids=lowercase__ , pixel_values=lowercase__ , attention_mask=lowercase__ ) self.assertEqual(output["text_embeds"].shape , (input_ids.shape[0], config.projection_dim) ) self.assertEqual(output["image_embeds"].shape , (pixel_values.shape[0], config.projection_dim) ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__=None , **lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : List[str] = self.get_vision_text_model(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = TFVisionTextDualEncoderModel(vision_model=lowercase__ , text_model=lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = model(input_ids=lowercase__ , pixel_values=lowercase__ , attention_mask=lowercase__ ) self.assertEqual(output["text_embeds"].shape , (input_ids.shape[0], model.config.projection_dim) ) self.assertEqual(output["image_embeds"].shape , (pixel_values.shape[0], model.config.projection_dim) ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__=None , **lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : str = self.get_vision_text_model(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = {"vision_model": vision_model, "text_model": text_model} SCREAMING_SNAKE_CASE_ : Union[str, Any] = TFVisionTextDualEncoderModel.from_vision_text_pretrained(**lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = model(input_ids=lowercase__ , pixel_values=lowercase__ , attention_mask=lowercase__ ) self.assertEqual(output["text_embeds"].shape , (input_ids.shape[0], model.config.projection_dim) ) self.assertEqual(output["image_embeds"].shape , (pixel_values.shape[0], model.config.projection_dim) ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__=None , **lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : List[Any] = self.get_vision_text_model(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : str = TFVisionTextDualEncoderModel(vision_model=lowercase__ , text_model=lowercase__ ) SCREAMING_SNAKE_CASE_ : Tuple = model(input_ids=lowercase__ , pixel_values=lowercase__ , attention_mask=lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = output[0].numpy() with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(lowercase__ ) SCREAMING_SNAKE_CASE_ : int = TFVisionTextDualEncoderModel.from_pretrained(lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = model(input_ids=lowercase__ , pixel_values=lowercase__ , attention_mask=lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = after_output[0].numpy() SCREAMING_SNAKE_CASE_ : Optional[int] = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(lowercase__ , 1e-5 ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__=None , **lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.get_vision_text_model(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = TFVisionTextDualEncoderModel(vision_model=lowercase__ , text_model=lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = model( input_ids=lowercase__ , pixel_values=lowercase__ , attention_mask=lowercase__ , output_attentions=lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = output.vision_model_output.attentions self.assertEqual(len(lowercase__ ) , vision_config.num_hidden_layers ) # in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token) SCREAMING_SNAKE_CASE_ : Tuple = to_atuple(vision_model.config.image_size ) SCREAMING_SNAKE_CASE_ : int = to_atuple(vision_model.config.patch_size ) SCREAMING_SNAKE_CASE_ : int = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) SCREAMING_SNAKE_CASE_ : Optional[int] = num_patches + 1 self.assertEqual(vision_attentions[0].shape[-3:] , (vision_config.num_attention_heads, seq_len, seq_len) ) SCREAMING_SNAKE_CASE_ : Tuple = output.text_model_output.attentions self.assertEqual(len(lowercase__ ) , text_config.num_hidden_layers ) self.assertEqual( text_attentions[0].shape[-3:] , (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1]) , ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = np.abs((a - b) ).max() self.assertLessEqual(lowercase__ , lowercase__ , F"Difference between torch and flax is {diff} (>= {tol})." ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = self.prepare_config_and_inputs() self.check_vision_text_dual_encoder_model(**lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = self.prepare_config_and_inputs() self.check_model_from_pretrained_configs(**lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.prepare_config_and_inputs() self.check_vision_text_dual_encoder_from_pretrained(**lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = self.prepare_config_and_inputs() self.check_save_load(**lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = self.prepare_config_and_inputs() self.check_vision_text_output_attention(**lowercase__ ) @slow def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : int = self.get_pretrained_model_and_inputs() SCREAMING_SNAKE_CASE_ : Optional[Any] = model_a(**lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = outputs[0].numpy() with tempfile.TemporaryDirectory() as tmp_dirname: model_a.save_pretrained(lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = TFVisionTextDualEncoderModel.from_pretrained(lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = model_a(**lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = after_outputs[0].numpy() SCREAMING_SNAKE_CASE_ : int = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(lowercase__ , 1e-5 ) @require_tf class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,unittest.TestCase ): def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = TFVisionTextDualEncoderModel.from_vision_text_pretrained( "hf-internal-testing/tiny-random-vit" , "hf-internal-testing/tiny-random-bert" ) SCREAMING_SNAKE_CASE_ : Dict = 13 SCREAMING_SNAKE_CASE_ : str = floats_tensor( [ batch_size, model.vision_model.config.num_channels, model.vision_model.config.image_size, model.vision_model.config.image_size, ] ) SCREAMING_SNAKE_CASE_ : Tuple = ids_tensor([batch_size, 4] , model.text_model.config.vocab_size ) SCREAMING_SNAKE_CASE_ : Dict = random_attention_mask([batch_size, 4] ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = {"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask} return model, inputs def __lowerCamelCase ( self , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = TFViTModel(lowercase__ , name="vision_model" ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = TFBertModel(lowercase__ , name="text_model" ) return vision_model, text_model def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = TFViTModelTester(self ) SCREAMING_SNAKE_CASE_ : Any = TFBertModelTester(self ) SCREAMING_SNAKE_CASE_ : List[Any] = vit_model_tester.prepare_config_and_inputs() SCREAMING_SNAKE_CASE_ : Any = bert_model_tester.prepare_config_and_inputs() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Union[str, Any] = vision_config_and_inputs ( ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ) : Dict = text_config_and_inputs return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": input_mask, "input_ids": input_ids, "text_token_type_ids": token_type_ids, "text_sequence_labels": sequence_labels, "text_token_labels": token_labels, "text_choice_labels": choice_labels, } @require_tf class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,unittest.TestCase ): def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = TFVisionTextDualEncoderModel.from_vision_text_pretrained( "Rocketknight1/tiny-random-deit-tf" , "hf-internal-testing/tiny-random-roberta" ) SCREAMING_SNAKE_CASE_ : List[Any] = 13 SCREAMING_SNAKE_CASE_ : Dict = floats_tensor( [ batch_size, model.vision_model.config.num_channels, model.vision_model.config.image_size, model.vision_model.config.image_size, ] ) SCREAMING_SNAKE_CASE_ : List[Any] = ids_tensor([batch_size, 4] , model.text_model.config.vocab_size ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = random_attention_mask([batch_size, 4] ) SCREAMING_SNAKE_CASE_ : Tuple = {"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask} return model, inputs def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__=None , **lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Tuple = self.get_vision_text_model(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = TFVisionTextDualEncoderModel(vision_model=lowercase__ , text_model=lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = model( input_ids=lowercase__ , pixel_values=lowercase__ , attention_mask=lowercase__ , output_attentions=lowercase__ ) SCREAMING_SNAKE_CASE_ : int = output.vision_model_output.attentions self.assertEqual(len(lowercase__ ) , vision_config.num_hidden_layers ) # in DEiT, the seq_len equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens) SCREAMING_SNAKE_CASE_ : str = to_atuple(vision_model.config.image_size ) SCREAMING_SNAKE_CASE_ : int = to_atuple(vision_model.config.patch_size ) SCREAMING_SNAKE_CASE_ : str = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) SCREAMING_SNAKE_CASE_ : int = num_patches + 2 self.assertEqual(vision_attentions[0].shape[-3:] , (vision_config.num_attention_heads, seq_len, seq_len) ) SCREAMING_SNAKE_CASE_ : List[str] = output.text_model_output.attentions self.assertEqual(len(lowercase__ ) , text_config.num_hidden_layers ) self.assertEqual( text_attentions[0].shape[-3:] , (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1]) , ) def __lowerCamelCase ( self , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = TFDeiTModel(lowercase__ , name="vision_model" ) SCREAMING_SNAKE_CASE_ : Any = TFRobertaModel(lowercase__ , name="text_model" ) return vision_model, text_model def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = TFDeiTModelTester(self ) SCREAMING_SNAKE_CASE_ : Tuple = TFRobertaModelTester(self ) SCREAMING_SNAKE_CASE_ : Any = vit_model_tester.prepare_config_and_inputs() SCREAMING_SNAKE_CASE_ : Optional[Any] = bert_model_tester.prepare_config_and_inputs() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : str = vision_config_and_inputs ( ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ) : Tuple = text_config_and_inputs return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": input_mask, "input_ids": input_ids, "text_token_type_ids": token_type_ids, "text_sequence_labels": sequence_labels, "text_token_labels": token_labels, "text_choice_labels": choice_labels, } @require_tf class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,unittest.TestCase ): def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = TFVisionTextDualEncoderModel.from_vision_text_pretrained( "Rocketknight1/tiny-random-clip-tf" , "hf-internal-testing/tiny-random-bert" ) SCREAMING_SNAKE_CASE_ : Optional[int] = 13 SCREAMING_SNAKE_CASE_ : int = floats_tensor( [ batch_size, model.vision_model.config.num_channels, model.vision_model.config.image_size, model.vision_model.config.image_size, ] ) SCREAMING_SNAKE_CASE_ : str = ids_tensor([batch_size, 4] , model.text_model.config.vocab_size ) SCREAMING_SNAKE_CASE_ : int = random_attention_mask([batch_size, 4] ) SCREAMING_SNAKE_CASE_ : Optional[int] = {"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask} return model, inputs def __lowerCamelCase ( self , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = TFCLIPVisionModel(lowercase__ , name="vision_model" ) SCREAMING_SNAKE_CASE_ : Dict = TFBertModel(lowercase__ , name="text_model" ) return vision_model, text_model def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int = TFCLIPVisionModelTester(self ) SCREAMING_SNAKE_CASE_ : Optional[Any] = TFBertModelTester(self ) SCREAMING_SNAKE_CASE_ : Optional[Any] = clip_model_tester.prepare_config_and_inputs() SCREAMING_SNAKE_CASE_ : Tuple = bert_model_tester.prepare_config_and_inputs() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : List[str] = vision_config_and_inputs ( ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ) : Optional[Any] = text_config_and_inputs return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": input_mask, "input_ids": input_ids, "text_token_type_ids": token_type_ids, "text_sequence_labels": sequence_labels, "text_token_labels": token_labels, "text_choice_labels": choice_labels, } @require_vision @require_tf class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): @slow def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = TFVisionTextDualEncoderModel.from_pretrained( "clip-italian/clip-italian" , logit_scale_init_value=1.0 , from_pt=lowercase__ ) SCREAMING_SNAKE_CASE_ : Tuple = VisionTextDualEncoderProcessor.from_pretrained("clip-italian/clip-italian" ) SCREAMING_SNAKE_CASE_ : Optional[int] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) SCREAMING_SNAKE_CASE_ : List[str] = processor( text=["una foto di un gatto", "una foto di un cane"] , images=lowercase__ , padding=lowercase__ , return_tensors="np" ) SCREAMING_SNAKE_CASE_ : Optional[int] = model(**lowercase__ ) # verify the logits self.assertEqual(outputs.logits_per_image.shape , (inputs.pixel_values.shape[0], inputs.input_ids.shape[0]) ) self.assertEqual( outputs.logits_per_text.shape , (inputs.input_ids.shape[0], inputs.pixel_values.shape[0]) , ) SCREAMING_SNAKE_CASE_ : str = np.array([[1.2284727, 0.3104122]] ) self.assertTrue(np.allclose(outputs.logits_per_image.numpy() , lowercase__ , atol=1e-3 ) )
68
'''simple docstring''' import json import os import tempfile from unittest.mock import patch import torch from torch.utils.data import DataLoader, TensorDataset from accelerate import DistributedType, infer_auto_device_map, init_empty_weights from accelerate.accelerator import Accelerator from accelerate.state import GradientState, PartialState from accelerate.test_utils import require_bnb, require_multi_gpu, slow from accelerate.test_utils.testing import AccelerateTestCase, require_cuda from accelerate.utils import patch_environment def __lowerCamelCase ( ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = torch.nn.Linear(2 , 4 ) SCREAMING_SNAKE_CASE_ : List[Any] = torch.optim.AdamW(model.parameters() , lr=1.0 ) SCREAMING_SNAKE_CASE_ : Any = torch.optim.lr_scheduler.OneCycleLR(SCREAMING_SNAKE_CASE_ , max_lr=0.01 , steps_per_epoch=2 , epochs=1 ) SCREAMING_SNAKE_CASE_ : Dict = DataLoader(TensorDataset(torch.tensor([1, 2, 3] ) ) ) SCREAMING_SNAKE_CASE_ : Tuple = DataLoader(TensorDataset(torch.tensor([4, 5, 6] ) ) ) return model, optimizer, scheduler, train_dl, valid_dl def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : List[str] ) -> Tuple: """simple docstring""" return (model.weight.abs().sum() + model.bias.abs().sum()).item() def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Any ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : str = torch.nn.Linear(*tuple(model.weight.T.shape ) ).state_dict() model.load_state_dict(SCREAMING_SNAKE_CASE_ ) class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): @require_cuda def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = Accelerator() assert PartialState._shared_state["_cpu"] is False assert PartialState._shared_state["device"].type == "cuda" with self.assertRaises(lowercase__ ): SCREAMING_SNAKE_CASE_ : List[Any] = Accelerator(cpu=lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = Accelerator() SCREAMING_SNAKE_CASE_ : Any = GradientState() assert state.num_steps == 1 SCREAMING_SNAKE_CASE_ : Union[str, Any] = 4 assert state.num_steps == 4 assert state.sync_gradients is True SCREAMING_SNAKE_CASE_ : Optional[int] = False assert state.sync_gradients is False GradientState._reset_state() def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[int] = create_components() ( ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ) : Optional[Any] = accelerator.prepare(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) self.assertTrue(prepared_model in accelerator._models ) self.assertTrue(prepared_optimizer in accelerator._optimizers ) self.assertTrue(prepared_scheduler in accelerator._schedulers ) self.assertTrue(prepared_train_dl in accelerator._dataloaders ) self.assertTrue(prepared_valid_dl in accelerator._dataloaders ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : str = create_components() accelerator.prepare(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) accelerator.free_memory() self.assertTrue(len(accelerator._models ) == 0 ) self.assertTrue(len(accelerator._optimizers ) == 0 ) self.assertTrue(len(accelerator._schedulers ) == 0 ) self.assertTrue(len(accelerator._dataloaders ) == 0 ) def __lowerCamelCase ( self ): """simple docstring""" PartialState._reset_state() # Mock torch.cuda.set_device to avoid an exception as the device doesn't exist def noop(*lowercase__ , **lowercase__ ): pass with patch("torch.cuda.set_device" , lowercase__ ), patch_environment(ACCELERATE_TORCH_DEVICE="cuda:64" ): SCREAMING_SNAKE_CASE_ : List[str] = Accelerator() self.assertEqual(str(accelerator.state.device ) , "cuda:64" ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = create_components() accelerator.prepare(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = get_signature(lowercase__ ) with tempfile.TemporaryDirectory() as tmpdirname: accelerator.save_state(lowercase__ ) # make sure random weights don't match load_random_weights(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) > 1e-3 ) # make sure loaded weights match accelerator.load_state(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) < 1e-3 ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[int] = create_components() accelerator.prepare(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = get_signature(lowercase__ ) # saving hook def save_config(lowercase__ , lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE_ : Optional[Any] = {"class_name": models[0].__class__.__name__} with open(os.path.join(lowercase__ , "data.json" ) , "w" ) as f: json.dump(lowercase__ , lowercase__ ) # loading hook def load_config(lowercase__ , lowercase__ ): with open(os.path.join(lowercase__ , "data.json" ) , "r" ) as f: SCREAMING_SNAKE_CASE_ : Any = json.load(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = config["class_name"] SCREAMING_SNAKE_CASE_ : Dict = accelerator.register_save_state_pre_hook(lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = accelerator.register_load_state_pre_hook(lowercase__ ) with tempfile.TemporaryDirectory() as tmpdirname: accelerator.save_state(lowercase__ ) # make sure random weights don't match with hooks load_random_weights(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) > 1e-3 ) # random class name to verify correct one is loaded SCREAMING_SNAKE_CASE_ : Union[str, Any] = "random" # make sure loaded weights match with hooks accelerator.load_state(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) < 1e-3 ) # mode.class_name is loaded from config self.assertTrue(model.class_name == model.__class__.__name__ ) # remove hooks save_hook.remove() load_hook.remove() with tempfile.TemporaryDirectory() as tmpdirname: accelerator.save_state(lowercase__ ) # make sure random weights don't match with hooks removed load_random_weights(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) > 1e-3 ) # random class name to verify correct one is loaded SCREAMING_SNAKE_CASE_ : Tuple = "random" # make sure loaded weights match with hooks removed accelerator.load_state(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) < 1e-3 ) # mode.class_name is NOT loaded from config self.assertTrue(model.class_name != model.__class__.__name__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Tuple = create_components() SCREAMING_SNAKE_CASE_ : Union[str, Any] = None # This should work SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[int] = accelerator.prepare( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) self.assertTrue(dummy_obj is None ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = create_components() SCREAMING_SNAKE_CASE_ : Union[str, Any] = [1, 2, 3] # This should work SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : int = accelerator.prepare( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Dummy object should have `_is_accelerate_prepared` set to `True`" , ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Model is missing `_is_accelerator_prepared` or is set to `False`" , ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Optimizer is missing `_is_accelerator_prepared` or is set to `False`" , ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Scheduler is missing `_is_accelerator_prepared` or is set to `False`" , ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Train Dataloader is missing `_is_accelerator_prepared` or is set to `False`" , ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Valid Dataloader is missing `_is_accelerator_prepared` or is set to `False`" , ) @slow @require_bnb def __lowerCamelCase ( self ): """simple docstring""" from transformers import AutoModelForCausalLM SCREAMING_SNAKE_CASE_ : Optional[int] = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , load_in_abit=lowercase__ , device_map={"": 0} , ) SCREAMING_SNAKE_CASE_ : Optional[int] = Accelerator() # This should work SCREAMING_SNAKE_CASE_ : List[Any] = accelerator.prepare(lowercase__ ) @slow @require_bnb def __lowerCamelCase ( self ): """simple docstring""" from transformers import AutoModelForCausalLM SCREAMING_SNAKE_CASE_ : Optional[Any] = Accelerator() with init_empty_weights(): SCREAMING_SNAKE_CASE_ : Tuple = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , ) model.tie_weights() SCREAMING_SNAKE_CASE_ : Optional[Any] = infer_auto_device_map(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = "cpu" SCREAMING_SNAKE_CASE_ : Tuple = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , device_map=lowercase__ , load_in_abit=lowercase__ , llm_inta_enable_fpaa_cpu_offload=lowercase__ ) # This should not work and get value error with self.assertRaises(lowercase__ ): SCREAMING_SNAKE_CASE_ : str = accelerator.prepare(lowercase__ ) @slow @require_bnb @require_multi_gpu def __lowerCamelCase ( self ): """simple docstring""" from transformers import AutoModelForCausalLM SCREAMING_SNAKE_CASE_ : str = {"distributed_type": DistributedType.MULTI_GPU} with init_empty_weights(): SCREAMING_SNAKE_CASE_ : Optional[int] = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , ) model.tie_weights() SCREAMING_SNAKE_CASE_ : str = infer_auto_device_map(lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = 1 SCREAMING_SNAKE_CASE_ : str = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , load_in_abit=lowercase__ , device_map=lowercase__ , ) SCREAMING_SNAKE_CASE_ : Any = Accelerator() # This should not work and get value error with self.assertRaises(lowercase__ ): SCREAMING_SNAKE_CASE_ : Tuple = accelerator.prepare(lowercase__ ) PartialState._reset_state() @slow @require_bnb @require_multi_gpu def __lowerCamelCase ( self ): """simple docstring""" from transformers import AutoModelForCausalLM with init_empty_weights(): SCREAMING_SNAKE_CASE_ : Optional[int] = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , ) SCREAMING_SNAKE_CASE_ : Optional[Any] = infer_auto_device_map(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = 1 SCREAMING_SNAKE_CASE_ : str = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , load_in_abit=lowercase__ , device_map=lowercase__ , ) SCREAMING_SNAKE_CASE_ : Any = Accelerator() # This should work SCREAMING_SNAKE_CASE_ : Optional[int] = accelerator.prepare(lowercase__ ) @require_cuda def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = torch.nn.Linear(10 , 10 ) SCREAMING_SNAKE_CASE_ : Optional[int] = torch.optim.SGD(model.parameters() , lr=0.01 ) SCREAMING_SNAKE_CASE_ : Tuple = Accelerator(cpu=lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = accelerator.prepare(lowercase__ )
68
1
'''simple docstring''' import argparse import torch from transformers import ( WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaForAudioFrameClassification, WavaVecaForSequenceClassification, WavaVecaForXVector, logging, ) logging.set_verbosity_info() snake_case_ = logging.get_logger(__name__) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : str ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = WavaVecaForSequenceClassification.from_pretrained(SCREAMING_SNAKE_CASE_ , config=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Any = downstream_dict["projector.weight"] SCREAMING_SNAKE_CASE_ : List[str] = downstream_dict["projector.bias"] SCREAMING_SNAKE_CASE_ : List[str] = downstream_dict["model.post_net.linear.weight"] SCREAMING_SNAKE_CASE_ : List[Any] = downstream_dict["model.post_net.linear.bias"] return model def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : List[Any] ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = WavaVecaForAudioFrameClassification.from_pretrained(SCREAMING_SNAKE_CASE_ , config=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : str = downstream_dict["model.linear.weight"] SCREAMING_SNAKE_CASE_ : List[Any] = downstream_dict["model.linear.bias"] return model def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = WavaVecaForXVector.from_pretrained(SCREAMING_SNAKE_CASE_ , config=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Dict = downstream_dict["connector.weight"] SCREAMING_SNAKE_CASE_ : int = downstream_dict["connector.bias"] for i, kernel_size in enumerate(hf_config.tdnn_kernel ): SCREAMING_SNAKE_CASE_ : List[Any] = downstream_dict[ F"model.framelevel_feature_extractor.module.{i}.kernel.weight" ] SCREAMING_SNAKE_CASE_ : int = downstream_dict[F"model.framelevel_feature_extractor.module.{i}.kernel.bias"] SCREAMING_SNAKE_CASE_ : List[Any] = downstream_dict["model.utterancelevel_feature_extractor.linear1.weight"] SCREAMING_SNAKE_CASE_ : List[str] = downstream_dict["model.utterancelevel_feature_extractor.linear1.bias"] SCREAMING_SNAKE_CASE_ : Optional[Any] = downstream_dict["model.utterancelevel_feature_extractor.linear2.weight"] SCREAMING_SNAKE_CASE_ : str = downstream_dict["model.utterancelevel_feature_extractor.linear2.bias"] SCREAMING_SNAKE_CASE_ : Dict = downstream_dict["objective.W"] return model @torch.no_grad() def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Dict ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.load(SCREAMING_SNAKE_CASE_ , map_location="cpu" ) SCREAMING_SNAKE_CASE_ : Optional[Any] = checkpoint["Downstream"] SCREAMING_SNAKE_CASE_ : Optional[Any] = WavaVecaConfig.from_pretrained(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : List[str] = WavaVecaFeatureExtractor.from_pretrained( SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , do_normalize=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Optional[int] = hf_config.architectures[0] if arch.endswith("ForSequenceClassification" ): SCREAMING_SNAKE_CASE_ : int = convert_classification(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) elif arch.endswith("ForAudioFrameClassification" ): SCREAMING_SNAKE_CASE_ : List[Any] = convert_diarization(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) elif arch.endswith("ForXVector" ): SCREAMING_SNAKE_CASE_ : Any = convert_xvector(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else: raise NotImplementedError(F"S3PRL weights conversion is not supported for {arch}" ) if hf_config.use_weighted_layer_sum: SCREAMING_SNAKE_CASE_ : Tuple = checkpoint["Featurizer"]["weights"] hf_feature_extractor.save_pretrained(SCREAMING_SNAKE_CASE_ ) hf_model.save_pretrained(SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": snake_case_ = argparse.ArgumentParser() parser.add_argument( '--base_model_name', default=None, type=str, help='Name of the huggingface pretrained base model.' ) parser.add_argument('--config_path', default=None, type=str, help='Path to the huggingface classifier config.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to the s3prl checkpoint.') parser.add_argument('--model_dump_path', default=None, type=str, help='Path to the final converted model.') snake_case_ = parser.parse_args() convert_saprl_checkpoint(args.base_model_name, args.config_path, args.checkpoint_path, args.model_dump_path)
68
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging snake_case_ = logging.get_logger(__name__) snake_case_ = { 'facebook/xmod-base': 'https://huggingface.co/facebook/xmod-base/resolve/main/config.json', 'facebook/xmod-large-prenorm': 'https://huggingface.co/facebook/xmod-large-prenorm/resolve/main/config.json', 'facebook/xmod-base-13-125k': 'https://huggingface.co/facebook/xmod-base-13-125k/resolve/main/config.json', 'facebook/xmod-base-30-125k': 'https://huggingface.co/facebook/xmod-base-30-125k/resolve/main/config.json', 'facebook/xmod-base-30-195k': 'https://huggingface.co/facebook/xmod-base-30-195k/resolve/main/config.json', 'facebook/xmod-base-60-125k': 'https://huggingface.co/facebook/xmod-base-60-125k/resolve/main/config.json', 'facebook/xmod-base-60-265k': 'https://huggingface.co/facebook/xmod-base-60-265k/resolve/main/config.json', 'facebook/xmod-base-75-125k': 'https://huggingface.co/facebook/xmod-base-75-125k/resolve/main/config.json', 'facebook/xmod-base-75-269k': 'https://huggingface.co/facebook/xmod-base-75-269k/resolve/main/config.json', } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = "xmod" def __init__( self , lowercase__=3_0522 , lowercase__=768 , lowercase__=12 , lowercase__=12 , lowercase__=3072 , lowercase__="gelu" , lowercase__=0.1 , lowercase__=0.1 , lowercase__=512 , lowercase__=2 , lowercase__=0.02 , lowercase__=1e-12 , lowercase__=1 , lowercase__=0 , lowercase__=2 , lowercase__="absolute" , lowercase__=True , lowercase__=None , lowercase__=False , lowercase__=2 , lowercase__=False , lowercase__=True , lowercase__=True , lowercase__=("en_XX",) , lowercase__=None , **lowercase__ , ): """simple docstring""" super().__init__(pad_token_id=lowercase__ , bos_token_id=lowercase__ , eos_token_id=lowercase__ , **lowercase__ ) SCREAMING_SNAKE_CASE_ : Tuple = vocab_size SCREAMING_SNAKE_CASE_ : Optional[Any] = hidden_size SCREAMING_SNAKE_CASE_ : Tuple = num_hidden_layers SCREAMING_SNAKE_CASE_ : Optional[int] = num_attention_heads SCREAMING_SNAKE_CASE_ : List[str] = hidden_act SCREAMING_SNAKE_CASE_ : Optional[int] = intermediate_size SCREAMING_SNAKE_CASE_ : Tuple = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : int = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE_ : Dict = type_vocab_size SCREAMING_SNAKE_CASE_ : str = initializer_range SCREAMING_SNAKE_CASE_ : List[str] = layer_norm_eps SCREAMING_SNAKE_CASE_ : Tuple = position_embedding_type SCREAMING_SNAKE_CASE_ : str = use_cache SCREAMING_SNAKE_CASE_ : Optional[int] = classifier_dropout SCREAMING_SNAKE_CASE_ : int = pre_norm SCREAMING_SNAKE_CASE_ : Optional[int] = adapter_reduction_factor SCREAMING_SNAKE_CASE_ : List[str] = adapter_layer_norm SCREAMING_SNAKE_CASE_ : List[str] = adapter_reuse_layer_norm SCREAMING_SNAKE_CASE_ : int = ln_before_adapter SCREAMING_SNAKE_CASE_ : List[Any] = list(lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = default_language class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): @property def __lowerCamelCase ( self ): """simple docstring""" if self.task == "multiple-choice": SCREAMING_SNAKE_CASE_ : Tuple = {0: "batch", 1: "choice", 2: "sequence"} else: SCREAMING_SNAKE_CASE_ : Optional[int] = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
68
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging snake_case_ = logging.get_logger(__name__) snake_case_ = { 'google/realm-cc-news-pretrained-embedder': ( 'https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/config.json' ), 'google/realm-cc-news-pretrained-encoder': ( 'https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/config.json' ), 'google/realm-cc-news-pretrained-scorer': ( 'https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/config.json' ), 'google/realm-cc-news-pretrained-openqa': ( 'https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/config.json' ), 'google/realm-orqa-nq-openqa': 'https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/config.json', 'google/realm-orqa-nq-reader': 'https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/config.json', 'google/realm-orqa-wq-openqa': 'https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/config.json', 'google/realm-orqa-wq-reader': 'https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/config.json', # See all REALM models at https://huggingface.co/models?filter=realm } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = "realm" def __init__( self , lowercase__=3_0522 , lowercase__=768 , lowercase__=128 , lowercase__=12 , lowercase__=12 , lowercase__=8 , lowercase__=3072 , lowercase__="gelu_new" , lowercase__=0.1 , lowercase__=0.1 , lowercase__=512 , lowercase__=2 , lowercase__=0.02 , lowercase__=1e-12 , lowercase__=256 , lowercase__=10 , lowercase__=1e-3 , lowercase__=5 , lowercase__=320 , lowercase__=1335_3718 , lowercase__=5000 , lowercase__=1 , lowercase__=0 , lowercase__=2 , **lowercase__ , ): """simple docstring""" super().__init__(pad_token_id=lowercase__ , bos_token_id=lowercase__ , eos_token_id=lowercase__ , **lowercase__ ) # Common config SCREAMING_SNAKE_CASE_ : List[Any] = vocab_size SCREAMING_SNAKE_CASE_ : Any = max_position_embeddings SCREAMING_SNAKE_CASE_ : List[str] = hidden_size SCREAMING_SNAKE_CASE_ : Union[str, Any] = retriever_proj_size SCREAMING_SNAKE_CASE_ : List[str] = num_hidden_layers SCREAMING_SNAKE_CASE_ : Tuple = num_attention_heads SCREAMING_SNAKE_CASE_ : Dict = num_candidates SCREAMING_SNAKE_CASE_ : List[str] = intermediate_size SCREAMING_SNAKE_CASE_ : Optional[Any] = hidden_act SCREAMING_SNAKE_CASE_ : str = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : Any = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : List[str] = initializer_range SCREAMING_SNAKE_CASE_ : Dict = type_vocab_size SCREAMING_SNAKE_CASE_ : List[Any] = layer_norm_eps # Reader config SCREAMING_SNAKE_CASE_ : List[str] = span_hidden_size SCREAMING_SNAKE_CASE_ : int = max_span_width SCREAMING_SNAKE_CASE_ : Dict = reader_layer_norm_eps SCREAMING_SNAKE_CASE_ : List[str] = reader_beam_size SCREAMING_SNAKE_CASE_ : str = reader_seq_len # Retrieval config SCREAMING_SNAKE_CASE_ : Optional[int] = num_block_records SCREAMING_SNAKE_CASE_ : str = searcher_beam_size
68
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int ) -> int: """simple docstring""" return int((input_a, input_a).count(1 ) != 0 ) def __lowerCamelCase ( ) -> None: """simple docstring""" assert or_gate(0 , 0 ) == 0 assert or_gate(0 , 1 ) == 1 assert or_gate(1 , 0 ) == 1 assert or_gate(1 , 1 ) == 1 if __name__ == "__main__": print(or_gate(0, 1)) print(or_gate(1, 0)) print(or_gate(0, 0)) print(or_gate(1, 1))
68
1
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int ) -> int: """simple docstring""" return int((input_a, input_a).count(1 ) != 0 ) def __lowerCamelCase ( ) -> None: """simple docstring""" assert or_gate(0 , 0 ) == 0 assert or_gate(0 , 1 ) == 1 assert or_gate(1 , 0 ) == 1 assert or_gate(1 , 1 ) == 1 if __name__ == "__main__": print(or_gate(0, 1)) print(or_gate(1, 0)) print(or_gate(0, 0)) print(or_gate(1, 1))
68
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..bit import BitConfig snake_case_ = logging.get_logger(__name__) snake_case_ = { 'Intel/dpt-large': 'https://huggingface.co/Intel/dpt-large/resolve/main/config.json', # See all DPT models at https://huggingface.co/models?filter=dpt } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = "dpt" def __init__( self , lowercase__=768 , lowercase__=12 , lowercase__=12 , lowercase__=3072 , lowercase__="gelu" , lowercase__=0.0 , lowercase__=0.0 , lowercase__=0.02 , lowercase__=1e-12 , lowercase__=384 , lowercase__=16 , lowercase__=3 , lowercase__=False , lowercase__=True , lowercase__=[2, 5, 8, 11] , lowercase__="project" , lowercase__=[4, 2, 1, 0.5] , lowercase__=[96, 192, 384, 768] , lowercase__=256 , lowercase__=-1 , lowercase__=False , lowercase__=True , lowercase__=0.4 , lowercase__=255 , lowercase__=0.1 , lowercase__=[1, 1024, 24, 24] , lowercase__=[0, 1] , lowercase__=None , **lowercase__ , ): """simple docstring""" super().__init__(**lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = hidden_size SCREAMING_SNAKE_CASE_ : Union[str, Any] = is_hybrid if self.is_hybrid: if backbone_config is None: logger.info("Initializing the config with a `BiT` backbone." ) SCREAMING_SNAKE_CASE_ : Tuple = { "global_padding": "same", "layer_type": "bottleneck", "depths": [3, 4, 9], "out_features": ["stage1", "stage2", "stage3"], "embedding_dynamic_padding": True, } SCREAMING_SNAKE_CASE_ : Union[str, Any] = BitConfig(**lowercase__ ) elif isinstance(lowercase__ , lowercase__ ): logger.info("Initializing the config with a `BiT` backbone." ) SCREAMING_SNAKE_CASE_ : Dict = BitConfig(**lowercase__ ) elif isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE_ : Optional[int] = backbone_config else: raise ValueError( F"backbone_config must be a dictionary or a `PretrainedConfig`, got {backbone_config.__class__}." ) SCREAMING_SNAKE_CASE_ : List[Any] = backbone_featmap_shape SCREAMING_SNAKE_CASE_ : Union[str, Any] = neck_ignore_stages if readout_type != "project": raise ValueError("Readout type must be 'project' when using `DPT-hybrid` mode." ) else: SCREAMING_SNAKE_CASE_ : Optional[Any] = None SCREAMING_SNAKE_CASE_ : int = None SCREAMING_SNAKE_CASE_ : List[Any] = [] SCREAMING_SNAKE_CASE_ : int = num_hidden_layers SCREAMING_SNAKE_CASE_ : Union[str, Any] = num_attention_heads SCREAMING_SNAKE_CASE_ : Tuple = intermediate_size SCREAMING_SNAKE_CASE_ : Optional[int] = hidden_act SCREAMING_SNAKE_CASE_ : Dict = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : str = initializer_range SCREAMING_SNAKE_CASE_ : List[Any] = layer_norm_eps SCREAMING_SNAKE_CASE_ : Any = image_size SCREAMING_SNAKE_CASE_ : Union[str, Any] = patch_size SCREAMING_SNAKE_CASE_ : Union[str, Any] = num_channels SCREAMING_SNAKE_CASE_ : Union[str, Any] = qkv_bias SCREAMING_SNAKE_CASE_ : Optional[Any] = backbone_out_indices if readout_type not in ["ignore", "add", "project"]: raise ValueError("Readout_type must be one of ['ignore', 'add', 'project']" ) SCREAMING_SNAKE_CASE_ : Any = readout_type SCREAMING_SNAKE_CASE_ : Optional[Any] = reassemble_factors SCREAMING_SNAKE_CASE_ : str = neck_hidden_sizes SCREAMING_SNAKE_CASE_ : Union[str, Any] = fusion_hidden_size SCREAMING_SNAKE_CASE_ : Any = head_in_index SCREAMING_SNAKE_CASE_ : str = use_batch_norm_in_fusion_residual # auxiliary head attributes (semantic segmentation) SCREAMING_SNAKE_CASE_ : List[Any] = use_auxiliary_head SCREAMING_SNAKE_CASE_ : int = auxiliary_loss_weight SCREAMING_SNAKE_CASE_ : Union[str, Any] = semantic_loss_ignore_index SCREAMING_SNAKE_CASE_ : Any = semantic_classifier_dropout def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = copy.deepcopy(self.__dict__ ) if output["backbone_config"] is not None: SCREAMING_SNAKE_CASE_ : List[str] = self.backbone_config.to_dict() SCREAMING_SNAKE_CASE_ : Optional[int] = self.__class__.model_type return output
68
1
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_roberta import RobertaTokenizer snake_case_ = logging.get_logger(__name__) snake_case_ = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'} snake_case_ = { 'vocab_file': { 'roberta-base': 'https://huggingface.co/roberta-base/resolve/main/vocab.json', 'roberta-large': 'https://huggingface.co/roberta-large/resolve/main/vocab.json', 'roberta-large-mnli': 'https://huggingface.co/roberta-large-mnli/resolve/main/vocab.json', 'distilroberta-base': 'https://huggingface.co/distilroberta-base/resolve/main/vocab.json', 'roberta-base-openai-detector': 'https://huggingface.co/roberta-base-openai-detector/resolve/main/vocab.json', 'roberta-large-openai-detector': ( 'https://huggingface.co/roberta-large-openai-detector/resolve/main/vocab.json' ), }, 'merges_file': { 'roberta-base': 'https://huggingface.co/roberta-base/resolve/main/merges.txt', 'roberta-large': 'https://huggingface.co/roberta-large/resolve/main/merges.txt', 'roberta-large-mnli': 'https://huggingface.co/roberta-large-mnli/resolve/main/merges.txt', 'distilroberta-base': 'https://huggingface.co/distilroberta-base/resolve/main/merges.txt', 'roberta-base-openai-detector': 'https://huggingface.co/roberta-base-openai-detector/resolve/main/merges.txt', 'roberta-large-openai-detector': ( 'https://huggingface.co/roberta-large-openai-detector/resolve/main/merges.txt' ), }, 'tokenizer_file': { 'roberta-base': 'https://huggingface.co/roberta-base/resolve/main/tokenizer.json', 'roberta-large': 'https://huggingface.co/roberta-large/resolve/main/tokenizer.json', 'roberta-large-mnli': 'https://huggingface.co/roberta-large-mnli/resolve/main/tokenizer.json', 'distilroberta-base': 'https://huggingface.co/distilroberta-base/resolve/main/tokenizer.json', 'roberta-base-openai-detector': ( 'https://huggingface.co/roberta-base-openai-detector/resolve/main/tokenizer.json' ), 'roberta-large-openai-detector': ( 'https://huggingface.co/roberta-large-openai-detector/resolve/main/tokenizer.json' ), }, } snake_case_ = { 'roberta-base': 5_1_2, 'roberta-large': 5_1_2, 'roberta-large-mnli': 5_1_2, 'distilroberta-base': 5_1_2, 'roberta-base-openai-detector': 5_1_2, 'roberta-large-openai-detector': 5_1_2, } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = VOCAB_FILES_NAMES _A = PRETRAINED_VOCAB_FILES_MAP _A = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _A = ["input_ids", "attention_mask"] _A = RobertaTokenizer def __init__( self , lowercase__=None , lowercase__=None , lowercase__=None , lowercase__="replace" , lowercase__="<s>" , lowercase__="</s>" , lowercase__="</s>" , lowercase__="<s>" , lowercase__="<unk>" , lowercase__="<pad>" , lowercase__="<mask>" , lowercase__=False , lowercase__=True , **lowercase__ , ): """simple docstring""" super().__init__( lowercase__ , lowercase__ , tokenizer_file=lowercase__ , errors=lowercase__ , bos_token=lowercase__ , eos_token=lowercase__ , sep_token=lowercase__ , cls_token=lowercase__ , unk_token=lowercase__ , pad_token=lowercase__ , mask_token=lowercase__ , add_prefix_space=lowercase__ , trim_offsets=lowercase__ , **lowercase__ , ) SCREAMING_SNAKE_CASE_ : Dict = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("add_prefix_space" , lowercase__ ) != add_prefix_space: SCREAMING_SNAKE_CASE_ : int = getattr(lowercase__ , pre_tok_state.pop("type" ) ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = add_prefix_space SCREAMING_SNAKE_CASE_ : str = pre_tok_class(**lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = add_prefix_space SCREAMING_SNAKE_CASE_ : Union[str, Any] = "post_processor" SCREAMING_SNAKE_CASE_ : Union[str, Any] = getattr(self.backend_tokenizer , lowercase__ , lowercase__ ) if tokenizer_component_instance: SCREAMING_SNAKE_CASE_ : Optional[int] = json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: SCREAMING_SNAKE_CASE_ : Optional[Any] = tuple(state["sep"] ) if "cls" in state: SCREAMING_SNAKE_CASE_ : Optional[Any] = tuple(state["cls"] ) SCREAMING_SNAKE_CASE_ : Optional[int] = False if state.get("add_prefix_space" , lowercase__ ) != add_prefix_space: SCREAMING_SNAKE_CASE_ : Dict = add_prefix_space SCREAMING_SNAKE_CASE_ : Any = True if state.get("trim_offsets" , lowercase__ ) != trim_offsets: SCREAMING_SNAKE_CASE_ : Optional[int] = trim_offsets SCREAMING_SNAKE_CASE_ : Tuple = True if changes_to_apply: SCREAMING_SNAKE_CASE_ : Optional[int] = getattr(lowercase__ , state.pop("type" ) ) SCREAMING_SNAKE_CASE_ : str = component_class(**lowercase__ ) setattr(self.backend_tokenizer , lowercase__ , lowercase__ ) @property def __lowerCamelCase ( self ): """simple docstring""" if self._mask_token is None: if self.verbose: logger.error("Using mask_token, but it is not set yet." ) return None return str(self._mask_token ) @mask_token.setter def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = AddedToken(lowercase__ , lstrip=lowercase__ , rstrip=lowercase__ ) if isinstance(lowercase__ , lowercase__ ) else value SCREAMING_SNAKE_CASE_ : List[str] = value def __lowerCamelCase ( self , *lowercase__ , **lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = kwargs.get("is_split_into_words" , lowercase__ ) assert self.add_prefix_space or not is_split_into_words, ( F"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*lowercase__ , **lowercase__ ) def __lowerCamelCase ( self , *lowercase__ , **lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = kwargs.get("is_split_into_words" , lowercase__ ) assert self.add_prefix_space or not is_split_into_words, ( F"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " "to use it with pretokenized inputs." ) return super()._encode_plus(*lowercase__ , **lowercase__ ) def __lowerCamelCase ( self , lowercase__ , lowercase__ = None ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = self._tokenizer.model.save(lowercase__ , name=lowercase__ ) return tuple(lowercase__ ) def __lowerCamelCase ( self , lowercase__ , lowercase__=None ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def __lowerCamelCase ( self , lowercase__ , lowercase__ = None ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = [self.sep_token_id] SCREAMING_SNAKE_CASE_ : Optional[int] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
68
'''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 if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ChineseCLIPImageProcessor class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __init__( self , lowercase__ , lowercase__=7 , lowercase__=3 , lowercase__=18 , lowercase__=30 , lowercase__=400 , lowercase__=True , lowercase__=None , lowercase__=True , lowercase__=None , lowercase__=True , lowercase__=[0.48145466, 0.4578275, 0.40821073] , lowercase__=[0.26862954, 0.26130258, 0.27577711] , lowercase__=True , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = size if size is not None else {"height": 224, "width": 224} SCREAMING_SNAKE_CASE_ : Optional[Any] = crop_size if crop_size is not None else {"height": 18, "width": 18} SCREAMING_SNAKE_CASE_ : str = parent SCREAMING_SNAKE_CASE_ : List[Any] = batch_size SCREAMING_SNAKE_CASE_ : Dict = num_channels SCREAMING_SNAKE_CASE_ : Any = image_size SCREAMING_SNAKE_CASE_ : Tuple = min_resolution SCREAMING_SNAKE_CASE_ : Optional[Any] = max_resolution SCREAMING_SNAKE_CASE_ : Tuple = do_resize SCREAMING_SNAKE_CASE_ : List[str] = size SCREAMING_SNAKE_CASE_ : str = do_center_crop SCREAMING_SNAKE_CASE_ : List[str] = crop_size SCREAMING_SNAKE_CASE_ : int = do_normalize SCREAMING_SNAKE_CASE_ : Optional[int] = image_mean SCREAMING_SNAKE_CASE_ : Dict = image_std SCREAMING_SNAKE_CASE_ : List[Any] = do_convert_rgb def __lowerCamelCase ( self ): """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_convert_rgb": self.do_convert_rgb, } def __lowerCamelCase ( self , lowercase__=False , lowercase__=False , lowercase__=False ): """simple docstring""" assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time" if equal_resolution: SCREAMING_SNAKE_CASE_ : Optional[int] = [] for i in range(self.batch_size ): image_inputs.append( np.random.randint( 255 , size=(self.num_channels, self.max_resolution, self.max_resolution) , dtype=np.uinta ) ) else: SCREAMING_SNAKE_CASE_ : str = [] for i in range(self.batch_size ): SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[Any] = np.random.choice(np.arange(self.min_resolution , self.max_resolution ) , 2 ) image_inputs.append(np.random.randint(255 , size=(self.num_channels, width, height) , dtype=np.uinta ) ) if not numpify and not torchify: # PIL expects the channel dimension as last dimension SCREAMING_SNAKE_CASE_ : str = [Image.fromarray(np.moveaxis(lowercase__ , 0 , -1 ) ) for x in image_inputs] if torchify: SCREAMING_SNAKE_CASE_ : List[str] = [torch.from_numpy(lowercase__ ) for x in image_inputs] return image_inputs @require_torch @require_vision class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,unittest.TestCase ): _A = ChineseCLIPImageProcessor if is_vision_available() else None def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = ChineseCLIPImageProcessingTester(self , do_center_crop=lowercase__ ) @property def __lowerCamelCase ( self ): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowercase__ , "do_resize" ) ) self.assertTrue(hasattr(lowercase__ , "size" ) ) self.assertTrue(hasattr(lowercase__ , "do_center_crop" ) ) self.assertTrue(hasattr(lowercase__ , "center_crop" ) ) self.assertTrue(hasattr(lowercase__ , "do_normalize" ) ) self.assertTrue(hasattr(lowercase__ , "image_mean" ) ) self.assertTrue(hasattr(lowercase__ , "image_std" ) ) self.assertTrue(hasattr(lowercase__ , "do_convert_rgb" ) ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"height": 224, "width": 224} ) self.assertEqual(image_processor.crop_size , {"height": 18, "width": 18} ) SCREAMING_SNAKE_CASE_ : str = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 ) self.assertEqual(image_processor.size , {"shortest_edge": 42} ) self.assertEqual(image_processor.crop_size , {"height": 84, "width": 84} ) def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE_ : Tuple = self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__ ) for image in image_inputs: self.assertIsInstance(lowercase__ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE_ : Dict = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE_ : Optional[int] = image_processing(lowercase__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__ , numpify=lowercase__ ) for image in image_inputs: self.assertIsInstance(lowercase__ , np.ndarray ) # Test not batched input SCREAMING_SNAKE_CASE_ : Optional[int] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE_ : List[str] = image_processing(lowercase__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors SCREAMING_SNAKE_CASE_ : List[str] = self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__ , torchify=lowercase__ ) for image in image_inputs: self.assertIsInstance(lowercase__ , torch.Tensor ) # Test not batched input SCREAMING_SNAKE_CASE_ : Union[str, Any] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE_ : int = image_processing(lowercase__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) @require_torch @require_vision class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,unittest.TestCase ): _A = ChineseCLIPImageProcessor if is_vision_available() else None def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int = ChineseCLIPImageProcessingTester(self , num_channels=4 , do_center_crop=lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = 3 @property def __lowerCamelCase ( self ): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowercase__ , "do_resize" ) ) self.assertTrue(hasattr(lowercase__ , "size" ) ) self.assertTrue(hasattr(lowercase__ , "do_center_crop" ) ) self.assertTrue(hasattr(lowercase__ , "center_crop" ) ) self.assertTrue(hasattr(lowercase__ , "do_normalize" ) ) self.assertTrue(hasattr(lowercase__ , "image_mean" ) ) self.assertTrue(hasattr(lowercase__ , "image_std" ) ) self.assertTrue(hasattr(lowercase__ , "do_convert_rgb" ) ) def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE_ : Optional[int] = self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__ ) for image in image_inputs: self.assertIsInstance(lowercase__ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE_ : Optional[Any] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE_ : List[str] = image_processing(lowercase__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , )
68
1
'''simple docstring''' from __future__ import annotations def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , ) -> tuple: """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()
68
'''simple docstring''' from __future__ import annotations def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int ) -> bool: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = str(SCREAMING_SNAKE_CASE_ ) return len(SCREAMING_SNAKE_CASE_ ) == 9 and set(SCREAMING_SNAKE_CASE_ ) == set("123456789" ) def __lowerCamelCase ( ) -> int | None: """simple docstring""" for base_num in range(9_9_9_9 , 4_9_9_9 , -1 ): SCREAMING_SNAKE_CASE_ : int = 1_0_0_0_0_2 * base_num if is_9_pandigital(SCREAMING_SNAKE_CASE_ ): return candidate for base_num in range(3_3_3 , 9_9 , -1 ): SCREAMING_SNAKE_CASE_ : List[str] = 1_0_0_2_0_0_3 * base_num if is_9_pandigital(SCREAMING_SNAKE_CASE_ ): return candidate return None if __name__ == "__main__": print(F'''{solution() = }''')
68
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available snake_case_ = { 'configuration_clap': [ 'CLAP_PRETRAINED_MODEL_ARCHIVE_LIST', 'ClapAudioConfig', 'ClapConfig', 'ClapTextConfig', ], 'processing_clap': ['ClapProcessor'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ = [ 'CLAP_PRETRAINED_MODEL_ARCHIVE_LIST', 'ClapModel', 'ClapPreTrainedModel', 'ClapTextModel', 'ClapTextModelWithProjection', 'ClapAudioModel', 'ClapAudioModelWithProjection', ] snake_case_ = ['ClapFeatureExtractor'] if TYPE_CHECKING: from .configuration_clap import ( CLAP_PRETRAINED_MODEL_ARCHIVE_LIST, ClapAudioConfig, ClapConfig, ClapTextConfig, ) from .processing_clap import ClapProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_clap import ClapFeatureExtractor from .modeling_clap import ( CLAP_PRETRAINED_MODEL_ARCHIVE_LIST, ClapAudioModel, ClapAudioModelWithProjection, ClapModel, ClapPreTrainedModel, ClapTextModel, ClapTextModelWithProjection, ) else: import sys snake_case_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
68
'''simple docstring''' from typing import Optional import pyspark from .. import Features, NamedSplit from ..download import DownloadMode from ..packaged_modules.spark.spark import Spark from .abc import AbstractDatasetReader class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): def __init__( self , lowercase__ , lowercase__ = None , lowercase__ = None , lowercase__ = True , lowercase__ = None , lowercase__ = False , lowercase__ = None , lowercase__ = True , lowercase__ = "arrow" , **lowercase__ , ): """simple docstring""" super().__init__( split=lowercase__ , features=lowercase__ , cache_dir=lowercase__ , keep_in_memory=lowercase__ , streaming=lowercase__ , **lowercase__ , ) SCREAMING_SNAKE_CASE_ : Any = load_from_cache_file SCREAMING_SNAKE_CASE_ : Optional[int] = file_format SCREAMING_SNAKE_CASE_ : List[Any] = Spark( df=lowercase__ , features=lowercase__ , cache_dir=lowercase__ , working_dir=lowercase__ , **lowercase__ , ) def __lowerCamelCase ( self ): """simple docstring""" if self.streaming: return self.builder.as_streaming_dataset(split=self.split ) SCREAMING_SNAKE_CASE_ : Optional[int] = None if self._load_from_cache_file else DownloadMode.FORCE_REDOWNLOAD self.builder.download_and_prepare( download_mode=lowercase__ , file_format=self._file_format , ) return self.builder.as_dataset(split=self.split )
68
1
'''simple docstring''' from typing import List from .keymap import KEYMAP, get_character def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str ) -> List[Any]: """simple docstring""" def decorator(SCREAMING_SNAKE_CASE_ : int ): SCREAMING_SNAKE_CASE_ : Any = getattr(SCREAMING_SNAKE_CASE_ , "handle_key" , [] ) handle += [key] setattr(SCREAMING_SNAKE_CASE_ , "handle_key" , SCREAMING_SNAKE_CASE_ ) return func return decorator def __lowerCamelCase ( *SCREAMING_SNAKE_CASE_ : List[str] ) -> List[Any]: """simple docstring""" def decorator(SCREAMING_SNAKE_CASE_ : List[str] ): SCREAMING_SNAKE_CASE_ : Optional[Any] = getattr(SCREAMING_SNAKE_CASE_ , "handle_key" , [] ) handle += keys setattr(SCREAMING_SNAKE_CASE_ , "handle_key" , SCREAMING_SNAKE_CASE_ ) return func return decorator class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): def __new__( cls , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = super().__new__(cls , lowercase__ , lowercase__ , lowercase__ ) if not hasattr(lowercase__ , "key_handler" ): setattr(lowercase__ , "key_handler" , {} ) setattr(lowercase__ , "handle_input" , KeyHandler.handle_input ) for value in attrs.values(): SCREAMING_SNAKE_CASE_ : Tuple = getattr(lowercase__ , "handle_key" , [] ) for key in handled_keys: SCREAMING_SNAKE_CASE_ : Union[str, Any] = value return new_cls @staticmethod def __lowerCamelCase ( cls ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = get_character() if char != KEYMAP["undefined"]: SCREAMING_SNAKE_CASE_ : Optional[Any] = ord(lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = cls.key_handler.get(lowercase__ ) if handler: SCREAMING_SNAKE_CASE_ : Any = char return handler(cls ) else: return None def __lowerCamelCase ( cls : Optional[int] ) -> Optional[Any]: """simple docstring""" return KeyHandler(cls.__name__ , cls.__bases__ , cls.__dict__.copy() )
68
'''simple docstring''' import re import string import numpy as np import datasets snake_case_ = '\nReturns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list.\n' snake_case_ = '\nArgs:\n predictions: List of predicted texts.\n references: List of reference texts.\n regexes_to_ignore: List, defaults to None. Regex expressions of characters to\n ignore when calculating the exact matches. Note: these regexes are removed\n from the input data before the changes based on the options below (e.g. ignore_case,\n ignore_punctuation, ignore_numbers) are applied.\n ignore_case: Boolean, defaults to False. If true, turns everything\n to lowercase so that capitalization differences are ignored.\n ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\n ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\nReturns:\n exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive.\nExamples:\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results["exact_match"], 1))\n 25.0\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results["exact_match"], 1))\n 50.0\n\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results["exact_match"], 1))\n 75.0\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True)\n >>> print(round(results["exact_match"], 1))\n 100.0\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["The cat sat on the mat.", "Theaters are great.", "It\'s like comparing oranges and apples."]\n >>> preds = ["The cat sat on the mat?", "Theaters are great.", "It\'s like comparing apples and oranges."]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results["exact_match"], 1))\n 33.3\n\n' snake_case_ = '\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION,_KWARGS_DESCRIPTION ) class SCREAMING_SNAKE_CASE__ ( datasets.Metric ): def __lowerCamelCase ( self ): """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Value("string" , id="sequence" ), "references": datasets.Value("string" , id="sequence" ), } ) , reference_urls=[] , ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__=None , lowercase__=False , lowercase__=False , lowercase__=False , ): """simple docstring""" if regexes_to_ignore is not None: for s in regexes_to_ignore: SCREAMING_SNAKE_CASE_ : Optional[Any] = np.array([re.sub(lowercase__ , "" , lowercase__ ) for x in predictions] ) SCREAMING_SNAKE_CASE_ : List[Any] = np.array([re.sub(lowercase__ , "" , lowercase__ ) for x in references] ) else: SCREAMING_SNAKE_CASE_ : int = np.asarray(lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = np.asarray(lowercase__ ) if ignore_case: SCREAMING_SNAKE_CASE_ : Dict = np.char.lower(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = np.char.lower(lowercase__ ) if ignore_punctuation: SCREAMING_SNAKE_CASE_ : Optional[int] = string.punctuation.maketrans("" , "" , string.punctuation ) SCREAMING_SNAKE_CASE_ : int = np.char.translate(lowercase__ , table=lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = np.char.translate(lowercase__ , table=lowercase__ ) if ignore_numbers: SCREAMING_SNAKE_CASE_ : Optional[int] = string.digits.maketrans("" , "" , string.digits ) SCREAMING_SNAKE_CASE_ : Dict = np.char.translate(lowercase__ , table=lowercase__ ) SCREAMING_SNAKE_CASE_ : int = np.char.translate(lowercase__ , table=lowercase__ ) SCREAMING_SNAKE_CASE_ : str = predictions == references return {"exact_match": np.mean(lowercase__ ) * 100}
68
1
'''simple docstring''' import gc import random import unittest import numpy as np import torch from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModel, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import AutoencoderKL, DDIMScheduler, DDPMScheduler, StableUnCLIPImgaImgPipeline, UNetaDConditionModel from diffusers.pipelines.pipeline_utils import DiffusionPipeline from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import ( enable_full_determinism, floats_tensor, load_image, load_numpy, require_torch_gpu, skip_mps, slow, torch_device, ) from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS from ..test_pipelines_common import ( PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin, assert_mean_pixel_difference, ) enable_full_determinism() class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,_UpperCAmelCase,_UpperCAmelCase,unittest.TestCase ): _A = StableUnCLIPImgaImgPipeline _A = TEXT_GUIDED_IMAGE_VARIATION_PARAMS _A = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS _A = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess _A = frozenset([] ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = 32 SCREAMING_SNAKE_CASE_ : List[Any] = embedder_hidden_size # image encoding components SCREAMING_SNAKE_CASE_ : int = CLIPImageProcessor(crop_size=32 , size=32 ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ : Any = CLIPVisionModelWithProjection( CLIPVisionConfig( hidden_size=lowercase__ , projection_dim=lowercase__ , num_hidden_layers=5 , num_attention_heads=4 , image_size=32 , intermediate_size=37 , patch_size=1 , ) ) # regular denoising components torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ : str = StableUnCLIPImageNormalizer(embedding_dim=lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = DDPMScheduler(beta_schedule="squaredcos_cap_v2" ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ : Tuple = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ : List[Any] = CLIPTextModel( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=lowercase__ , projection_dim=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ : Dict = UNetaDConditionModel( sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("CrossAttnDownBlock2D", "DownBlock2D") , up_block_types=("UpBlock2D", "CrossAttnUpBlock2D") , block_out_channels=(32, 64) , attention_head_dim=(2, 4) , class_embed_type="projection" , projection_class_embeddings_input_dim=embedder_projection_dim * 2 , cross_attention_dim=lowercase__ , layers_per_block=1 , upcast_attention=lowercase__ , use_linear_projection=lowercase__ , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ : str = DDIMScheduler( beta_schedule="scaled_linear" , beta_start=0.00085 , beta_end=0.012 , prediction_type="v_prediction" , set_alpha_to_one=lowercase__ , steps_offset=1 , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ : Optional[Any] = AutoencoderKL() SCREAMING_SNAKE_CASE_ : Tuple = { # image encoding components "feature_extractor": feature_extractor, "image_encoder": image_encoder.eval(), # image noising components "image_normalizer": image_normalizer.eval(), "image_noising_scheduler": image_noising_scheduler, # regular denoising components "tokenizer": tokenizer, "text_encoder": text_encoder.eval(), "unet": unet.eval(), "scheduler": scheduler, "vae": vae.eval(), } return components def __lowerCamelCase ( self , lowercase__ , lowercase__=0 , lowercase__=True ): """simple docstring""" if str(lowercase__ ).startswith("mps" ): SCREAMING_SNAKE_CASE_ : Optional[int] = torch.manual_seed(lowercase__ ) else: SCREAMING_SNAKE_CASE_ : List[str] = torch.Generator(device=lowercase__ ).manual_seed(lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = floats_tensor((1, 3, 32, 32) , rng=random.Random(lowercase__ ) ).to(lowercase__ ) if pil_image: SCREAMING_SNAKE_CASE_ : Optional[Any] = input_image * 0.5 + 0.5 SCREAMING_SNAKE_CASE_ : List[Any] = input_image.clamp(0 , 1 ) SCREAMING_SNAKE_CASE_ : Dict = input_image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() SCREAMING_SNAKE_CASE_ : int = DiffusionPipeline.numpy_to_pil(lowercase__ )[0] return { "prompt": "An anime racoon running a marathon", "image": input_image, "generator": generator, "num_inference_steps": 2, "output_type": "np", } @skip_mps def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = "cpu" # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE_ : Dict = self.get_dummy_components() SCREAMING_SNAKE_CASE_ : Any = StableUnCLIPImgaImgPipeline(**lowercase__ ) SCREAMING_SNAKE_CASE_ : int = sd_pipe.to(lowercase__ ) sd_pipe.set_progress_bar_config(disable=lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = self.get_dummy_inputs(lowercase__ ) inputs.update({"image_embeds": None} ) SCREAMING_SNAKE_CASE_ : Dict = sd_pipe(**lowercase__ ).images SCREAMING_SNAKE_CASE_ : int = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE_ : Any = np.array([0.3872, 0.7224, 0.5601, 0.4741, 0.6872, 0.5814, 0.4636, 0.3867, 0.5078] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = torch_device in ["cpu", "mps"] self._test_attention_slicing_forward_pass(test_max_difference=lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = torch_device in ["cpu", "mps"] self._test_inference_batch_single_identical(test_max_difference=lowercase__ ) @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def __lowerCamelCase ( self ): """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(test_max_difference=lowercase__ ) @slow @require_torch_gpu class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __lowerCamelCase ( self ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png" ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_img2img_anime_turtle_fp16.npy" ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = StableUnCLIPImgaImgPipeline.from_pretrained( "fusing/stable-unclip-2-1-l-img2img" , torch_dtype=torch.floataa ) pipe.to(lowercase__ ) pipe.set_progress_bar_config(disable=lowercase__ ) # stable unclip will oom when integration tests are run on a V100, # so turn on memory savings pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() SCREAMING_SNAKE_CASE_ : List[str] = torch.Generator(device="cpu" ).manual_seed(0 ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = pipe(lowercase__ , "anime turle" , generator=lowercase__ , output_type="np" ) SCREAMING_SNAKE_CASE_ : str = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(lowercase__ , lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png" ) SCREAMING_SNAKE_CASE_ : List[Any] = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_h_img2img_anime_turtle_fp16.npy" ) SCREAMING_SNAKE_CASE_ : int = StableUnCLIPImgaImgPipeline.from_pretrained( "fusing/stable-unclip-2-1-h-img2img" , torch_dtype=torch.floataa ) pipe.to(lowercase__ ) pipe.set_progress_bar_config(disable=lowercase__ ) # stable unclip will oom when integration tests are run on a V100, # so turn on memory savings pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() SCREAMING_SNAKE_CASE_ : int = torch.Generator(device="cpu" ).manual_seed(0 ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = pipe(lowercase__ , "anime turle" , generator=lowercase__ , output_type="np" ) SCREAMING_SNAKE_CASE_ : Optional[Any] = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(lowercase__ , lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png" ) torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() SCREAMING_SNAKE_CASE_ : List[str] = StableUnCLIPImgaImgPipeline.from_pretrained( "fusing/stable-unclip-2-1-h-img2img" , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE_ : Dict = pipe.to(lowercase__ ) pipe.set_progress_bar_config(disable=lowercase__ ) pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() SCREAMING_SNAKE_CASE_ : List[Any] = pipe( lowercase__ , "anime turtle" , num_inference_steps=2 , output_type="np" , ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.cuda.max_memory_allocated() # make sure that less than 7 GB is allocated assert mem_bytes < 7 * 10**9
68
'''simple docstring''' import os import re import unicodedata from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import is_torch_available, logging if is_torch_available(): import torch if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation snake_case_ = logging.get_logger(__name__) snake_case_ = {'vocab_file': 'spiece.model'} snake_case_ = { 'vocab_file': { 'AI-Sweden/gpt-sw3-126m': 'https://huggingface.co/AI-Sweden/gpt-sw3-126m/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-350m': 'https://huggingface.co/AI-Sweden/gpt-sw3-350m/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-1.6b': 'https://huggingface.co/AI-Sweden/gpt-sw3-1.6b/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-6.7b': 'https://huggingface.co/AI-Sweden/gpt-sw3-6.7b/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-20b': 'https://huggingface.co/AI-Sweden/gpt-sw3-20b/resolve/main/spiece.model', } } snake_case_ = { 'AI-Sweden/gpt-sw3-126m': 2_0_4_8, 'AI-Sweden/gpt-sw3-350m': 2_0_4_8, 'AI-Sweden/gpt-sw3-1.6b': 2_0_4_8, 'AI-Sweden/gpt-sw3-6.7b': 2_0_4_8, 'AI-Sweden/gpt-sw3-20b': 2_0_4_8, } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = VOCAB_FILES_NAMES _A = PRETRAINED_VOCAB_FILES_MAP _A = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _A = ["input_ids", "attention_mask"] def __init__( self , lowercase__ , lowercase__=False , lowercase__=False , lowercase__=False , lowercase__=None , lowercase__=None , lowercase__=None , lowercase__=None , lowercase__ = None , **lowercase__ , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = {} if sp_model_kwargs is None else sp_model_kwargs SCREAMING_SNAKE_CASE_ : Dict = kwargs.get("name_or_path" ) if name_or_path is None: logger.warning( "name_or_path not provided, will work for all GPTSw3 models except gpt-sw3-7b," " you are testing the model, this can safely be ignored" ) SCREAMING_SNAKE_CASE_ : str = "None" # Default definitions for our 2 tokenizer versions, with None-checks to enable proper testing SCREAMING_SNAKE_CASE_ : List[Any] = "<|endoftext|>" if eos_token is None else eos_token SCREAMING_SNAKE_CASE_ : Dict = "<unk>" if unk_token is None else unk_token if "gpt-sw3-7b" in name_or_path: SCREAMING_SNAKE_CASE_ : Tuple = unk_token if pad_token is None else pad_token SCREAMING_SNAKE_CASE_ : Optional[Any] = eos_token if bos_token is None else bos_token else: SCREAMING_SNAKE_CASE_ : int = "<pad>" if pad_token is None else pad_token SCREAMING_SNAKE_CASE_ : Any = "<s>" if bos_token is None else bos_token super().__init__( do_lower_case=lowercase__ , remove_space=lowercase__ , keep_accents=lowercase__ , bos_token=lowercase__ , eos_token=lowercase__ , unk_token=lowercase__ , pad_token=lowercase__ , sp_model_kwargs=self.sp_model_kwargs , **lowercase__ , ) SCREAMING_SNAKE_CASE_ : Optional[Any] = do_lower_case SCREAMING_SNAKE_CASE_ : Optional[int] = remove_space SCREAMING_SNAKE_CASE_ : int = keep_accents SCREAMING_SNAKE_CASE_ : List[Any] = vocab_file SCREAMING_SNAKE_CASE_ : List[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(lowercase__ ) # Used for whitespace normalization in input texts # fmt : off SCREAMING_SNAKE_CASE_ : int = {" ", " ", " ", " ", " ", " ", " ", " ", " ", " ", "", "„"} # fmt : on # Regular expression to remove non-printing characters (e.g. some unicode control chars) in preprocessing SCREAMING_SNAKE_CASE_ : List[str] = re.compile( F"[{''.join(map(lowercase__ , list(range(0 , 9 ) ) + list(range(11 , 32 ) ) + list(range(127 , 160 ) ) + [160, 173, 8203] ) )}]" ) def __getstate__( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = self.__dict__.copy() SCREAMING_SNAKE_CASE_ : Dict = None return state def __setstate__( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): SCREAMING_SNAKE_CASE_ : Union[str, Any] = {} SCREAMING_SNAKE_CASE_ : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) @property # Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.vocab_size def __lowerCamelCase ( self ): """simple docstring""" return len(self.sp_model ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.non_printing_characters_re.sub("" , lowercase__ ) # Normalize whitespaces SCREAMING_SNAKE_CASE_ : List[str] = "".join([char if char not in self.whitespaces else " " for char in text] ) # NFC Unicode normalization SCREAMING_SNAKE_CASE_ : List[Any] = unicodedata.normalize("NFC" , lowercase__ ) return text def __lowerCamelCase ( self , lowercase__ , **lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = self.preprocess_text(lowercase__ ) return self.sp_model.encode(lowercase__ , out_type=lowercase__ ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" return self.sp_model.PieceToId(lowercase__ ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" return self.sp_model.IdToPiece(lowercase__ ) @staticmethod def __lowerCamelCase ( lowercase__ ): """simple docstring""" return out_string def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = [] SCREAMING_SNAKE_CASE_ : Any = "" SCREAMING_SNAKE_CASE_ : Dict = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: # TODO: Check if this is needed, as it ensures that decode(encode(doc)) != doc by adding extra whitespace in the decoded document if not prev_is_special: out_string += " " out_string += self.sp_model.decode(lowercase__ ) + token SCREAMING_SNAKE_CASE_ : Union[str, Any] = True SCREAMING_SNAKE_CASE_ : int = [] else: current_sub_tokens.append(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = False out_string += self.sp_model.decode(lowercase__ ) return out_string def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = {self.convert_ids_to_tokens(lowercase__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __lowerCamelCase ( self , lowercase__ , lowercase__ = None ): """simple docstring""" if not os.path.isdir(lowercase__ ): logger.error(F"Vocabulary path ({save_directory}) should be a directory" ) return SCREAMING_SNAKE_CASE_ : Any = os.path.join( lowercase__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(lowercase__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , lowercase__ ) elif not os.path.isfile(self.vocab_file ): with open(lowercase__ , "wb" ) as fi: SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.sp_model.serialized_model_proto() fi.write(lowercase__ ) return (out_vocab_file,) def __lowerCamelCase ( self , lowercase__ , lowercase__ = False ): """simple docstring""" if isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE_ : List[Any] = self.preprocess_text(lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = self.sp_model.encode(lowercase__ ) else: SCREAMING_SNAKE_CASE_ : str = [self.preprocess_text(lowercase__ ) for t in text] SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.sp_model.encode(lowercase__ ) if return_tensors is True or return_tensors == "pt": SCREAMING_SNAKE_CASE_ : str = torch.tensor(lowercase__ ) return token_ids def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" return self.sp_model.decode(lowercase__ ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = [F"User: {text}" if is_user else F"Bot: {text}" for is_user, text in conversation.iter_texts()] SCREAMING_SNAKE_CASE_ : List[str] = ( F"{self.eos_token}{self.bos_token}" + F"{self.bos_token}".join(lowercase__ ) + F"{self.bos_token}Bot:" ) return self.encode(text=lowercase__ )
68
1
'''simple docstring''' import argparse from collections import defaultdict import yaml snake_case_ = 'docs/source/en/_toctree.yml' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : List[Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : str = defaultdict(SCREAMING_SNAKE_CASE_ ) for doc in model_doc: counts[doc["local"]] += 1 SCREAMING_SNAKE_CASE_ : str = [key for key, value in counts.items() if value > 1] SCREAMING_SNAKE_CASE_ : Any = [] for duplicate_key in duplicates: SCREAMING_SNAKE_CASE_ : Any = list({doc["title"] for doc in model_doc if doc["local"] == duplicate_key} ) if len(SCREAMING_SNAKE_CASE_ ) > 1: raise ValueError( F"{duplicate_key} is present several times in the documentation table of content at " "`docs/source/en/_toctree.yml` with different *Title* values. Choose one of those and remove the " "others." ) # Only add this once new_doc.append({"local": duplicate_key, "title": titles[0]} ) # Add none duplicate-keys new_doc.extend([doc for doc in model_doc if counts[doc["local"]] == 1] ) # Sort return sorted(SCREAMING_SNAKE_CASE_ , key=lambda SCREAMING_SNAKE_CASE_ : s["title"].lower() ) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str=False ) -> Tuple: """simple docstring""" with open(SCREAMING_SNAKE_CASE_ , encoding="utf-8" ) as f: SCREAMING_SNAKE_CASE_ : List[str] = yaml.safe_load(f.read() ) # Get to the API doc SCREAMING_SNAKE_CASE_ : Any = 0 while content[api_idx]["title"] != "API": api_idx += 1 SCREAMING_SNAKE_CASE_ : Dict = content[api_idx]["sections"] # Then to the model doc SCREAMING_SNAKE_CASE_ : int = 0 while api_doc[model_idx]["title"] != "Models": model_idx += 1 SCREAMING_SNAKE_CASE_ : List[Any] = api_doc[model_idx]["sections"] SCREAMING_SNAKE_CASE_ : Union[str, Any] = [(idx, section) for idx, section in enumerate(SCREAMING_SNAKE_CASE_ ) if "sections" in section] SCREAMING_SNAKE_CASE_ : Tuple = False for idx, modality_doc in modalities_docs: SCREAMING_SNAKE_CASE_ : str = modality_doc["sections"] SCREAMING_SNAKE_CASE_ : int = clean_model_doc_toc(SCREAMING_SNAKE_CASE_ ) if old_modality_doc != new_modality_doc: SCREAMING_SNAKE_CASE_ : List[Any] = True if overwrite: SCREAMING_SNAKE_CASE_ : Optional[int] = new_modality_doc if diff: if overwrite: SCREAMING_SNAKE_CASE_ : Optional[int] = model_doc SCREAMING_SNAKE_CASE_ : List[Any] = api_doc with open(SCREAMING_SNAKE_CASE_ , "w" , encoding="utf-8" ) as f: f.write(yaml.dump(SCREAMING_SNAKE_CASE_ , allow_unicode=SCREAMING_SNAKE_CASE_ ) ) else: raise ValueError( "The model doc part of the table of content is not properly sorted, run `make style` to fix this." ) if __name__ == "__main__": snake_case_ = argparse.ArgumentParser() parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.') snake_case_ = parser.parse_args() check_model_doc(args.fix_and_overwrite)
68
'''simple docstring''' import re from filelock import FileLock try: import nltk snake_case_ = True except (ImportError, ModuleNotFoundError): snake_case_ = False if NLTK_AVAILABLE: with FileLock('.lock') as lock: nltk.download('punkt', quiet=True) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str ) -> str: """simple docstring""" re.sub("<n>" , "" , SCREAMING_SNAKE_CASE_ ) # remove pegasus newline char assert NLTK_AVAILABLE, "nltk must be installed to separate newlines between sentences. (pip install nltk)" return "\n".join(nltk.sent_tokenize(SCREAMING_SNAKE_CASE_ ) )
68
1
'''simple docstring''' import math import os import sys def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = "" try: with open(SCREAMING_SNAKE_CASE_ , "rb" ) as binary_file: SCREAMING_SNAKE_CASE_ : int = binary_file.read() for dat in data: SCREAMING_SNAKE_CASE_ : Optional[Any] = F"{dat:08b}" result += curr_byte return result except OSError: print("File not accessible" ) sys.exit() def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : dict[str, str] , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : str ) -> None: """simple docstring""" lexicon.pop(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : str = last_match_id if math.loga(SCREAMING_SNAKE_CASE_ ).is_integer(): for curr_key in lexicon: SCREAMING_SNAKE_CASE_ : List[str] = "0" + lexicon[curr_key] SCREAMING_SNAKE_CASE_ : int = bin(SCREAMING_SNAKE_CASE_ )[2:] def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE_ : int = {"0": "0", "1": "1"} SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : str = "", "" SCREAMING_SNAKE_CASE_ : Any = len(SCREAMING_SNAKE_CASE_ ) for i in range(len(SCREAMING_SNAKE_CASE_ ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue SCREAMING_SNAKE_CASE_ : Tuple = lexicon[curr_string] result += last_match_id add_key_to_lexicon(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) index += 1 SCREAMING_SNAKE_CASE_ : Union[str, Any] = "" while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": SCREAMING_SNAKE_CASE_ : int = lexicon[curr_string] result += last_match_id return result def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : str ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = os.path.getsize(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = bin(SCREAMING_SNAKE_CASE_ )[2:] SCREAMING_SNAKE_CASE_ : Optional[Any] = len(SCREAMING_SNAKE_CASE_ ) return "0" * (length_length - 1) + file_length_binary + compressed def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : str ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = 8 try: with open(SCREAMING_SNAKE_CASE_ , "wb" ) as opened_file: SCREAMING_SNAKE_CASE_ : Tuple = [ to_write[i : i + byte_length] for i in range(0 , len(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) ] if len(result_byte_array[-1] ) % byte_length == 0: result_byte_array.append("10000000" ) else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1] ) - 1 ) for elem in result_byte_array: opened_file.write(int(SCREAMING_SNAKE_CASE_ , 2 ).to_bytes(1 , byteorder="big" ) ) except OSError: print("File not accessible" ) sys.exit() def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : str ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = read_file_binary(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = compress_data(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Optional[int] = add_file_length(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) write_file_binary(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
68
'''simple docstring''' from __future__ import annotations import copy import inspect import unittest import numpy as np from transformers import is_tf_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_tf, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, TFLayoutLMvaModel, ) if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class SCREAMING_SNAKE_CASE__ : def __init__( self , lowercase__ , lowercase__=2 , lowercase__=3 , lowercase__=4 , lowercase__=2 , lowercase__=7 , lowercase__=True , lowercase__=True , lowercase__=True , lowercase__=True , lowercase__=99 , lowercase__=36 , lowercase__=2 , lowercase__=4 , lowercase__=37 , lowercase__="gelu" , lowercase__=0.1 , lowercase__=0.1 , lowercase__=512 , lowercase__=16 , lowercase__=2 , lowercase__=0.02 , lowercase__=6 , lowercase__=6 , lowercase__=3 , lowercase__=4 , lowercase__=None , lowercase__=1000 , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = parent SCREAMING_SNAKE_CASE_ : Optional[int] = batch_size SCREAMING_SNAKE_CASE_ : Dict = num_channels SCREAMING_SNAKE_CASE_ : Union[str, Any] = image_size SCREAMING_SNAKE_CASE_ : Optional[int] = patch_size SCREAMING_SNAKE_CASE_ : str = is_training SCREAMING_SNAKE_CASE_ : str = use_input_mask SCREAMING_SNAKE_CASE_ : Any = use_token_type_ids SCREAMING_SNAKE_CASE_ : int = use_labels SCREAMING_SNAKE_CASE_ : Union[str, Any] = vocab_size SCREAMING_SNAKE_CASE_ : Optional[Any] = hidden_size SCREAMING_SNAKE_CASE_ : Dict = num_hidden_layers SCREAMING_SNAKE_CASE_ : Any = num_attention_heads SCREAMING_SNAKE_CASE_ : Optional[Any] = intermediate_size SCREAMING_SNAKE_CASE_ : str = hidden_act SCREAMING_SNAKE_CASE_ : int = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : Tuple = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : Union[str, Any] = max_position_embeddings SCREAMING_SNAKE_CASE_ : Dict = type_vocab_size SCREAMING_SNAKE_CASE_ : List[Any] = type_sequence_label_size SCREAMING_SNAKE_CASE_ : Tuple = initializer_range SCREAMING_SNAKE_CASE_ : List[str] = coordinate_size SCREAMING_SNAKE_CASE_ : Optional[Any] = shape_size SCREAMING_SNAKE_CASE_ : List[str] = num_labels SCREAMING_SNAKE_CASE_ : Optional[int] = num_choices SCREAMING_SNAKE_CASE_ : Union[str, Any] = scope SCREAMING_SNAKE_CASE_ : Dict = 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_ : Union[str, Any] = text_seq_length SCREAMING_SNAKE_CASE_ : Tuple = (image_size // patch_size) ** 2 + 1 SCREAMING_SNAKE_CASE_ : Optional[int] = self.text_seq_length + self.image_seq_length def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE_ : Optional[Any] = ids_tensor([self.batch_size, self.text_seq_length, 4] , self.range_bbox ) SCREAMING_SNAKE_CASE_ : Dict = bbox.numpy() # 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_ : Optional[int] = bbox[i, j, 3] SCREAMING_SNAKE_CASE_ : str = bbox[i, j, 1] SCREAMING_SNAKE_CASE_ : Dict = tmp_coordinate if bbox[i, j, 2] < bbox[i, j, 0]: SCREAMING_SNAKE_CASE_ : List[Any] = bbox[i, j, 2] SCREAMING_SNAKE_CASE_ : Dict = bbox[i, j, 0] SCREAMING_SNAKE_CASE_ : Tuple = tmp_coordinate SCREAMING_SNAKE_CASE_ : Dict = tf.constant(lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE_ : Dict = None if self.use_input_mask: SCREAMING_SNAKE_CASE_ : Any = random_attention_mask([self.batch_size, self.text_seq_length] ) SCREAMING_SNAKE_CASE_ : List[str] = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE_ : Dict = ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE_ : Dict = None SCREAMING_SNAKE_CASE_ : Tuple = None if self.use_labels: SCREAMING_SNAKE_CASE_ : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE_ : List[str] = ids_tensor([self.batch_size, self.text_seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE_ : str = 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 __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = TFLayoutLMvaModel(config=lowercase__ ) # text + image SCREAMING_SNAKE_CASE_ : int = model(lowercase__ , pixel_values=lowercase__ , training=lowercase__ ) SCREAMING_SNAKE_CASE_ : str = model( lowercase__ , bbox=lowercase__ , pixel_values=lowercase__ , attention_mask=lowercase__ , token_type_ids=lowercase__ , training=lowercase__ , ) SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase__ , bbox=lowercase__ , pixel_values=lowercase__ , training=lowercase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # text only SCREAMING_SNAKE_CASE_ : Tuple = model(lowercase__ , training=lowercase__ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size) ) # image only SCREAMING_SNAKE_CASE_ : int = model({"pixel_values": pixel_values} , training=lowercase__ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size) ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = self.num_labels SCREAMING_SNAKE_CASE_ : Union[str, Any] = TFLayoutLMvaForSequenceClassification(config=lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = model( lowercase__ , bbox=lowercase__ , pixel_values=lowercase__ , attention_mask=lowercase__ , token_type_ids=lowercase__ , labels=lowercase__ , training=lowercase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.num_labels SCREAMING_SNAKE_CASE_ : Any = TFLayoutLMvaForTokenClassification(config=lowercase__ ) SCREAMING_SNAKE_CASE_ : int = model( lowercase__ , bbox=lowercase__ , pixel_values=lowercase__ , attention_mask=lowercase__ , token_type_ids=lowercase__ , labels=lowercase__ , training=lowercase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels) ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = 2 SCREAMING_SNAKE_CASE_ : List[Any] = TFLayoutLMvaForQuestionAnswering(config=lowercase__ ) SCREAMING_SNAKE_CASE_ : int = model( lowercase__ , bbox=lowercase__ , pixel_values=lowercase__ , attention_mask=lowercase__ , token_type_ids=lowercase__ , start_positions=lowercase__ , end_positions=lowercase__ , training=lowercase__ , ) 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 __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = 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_)) : Any = config_and_inputs SCREAMING_SNAKE_CASE_ : Optional[Any] = { "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_tf class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,_UpperCAmelCase,unittest.TestCase ): _A = ( ( TFLayoutLMvaModel, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, ) if is_tf_available() else () ) _A = ( {"document-question-answering": TFLayoutLMvaForQuestionAnswering, "feature-extraction": TFLayoutLMvaModel} if is_tf_available() else {} ) _A = False _A = False _A = False def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" return True def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__=False ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = copy.deepcopy(lowercase__ ) if model_class in get_values(lowercase__ ): SCREAMING_SNAKE_CASE_ : str = { k: tf.tile(tf.expand_dims(lowercase__ , 1 ) , (1, self.model_tester.num_choices) + (1,) * (v.ndim - 1) ) if isinstance(lowercase__ , tf.Tensor ) and v.ndim > 0 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(lowercase__ ): SCREAMING_SNAKE_CASE_ : Tuple = tf.ones(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(lowercase__ ): SCREAMING_SNAKE_CASE_ : Any = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) SCREAMING_SNAKE_CASE_ : List[Any] = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(lowercase__ ): SCREAMING_SNAKE_CASE_ : List[str] = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(lowercase__ ): SCREAMING_SNAKE_CASE_ : Optional[Any] = tf.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=tf.intaa ) return inputs_dict def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = TFLayoutLMvaModelTester(self ) SCREAMING_SNAKE_CASE_ : int = ConfigTester(self , config_class=lowercase__ , hidden_size=37 ) def __lowerCamelCase ( self ): """simple docstring""" self.config_tester.run_common_tests() def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ : int = model_class(lowercase__ ) if getattr(lowercase__ , "hf_compute_loss" , lowercase__ ): # The number of elements in the loss should be the same as the number of elements in the label SCREAMING_SNAKE_CASE_ : Dict = self._prepare_for_class(inputs_dict.copy() , lowercase__ , return_labels=lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = prepared_for_class[ sorted(prepared_for_class.keys() - inputs_dict.keys() , reverse=lowercase__ )[0] ] SCREAMING_SNAKE_CASE_ : Any = added_label.shape.as_list()[:1] # Test that model correctly compute the loss with kwargs SCREAMING_SNAKE_CASE_ : Dict = self._prepare_for_class(inputs_dict.copy() , lowercase__ , return_labels=lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = prepared_for_class.pop("input_ids" ) SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase__ , **lowercase__ )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss when we mask some positions SCREAMING_SNAKE_CASE_ : List[Any] = self._prepare_for_class(inputs_dict.copy() , lowercase__ , return_labels=lowercase__ ) SCREAMING_SNAKE_CASE_ : int = prepared_for_class.pop("input_ids" ) if "labels" in prepared_for_class: SCREAMING_SNAKE_CASE_ : str = prepared_for_class["labels"].numpy() if len(labels.shape ) > 1 and labels.shape[1] != 1: SCREAMING_SNAKE_CASE_ : str = -100 SCREAMING_SNAKE_CASE_ : str = tf.convert_to_tensor(lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = model(lowercase__ , **lowercase__ )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) self.assertTrue(not np.any(np.isnan(loss.numpy() ) ) ) # Test that model correctly compute the loss with a dict SCREAMING_SNAKE_CASE_ : List[Any] = self._prepare_for_class(inputs_dict.copy() , lowercase__ , return_labels=lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = model(lowercase__ )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss with a tuple SCREAMING_SNAKE_CASE_ : Optional[Any] = self._prepare_for_class(inputs_dict.copy() , lowercase__ , return_labels=lowercase__ ) # Get keys that were added with the _prepare_for_class function SCREAMING_SNAKE_CASE_ : int = prepared_for_class.keys() - inputs_dict.keys() SCREAMING_SNAKE_CASE_ : Optional[int] = inspect.signature(model.call ).parameters SCREAMING_SNAKE_CASE_ : Tuple = list(signature.keys() ) # Create a dictionary holding the location of the tensors in the tuple SCREAMING_SNAKE_CASE_ : List[Any] = {0: "input_ids"} for label_key in label_keys: SCREAMING_SNAKE_CASE_ : Optional[int] = signature_names.index(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = label_key SCREAMING_SNAKE_CASE_ : List[str] = sorted(tuple_index_mapping.items() ) # Initialize a list with their default values, update the values and convert to a tuple SCREAMING_SNAKE_CASE_ : List[str] = [] for name in signature_names: if name != "kwargs": list_input.append(signature[name].default ) for index, value in sorted_tuple_index_mapping: SCREAMING_SNAKE_CASE_ : List[str] = prepared_for_class[value] SCREAMING_SNAKE_CASE_ : List[Any] = tuple(lowercase__ ) # Send to model SCREAMING_SNAKE_CASE_ : int = model(tuple_input[:-1] )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) def __lowerCamelCase ( self ): """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_ ), ) : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) def __lowerCamelCase ( self ): """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_ ), ) : Optional[Any] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE_ : List[str] = type self.model_tester.create_and_check_model(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) def __lowerCamelCase ( self ): """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_ ), ) : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) def __lowerCamelCase ( self ): """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_ ), ) : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) def __lowerCamelCase ( self ): """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_ ), ) : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) @slow def __lowerCamelCase ( self ): """simple docstring""" for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE_ : Union[str, Any] = TFLayoutLMvaModel.from_pretrained(lowercase__ ) self.assertIsNotNone(lowercase__ ) def __lowerCamelCase ( ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : str = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_tf class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): @cached_property def __lowerCamelCase ( self ): """simple docstring""" return LayoutLMvaImageProcessor(apply_ocr=lowercase__ ) if is_vision_available() else None @slow def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = TFLayoutLMvaModel.from_pretrained("microsoft/layoutlmv3-base" ) SCREAMING_SNAKE_CASE_ : Any = self.default_image_processor SCREAMING_SNAKE_CASE_ : Optional[int] = prepare_img() SCREAMING_SNAKE_CASE_ : Optional[Any] = image_processor(images=lowercase__ , return_tensors="tf" ).pixel_values SCREAMING_SNAKE_CASE_ : Dict = tf.constant([[1, 2]] ) SCREAMING_SNAKE_CASE_ : Any = tf.expand_dims(tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]] ) , axis=0 ) # forward pass SCREAMING_SNAKE_CASE_ : List[Any] = model(input_ids=lowercase__ , bbox=lowercase__ , pixel_values=lowercase__ , training=lowercase__ ) # verify the logits SCREAMING_SNAKE_CASE_ : Tuple = (1, 199, 768) self.assertEqual(outputs.last_hidden_state.shape , lowercase__ ) SCREAMING_SNAKE_CASE_ : int = tf.constant( [[-0.0529, 0.3618, 0.1632], [-0.1587, -0.1667, -0.0400], [-0.1557, -0.1671, -0.0505]] ) self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3] , lowercase__ , atol=1e-4 ) )
68
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 snake_case_ = get_tests_dir('fixtures/test_sentencepiece.model') if is_torch_available(): from transformers.models.mbart.modeling_mbart import shift_tokens_right snake_case_ = 2_5_0_0_0_4 snake_case_ = 2_5_0_0_2_0 @require_sentencepiece @require_tokenizers class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,unittest.TestCase ): _A = MBartTokenizer _A = MBartTokenizerFast _A = True _A = True def __lowerCamelCase ( self ): """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE_ : Optional[Any] = MBartTokenizer(lowercase__ , keep_accents=lowercase__ ) tokenizer.save_pretrained(self.tmpdirname ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int = MBartTokenizer(lowercase__ , keep_accents=lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = tokenizer.tokenize("This is a test" ) self.assertListEqual(lowercase__ , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(lowercase__ ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) SCREAMING_SNAKE_CASE_ : List[Any] = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( lowercase__ , [ 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_ : Optional[Any] = tokenizer.convert_tokens_to_ids(lowercase__ ) self.assertListEqual( lowercase__ , [ 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_ : Optional[int] = tokenizer.convert_ids_to_tokens(lowercase__ ) self.assertListEqual( lowercase__ , [ 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 __lowerCamelCase ( self ): """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_ : Tuple = (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_ : Dict = self.rust_tokenizer_class.from_pretrained(lowercase__ , **lowercase__ ) SCREAMING_SNAKE_CASE_ : str = self.tokenizer_class.from_pretrained(lowercase__ , **lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE_ : Dict = tokenizer_r.save_pretrained(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = tokenizer_p.save_pretrained(lowercase__ ) # 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_ : Union[str, Any] = tuple(f for f in tokenizer_r_files if "tokenizer.json" not in f ) self.assertSequenceEqual(lowercase__ , lowercase__ ) # Checks everything loads correctly in the same way SCREAMING_SNAKE_CASE_ : Optional[int] = tokenizer_r.from_pretrained(lowercase__ ) SCREAMING_SNAKE_CASE_ : int = tokenizer_p.from_pretrained(lowercase__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(lowercase__ , lowercase__ ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(lowercase__ ) # Save tokenizer rust, legacy_format=True SCREAMING_SNAKE_CASE_ : str = tempfile.mkdtemp() SCREAMING_SNAKE_CASE_ : Tuple = tokenizer_r.save_pretrained(lowercase__ , legacy_format=lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = tokenizer_p.save_pretrained(lowercase__ ) # Checks it save with the same files self.assertSequenceEqual(lowercase__ , lowercase__ ) # Checks everything loads correctly in the same way SCREAMING_SNAKE_CASE_ : int = tokenizer_r.from_pretrained(lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = tokenizer_p.from_pretrained(lowercase__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(lowercase__ , lowercase__ ) ) shutil.rmtree(lowercase__ ) # Save tokenizer rust, legacy_format=False SCREAMING_SNAKE_CASE_ : List[str] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE_ : Any = tokenizer_r.save_pretrained(lowercase__ , legacy_format=lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = tokenizer_p.save_pretrained(lowercase__ ) # 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_ : Any = tokenizer_r.from_pretrained(lowercase__ ) SCREAMING_SNAKE_CASE_ : str = tokenizer_p.from_pretrained(lowercase__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(lowercase__ , lowercase__ ) ) shutil.rmtree(lowercase__ ) @require_torch @require_sentencepiece @require_tokenizers class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): _A = "facebook/mbart-large-en-ro" _A = [ " 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.", ] _A = [ "Ş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.", ] _A = [8_274, 127_873, 25_916, 7, 8_622, 2_071, 438, 67_485, 53, 187_895, 23, 51_712, 2, EN_CODE] @classmethod def __lowerCamelCase ( cls ): """simple docstring""" SCREAMING_SNAKE_CASE_ : MBartTokenizer = MBartTokenizer.from_pretrained( cls.checkpoint_name , src_lang="en_XX" , tgt_lang="ro_RO" ) SCREAMING_SNAKE_CASE_ : Any = 1 return cls def __lowerCamelCase ( self ): """simple docstring""" self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["ar_AR"] , 25_0001 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["en_EN"] , 25_0004 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["ro_RO"] , 25_0020 ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" self.assertIn(lowercase__ , self.tokenizer.all_special_ids ) SCREAMING_SNAKE_CASE_ : List[Any] = [RO_CODE, 884, 9019, 96, 9, 916, 8_6792, 36, 1_8743, 1_5596, 5, 2] SCREAMING_SNAKE_CASE_ : Dict = self.tokenizer.decode(lowercase__ , skip_special_tokens=lowercase__ ) SCREAMING_SNAKE_CASE_ : Tuple = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=lowercase__ ) self.assertEqual(lowercase__ , lowercase__ ) self.assertNotIn(self.tokenizer.eos_token , lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = ["this is gunna be a long sentence " * 20] assert isinstance(src_text[0] , lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = 10 SCREAMING_SNAKE_CASE_ : Tuple = self.tokenizer(lowercase__ , max_length=lowercase__ , truncation=lowercase__ ).input_ids[0] self.assertEqual(ids[-2] , 2 ) self.assertEqual(ids[-1] , lowercase__ ) self.assertEqual(len(lowercase__ ) , lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" self.assertListEqual(self.tokenizer.convert_tokens_to_ids(["<mask>", "ar_AR"] ) , [25_0026, 25_0001] ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE_ : Tuple = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = MBartTokenizer.from_pretrained(lowercase__ ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , lowercase__ ) @require_torch def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=lowercase__ , return_tensors="pt" ) SCREAMING_SNAKE_CASE_ : int = 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 __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=lowercase__ , truncation=lowercase__ , max_length=len(self.expected_src_tokens ) , return_tensors="pt" , ) SCREAMING_SNAKE_CASE_ : str = shift_tokens_right(batch["labels"] , self.tokenizer.pad_token_id ) self.assertIsInstance(lowercase__ , lowercase__ ) self.assertEqual((2, 14) , batch.input_ids.shape ) self.assertEqual((2, 14) , batch.attention_mask.shape ) SCREAMING_SNAKE_CASE_ : List[str] = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , lowercase__ ) 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 __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = self.tokenizer(self.src_text , padding=lowercase__ , truncation=lowercase__ , max_length=3 , return_tensors="pt" ) SCREAMING_SNAKE_CASE_ : Dict = self.tokenizer( text_target=self.tgt_text , padding=lowercase__ , truncation=lowercase__ , max_length=10 , return_tensors="pt" ) SCREAMING_SNAKE_CASE_ : Any = targets["input_ids"] SCREAMING_SNAKE_CASE_ : str = shift_tokens_right(lowercase__ , 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 __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.tokenizer._build_translation_inputs( "A test" , return_tensors="pt" , src_lang="en_XX" , tgt_lang="ar_AR" ) self.assertEqual( nested_simplify(lowercase__ ) , { # A, test, EOS, en_XX "input_ids": [[62, 3034, 2, 25_0004]], "attention_mask": [[1, 1, 1, 1]], # ar_AR "forced_bos_token_id": 25_0001, } , )
68
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Tuple ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = [1] for i in range(2 , SCREAMING_SNAKE_CASE_ ): factorials.append(factorials[-1] * i ) assert 0 <= k < factorials[-1] * n, "k out of bounds" SCREAMING_SNAKE_CASE_ : Union[str, Any] = [] SCREAMING_SNAKE_CASE_ : Dict = list(range(SCREAMING_SNAKE_CASE_ ) ) # Find permutation while factorials: SCREAMING_SNAKE_CASE_ : Any = factorials.pop() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[int] = divmod(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) permutation.append(elements[number] ) elements.remove(elements[number] ) permutation.append(elements[0] ) return permutation if __name__ == "__main__": import doctest doctest.testmod()
68
1
'''simple docstring''' snake_case_ = 8.3_1_4_4_6_2 # Unit - J mol-1 K-1 def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float ) -> float: """simple docstring""" if moles < 0 or kelvin < 0 or volume < 0: raise ValueError("Invalid inputs. Enter positive value." ) return moles * kelvin * UNIVERSAL_GAS_CONSTANT / volume def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float ) -> float: """simple docstring""" if moles < 0 or kelvin < 0 or pressure < 0: raise ValueError("Invalid inputs. Enter positive value." ) return moles * kelvin * UNIVERSAL_GAS_CONSTANT / pressure if __name__ == "__main__": from doctest import testmod testmod()
68
'''simple docstring''' import argparse from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_controlnet_from_original_ckpt if __name__ == "__main__": snake_case_ = argparse.ArgumentParser() parser.add_argument( '--checkpoint_path', default=None, type=str, required=True, help='Path to the checkpoint to convert.' ) parser.add_argument( '--original_config_file', type=str, required=True, help='The YAML config file corresponding to the original architecture.', ) parser.add_argument( '--num_in_channels', default=None, type=int, help='The number of input channels. If `None` number of input channels will be automatically inferred.', ) parser.add_argument( '--image_size', default=5_1_2, type=int, help=( 'The image size that the model was trained on. Use 512 for Stable Diffusion v1.X and Stable Siffusion v2' ' Base. Use 768 for Stable Diffusion v2.' ), ) parser.add_argument( '--extract_ema', action='store_true', help=( 'Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights' ' or not. Defaults to `False`. Add `--extract_ema` to extract the EMA weights. EMA weights usually yield' ' higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning.' ), ) parser.add_argument( '--upcast_attention', action='store_true', help=( 'Whether the attention computation should always be upcasted. This is necessary when running stable' ' diffusion 2.1.' ), ) parser.add_argument( '--from_safetensors', action='store_true', help='If `--checkpoint_path` is in `safetensors` format, load checkpoint with safetensors instead of PyTorch.', ) parser.add_argument( '--to_safetensors', action='store_true', help='Whether to store pipeline in safetensors format or not.', ) parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.') parser.add_argument('--device', type=str, help='Device to use (e.g. cpu, cuda:0, cuda:1, etc.)') def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Optional[int] ) -> Dict: """simple docstring""" if string == "True": return True elif string == "False": return False else: raise ValueError(F"could not parse string as bool {string}" ) parser.add_argument( '--use_linear_projection', help='Override for use linear projection', required=False, type=parse_bool ) parser.add_argument('--cross_attention_dim', help='Override for cross attention_dim', required=False, type=int) snake_case_ = parser.parse_args() snake_case_ = download_controlnet_from_original_ckpt( checkpoint_path=args.checkpoint_path, original_config_file=args.original_config_file, image_size=args.image_size, extract_ema=args.extract_ema, num_in_channels=args.num_in_channels, upcast_attention=args.upcast_attention, from_safetensors=args.from_safetensors, device=args.device, use_linear_projection=args.use_linear_projection, cross_attention_dim=args.cross_attention_dim, ) controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
68
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) snake_case_ = {'configuration_fnet': ['FNET_PRETRAINED_CONFIG_ARCHIVE_MAP', 'FNetConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ = ['FNetTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ = ['FNetTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ = [ 'FNET_PRETRAINED_MODEL_ARCHIVE_LIST', 'FNetForMaskedLM', 'FNetForMultipleChoice', 'FNetForNextSentencePrediction', 'FNetForPreTraining', 'FNetForQuestionAnswering', 'FNetForSequenceClassification', 'FNetForTokenClassification', 'FNetLayer', 'FNetModel', 'FNetPreTrainedModel', ] if TYPE_CHECKING: from .configuration_fnet import FNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet import FNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet_fast import FNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_fnet import ( FNET_PRETRAINED_MODEL_ARCHIVE_LIST, FNetForMaskedLM, FNetForMultipleChoice, FNetForNextSentencePrediction, FNetForPreTraining, FNetForQuestionAnswering, FNetForSequenceClassification, FNetForTokenClassification, FNetLayer, FNetModel, FNetPreTrainedModel, ) else: import sys snake_case_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
68
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging snake_case_ = logging.get_logger(__name__) snake_case_ = { 'camembert-base': 'https://huggingface.co/camembert-base/resolve/main/config.json', 'umberto-commoncrawl-cased-v1': ( 'https://huggingface.co/Musixmatch/umberto-commoncrawl-cased-v1/resolve/main/config.json' ), 'umberto-wikipedia-uncased-v1': ( 'https://huggingface.co/Musixmatch/umberto-wikipedia-uncased-v1/resolve/main/config.json' ), } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = "camembert" def __init__( self , lowercase__=3_0522 , lowercase__=768 , lowercase__=12 , lowercase__=12 , lowercase__=3072 , lowercase__="gelu" , lowercase__=0.1 , lowercase__=0.1 , lowercase__=512 , lowercase__=2 , lowercase__=0.02 , lowercase__=1e-12 , lowercase__=1 , lowercase__=0 , lowercase__=2 , lowercase__="absolute" , lowercase__=True , lowercase__=None , **lowercase__ , ): """simple docstring""" super().__init__(pad_token_id=lowercase__ , bos_token_id=lowercase__ , eos_token_id=lowercase__ , **lowercase__ ) SCREAMING_SNAKE_CASE_ : Tuple = vocab_size SCREAMING_SNAKE_CASE_ : str = hidden_size SCREAMING_SNAKE_CASE_ : str = num_hidden_layers SCREAMING_SNAKE_CASE_ : Dict = num_attention_heads SCREAMING_SNAKE_CASE_ : Any = hidden_act SCREAMING_SNAKE_CASE_ : Optional[int] = intermediate_size SCREAMING_SNAKE_CASE_ : Optional[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : List[str] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : Optional[Any] = max_position_embeddings SCREAMING_SNAKE_CASE_ : List[str] = type_vocab_size SCREAMING_SNAKE_CASE_ : Tuple = initializer_range SCREAMING_SNAKE_CASE_ : List[Any] = layer_norm_eps SCREAMING_SNAKE_CASE_ : List[Any] = position_embedding_type SCREAMING_SNAKE_CASE_ : Any = use_cache SCREAMING_SNAKE_CASE_ : Optional[int] = classifier_dropout class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): @property def __lowerCamelCase ( self ): """simple docstring""" if self.task == "multiple-choice": SCREAMING_SNAKE_CASE_ : Optional[int] = {0: "batch", 1: "choice", 2: "sequence"} else: SCREAMING_SNAKE_CASE_ : Any = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
68
1
'''simple docstring''' import argparse import torch from transformers import ( EncodecConfig, EncodecFeatureExtractor, EncodecModel, logging, ) # checkpoints downloaded from: # https://dl.fbaipublicfiles.com/encodec/v0/encodec_24khz-d7cc33bc.th # https://huggingface.co/facebook/musicgen-small/resolve/main/compression_state_dict.bin # https://dl.fbaipublicfiles.com/encodec/v0/encodec_48khz-7e698e3e.th logging.set_verbosity_info() snake_case_ = logging.get_logger('transformers.models.encodec') snake_case_ = { 'quantizer.vq.layers.*._codebook.inited': 'quantizer.layers.*.codebook.inited', 'quantizer.vq.layers.*._codebook.cluster_size': 'quantizer.layers.*.codebook.cluster_size', 'quantizer.vq.layers.*._codebook.embed': 'quantizer.layers.*.codebook.embed', 'quantizer.vq.layers.*._codebook.embed_avg': 'quantizer.layers.*.codebook.embed_avg', } snake_case_ = { 'encoder.model.0.conv.conv': 'encoder.layers.0.conv', 'encoder.model.1.block.1.conv.conv': 'encoder.layers.1.block.1.conv', 'encoder.model.1.block.3.conv.conv': 'encoder.layers.1.block.3.conv', 'encoder.model.1.shortcut.conv.conv': 'encoder.layers.1.shortcut.conv', 'encoder.model.3.conv.conv': 'encoder.layers.3.conv', 'encoder.model.4.block.1.conv.conv': 'encoder.layers.4.block.1.conv', 'encoder.model.4.block.3.conv.conv': 'encoder.layers.4.block.3.conv', 'encoder.model.4.shortcut.conv.conv': 'encoder.layers.4.shortcut.conv', 'encoder.model.6.conv.conv': 'encoder.layers.6.conv', 'encoder.model.7.block.1.conv.conv': 'encoder.layers.7.block.1.conv', 'encoder.model.7.block.3.conv.conv': 'encoder.layers.7.block.3.conv', 'encoder.model.7.shortcut.conv.conv': 'encoder.layers.7.shortcut.conv', 'encoder.model.9.conv.conv': 'encoder.layers.9.conv', 'encoder.model.10.block.1.conv.conv': 'encoder.layers.10.block.1.conv', 'encoder.model.10.block.3.conv.conv': 'encoder.layers.10.block.3.conv', 'encoder.model.10.shortcut.conv.conv': 'encoder.layers.10.shortcut.conv', 'encoder.model.12.conv.conv': 'encoder.layers.12.conv', 'encoder.model.13.lstm': 'encoder.layers.13.lstm', 'encoder.model.15.conv.conv': 'encoder.layers.15.conv', } snake_case_ = { 'encoder.model.0.conv.norm': 'encoder.layers.0.norm', 'encoder.model.1.block.1.conv.norm': 'encoder.layers.1.block.1.norm', 'encoder.model.1.block.3.conv.norm': 'encoder.layers.1.block.3.norm', 'encoder.model.1.shortcut.conv.norm': 'encoder.layers.1.shortcut.norm', 'encoder.model.3.conv.norm': 'encoder.layers.3.norm', 'encoder.model.4.block.1.conv.norm': 'encoder.layers.4.block.1.norm', 'encoder.model.4.block.3.conv.norm': 'encoder.layers.4.block.3.norm', 'encoder.model.4.shortcut.conv.norm': 'encoder.layers.4.shortcut.norm', 'encoder.model.6.conv.norm': 'encoder.layers.6.norm', 'encoder.model.7.block.1.conv.norm': 'encoder.layers.7.block.1.norm', 'encoder.model.7.block.3.conv.norm': 'encoder.layers.7.block.3.norm', 'encoder.model.7.shortcut.conv.norm': 'encoder.layers.7.shortcut.norm', 'encoder.model.9.conv.norm': 'encoder.layers.9.norm', 'encoder.model.10.block.1.conv.norm': 'encoder.layers.10.block.1.norm', 'encoder.model.10.block.3.conv.norm': 'encoder.layers.10.block.3.norm', 'encoder.model.10.shortcut.conv.norm': 'encoder.layers.10.shortcut.norm', 'encoder.model.12.conv.norm': 'encoder.layers.12.norm', 'encoder.model.15.conv.norm': 'encoder.layers.15.norm', } snake_case_ = { 'decoder.model.0.conv.conv': 'decoder.layers.0.conv', 'decoder.model.1.lstm': 'decoder.layers.1.lstm', 'decoder.model.3.convtr.convtr': 'decoder.layers.3.conv', 'decoder.model.4.block.1.conv.conv': 'decoder.layers.4.block.1.conv', 'decoder.model.4.block.3.conv.conv': 'decoder.layers.4.block.3.conv', 'decoder.model.4.shortcut.conv.conv': 'decoder.layers.4.shortcut.conv', 'decoder.model.6.convtr.convtr': 'decoder.layers.6.conv', 'decoder.model.7.block.1.conv.conv': 'decoder.layers.7.block.1.conv', 'decoder.model.7.block.3.conv.conv': 'decoder.layers.7.block.3.conv', 'decoder.model.7.shortcut.conv.conv': 'decoder.layers.7.shortcut.conv', 'decoder.model.9.convtr.convtr': 'decoder.layers.9.conv', 'decoder.model.10.block.1.conv.conv': 'decoder.layers.10.block.1.conv', 'decoder.model.10.block.3.conv.conv': 'decoder.layers.10.block.3.conv', 'decoder.model.10.shortcut.conv.conv': 'decoder.layers.10.shortcut.conv', 'decoder.model.12.convtr.convtr': 'decoder.layers.12.conv', 'decoder.model.13.block.1.conv.conv': 'decoder.layers.13.block.1.conv', 'decoder.model.13.block.3.conv.conv': 'decoder.layers.13.block.3.conv', 'decoder.model.13.shortcut.conv.conv': 'decoder.layers.13.shortcut.conv', 'decoder.model.15.conv.conv': 'decoder.layers.15.conv', } snake_case_ = { 'decoder.model.0.conv.norm': 'decoder.layers.0.norm', 'decoder.model.3.convtr.norm': 'decoder.layers.3.norm', 'decoder.model.4.block.1.conv.norm': 'decoder.layers.4.block.1.norm', 'decoder.model.4.block.3.conv.norm': 'decoder.layers.4.block.3.norm', 'decoder.model.4.shortcut.conv.norm': 'decoder.layers.4.shortcut.norm', 'decoder.model.6.convtr.norm': 'decoder.layers.6.norm', 'decoder.model.7.block.1.conv.norm': 'decoder.layers.7.block.1.norm', 'decoder.model.7.block.3.conv.norm': 'decoder.layers.7.block.3.norm', 'decoder.model.7.shortcut.conv.norm': 'decoder.layers.7.shortcut.norm', 'decoder.model.9.convtr.norm': 'decoder.layers.9.norm', 'decoder.model.10.block.1.conv.norm': 'decoder.layers.10.block.1.norm', 'decoder.model.10.block.3.conv.norm': 'decoder.layers.10.block.3.norm', 'decoder.model.10.shortcut.conv.norm': 'decoder.layers.10.shortcut.norm', 'decoder.model.12.convtr.norm': 'decoder.layers.12.norm', 'decoder.model.13.block.1.conv.norm': 'decoder.layers.13.block.1.norm', 'decoder.model.13.block.3.conv.norm': 'decoder.layers.13.block.3.norm', 'decoder.model.13.shortcut.conv.norm': 'decoder.layers.13.shortcut.norm', 'decoder.model.15.conv.norm': 'decoder.layers.15.norm', } snake_case_ = { **MAPPING_QUANTIZER, **MAPPING_ENCODER, **MAPPING_DECODER, } snake_case_ = { **MAPPING_QUANTIZER, **MAPPING_ENCODER, **MAPPING_ENCODER_48K, **MAPPING_DECODER, **MAPPING_DECODER_48K, } snake_case_ = [] snake_case_ = [] def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Optional[int] ) -> Optional[int]: """simple docstring""" for attribute in key.split("." ): SCREAMING_SNAKE_CASE_ : Dict = getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if weight_type is not None: SCREAMING_SNAKE_CASE_ : Tuple = getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).shape else: SCREAMING_SNAKE_CASE_ : Tuple = hf_pointer.shape if hf_shape != value.shape: raise ValueError( F"Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be" F" {value.shape} for {full_name}" ) if weight_type == "weight": SCREAMING_SNAKE_CASE_ : List[str] = value elif weight_type == "weight_g": SCREAMING_SNAKE_CASE_ : int = value elif weight_type == "weight_v": SCREAMING_SNAKE_CASE_ : Optional[int] = value elif weight_type == "bias": SCREAMING_SNAKE_CASE_ : Tuple = value elif weight_type == "running_mean": SCREAMING_SNAKE_CASE_ : Union[str, Any] = value elif weight_type == "running_var": SCREAMING_SNAKE_CASE_ : str = value elif weight_type == "num_batches_tracked": SCREAMING_SNAKE_CASE_ : Any = value elif weight_type == "weight_ih_l0": SCREAMING_SNAKE_CASE_ : Union[str, Any] = value elif weight_type == "weight_hh_l0": SCREAMING_SNAKE_CASE_ : Union[str, Any] = value elif weight_type == "bias_ih_l0": SCREAMING_SNAKE_CASE_ : Union[str, Any] = value elif weight_type == "bias_hh_l0": SCREAMING_SNAKE_CASE_ : Union[str, Any] = value elif weight_type == "weight_ih_l1": SCREAMING_SNAKE_CASE_ : int = value elif weight_type == "weight_hh_l1": SCREAMING_SNAKE_CASE_ : List[Any] = value elif weight_type == "bias_ih_l1": SCREAMING_SNAKE_CASE_ : Any = value elif weight_type == "bias_hh_l1": SCREAMING_SNAKE_CASE_ : Tuple = value else: SCREAMING_SNAKE_CASE_ : Tuple = value logger.info(F"{key + ('.' + weight_type if weight_type is not None else '')} was initialized from {full_name}." ) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : Dict ) -> Optional[Any]: """simple docstring""" for key in ignore_keys: if key.endswith(".*" ): if name.startswith(key[:-1] ): return True elif ".*." in key: SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Union[str, Any] = key.split(".*." ) if prefix in name and suffix in name: return True elif key in name: return True return False def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : Optional[Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = [] if model_name == "encodec_24khz" or "encodec_32khz": SCREAMING_SNAKE_CASE_ : List[Any] = MAPPING_24K elif model_name == "encodec_48khz": SCREAMING_SNAKE_CASE_ : int = MAPPING_48K else: raise ValueError(F"Unsupported model: {model_name}" ) for name, value in orig_dict.items(): if should_ignore(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): logger.info(F"{name} was ignored" ) continue SCREAMING_SNAKE_CASE_ : int = False for key, mapped_key in MAPPING.items(): if "*" in key: SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : int = key.split(".*." ) if prefix in name and suffix in name: SCREAMING_SNAKE_CASE_ : int = suffix if key in name: # HACK otherwise .embed gets initialized with .embed_avg too if key.endswith("embed" ) and name.endswith("embed_avg" ): continue SCREAMING_SNAKE_CASE_ : Any = True if "*" in mapped_key: SCREAMING_SNAKE_CASE_ : Optional[Any] = name.split(SCREAMING_SNAKE_CASE_ )[0].split("." )[-2] SCREAMING_SNAKE_CASE_ : Optional[Any] = mapped_key.replace("*" , SCREAMING_SNAKE_CASE_ ) if "weight_g" in name: SCREAMING_SNAKE_CASE_ : Any = "weight_g" elif "weight_v" in name: SCREAMING_SNAKE_CASE_ : Tuple = "weight_v" elif "weight_ih_l0" in name: SCREAMING_SNAKE_CASE_ : str = "weight_ih_l0" elif "weight_hh_l0" in name: SCREAMING_SNAKE_CASE_ : Any = "weight_hh_l0" elif "bias_ih_l0" in name: SCREAMING_SNAKE_CASE_ : Tuple = "bias_ih_l0" elif "bias_hh_l0" in name: SCREAMING_SNAKE_CASE_ : int = "bias_hh_l0" elif "weight_ih_l1" in name: SCREAMING_SNAKE_CASE_ : List[Any] = "weight_ih_l1" elif "weight_hh_l1" in name: SCREAMING_SNAKE_CASE_ : Optional[Any] = "weight_hh_l1" elif "bias_ih_l1" in name: SCREAMING_SNAKE_CASE_ : Union[str, Any] = "bias_ih_l1" elif "bias_hh_l1" in name: SCREAMING_SNAKE_CASE_ : Optional[Any] = "bias_hh_l1" elif "bias" in name: SCREAMING_SNAKE_CASE_ : Any = "bias" elif "weight" in name: SCREAMING_SNAKE_CASE_ : Dict = "weight" elif "running_mean" in name: SCREAMING_SNAKE_CASE_ : Tuple = "running_mean" elif "running_var" in name: SCREAMING_SNAKE_CASE_ : int = "running_var" elif "num_batches_tracked" in name: SCREAMING_SNAKE_CASE_ : List[str] = "num_batches_tracked" else: SCREAMING_SNAKE_CASE_ : Dict = None set_recursively(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) continue if not is_used: unused_weights.append(SCREAMING_SNAKE_CASE_ ) logger.warning(F"Unused weights: {unused_weights}" ) @torch.no_grad() def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : int=None , SCREAMING_SNAKE_CASE_ : Optional[Any]=None , ) -> Optional[int]: """simple docstring""" if config_path is not None: SCREAMING_SNAKE_CASE_ : int = EncodecConfig.from_pretrained(SCREAMING_SNAKE_CASE_ ) else: SCREAMING_SNAKE_CASE_ : Tuple = EncodecConfig() if model_name == "encodec_24khz": pass # config is already correct elif model_name == "encodec_32khz": SCREAMING_SNAKE_CASE_ : Any = [8, 5, 4, 4] SCREAMING_SNAKE_CASE_ : List[Any] = [2.2] SCREAMING_SNAKE_CASE_ : Optional[Any] = 6_4 SCREAMING_SNAKE_CASE_ : Optional[Any] = 3_2_0_0_0 SCREAMING_SNAKE_CASE_ : int = 2_0_4_8 SCREAMING_SNAKE_CASE_ : int = False SCREAMING_SNAKE_CASE_ : int = False SCREAMING_SNAKE_CASE_ : Union[str, Any] = False elif model_name == "encodec_48khz": SCREAMING_SNAKE_CASE_ : Any = [8, 5, 4, 2] SCREAMING_SNAKE_CASE_ : Tuple = [3.0, 6.0, 12.0, 24.0] SCREAMING_SNAKE_CASE_ : Any = 4_8_0_0_0 SCREAMING_SNAKE_CASE_ : List[Any] = 2 SCREAMING_SNAKE_CASE_ : List[Any] = False SCREAMING_SNAKE_CASE_ : Optional[int] = "time_group_norm" SCREAMING_SNAKE_CASE_ : Optional[int] = True SCREAMING_SNAKE_CASE_ : Any = 1.0 SCREAMING_SNAKE_CASE_ : Optional[Any] = 0.01 else: raise ValueError(F"Unknown model name: {model_name}" ) SCREAMING_SNAKE_CASE_ : str = EncodecModel(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : List[str] = EncodecFeatureExtractor( feature_size=config.audio_channels , sampling_rate=config.sampling_rate , chunk_length_s=config.chunk_length_s , overlap=config.overlap , ) feature_extractor.save_pretrained(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : int = torch.load(SCREAMING_SNAKE_CASE_ ) if "best_state" in original_checkpoint: # we might have a training state saved, in which case discard the yaml results and just retain the weights SCREAMING_SNAKE_CASE_ : Optional[int] = original_checkpoint["best_state"] recursively_load_weights(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) model.save_pretrained(SCREAMING_SNAKE_CASE_ ) if repo_id: print("Pushing to the hub..." ) feature_extractor.push_to_hub(SCREAMING_SNAKE_CASE_ ) model.push_to_hub(SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": snake_case_ = argparse.ArgumentParser() parser.add_argument( '--model', default='encodec_24khz', type=str, help='The model to convert. Should be one of \'encodec_24khz\', \'encodec_32khz\', \'encodec_48khz\'.', ) parser.add_argument('--checkpoint_path', required=True, default=None, type=str, help='Path to original checkpoint') 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.' ) snake_case_ = parser.parse_args() convert_checkpoint( args.model, args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.push_to_hub, )
68
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : list[int] ) -> list[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = len(SCREAMING_SNAKE_CASE_ ) for i in range(SCREAMING_SNAKE_CASE_ ): for j in range(i + 1 , SCREAMING_SNAKE_CASE_ ): if numbers[j] < numbers[i]: SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Tuple = numbers[j], numbers[i] return numbers if __name__ == "__main__": snake_case_ = input('Enter numbers separated by a comma:\n').strip() snake_case_ = [int(item) for item in user_input.split(',')] print(exchange_sort(unsorted))
68
1
'''simple docstring''' from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import numpy as np import tensorflow as tf from transformers import TFCamembertModel @require_tf @require_sentencepiece @require_tokenizers class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): @slow def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = TFCamembertModel.from_pretrained("jplu/tf-camembert-base" ) SCREAMING_SNAKE_CASE_ : Optional[int] = tf.convert_to_tensor( [[5, 121, 11, 660, 16, 730, 2_5543, 110, 83, 6]] , dtype=tf.intaa , ) # J'aime le camembert !" SCREAMING_SNAKE_CASE_ : Tuple = model(lowercase__ )["last_hidden_state"] SCREAMING_SNAKE_CASE_ : Any = tf.TensorShape((1, 10, 768) ) self.assertEqual(output.shape , lowercase__ ) # compare the actual values for a slice. SCREAMING_SNAKE_CASE_ : Dict = tf.convert_to_tensor( [[[-0.0254, 0.0235, 0.1027], [0.0606, -0.1811, -0.0418], [-0.1561, -0.1127, 0.2687]]] , dtype=tf.floataa , ) # camembert = torch.hub.load('pytorch/fairseq', 'camembert.v0') # camembert.eval() # expected_slice = roberta.model.forward(input_ids)[0][:, :3, :3].detach() self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1e-4 ) )
68
'''simple docstring''' import logging import os import sys from pathlib import Path from unittest.mock import patch from parameterized import parameterized from run_eval import run_generate from run_eval_search import run_search from transformers.testing_utils import CaptureStdout, TestCasePlus, slow from utils import ROUGE_KEYS logging.basicConfig(level=logging.DEBUG) snake_case_ = logging.getLogger() def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Path , SCREAMING_SNAKE_CASE_ : list ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = "\n".join(SCREAMING_SNAKE_CASE_ ) Path(SCREAMING_SNAKE_CASE_ ).open("w" ).writelines(SCREAMING_SNAKE_CASE_ ) snake_case_ = 'patrickvonplaten/t5-tiny-random' snake_case_ = 'sshleifer/bart-tiny-random' snake_case_ = 'sshleifer/tiny-mbart' snake_case_ = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) logging.disable(logging.CRITICAL) # remove noisy download output from tracebacks class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = Path(self.get_auto_remove_tmp_dir() ) / "utest_input.source" SCREAMING_SNAKE_CASE_ : List[str] = input_file_name.parent / "utest_output.txt" assert not output_file_name.exists() SCREAMING_SNAKE_CASE_ : Dict = [" New York (CNN)When Liana Barrientos was 23 years old, she got married in Westchester County."] _dump_articles(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : Tuple = str(Path(self.get_auto_remove_tmp_dir() ) / "scores.json" ) SCREAMING_SNAKE_CASE_ : Tuple = "translation_en_to_de" if model == T5_TINY else "summarization" SCREAMING_SNAKE_CASE_ : Dict = F"\n run_eval_search.py\n {model}\n {input_file_name}\n {output_file_name}\n --score_path {score_path}\n --task {task}\n --num_beams 2\n --length_penalty 2.0\n ".split() with patch.object(lowercase__ , "argv" , lowercase__ ): run_generate() assert Path(lowercase__ ).exists() # os.remove(Path(output_file_name)) def __lowerCamelCase ( self ): """simple docstring""" self.run_eval_tester(lowercase__ ) @parameterized.expand([BART_TINY, MBART_TINY] ) @slow def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" self.run_eval_tester(lowercase__ ) @parameterized.expand([T5_TINY, MBART_TINY] ) @slow def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = Path(self.get_auto_remove_tmp_dir() ) / "utest_input.source" SCREAMING_SNAKE_CASE_ : Optional[Any] = input_file_name.parent / "utest_output.txt" assert not output_file_name.exists() SCREAMING_SNAKE_CASE_ : List[Any] = { "en": ["Machine learning is great, isn't it?", "I like to eat bananas", "Tomorrow is another great day!"], "de": [ "Maschinelles Lernen ist großartig, oder?", "Ich esse gerne Bananen", "Morgen ist wieder ein toller Tag!", ], } SCREAMING_SNAKE_CASE_ : Dict = Path(self.get_auto_remove_tmp_dir() ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = str(tmp_dir / "scores.json" ) SCREAMING_SNAKE_CASE_ : List[Any] = str(tmp_dir / "val.target" ) _dump_articles(lowercase__ , text["en"] ) _dump_articles(lowercase__ , text["de"] ) SCREAMING_SNAKE_CASE_ : List[Any] = "translation_en_to_de" if model == T5_TINY else "summarization" SCREAMING_SNAKE_CASE_ : List[str] = F"\n run_eval_search.py\n {model}\n {str(lowercase__ )}\n {str(lowercase__ )}\n --score_path {score_path}\n --reference_path {reference_path}\n --task {task}\n ".split() testargs.extend(["--search", "num_beams=1:2 length_penalty=0.9:1.0"] ) with patch.object(lowercase__ , "argv" , lowercase__ ): with CaptureStdout() as cs: run_search() SCREAMING_SNAKE_CASE_ : Union[str, Any] = [" num_beams | length_penalty", model, "Best score args"] SCREAMING_SNAKE_CASE_ : Optional[Any] = ["Info"] if "translation" in task: expected_strings.append("bleu" ) else: expected_strings.extend(lowercase__ ) for w in expected_strings: assert w in cs.out for w in un_expected_strings: assert w not in cs.out assert Path(lowercase__ ).exists() os.remove(Path(lowercase__ ) )
68
1
'''simple docstring''' import argparse import logging import os import time import timeit import datasets import numpy as np import pycuda.autoinit # noqa: F401 import pycuda.driver as cuda import tensorrt as trt import torch from absl import logging as absl_logging from accelerate import Accelerator from datasets import load_dataset, load_metric from torch.utils.data import DataLoader from utils_qa import postprocess_qa_predictions import transformers from transformers import AutoTokenizer, EvalPrediction, default_data_collator, set_seed from transformers.trainer_pt_utils import nested_concat, nested_truncate snake_case_ = trt.Logger(trt.Logger.WARNING) snake_case_ = absl_logging.get_absl_logger() absl_logger.setLevel(logging.WARNING) snake_case_ = logging.getLogger(__name__) snake_case_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--onnx_model_path', default=None, type=str, required=True, help='Path to ONNX model: ', ) parser.add_argument( '--output_dir', default=None, type=str, required=True, help='The output directory where the model checkpoints and predictions will be written.', ) # Other parameters parser.add_argument( '--tokenizer_name', default='', type=str, required=True, help='Pretrained tokenizer name or path if not the same as model_name', ) parser.add_argument( '--version_2_with_negative', action='store_true', help='If true, the SQuAD examples contain some that do not have an answer.', ) parser.add_argument( '--null_score_diff_threshold', type=float, default=0.0, help='If null_score - best_non_null is greater than the threshold predict null.', ) parser.add_argument( '--max_seq_length', default=3_8_4, type=int, help=( 'The maximum total input sequence length after WordPiece tokenization. Sequences ' 'longer than this will be truncated, and sequences shorter than this will be padded.' ), ) parser.add_argument( '--doc_stride', default=1_2_8, type=int, help='When splitting up a long document into chunks, how much stride to take between chunks.', ) parser.add_argument('--per_device_eval_batch_size', default=8, type=int, help='Batch size per GPU/CPU for evaluation.') parser.add_argument( '--n_best_size', default=2_0, type=int, help='The total number of n-best predictions to generate in the nbest_predictions.json output file.', ) parser.add_argument( '--max_answer_length', default=3_0, type=int, help=( 'The maximum length of an answer that can be generated. This is needed because the start ' 'and end predictions are not conditioned on one another.' ), ) parser.add_argument('--seed', type=int, default=4_2, help='random seed for initialization') parser.add_argument( '--dataset_name', type=str, default=None, required=True, help='The name of the dataset to use (via the datasets library).', ) parser.add_argument( '--dataset_config_name', type=str, default=None, help='The configuration name of the dataset to use (via the datasets library).', ) parser.add_argument( '--preprocessing_num_workers', type=int, default=4, help='A csv or a json file containing the training data.' ) parser.add_argument('--overwrite_cache', action='store_true', help='Overwrite the cached training and evaluation sets') parser.add_argument( '--fp16', action='store_true', help='Whether to use 16-bit (mixed) precision instead of 32-bit', ) parser.add_argument( '--int8', action='store_true', help='Whether to use INT8', ) snake_case_ = parser.parse_args() if args.tokenizer_name: snake_case_ = AutoTokenizer.from_pretrained(args.tokenizer_name, use_fast=True) else: raise ValueError( 'You are instantiating a new tokenizer from scratch. This is not supported by this script.' 'You can do it from another script, save it, and load it from here, using --tokenizer_name.' ) logger.info('Training/evaluation parameters %s', args) snake_case_ = args.per_device_eval_batch_size snake_case_ = (args.eval_batch_size, args.max_seq_length) # TRT Engine properties snake_case_ = True snake_case_ = 'temp_engine/bert-fp32.engine' if args.fpaa: snake_case_ = 'temp_engine/bert-fp16.engine' if args.inta: snake_case_ = 'temp_engine/bert-int8.engine' # import ONNX file if not os.path.exists('temp_engine'): os.makedirs('temp_engine') snake_case_ = 1 << (int)(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH) with trt.Builder(TRT_LOGGER) as builder, builder.create_network(EXPLICIT_BATCH) as network, trt.OnnxParser( network, TRT_LOGGER ) as parser: with open(args.onnx_model_path, 'rb') as model: if not parser.parse(model.read()): for error in range(parser.num_errors): print(parser.get_error(error)) # Query input names and shapes from parsed TensorRT network snake_case_ = [network.get_input(i) for i in range(network.num_inputs)] snake_case_ = [_input.name for _input in network_inputs] # ex: ["actual_input1"] with builder.create_builder_config() as config: snake_case_ = 1 << 5_0 if STRICT_TYPES: config.set_flag(trt.BuilderFlag.STRICT_TYPES) if args.fpaa: config.set_flag(trt.BuilderFlag.FPaa) if args.inta: config.set_flag(trt.BuilderFlag.INTa) snake_case_ = builder.create_optimization_profile() config.add_optimization_profile(profile) for i in range(len(input_names)): profile.set_shape(input_names[i], INPUT_SHAPE, INPUT_SHAPE, INPUT_SHAPE) snake_case_ = builder.build_engine(network, config) # serialize_engine and store in file (can be directly loaded and deserialized): with open(engine_name, 'wb') as f: f.write(engine.serialize()) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : Dict ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = np.asarray(inputs["input_ids"] , dtype=np.intaa ) SCREAMING_SNAKE_CASE_ : Optional[Any] = np.asarray(inputs["attention_mask"] , dtype=np.intaa ) SCREAMING_SNAKE_CASE_ : Any = np.asarray(inputs["token_type_ids"] , dtype=np.intaa ) # Copy inputs cuda.memcpy_htod_async(d_inputs[0] , input_ids.ravel() , SCREAMING_SNAKE_CASE_ ) cuda.memcpy_htod_async(d_inputs[1] , attention_mask.ravel() , SCREAMING_SNAKE_CASE_ ) cuda.memcpy_htod_async(d_inputs[2] , token_type_ids.ravel() , SCREAMING_SNAKE_CASE_ ) # start time SCREAMING_SNAKE_CASE_ : Tuple = time.time() # Run inference context.execute_async( bindings=[int(SCREAMING_SNAKE_CASE_ ) for d_inp in d_inputs] + [int(SCREAMING_SNAKE_CASE_ ), int(SCREAMING_SNAKE_CASE_ )] , stream_handle=stream.handle ) # Transfer predictions back from GPU cuda.memcpy_dtoh_async(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) cuda.memcpy_dtoh_async(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Synchronize the stream and take time stream.synchronize() # end time SCREAMING_SNAKE_CASE_ : Optional[int] = time.time() SCREAMING_SNAKE_CASE_ : int = end_time - start_time SCREAMING_SNAKE_CASE_ : List[str] = (h_outputa, h_outputa) # print(outputs) return outputs, infer_time # Initialize the accelerator. We will let the accelerator handle device placement for us in this example. snake_case_ = Accelerator() # Make one log on every process with the configuration for debugging. logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO, ) # Setup logging, we only want one process per machine to log things on the screen. # accelerator.is_local_main_process is only True for one process per machine. logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_info() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # If passed along, set the training seed now. if args.seed is not None: set_seed(args.seed) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). if args.dataset_name is not None: # Downloading and loading a dataset from the hub. snake_case_ = load_dataset(args.dataset_name, args.dataset_config_name) else: raise ValueError('Evaluation requires a dataset name') # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Preprocessing the datasets. # Preprocessing is slighlty different for training and evaluation. snake_case_ = raw_datasets['validation'].column_names snake_case_ = 'question' if 'question' in column_names else column_names[0] snake_case_ = 'context' if 'context' in column_names else column_names[1] snake_case_ = 'answers' if 'answers' in column_names else column_names[2] # Padding side determines if we do (question|context) or (context|question). snake_case_ = tokenizer.padding_side == 'right' if args.max_seq_length > tokenizer.model_max_length: logger.warning( F'''The max_seq_length passed ({args.max_seq_length}) is larger than the maximum length for the''' F'''model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.''' ) snake_case_ = min(args.max_seq_length, tokenizer.model_max_length) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Tuple ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = [q.lstrip() for q in examples[question_column_name]] # Tokenize our examples with truncation and maybe padding, but keep the overflows using a stride. This results # in one example possible giving several features when a context is long, each of those features having a # context that overlaps a bit the context of the previous feature. SCREAMING_SNAKE_CASE_ : Optional[Any] = tokenizer( examples[question_column_name if pad_on_right else context_column_name] , examples[context_column_name if pad_on_right else question_column_name] , truncation="only_second" if pad_on_right else "only_first" , max_length=SCREAMING_SNAKE_CASE_ , stride=args.doc_stride , return_overflowing_tokens=SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , padding="max_length" , ) # Since one example might give us several features if it has a long context, we need a map from a feature to # its corresponding example. This key gives us just that. SCREAMING_SNAKE_CASE_ : List[str] = tokenized_examples.pop("overflow_to_sample_mapping" ) # For evaluation, we will need to convert our predictions to substrings of the context, so we keep the # corresponding example_id and we will store the offset mappings. SCREAMING_SNAKE_CASE_ : str = [] for i in range(len(tokenized_examples["input_ids"] ) ): # Grab the sequence corresponding to that example (to know what is the context and what is the question). SCREAMING_SNAKE_CASE_ : Optional[int] = tokenized_examples.sequence_ids(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : int = 1 if pad_on_right else 0 # One example can give several spans, this is the index of the example containing this span of text. SCREAMING_SNAKE_CASE_ : str = sample_mapping[i] tokenized_examples["example_id"].append(examples["id"][sample_index] ) # Set to None the offset_mapping that are not part of the context so it's easy to determine if a token # position is part of the context or not. SCREAMING_SNAKE_CASE_ : Optional[Any] = [ (o if sequence_ids[k] == context_index else None) for k, o in enumerate(tokenized_examples["offset_mapping"][i] ) ] return tokenized_examples snake_case_ = raw_datasets['validation'] # Validation Feature Creation snake_case_ = eval_examples.map( prepare_validation_features, batched=True, num_proc=args.preprocessing_num_workers, remove_columns=column_names, load_from_cache_file=not args.overwrite_cache, desc='Running tokenizer on validation dataset', ) snake_case_ = default_data_collator snake_case_ = eval_dataset.remove_columns(['example_id', 'offset_mapping']) snake_case_ = DataLoader( eval_dataset_for_model, collate_fn=data_collator, batch_size=args.per_device_eval_batch_size ) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : List[str]="eval" ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = postprocess_qa_predictions( examples=SCREAMING_SNAKE_CASE_ , features=SCREAMING_SNAKE_CASE_ , predictions=SCREAMING_SNAKE_CASE_ , version_2_with_negative=args.version_2_with_negative , n_best_size=args.n_best_size , max_answer_length=args.max_answer_length , null_score_diff_threshold=args.null_score_diff_threshold , output_dir=args.output_dir , prefix=SCREAMING_SNAKE_CASE_ , ) # Format the result to the format the metric expects. if args.version_2_with_negative: SCREAMING_SNAKE_CASE_ : Dict = [ {"id": k, "prediction_text": v, "no_answer_probability": 0.0} for k, v in predictions.items() ] else: SCREAMING_SNAKE_CASE_ : str = [{"id": k, "prediction_text": v} for k, v in predictions.items()] SCREAMING_SNAKE_CASE_ : Optional[int] = [{"id": ex["id"], "answers": ex[answer_column_name]} for ex in examples] return EvalPrediction(predictions=SCREAMING_SNAKE_CASE_ , label_ids=SCREAMING_SNAKE_CASE_ ) snake_case_ = load_metric('squad_v2' if args.version_2_with_negative else 'squad') # Evaluation! logger.info('Loading ONNX model %s for evaluation', args.onnx_model_path) with open(engine_name, 'rb') as f, trt.Runtime(TRT_LOGGER) as runtime, runtime.deserialize_cuda_engine( f.read() ) as engine, engine.create_execution_context() as context: # setup for TRT inferrence for i in range(len(input_names)): context.set_binding_shape(i, INPUT_SHAPE) assert context.all_binding_shapes_specified def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int ) -> Any: """simple docstring""" return trt.volume(engine.get_binding_shape(SCREAMING_SNAKE_CASE_ ) ) * engine.get_binding_dtype(SCREAMING_SNAKE_CASE_ ).itemsize # Allocate device memory for inputs and outputs. snake_case_ = [cuda.mem_alloc(binding_nbytes(binding)) for binding in engine if engine.binding_is_input(binding)] # Allocate output buffer snake_case_ = cuda.pagelocked_empty(tuple(context.get_binding_shape(3)), dtype=np.floataa) snake_case_ = cuda.pagelocked_empty(tuple(context.get_binding_shape(4)), dtype=np.floataa) snake_case_ = cuda.mem_alloc(h_outputa.nbytes) snake_case_ = cuda.mem_alloc(h_outputa.nbytes) # Create a stream in which to copy inputs/outputs and run inference. snake_case_ = cuda.Stream() # Evaluation logger.info('***** Running Evaluation *****') logger.info(F''' Num examples = {len(eval_dataset)}''') logger.info(F''' Batch size = {args.per_device_eval_batch_size}''') snake_case_ = 0.0 snake_case_ = 0 snake_case_ = timeit.default_timer() snake_case_ = None for step, batch in enumerate(eval_dataloader): snake_case_ , snake_case_ = model_infer(batch, context, d_inputs, h_outputa, h_outputa, d_outputa, d_outputa, stream) total_time += infer_time niter += 1 snake_case_ , snake_case_ = outputs snake_case_ = torch.tensor(start_logits) snake_case_ = torch.tensor(end_logits) # necessary to pad predictions and labels for being gathered snake_case_ = accelerator.pad_across_processes(start_logits, dim=1, pad_index=-1_0_0) snake_case_ = accelerator.pad_across_processes(end_logits, dim=1, pad_index=-1_0_0) snake_case_ = (accelerator.gather(start_logits).cpu().numpy(), accelerator.gather(end_logits).cpu().numpy()) snake_case_ = logits if all_preds is None else nested_concat(all_preds, logits, padding_index=-1_0_0) if all_preds is not None: snake_case_ = nested_truncate(all_preds, len(eval_dataset)) snake_case_ = timeit.default_timer() - start_time logger.info(' Evaluation done in total %f secs (%f sec per example)', evalTime, evalTime / len(eval_dataset)) # Inference time from TRT logger.info('Average Inference Time = {:.3f} ms'.format(total_time * 1_0_0_0 / niter)) logger.info('Total Inference Time = {:.3f} ms'.format(total_time * 1_0_0_0)) logger.info('Total Number of Inference = %d', niter) snake_case_ = post_processing_function(eval_examples, eval_dataset, all_preds) snake_case_ = metric.compute(predictions=prediction.predictions, references=prediction.label_ids) logger.info(F'''Evaluation metrics: {eval_metric}''')
68
'''simple docstring''' from __future__ import annotations import numpy as np from numpy import floataa from numpy.typing import NDArray def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : NDArray[floataa] , SCREAMING_SNAKE_CASE_ : NDArray[floataa] , SCREAMING_SNAKE_CASE_ : list[int] , SCREAMING_SNAKE_CASE_ : int , ) -> list[float]: """simple docstring""" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : str = coefficient_matrix.shape SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : List[Any] = constant_matrix.shape if rowsa != colsa: SCREAMING_SNAKE_CASE_ : Union[str, Any] = F"Coefficient matrix dimensions must be nxn but received {rowsa}x{colsa}" raise ValueError(SCREAMING_SNAKE_CASE_ ) if colsa != 1: SCREAMING_SNAKE_CASE_ : List[Any] = F"Constant matrix must be nx1 but received {rowsa}x{colsa}" raise ValueError(SCREAMING_SNAKE_CASE_ ) if rowsa != rowsa: SCREAMING_SNAKE_CASE_ : Any = ( "Coefficient and constant matrices dimensions must be nxn and nx1 but " F"received {rowsa}x{colsa} and {rowsa}x{colsa}" ) raise ValueError(SCREAMING_SNAKE_CASE_ ) if len(SCREAMING_SNAKE_CASE_ ) != rowsa: SCREAMING_SNAKE_CASE_ : int = ( "Number of initial values must be equal to number of rows in coefficient " F"matrix but received {len(SCREAMING_SNAKE_CASE_ )} and {rowsa}" ) raise ValueError(SCREAMING_SNAKE_CASE_ ) if iterations <= 0: raise ValueError("Iterations must be at least 1" ) SCREAMING_SNAKE_CASE_ : NDArray[floataa] = np.concatenate( (coefficient_matrix, constant_matrix) , axis=1 ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Any = table.shape strictly_diagonally_dominant(SCREAMING_SNAKE_CASE_ ) # Iterates the whole matrix for given number of times for _ in range(SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ : Tuple = [] for row in range(SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ : Any = 0 for col in range(SCREAMING_SNAKE_CASE_ ): if col == row: SCREAMING_SNAKE_CASE_ : Any = table[row][col] elif col == cols - 1: SCREAMING_SNAKE_CASE_ : Dict = table[row][col] else: temp += (-1) * table[row][col] * init_val[col] SCREAMING_SNAKE_CASE_ : Optional[Any] = (temp + val) / denom new_val.append(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = new_val return [float(SCREAMING_SNAKE_CASE_ ) for i in new_val] def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : NDArray[floataa] ) -> bool: """simple docstring""" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = table.shape SCREAMING_SNAKE_CASE_ : Tuple = True for i in range(0 , SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ : int = 0 for j in range(0 , cols - 1 ): if i == j: continue else: total += table[i][j] if table[i][i] <= total: raise ValueError("Coefficient matrix is not strictly diagonally dominant" ) return is_diagonally_dominant # Test Cases if __name__ == "__main__": import doctest doctest.testmod()
68
1
'''simple docstring''' from collections import defaultdict class SCREAMING_SNAKE_CASE__ : def __init__( self , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = total # total no of tasks (N) # DP table will have a dimension of (2^M)*N # initially all values are set to -1 SCREAMING_SNAKE_CASE_ : Dict = [ [-1 for i in range(total + 1 )] for j in range(2 ** len(lowercase__ ) ) ] SCREAMING_SNAKE_CASE_ : Union[str, Any] = defaultdict(lowercase__ ) # stores the list of persons for each task # final_mask is used to check if all persons are included by setting all bits # to 1 SCREAMING_SNAKE_CASE_ : Union[str, Any] = (1 << len(lowercase__ )) - 1 def __lowerCamelCase ( self , lowercase__ , lowercase__ ): """simple docstring""" if mask == self.final_mask: return 1 # if not everyone gets the task and no more tasks are available, return 0 if task_no > self.total_tasks: return 0 # if case already considered if self.dp[mask][task_no] != -1: return self.dp[mask][task_no] # Number of ways when we don't this task in the arrangement SCREAMING_SNAKE_CASE_ : Optional[int] = self.count_ways_until(lowercase__ , task_no + 1 ) # now assign the tasks one by one to all possible persons and recursively # assign for the remaining tasks. if task_no in self.task: for p in self.task[task_no]: # if p is already given a task if mask & (1 << p): continue # assign this task to p and change the mask value. And recursively # assign tasks with the new mask value. total_ways_util += self.count_ways_until(mask | (1 << p) , task_no + 1 ) # save the value. SCREAMING_SNAKE_CASE_ : List[str] = total_ways_util return self.dp[mask][task_no] def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" for i in range(len(lowercase__ ) ): for j in task_performed[i]: self.task[j].append(lowercase__ ) # call the function to fill the DP table, final answer is stored in dp[0][1] return self.count_ways_until(0 , 1 ) if __name__ == "__main__": snake_case_ = 5 # total no of tasks (the value of N) # the list of tasks that can be done by M persons. snake_case_ = [[1, 3, 4], [1, 2, 5], [3, 4]] print( AssignmentUsingBitmask(task_performed, total_tasks).count_no_of_ways( task_performed ) )
68
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int ) -> int: """simple docstring""" return 1 if input_a == input_a else 0 def __lowerCamelCase ( ) -> None: """simple docstring""" assert xnor_gate(0 , 0 ) == 1 assert xnor_gate(0 , 1 ) == 0 assert xnor_gate(1 , 0 ) == 0 assert xnor_gate(1 , 1 ) == 1 if __name__ == "__main__": print(xnor_gate(0, 0)) print(xnor_gate(0, 1)) print(xnor_gate(1, 0)) print(xnor_gate(1, 1))
68
1
'''simple docstring''' import math from collections import defaultdict from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Optional[Any]=0.999 , SCREAMING_SNAKE_CASE_ : Any="cosine" , ) -> List[str]: """simple docstring""" if alpha_transform_type == "cosine": def alpha_bar_fn(SCREAMING_SNAKE_CASE_ : List[str] ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(SCREAMING_SNAKE_CASE_ : Optional[Any] ): return math.exp(t * -12.0 ) else: raise ValueError(F"Unsupported alpha_tranform_type: {alpha_transform_type}" ) SCREAMING_SNAKE_CASE_ : Tuple = [] for i in range(SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ : int = i / num_diffusion_timesteps SCREAMING_SNAKE_CASE_ : Any = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(SCREAMING_SNAKE_CASE_ ) / alpha_bar_fn(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) ) return torch.tensor(SCREAMING_SNAKE_CASE_ , dtype=torch.floataa ) class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,_UpperCAmelCase ): _A = [e.name for e in KarrasDiffusionSchedulers] _A = 2 @register_to_config def __init__( self , lowercase__ = 1000 , lowercase__ = 0.00085 , lowercase__ = 0.012 , lowercase__ = "linear" , lowercase__ = None , lowercase__ = "epsilon" , lowercase__ = "linspace" , lowercase__ = 0 , ): """simple docstring""" if trained_betas is not None: SCREAMING_SNAKE_CASE_ : Any = torch.tensor(lowercase__ , dtype=torch.floataa ) elif beta_schedule == "linear": SCREAMING_SNAKE_CASE_ : Dict = torch.linspace(lowercase__ , lowercase__ , lowercase__ , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. SCREAMING_SNAKE_CASE_ : Any = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , lowercase__ , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule SCREAMING_SNAKE_CASE_ : Optional[Any] = betas_for_alpha_bar(lowercase__ ) else: raise NotImplementedError(F"{beta_schedule} does is not implemented for {self.__class__}" ) SCREAMING_SNAKE_CASE_ : Dict = 1.0 - self.betas SCREAMING_SNAKE_CASE_ : List[str] = torch.cumprod(self.alphas , dim=0 ) # set all values self.set_timesteps(lowercase__ , lowercase__ , lowercase__ ) def __lowerCamelCase ( self , lowercase__ , lowercase__=None ): """simple docstring""" if schedule_timesteps is None: SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.timesteps SCREAMING_SNAKE_CASE_ : Tuple = (schedule_timesteps == timestep).nonzero() # The sigma index that is taken for the **very** first `step` # is always the second index (or the last index if there is only 1) # This way we can ensure we don't accidentally skip a sigma in # case we start in the middle of the denoising schedule (e.g. for image-to-image) if len(self._index_counter ) == 0: SCREAMING_SNAKE_CASE_ : List[str] = 1 if len(lowercase__ ) > 1 else 0 else: SCREAMING_SNAKE_CASE_ : List[str] = timestep.cpu().item() if torch.is_tensor(lowercase__ ) else timestep SCREAMING_SNAKE_CASE_ : Optional[Any] = self._index_counter[timestep_int] return indices[pos].item() @property def __lowerCamelCase ( self ): """simple docstring""" if self.config.timestep_spacing in ["linspace", "trailing"]: return self.sigmas.max() return (self.sigmas.max() ** 2 + 1) ** 0.5 def __lowerCamelCase ( self , lowercase__ , lowercase__ , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = self.index_for_timestep(lowercase__ ) if self.state_in_first_order: SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.sigmas[step_index] else: SCREAMING_SNAKE_CASE_ : Optional[int] = self.sigmas_interpol[step_index] SCREAMING_SNAKE_CASE_ : Optional[int] = sample / ((sigma**2 + 1) ** 0.5) return sample def __lowerCamelCase ( self , lowercase__ , lowercase__ = None , lowercase__ = None , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = num_inference_steps SCREAMING_SNAKE_CASE_ : Any = num_train_timesteps or self.config.num_train_timesteps # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891 if self.config.timestep_spacing == "linspace": SCREAMING_SNAKE_CASE_ : int = np.linspace(0 , num_train_timesteps - 1 , lowercase__ , dtype=lowercase__ )[::-1].copy() elif self.config.timestep_spacing == "leading": SCREAMING_SNAKE_CASE_ : Optional[Any] = num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 SCREAMING_SNAKE_CASE_ : Optional[Any] = (np.arange(0 , lowercase__ ) * step_ratio).round()[::-1].copy().astype(lowercase__ ) timesteps += self.config.steps_offset elif self.config.timestep_spacing == "trailing": SCREAMING_SNAKE_CASE_ : Optional[int] = num_train_timesteps / self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 SCREAMING_SNAKE_CASE_ : str = (np.arange(lowercase__ , 0 , -step_ratio )).round().copy().astype(lowercase__ ) timesteps -= 1 else: raise ValueError( F"{self.config.timestep_spacing} is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'." ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5 ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.from_numpy(np.log(lowercase__ ) ).to(lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = np.interp(lowercase__ , np.arange(0 , len(lowercase__ ) ) , lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = np.concatenate([sigmas, [0.0]] ).astype(np.floataa ) SCREAMING_SNAKE_CASE_ : Dict = torch.from_numpy(lowercase__ ).to(device=lowercase__ ) # interpolate sigmas SCREAMING_SNAKE_CASE_ : str = sigmas.log().lerp(sigmas.roll(1 ).log() , 0.5 ).exp() SCREAMING_SNAKE_CASE_ : Any = torch.cat([sigmas[:1], sigmas[1:].repeat_interleave(2 ), sigmas[-1:]] ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.cat( [sigmas_interpol[:1], sigmas_interpol[1:].repeat_interleave(2 ), sigmas_interpol[-1:]] ) if str(lowercase__ ).startswith("mps" ): # mps does not support float64 SCREAMING_SNAKE_CASE_ : str = torch.from_numpy(lowercase__ ).to(lowercase__ , dtype=torch.floataa ) else: SCREAMING_SNAKE_CASE_ : List[str] = torch.from_numpy(lowercase__ ).to(lowercase__ ) # interpolate timesteps SCREAMING_SNAKE_CASE_ : Optional[Any] = self.sigma_to_t(lowercase__ ).to(lowercase__ , dtype=timesteps.dtype ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.stack((timesteps_interpol[1:-1, None], timesteps[1:, None]) , dim=-1 ).flatten() SCREAMING_SNAKE_CASE_ : List[str] = torch.cat([timesteps[:1], interleaved_timesteps] ) SCREAMING_SNAKE_CASE_ : Tuple = None # for exp beta schedules, such as the one for `pipeline_shap_e.py` # we need an index counter SCREAMING_SNAKE_CASE_ : str = defaultdict(lowercase__ ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = sigma.log() # get distribution SCREAMING_SNAKE_CASE_ : Optional[int] = log_sigma - self.log_sigmas[:, None] # get sigmas range SCREAMING_SNAKE_CASE_ : Optional[Any] = dists.ge(0 ).cumsum(dim=0 ).argmax(dim=0 ).clamp(max=self.log_sigmas.shape[0] - 2 ) SCREAMING_SNAKE_CASE_ : List[str] = low_idx + 1 SCREAMING_SNAKE_CASE_ : Optional[Any] = self.log_sigmas[low_idx] SCREAMING_SNAKE_CASE_ : List[Any] = self.log_sigmas[high_idx] # interpolate sigmas SCREAMING_SNAKE_CASE_ : Union[str, Any] = (low - log_sigma) / (low - high) SCREAMING_SNAKE_CASE_ : Dict = w.clamp(0 , 1 ) # transform interpolation to time range SCREAMING_SNAKE_CASE_ : Optional[int] = (1 - w) * low_idx + w * high_idx SCREAMING_SNAKE_CASE_ : int = t.view(sigma.shape ) return t @property def __lowerCamelCase ( self ): """simple docstring""" return self.sample is None def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ = True , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = self.index_for_timestep(lowercase__ ) # advance index counter by 1 SCREAMING_SNAKE_CASE_ : Tuple = timestep.cpu().item() if torch.is_tensor(lowercase__ ) else timestep self._index_counter[timestep_int] += 1 if self.state_in_first_order: SCREAMING_SNAKE_CASE_ : List[str] = self.sigmas[step_index] SCREAMING_SNAKE_CASE_ : int = self.sigmas_interpol[step_index + 1] SCREAMING_SNAKE_CASE_ : List[Any] = self.sigmas[step_index + 1] else: # 2nd order / KDPM2's method SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.sigmas[step_index - 1] SCREAMING_SNAKE_CASE_ : Any = self.sigmas_interpol[step_index] SCREAMING_SNAKE_CASE_ : Optional[Any] = self.sigmas[step_index] # currently only gamma=0 is supported. This usually works best anyways. # We can support gamma in the future but then need to scale the timestep before # passing it to the model which requires a change in API SCREAMING_SNAKE_CASE_ : List[str] = 0 SCREAMING_SNAKE_CASE_ : int = sigma * (gamma + 1) # Note: sigma_hat == sigma for now # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise if self.config.prediction_type == "epsilon": SCREAMING_SNAKE_CASE_ : List[str] = sigma_hat if self.state_in_first_order else sigma_interpol SCREAMING_SNAKE_CASE_ : Union[str, Any] = sample - sigma_input * model_output elif self.config.prediction_type == "v_prediction": SCREAMING_SNAKE_CASE_ : List[str] = sigma_hat if self.state_in_first_order else sigma_interpol SCREAMING_SNAKE_CASE_ : Tuple = model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + ( sample / (sigma_input**2 + 1) ) elif self.config.prediction_type == "sample": raise NotImplementedError("prediction_type not implemented yet: sample" ) else: raise ValueError( F"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`" ) if self.state_in_first_order: # 2. Convert to an ODE derivative for 1st order SCREAMING_SNAKE_CASE_ : List[Any] = (sample - pred_original_sample) / sigma_hat # 3. delta timestep SCREAMING_SNAKE_CASE_ : Any = sigma_interpol - sigma_hat # store for 2nd order step SCREAMING_SNAKE_CASE_ : Optional[int] = sample else: # DPM-Solver-2 # 2. Convert to an ODE derivative for 2nd order SCREAMING_SNAKE_CASE_ : str = (sample - pred_original_sample) / sigma_interpol # 3. delta timestep SCREAMING_SNAKE_CASE_ : Optional[int] = sigma_next - sigma_hat SCREAMING_SNAKE_CASE_ : Tuple = self.sample SCREAMING_SNAKE_CASE_ : Union[str, Any] = None SCREAMING_SNAKE_CASE_ : List[str] = sample + derivative * dt if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=lowercase__ ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = self.sigmas.to(device=original_samples.device , dtype=original_samples.dtype ) if original_samples.device.type == "mps" and torch.is_floating_point(lowercase__ ): # mps does not support float64 SCREAMING_SNAKE_CASE_ : List[str] = self.timesteps.to(original_samples.device , dtype=torch.floataa ) SCREAMING_SNAKE_CASE_ : Tuple = timesteps.to(original_samples.device , dtype=torch.floataa ) else: SCREAMING_SNAKE_CASE_ : List[str] = self.timesteps.to(original_samples.device ) SCREAMING_SNAKE_CASE_ : str = timesteps.to(original_samples.device ) SCREAMING_SNAKE_CASE_ : Dict = [self.index_for_timestep(lowercase__ , lowercase__ ) for t in timesteps] SCREAMING_SNAKE_CASE_ : Optional[Any] = sigmas[step_indices].flatten() while len(sigma.shape ) < len(original_samples.shape ): SCREAMING_SNAKE_CASE_ : Optional[int] = sigma.unsqueeze(-1 ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = original_samples + noise * sigma return noisy_samples def __len__( self ): """simple docstring""" return self.config.num_train_timesteps
68
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , ) -> float: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = [redshift, radiation_density, matter_density, dark_energy] if any(p < 0 for p in parameters ): raise ValueError("All input parameters must be positive" ) if any(p > 1 for p in parameters[1:4] ): raise ValueError("Relative densities cannot be greater than one" ) else: SCREAMING_SNAKE_CASE_ : int = 1 - (matter_density + radiation_density + dark_energy) SCREAMING_SNAKE_CASE_ : List[Any] = ( radiation_density * (redshift + 1) ** 4 + matter_density * (redshift + 1) ** 3 + curvature * (redshift + 1) ** 2 + dark_energy ) SCREAMING_SNAKE_CASE_ : Dict = hubble_constant * e_a ** (1 / 2) return hubble if __name__ == "__main__": import doctest # run doctest doctest.testmod() # demo LCDM approximation snake_case_ = 0.3 print( hubble_parameter( hubble_constant=6_8.3, radiation_density=1E-4, matter_density=matter_density, dark_energy=1 - matter_density, redshift=0, ) )
68
1
'''simple docstring''' import unittest import numpy as np import torch from diffusers import ScoreSdeVePipeline, ScoreSdeVeScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): @property def __lowerCamelCase ( self ): """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ : Any = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=("DownBlock2D", "AttnDownBlock2D") , up_block_types=("AttnUpBlock2D", "UpBlock2D") , ) return model def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = self.dummy_uncond_unet SCREAMING_SNAKE_CASE_ : Optional[int] = ScoreSdeVeScheduler() SCREAMING_SNAKE_CASE_ : int = ScoreSdeVePipeline(unet=lowercase__ , scheduler=lowercase__ ) sde_ve.to(lowercase__ ) sde_ve.set_progress_bar_config(disable=lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ : int = sde_ve(num_inference_steps=2 , output_type="numpy" , generator=lowercase__ ).images SCREAMING_SNAKE_CASE_ : List[str] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ : int = sde_ve(num_inference_steps=2 , output_type="numpy" , generator=lowercase__ , return_dict=lowercase__ )[ 0 ] SCREAMING_SNAKE_CASE_ : Tuple = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE_ : Any = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE_ : int = np.array([0.0, 1.0, 0.0, 0.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 SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = "google/ncsnpp-church-256" SCREAMING_SNAKE_CASE_ : List[Any] = UNetaDModel.from_pretrained(lowercase__ ) SCREAMING_SNAKE_CASE_ : int = ScoreSdeVeScheduler.from_pretrained(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = ScoreSdeVePipeline(unet=lowercase__ , scheduler=lowercase__ ) sde_ve.to(lowercase__ ) sde_ve.set_progress_bar_config(disable=lowercase__ ) SCREAMING_SNAKE_CASE_ : int = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ : str = sde_ve(num_inference_steps=10 , output_type="numpy" , generator=lowercase__ ).images SCREAMING_SNAKE_CASE_ : Dict = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) SCREAMING_SNAKE_CASE_ : Optional[int] = np.array([0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
68
'''simple docstring''' import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.generation import DisjunctiveConstraint @require_torch class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = [[1, 2, 4], [1, 2, 3, 4]] SCREAMING_SNAKE_CASE_ : Any = DisjunctiveConstraint(lowercase__ ) self.assertTrue(isinstance(dc.token_ids , lowercase__ ) ) with self.assertRaises(lowercase__ ): DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]] ) ) with self.assertRaises(lowercase__ ): DisjunctiveConstraint([torch.LongTensor([1, 2, 4] ), torch.LongTensor([1, 2, 3, 4, 5] )] ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = [[1, 2], [1, 2, 3, 4]] with self.assertRaises(lowercase__ ): DisjunctiveConstraint(lowercase__ ) # fails here def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = [[1, 2, 3], [1, 2, 4]] SCREAMING_SNAKE_CASE_ : Optional[Any] = DisjunctiveConstraint(lowercase__ ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = dc.update(1 ) SCREAMING_SNAKE_CASE_ : Optional[int] = stepped is True and completed is False and reset is False self.assertTrue(lowercase__ ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Tuple = dc.update(2 ) SCREAMING_SNAKE_CASE_ : Tuple = stepped is True and completed is False and reset is False self.assertTrue(lowercase__ ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Any = dc.update(3 ) SCREAMING_SNAKE_CASE_ : Tuple = stepped is True and completed is True and reset is False self.assertTrue(lowercase__ ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 3] ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]] SCREAMING_SNAKE_CASE_ : Dict = DisjunctiveConstraint(lowercase__ ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : List[Any] = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = dc.update(4 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2, 4] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : List[Any] = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 4, 5] ) dc.reset() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Tuple = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 3 ) self.assertTrue(dc.current_seq == [1] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : str = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 2 ) self.assertTrue(dc.current_seq == [1, 2] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : str = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.remaining() == 0 ) self.assertTrue(dc.current_seq == [1, 2, 5] )
68
1
'''simple docstring''' import functools import gc import inspect import torch from .imports import is_npu_available, is_xpu_available def __lowerCamelCase ( *SCREAMING_SNAKE_CASE_ : Any ) -> Union[str, Any]: """simple docstring""" if not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ : Union[str, Any] = list(SCREAMING_SNAKE_CASE_ ) for i in range(len(SCREAMING_SNAKE_CASE_ ) ): SCREAMING_SNAKE_CASE_ : Tuple = None gc.collect() if is_xpu_available(): torch.xpu.empty_cache() elif is_npu_available(): torch.npu.empty_cache() else: torch.cuda.empty_cache() return objects def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Exception ) -> bool: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = [ "CUDA out of memory.", # CUDA OOM "cuDNN error: CUDNN_STATUS_NOT_SUPPORTED.", # CUDNN SNAFU "DefaultCPUAllocator: can't allocate memory", # CPU OOM ] if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) and len(exception.args ) == 1: return any(err in exception.args[0] for err in _statements ) return False def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : callable = None , SCREAMING_SNAKE_CASE_ : int = 1_2_8 ) -> Tuple: """simple docstring""" if function is None: return functools.partial(SCREAMING_SNAKE_CASE_ , starting_batch_size=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = starting_batch_size def decorator(*SCREAMING_SNAKE_CASE_ : List[Any] , **SCREAMING_SNAKE_CASE_ : Union[str, Any] ): nonlocal batch_size gc.collect() if is_xpu_available(): torch.xpu.empty_cache() elif is_npu_available(): torch.npu.empty_cache() else: torch.cuda.empty_cache() SCREAMING_SNAKE_CASE_ : Optional[int] = list(inspect.signature(SCREAMING_SNAKE_CASE_ ).parameters.keys() ) # Guard against user error if len(SCREAMING_SNAKE_CASE_ ) < (len(SCREAMING_SNAKE_CASE_ ) + 1): SCREAMING_SNAKE_CASE_ : Tuple = ", ".join([F"{arg}={value}" for arg, value in zip(params[1:] , args[1:] )] ) raise TypeError( F"Batch size was passed into `{function.__name__}` as the first argument when called." F"Remove this as the decorator already does so: `{function.__name__}({arg_str})`" ) while True: if batch_size == 0: raise RuntimeError("No executable batch size found, reached zero." ) try: return function(SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) except Exception as e: if should_reduce_batch_size(SCREAMING_SNAKE_CASE_ ): gc.collect() if is_xpu_available(): torch.xpu.empty_cache() elif is_npu_available(): torch.npu.empty_cache() else: torch.cuda.empty_cache() batch_size //= 2 else: raise return decorator
68
'''simple docstring''' import unittest import torch from diffusers import VQModel from diffusers.utils import floats_tensor, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,_UpperCAmelCase,unittest.TestCase ): _A = VQModel _A = "sample" @property def __lowerCamelCase ( self , lowercase__=(32, 32) ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = 4 SCREAMING_SNAKE_CASE_ : str = 3 SCREAMING_SNAKE_CASE_ : str = floats_tensor((batch_size, num_channels) + sizes ).to(lowercase__ ) return {"sample": image} @property def __lowerCamelCase ( self ): """simple docstring""" return (3, 32, 32) @property def __lowerCamelCase ( self ): """simple docstring""" return (3, 32, 32) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = { "block_out_channels": [32, 64], "in_channels": 3, "out_channels": 3, "down_block_types": ["DownEncoderBlock2D", "DownEncoderBlock2D"], "up_block_types": ["UpDecoderBlock2D", "UpDecoderBlock2D"], "latent_channels": 3, } SCREAMING_SNAKE_CASE_ : int = self.dummy_input return init_dict, inputs_dict def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : int = VQModel.from_pretrained("fusing/vqgan-dummy" , output_loading_info=lowercase__ ) self.assertIsNotNone(lowercase__ ) self.assertEqual(len(loading_info["missing_keys"] ) , 0 ) model.to(lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = VQModel.from_pretrained("fusing/vqgan-dummy" ) model.to(lowercase__ ).eval() torch.manual_seed(0 ) if torch.cuda.is_available(): torch.cuda.manual_seed_all(0 ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.randn(1 , model.config.in_channels , model.config.sample_size , model.config.sample_size ) SCREAMING_SNAKE_CASE_ : str = image.to(lowercase__ ) with torch.no_grad(): SCREAMING_SNAKE_CASE_ : int = model(lowercase__ ).sample SCREAMING_SNAKE_CASE_ : Any = output[0, -1, -3:, -3:].flatten().cpu() # fmt: off SCREAMING_SNAKE_CASE_ : Optional[Any] = torch.tensor([-0.0153, -0.4044, -0.1880, -0.5161, -0.2418, -0.4072, -0.1612, -0.0633, -0.0143] ) # fmt: on self.assertTrue(torch.allclose(lowercase__ , lowercase__ , atol=1e-3 ) )
68
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging snake_case_ = logging.get_logger(__name__) snake_case_ = { 'microsoft/cvt-13': 'https://huggingface.co/microsoft/cvt-13/resolve/main/config.json', # See all Cvt models at https://huggingface.co/models?filter=cvt } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = "cvt" def __init__( self , lowercase__=3 , lowercase__=[7, 3, 3] , lowercase__=[4, 2, 2] , lowercase__=[2, 1, 1] , lowercase__=[64, 192, 384] , lowercase__=[1, 3, 6] , lowercase__=[1, 2, 10] , lowercase__=[4.0, 4.0, 4.0] , lowercase__=[0.0, 0.0, 0.0] , lowercase__=[0.0, 0.0, 0.0] , lowercase__=[0.0, 0.0, 0.1] , lowercase__=[True, True, True] , lowercase__=[False, False, True] , lowercase__=["dw_bn", "dw_bn", "dw_bn"] , lowercase__=[3, 3, 3] , lowercase__=[1, 1, 1] , lowercase__=[2, 2, 2] , lowercase__=[1, 1, 1] , lowercase__=[1, 1, 1] , lowercase__=0.02 , lowercase__=1e-12 , **lowercase__ , ): """simple docstring""" super().__init__(**lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = num_channels SCREAMING_SNAKE_CASE_ : List[Any] = patch_sizes SCREAMING_SNAKE_CASE_ : List[Any] = patch_stride SCREAMING_SNAKE_CASE_ : Dict = patch_padding SCREAMING_SNAKE_CASE_ : Tuple = embed_dim SCREAMING_SNAKE_CASE_ : Tuple = num_heads SCREAMING_SNAKE_CASE_ : str = depth SCREAMING_SNAKE_CASE_ : str = mlp_ratio SCREAMING_SNAKE_CASE_ : str = attention_drop_rate SCREAMING_SNAKE_CASE_ : Optional[int] = drop_rate SCREAMING_SNAKE_CASE_ : Optional[int] = drop_path_rate SCREAMING_SNAKE_CASE_ : List[str] = qkv_bias SCREAMING_SNAKE_CASE_ : Any = cls_token SCREAMING_SNAKE_CASE_ : Tuple = qkv_projection_method SCREAMING_SNAKE_CASE_ : Dict = kernel_qkv SCREAMING_SNAKE_CASE_ : Dict = padding_kv SCREAMING_SNAKE_CASE_ : Optional[Any] = stride_kv SCREAMING_SNAKE_CASE_ : Optional[int] = padding_q SCREAMING_SNAKE_CASE_ : Tuple = stride_q SCREAMING_SNAKE_CASE_ : str = initializer_range SCREAMING_SNAKE_CASE_ : Dict = layer_norm_eps
68
'''simple docstring''' import os import unittest from huggingface_hub.utils import are_progress_bars_disabled import transformers.models.bart.tokenization_bart from transformers import logging from transformers.testing_utils import CaptureLogger, mockenv, mockenv_context from transformers.utils.logging import disable_progress_bar, enable_progress_bar class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = logging.get_logger() # the current default level is logging.WARNING SCREAMING_SNAKE_CASE_ : Optional[int] = logging.get_verbosity() logging.set_verbosity_error() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_warning() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_info() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_debug() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) # restore to the original level logging.set_verbosity(lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = logging.get_verbosity() SCREAMING_SNAKE_CASE_ : List[Any] = logging.get_logger("transformers.models.bart.tokenization_bart" ) SCREAMING_SNAKE_CASE_ : List[Any] = "Testing 1, 2, 3" # should be able to log warnings (if default settings weren't overridden by `pytest --log-level-all`) if level_origin <= logging.WARNING: with CaptureLogger(lowercase__ ) as cl: logger.warning(lowercase__ ) self.assertEqual(cl.out , msg + "\n" ) # this is setting the level for all of `transformers.*` loggers logging.set_verbosity_error() # should not be able to log warnings with CaptureLogger(lowercase__ ) as cl: logger.warning(lowercase__ ) self.assertEqual(cl.out , "" ) # should be able to log warnings again logging.set_verbosity_warning() with CaptureLogger(lowercase__ ) as cl: logger.warning(lowercase__ ) self.assertEqual(cl.out , msg + "\n" ) # restore to the original level logging.set_verbosity(lowercase__ ) @mockenv(TRANSFORMERS_VERBOSITY="error" ) def __lowerCamelCase ( self ): """simple docstring""" transformers.utils.logging._reset_library_root_logger() # this action activates the env var SCREAMING_SNAKE_CASE_ : Tuple = logging.get_logger("transformers.models.bart.tokenization_bart" ) SCREAMING_SNAKE_CASE_ : int = os.getenv("TRANSFORMERS_VERBOSITY" , lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = logging.log_levels[env_level_str] SCREAMING_SNAKE_CASE_ : str = logging.get_verbosity() self.assertEqual( lowercase__ , lowercase__ , F"TRANSFORMERS_VERBOSITY={env_level_str}/{env_level}, but internal verbosity is {current_level}" , ) # restore to the original level SCREAMING_SNAKE_CASE_ : Optional[int] = "" transformers.utils.logging._reset_library_root_logger() @mockenv(TRANSFORMERS_VERBOSITY="super-error" ) def __lowerCamelCase ( self ): """simple docstring""" transformers.utils.logging._reset_library_root_logger() SCREAMING_SNAKE_CASE_ : List[Any] = logging.logging.getLogger() with CaptureLogger(lowercase__ ) as cl: # this action activates the env var logging.get_logger("transformers.models.bart.tokenization_bart" ) self.assertIn("Unknown option TRANSFORMERS_VERBOSITY=super-error" , cl.out ) # no need to restore as nothing was changed def __lowerCamelCase ( self ): """simple docstring""" transformers.utils.logging._reset_library_root_logger() SCREAMING_SNAKE_CASE_ : str = logging.get_logger("transformers.models.bart.tokenization_bart" ) SCREAMING_SNAKE_CASE_ : List[Any] = "Testing 1, 2, 3" with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS="1" ): # nothing should be logged as env var disables this method with CaptureLogger(lowercase__ ) as cl: logger.warning_advice(lowercase__ ) self.assertEqual(cl.out , "" ) with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS="" ): # should log normally as TRANSFORMERS_NO_ADVISORY_WARNINGS is unset with CaptureLogger(lowercase__ ) as cl: logger.warning_advice(lowercase__ ) self.assertEqual(cl.out , msg + "\n" ) def __lowerCamelCase ( ) -> Optional[int]: """simple docstring""" disable_progress_bar() assert are_progress_bars_disabled() enable_progress_bar() assert not are_progress_bars_disabled()
68
1
'''simple docstring''' from PIL import Image def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Image , SCREAMING_SNAKE_CASE_ : float ) -> Image: """simple docstring""" def brightness(SCREAMING_SNAKE_CASE_ : int ) -> float: return 1_2_8 + level + (c - 1_2_8) if not -255.0 <= level <= 255.0: raise ValueError("level must be between -255.0 (black) and 255.0 (white)" ) return img.point(SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": # Load image with Image.open('image_data/lena.jpg') as img: # Change brightness to 100 snake_case_ = change_brightness(img, 1_0_0) brigt_img.save('image_data/lena_brightness.png', format='png')
68
'''simple docstring''' import json import os import tempfile from unittest.mock import patch import torch from torch.utils.data import DataLoader, TensorDataset from accelerate import DistributedType, infer_auto_device_map, init_empty_weights from accelerate.accelerator import Accelerator from accelerate.state import GradientState, PartialState from accelerate.test_utils import require_bnb, require_multi_gpu, slow from accelerate.test_utils.testing import AccelerateTestCase, require_cuda from accelerate.utils import patch_environment def __lowerCamelCase ( ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = torch.nn.Linear(2 , 4 ) SCREAMING_SNAKE_CASE_ : List[Any] = torch.optim.AdamW(model.parameters() , lr=1.0 ) SCREAMING_SNAKE_CASE_ : Any = torch.optim.lr_scheduler.OneCycleLR(SCREAMING_SNAKE_CASE_ , max_lr=0.01 , steps_per_epoch=2 , epochs=1 ) SCREAMING_SNAKE_CASE_ : Dict = DataLoader(TensorDataset(torch.tensor([1, 2, 3] ) ) ) SCREAMING_SNAKE_CASE_ : Tuple = DataLoader(TensorDataset(torch.tensor([4, 5, 6] ) ) ) return model, optimizer, scheduler, train_dl, valid_dl def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : List[str] ) -> Tuple: """simple docstring""" return (model.weight.abs().sum() + model.bias.abs().sum()).item() def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Any ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : str = torch.nn.Linear(*tuple(model.weight.T.shape ) ).state_dict() model.load_state_dict(SCREAMING_SNAKE_CASE_ ) class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): @require_cuda def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = Accelerator() assert PartialState._shared_state["_cpu"] is False assert PartialState._shared_state["device"].type == "cuda" with self.assertRaises(lowercase__ ): SCREAMING_SNAKE_CASE_ : List[Any] = Accelerator(cpu=lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = Accelerator() SCREAMING_SNAKE_CASE_ : Any = GradientState() assert state.num_steps == 1 SCREAMING_SNAKE_CASE_ : Union[str, Any] = 4 assert state.num_steps == 4 assert state.sync_gradients is True SCREAMING_SNAKE_CASE_ : Optional[int] = False assert state.sync_gradients is False GradientState._reset_state() def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[int] = create_components() ( ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ) : Optional[Any] = accelerator.prepare(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) self.assertTrue(prepared_model in accelerator._models ) self.assertTrue(prepared_optimizer in accelerator._optimizers ) self.assertTrue(prepared_scheduler in accelerator._schedulers ) self.assertTrue(prepared_train_dl in accelerator._dataloaders ) self.assertTrue(prepared_valid_dl in accelerator._dataloaders ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : str = create_components() accelerator.prepare(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) accelerator.free_memory() self.assertTrue(len(accelerator._models ) == 0 ) self.assertTrue(len(accelerator._optimizers ) == 0 ) self.assertTrue(len(accelerator._schedulers ) == 0 ) self.assertTrue(len(accelerator._dataloaders ) == 0 ) def __lowerCamelCase ( self ): """simple docstring""" PartialState._reset_state() # Mock torch.cuda.set_device to avoid an exception as the device doesn't exist def noop(*lowercase__ , **lowercase__ ): pass with patch("torch.cuda.set_device" , lowercase__ ), patch_environment(ACCELERATE_TORCH_DEVICE="cuda:64" ): SCREAMING_SNAKE_CASE_ : List[str] = Accelerator() self.assertEqual(str(accelerator.state.device ) , "cuda:64" ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = create_components() accelerator.prepare(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = get_signature(lowercase__ ) with tempfile.TemporaryDirectory() as tmpdirname: accelerator.save_state(lowercase__ ) # make sure random weights don't match load_random_weights(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) > 1e-3 ) # make sure loaded weights match accelerator.load_state(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) < 1e-3 ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[int] = create_components() accelerator.prepare(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = get_signature(lowercase__ ) # saving hook def save_config(lowercase__ , lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE_ : Optional[Any] = {"class_name": models[0].__class__.__name__} with open(os.path.join(lowercase__ , "data.json" ) , "w" ) as f: json.dump(lowercase__ , lowercase__ ) # loading hook def load_config(lowercase__ , lowercase__ ): with open(os.path.join(lowercase__ , "data.json" ) , "r" ) as f: SCREAMING_SNAKE_CASE_ : Any = json.load(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = config["class_name"] SCREAMING_SNAKE_CASE_ : Dict = accelerator.register_save_state_pre_hook(lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = accelerator.register_load_state_pre_hook(lowercase__ ) with tempfile.TemporaryDirectory() as tmpdirname: accelerator.save_state(lowercase__ ) # make sure random weights don't match with hooks load_random_weights(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) > 1e-3 ) # random class name to verify correct one is loaded SCREAMING_SNAKE_CASE_ : Union[str, Any] = "random" # make sure loaded weights match with hooks accelerator.load_state(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) < 1e-3 ) # mode.class_name is loaded from config self.assertTrue(model.class_name == model.__class__.__name__ ) # remove hooks save_hook.remove() load_hook.remove() with tempfile.TemporaryDirectory() as tmpdirname: accelerator.save_state(lowercase__ ) # make sure random weights don't match with hooks removed load_random_weights(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) > 1e-3 ) # random class name to verify correct one is loaded SCREAMING_SNAKE_CASE_ : Tuple = "random" # make sure loaded weights match with hooks removed accelerator.load_state(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) < 1e-3 ) # mode.class_name is NOT loaded from config self.assertTrue(model.class_name != model.__class__.__name__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Tuple = create_components() SCREAMING_SNAKE_CASE_ : Union[str, Any] = None # This should work SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[int] = accelerator.prepare( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) self.assertTrue(dummy_obj is None ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = create_components() SCREAMING_SNAKE_CASE_ : Union[str, Any] = [1, 2, 3] # This should work SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : int = accelerator.prepare( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Dummy object should have `_is_accelerate_prepared` set to `True`" , ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Model is missing `_is_accelerator_prepared` or is set to `False`" , ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Optimizer is missing `_is_accelerator_prepared` or is set to `False`" , ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Scheduler is missing `_is_accelerator_prepared` or is set to `False`" , ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Train Dataloader is missing `_is_accelerator_prepared` or is set to `False`" , ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Valid Dataloader is missing `_is_accelerator_prepared` or is set to `False`" , ) @slow @require_bnb def __lowerCamelCase ( self ): """simple docstring""" from transformers import AutoModelForCausalLM SCREAMING_SNAKE_CASE_ : Optional[int] = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , load_in_abit=lowercase__ , device_map={"": 0} , ) SCREAMING_SNAKE_CASE_ : Optional[int] = Accelerator() # This should work SCREAMING_SNAKE_CASE_ : List[Any] = accelerator.prepare(lowercase__ ) @slow @require_bnb def __lowerCamelCase ( self ): """simple docstring""" from transformers import AutoModelForCausalLM SCREAMING_SNAKE_CASE_ : Optional[Any] = Accelerator() with init_empty_weights(): SCREAMING_SNAKE_CASE_ : Tuple = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , ) model.tie_weights() SCREAMING_SNAKE_CASE_ : Optional[Any] = infer_auto_device_map(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = "cpu" SCREAMING_SNAKE_CASE_ : Tuple = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , device_map=lowercase__ , load_in_abit=lowercase__ , llm_inta_enable_fpaa_cpu_offload=lowercase__ ) # This should not work and get value error with self.assertRaises(lowercase__ ): SCREAMING_SNAKE_CASE_ : str = accelerator.prepare(lowercase__ ) @slow @require_bnb @require_multi_gpu def __lowerCamelCase ( self ): """simple docstring""" from transformers import AutoModelForCausalLM SCREAMING_SNAKE_CASE_ : str = {"distributed_type": DistributedType.MULTI_GPU} with init_empty_weights(): SCREAMING_SNAKE_CASE_ : Optional[int] = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , ) model.tie_weights() SCREAMING_SNAKE_CASE_ : str = infer_auto_device_map(lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = 1 SCREAMING_SNAKE_CASE_ : str = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , load_in_abit=lowercase__ , device_map=lowercase__ , ) SCREAMING_SNAKE_CASE_ : Any = Accelerator() # This should not work and get value error with self.assertRaises(lowercase__ ): SCREAMING_SNAKE_CASE_ : Tuple = accelerator.prepare(lowercase__ ) PartialState._reset_state() @slow @require_bnb @require_multi_gpu def __lowerCamelCase ( self ): """simple docstring""" from transformers import AutoModelForCausalLM with init_empty_weights(): SCREAMING_SNAKE_CASE_ : Optional[int] = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , ) SCREAMING_SNAKE_CASE_ : Optional[Any] = infer_auto_device_map(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = 1 SCREAMING_SNAKE_CASE_ : str = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , load_in_abit=lowercase__ , device_map=lowercase__ , ) SCREAMING_SNAKE_CASE_ : Any = Accelerator() # This should work SCREAMING_SNAKE_CASE_ : Optional[int] = accelerator.prepare(lowercase__ ) @require_cuda def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = torch.nn.Linear(10 , 10 ) SCREAMING_SNAKE_CASE_ : Optional[int] = torch.optim.SGD(model.parameters() , lr=0.01 ) SCREAMING_SNAKE_CASE_ : Tuple = Accelerator(cpu=lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = accelerator.prepare(lowercase__ )
68
1
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : int ) -> List[Any]: """simple docstring""" if n == 0: return 1 elif n % 2 == 1: return (binary_exponentiation(SCREAMING_SNAKE_CASE_ , n - 1 , SCREAMING_SNAKE_CASE_ ) * a) % mod else: SCREAMING_SNAKE_CASE_ : List[str] = binary_exponentiation(SCREAMING_SNAKE_CASE_ , n / 2 , SCREAMING_SNAKE_CASE_ ) return (b * b) % mod # a prime number snake_case_ = 7_0_1 snake_case_ = 1_0_0_0_0_0_0_0_0_0 snake_case_ = 1_0 # using binary exponentiation function, O(log(p)): print((a / b) % p == (a * binary_exponentiation(b, p - 2, p)) % p) print((a / b) % p == (a * b ** (p - 2)) % p)
68
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging snake_case_ = logging.get_logger(__name__) snake_case_ = { 'facebook/xmod-base': 'https://huggingface.co/facebook/xmod-base/resolve/main/config.json', 'facebook/xmod-large-prenorm': 'https://huggingface.co/facebook/xmod-large-prenorm/resolve/main/config.json', 'facebook/xmod-base-13-125k': 'https://huggingface.co/facebook/xmod-base-13-125k/resolve/main/config.json', 'facebook/xmod-base-30-125k': 'https://huggingface.co/facebook/xmod-base-30-125k/resolve/main/config.json', 'facebook/xmod-base-30-195k': 'https://huggingface.co/facebook/xmod-base-30-195k/resolve/main/config.json', 'facebook/xmod-base-60-125k': 'https://huggingface.co/facebook/xmod-base-60-125k/resolve/main/config.json', 'facebook/xmod-base-60-265k': 'https://huggingface.co/facebook/xmod-base-60-265k/resolve/main/config.json', 'facebook/xmod-base-75-125k': 'https://huggingface.co/facebook/xmod-base-75-125k/resolve/main/config.json', 'facebook/xmod-base-75-269k': 'https://huggingface.co/facebook/xmod-base-75-269k/resolve/main/config.json', } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = "xmod" def __init__( self , lowercase__=3_0522 , lowercase__=768 , lowercase__=12 , lowercase__=12 , lowercase__=3072 , lowercase__="gelu" , lowercase__=0.1 , lowercase__=0.1 , lowercase__=512 , lowercase__=2 , lowercase__=0.02 , lowercase__=1e-12 , lowercase__=1 , lowercase__=0 , lowercase__=2 , lowercase__="absolute" , lowercase__=True , lowercase__=None , lowercase__=False , lowercase__=2 , lowercase__=False , lowercase__=True , lowercase__=True , lowercase__=("en_XX",) , lowercase__=None , **lowercase__ , ): """simple docstring""" super().__init__(pad_token_id=lowercase__ , bos_token_id=lowercase__ , eos_token_id=lowercase__ , **lowercase__ ) SCREAMING_SNAKE_CASE_ : Tuple = vocab_size SCREAMING_SNAKE_CASE_ : Optional[Any] = hidden_size SCREAMING_SNAKE_CASE_ : Tuple = num_hidden_layers SCREAMING_SNAKE_CASE_ : Optional[int] = num_attention_heads SCREAMING_SNAKE_CASE_ : List[str] = hidden_act SCREAMING_SNAKE_CASE_ : Optional[int] = intermediate_size SCREAMING_SNAKE_CASE_ : Tuple = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : int = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE_ : Dict = type_vocab_size SCREAMING_SNAKE_CASE_ : str = initializer_range SCREAMING_SNAKE_CASE_ : List[str] = layer_norm_eps SCREAMING_SNAKE_CASE_ : Tuple = position_embedding_type SCREAMING_SNAKE_CASE_ : str = use_cache SCREAMING_SNAKE_CASE_ : Optional[int] = classifier_dropout SCREAMING_SNAKE_CASE_ : int = pre_norm SCREAMING_SNAKE_CASE_ : Optional[int] = adapter_reduction_factor SCREAMING_SNAKE_CASE_ : List[str] = adapter_layer_norm SCREAMING_SNAKE_CASE_ : List[str] = adapter_reuse_layer_norm SCREAMING_SNAKE_CASE_ : int = ln_before_adapter SCREAMING_SNAKE_CASE_ : List[Any] = list(lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = default_language class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): @property def __lowerCamelCase ( self ): """simple docstring""" if self.task == "multiple-choice": SCREAMING_SNAKE_CASE_ : Tuple = {0: "batch", 1: "choice", 2: "sequence"} else: SCREAMING_SNAKE_CASE_ : Optional[int] = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
68
1
'''simple docstring''' import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import YolosConfig, YolosForObjectDetection, YolosImageProcessor from transformers.utils import logging logging.set_verbosity_info() snake_case_ = logging.get_logger(__name__) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str ) -> YolosConfig: """simple docstring""" SCREAMING_SNAKE_CASE_ : str = YolosConfig() # size of the architecture if "yolos_ti" in yolos_name: SCREAMING_SNAKE_CASE_ : str = 1_9_2 SCREAMING_SNAKE_CASE_ : Optional[Any] = 7_6_8 SCREAMING_SNAKE_CASE_ : Optional[Any] = 1_2 SCREAMING_SNAKE_CASE_ : Any = 3 SCREAMING_SNAKE_CASE_ : int = [8_0_0, 1_3_3_3] SCREAMING_SNAKE_CASE_ : Tuple = False elif yolos_name == "yolos_s_dWr": SCREAMING_SNAKE_CASE_ : Dict = 3_3_0 SCREAMING_SNAKE_CASE_ : List[Any] = 1_4 SCREAMING_SNAKE_CASE_ : int = 6 SCREAMING_SNAKE_CASE_ : str = 1_3_2_0 elif "yolos_s" in yolos_name: SCREAMING_SNAKE_CASE_ : Union[str, Any] = 3_8_4 SCREAMING_SNAKE_CASE_ : str = 1_5_3_6 SCREAMING_SNAKE_CASE_ : List[str] = 1_2 SCREAMING_SNAKE_CASE_ : Optional[Any] = 6 elif "yolos_b" in yolos_name: SCREAMING_SNAKE_CASE_ : Union[str, Any] = [8_0_0, 1_3_4_4] SCREAMING_SNAKE_CASE_ : List[Any] = 9_1 SCREAMING_SNAKE_CASE_ : Dict = "huggingface/label-files" SCREAMING_SNAKE_CASE_ : str = "coco-detection-id2label.json" SCREAMING_SNAKE_CASE_ : Any = json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , repo_type="dataset" ) , "r" ) ) SCREAMING_SNAKE_CASE_ : int = {int(SCREAMING_SNAKE_CASE_ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE_ : Optional[Any] = idalabel SCREAMING_SNAKE_CASE_ : Dict = {v: k for k, v in idalabel.items()} return config def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : dict , SCREAMING_SNAKE_CASE_ : YolosConfig , SCREAMING_SNAKE_CASE_ : bool = False ) -> Optional[Any]: """simple docstring""" for i in range(config.num_hidden_layers ): # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) SCREAMING_SNAKE_CASE_ : Any = state_dict.pop(F"blocks.{i}.attn.qkv.weight" ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = state_dict.pop(F"blocks.{i}.attn.qkv.bias" ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE_ : Any = in_proj_weight[: config.hidden_size, :] SCREAMING_SNAKE_CASE_ : Union[str, Any] = in_proj_bias[: config.hidden_size] SCREAMING_SNAKE_CASE_ : Union[str, Any] = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] SCREAMING_SNAKE_CASE_ : Any = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] SCREAMING_SNAKE_CASE_ : int = in_proj_weight[-config.hidden_size :, :] SCREAMING_SNAKE_CASE_ : List[Any] = in_proj_bias[-config.hidden_size :] def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str ) -> str: """simple docstring""" if "backbone" in name: SCREAMING_SNAKE_CASE_ : Optional[int] = name.replace("backbone" , "vit" ) if "cls_token" in name: SCREAMING_SNAKE_CASE_ : str = name.replace("cls_token" , "embeddings.cls_token" ) if "det_token" in name: SCREAMING_SNAKE_CASE_ : str = name.replace("det_token" , "embeddings.detection_tokens" ) if "mid_pos_embed" in name: SCREAMING_SNAKE_CASE_ : List[str] = name.replace("mid_pos_embed" , "encoder.mid_position_embeddings" ) if "pos_embed" in name: SCREAMING_SNAKE_CASE_ : str = name.replace("pos_embed" , "embeddings.position_embeddings" ) if "patch_embed.proj" in name: SCREAMING_SNAKE_CASE_ : Optional[Any] = name.replace("patch_embed.proj" , "embeddings.patch_embeddings.projection" ) if "blocks" in name: SCREAMING_SNAKE_CASE_ : Dict = name.replace("blocks" , "encoder.layer" ) if "attn.proj" in name: SCREAMING_SNAKE_CASE_ : Tuple = name.replace("attn.proj" , "attention.output.dense" ) if "attn" in name: SCREAMING_SNAKE_CASE_ : str = name.replace("attn" , "attention.self" ) if "norm1" in name: SCREAMING_SNAKE_CASE_ : Any = name.replace("norm1" , "layernorm_before" ) if "norm2" in name: SCREAMING_SNAKE_CASE_ : Optional[int] = name.replace("norm2" , "layernorm_after" ) if "mlp.fc1" in name: SCREAMING_SNAKE_CASE_ : str = name.replace("mlp.fc1" , "intermediate.dense" ) if "mlp.fc2" in name: SCREAMING_SNAKE_CASE_ : Dict = name.replace("mlp.fc2" , "output.dense" ) if "class_embed" in name: SCREAMING_SNAKE_CASE_ : int = name.replace("class_embed" , "class_labels_classifier" ) if "bbox_embed" in name: SCREAMING_SNAKE_CASE_ : Any = name.replace("bbox_embed" , "bbox_predictor" ) if "vit.norm" in name: SCREAMING_SNAKE_CASE_ : Any = name.replace("vit.norm" , "vit.layernorm" ) return name def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : dict , SCREAMING_SNAKE_CASE_ : YolosForObjectDetection ) -> dict: """simple docstring""" for key in orig_state_dict.copy().keys(): SCREAMING_SNAKE_CASE_ : List[Any] = orig_state_dict.pop(SCREAMING_SNAKE_CASE_ ) if "qkv" in key: SCREAMING_SNAKE_CASE_ : str = key.split("." ) SCREAMING_SNAKE_CASE_ : str = int(key_split[2] ) SCREAMING_SNAKE_CASE_ : Dict = model.vit.encoder.layer[layer_num].attention.attention.all_head_size if "weight" in key: SCREAMING_SNAKE_CASE_ : Dict = val[:dim, :] SCREAMING_SNAKE_CASE_ : Optional[int] = val[ dim : dim * 2, : ] SCREAMING_SNAKE_CASE_ : List[Any] = val[-dim:, :] else: SCREAMING_SNAKE_CASE_ : str = val[:dim] SCREAMING_SNAKE_CASE_ : Optional[Any] = val[dim : dim * 2] SCREAMING_SNAKE_CASE_ : int = val[-dim:] else: SCREAMING_SNAKE_CASE_ : Dict = val return orig_state_dict def __lowerCamelCase ( ) -> torch.Tensor: """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = "http://images.cocodataset.org/val2017/000000039769.jpg" SCREAMING_SNAKE_CASE_ : List[Any] = Image.open(requests.get(SCREAMING_SNAKE_CASE_ , stream=SCREAMING_SNAKE_CASE_ ).raw ) return im @torch.no_grad() def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : bool = False ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : str = get_yolos_config(SCREAMING_SNAKE_CASE_ ) # load original state_dict SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.load(SCREAMING_SNAKE_CASE_ , map_location="cpu" )["model"] # load 🤗 model SCREAMING_SNAKE_CASE_ : List[Any] = YolosForObjectDetection(SCREAMING_SNAKE_CASE_ ) model.eval() SCREAMING_SNAKE_CASE_ : int = convert_state_dict(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) model.load_state_dict(SCREAMING_SNAKE_CASE_ ) # Check outputs on an image, prepared by YolosImageProcessor SCREAMING_SNAKE_CASE_ : int = 8_0_0 if yolos_name != "yolos_ti" else 5_1_2 SCREAMING_SNAKE_CASE_ : Dict = YolosImageProcessor(format="coco_detection" , size=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = image_processor(images=prepare_img() , return_tensors="pt" ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = model(**SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : List[str] = outputs.logits, outputs.pred_boxes SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[int] = None, None if yolos_name == "yolos_ti": SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.tensor( [[-39.5022, -11.9820, -17.6888], [-29.9574, -9.9769, -17.7691], [-42.3281, -20.7200, -30.6294]] ) SCREAMING_SNAKE_CASE_ : Optional[Any] = torch.tensor( [[0.4021, 0.0836, 0.7979], [0.0184, 0.2609, 0.0364], [0.1781, 0.2004, 0.2095]] ) elif yolos_name == "yolos_s_200_pre": SCREAMING_SNAKE_CASE_ : List[Any] = torch.tensor( [[-24.0248, -10.3024, -14.8290], [-42.0392, -16.8200, -27.4334], [-27.2743, -11.8154, -18.7148]] ) SCREAMING_SNAKE_CASE_ : str = torch.tensor( [[0.2559, 0.5455, 0.4706], [0.2989, 0.7279, 0.1875], [0.7732, 0.4017, 0.4462]] ) elif yolos_name == "yolos_s_300_pre": SCREAMING_SNAKE_CASE_ : List[Any] = torch.tensor( [[-36.2220, -14.4385, -23.5457], [-35.6970, -14.7583, -21.3935], [-31.5939, -13.6042, -16.8049]] ) SCREAMING_SNAKE_CASE_ : Optional[Any] = torch.tensor( [[0.7614, 0.2316, 0.4728], [0.7168, 0.4495, 0.3855], [0.4996, 0.1466, 0.9996]] ) elif yolos_name == "yolos_s_dWr": SCREAMING_SNAKE_CASE_ : List[Any] = torch.tensor( [[-42.8668, -24.1049, -41.1690], [-34.7456, -14.1274, -24.9194], [-33.7898, -12.1946, -25.6495]] ) SCREAMING_SNAKE_CASE_ : Tuple = torch.tensor( [[0.5587, 0.2773, 0.0605], [0.5004, 0.3014, 0.9994], [0.4999, 0.1548, 0.9994]] ) elif yolos_name == "yolos_base": SCREAMING_SNAKE_CASE_ : List[str] = torch.tensor( [[-40.6064, -24.3084, -32.6447], [-55.1990, -30.7719, -35.5877], [-51.4311, -33.3507, -35.6462]] ) SCREAMING_SNAKE_CASE_ : List[Any] = torch.tensor( [[0.5555, 0.2794, 0.0655], [0.9049, 0.2664, 0.1894], [0.9183, 0.1984, 0.1635]] ) else: raise ValueError(F"Unknown yolos_name: {yolos_name}" ) assert torch.allclose(logits[0, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=1E-4 ) assert torch.allclose(pred_boxes[0, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=1E-4 ) Path(SCREAMING_SNAKE_CASE_ ).mkdir(exist_ok=SCREAMING_SNAKE_CASE_ ) print(F"Saving model {yolos_name} to {pytorch_dump_folder_path}" ) model.save_pretrained(SCREAMING_SNAKE_CASE_ ) print(F"Saving image processor to {pytorch_dump_folder_path}" ) image_processor.save_pretrained(SCREAMING_SNAKE_CASE_ ) if push_to_hub: SCREAMING_SNAKE_CASE_ : List[str] = { "yolos_ti": "yolos-tiny", "yolos_s_200_pre": "yolos-small", "yolos_s_300_pre": "yolos-small-300", "yolos_s_dWr": "yolos-small-dwr", "yolos_base": "yolos-base", } print("Pushing to the hub..." ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = model_mapping[yolos_name] image_processor.push_to_hub(SCREAMING_SNAKE_CASE_ , organization="hustvl" ) model.push_to_hub(SCREAMING_SNAKE_CASE_ , organization="hustvl" ) if __name__ == "__main__": snake_case_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--yolos_name', default='yolos_s_200_pre', type=str, help=( 'Name of the YOLOS model you\'d like to convert. Should be one of \'yolos_ti\', \'yolos_s_200_pre\',' ' \'yolos_s_300_pre\', \'yolos_s_dWr\', \'yolos_base\'.' ), ) parser.add_argument( '--checkpoint_path', default=None, type=str, help='Path to the original state dict (.pth file).' ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.' ) snake_case_ = parser.parse_args() convert_yolos_checkpoint(args.yolos_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub)
68
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int ) -> int: """simple docstring""" return int((input_a, input_a).count(1 ) != 0 ) def __lowerCamelCase ( ) -> None: """simple docstring""" assert or_gate(0 , 0 ) == 0 assert or_gate(0 , 1 ) == 1 assert or_gate(1 , 0 ) == 1 assert or_gate(1 , 1 ) == 1 if __name__ == "__main__": print(or_gate(0, 1)) print(or_gate(1, 0)) print(or_gate(0, 0)) print(or_gate(1, 1))
68
1
'''simple docstring''' from .imports import is_rich_available if is_rich_available(): from rich.traceback import install install(show_locals=False) else: raise ModuleNotFoundError('To use the rich extension, install rich with `pip install rich`')
68
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..bit import BitConfig snake_case_ = logging.get_logger(__name__) snake_case_ = { 'Intel/dpt-large': 'https://huggingface.co/Intel/dpt-large/resolve/main/config.json', # See all DPT models at https://huggingface.co/models?filter=dpt } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = "dpt" def __init__( self , lowercase__=768 , lowercase__=12 , lowercase__=12 , lowercase__=3072 , lowercase__="gelu" , lowercase__=0.0 , lowercase__=0.0 , lowercase__=0.02 , lowercase__=1e-12 , lowercase__=384 , lowercase__=16 , lowercase__=3 , lowercase__=False , lowercase__=True , lowercase__=[2, 5, 8, 11] , lowercase__="project" , lowercase__=[4, 2, 1, 0.5] , lowercase__=[96, 192, 384, 768] , lowercase__=256 , lowercase__=-1 , lowercase__=False , lowercase__=True , lowercase__=0.4 , lowercase__=255 , lowercase__=0.1 , lowercase__=[1, 1024, 24, 24] , lowercase__=[0, 1] , lowercase__=None , **lowercase__ , ): """simple docstring""" super().__init__(**lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = hidden_size SCREAMING_SNAKE_CASE_ : Union[str, Any] = is_hybrid if self.is_hybrid: if backbone_config is None: logger.info("Initializing the config with a `BiT` backbone." ) SCREAMING_SNAKE_CASE_ : Tuple = { "global_padding": "same", "layer_type": "bottleneck", "depths": [3, 4, 9], "out_features": ["stage1", "stage2", "stage3"], "embedding_dynamic_padding": True, } SCREAMING_SNAKE_CASE_ : Union[str, Any] = BitConfig(**lowercase__ ) elif isinstance(lowercase__ , lowercase__ ): logger.info("Initializing the config with a `BiT` backbone." ) SCREAMING_SNAKE_CASE_ : Dict = BitConfig(**lowercase__ ) elif isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE_ : Optional[int] = backbone_config else: raise ValueError( F"backbone_config must be a dictionary or a `PretrainedConfig`, got {backbone_config.__class__}." ) SCREAMING_SNAKE_CASE_ : List[Any] = backbone_featmap_shape SCREAMING_SNAKE_CASE_ : Union[str, Any] = neck_ignore_stages if readout_type != "project": raise ValueError("Readout type must be 'project' when using `DPT-hybrid` mode." ) else: SCREAMING_SNAKE_CASE_ : Optional[Any] = None SCREAMING_SNAKE_CASE_ : int = None SCREAMING_SNAKE_CASE_ : List[Any] = [] SCREAMING_SNAKE_CASE_ : int = num_hidden_layers SCREAMING_SNAKE_CASE_ : Union[str, Any] = num_attention_heads SCREAMING_SNAKE_CASE_ : Tuple = intermediate_size SCREAMING_SNAKE_CASE_ : Optional[int] = hidden_act SCREAMING_SNAKE_CASE_ : Dict = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : str = initializer_range SCREAMING_SNAKE_CASE_ : List[Any] = layer_norm_eps SCREAMING_SNAKE_CASE_ : Any = image_size SCREAMING_SNAKE_CASE_ : Union[str, Any] = patch_size SCREAMING_SNAKE_CASE_ : Union[str, Any] = num_channels SCREAMING_SNAKE_CASE_ : Union[str, Any] = qkv_bias SCREAMING_SNAKE_CASE_ : Optional[Any] = backbone_out_indices if readout_type not in ["ignore", "add", "project"]: raise ValueError("Readout_type must be one of ['ignore', 'add', 'project']" ) SCREAMING_SNAKE_CASE_ : Any = readout_type SCREAMING_SNAKE_CASE_ : Optional[Any] = reassemble_factors SCREAMING_SNAKE_CASE_ : str = neck_hidden_sizes SCREAMING_SNAKE_CASE_ : Union[str, Any] = fusion_hidden_size SCREAMING_SNAKE_CASE_ : Any = head_in_index SCREAMING_SNAKE_CASE_ : str = use_batch_norm_in_fusion_residual # auxiliary head attributes (semantic segmentation) SCREAMING_SNAKE_CASE_ : List[Any] = use_auxiliary_head SCREAMING_SNAKE_CASE_ : int = auxiliary_loss_weight SCREAMING_SNAKE_CASE_ : Union[str, Any] = semantic_loss_ignore_index SCREAMING_SNAKE_CASE_ : Any = semantic_classifier_dropout def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = copy.deepcopy(self.__dict__ ) if output["backbone_config"] is not None: SCREAMING_SNAKE_CASE_ : List[str] = self.backbone_config.to_dict() SCREAMING_SNAKE_CASE_ : Optional[int] = self.__class__.model_type return output
68
1
'''simple docstring''' snake_case_ = { 'Pillow': 'Pillow<10.0.0', 'accelerate': 'accelerate>=0.20.3', 'av': 'av==9.2.0', 'beautifulsoup4': 'beautifulsoup4', 'black': 'black~=23.1', 'codecarbon': 'codecarbon==1.2.0', 'cookiecutter': 'cookiecutter==1.7.3', 'dataclasses': 'dataclasses', 'datasets': 'datasets!=2.5.0', 'decord': 'decord==0.6.0', 'deepspeed': 'deepspeed>=0.9.3', 'diffusers': 'diffusers', 'dill': 'dill<0.3.5', 'evaluate': 'evaluate>=0.2.0', 'fairscale': 'fairscale>0.3', 'faiss-cpu': 'faiss-cpu', 'fastapi': 'fastapi', 'filelock': 'filelock', 'flax': 'flax>=0.4.1,<=0.7.0', 'ftfy': 'ftfy', 'fugashi': 'fugashi>=1.0', 'GitPython': 'GitPython<3.1.19', 'hf-doc-builder': 'hf-doc-builder>=0.3.0', 'huggingface-hub': 'huggingface-hub>=0.14.1,<1.0', 'importlib_metadata': 'importlib_metadata', 'ipadic': 'ipadic>=1.0.0,<2.0', 'isort': 'isort>=5.5.4', 'jax': 'jax>=0.2.8,!=0.3.2,<=0.4.13', 'jaxlib': 'jaxlib>=0.1.65,<=0.4.13', 'jieba': 'jieba', 'kenlm': 'kenlm', 'keras-nlp': 'keras-nlp>=0.3.1', 'librosa': 'librosa', 'nltk': 'nltk', 'natten': 'natten>=0.14.6', 'numpy': 'numpy>=1.17', 'onnxconverter-common': 'onnxconverter-common', 'onnxruntime-tools': 'onnxruntime-tools>=1.4.2', 'onnxruntime': 'onnxruntime>=1.4.0', 'opencv-python': 'opencv-python', 'optuna': 'optuna', 'optax': 'optax>=0.0.8,<=0.1.4', 'packaging': 'packaging>=20.0', 'parameterized': 'parameterized', 'phonemizer': 'phonemizer', 'protobuf': 'protobuf', 'psutil': 'psutil', 'pyyaml': 'pyyaml>=5.1', 'pydantic': 'pydantic<2', 'pytest': 'pytest>=7.2.0', 'pytest-timeout': 'pytest-timeout', 'pytest-xdist': 'pytest-xdist', 'python': 'python>=3.8.0', 'ray[tune]': 'ray[tune]', 'regex': 'regex!=2019.12.17', 'requests': 'requests', 'rhoknp': 'rhoknp>=1.1.0,<1.3.1', 'rjieba': 'rjieba', 'rouge-score': 'rouge-score!=0.0.7,!=0.0.8,!=0.1,!=0.1.1', 'ruff': 'ruff>=0.0.241,<=0.0.259', 'sacrebleu': 'sacrebleu>=1.4.12,<2.0.0', 'sacremoses': 'sacremoses', 'safetensors': 'safetensors>=0.3.1', 'sagemaker': 'sagemaker>=2.31.0', 'scikit-learn': 'scikit-learn', 'sentencepiece': 'sentencepiece>=0.1.91,!=0.1.92', 'sigopt': 'sigopt', 'starlette': 'starlette', 'sudachipy': 'sudachipy>=0.6.6', 'sudachidict_core': 'sudachidict_core>=20220729', 'tensorflow-cpu': 'tensorflow-cpu>=2.6,<2.14', 'tensorflow': 'tensorflow>=2.6,<2.14', 'tensorflow-text': 'tensorflow-text<2.14', 'tf2onnx': 'tf2onnx', 'timeout-decorator': 'timeout-decorator', 'timm': 'timm', 'tokenizers': 'tokenizers>=0.11.1,!=0.11.3,<0.14', 'torch': 'torch>=1.9,!=1.12.0', 'torchaudio': 'torchaudio', 'torchvision': 'torchvision', 'pyctcdecode': 'pyctcdecode>=0.4.0', 'tqdm': 'tqdm>=4.27', 'unidic': 'unidic>=1.0.2', 'unidic_lite': 'unidic_lite>=1.0.7', 'urllib3': 'urllib3<2.0.0', 'uvicorn': 'uvicorn', }
68
'''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 if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ChineseCLIPImageProcessor class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __init__( self , lowercase__ , lowercase__=7 , lowercase__=3 , lowercase__=18 , lowercase__=30 , lowercase__=400 , lowercase__=True , lowercase__=None , lowercase__=True , lowercase__=None , lowercase__=True , lowercase__=[0.48145466, 0.4578275, 0.40821073] , lowercase__=[0.26862954, 0.26130258, 0.27577711] , lowercase__=True , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = size if size is not None else {"height": 224, "width": 224} SCREAMING_SNAKE_CASE_ : Optional[Any] = crop_size if crop_size is not None else {"height": 18, "width": 18} SCREAMING_SNAKE_CASE_ : str = parent SCREAMING_SNAKE_CASE_ : List[Any] = batch_size SCREAMING_SNAKE_CASE_ : Dict = num_channels SCREAMING_SNAKE_CASE_ : Any = image_size SCREAMING_SNAKE_CASE_ : Tuple = min_resolution SCREAMING_SNAKE_CASE_ : Optional[Any] = max_resolution SCREAMING_SNAKE_CASE_ : Tuple = do_resize SCREAMING_SNAKE_CASE_ : List[str] = size SCREAMING_SNAKE_CASE_ : str = do_center_crop SCREAMING_SNAKE_CASE_ : List[str] = crop_size SCREAMING_SNAKE_CASE_ : int = do_normalize SCREAMING_SNAKE_CASE_ : Optional[int] = image_mean SCREAMING_SNAKE_CASE_ : Dict = image_std SCREAMING_SNAKE_CASE_ : List[Any] = do_convert_rgb def __lowerCamelCase ( self ): """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_convert_rgb": self.do_convert_rgb, } def __lowerCamelCase ( self , lowercase__=False , lowercase__=False , lowercase__=False ): """simple docstring""" assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time" if equal_resolution: SCREAMING_SNAKE_CASE_ : Optional[int] = [] for i in range(self.batch_size ): image_inputs.append( np.random.randint( 255 , size=(self.num_channels, self.max_resolution, self.max_resolution) , dtype=np.uinta ) ) else: SCREAMING_SNAKE_CASE_ : str = [] for i in range(self.batch_size ): SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[Any] = np.random.choice(np.arange(self.min_resolution , self.max_resolution ) , 2 ) image_inputs.append(np.random.randint(255 , size=(self.num_channels, width, height) , dtype=np.uinta ) ) if not numpify and not torchify: # PIL expects the channel dimension as last dimension SCREAMING_SNAKE_CASE_ : str = [Image.fromarray(np.moveaxis(lowercase__ , 0 , -1 ) ) for x in image_inputs] if torchify: SCREAMING_SNAKE_CASE_ : List[str] = [torch.from_numpy(lowercase__ ) for x in image_inputs] return image_inputs @require_torch @require_vision class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,unittest.TestCase ): _A = ChineseCLIPImageProcessor if is_vision_available() else None def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = ChineseCLIPImageProcessingTester(self , do_center_crop=lowercase__ ) @property def __lowerCamelCase ( self ): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowercase__ , "do_resize" ) ) self.assertTrue(hasattr(lowercase__ , "size" ) ) self.assertTrue(hasattr(lowercase__ , "do_center_crop" ) ) self.assertTrue(hasattr(lowercase__ , "center_crop" ) ) self.assertTrue(hasattr(lowercase__ , "do_normalize" ) ) self.assertTrue(hasattr(lowercase__ , "image_mean" ) ) self.assertTrue(hasattr(lowercase__ , "image_std" ) ) self.assertTrue(hasattr(lowercase__ , "do_convert_rgb" ) ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"height": 224, "width": 224} ) self.assertEqual(image_processor.crop_size , {"height": 18, "width": 18} ) SCREAMING_SNAKE_CASE_ : str = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 ) self.assertEqual(image_processor.size , {"shortest_edge": 42} ) self.assertEqual(image_processor.crop_size , {"height": 84, "width": 84} ) def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE_ : Tuple = self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__ ) for image in image_inputs: self.assertIsInstance(lowercase__ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE_ : Dict = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE_ : Optional[int] = image_processing(lowercase__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__ , numpify=lowercase__ ) for image in image_inputs: self.assertIsInstance(lowercase__ , np.ndarray ) # Test not batched input SCREAMING_SNAKE_CASE_ : Optional[int] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE_ : List[str] = image_processing(lowercase__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors SCREAMING_SNAKE_CASE_ : List[str] = self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__ , torchify=lowercase__ ) for image in image_inputs: self.assertIsInstance(lowercase__ , torch.Tensor ) # Test not batched input SCREAMING_SNAKE_CASE_ : Union[str, Any] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE_ : int = image_processing(lowercase__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) @require_torch @require_vision class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,unittest.TestCase ): _A = ChineseCLIPImageProcessor if is_vision_available() else None def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int = ChineseCLIPImageProcessingTester(self , num_channels=4 , do_center_crop=lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = 3 @property def __lowerCamelCase ( self ): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowercase__ , "do_resize" ) ) self.assertTrue(hasattr(lowercase__ , "size" ) ) self.assertTrue(hasattr(lowercase__ , "do_center_crop" ) ) self.assertTrue(hasattr(lowercase__ , "center_crop" ) ) self.assertTrue(hasattr(lowercase__ , "do_normalize" ) ) self.assertTrue(hasattr(lowercase__ , "image_mean" ) ) self.assertTrue(hasattr(lowercase__ , "image_std" ) ) self.assertTrue(hasattr(lowercase__ , "do_convert_rgb" ) ) def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE_ : Optional[int] = self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__ ) for image in image_inputs: self.assertIsInstance(lowercase__ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE_ : Optional[Any] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE_ : List[str] = image_processing(lowercase__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , )
68
1
'''simple docstring''' import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DPMSolverMultistepScheduler, TextToVideoSDPipeline, UNetaDConditionModel, ) from diffusers.utils import is_xformers_available, load_numpy, skip_mps, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,unittest.TestCase ): _A = TextToVideoSDPipeline _A = TEXT_TO_IMAGE_PARAMS _A = TEXT_TO_IMAGE_BATCH_PARAMS # No `output_type`. _A = frozenset( [ "num_inference_steps", "generator", "latents", "return_dict", "callback", "callback_steps", ] ) def __lowerCamelCase ( self ): """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ : str = UNetaDConditionModel( block_out_channels=(32, 64, 64, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "DownBlock3D") , up_block_types=("UpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D") , cross_attention_dim=32 , attention_head_dim=4 , ) SCREAMING_SNAKE_CASE_ : str = DDIMScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule="scaled_linear" , clip_sample=lowercase__ , set_alpha_to_one=lowercase__ , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = 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_ : Optional[Any] = 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=1000 , hidden_act="gelu" , projection_dim=512 , ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = CLIPTextModel(lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) SCREAMING_SNAKE_CASE_ : List[Any] = { "unet": unet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, } return components def __lowerCamelCase ( self , lowercase__ , lowercase__=0 ): """simple docstring""" if str(lowercase__ ).startswith("mps" ): SCREAMING_SNAKE_CASE_ : Any = torch.manual_seed(lowercase__ ) else: SCREAMING_SNAKE_CASE_ : List[Any] = torch.Generator(device=lowercase__ ).manual_seed(lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = { "prompt": "A painting of a squirrel eating a burger", "generator": generator, "num_inference_steps": 2, "guidance_scale": 6.0, "output_type": "pt", } return inputs def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = "cpu" # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE_ : List[Any] = self.get_dummy_components() SCREAMING_SNAKE_CASE_ : Any = TextToVideoSDPipeline(**lowercase__ ) SCREAMING_SNAKE_CASE_ : str = sd_pipe.to(lowercase__ ) sd_pipe.set_progress_bar_config(disable=lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = self.get_dummy_inputs(lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = "np" SCREAMING_SNAKE_CASE_ : str = sd_pipe(**lowercase__ ).frames SCREAMING_SNAKE_CASE_ : Optional[int] = frames[0][-3:, -3:, -1] assert frames[0].shape == (64, 64, 3) SCREAMING_SNAKE_CASE_ : Tuple = np.array([158.0, 160.0, 153.0, 125.0, 100.0, 121.0, 111.0, 93.0, 113.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __lowerCamelCase ( self ): """simple docstring""" self._test_attention_slicing_forward_pass(test_mean_pixel_difference=lowercase__ , expected_max_diff=3e-3 ) @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def __lowerCamelCase ( self ): """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=lowercase__ , expected_max_diff=1e-2 ) @unittest.skip(reason="Batching needs to be properly figured out first for this pipeline." ) def __lowerCamelCase ( self ): """simple docstring""" pass @unittest.skip(reason="Batching needs to be properly figured out first for this pipeline." ) def __lowerCamelCase ( self ): """simple docstring""" pass @unittest.skip(reason="`num_images_per_prompt` argument is not supported for this pipeline." ) def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self ): """simple docstring""" return super().test_progress_bar() @slow @skip_mps class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video.npy" ) SCREAMING_SNAKE_CASE_ : Dict = TextToVideoSDPipeline.from_pretrained("damo-vilab/text-to-video-ms-1.7b" ) SCREAMING_SNAKE_CASE_ : List[str] = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) SCREAMING_SNAKE_CASE_ : Dict = pipe.to("cuda" ) SCREAMING_SNAKE_CASE_ : str = "Spiderman is surfing" SCREAMING_SNAKE_CASE_ : str = torch.Generator(device="cpu" ).manual_seed(0 ) SCREAMING_SNAKE_CASE_ : Any = pipe(lowercase__ , generator=lowercase__ , num_inference_steps=25 , output_type="pt" ).frames SCREAMING_SNAKE_CASE_ : List[Any] = video_frames.cpu().numpy() assert np.abs(expected_video - video ).mean() < 5e-2 def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video_2step.npy" ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = TextToVideoSDPipeline.from_pretrained("damo-vilab/text-to-video-ms-1.7b" ) SCREAMING_SNAKE_CASE_ : Dict = pipe.to("cuda" ) SCREAMING_SNAKE_CASE_ : Any = "Spiderman is surfing" SCREAMING_SNAKE_CASE_ : List[str] = torch.Generator(device="cpu" ).manual_seed(0 ) SCREAMING_SNAKE_CASE_ : int = pipe(lowercase__ , generator=lowercase__ , num_inference_steps=2 , output_type="pt" ).frames SCREAMING_SNAKE_CASE_ : Dict = video_frames.cpu().numpy() assert np.abs(expected_video - video ).mean() < 5e-2
68
'''simple docstring''' from __future__ import annotations def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int ) -> bool: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = str(SCREAMING_SNAKE_CASE_ ) return len(SCREAMING_SNAKE_CASE_ ) == 9 and set(SCREAMING_SNAKE_CASE_ ) == set("123456789" ) def __lowerCamelCase ( ) -> int | None: """simple docstring""" for base_num in range(9_9_9_9 , 4_9_9_9 , -1 ): SCREAMING_SNAKE_CASE_ : int = 1_0_0_0_0_2 * base_num if is_9_pandigital(SCREAMING_SNAKE_CASE_ ): return candidate for base_num in range(3_3_3 , 9_9 , -1 ): SCREAMING_SNAKE_CASE_ : List[str] = 1_0_0_2_0_0_3 * base_num if is_9_pandigital(SCREAMING_SNAKE_CASE_ ): return candidate return None if __name__ == "__main__": print(F'''{solution() = }''')
68
1
'''simple docstring''' import math import sys def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = "" try: with open(SCREAMING_SNAKE_CASE_ , "rb" ) as binary_file: SCREAMING_SNAKE_CASE_ : List[Any] = binary_file.read() for dat in data: SCREAMING_SNAKE_CASE_ : List[str] = F"{dat:08b}" result += curr_byte return result except OSError: print("File not accessible" ) sys.exit() def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = {"0": "0", "1": "1"} SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : List[str] = "", "" SCREAMING_SNAKE_CASE_ : Dict = len(SCREAMING_SNAKE_CASE_ ) for i in range(len(SCREAMING_SNAKE_CASE_ ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue SCREAMING_SNAKE_CASE_ : Optional[int] = lexicon[curr_string] result += last_match_id SCREAMING_SNAKE_CASE_ : int = last_match_id + "0" if math.loga(SCREAMING_SNAKE_CASE_ ).is_integer(): SCREAMING_SNAKE_CASE_ : List[str] = {} for curr_key in list(SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ : str = lexicon.pop(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : int = new_lex SCREAMING_SNAKE_CASE_ : Optional[Any] = last_match_id + "1" index += 1 SCREAMING_SNAKE_CASE_ : List[Any] = "" return result def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : str ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = 8 try: with open(SCREAMING_SNAKE_CASE_ , "wb" ) as opened_file: SCREAMING_SNAKE_CASE_ : List[Any] = [ to_write[i : i + byte_length] for i in range(0 , len(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) ] if len(result_byte_array[-1] ) % byte_length == 0: result_byte_array.append("10000000" ) else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1] ) - 1 ) for elem in result_byte_array[:-1]: opened_file.write(int(SCREAMING_SNAKE_CASE_ , 2 ).to_bytes(1 , byteorder="big" ) ) except OSError: print("File not accessible" ) sys.exit() def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = 0 for letter in data_bits: if letter == "1": break counter += 1 SCREAMING_SNAKE_CASE_ : Dict = data_bits[counter:] SCREAMING_SNAKE_CASE_ : str = data_bits[counter + 1 :] return data_bits def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : str ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = read_file_binary(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : List[Any] = remove_prefix(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : List[Any] = decompress_data(SCREAMING_SNAKE_CASE_ ) write_file_binary(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
68
'''simple docstring''' from typing import Optional import pyspark from .. import Features, NamedSplit from ..download import DownloadMode from ..packaged_modules.spark.spark import Spark from .abc import AbstractDatasetReader class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): def __init__( self , lowercase__ , lowercase__ = None , lowercase__ = None , lowercase__ = True , lowercase__ = None , lowercase__ = False , lowercase__ = None , lowercase__ = True , lowercase__ = "arrow" , **lowercase__ , ): """simple docstring""" super().__init__( split=lowercase__ , features=lowercase__ , cache_dir=lowercase__ , keep_in_memory=lowercase__ , streaming=lowercase__ , **lowercase__ , ) SCREAMING_SNAKE_CASE_ : Any = load_from_cache_file SCREAMING_SNAKE_CASE_ : Optional[int] = file_format SCREAMING_SNAKE_CASE_ : List[Any] = Spark( df=lowercase__ , features=lowercase__ , cache_dir=lowercase__ , working_dir=lowercase__ , **lowercase__ , ) def __lowerCamelCase ( self ): """simple docstring""" if self.streaming: return self.builder.as_streaming_dataset(split=self.split ) SCREAMING_SNAKE_CASE_ : Optional[int] = None if self._load_from_cache_file else DownloadMode.FORCE_REDOWNLOAD self.builder.download_and_prepare( download_mode=lowercase__ , file_format=self._file_format , ) return self.builder.as_dataset(split=self.split )
68
1
'''simple docstring''' import argparse import torch from transformers import GPTaLMHeadModel, RobertaForMaskedLM if __name__ == "__main__": snake_case_ = argparse.ArgumentParser( description=( 'Extraction some layers of the full RobertaForMaskedLM or GPT2LMHeadModel for Transfer Learned' ' Distillation' ) ) parser.add_argument('--model_type', default='roberta', choices=['roberta', 'gpt2']) parser.add_argument('--model_name', default='roberta-large', type=str) parser.add_argument('--dump_checkpoint', default='serialization_dir/tf_roberta_048131723.pth', type=str) parser.add_argument('--vocab_transform', action='store_true') snake_case_ = parser.parse_args() if args.model_type == "roberta": snake_case_ = RobertaForMaskedLM.from_pretrained(args.model_name) snake_case_ = 'roberta' elif args.model_type == "gpt2": snake_case_ = GPTaLMHeadModel.from_pretrained(args.model_name) snake_case_ = 'transformer' snake_case_ = model.state_dict() snake_case_ = {} # Embeddings # if args.model_type == "gpt2": for param_name in ["wte.weight", "wpe.weight"]: snake_case_ = state_dict[F'''{prefix}.{param_name}'''] else: for w in ["word_embeddings", "position_embeddings", "token_type_embeddings"]: snake_case_ = F'''{prefix}.embeddings.{w}.weight''' snake_case_ = state_dict[param_name] for w in ["weight", "bias"]: snake_case_ = F'''{prefix}.embeddings.LayerNorm.{w}''' snake_case_ = state_dict[param_name] # Transformer Blocks # snake_case_ = 0 for teacher_idx in [0, 2, 4, 7, 9, 1_1]: if args.model_type == "gpt2": for layer in ["ln_1", "attn.c_attn", "attn.c_proj", "ln_2", "mlp.c_fc", "mlp.c_proj"]: for w in ["weight", "bias"]: snake_case_ = state_dict[ F'''{prefix}.h.{teacher_idx}.{layer}.{w}''' ] snake_case_ = state_dict[F'''{prefix}.h.{teacher_idx}.attn.bias'''] else: for layer in [ "attention.self.query", "attention.self.key", "attention.self.value", "attention.output.dense", "attention.output.LayerNorm", "intermediate.dense", "output.dense", "output.LayerNorm", ]: for w in ["weight", "bias"]: snake_case_ = state_dict[ F'''{prefix}.encoder.layer.{teacher_idx}.{layer}.{w}''' ] std_idx += 1 # Language Modeling Head ###s if args.model_type == "roberta": for layer in ["lm_head.decoder.weight", "lm_head.bias"]: snake_case_ = state_dict[F'''{layer}'''] if args.vocab_transform: for w in ["weight", "bias"]: snake_case_ = state_dict[F'''lm_head.dense.{w}'''] snake_case_ = state_dict[F'''lm_head.layer_norm.{w}'''] elif args.model_type == "gpt2": for w in ["weight", "bias"]: snake_case_ = state_dict[F'''{prefix}.ln_f.{w}'''] snake_case_ = state_dict['lm_head.weight'] print(F'''N layers selected for distillation: {std_idx}''') print(F'''Number of params transferred for distillation: {len(compressed_sd.keys())}''') print(F'''Save transferred checkpoint to {args.dump_checkpoint}.''') torch.save(compressed_sd, args.dump_checkpoint)
68
'''simple docstring''' import re import string import numpy as np import datasets snake_case_ = '\nReturns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list.\n' snake_case_ = '\nArgs:\n predictions: List of predicted texts.\n references: List of reference texts.\n regexes_to_ignore: List, defaults to None. Regex expressions of characters to\n ignore when calculating the exact matches. Note: these regexes are removed\n from the input data before the changes based on the options below (e.g. ignore_case,\n ignore_punctuation, ignore_numbers) are applied.\n ignore_case: Boolean, defaults to False. If true, turns everything\n to lowercase so that capitalization differences are ignored.\n ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\n ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\nReturns:\n exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive.\nExamples:\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results["exact_match"], 1))\n 25.0\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results["exact_match"], 1))\n 50.0\n\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results["exact_match"], 1))\n 75.0\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True)\n >>> print(round(results["exact_match"], 1))\n 100.0\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["The cat sat on the mat.", "Theaters are great.", "It\'s like comparing oranges and apples."]\n >>> preds = ["The cat sat on the mat?", "Theaters are great.", "It\'s like comparing apples and oranges."]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results["exact_match"], 1))\n 33.3\n\n' snake_case_ = '\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION,_KWARGS_DESCRIPTION ) class SCREAMING_SNAKE_CASE__ ( datasets.Metric ): def __lowerCamelCase ( self ): """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Value("string" , id="sequence" ), "references": datasets.Value("string" , id="sequence" ), } ) , reference_urls=[] , ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__=None , lowercase__=False , lowercase__=False , lowercase__=False , ): """simple docstring""" if regexes_to_ignore is not None: for s in regexes_to_ignore: SCREAMING_SNAKE_CASE_ : Optional[Any] = np.array([re.sub(lowercase__ , "" , lowercase__ ) for x in predictions] ) SCREAMING_SNAKE_CASE_ : List[Any] = np.array([re.sub(lowercase__ , "" , lowercase__ ) for x in references] ) else: SCREAMING_SNAKE_CASE_ : int = np.asarray(lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = np.asarray(lowercase__ ) if ignore_case: SCREAMING_SNAKE_CASE_ : Dict = np.char.lower(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = np.char.lower(lowercase__ ) if ignore_punctuation: SCREAMING_SNAKE_CASE_ : Optional[int] = string.punctuation.maketrans("" , "" , string.punctuation ) SCREAMING_SNAKE_CASE_ : int = np.char.translate(lowercase__ , table=lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = np.char.translate(lowercase__ , table=lowercase__ ) if ignore_numbers: SCREAMING_SNAKE_CASE_ : Optional[int] = string.digits.maketrans("" , "" , string.digits ) SCREAMING_SNAKE_CASE_ : Dict = np.char.translate(lowercase__ , table=lowercase__ ) SCREAMING_SNAKE_CASE_ : int = np.char.translate(lowercase__ , table=lowercase__ ) SCREAMING_SNAKE_CASE_ : str = predictions == references return {"exact_match": np.mean(lowercase__ ) * 100}
68
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) snake_case_ = { 'configuration_clip': [ 'CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP', 'CLIPConfig', 'CLIPOnnxConfig', 'CLIPTextConfig', 'CLIPVisionConfig', ], 'processing_clip': ['CLIPProcessor'], 'tokenization_clip': ['CLIPTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ = ['CLIPTokenizerFast'] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ = ['CLIPFeatureExtractor'] snake_case_ = ['CLIPImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ = [ 'CLIP_PRETRAINED_MODEL_ARCHIVE_LIST', 'CLIPModel', 'CLIPPreTrainedModel', 'CLIPTextModel', 'CLIPTextModelWithProjection', 'CLIPVisionModel', 'CLIPVisionModelWithProjection', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ = [ 'TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFCLIPModel', 'TFCLIPPreTrainedModel', 'TFCLIPTextModel', 'TFCLIPVisionModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ = [ 'FlaxCLIPModel', 'FlaxCLIPPreTrainedModel', 'FlaxCLIPTextModel', 'FlaxCLIPTextPreTrainedModel', 'FlaxCLIPVisionModel', 'FlaxCLIPVisionPreTrainedModel', ] if TYPE_CHECKING: from .configuration_clip import ( CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, CLIPConfig, CLIPOnnxConfig, CLIPTextConfig, CLIPVisionConfig, ) from .processing_clip import CLIPProcessor from .tokenization_clip import CLIPTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_clip_fast import CLIPTokenizerFast try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_clip import CLIPFeatureExtractor from .image_processing_clip import CLIPImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_clip import ( CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, CLIPModel, CLIPPreTrainedModel, CLIPTextModel, CLIPTextModelWithProjection, CLIPVisionModel, CLIPVisionModelWithProjection, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_clip import ( TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, TFCLIPModel, TFCLIPPreTrainedModel, TFCLIPTextModel, TFCLIPVisionModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_clip import ( FlaxCLIPModel, FlaxCLIPPreTrainedModel, FlaxCLIPTextModel, FlaxCLIPTextPreTrainedModel, FlaxCLIPVisionModel, FlaxCLIPVisionPreTrainedModel, ) else: import sys snake_case_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
68
'''simple docstring''' import os import re import unicodedata from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import is_torch_available, logging if is_torch_available(): import torch if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation snake_case_ = logging.get_logger(__name__) snake_case_ = {'vocab_file': 'spiece.model'} snake_case_ = { 'vocab_file': { 'AI-Sweden/gpt-sw3-126m': 'https://huggingface.co/AI-Sweden/gpt-sw3-126m/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-350m': 'https://huggingface.co/AI-Sweden/gpt-sw3-350m/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-1.6b': 'https://huggingface.co/AI-Sweden/gpt-sw3-1.6b/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-6.7b': 'https://huggingface.co/AI-Sweden/gpt-sw3-6.7b/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-20b': 'https://huggingface.co/AI-Sweden/gpt-sw3-20b/resolve/main/spiece.model', } } snake_case_ = { 'AI-Sweden/gpt-sw3-126m': 2_0_4_8, 'AI-Sweden/gpt-sw3-350m': 2_0_4_8, 'AI-Sweden/gpt-sw3-1.6b': 2_0_4_8, 'AI-Sweden/gpt-sw3-6.7b': 2_0_4_8, 'AI-Sweden/gpt-sw3-20b': 2_0_4_8, } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = VOCAB_FILES_NAMES _A = PRETRAINED_VOCAB_FILES_MAP _A = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _A = ["input_ids", "attention_mask"] def __init__( self , lowercase__ , lowercase__=False , lowercase__=False , lowercase__=False , lowercase__=None , lowercase__=None , lowercase__=None , lowercase__=None , lowercase__ = None , **lowercase__ , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = {} if sp_model_kwargs is None else sp_model_kwargs SCREAMING_SNAKE_CASE_ : Dict = kwargs.get("name_or_path" ) if name_or_path is None: logger.warning( "name_or_path not provided, will work for all GPTSw3 models except gpt-sw3-7b," " you are testing the model, this can safely be ignored" ) SCREAMING_SNAKE_CASE_ : str = "None" # Default definitions for our 2 tokenizer versions, with None-checks to enable proper testing SCREAMING_SNAKE_CASE_ : List[Any] = "<|endoftext|>" if eos_token is None else eos_token SCREAMING_SNAKE_CASE_ : Dict = "<unk>" if unk_token is None else unk_token if "gpt-sw3-7b" in name_or_path: SCREAMING_SNAKE_CASE_ : Tuple = unk_token if pad_token is None else pad_token SCREAMING_SNAKE_CASE_ : Optional[Any] = eos_token if bos_token is None else bos_token else: SCREAMING_SNAKE_CASE_ : int = "<pad>" if pad_token is None else pad_token SCREAMING_SNAKE_CASE_ : Any = "<s>" if bos_token is None else bos_token super().__init__( do_lower_case=lowercase__ , remove_space=lowercase__ , keep_accents=lowercase__ , bos_token=lowercase__ , eos_token=lowercase__ , unk_token=lowercase__ , pad_token=lowercase__ , sp_model_kwargs=self.sp_model_kwargs , **lowercase__ , ) SCREAMING_SNAKE_CASE_ : Optional[Any] = do_lower_case SCREAMING_SNAKE_CASE_ : Optional[int] = remove_space SCREAMING_SNAKE_CASE_ : int = keep_accents SCREAMING_SNAKE_CASE_ : List[Any] = vocab_file SCREAMING_SNAKE_CASE_ : List[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(lowercase__ ) # Used for whitespace normalization in input texts # fmt : off SCREAMING_SNAKE_CASE_ : int = {" ", " ", " ", " ", " ", " ", " ", " ", " ", " ", "", "„"} # fmt : on # Regular expression to remove non-printing characters (e.g. some unicode control chars) in preprocessing SCREAMING_SNAKE_CASE_ : List[str] = re.compile( F"[{''.join(map(lowercase__ , list(range(0 , 9 ) ) + list(range(11 , 32 ) ) + list(range(127 , 160 ) ) + [160, 173, 8203] ) )}]" ) def __getstate__( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = self.__dict__.copy() SCREAMING_SNAKE_CASE_ : Dict = None return state def __setstate__( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): SCREAMING_SNAKE_CASE_ : Union[str, Any] = {} SCREAMING_SNAKE_CASE_ : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) @property # Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.vocab_size def __lowerCamelCase ( self ): """simple docstring""" return len(self.sp_model ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.non_printing_characters_re.sub("" , lowercase__ ) # Normalize whitespaces SCREAMING_SNAKE_CASE_ : List[str] = "".join([char if char not in self.whitespaces else " " for char in text] ) # NFC Unicode normalization SCREAMING_SNAKE_CASE_ : List[Any] = unicodedata.normalize("NFC" , lowercase__ ) return text def __lowerCamelCase ( self , lowercase__ , **lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = self.preprocess_text(lowercase__ ) return self.sp_model.encode(lowercase__ , out_type=lowercase__ ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" return self.sp_model.PieceToId(lowercase__ ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" return self.sp_model.IdToPiece(lowercase__ ) @staticmethod def __lowerCamelCase ( lowercase__ ): """simple docstring""" return out_string def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = [] SCREAMING_SNAKE_CASE_ : Any = "" SCREAMING_SNAKE_CASE_ : Dict = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: # TODO: Check if this is needed, as it ensures that decode(encode(doc)) != doc by adding extra whitespace in the decoded document if not prev_is_special: out_string += " " out_string += self.sp_model.decode(lowercase__ ) + token SCREAMING_SNAKE_CASE_ : Union[str, Any] = True SCREAMING_SNAKE_CASE_ : int = [] else: current_sub_tokens.append(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = False out_string += self.sp_model.decode(lowercase__ ) return out_string def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = {self.convert_ids_to_tokens(lowercase__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __lowerCamelCase ( self , lowercase__ , lowercase__ = None ): """simple docstring""" if not os.path.isdir(lowercase__ ): logger.error(F"Vocabulary path ({save_directory}) should be a directory" ) return SCREAMING_SNAKE_CASE_ : Any = os.path.join( lowercase__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(lowercase__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , lowercase__ ) elif not os.path.isfile(self.vocab_file ): with open(lowercase__ , "wb" ) as fi: SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.sp_model.serialized_model_proto() fi.write(lowercase__ ) return (out_vocab_file,) def __lowerCamelCase ( self , lowercase__ , lowercase__ = False ): """simple docstring""" if isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE_ : List[Any] = self.preprocess_text(lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = self.sp_model.encode(lowercase__ ) else: SCREAMING_SNAKE_CASE_ : str = [self.preprocess_text(lowercase__ ) for t in text] SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.sp_model.encode(lowercase__ ) if return_tensors is True or return_tensors == "pt": SCREAMING_SNAKE_CASE_ : str = torch.tensor(lowercase__ ) return token_ids def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" return self.sp_model.decode(lowercase__ ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = [F"User: {text}" if is_user else F"Bot: {text}" for is_user, text in conversation.iter_texts()] SCREAMING_SNAKE_CASE_ : List[str] = ( F"{self.eos_token}{self.bos_token}" + F"{self.bos_token}".join(lowercase__ ) + F"{self.bos_token}Bot:" ) return self.encode(text=lowercase__ )
68
1
'''simple docstring''' from typing import List, Optional, Tuple, Union import PIL import torch from torchvision import transforms from diffusers.pipeline_utils import DiffusionPipeline, ImagePipelineOutput from diffusers.schedulers import DDIMScheduler from diffusers.utils import randn_tensor snake_case_ = transforms.Compose( [ transforms.Resize((2_5_6, 2_5_6)), transforms.ToTensor(), transforms.Normalize([0.5], [0.5]), ] ) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Any ) -> List[Any]: """simple docstring""" if isinstance(SCREAMING_SNAKE_CASE_ , torch.Tensor ): return image elif isinstance(SCREAMING_SNAKE_CASE_ , PIL.Image.Image ): SCREAMING_SNAKE_CASE_ : List[str] = [image] SCREAMING_SNAKE_CASE_ : Tuple = [trans(img.convert("RGB" ) ) for img in image] SCREAMING_SNAKE_CASE_ : str = torch.stack(SCREAMING_SNAKE_CASE_ ) return image class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): def __init__( self , lowercase__ , lowercase__ ): """simple docstring""" super().__init__() # make sure scheduler can always be converted to DDIM SCREAMING_SNAKE_CASE_ : Tuple = DDIMScheduler.from_config(scheduler.config ) self.register_modules(unet=lowercase__ , scheduler=lowercase__ ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" if strength < 0 or strength > 1: raise ValueError(F"The value of strength should in [0.0, 1.0] but is {strength}" ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = min(int(num_inference_steps * strength ) , lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = max(num_inference_steps - init_timestep , 0 ) SCREAMING_SNAKE_CASE_ : List[str] = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__=None ): """simple docstring""" if not isinstance(lowercase__ , (torch.Tensor, PIL.Image.Image, list) ): raise ValueError( F"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(lowercase__ )}" ) SCREAMING_SNAKE_CASE_ : List[str] = image.to(device=lowercase__ , dtype=lowercase__ ) if isinstance(lowercase__ , lowercase__ ) and len(lowercase__ ) != batch_size: raise ValueError( F"You have passed a list of generators of length {len(lowercase__ )}, but requested an effective batch" F" size of {batch_size}. Make sure the batch size matches the length of the generators." ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = init_latents.shape SCREAMING_SNAKE_CASE_ : int = randn_tensor(lowercase__ , generator=lowercase__ , device=lowercase__ , dtype=lowercase__ ) # get latents print("add noise to latents at timestep" , lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = self.scheduler.add_noise(lowercase__ , lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : int = init_latents return latents @torch.no_grad() def __call__( self , lowercase__ = None , lowercase__ = 0.8 , lowercase__ = 1 , lowercase__ = None , lowercase__ = 0.0 , lowercase__ = 50 , lowercase__ = None , lowercase__ = "pil" , lowercase__ = True , ): """simple docstring""" self.check_inputs(lowercase__ ) # 2. Preprocess image SCREAMING_SNAKE_CASE_ : Union[str, Any] = preprocess(lowercase__ ) # 3. set timesteps self.scheduler.set_timesteps(lowercase__ , device=self.device ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Tuple = self.get_timesteps(lowercase__ , lowercase__ , self.device ) SCREAMING_SNAKE_CASE_ : int = timesteps[:1].repeat(lowercase__ ) # 4. Prepare latent variables SCREAMING_SNAKE_CASE_ : Tuple = self.prepare_latents(lowercase__ , lowercase__ , lowercase__ , self.unet.dtype , self.device , lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = latents # 5. Denoising loop for t in self.progress_bar(lowercase__ ): # 1. predict noise model_output SCREAMING_SNAKE_CASE_ : int = self.unet(lowercase__ , lowercase__ ).sample # 2. predict previous mean of image x_t-1 and add variance depending on eta # eta corresponds to η in paper and should be between [0, 1] # do x_t -> x_t-1 SCREAMING_SNAKE_CASE_ : Tuple = self.scheduler.step( lowercase__ , lowercase__ , lowercase__ , eta=lowercase__ , use_clipped_model_output=lowercase__ , generator=lowercase__ , ).prev_sample SCREAMING_SNAKE_CASE_ : Optional[Any] = (image / 2 + 0.5).clamp(0 , 1 ) SCREAMING_SNAKE_CASE_ : Any = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": SCREAMING_SNAKE_CASE_ : Tuple = self.numpy_to_pil(lowercase__ ) if not return_dict: return (image, latent_timestep.item()) return ImagePipelineOutput(images=lowercase__ )
68
'''simple docstring''' import re from filelock import FileLock try: import nltk snake_case_ = True except (ImportError, ModuleNotFoundError): snake_case_ = False if NLTK_AVAILABLE: with FileLock('.lock') as lock: nltk.download('punkt', quiet=True) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str ) -> str: """simple docstring""" re.sub("<n>" , "" , SCREAMING_SNAKE_CASE_ ) # remove pegasus newline char assert NLTK_AVAILABLE, "nltk must be installed to separate newlines between sentences. (pip install nltk)" return "\n".join(nltk.sent_tokenize(SCREAMING_SNAKE_CASE_ ) )
68
1
'''simple docstring''' from typing import Dict, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, flip_channel_order, get_resize_output_image_size, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_torch_available, is_torch_tensor, is_vision_available, logging if is_vision_available(): import PIL if is_torch_available(): import torch snake_case_ = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = ["pixel_values"] def __init__( self , lowercase__ = True , lowercase__ = None , lowercase__ = PILImageResampling.BILINEAR , lowercase__ = True , lowercase__ = 1 / 255 , lowercase__ = True , lowercase__ = None , lowercase__ = True , **lowercase__ , ): """simple docstring""" super().__init__(**lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = size if size is not None else {"shortest_edge": 224} SCREAMING_SNAKE_CASE_ : Optional[int] = get_size_dict(lowercase__ , default_to_square=lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = crop_size if crop_size is not None else {"height": 256, "width": 256} SCREAMING_SNAKE_CASE_ : Dict = get_size_dict(lowercase__ , param_name="crop_size" ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = do_resize SCREAMING_SNAKE_CASE_ : Union[str, Any] = size SCREAMING_SNAKE_CASE_ : List[str] = resample SCREAMING_SNAKE_CASE_ : Dict = do_rescale SCREAMING_SNAKE_CASE_ : List[Any] = rescale_factor SCREAMING_SNAKE_CASE_ : Optional[Any] = do_center_crop SCREAMING_SNAKE_CASE_ : Dict = crop_size SCREAMING_SNAKE_CASE_ : str = do_flip_channel_order def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ = PIL.Image.BILINEAR , lowercase__ = None , **lowercase__ , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = get_size_dict(lowercase__ , default_to_square=lowercase__ ) if "shortest_edge" not in size: raise ValueError(F"The `size` dictionary must contain the key `shortest_edge`. Got {size.keys()}" ) SCREAMING_SNAKE_CASE_ : List[Any] = get_resize_output_image_size(lowercase__ , size=size["shortest_edge"] , default_to_square=lowercase__ ) return resize(lowercase__ , size=lowercase__ , resample=lowercase__ , data_format=lowercase__ , **lowercase__ ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ = None , **lowercase__ , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = get_size_dict(lowercase__ ) if "height" not in size or "width" not in size: raise ValueError(F"The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}" ) return center_crop(lowercase__ , size=(size["height"], size["width"]) , data_format=lowercase__ , **lowercase__ ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ = None , **lowercase__ , ): """simple docstring""" return rescale(lowercase__ , scale=lowercase__ , data_format=lowercase__ , **lowercase__ ) def __lowerCamelCase ( self , lowercase__ , lowercase__ = None ): """simple docstring""" return flip_channel_order(lowercase__ , data_format=lowercase__ ) def __lowerCamelCase ( self , lowercase__ , lowercase__ = None , lowercase__ = None , lowercase__ = None , lowercase__ = None , lowercase__ = None , lowercase__ = None , lowercase__ = None , lowercase__ = None , lowercase__ = None , lowercase__ = ChannelDimension.FIRST , **lowercase__ , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE_ : str = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE_ : int = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE_ : Dict = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE_ : List[str] = do_center_crop if do_center_crop is not None else self.do_center_crop SCREAMING_SNAKE_CASE_ : Union[str, Any] = ( do_flip_channel_order if do_flip_channel_order is not None else self.do_flip_channel_order ) SCREAMING_SNAKE_CASE_ : Tuple = size if size is not None else self.size SCREAMING_SNAKE_CASE_ : List[str] = get_size_dict(lowercase__ , default_to_square=lowercase__ ) SCREAMING_SNAKE_CASE_ : str = crop_size if crop_size is not None else self.crop_size SCREAMING_SNAKE_CASE_ : Tuple = get_size_dict(lowercase__ , param_name="crop_size" ) SCREAMING_SNAKE_CASE_ : Optional[Any] = make_list_of_images(lowercase__ ) if not valid_images(lowercase__ ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None: raise ValueError("Size must be specified if do_resize is True." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_center_crop and crop_size is None: raise ValueError("Crop size must be specified if do_center_crop is True." ) # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE_ : Any = [to_numpy_array(lowercase__ ) for image in images] if do_resize: SCREAMING_SNAKE_CASE_ : Optional[Any] = [self.resize(image=lowercase__ , size=lowercase__ , resample=lowercase__ ) for image in images] if do_center_crop: SCREAMING_SNAKE_CASE_ : int = [self.center_crop(image=lowercase__ , size=lowercase__ ) for image in images] if do_rescale: SCREAMING_SNAKE_CASE_ : str = [self.rescale(image=lowercase__ , scale=lowercase__ ) for image in images] # the pretrained checkpoints assume images are BGR, not RGB if do_flip_channel_order: SCREAMING_SNAKE_CASE_ : Optional[Any] = [self.flip_channel_order(image=lowercase__ ) for image in images] SCREAMING_SNAKE_CASE_ : List[Any] = [to_channel_dimension_format(lowercase__ , lowercase__ ) for image in images] SCREAMING_SNAKE_CASE_ : int = {"pixel_values": images} return BatchFeature(data=lowercase__ , tensor_type=lowercase__ ) def __lowerCamelCase ( self , lowercase__ , lowercase__ = None ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(lowercase__ ) != len(lowercase__ ): raise ValueError( "Make sure that you pass in as many target sizes as the batch dimension of the logits" ) if is_torch_tensor(lowercase__ ): SCREAMING_SNAKE_CASE_ : int = target_sizes.numpy() SCREAMING_SNAKE_CASE_ : List[Any] = [] for idx in range(len(lowercase__ ) ): SCREAMING_SNAKE_CASE_ : Tuple = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode="bilinear" , align_corners=lowercase__ ) SCREAMING_SNAKE_CASE_ : Tuple = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(lowercase__ ) else: SCREAMING_SNAKE_CASE_ : Any = logits.argmax(dim=1 ) SCREAMING_SNAKE_CASE_ : Dict = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
68
'''simple docstring''' from __future__ import annotations import copy import inspect import unittest import numpy as np from transformers import is_tf_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_tf, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, TFLayoutLMvaModel, ) if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class SCREAMING_SNAKE_CASE__ : def __init__( self , lowercase__ , lowercase__=2 , lowercase__=3 , lowercase__=4 , lowercase__=2 , lowercase__=7 , lowercase__=True , lowercase__=True , lowercase__=True , lowercase__=True , lowercase__=99 , lowercase__=36 , lowercase__=2 , lowercase__=4 , lowercase__=37 , lowercase__="gelu" , lowercase__=0.1 , lowercase__=0.1 , lowercase__=512 , lowercase__=16 , lowercase__=2 , lowercase__=0.02 , lowercase__=6 , lowercase__=6 , lowercase__=3 , lowercase__=4 , lowercase__=None , lowercase__=1000 , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = parent SCREAMING_SNAKE_CASE_ : Optional[int] = batch_size SCREAMING_SNAKE_CASE_ : Dict = num_channels SCREAMING_SNAKE_CASE_ : Union[str, Any] = image_size SCREAMING_SNAKE_CASE_ : Optional[int] = patch_size SCREAMING_SNAKE_CASE_ : str = is_training SCREAMING_SNAKE_CASE_ : str = use_input_mask SCREAMING_SNAKE_CASE_ : Any = use_token_type_ids SCREAMING_SNAKE_CASE_ : int = use_labels SCREAMING_SNAKE_CASE_ : Union[str, Any] = vocab_size SCREAMING_SNAKE_CASE_ : Optional[Any] = hidden_size SCREAMING_SNAKE_CASE_ : Dict = num_hidden_layers SCREAMING_SNAKE_CASE_ : Any = num_attention_heads SCREAMING_SNAKE_CASE_ : Optional[Any] = intermediate_size SCREAMING_SNAKE_CASE_ : str = hidden_act SCREAMING_SNAKE_CASE_ : int = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : Tuple = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : Union[str, Any] = max_position_embeddings SCREAMING_SNAKE_CASE_ : Dict = type_vocab_size SCREAMING_SNAKE_CASE_ : List[Any] = type_sequence_label_size SCREAMING_SNAKE_CASE_ : Tuple = initializer_range SCREAMING_SNAKE_CASE_ : List[str] = coordinate_size SCREAMING_SNAKE_CASE_ : Optional[Any] = shape_size SCREAMING_SNAKE_CASE_ : List[str] = num_labels SCREAMING_SNAKE_CASE_ : Optional[int] = num_choices SCREAMING_SNAKE_CASE_ : Union[str, Any] = scope SCREAMING_SNAKE_CASE_ : Dict = 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_ : Union[str, Any] = text_seq_length SCREAMING_SNAKE_CASE_ : Tuple = (image_size // patch_size) ** 2 + 1 SCREAMING_SNAKE_CASE_ : Optional[int] = self.text_seq_length + self.image_seq_length def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE_ : Optional[Any] = ids_tensor([self.batch_size, self.text_seq_length, 4] , self.range_bbox ) SCREAMING_SNAKE_CASE_ : Dict = bbox.numpy() # 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_ : Optional[int] = bbox[i, j, 3] SCREAMING_SNAKE_CASE_ : str = bbox[i, j, 1] SCREAMING_SNAKE_CASE_ : Dict = tmp_coordinate if bbox[i, j, 2] < bbox[i, j, 0]: SCREAMING_SNAKE_CASE_ : List[Any] = bbox[i, j, 2] SCREAMING_SNAKE_CASE_ : Dict = bbox[i, j, 0] SCREAMING_SNAKE_CASE_ : Tuple = tmp_coordinate SCREAMING_SNAKE_CASE_ : Dict = tf.constant(lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE_ : Dict = None if self.use_input_mask: SCREAMING_SNAKE_CASE_ : Any = random_attention_mask([self.batch_size, self.text_seq_length] ) SCREAMING_SNAKE_CASE_ : List[str] = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE_ : Dict = ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE_ : Dict = None SCREAMING_SNAKE_CASE_ : Tuple = None if self.use_labels: SCREAMING_SNAKE_CASE_ : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE_ : List[str] = ids_tensor([self.batch_size, self.text_seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE_ : str = 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 __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = TFLayoutLMvaModel(config=lowercase__ ) # text + image SCREAMING_SNAKE_CASE_ : int = model(lowercase__ , pixel_values=lowercase__ , training=lowercase__ ) SCREAMING_SNAKE_CASE_ : str = model( lowercase__ , bbox=lowercase__ , pixel_values=lowercase__ , attention_mask=lowercase__ , token_type_ids=lowercase__ , training=lowercase__ , ) SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase__ , bbox=lowercase__ , pixel_values=lowercase__ , training=lowercase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # text only SCREAMING_SNAKE_CASE_ : Tuple = model(lowercase__ , training=lowercase__ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size) ) # image only SCREAMING_SNAKE_CASE_ : int = model({"pixel_values": pixel_values} , training=lowercase__ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size) ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = self.num_labels SCREAMING_SNAKE_CASE_ : Union[str, Any] = TFLayoutLMvaForSequenceClassification(config=lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = model( lowercase__ , bbox=lowercase__ , pixel_values=lowercase__ , attention_mask=lowercase__ , token_type_ids=lowercase__ , labels=lowercase__ , training=lowercase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.num_labels SCREAMING_SNAKE_CASE_ : Any = TFLayoutLMvaForTokenClassification(config=lowercase__ ) SCREAMING_SNAKE_CASE_ : int = model( lowercase__ , bbox=lowercase__ , pixel_values=lowercase__ , attention_mask=lowercase__ , token_type_ids=lowercase__ , labels=lowercase__ , training=lowercase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels) ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = 2 SCREAMING_SNAKE_CASE_ : List[Any] = TFLayoutLMvaForQuestionAnswering(config=lowercase__ ) SCREAMING_SNAKE_CASE_ : int = model( lowercase__ , bbox=lowercase__ , pixel_values=lowercase__ , attention_mask=lowercase__ , token_type_ids=lowercase__ , start_positions=lowercase__ , end_positions=lowercase__ , training=lowercase__ , ) 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 __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = 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_)) : Any = config_and_inputs SCREAMING_SNAKE_CASE_ : Optional[Any] = { "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_tf class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,_UpperCAmelCase,unittest.TestCase ): _A = ( ( TFLayoutLMvaModel, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, ) if is_tf_available() else () ) _A = ( {"document-question-answering": TFLayoutLMvaForQuestionAnswering, "feature-extraction": TFLayoutLMvaModel} if is_tf_available() else {} ) _A = False _A = False _A = False def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" return True def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__=False ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = copy.deepcopy(lowercase__ ) if model_class in get_values(lowercase__ ): SCREAMING_SNAKE_CASE_ : str = { k: tf.tile(tf.expand_dims(lowercase__ , 1 ) , (1, self.model_tester.num_choices) + (1,) * (v.ndim - 1) ) if isinstance(lowercase__ , tf.Tensor ) and v.ndim > 0 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(lowercase__ ): SCREAMING_SNAKE_CASE_ : Tuple = tf.ones(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(lowercase__ ): SCREAMING_SNAKE_CASE_ : Any = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) SCREAMING_SNAKE_CASE_ : List[Any] = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(lowercase__ ): SCREAMING_SNAKE_CASE_ : List[str] = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(lowercase__ ): SCREAMING_SNAKE_CASE_ : Optional[Any] = tf.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=tf.intaa ) return inputs_dict def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = TFLayoutLMvaModelTester(self ) SCREAMING_SNAKE_CASE_ : int = ConfigTester(self , config_class=lowercase__ , hidden_size=37 ) def __lowerCamelCase ( self ): """simple docstring""" self.config_tester.run_common_tests() def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ : int = model_class(lowercase__ ) if getattr(lowercase__ , "hf_compute_loss" , lowercase__ ): # The number of elements in the loss should be the same as the number of elements in the label SCREAMING_SNAKE_CASE_ : Dict = self._prepare_for_class(inputs_dict.copy() , lowercase__ , return_labels=lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = prepared_for_class[ sorted(prepared_for_class.keys() - inputs_dict.keys() , reverse=lowercase__ )[0] ] SCREAMING_SNAKE_CASE_ : Any = added_label.shape.as_list()[:1] # Test that model correctly compute the loss with kwargs SCREAMING_SNAKE_CASE_ : Dict = self._prepare_for_class(inputs_dict.copy() , lowercase__ , return_labels=lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = prepared_for_class.pop("input_ids" ) SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase__ , **lowercase__ )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss when we mask some positions SCREAMING_SNAKE_CASE_ : List[Any] = self._prepare_for_class(inputs_dict.copy() , lowercase__ , return_labels=lowercase__ ) SCREAMING_SNAKE_CASE_ : int = prepared_for_class.pop("input_ids" ) if "labels" in prepared_for_class: SCREAMING_SNAKE_CASE_ : str = prepared_for_class["labels"].numpy() if len(labels.shape ) > 1 and labels.shape[1] != 1: SCREAMING_SNAKE_CASE_ : str = -100 SCREAMING_SNAKE_CASE_ : str = tf.convert_to_tensor(lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = model(lowercase__ , **lowercase__ )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) self.assertTrue(not np.any(np.isnan(loss.numpy() ) ) ) # Test that model correctly compute the loss with a dict SCREAMING_SNAKE_CASE_ : List[Any] = self._prepare_for_class(inputs_dict.copy() , lowercase__ , return_labels=lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = model(lowercase__ )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss with a tuple SCREAMING_SNAKE_CASE_ : Optional[Any] = self._prepare_for_class(inputs_dict.copy() , lowercase__ , return_labels=lowercase__ ) # Get keys that were added with the _prepare_for_class function SCREAMING_SNAKE_CASE_ : int = prepared_for_class.keys() - inputs_dict.keys() SCREAMING_SNAKE_CASE_ : Optional[int] = inspect.signature(model.call ).parameters SCREAMING_SNAKE_CASE_ : Tuple = list(signature.keys() ) # Create a dictionary holding the location of the tensors in the tuple SCREAMING_SNAKE_CASE_ : List[Any] = {0: "input_ids"} for label_key in label_keys: SCREAMING_SNAKE_CASE_ : Optional[int] = signature_names.index(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = label_key SCREAMING_SNAKE_CASE_ : List[str] = sorted(tuple_index_mapping.items() ) # Initialize a list with their default values, update the values and convert to a tuple SCREAMING_SNAKE_CASE_ : List[str] = [] for name in signature_names: if name != "kwargs": list_input.append(signature[name].default ) for index, value in sorted_tuple_index_mapping: SCREAMING_SNAKE_CASE_ : List[str] = prepared_for_class[value] SCREAMING_SNAKE_CASE_ : List[Any] = tuple(lowercase__ ) # Send to model SCREAMING_SNAKE_CASE_ : int = model(tuple_input[:-1] )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) def __lowerCamelCase ( self ): """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_ ), ) : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) def __lowerCamelCase ( self ): """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_ ), ) : Optional[Any] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE_ : List[str] = type self.model_tester.create_and_check_model(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) def __lowerCamelCase ( self ): """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_ ), ) : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) def __lowerCamelCase ( self ): """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_ ), ) : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) def __lowerCamelCase ( self ): """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_ ), ) : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) @slow def __lowerCamelCase ( self ): """simple docstring""" for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE_ : Union[str, Any] = TFLayoutLMvaModel.from_pretrained(lowercase__ ) self.assertIsNotNone(lowercase__ ) def __lowerCamelCase ( ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : str = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_tf class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): @cached_property def __lowerCamelCase ( self ): """simple docstring""" return LayoutLMvaImageProcessor(apply_ocr=lowercase__ ) if is_vision_available() else None @slow def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = TFLayoutLMvaModel.from_pretrained("microsoft/layoutlmv3-base" ) SCREAMING_SNAKE_CASE_ : Any = self.default_image_processor SCREAMING_SNAKE_CASE_ : Optional[int] = prepare_img() SCREAMING_SNAKE_CASE_ : Optional[Any] = image_processor(images=lowercase__ , return_tensors="tf" ).pixel_values SCREAMING_SNAKE_CASE_ : Dict = tf.constant([[1, 2]] ) SCREAMING_SNAKE_CASE_ : Any = tf.expand_dims(tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]] ) , axis=0 ) # forward pass SCREAMING_SNAKE_CASE_ : List[Any] = model(input_ids=lowercase__ , bbox=lowercase__ , pixel_values=lowercase__ , training=lowercase__ ) # verify the logits SCREAMING_SNAKE_CASE_ : Tuple = (1, 199, 768) self.assertEqual(outputs.last_hidden_state.shape , lowercase__ ) SCREAMING_SNAKE_CASE_ : int = tf.constant( [[-0.0529, 0.3618, 0.1632], [-0.1587, -0.1667, -0.0400], [-0.1557, -0.1671, -0.0505]] ) self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3] , lowercase__ , atol=1e-4 ) )
68
1
'''simple docstring''' from __future__ import annotations import matplotlib.pyplot as plt # type: ignore import numpy # initial triangle of Koch snowflake snake_case_ = numpy.array([0, 0]) snake_case_ = numpy.array([0.5, 0.8_6_6_0_2_5_4]) snake_case_ = numpy.array([1, 0]) snake_case_ = [VECTOR_1, VECTOR_2, VECTOR_3, VECTOR_1] def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : list[numpy.ndarray] , SCREAMING_SNAKE_CASE_ : int ) -> list[numpy.ndarray]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = initial_vectors for _ in range(SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ : List[str] = iteration_step(SCREAMING_SNAKE_CASE_ ) return vectors def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : list[numpy.ndarray] ) -> list[numpy.ndarray]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = [] for i, start_vector in enumerate(vectors[:-1] ): SCREAMING_SNAKE_CASE_ : Optional[int] = vectors[i + 1] new_vectors.append(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Any = end_vector - start_vector new_vectors.append(start_vector + difference_vector / 3 ) new_vectors.append( start_vector + difference_vector / 3 + rotate(difference_vector / 3 , 6_0 ) ) new_vectors.append(start_vector + difference_vector * 2 / 3 ) new_vectors.append(vectors[-1] ) return new_vectors def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : numpy.ndarray , SCREAMING_SNAKE_CASE_ : float ) -> numpy.ndarray: """simple docstring""" SCREAMING_SNAKE_CASE_ : str = numpy.radians(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : List[str] = numpy.cos(SCREAMING_SNAKE_CASE_ ), numpy.sin(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Dict = numpy.array(((c, -s), (s, c)) ) return numpy.dot(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : list[numpy.ndarray] ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = plt.gca() axes.set_aspect("equal" ) # matplotlib.pyplot.plot takes a list of all x-coordinates and a list of all # y-coordinates as inputs, which are constructed from the vector-list using # zip() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : str = zip(*SCREAMING_SNAKE_CASE_ ) plt.plot(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) plt.show() if __name__ == "__main__": import doctest doctest.testmod() snake_case_ = iterate(INITIAL_VECTORS, 5) plot(processed_vectors)
68
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Tuple ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = [1] for i in range(2 , SCREAMING_SNAKE_CASE_ ): factorials.append(factorials[-1] * i ) assert 0 <= k < factorials[-1] * n, "k out of bounds" SCREAMING_SNAKE_CASE_ : Union[str, Any] = [] SCREAMING_SNAKE_CASE_ : Dict = list(range(SCREAMING_SNAKE_CASE_ ) ) # Find permutation while factorials: SCREAMING_SNAKE_CASE_ : Any = factorials.pop() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[int] = divmod(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) permutation.append(elements[number] ) elements.remove(elements[number] ) permutation.append(elements[0] ) return permutation if __name__ == "__main__": import doctest doctest.testmod()
68
1
'''simple docstring''' import collections import inspect import unittest from transformers import SwinvaConfig 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, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import SwinvaForImageClassification, SwinvaForMaskedImageModeling, SwinvaModel from transformers.models.swinva.modeling_swinva import SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class SCREAMING_SNAKE_CASE__ : def __init__( self , lowercase__ , lowercase__=13 , lowercase__=32 , lowercase__=2 , lowercase__=3 , lowercase__=16 , lowercase__=[1, 2, 1] , lowercase__=[2, 2, 4] , lowercase__=2 , lowercase__=2.0 , lowercase__=True , lowercase__=0.0 , lowercase__=0.0 , lowercase__=0.1 , lowercase__="gelu" , lowercase__=False , lowercase__=True , lowercase__=0.02 , lowercase__=1e-5 , lowercase__=True , lowercase__=None , lowercase__=True , lowercase__=10 , lowercase__=8 , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = parent SCREAMING_SNAKE_CASE_ : List[Any] = batch_size SCREAMING_SNAKE_CASE_ : Optional[int] = image_size SCREAMING_SNAKE_CASE_ : List[Any] = patch_size SCREAMING_SNAKE_CASE_ : Any = num_channels SCREAMING_SNAKE_CASE_ : Tuple = embed_dim SCREAMING_SNAKE_CASE_ : Optional[Any] = depths SCREAMING_SNAKE_CASE_ : Any = num_heads SCREAMING_SNAKE_CASE_ : List[Any] = window_size SCREAMING_SNAKE_CASE_ : Union[str, Any] = mlp_ratio SCREAMING_SNAKE_CASE_ : List[str] = qkv_bias SCREAMING_SNAKE_CASE_ : Optional[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : Union[str, Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : Any = drop_path_rate SCREAMING_SNAKE_CASE_ : List[str] = hidden_act SCREAMING_SNAKE_CASE_ : str = use_absolute_embeddings SCREAMING_SNAKE_CASE_ : List[Any] = patch_norm SCREAMING_SNAKE_CASE_ : Optional[int] = layer_norm_eps SCREAMING_SNAKE_CASE_ : List[Any] = initializer_range SCREAMING_SNAKE_CASE_ : List[Any] = is_training SCREAMING_SNAKE_CASE_ : int = scope SCREAMING_SNAKE_CASE_ : Union[str, Any] = use_labels SCREAMING_SNAKE_CASE_ : Union[str, Any] = type_sequence_label_size SCREAMING_SNAKE_CASE_ : str = encoder_stride def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE_ : Tuple = None if self.use_labels: SCREAMING_SNAKE_CASE_ : str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE_ : int = self.get_config() return config, pixel_values, labels def __lowerCamelCase ( self ): """simple docstring""" return SwinvaConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = SwinvaModel(config=lowercase__ ) model.to(lowercase__ ) model.eval() SCREAMING_SNAKE_CASE_ : Tuple = model(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) SCREAMING_SNAKE_CASE_ : Optional[Any] = int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim) ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = SwinvaForMaskedImageModeling(config=lowercase__ ) model.to(lowercase__ ) model.eval() SCREAMING_SNAKE_CASE_ : int = model(lowercase__ ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images SCREAMING_SNAKE_CASE_ : Union[str, Any] = 1 SCREAMING_SNAKE_CASE_ : Any = SwinvaForMaskedImageModeling(lowercase__ ) model.to(lowercase__ ) model.eval() SCREAMING_SNAKE_CASE_ : Tuple = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE_ : str = model(lowercase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = self.type_sequence_label_size SCREAMING_SNAKE_CASE_ : int = SwinvaForImageClassification(lowercase__ ) model.to(lowercase__ ) model.eval() SCREAMING_SNAKE_CASE_ : Optional[int] = model(lowercase__ , labels=lowercase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : str = config_and_inputs SCREAMING_SNAKE_CASE_ : int = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,_UpperCAmelCase,unittest.TestCase ): _A = ( (SwinvaModel, SwinvaForImageClassification, SwinvaForMaskedImageModeling) if is_torch_available() else () ) _A = ( {"feature-extraction": SwinvaModel, "image-classification": SwinvaForImageClassification} if is_torch_available() else {} ) _A = False _A = False _A = False _A = False def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = SwinvaModelTester(self ) SCREAMING_SNAKE_CASE_ : int = ConfigTester(self , config_class=lowercase__ , embed_dim=37 ) def __lowerCamelCase ( self ): """simple docstring""" self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase__ ) @unittest.skip(reason="Got `CUDA error: misaligned address` with PyTorch 2.0.0." ) def __lowerCamelCase ( self ): """simple docstring""" pass @unittest.skip(reason="Swinv2 does not use inputs_embeds" ) def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ : Optional[Any] = model_class(lowercase__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) SCREAMING_SNAKE_CASE_ : str = model.get_output_embeddings() self.assertTrue(x is None or isinstance(lowercase__ , nn.Linear ) ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ : Optional[Any] = model_class(lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE_ : int = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE_ : Optional[Any] = ["pixel_values"] self.assertListEqual(arg_names[:1] , lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : str = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE_ : List[str] = True for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ : Optional[Any] = True SCREAMING_SNAKE_CASE_ : List[Any] = False SCREAMING_SNAKE_CASE_ : Optional[int] = True SCREAMING_SNAKE_CASE_ : Any = model_class(lowercase__ ) model.to(lowercase__ ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE_ : int = model(**self._prepare_for_class(lowercase__ , lowercase__ ) ) SCREAMING_SNAKE_CASE_ : List[Any] = outputs.attentions SCREAMING_SNAKE_CASE_ : Any = len(self.model_tester.depths ) self.assertEqual(len(lowercase__ ) , lowercase__ ) # check that output_attentions also work using config del inputs_dict["output_attentions"] SCREAMING_SNAKE_CASE_ : Any = True SCREAMING_SNAKE_CASE_ : Union[str, Any] = config.window_size**2 SCREAMING_SNAKE_CASE_ : str = model_class(lowercase__ ) model.to(lowercase__ ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE_ : Any = model(**self._prepare_for_class(lowercase__ , lowercase__ ) ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = outputs.attentions self.assertEqual(len(lowercase__ ) , lowercase__ ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_heads[0], window_size_squared, window_size_squared] , ) SCREAMING_SNAKE_CASE_ : Optional[Any] = len(lowercase__ ) # Check attention is always last and order is fine SCREAMING_SNAKE_CASE_ : List[Any] = True SCREAMING_SNAKE_CASE_ : Any = True SCREAMING_SNAKE_CASE_ : List[str] = model_class(lowercase__ ) model.to(lowercase__ ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE_ : Tuple = model(**self._prepare_for_class(lowercase__ , lowercase__ ) ) if hasattr(self.model_tester , "num_hidden_states_types" ): SCREAMING_SNAKE_CASE_ : List[Any] = self.model_tester.num_hidden_states_types else: # also another +1 for reshaped_hidden_states SCREAMING_SNAKE_CASE_ : Tuple = 2 self.assertEqual(out_len + added_hidden_states , len(lowercase__ ) ) SCREAMING_SNAKE_CASE_ : Tuple = outputs.attentions self.assertEqual(len(lowercase__ ) , lowercase__ ) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_heads[0], window_size_squared, window_size_squared] , ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = model_class(lowercase__ ) model.to(lowercase__ ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE_ : Union[str, Any] = model(**self._prepare_for_class(lowercase__ , lowercase__ ) ) SCREAMING_SNAKE_CASE_ : Any = outputs.hidden_states SCREAMING_SNAKE_CASE_ : Dict = getattr( self.model_tester , "expected_num_hidden_layers" , len(self.model_tester.depths ) + 1 ) self.assertEqual(len(lowercase__ ) , lowercase__ ) # Swinv2 has a different seq_length SCREAMING_SNAKE_CASE_ : Any = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) SCREAMING_SNAKE_CASE_ : Any = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) SCREAMING_SNAKE_CASE_ : Tuple = outputs.reshaped_hidden_states self.assertEqual(len(lowercase__ ) , lowercase__ ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[Any] = reshaped_hidden_states[0].shape SCREAMING_SNAKE_CASE_ : List[Any] = ( reshaped_hidden_states[0].view(lowercase__ , lowercase__ , height * width ).permute(0 , 2 , 1 ) ) self.assertListEqual( list(reshaped_hidden_states.shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE_ : List[Any] = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ : Union[str, Any] = True self.check_hidden_states_output(lowercase__ , lowercase__ , lowercase__ , lowercase__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE_ : Union[str, Any] = True self.check_hidden_states_output(lowercase__ , lowercase__ , lowercase__ , lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : str = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE_ : Tuple = 3 SCREAMING_SNAKE_CASE_ : List[str] = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) SCREAMING_SNAKE_CASE_ : Any = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) SCREAMING_SNAKE_CASE_ : str = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) SCREAMING_SNAKE_CASE_ : Dict = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ : Dict = True self.check_hidden_states_output(lowercase__ , lowercase__ , lowercase__ , (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE_ : Optional[Any] = True self.check_hidden_states_output(lowercase__ , lowercase__ , lowercase__ , (padded_height, padded_width) ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowercase__ ) @slow def __lowerCamelCase ( self ): """simple docstring""" for model_name in SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE_ : List[str] = SwinvaModel.from_pretrained(lowercase__ ) self.assertIsNotNone(lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE_ : Optional[Any] = _config_zero_init(lowercase__ ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ : List[Any] = model_class(config=lowercase__ ) for name, param in model.named_parameters(): if "embeddings" not in name and "logit_scale" not in name and param.requires_grad: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=F"Parameter {name} of model {model_class} seems not properly initialized" , ) @require_vision @require_torch class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): @cached_property def __lowerCamelCase ( self ): """simple docstring""" return ( AutoImageProcessor.from_pretrained("microsoft/swinv2-tiny-patch4-window8-256" ) if is_vision_available() else None ) @slow def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = SwinvaForImageClassification.from_pretrained("microsoft/swinv2-tiny-patch4-window8-256" ).to( lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = self.default_image_processor SCREAMING_SNAKE_CASE_ : Optional[Any] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) SCREAMING_SNAKE_CASE_ : List[str] = image_processor(images=lowercase__ , return_tensors="pt" ).to(lowercase__ ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE_ : Any = model(**lowercase__ ) # verify the logits SCREAMING_SNAKE_CASE_ : List[Any] = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = torch.tensor([-0.3947, -0.4306, 0.0026] ).to(lowercase__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowercase__ , atol=1e-4 ) )
68
'''simple docstring''' import argparse from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_controlnet_from_original_ckpt if __name__ == "__main__": snake_case_ = argparse.ArgumentParser() parser.add_argument( '--checkpoint_path', default=None, type=str, required=True, help='Path to the checkpoint to convert.' ) parser.add_argument( '--original_config_file', type=str, required=True, help='The YAML config file corresponding to the original architecture.', ) parser.add_argument( '--num_in_channels', default=None, type=int, help='The number of input channels. If `None` number of input channels will be automatically inferred.', ) parser.add_argument( '--image_size', default=5_1_2, type=int, help=( 'The image size that the model was trained on. Use 512 for Stable Diffusion v1.X and Stable Siffusion v2' ' Base. Use 768 for Stable Diffusion v2.' ), ) parser.add_argument( '--extract_ema', action='store_true', help=( 'Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights' ' or not. Defaults to `False`. Add `--extract_ema` to extract the EMA weights. EMA weights usually yield' ' higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning.' ), ) parser.add_argument( '--upcast_attention', action='store_true', help=( 'Whether the attention computation should always be upcasted. This is necessary when running stable' ' diffusion 2.1.' ), ) parser.add_argument( '--from_safetensors', action='store_true', help='If `--checkpoint_path` is in `safetensors` format, load checkpoint with safetensors instead of PyTorch.', ) parser.add_argument( '--to_safetensors', action='store_true', help='Whether to store pipeline in safetensors format or not.', ) parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.') parser.add_argument('--device', type=str, help='Device to use (e.g. cpu, cuda:0, cuda:1, etc.)') def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Optional[int] ) -> Dict: """simple docstring""" if string == "True": return True elif string == "False": return False else: raise ValueError(F"could not parse string as bool {string}" ) parser.add_argument( '--use_linear_projection', help='Override for use linear projection', required=False, type=parse_bool ) parser.add_argument('--cross_attention_dim', help='Override for cross attention_dim', required=False, type=int) snake_case_ = parser.parse_args() snake_case_ = download_controlnet_from_original_ckpt( checkpoint_path=args.checkpoint_path, original_config_file=args.original_config_file, image_size=args.image_size, extract_ema=args.extract_ema, num_in_channels=args.num_in_channels, upcast_attention=args.upcast_attention, from_safetensors=args.from_safetensors, device=args.device, use_linear_projection=args.use_linear_projection, cross_attention_dim=args.cross_attention_dim, ) controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
68
1
'''simple docstring''' import os import sys import warnings from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import xopen from ..table import array_cast from ..utils.file_utils import is_local_path from ..utils.py_utils import first_non_null_value, no_op_if_value_is_null, string_to_dict if TYPE_CHECKING: import PIL.Image from .features import FeatureType snake_case_ = None snake_case_ = '<' if sys.byteorder == 'little' else '>' # Origin: https://github.com/python-pillow/Pillow/blob/698951e19e19972aeed56df686868f1329981c12/src/PIL/Image.py#L3126 minus "|i1" which values are not preserved correctly when saving and loading an image snake_case_ = [ np.dtype('|b1'), np.dtype('|u1'), np.dtype('<u2'), np.dtype('>u2'), np.dtype('<i2'), np.dtype('>i2'), np.dtype('<u4'), np.dtype('>u4'), np.dtype('<i4'), np.dtype('>i4'), np.dtype('<f4'), np.dtype('>f4'), np.dtype('<f8'), np.dtype('>f8'), ] @dataclass class SCREAMING_SNAKE_CASE__ : _A = True _A = None # Automatically constructed _A = "PIL.Image.Image" _A = pa.struct({"bytes": pa.binary(), "path": pa.string()} ) _A = field(default="Image",init=_UpperCAmelCase,repr=_UpperCAmelCase ) def __call__( self ): """simple docstring""" return self.pa_type def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support encoding images, please install 'Pillow'." ) if isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE_ : List[Any] = np.array(lowercase__ ) if isinstance(lowercase__ , lowercase__ ): return {"path": value, "bytes": None} elif isinstance(lowercase__ , lowercase__ ): return {"path": None, "bytes": value} elif isinstance(lowercase__ , np.ndarray ): # convert the image array to PNG/TIFF bytes return encode_np_array(lowercase__ ) elif isinstance(lowercase__ , PIL.Image.Image ): # convert the PIL image to bytes (default format is PNG/TIFF) return encode_pil_image(lowercase__ ) elif value.get("path" ) is not None and os.path.isfile(value["path"] ): # we set "bytes": None to not duplicate the data if they're already available locally return {"bytes": None, "path": value.get("path" )} elif value.get("bytes" ) is not None or value.get("path" ) is not None: # store the image bytes, and path is used to infer the image format using the file extension return {"bytes": value.get("bytes" ), "path": value.get("path" )} else: raise ValueError( F"An image sample should have one of 'path' or 'bytes' but they are missing or None in {value}." ) def __lowerCamelCase ( self , lowercase__ , lowercase__=None ): """simple docstring""" if not self.decode: raise RuntimeError("Decoding is disabled for this feature. Please use Image(decode=True) instead." ) if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support decoding images, please install 'Pillow'." ) if token_per_repo_id is None: SCREAMING_SNAKE_CASE_ : Optional[int] = {} SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Tuple = value["path"], value["bytes"] if bytes_ is None: if path is None: raise ValueError(F"An image should have one of 'path' or 'bytes' but both are None in {value}." ) else: if is_local_path(lowercase__ ): SCREAMING_SNAKE_CASE_ : Union[str, Any] = PIL.Image.open(lowercase__ ) else: SCREAMING_SNAKE_CASE_ : Optional[int] = path.split("::" )[-1] try: SCREAMING_SNAKE_CASE_ : Dict = string_to_dict(lowercase__ , config.HUB_DATASETS_URL )["repo_id"] SCREAMING_SNAKE_CASE_ : List[Any] = token_per_repo_id.get(lowercase__ ) except ValueError: SCREAMING_SNAKE_CASE_ : List[Any] = None with xopen(lowercase__ , "rb" , use_auth_token=lowercase__ ) as f: SCREAMING_SNAKE_CASE_ : str = BytesIO(f.read() ) SCREAMING_SNAKE_CASE_ : str = PIL.Image.open(bytes_ ) else: SCREAMING_SNAKE_CASE_ : int = PIL.Image.open(BytesIO(bytes_ ) ) image.load() # to avoid "Too many open files" errors return image def __lowerCamelCase ( self ): """simple docstring""" from .features import Value return ( self if self.decode else { "bytes": Value("binary" ), "path": Value("string" ), } ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" if pa.types.is_string(storage.type ): SCREAMING_SNAKE_CASE_ : Tuple = pa.array([None] * len(lowercase__ ) , type=pa.binary() ) SCREAMING_SNAKE_CASE_ : List[str] = pa.StructArray.from_arrays([bytes_array, storage] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_binary(storage.type ): SCREAMING_SNAKE_CASE_ : Any = pa.array([None] * len(lowercase__ ) , type=pa.string() ) SCREAMING_SNAKE_CASE_ : Any = pa.StructArray.from_arrays([storage, path_array] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_struct(storage.type ): if storage.type.get_field_index("bytes" ) >= 0: SCREAMING_SNAKE_CASE_ : Tuple = storage.field("bytes" ) else: SCREAMING_SNAKE_CASE_ : str = pa.array([None] * len(lowercase__ ) , type=pa.binary() ) if storage.type.get_field_index("path" ) >= 0: SCREAMING_SNAKE_CASE_ : List[str] = storage.field("path" ) else: SCREAMING_SNAKE_CASE_ : List[Any] = pa.array([None] * len(lowercase__ ) , type=pa.string() ) SCREAMING_SNAKE_CASE_ : Any = pa.StructArray.from_arrays([bytes_array, path_array] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_list(storage.type ): SCREAMING_SNAKE_CASE_ : Tuple = pa.array( [encode_np_array(np.array(lowercase__ ) )["bytes"] if arr is not None else None for arr in storage.to_pylist()] , type=pa.binary() , ) SCREAMING_SNAKE_CASE_ : Tuple = pa.array([None] * len(lowercase__ ) , type=pa.string() ) SCREAMING_SNAKE_CASE_ : Optional[int] = pa.StructArray.from_arrays( [bytes_array, path_array] , ["bytes", "path"] , mask=bytes_array.is_null() ) return array_cast(lowercase__ , self.pa_type ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" @no_op_if_value_is_null def path_to_bytes(lowercase__ ): with xopen(lowercase__ , "rb" ) as f: SCREAMING_SNAKE_CASE_ : List[Any] = f.read() return bytes_ SCREAMING_SNAKE_CASE_ : str = pa.array( [ (path_to_bytes(x["path"] ) if x["bytes"] is None else x["bytes"]) if x is not None else None for x in storage.to_pylist() ] , type=pa.binary() , ) SCREAMING_SNAKE_CASE_ : int = pa.array( [os.path.basename(lowercase__ ) if path is not None else None for path in storage.field("path" ).to_pylist()] , type=pa.string() , ) SCREAMING_SNAKE_CASE_ : Tuple = pa.StructArray.from_arrays([bytes_array, path_array] , ["bytes", "path"] , mask=bytes_array.is_null() ) return array_cast(lowercase__ , self.pa_type ) def __lowerCamelCase ( ) -> List[str]: """simple docstring""" if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support encoding images, please install 'Pillow'." ) global _IMAGE_COMPRESSION_FORMATS if _IMAGE_COMPRESSION_FORMATS is None: PIL.Image.init() SCREAMING_SNAKE_CASE_ : int = list(set(PIL.Image.OPEN.keys() ) & set(PIL.Image.SAVE.keys() ) ) return _IMAGE_COMPRESSION_FORMATS def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : "PIL.Image.Image" ) -> bytes: """simple docstring""" SCREAMING_SNAKE_CASE_ : int = BytesIO() if image.format in list_image_compression_formats(): SCREAMING_SNAKE_CASE_ : List[Any] = image.format else: SCREAMING_SNAKE_CASE_ : Dict = "PNG" if image.mode in ["1", "L", "LA", "RGB", "RGBA"] else "TIFF" image.save(SCREAMING_SNAKE_CASE_ , format=SCREAMING_SNAKE_CASE_ ) return buffer.getvalue() def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : "PIL.Image.Image" ) -> dict: """simple docstring""" if hasattr(SCREAMING_SNAKE_CASE_ , "filename" ) and image.filename != "": return {"path": image.filename, "bytes": None} else: return {"path": None, "bytes": image_to_bytes(SCREAMING_SNAKE_CASE_ )} def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : np.ndarray ) -> dict: """simple docstring""" if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support encoding images, please install 'Pillow'." ) SCREAMING_SNAKE_CASE_ : Optional[int] = array.dtype SCREAMING_SNAKE_CASE_ : Dict = dtype.byteorder if dtype.byteorder != "=" else _NATIVE_BYTEORDER SCREAMING_SNAKE_CASE_ : List[Any] = dtype.kind SCREAMING_SNAKE_CASE_ : Union[str, Any] = dtype.itemsize SCREAMING_SNAKE_CASE_ : List[str] = None # Multi-channel array case (only np.dtype("|u1") is allowed) if array.shape[2:]: SCREAMING_SNAKE_CASE_ : Optional[Any] = np.dtype("|u1" ) if dtype_kind not in ["u", "i"]: raise TypeError( F"Unsupported array dtype {dtype} for image encoding. Only {dest_dtype} is supported for multi-channel arrays." ) if dtype is not dest_dtype: warnings.warn(F"Downcasting array dtype {dtype} to {dest_dtype} to be compatible with 'Pillow'" ) # Exact match elif dtype in _VALID_IMAGE_ARRAY_DTPYES: SCREAMING_SNAKE_CASE_ : str = dtype else: # Downcast the type within the kind (np.can_cast(from_type, to_type, casting="same_kind") doesn't behave as expected, so do it manually) while dtype_itemsize >= 1: SCREAMING_SNAKE_CASE_ : str = dtype_byteorder + dtype_kind + str(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : List[Any] = np.dtype(SCREAMING_SNAKE_CASE_ ) if dest_dtype in _VALID_IMAGE_ARRAY_DTPYES: warnings.warn(F"Downcasting array dtype {dtype} to {dest_dtype} to be compatible with 'Pillow'" ) break else: dtype_itemsize //= 2 if dest_dtype is None: raise TypeError( F"Cannot convert dtype {dtype} to a valid image dtype. Valid image dtypes: {_VALID_IMAGE_ARRAY_DTPYES}" ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = PIL.Image.fromarray(array.astype(SCREAMING_SNAKE_CASE_ ) ) return {"path": None, "bytes": image_to_bytes(SCREAMING_SNAKE_CASE_ )} def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Union[List[str], List[dict], List[np.ndarray], List["PIL.Image.Image"]] ) -> List[dict]: """simple docstring""" if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support encoding images, please install 'Pillow'." ) if objs: SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : List[str] = first_non_null_value(SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): return [{"path": obj, "bytes": None} if obj is not None else None for obj in objs] if isinstance(SCREAMING_SNAKE_CASE_ , np.ndarray ): SCREAMING_SNAKE_CASE_ : Tuple = no_op_if_value_is_null(SCREAMING_SNAKE_CASE_ ) return [obj_to_image_dict_func(SCREAMING_SNAKE_CASE_ ) for obj in objs] elif isinstance(SCREAMING_SNAKE_CASE_ , PIL.Image.Image ): SCREAMING_SNAKE_CASE_ : int = no_op_if_value_is_null(SCREAMING_SNAKE_CASE_ ) return [obj_to_image_dict_func(SCREAMING_SNAKE_CASE_ ) for obj in objs] else: return objs else: return objs
68
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging snake_case_ = logging.get_logger(__name__) snake_case_ = { 'camembert-base': 'https://huggingface.co/camembert-base/resolve/main/config.json', 'umberto-commoncrawl-cased-v1': ( 'https://huggingface.co/Musixmatch/umberto-commoncrawl-cased-v1/resolve/main/config.json' ), 'umberto-wikipedia-uncased-v1': ( 'https://huggingface.co/Musixmatch/umberto-wikipedia-uncased-v1/resolve/main/config.json' ), } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = "camembert" def __init__( self , lowercase__=3_0522 , lowercase__=768 , lowercase__=12 , lowercase__=12 , lowercase__=3072 , lowercase__="gelu" , lowercase__=0.1 , lowercase__=0.1 , lowercase__=512 , lowercase__=2 , lowercase__=0.02 , lowercase__=1e-12 , lowercase__=1 , lowercase__=0 , lowercase__=2 , lowercase__="absolute" , lowercase__=True , lowercase__=None , **lowercase__ , ): """simple docstring""" super().__init__(pad_token_id=lowercase__ , bos_token_id=lowercase__ , eos_token_id=lowercase__ , **lowercase__ ) SCREAMING_SNAKE_CASE_ : Tuple = vocab_size SCREAMING_SNAKE_CASE_ : str = hidden_size SCREAMING_SNAKE_CASE_ : str = num_hidden_layers SCREAMING_SNAKE_CASE_ : Dict = num_attention_heads SCREAMING_SNAKE_CASE_ : Any = hidden_act SCREAMING_SNAKE_CASE_ : Optional[int] = intermediate_size SCREAMING_SNAKE_CASE_ : Optional[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : List[str] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : Optional[Any] = max_position_embeddings SCREAMING_SNAKE_CASE_ : List[str] = type_vocab_size SCREAMING_SNAKE_CASE_ : Tuple = initializer_range SCREAMING_SNAKE_CASE_ : List[Any] = layer_norm_eps SCREAMING_SNAKE_CASE_ : List[Any] = position_embedding_type SCREAMING_SNAKE_CASE_ : Any = use_cache SCREAMING_SNAKE_CASE_ : Optional[int] = classifier_dropout class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): @property def __lowerCamelCase ( self ): """simple docstring""" if self.task == "multiple-choice": SCREAMING_SNAKE_CASE_ : Optional[int] = {0: "batch", 1: "choice", 2: "sequence"} else: SCREAMING_SNAKE_CASE_ : Any = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
68
1
'''simple docstring''' import math import unittest def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int ) -> bool: """simple docstring""" assert isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) and ( number >= 0 ), "'number' must been an int and positive" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(SCREAMING_SNAKE_CASE_ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __lowerCamelCase ( self ): """simple docstring""" self.assertTrue(is_prime(2 ) ) self.assertTrue(is_prime(3 ) ) self.assertTrue(is_prime(5 ) ) self.assertTrue(is_prime(7 ) ) self.assertTrue(is_prime(11 ) ) self.assertTrue(is_prime(13 ) ) self.assertTrue(is_prime(17 ) ) self.assertTrue(is_prime(19 ) ) self.assertTrue(is_prime(23 ) ) self.assertTrue(is_prime(29 ) ) def __lowerCamelCase ( self ): """simple docstring""" with self.assertRaises(lowercase__ ): is_prime(-19 ) self.assertFalse( is_prime(0 ) , "Zero doesn't have any positive factors, primes must have exactly two." , ) self.assertFalse( is_prime(1 ) , "One only has 1 positive factor, primes must have exactly two." , ) self.assertFalse(is_prime(2 * 2 ) ) self.assertFalse(is_prime(2 * 3 ) ) self.assertFalse(is_prime(3 * 3 ) ) self.assertFalse(is_prime(3 * 5 ) ) self.assertFalse(is_prime(3 * 5 * 7 ) ) if __name__ == "__main__": unittest.main()
68
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : list[int] ) -> list[int]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = len(SCREAMING_SNAKE_CASE_ ) for i in range(SCREAMING_SNAKE_CASE_ ): for j in range(i + 1 , SCREAMING_SNAKE_CASE_ ): if numbers[j] < numbers[i]: SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Tuple = numbers[j], numbers[i] return numbers if __name__ == "__main__": snake_case_ = input('Enter numbers separated by a comma:\n').strip() snake_case_ = [int(item) for item in user_input.split(',')] print(exchange_sort(unsorted))
68
1
'''simple docstring''' from __future__ import annotations def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : list[list[int]] ) -> int: """simple docstring""" for i in range(1 , len(matrix[0] ) ): matrix[0][i] += matrix[0][i - 1] # preprocessing the first column for i in range(1 , len(SCREAMING_SNAKE_CASE_ ) ): matrix[i][0] += matrix[i - 1][0] # updating the path cost for current position for i in range(1 , len(SCREAMING_SNAKE_CASE_ ) ): for j in range(1 , len(matrix[0] ) ): matrix[i][j] += min(matrix[i - 1][j] , matrix[i][j - 1] ) return matrix[-1][-1] if __name__ == "__main__": import doctest doctest.testmod()
68
'''simple docstring''' import logging import os import sys from pathlib import Path from unittest.mock import patch from parameterized import parameterized from run_eval import run_generate from run_eval_search import run_search from transformers.testing_utils import CaptureStdout, TestCasePlus, slow from utils import ROUGE_KEYS logging.basicConfig(level=logging.DEBUG) snake_case_ = logging.getLogger() def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Path , SCREAMING_SNAKE_CASE_ : list ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = "\n".join(SCREAMING_SNAKE_CASE_ ) Path(SCREAMING_SNAKE_CASE_ ).open("w" ).writelines(SCREAMING_SNAKE_CASE_ ) snake_case_ = 'patrickvonplaten/t5-tiny-random' snake_case_ = 'sshleifer/bart-tiny-random' snake_case_ = 'sshleifer/tiny-mbart' snake_case_ = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) logging.disable(logging.CRITICAL) # remove noisy download output from tracebacks class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = Path(self.get_auto_remove_tmp_dir() ) / "utest_input.source" SCREAMING_SNAKE_CASE_ : List[str] = input_file_name.parent / "utest_output.txt" assert not output_file_name.exists() SCREAMING_SNAKE_CASE_ : Dict = [" New York (CNN)When Liana Barrientos was 23 years old, she got married in Westchester County."] _dump_articles(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : Tuple = str(Path(self.get_auto_remove_tmp_dir() ) / "scores.json" ) SCREAMING_SNAKE_CASE_ : Tuple = "translation_en_to_de" if model == T5_TINY else "summarization" SCREAMING_SNAKE_CASE_ : Dict = F"\n run_eval_search.py\n {model}\n {input_file_name}\n {output_file_name}\n --score_path {score_path}\n --task {task}\n --num_beams 2\n --length_penalty 2.0\n ".split() with patch.object(lowercase__ , "argv" , lowercase__ ): run_generate() assert Path(lowercase__ ).exists() # os.remove(Path(output_file_name)) def __lowerCamelCase ( self ): """simple docstring""" self.run_eval_tester(lowercase__ ) @parameterized.expand([BART_TINY, MBART_TINY] ) @slow def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" self.run_eval_tester(lowercase__ ) @parameterized.expand([T5_TINY, MBART_TINY] ) @slow def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = Path(self.get_auto_remove_tmp_dir() ) / "utest_input.source" SCREAMING_SNAKE_CASE_ : Optional[Any] = input_file_name.parent / "utest_output.txt" assert not output_file_name.exists() SCREAMING_SNAKE_CASE_ : List[Any] = { "en": ["Machine learning is great, isn't it?", "I like to eat bananas", "Tomorrow is another great day!"], "de": [ "Maschinelles Lernen ist großartig, oder?", "Ich esse gerne Bananen", "Morgen ist wieder ein toller Tag!", ], } SCREAMING_SNAKE_CASE_ : Dict = Path(self.get_auto_remove_tmp_dir() ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = str(tmp_dir / "scores.json" ) SCREAMING_SNAKE_CASE_ : List[Any] = str(tmp_dir / "val.target" ) _dump_articles(lowercase__ , text["en"] ) _dump_articles(lowercase__ , text["de"] ) SCREAMING_SNAKE_CASE_ : List[Any] = "translation_en_to_de" if model == T5_TINY else "summarization" SCREAMING_SNAKE_CASE_ : List[str] = F"\n run_eval_search.py\n {model}\n {str(lowercase__ )}\n {str(lowercase__ )}\n --score_path {score_path}\n --reference_path {reference_path}\n --task {task}\n ".split() testargs.extend(["--search", "num_beams=1:2 length_penalty=0.9:1.0"] ) with patch.object(lowercase__ , "argv" , lowercase__ ): with CaptureStdout() as cs: run_search() SCREAMING_SNAKE_CASE_ : Union[str, Any] = [" num_beams | length_penalty", model, "Best score args"] SCREAMING_SNAKE_CASE_ : Optional[Any] = ["Info"] if "translation" in task: expected_strings.append("bleu" ) else: expected_strings.extend(lowercase__ ) for w in expected_strings: assert w in cs.out for w in un_expected_strings: assert w not in cs.out assert Path(lowercase__ ).exists() os.remove(Path(lowercase__ ) )
68
1
'''simple docstring''' import glob import os import random from string import ascii_lowercase, digits import cva import numpy as np # Parrameters snake_case_ = (7_2_0, 1_2_8_0) # Height, Width snake_case_ = (0.4, 0.6) # if height or width lower than this scale, drop it. snake_case_ = 1 / 1_0_0 snake_case_ = '' snake_case_ = '' snake_case_ = '' snake_case_ = 2_5_0 def __lowerCamelCase ( ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Tuple = get_dataset(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for index in range(SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ : str = random.sample(range(len(SCREAMING_SNAKE_CASE_ ) ) , 4 ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Tuple = update_image_and_anno( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , filter_scale=SCREAMING_SNAKE_CASE_ , ) # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' SCREAMING_SNAKE_CASE_ : int = random_chars(3_2 ) SCREAMING_SNAKE_CASE_ : List[str] = path.split(os.sep )[-1].rsplit("." , 1 )[0] SCREAMING_SNAKE_CASE_ : Optional[int] = F"{OUTPUT_DIR}/{file_name}_MOSAIC_{letter_code}" cva.imwrite(F"{file_root}.jpg" , SCREAMING_SNAKE_CASE_ , [cva.IMWRITE_JPEG_QUALITY, 8_5] ) print(F"Succeeded {index+1}/{NUMBER_IMAGES} with {file_name}" ) SCREAMING_SNAKE_CASE_ : List[str] = [] for anno in new_annos: SCREAMING_SNAKE_CASE_ : Dict = anno[3] - anno[1] SCREAMING_SNAKE_CASE_ : Optional[int] = anno[4] - anno[2] SCREAMING_SNAKE_CASE_ : Optional[Any] = anno[1] + width / 2 SCREAMING_SNAKE_CASE_ : Tuple = anno[2] + height / 2 SCREAMING_SNAKE_CASE_ : int = F"{anno[0]} {x_center} {y_center} {width} {height}" annos_list.append(SCREAMING_SNAKE_CASE_ ) with open(F"{file_root}.txt" , "w" ) as outfile: outfile.write("\n".join(line for line in annos_list ) ) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : str ) -> tuple[list, list]: """simple docstring""" SCREAMING_SNAKE_CASE_ : int = [] SCREAMING_SNAKE_CASE_ : Any = [] for label_file in glob.glob(os.path.join(SCREAMING_SNAKE_CASE_ , "*.txt" ) ): SCREAMING_SNAKE_CASE_ : List[str] = label_file.split(os.sep )[-1].rsplit("." , 1 )[0] with open(SCREAMING_SNAKE_CASE_ ) as in_file: SCREAMING_SNAKE_CASE_ : Union[str, Any] = in_file.readlines() SCREAMING_SNAKE_CASE_ : List[str] = os.path.join(SCREAMING_SNAKE_CASE_ , F"{label_name}.jpg" ) SCREAMING_SNAKE_CASE_ : int = [] for obj_list in obj_lists: SCREAMING_SNAKE_CASE_ : Optional[Any] = obj_list.rstrip("\n" ).split(" " ) SCREAMING_SNAKE_CASE_ : Tuple = float(obj[1] ) - float(obj[3] ) / 2 SCREAMING_SNAKE_CASE_ : List[Any] = float(obj[2] ) - float(obj[4] ) / 2 SCREAMING_SNAKE_CASE_ : Any = float(obj[1] ) + float(obj[3] ) / 2 SCREAMING_SNAKE_CASE_ : Any = float(obj[2] ) + float(obj[4] ) / 2 boxes.append([int(obj[0] ), xmin, ymin, xmax, ymax] ) if not boxes: continue img_paths.append(SCREAMING_SNAKE_CASE_ ) labels.append(SCREAMING_SNAKE_CASE_ ) return img_paths, labels def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : list , SCREAMING_SNAKE_CASE_ : list , SCREAMING_SNAKE_CASE_ : list[int] , SCREAMING_SNAKE_CASE_ : tuple[int, int] , SCREAMING_SNAKE_CASE_ : tuple[float, float] , SCREAMING_SNAKE_CASE_ : float = 0.0 , ) -> tuple[list, list, str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = np.zeros([output_size[0], output_size[1], 3] , dtype=np.uinta ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) SCREAMING_SNAKE_CASE_ : Optional[int] = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) SCREAMING_SNAKE_CASE_ : Any = int(scale_x * output_size[1] ) SCREAMING_SNAKE_CASE_ : str = int(scale_y * output_size[0] ) SCREAMING_SNAKE_CASE_ : Dict = [] SCREAMING_SNAKE_CASE_ : List[str] = [] for i, index in enumerate(SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ : List[Any] = all_img_list[index] path_list.append(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Tuple = all_annos[index] SCREAMING_SNAKE_CASE_ : int = cva.imread(SCREAMING_SNAKE_CASE_ ) if i == 0: # top-left SCREAMING_SNAKE_CASE_ : Optional[Any] = cva.resize(SCREAMING_SNAKE_CASE_ , (divid_point_x, divid_point_y) ) SCREAMING_SNAKE_CASE_ : int = img for bbox in img_annos: SCREAMING_SNAKE_CASE_ : Union[str, Any] = bbox[1] * scale_x SCREAMING_SNAKE_CASE_ : List[str] = bbox[2] * scale_y SCREAMING_SNAKE_CASE_ : Union[str, Any] = bbox[3] * scale_x SCREAMING_SNAKE_CASE_ : Tuple = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 1: # top-right SCREAMING_SNAKE_CASE_ : Tuple = cva.resize(SCREAMING_SNAKE_CASE_ , (output_size[1] - divid_point_x, divid_point_y) ) SCREAMING_SNAKE_CASE_ : Tuple = img for bbox in img_annos: SCREAMING_SNAKE_CASE_ : Any = scale_x + bbox[1] * (1 - scale_x) SCREAMING_SNAKE_CASE_ : Optional[Any] = bbox[2] * scale_y SCREAMING_SNAKE_CASE_ : Optional[int] = scale_x + bbox[3] * (1 - scale_x) SCREAMING_SNAKE_CASE_ : Dict = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 2: # bottom-left SCREAMING_SNAKE_CASE_ : List[str] = cva.resize(SCREAMING_SNAKE_CASE_ , (divid_point_x, output_size[0] - divid_point_y) ) SCREAMING_SNAKE_CASE_ : int = img for bbox in img_annos: SCREAMING_SNAKE_CASE_ : Union[str, Any] = bbox[1] * scale_x SCREAMING_SNAKE_CASE_ : Optional[Any] = scale_y + bbox[2] * (1 - scale_y) SCREAMING_SNAKE_CASE_ : List[Any] = bbox[3] * scale_x SCREAMING_SNAKE_CASE_ : Union[str, Any] = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) else: # bottom-right SCREAMING_SNAKE_CASE_ : Optional[Any] = cva.resize( SCREAMING_SNAKE_CASE_ , (output_size[1] - divid_point_x, output_size[0] - divid_point_y) ) SCREAMING_SNAKE_CASE_ : int = img for bbox in img_annos: SCREAMING_SNAKE_CASE_ : int = scale_x + bbox[1] * (1 - scale_x) SCREAMING_SNAKE_CASE_ : List[Any] = scale_y + bbox[2] * (1 - scale_y) SCREAMING_SNAKE_CASE_ : Optional[Any] = scale_x + bbox[3] * (1 - scale_x) SCREAMING_SNAKE_CASE_ : List[Any] = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) # Remove bounding box small than scale of filter if filter_scale > 0: SCREAMING_SNAKE_CASE_ : Any = [ anno for anno in new_anno if filter_scale < (anno[3] - anno[1]) and filter_scale < (anno[4] - anno[2]) ] return output_img, new_anno, path_list[0] def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int ) -> str: """simple docstring""" assert number_char > 1, "The number of character should greater than 1" SCREAMING_SNAKE_CASE_ : Tuple = ascii_lowercase + digits return "".join(random.choice(SCREAMING_SNAKE_CASE_ ) for _ in range(SCREAMING_SNAKE_CASE_ ) ) if __name__ == "__main__": main() print('DONE ✅')
68
'''simple docstring''' from __future__ import annotations import numpy as np from numpy import floataa from numpy.typing import NDArray def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : NDArray[floataa] , SCREAMING_SNAKE_CASE_ : NDArray[floataa] , SCREAMING_SNAKE_CASE_ : list[int] , SCREAMING_SNAKE_CASE_ : int , ) -> list[float]: """simple docstring""" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : str = coefficient_matrix.shape SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : List[Any] = constant_matrix.shape if rowsa != colsa: SCREAMING_SNAKE_CASE_ : Union[str, Any] = F"Coefficient matrix dimensions must be nxn but received {rowsa}x{colsa}" raise ValueError(SCREAMING_SNAKE_CASE_ ) if colsa != 1: SCREAMING_SNAKE_CASE_ : List[Any] = F"Constant matrix must be nx1 but received {rowsa}x{colsa}" raise ValueError(SCREAMING_SNAKE_CASE_ ) if rowsa != rowsa: SCREAMING_SNAKE_CASE_ : Any = ( "Coefficient and constant matrices dimensions must be nxn and nx1 but " F"received {rowsa}x{colsa} and {rowsa}x{colsa}" ) raise ValueError(SCREAMING_SNAKE_CASE_ ) if len(SCREAMING_SNAKE_CASE_ ) != rowsa: SCREAMING_SNAKE_CASE_ : int = ( "Number of initial values must be equal to number of rows in coefficient " F"matrix but received {len(SCREAMING_SNAKE_CASE_ )} and {rowsa}" ) raise ValueError(SCREAMING_SNAKE_CASE_ ) if iterations <= 0: raise ValueError("Iterations must be at least 1" ) SCREAMING_SNAKE_CASE_ : NDArray[floataa] = np.concatenate( (coefficient_matrix, constant_matrix) , axis=1 ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Any = table.shape strictly_diagonally_dominant(SCREAMING_SNAKE_CASE_ ) # Iterates the whole matrix for given number of times for _ in range(SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ : Tuple = [] for row in range(SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ : Any = 0 for col in range(SCREAMING_SNAKE_CASE_ ): if col == row: SCREAMING_SNAKE_CASE_ : Any = table[row][col] elif col == cols - 1: SCREAMING_SNAKE_CASE_ : Dict = table[row][col] else: temp += (-1) * table[row][col] * init_val[col] SCREAMING_SNAKE_CASE_ : Optional[Any] = (temp + val) / denom new_val.append(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = new_val return [float(SCREAMING_SNAKE_CASE_ ) for i in new_val] def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : NDArray[floataa] ) -> bool: """simple docstring""" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = table.shape SCREAMING_SNAKE_CASE_ : Tuple = True for i in range(0 , SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ : int = 0 for j in range(0 , cols - 1 ): if i == j: continue else: total += table[i][j] if table[i][i] <= total: raise ValueError("Coefficient matrix is not strictly diagonally dominant" ) return is_diagonally_dominant # Test Cases if __name__ == "__main__": import doctest doctest.testmod()
68
1
'''simple docstring''' import math def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int ) -> bool: """simple docstring""" assert isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) and ( number >= 0 ), "'number' must been an int and positive" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or not number % 2: # Negatives, 0, 1 and all even numbers are not primes return False SCREAMING_SNAKE_CASE_ : Optional[Any] = range(3 , int(math.sqrt(SCREAMING_SNAKE_CASE_ ) + 1 ) , 2 ) return not any(not number % i for i in odd_numbers ) def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Union[str, Any]=1 , **SCREAMING_SNAKE_CASE_ : List[Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = factor * value SCREAMING_SNAKE_CASE_ : List[str] = value while not is_prime(SCREAMING_SNAKE_CASE_ ): value += 1 if not ("desc" in kwargs and kwargs["desc"] is True) else -1 if value == first_value_val: return next_prime(value + 1 , **SCREAMING_SNAKE_CASE_ ) return value
68
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int ) -> int: """simple docstring""" return 1 if input_a == input_a else 0 def __lowerCamelCase ( ) -> None: """simple docstring""" assert xnor_gate(0 , 0 ) == 1 assert xnor_gate(0 , 1 ) == 0 assert xnor_gate(1 , 0 ) == 0 assert xnor_gate(1 , 1 ) == 1 if __name__ == "__main__": print(xnor_gate(0, 0)) print(xnor_gate(0, 1)) print(xnor_gate(1, 0)) print(xnor_gate(1, 1))
68
1
'''simple docstring''' import torch from transformers import AutoModel class SCREAMING_SNAKE_CASE__ ( torch.nn.Module ): def __init__( self , lowercase__="sayef/fsner-bert-base-uncased" ): """simple docstring""" super(lowercase__ , self ).__init__() SCREAMING_SNAKE_CASE_ : int = AutoModel.from_pretrained(lowercase__ , return_dict=lowercase__ ) SCREAMING_SNAKE_CASE_ : Tuple = torch.nn.CosineSimilarity(3 , 1e-08 ) SCREAMING_SNAKE_CASE_ : List[Any] = torch.nn.Softmax(dim=1 ) def __lowerCamelCase ( self , **lowercase__ ): """simple docstring""" return self.bert(**lowercase__ ).last_hidden_state def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" return token_embeddings.sum(2 , keepdim=lowercase__ ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__=1 ): """simple docstring""" return self.softmax(T * self.cos(lowercase__ , lowercase__ ) ) def __lowerCamelCase ( self , lowercase__ , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = W_supports["sizes"].tolist() SCREAMING_SNAKE_CASE_ : List[str] = W_supports["start_token_id"].item() SCREAMING_SNAKE_CASE_ : Any = W_supports["end_token_id"].item() del W_supports["sizes"] del W_supports["start_token_id"] del W_supports["end_token_id"] SCREAMING_SNAKE_CASE_ : Any = self.BERT(**lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = self.BERT(**lowercase__ ) SCREAMING_SNAKE_CASE_ : Tuple = None SCREAMING_SNAKE_CASE_ : Any = None SCREAMING_SNAKE_CASE_ : Optional[Any] = W_supports["input_ids"] == start_token_id SCREAMING_SNAKE_CASE_ : str = W_supports["input_ids"] == end_token_id for i, size in enumerate(lowercase__ ): if i == 0: SCREAMING_SNAKE_CASE_ : Tuple = 0 else: SCREAMING_SNAKE_CASE_ : int = support_sizes[i - 1] SCREAMING_SNAKE_CASE_ : Optional[Any] = S[s : s + size][start_token_masks[s : s + size]] SCREAMING_SNAKE_CASE_ : Tuple = S[s : s + size][end_token_masks[s : s + size]] SCREAMING_SNAKE_CASE_ : List[Any] = torch.matmul(q[i] , s_start.T ).sum(1 ).softmax(0 ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.matmul(q[i] , s_end.T ).sum(1 ).softmax(0 ) if p_starts is not None: SCREAMING_SNAKE_CASE_ : List[str] = torch.vstack((p_starts, p_start) ) SCREAMING_SNAKE_CASE_ : int = torch.vstack((p_ends, p_end) ) else: SCREAMING_SNAKE_CASE_ : Optional[int] = p_start SCREAMING_SNAKE_CASE_ : int = p_end return p_starts, p_ends
68
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float , ) -> float: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = [redshift, radiation_density, matter_density, dark_energy] if any(p < 0 for p in parameters ): raise ValueError("All input parameters must be positive" ) if any(p > 1 for p in parameters[1:4] ): raise ValueError("Relative densities cannot be greater than one" ) else: SCREAMING_SNAKE_CASE_ : int = 1 - (matter_density + radiation_density + dark_energy) SCREAMING_SNAKE_CASE_ : List[Any] = ( radiation_density * (redshift + 1) ** 4 + matter_density * (redshift + 1) ** 3 + curvature * (redshift + 1) ** 2 + dark_energy ) SCREAMING_SNAKE_CASE_ : Dict = hubble_constant * e_a ** (1 / 2) return hubble if __name__ == "__main__": import doctest # run doctest doctest.testmod() # demo LCDM approximation snake_case_ = 0.3 print( hubble_parameter( hubble_constant=6_8.3, radiation_density=1E-4, matter_density=matter_density, dark_energy=1 - matter_density, redshift=0, ) )
68
1
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import convert_to_rgb, normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL snake_case_ = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = ["pixel_values"] def __init__( self , lowercase__ = True , lowercase__ = None , lowercase__ = PILImageResampling.BICUBIC , lowercase__ = True , lowercase__ = 1 / 255 , lowercase__ = True , lowercase__ = None , lowercase__ = None , lowercase__ = True , **lowercase__ , ): """simple docstring""" super().__init__(**lowercase__ ) SCREAMING_SNAKE_CASE_ : Tuple = size if size is not None else {"height": 384, "width": 384} SCREAMING_SNAKE_CASE_ : int = get_size_dict(lowercase__ , default_to_square=lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = do_resize SCREAMING_SNAKE_CASE_ : Union[str, Any] = size SCREAMING_SNAKE_CASE_ : Union[str, Any] = resample SCREAMING_SNAKE_CASE_ : Dict = do_rescale SCREAMING_SNAKE_CASE_ : Optional[Any] = rescale_factor SCREAMING_SNAKE_CASE_ : Any = do_normalize SCREAMING_SNAKE_CASE_ : Optional[int] = image_mean if image_mean is not None else OPENAI_CLIP_MEAN SCREAMING_SNAKE_CASE_ : str = image_std if image_std is not None else OPENAI_CLIP_STD SCREAMING_SNAKE_CASE_ : Optional[int] = do_convert_rgb def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ = PILImageResampling.BICUBIC , lowercase__ = None , **lowercase__ , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = get_size_dict(lowercase__ , default_to_square=lowercase__ ) if "height" not in size or "width" not in size: raise ValueError(F"The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}" ) SCREAMING_SNAKE_CASE_ : Optional[Any] = (size["height"], size["width"]) return resize(lowercase__ , size=lowercase__ , resample=lowercase__ , data_format=lowercase__ , **lowercase__ ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ = None , **lowercase__ , ): """simple docstring""" return rescale(lowercase__ , scale=lowercase__ , data_format=lowercase__ , **lowercase__ ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ = None , **lowercase__ , ): """simple docstring""" return normalize(lowercase__ , mean=lowercase__ , std=lowercase__ , data_format=lowercase__ , **lowercase__ ) def __lowerCamelCase ( self , lowercase__ , lowercase__ = None , lowercase__ = None , lowercase__ = None , lowercase__ = None , lowercase__ = None , lowercase__ = None , lowercase__ = None , lowercase__ = None , lowercase__ = None , lowercase__ = None , lowercase__ = ChannelDimension.FIRST , **lowercase__ , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE_ : int = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE_ : List[Any] = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE_ : Dict = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE_ : int = do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE_ : Optional[Any] = image_mean if image_mean is not None else self.image_mean SCREAMING_SNAKE_CASE_ : Union[str, Any] = image_std if image_std is not None else self.image_std SCREAMING_SNAKE_CASE_ : List[str] = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb SCREAMING_SNAKE_CASE_ : Union[str, Any] = size if size is not None else self.size SCREAMING_SNAKE_CASE_ : str = get_size_dict(lowercase__ , default_to_square=lowercase__ ) SCREAMING_SNAKE_CASE_ : Tuple = make_list_of_images(lowercase__ ) if not valid_images(lowercase__ ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None or resample is None: raise ValueError("Size and resample must be specified if do_resize is True." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) # PIL RGBA images are converted to RGB if do_convert_rgb: SCREAMING_SNAKE_CASE_ : str = [convert_to_rgb(lowercase__ ) for image in images] # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE_ : Optional[Any] = [to_numpy_array(lowercase__ ) for image in images] if do_resize: SCREAMING_SNAKE_CASE_ : int = [self.resize(image=lowercase__ , size=lowercase__ , resample=lowercase__ ) for image in images] if do_rescale: SCREAMING_SNAKE_CASE_ : Optional[int] = [self.rescale(image=lowercase__ , scale=lowercase__ ) for image in images] if do_normalize: SCREAMING_SNAKE_CASE_ : Tuple = [self.normalize(image=lowercase__ , mean=lowercase__ , std=lowercase__ ) for image in images] SCREAMING_SNAKE_CASE_ : Optional[int] = [to_channel_dimension_format(lowercase__ , lowercase__ ) for image in images] SCREAMING_SNAKE_CASE_ : int = BatchFeature(data={"pixel_values": images} , tensor_type=lowercase__ ) return encoded_outputs
68
'''simple docstring''' import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.generation import DisjunctiveConstraint @require_torch class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = [[1, 2, 4], [1, 2, 3, 4]] SCREAMING_SNAKE_CASE_ : Any = DisjunctiveConstraint(lowercase__ ) self.assertTrue(isinstance(dc.token_ids , lowercase__ ) ) with self.assertRaises(lowercase__ ): DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]] ) ) with self.assertRaises(lowercase__ ): DisjunctiveConstraint([torch.LongTensor([1, 2, 4] ), torch.LongTensor([1, 2, 3, 4, 5] )] ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = [[1, 2], [1, 2, 3, 4]] with self.assertRaises(lowercase__ ): DisjunctiveConstraint(lowercase__ ) # fails here def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = [[1, 2, 3], [1, 2, 4]] SCREAMING_SNAKE_CASE_ : Optional[Any] = DisjunctiveConstraint(lowercase__ ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = dc.update(1 ) SCREAMING_SNAKE_CASE_ : Optional[int] = stepped is True and completed is False and reset is False self.assertTrue(lowercase__ ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Tuple = dc.update(2 ) SCREAMING_SNAKE_CASE_ : Tuple = stepped is True and completed is False and reset is False self.assertTrue(lowercase__ ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Any = dc.update(3 ) SCREAMING_SNAKE_CASE_ : Tuple = stepped is True and completed is True and reset is False self.assertTrue(lowercase__ ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 3] ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]] SCREAMING_SNAKE_CASE_ : Dict = DisjunctiveConstraint(lowercase__ ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : List[Any] = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = dc.update(4 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2, 4] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : List[Any] = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 4, 5] ) dc.reset() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Tuple = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 3 ) self.assertTrue(dc.current_seq == [1] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : str = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 2 ) self.assertTrue(dc.current_seq == [1, 2] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : str = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.remaining() == 0 ) self.assertTrue(dc.current_seq == [1, 2, 5] )
68
1
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_bart import BartTokenizer snake_case_ = logging.get_logger(__name__) snake_case_ = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'} # See all BART models at https://huggingface.co/models?filter=bart snake_case_ = { 'vocab_file': { 'facebook/bart-base': 'https://huggingface.co/facebook/bart-base/resolve/main/vocab.json', 'facebook/bart-large': 'https://huggingface.co/facebook/bart-large/resolve/main/vocab.json', 'facebook/bart-large-mnli': 'https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json', 'facebook/bart-large-cnn': 'https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json', 'facebook/bart-large-xsum': 'https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json', 'yjernite/bart_eli5': 'https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json', }, 'merges_file': { 'facebook/bart-base': 'https://huggingface.co/facebook/bart-base/resolve/main/merges.txt', 'facebook/bart-large': 'https://huggingface.co/facebook/bart-large/resolve/main/merges.txt', 'facebook/bart-large-mnli': 'https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt', 'facebook/bart-large-cnn': 'https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt', 'facebook/bart-large-xsum': 'https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt', 'yjernite/bart_eli5': 'https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt', }, 'tokenizer_file': { 'facebook/bart-base': 'https://huggingface.co/facebook/bart-base/resolve/main/tokenizer.json', 'facebook/bart-large': 'https://huggingface.co/facebook/bart-large/resolve/main/tokenizer.json', 'facebook/bart-large-mnli': 'https://huggingface.co/facebook/bart-large-mnli/resolve/main/tokenizer.json', 'facebook/bart-large-cnn': 'https://huggingface.co/facebook/bart-large-cnn/resolve/main/tokenizer.json', 'facebook/bart-large-xsum': 'https://huggingface.co/facebook/bart-large-xsum/resolve/main/tokenizer.json', 'yjernite/bart_eli5': 'https://huggingface.co/yjernite/bart_eli5/resolve/main/tokenizer.json', }, } snake_case_ = { 'facebook/bart-base': 1_0_2_4, 'facebook/bart-large': 1_0_2_4, 'facebook/bart-large-mnli': 1_0_2_4, 'facebook/bart-large-cnn': 1_0_2_4, 'facebook/bart-large-xsum': 1_0_2_4, 'yjernite/bart_eli5': 1_0_2_4, } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = VOCAB_FILES_NAMES _A = PRETRAINED_VOCAB_FILES_MAP _A = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _A = ["input_ids", "attention_mask"] _A = BartTokenizer def __init__( self , lowercase__=None , lowercase__=None , lowercase__=None , lowercase__="replace" , lowercase__="<s>" , lowercase__="</s>" , lowercase__="</s>" , lowercase__="<s>" , lowercase__="<unk>" , lowercase__="<pad>" , lowercase__="<mask>" , lowercase__=False , lowercase__=True , **lowercase__ , ): """simple docstring""" super().__init__( lowercase__ , lowercase__ , tokenizer_file=lowercase__ , errors=lowercase__ , bos_token=lowercase__ , eos_token=lowercase__ , sep_token=lowercase__ , cls_token=lowercase__ , unk_token=lowercase__ , pad_token=lowercase__ , mask_token=lowercase__ , add_prefix_space=lowercase__ , trim_offsets=lowercase__ , **lowercase__ , ) SCREAMING_SNAKE_CASE_ : List[Any] = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("add_prefix_space" , lowercase__ ) != add_prefix_space: SCREAMING_SNAKE_CASE_ : Dict = getattr(lowercase__ , pre_tok_state.pop("type" ) ) SCREAMING_SNAKE_CASE_ : Optional[int] = add_prefix_space SCREAMING_SNAKE_CASE_ : int = pre_tok_class(**lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = add_prefix_space # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__` SCREAMING_SNAKE_CASE_ : Dict = "post_processor" SCREAMING_SNAKE_CASE_ : Dict = getattr(self.backend_tokenizer , lowercase__ , lowercase__ ) if tokenizer_component_instance: SCREAMING_SNAKE_CASE_ : Union[str, Any] = json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: SCREAMING_SNAKE_CASE_ : List[Any] = tuple(state["sep"] ) if "cls" in state: SCREAMING_SNAKE_CASE_ : Optional[int] = tuple(state["cls"] ) SCREAMING_SNAKE_CASE_ : List[str] = False if state.get("add_prefix_space" , lowercase__ ) != add_prefix_space: SCREAMING_SNAKE_CASE_ : Optional[int] = add_prefix_space SCREAMING_SNAKE_CASE_ : List[str] = True if state.get("trim_offsets" , lowercase__ ) != trim_offsets: SCREAMING_SNAKE_CASE_ : List[str] = trim_offsets SCREAMING_SNAKE_CASE_ : Optional[Any] = True if changes_to_apply: SCREAMING_SNAKE_CASE_ : str = getattr(lowercase__ , state.pop("type" ) ) SCREAMING_SNAKE_CASE_ : str = component_class(**lowercase__ ) setattr(self.backend_tokenizer , lowercase__ , lowercase__ ) @property def __lowerCamelCase ( self ): """simple docstring""" if self._mask_token is None: if self.verbose: logger.error("Using mask_token, but it is not set yet." ) return None return str(self._mask_token ) @mask_token.setter def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = AddedToken(lowercase__ , lstrip=lowercase__ , rstrip=lowercase__ ) if isinstance(lowercase__ , lowercase__ ) else value SCREAMING_SNAKE_CASE_ : List[str] = value def __lowerCamelCase ( self , *lowercase__ , **lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = kwargs.get("is_split_into_words" , lowercase__ ) if is_split_into_words and not self.add_prefix_space: raise ValueError( F"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*lowercase__ , **lowercase__ ) def __lowerCamelCase ( self , *lowercase__ , **lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = kwargs.get("is_split_into_words" , lowercase__ ) if is_split_into_words and not self.add_prefix_space: raise ValueError( F"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " "to use it with pretokenized inputs." ) return super()._encode_plus(*lowercase__ , **lowercase__ ) def __lowerCamelCase ( self , lowercase__ , lowercase__ = None ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = self._tokenizer.model.save(lowercase__ , name=lowercase__ ) return tuple(lowercase__ ) def __lowerCamelCase ( self , lowercase__ , lowercase__=None ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def __lowerCamelCase ( self , lowercase__ , lowercase__ = None ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int = [self.sep_token_id] SCREAMING_SNAKE_CASE_ : str = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
68
'''simple docstring''' import unittest import torch from diffusers import VQModel from diffusers.utils import floats_tensor, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,_UpperCAmelCase,unittest.TestCase ): _A = VQModel _A = "sample" @property def __lowerCamelCase ( self , lowercase__=(32, 32) ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = 4 SCREAMING_SNAKE_CASE_ : str = 3 SCREAMING_SNAKE_CASE_ : str = floats_tensor((batch_size, num_channels) + sizes ).to(lowercase__ ) return {"sample": image} @property def __lowerCamelCase ( self ): """simple docstring""" return (3, 32, 32) @property def __lowerCamelCase ( self ): """simple docstring""" return (3, 32, 32) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = { "block_out_channels": [32, 64], "in_channels": 3, "out_channels": 3, "down_block_types": ["DownEncoderBlock2D", "DownEncoderBlock2D"], "up_block_types": ["UpDecoderBlock2D", "UpDecoderBlock2D"], "latent_channels": 3, } SCREAMING_SNAKE_CASE_ : int = self.dummy_input return init_dict, inputs_dict def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : int = VQModel.from_pretrained("fusing/vqgan-dummy" , output_loading_info=lowercase__ ) self.assertIsNotNone(lowercase__ ) self.assertEqual(len(loading_info["missing_keys"] ) , 0 ) model.to(lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = VQModel.from_pretrained("fusing/vqgan-dummy" ) model.to(lowercase__ ).eval() torch.manual_seed(0 ) if torch.cuda.is_available(): torch.cuda.manual_seed_all(0 ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.randn(1 , model.config.in_channels , model.config.sample_size , model.config.sample_size ) SCREAMING_SNAKE_CASE_ : str = image.to(lowercase__ ) with torch.no_grad(): SCREAMING_SNAKE_CASE_ : int = model(lowercase__ ).sample SCREAMING_SNAKE_CASE_ : Any = output[0, -1, -3:, -3:].flatten().cpu() # fmt: off SCREAMING_SNAKE_CASE_ : Optional[Any] = torch.tensor([-0.0153, -0.4044, -0.1880, -0.5161, -0.2418, -0.4072, -0.1612, -0.0633, -0.0143] ) # fmt: on self.assertTrue(torch.allclose(lowercase__ , lowercase__ , atol=1e-3 ) )
68
1
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : str ) -> List[str]: """simple docstring""" assert x is not None assert y is not None SCREAMING_SNAKE_CASE_ : Optional[Any] = len(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = len(SCREAMING_SNAKE_CASE_ ) # declaring the array for storing the dp values SCREAMING_SNAKE_CASE_ : int = [[0] * (n + 1) for _ in range(m + 1 )] # noqa: E741 for i in range(1 , m + 1 ): for j in range(1 , n + 1 ): SCREAMING_SNAKE_CASE_ : Any = 1 if x[i - 1] == y[j - 1] else 0 SCREAMING_SNAKE_CASE_ : Optional[Any] = max(l[i - 1][j] , l[i][j - 1] , l[i - 1][j - 1] + match ) SCREAMING_SNAKE_CASE_ : Optional[int] = "" SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : int = m, n while i > 0 and j > 0: SCREAMING_SNAKE_CASE_ : Any = 1 if x[i - 1] == y[j - 1] else 0 if l[i][j] == l[i - 1][j - 1] + match: if match == 1: SCREAMING_SNAKE_CASE_ : List[str] = x[i - 1] + seq i -= 1 j -= 1 elif l[i][j] == l[i - 1][j]: i -= 1 else: j -= 1 return l[m][n], seq if __name__ == "__main__": snake_case_ = 'AGGTAB' snake_case_ = 'GXTXAYB' snake_case_ = 4 snake_case_ = 'GTAB' snake_case_ , snake_case_ = longest_common_subsequence(a, b) print('len =', ln, ', sub-sequence =', subseq) import doctest doctest.testmod()
68
'''simple docstring''' import os import unittest from huggingface_hub.utils import are_progress_bars_disabled import transformers.models.bart.tokenization_bart from transformers import logging from transformers.testing_utils import CaptureLogger, mockenv, mockenv_context from transformers.utils.logging import disable_progress_bar, enable_progress_bar class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = logging.get_logger() # the current default level is logging.WARNING SCREAMING_SNAKE_CASE_ : Optional[int] = logging.get_verbosity() logging.set_verbosity_error() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_warning() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_info() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_debug() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) # restore to the original level logging.set_verbosity(lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = logging.get_verbosity() SCREAMING_SNAKE_CASE_ : List[Any] = logging.get_logger("transformers.models.bart.tokenization_bart" ) SCREAMING_SNAKE_CASE_ : List[Any] = "Testing 1, 2, 3" # should be able to log warnings (if default settings weren't overridden by `pytest --log-level-all`) if level_origin <= logging.WARNING: with CaptureLogger(lowercase__ ) as cl: logger.warning(lowercase__ ) self.assertEqual(cl.out , msg + "\n" ) # this is setting the level for all of `transformers.*` loggers logging.set_verbosity_error() # should not be able to log warnings with CaptureLogger(lowercase__ ) as cl: logger.warning(lowercase__ ) self.assertEqual(cl.out , "" ) # should be able to log warnings again logging.set_verbosity_warning() with CaptureLogger(lowercase__ ) as cl: logger.warning(lowercase__ ) self.assertEqual(cl.out , msg + "\n" ) # restore to the original level logging.set_verbosity(lowercase__ ) @mockenv(TRANSFORMERS_VERBOSITY="error" ) def __lowerCamelCase ( self ): """simple docstring""" transformers.utils.logging._reset_library_root_logger() # this action activates the env var SCREAMING_SNAKE_CASE_ : Tuple = logging.get_logger("transformers.models.bart.tokenization_bart" ) SCREAMING_SNAKE_CASE_ : int = os.getenv("TRANSFORMERS_VERBOSITY" , lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = logging.log_levels[env_level_str] SCREAMING_SNAKE_CASE_ : str = logging.get_verbosity() self.assertEqual( lowercase__ , lowercase__ , F"TRANSFORMERS_VERBOSITY={env_level_str}/{env_level}, but internal verbosity is {current_level}" , ) # restore to the original level SCREAMING_SNAKE_CASE_ : Optional[int] = "" transformers.utils.logging._reset_library_root_logger() @mockenv(TRANSFORMERS_VERBOSITY="super-error" ) def __lowerCamelCase ( self ): """simple docstring""" transformers.utils.logging._reset_library_root_logger() SCREAMING_SNAKE_CASE_ : List[Any] = logging.logging.getLogger() with CaptureLogger(lowercase__ ) as cl: # this action activates the env var logging.get_logger("transformers.models.bart.tokenization_bart" ) self.assertIn("Unknown option TRANSFORMERS_VERBOSITY=super-error" , cl.out ) # no need to restore as nothing was changed def __lowerCamelCase ( self ): """simple docstring""" transformers.utils.logging._reset_library_root_logger() SCREAMING_SNAKE_CASE_ : str = logging.get_logger("transformers.models.bart.tokenization_bart" ) SCREAMING_SNAKE_CASE_ : List[Any] = "Testing 1, 2, 3" with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS="1" ): # nothing should be logged as env var disables this method with CaptureLogger(lowercase__ ) as cl: logger.warning_advice(lowercase__ ) self.assertEqual(cl.out , "" ) with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS="" ): # should log normally as TRANSFORMERS_NO_ADVISORY_WARNINGS is unset with CaptureLogger(lowercase__ ) as cl: logger.warning_advice(lowercase__ ) self.assertEqual(cl.out , msg + "\n" ) def __lowerCamelCase ( ) -> Optional[int]: """simple docstring""" disable_progress_bar() assert are_progress_bars_disabled() enable_progress_bar() assert not are_progress_bars_disabled()
68
1
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Dict ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = len(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : str = sum(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : str = [[False for x in range(s + 1 )] for y in range(n + 1 )] for i in range(1 , n + 1 ): SCREAMING_SNAKE_CASE_ : List[Any] = True for i in range(1 , s + 1 ): SCREAMING_SNAKE_CASE_ : Optional[Any] = False for i in range(1 , n + 1 ): for j in range(1 , s + 1 ): SCREAMING_SNAKE_CASE_ : List[str] = dp[i][j - 1] if arr[i - 1] <= j: SCREAMING_SNAKE_CASE_ : List[Any] = dp[i][j] or dp[i - 1][j - arr[i - 1]] for j in range(int(s / 2 ) , -1 , -1 ): if dp[n][j] is True: SCREAMING_SNAKE_CASE_ : str = s - 2 * j break return diff
68
'''simple docstring''' import json import os import tempfile from unittest.mock import patch import torch from torch.utils.data import DataLoader, TensorDataset from accelerate import DistributedType, infer_auto_device_map, init_empty_weights from accelerate.accelerator import Accelerator from accelerate.state import GradientState, PartialState from accelerate.test_utils import require_bnb, require_multi_gpu, slow from accelerate.test_utils.testing import AccelerateTestCase, require_cuda from accelerate.utils import patch_environment def __lowerCamelCase ( ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = torch.nn.Linear(2 , 4 ) SCREAMING_SNAKE_CASE_ : List[Any] = torch.optim.AdamW(model.parameters() , lr=1.0 ) SCREAMING_SNAKE_CASE_ : Any = torch.optim.lr_scheduler.OneCycleLR(SCREAMING_SNAKE_CASE_ , max_lr=0.01 , steps_per_epoch=2 , epochs=1 ) SCREAMING_SNAKE_CASE_ : Dict = DataLoader(TensorDataset(torch.tensor([1, 2, 3] ) ) ) SCREAMING_SNAKE_CASE_ : Tuple = DataLoader(TensorDataset(torch.tensor([4, 5, 6] ) ) ) return model, optimizer, scheduler, train_dl, valid_dl def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : List[str] ) -> Tuple: """simple docstring""" return (model.weight.abs().sum() + model.bias.abs().sum()).item() def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : Any ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : str = torch.nn.Linear(*tuple(model.weight.T.shape ) ).state_dict() model.load_state_dict(SCREAMING_SNAKE_CASE_ ) class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): @require_cuda def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = Accelerator() assert PartialState._shared_state["_cpu"] is False assert PartialState._shared_state["device"].type == "cuda" with self.assertRaises(lowercase__ ): SCREAMING_SNAKE_CASE_ : List[Any] = Accelerator(cpu=lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = Accelerator() SCREAMING_SNAKE_CASE_ : Any = GradientState() assert state.num_steps == 1 SCREAMING_SNAKE_CASE_ : Union[str, Any] = 4 assert state.num_steps == 4 assert state.sync_gradients is True SCREAMING_SNAKE_CASE_ : Optional[int] = False assert state.sync_gradients is False GradientState._reset_state() def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[int] = create_components() ( ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ( SCREAMING_SNAKE_CASE_ ), ) : Optional[Any] = accelerator.prepare(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) self.assertTrue(prepared_model in accelerator._models ) self.assertTrue(prepared_optimizer in accelerator._optimizers ) self.assertTrue(prepared_scheduler in accelerator._schedulers ) self.assertTrue(prepared_train_dl in accelerator._dataloaders ) self.assertTrue(prepared_valid_dl in accelerator._dataloaders ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : str = create_components() accelerator.prepare(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) accelerator.free_memory() self.assertTrue(len(accelerator._models ) == 0 ) self.assertTrue(len(accelerator._optimizers ) == 0 ) self.assertTrue(len(accelerator._schedulers ) == 0 ) self.assertTrue(len(accelerator._dataloaders ) == 0 ) def __lowerCamelCase ( self ): """simple docstring""" PartialState._reset_state() # Mock torch.cuda.set_device to avoid an exception as the device doesn't exist def noop(*lowercase__ , **lowercase__ ): pass with patch("torch.cuda.set_device" , lowercase__ ), patch_environment(ACCELERATE_TORCH_DEVICE="cuda:64" ): SCREAMING_SNAKE_CASE_ : List[str] = Accelerator() self.assertEqual(str(accelerator.state.device ) , "cuda:64" ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = create_components() accelerator.prepare(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[int] = get_signature(lowercase__ ) with tempfile.TemporaryDirectory() as tmpdirname: accelerator.save_state(lowercase__ ) # make sure random weights don't match load_random_weights(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) > 1e-3 ) # make sure loaded weights match accelerator.load_state(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) < 1e-3 ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[int] = create_components() accelerator.prepare(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = get_signature(lowercase__ ) # saving hook def save_config(lowercase__ , lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE_ : Optional[Any] = {"class_name": models[0].__class__.__name__} with open(os.path.join(lowercase__ , "data.json" ) , "w" ) as f: json.dump(lowercase__ , lowercase__ ) # loading hook def load_config(lowercase__ , lowercase__ ): with open(os.path.join(lowercase__ , "data.json" ) , "r" ) as f: SCREAMING_SNAKE_CASE_ : Any = json.load(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = config["class_name"] SCREAMING_SNAKE_CASE_ : Dict = accelerator.register_save_state_pre_hook(lowercase__ ) SCREAMING_SNAKE_CASE_ : Optional[Any] = accelerator.register_load_state_pre_hook(lowercase__ ) with tempfile.TemporaryDirectory() as tmpdirname: accelerator.save_state(lowercase__ ) # make sure random weights don't match with hooks load_random_weights(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) > 1e-3 ) # random class name to verify correct one is loaded SCREAMING_SNAKE_CASE_ : Union[str, Any] = "random" # make sure loaded weights match with hooks accelerator.load_state(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) < 1e-3 ) # mode.class_name is loaded from config self.assertTrue(model.class_name == model.__class__.__name__ ) # remove hooks save_hook.remove() load_hook.remove() with tempfile.TemporaryDirectory() as tmpdirname: accelerator.save_state(lowercase__ ) # make sure random weights don't match with hooks removed load_random_weights(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) > 1e-3 ) # random class name to verify correct one is loaded SCREAMING_SNAKE_CASE_ : Tuple = "random" # make sure loaded weights match with hooks removed accelerator.load_state(lowercase__ ) self.assertTrue(abs(model_signature - get_signature(lowercase__ ) ) < 1e-3 ) # mode.class_name is NOT loaded from config self.assertTrue(model.class_name != model.__class__.__name__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Tuple = create_components() SCREAMING_SNAKE_CASE_ : Union[str, Any] = None # This should work SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[int] = accelerator.prepare( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) self.assertTrue(dummy_obj is None ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = Accelerator() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = create_components() SCREAMING_SNAKE_CASE_ : Union[str, Any] = [1, 2, 3] # This should work SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : int = accelerator.prepare( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Dummy object should have `_is_accelerate_prepared` set to `True`" , ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Model is missing `_is_accelerator_prepared` or is set to `False`" , ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Optimizer is missing `_is_accelerator_prepared` or is set to `False`" , ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Scheduler is missing `_is_accelerator_prepared` or is set to `False`" , ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Train Dataloader is missing `_is_accelerator_prepared` or is set to `False`" , ) self.assertEqual( getattr(lowercase__ , "_is_accelerate_prepared" , lowercase__ ) , lowercase__ , "Valid Dataloader is missing `_is_accelerator_prepared` or is set to `False`" , ) @slow @require_bnb def __lowerCamelCase ( self ): """simple docstring""" from transformers import AutoModelForCausalLM SCREAMING_SNAKE_CASE_ : Optional[int] = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , load_in_abit=lowercase__ , device_map={"": 0} , ) SCREAMING_SNAKE_CASE_ : Optional[int] = Accelerator() # This should work SCREAMING_SNAKE_CASE_ : List[Any] = accelerator.prepare(lowercase__ ) @slow @require_bnb def __lowerCamelCase ( self ): """simple docstring""" from transformers import AutoModelForCausalLM SCREAMING_SNAKE_CASE_ : Optional[Any] = Accelerator() with init_empty_weights(): SCREAMING_SNAKE_CASE_ : Tuple = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , ) model.tie_weights() SCREAMING_SNAKE_CASE_ : Optional[Any] = infer_auto_device_map(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = "cpu" SCREAMING_SNAKE_CASE_ : Tuple = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , device_map=lowercase__ , load_in_abit=lowercase__ , llm_inta_enable_fpaa_cpu_offload=lowercase__ ) # This should not work and get value error with self.assertRaises(lowercase__ ): SCREAMING_SNAKE_CASE_ : str = accelerator.prepare(lowercase__ ) @slow @require_bnb @require_multi_gpu def __lowerCamelCase ( self ): """simple docstring""" from transformers import AutoModelForCausalLM SCREAMING_SNAKE_CASE_ : str = {"distributed_type": DistributedType.MULTI_GPU} with init_empty_weights(): SCREAMING_SNAKE_CASE_ : Optional[int] = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , ) model.tie_weights() SCREAMING_SNAKE_CASE_ : str = infer_auto_device_map(lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = 1 SCREAMING_SNAKE_CASE_ : str = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , load_in_abit=lowercase__ , device_map=lowercase__ , ) SCREAMING_SNAKE_CASE_ : Any = Accelerator() # This should not work and get value error with self.assertRaises(lowercase__ ): SCREAMING_SNAKE_CASE_ : Tuple = accelerator.prepare(lowercase__ ) PartialState._reset_state() @slow @require_bnb @require_multi_gpu def __lowerCamelCase ( self ): """simple docstring""" from transformers import AutoModelForCausalLM with init_empty_weights(): SCREAMING_SNAKE_CASE_ : Optional[int] = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , ) SCREAMING_SNAKE_CASE_ : Optional[Any] = infer_auto_device_map(lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = 1 SCREAMING_SNAKE_CASE_ : str = AutoModelForCausalLM.from_pretrained( "EleutherAI/gpt-neo-125m" , load_in_abit=lowercase__ , device_map=lowercase__ , ) SCREAMING_SNAKE_CASE_ : Any = Accelerator() # This should work SCREAMING_SNAKE_CASE_ : Optional[int] = accelerator.prepare(lowercase__ ) @require_cuda def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = torch.nn.Linear(10 , 10 ) SCREAMING_SNAKE_CASE_ : Optional[int] = torch.optim.SGD(model.parameters() , lr=0.01 ) SCREAMING_SNAKE_CASE_ : Tuple = Accelerator(cpu=lowercase__ ) SCREAMING_SNAKE_CASE_ : Dict = accelerator.prepare(lowercase__ )
68
1
'''simple docstring''' import copy from typing import TYPE_CHECKING, Any, Mapping, Optional, OrderedDict from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto.configuration_auto import AutoConfig if TYPE_CHECKING: from ... import PreTrainedTokenizerBase, TensorType snake_case_ = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = "vision-encoder-decoder" _A = True def __init__( self , **lowercase__ ): """simple docstring""" super().__init__(**lowercase__ ) if "encoder" not in kwargs or "decoder" not in kwargs: raise ValueError( F"A configuraton of type {self.model_type} cannot be instantiated because " F"not both `encoder` and `decoder` sub-configurations are passed, but only {kwargs}" ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = kwargs.pop("encoder" ) SCREAMING_SNAKE_CASE_ : str = encoder_config.pop("model_type" ) SCREAMING_SNAKE_CASE_ : str = kwargs.pop("decoder" ) SCREAMING_SNAKE_CASE_ : Optional[int] = decoder_config.pop("model_type" ) SCREAMING_SNAKE_CASE_ : Dict = AutoConfig.for_model(lowercase__ , **lowercase__ ) SCREAMING_SNAKE_CASE_ : List[Any] = AutoConfig.for_model(lowercase__ , **lowercase__ ) SCREAMING_SNAKE_CASE_ : List[str] = True @classmethod def __lowerCamelCase ( cls , lowercase__ , lowercase__ , **lowercase__ ): """simple docstring""" logger.info("Setting `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config" ) SCREAMING_SNAKE_CASE_ : Dict = True SCREAMING_SNAKE_CASE_ : List[Any] = True return cls(encoder=encoder_config.to_dict() , decoder=decoder_config.to_dict() , **lowercase__ ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE_ : List[Any] = self.encoder.to_dict() SCREAMING_SNAKE_CASE_ : List[Any] = self.decoder.to_dict() SCREAMING_SNAKE_CASE_ : Tuple = self.__class__.model_type return output class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = version.parse("1.11" ) @property def __lowerCamelCase ( self ): """simple docstring""" return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ] ) @property def __lowerCamelCase ( self ): """simple docstring""" return 1e-4 @property def __lowerCamelCase ( self ): """simple docstring""" return OrderedDict({"last_hidden_state": {0: "batch", 1: "encoder_sequence"}} ) class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): @property def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = OrderedDict() SCREAMING_SNAKE_CASE_ : List[str] = {0: "batch", 1: "past_decoder_sequence + sequence"} SCREAMING_SNAKE_CASE_ : Optional[Any] = {0: "batch", 1: "past_decoder_sequence + sequence"} SCREAMING_SNAKE_CASE_ : List[Any] = {0: "batch", 1: "encoder_sequence"} return common_inputs def __lowerCamelCase ( self , lowercase__ , lowercase__ = -1 , lowercase__ = -1 , lowercase__ = False , lowercase__ = None , ): """simple docstring""" import torch SCREAMING_SNAKE_CASE_ : Optional[int] = OrderedDict() SCREAMING_SNAKE_CASE_ : Any = super().generate_dummy_inputs( lowercase__ , batch_size=lowercase__ , seq_length=lowercase__ , is_pair=lowercase__ , framework=lowercase__ ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : List[str] = dummy_input["input_ids"].shape SCREAMING_SNAKE_CASE_ : Tuple = (batch, encoder_sequence, self._config.encoder_hidden_size) SCREAMING_SNAKE_CASE_ : Union[str, Any] = dummy_input.pop("input_ids" ) SCREAMING_SNAKE_CASE_ : Tuple = dummy_input.pop("attention_mask" ) SCREAMING_SNAKE_CASE_ : List[str] = torch.zeros(lowercase__ ) return common_inputs class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): @property def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" return VisionEncoderDecoderEncoderOnnxConfig(lowercase__ ) def __lowerCamelCase ( self , lowercase__ , lowercase__ , lowercase__ = "default" ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = encoder_config.hidden_size return VisionEncoderDecoderDecoderOnnxConfig(lowercase__ , lowercase__ )
68
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging snake_case_ = logging.get_logger(__name__) snake_case_ = { 'facebook/xmod-base': 'https://huggingface.co/facebook/xmod-base/resolve/main/config.json', 'facebook/xmod-large-prenorm': 'https://huggingface.co/facebook/xmod-large-prenorm/resolve/main/config.json', 'facebook/xmod-base-13-125k': 'https://huggingface.co/facebook/xmod-base-13-125k/resolve/main/config.json', 'facebook/xmod-base-30-125k': 'https://huggingface.co/facebook/xmod-base-30-125k/resolve/main/config.json', 'facebook/xmod-base-30-195k': 'https://huggingface.co/facebook/xmod-base-30-195k/resolve/main/config.json', 'facebook/xmod-base-60-125k': 'https://huggingface.co/facebook/xmod-base-60-125k/resolve/main/config.json', 'facebook/xmod-base-60-265k': 'https://huggingface.co/facebook/xmod-base-60-265k/resolve/main/config.json', 'facebook/xmod-base-75-125k': 'https://huggingface.co/facebook/xmod-base-75-125k/resolve/main/config.json', 'facebook/xmod-base-75-269k': 'https://huggingface.co/facebook/xmod-base-75-269k/resolve/main/config.json', } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = "xmod" def __init__( self , lowercase__=3_0522 , lowercase__=768 , lowercase__=12 , lowercase__=12 , lowercase__=3072 , lowercase__="gelu" , lowercase__=0.1 , lowercase__=0.1 , lowercase__=512 , lowercase__=2 , lowercase__=0.02 , lowercase__=1e-12 , lowercase__=1 , lowercase__=0 , lowercase__=2 , lowercase__="absolute" , lowercase__=True , lowercase__=None , lowercase__=False , lowercase__=2 , lowercase__=False , lowercase__=True , lowercase__=True , lowercase__=("en_XX",) , lowercase__=None , **lowercase__ , ): """simple docstring""" super().__init__(pad_token_id=lowercase__ , bos_token_id=lowercase__ , eos_token_id=lowercase__ , **lowercase__ ) SCREAMING_SNAKE_CASE_ : Tuple = vocab_size SCREAMING_SNAKE_CASE_ : Optional[Any] = hidden_size SCREAMING_SNAKE_CASE_ : Tuple = num_hidden_layers SCREAMING_SNAKE_CASE_ : Optional[int] = num_attention_heads SCREAMING_SNAKE_CASE_ : List[str] = hidden_act SCREAMING_SNAKE_CASE_ : Optional[int] = intermediate_size SCREAMING_SNAKE_CASE_ : Tuple = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : int = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE_ : Dict = type_vocab_size SCREAMING_SNAKE_CASE_ : str = initializer_range SCREAMING_SNAKE_CASE_ : List[str] = layer_norm_eps SCREAMING_SNAKE_CASE_ : Tuple = position_embedding_type SCREAMING_SNAKE_CASE_ : str = use_cache SCREAMING_SNAKE_CASE_ : Optional[int] = classifier_dropout SCREAMING_SNAKE_CASE_ : int = pre_norm SCREAMING_SNAKE_CASE_ : Optional[int] = adapter_reduction_factor SCREAMING_SNAKE_CASE_ : List[str] = adapter_layer_norm SCREAMING_SNAKE_CASE_ : List[str] = adapter_reuse_layer_norm SCREAMING_SNAKE_CASE_ : int = ln_before_adapter SCREAMING_SNAKE_CASE_ : List[Any] = list(lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = default_language class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): @property def __lowerCamelCase ( self ): """simple docstring""" if self.task == "multiple-choice": SCREAMING_SNAKE_CASE_ : Tuple = {0: "batch", 1: "choice", 2: "sequence"} else: SCREAMING_SNAKE_CASE_ : Optional[int] = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
68
1
'''simple docstring''' from __future__ import annotations from PIL import Image # Define glider example snake_case_ = [ [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [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], ] # Define blinker example snake_case_ = [[0, 1, 0], [0, 1, 0], [0, 1, 0]] def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : list[list[int]] ) -> list[list[int]]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = [] for i in range(len(SCREAMING_SNAKE_CASE_ ) ): SCREAMING_SNAKE_CASE_ : Any = [] for j in range(len(cells[i] ) ): # Get the number of live neighbours SCREAMING_SNAKE_CASE_ : Union[str, Any] = 0 if i > 0 and j > 0: neighbour_count += cells[i - 1][j - 1] if i > 0: neighbour_count += cells[i - 1][j] if i > 0 and j < len(cells[i] ) - 1: neighbour_count += cells[i - 1][j + 1] if j > 0: neighbour_count += cells[i][j - 1] if j < len(cells[i] ) - 1: neighbour_count += cells[i][j + 1] if i < len(SCREAMING_SNAKE_CASE_ ) - 1 and j > 0: neighbour_count += cells[i + 1][j - 1] if i < len(SCREAMING_SNAKE_CASE_ ) - 1: neighbour_count += cells[i + 1][j] if i < len(SCREAMING_SNAKE_CASE_ ) - 1 and j < len(cells[i] ) - 1: neighbour_count += cells[i + 1][j + 1] # Rules of the game of life (excerpt from Wikipedia): # 1. Any live cell with two or three live neighbours survives. # 2. Any dead cell with three live neighbours becomes a live cell. # 3. All other live cells die in the next generation. # Similarly, all other dead cells stay dead. SCREAMING_SNAKE_CASE_ : List[Any] = cells[i][j] == 1 if ( (alive and 2 <= neighbour_count <= 3) or not alive and neighbour_count == 3 ): next_generation_row.append(1 ) else: next_generation_row.append(0 ) next_generation.append(SCREAMING_SNAKE_CASE_ ) return next_generation def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : list[list[int]] , SCREAMING_SNAKE_CASE_ : int ) -> list[Image.Image]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = [] for _ in range(SCREAMING_SNAKE_CASE_ ): # Create output image SCREAMING_SNAKE_CASE_ : Union[str, Any] = Image.new("RGB" , (len(cells[0] ), len(SCREAMING_SNAKE_CASE_ )) ) SCREAMING_SNAKE_CASE_ : Dict = img.load() # Save cells to image for x in range(len(SCREAMING_SNAKE_CASE_ ) ): for y in range(len(cells[0] ) ): SCREAMING_SNAKE_CASE_ : List[str] = 2_5_5 - cells[y][x] * 2_5_5 SCREAMING_SNAKE_CASE_ : Optional[Any] = (colour, colour, colour) # Save image images.append(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ : Dict = new_generation(SCREAMING_SNAKE_CASE_ ) return images if __name__ == "__main__": snake_case_ = generate_images(GLIDER, 1_6) images[0].save('out.gif', save_all=True, append_images=images[1:])
68
'''simple docstring''' def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int ) -> int: """simple docstring""" return int((input_a, input_a).count(1 ) != 0 ) def __lowerCamelCase ( ) -> None: """simple docstring""" assert or_gate(0 , 0 ) == 0 assert or_gate(0 , 1 ) == 1 assert or_gate(1 , 0 ) == 1 assert or_gate(1 , 1 ) == 1 if __name__ == "__main__": print(or_gate(0, 1)) print(or_gate(1, 0)) print(or_gate(0, 0)) print(or_gate(1, 1))
68
1
'''simple docstring''' import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation snake_case_ = logging.get_logger(__name__) snake_case_ = {'tokenizer_file': 'tokenizer.json'} snake_case_ = { 'tokenizer_file': { 'bigscience/tokenizer': 'https://huggingface.co/bigscience/tokenizer/blob/main/tokenizer.json', 'bigscience/bloom-560m': 'https://huggingface.co/bigscience/bloom-560m/blob/main/tokenizer.json', 'bigscience/bloom-1b1': 'https://huggingface.co/bigscience/bloom-1b1/blob/main/tokenizer.json', 'bigscience/bloom-1b7': 'https://huggingface.co/bigscience/bloom-1b7/blob/main/tokenizer.json', 'bigscience/bloom-3b': 'https://huggingface.co/bigscience/bloom-3b/blob/main/tokenizer.json', 'bigscience/bloom-7b1': 'https://huggingface.co/bigscience/bloom-7b1/blob/main/tokenizer.json', 'bigscience/bloom': 'https://huggingface.co/bigscience/bloom/blob/main/tokenizer.json', }, } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = VOCAB_FILES_NAMES _A = PRETRAINED_VOCAB_FILES_MAP _A = ["input_ids", "attention_mask"] _A = None def __init__( self , lowercase__=None , lowercase__=None , lowercase__=None , lowercase__="<unk>" , lowercase__="<s>" , lowercase__="</s>" , lowercase__="<pad>" , lowercase__=False , lowercase__=False , **lowercase__ , ): """simple docstring""" super().__init__( lowercase__ , lowercase__ , tokenizer_file=lowercase__ , unk_token=lowercase__ , bos_token=lowercase__ , eos_token=lowercase__ , pad_token=lowercase__ , add_prefix_space=lowercase__ , clean_up_tokenization_spaces=lowercase__ , **lowercase__ , ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("add_prefix_space" , lowercase__ ) != add_prefix_space: SCREAMING_SNAKE_CASE_ : Optional[Any] = getattr(lowercase__ , pre_tok_state.pop("type" ) ) SCREAMING_SNAKE_CASE_ : int = add_prefix_space SCREAMING_SNAKE_CASE_ : Optional[Any] = pre_tok_class(**lowercase__ ) SCREAMING_SNAKE_CASE_ : Tuple = add_prefix_space def __lowerCamelCase ( self , *lowercase__ , **lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = kwargs.get("is_split_into_words" , lowercase__ ) if not (self.add_prefix_space or not is_split_into_words): raise Exception( F"You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with" " pretokenized inputs." ) return super()._batch_encode_plus(*lowercase__ , **lowercase__ ) def __lowerCamelCase ( self , *lowercase__ , **lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = kwargs.get("is_split_into_words" , lowercase__ ) if not (self.add_prefix_space or not is_split_into_words): raise Exception( F"You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with" " pretokenized inputs." ) return super()._encode_plus(*lowercase__ , **lowercase__ ) def __lowerCamelCase ( self , lowercase__ , lowercase__ = None ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = self._tokenizer.model.save(lowercase__ , name=lowercase__ ) return tuple(lowercase__ ) def __lowerCamelCase ( self , lowercase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(lowercase__ , add_special_tokens=lowercase__ ) + [self.eos_token_id] ) if len(lowercase__ ) > self.model_max_length: SCREAMING_SNAKE_CASE_ : Dict = input_ids[-self.model_max_length :] return input_ids
68
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..bit import BitConfig snake_case_ = logging.get_logger(__name__) snake_case_ = { 'Intel/dpt-large': 'https://huggingface.co/Intel/dpt-large/resolve/main/config.json', # See all DPT models at https://huggingface.co/models?filter=dpt } class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): _A = "dpt" def __init__( self , lowercase__=768 , lowercase__=12 , lowercase__=12 , lowercase__=3072 , lowercase__="gelu" , lowercase__=0.0 , lowercase__=0.0 , lowercase__=0.02 , lowercase__=1e-12 , lowercase__=384 , lowercase__=16 , lowercase__=3 , lowercase__=False , lowercase__=True , lowercase__=[2, 5, 8, 11] , lowercase__="project" , lowercase__=[4, 2, 1, 0.5] , lowercase__=[96, 192, 384, 768] , lowercase__=256 , lowercase__=-1 , lowercase__=False , lowercase__=True , lowercase__=0.4 , lowercase__=255 , lowercase__=0.1 , lowercase__=[1, 1024, 24, 24] , lowercase__=[0, 1] , lowercase__=None , **lowercase__ , ): """simple docstring""" super().__init__(**lowercase__ ) SCREAMING_SNAKE_CASE_ : Any = hidden_size SCREAMING_SNAKE_CASE_ : Union[str, Any] = is_hybrid if self.is_hybrid: if backbone_config is None: logger.info("Initializing the config with a `BiT` backbone." ) SCREAMING_SNAKE_CASE_ : Tuple = { "global_padding": "same", "layer_type": "bottleneck", "depths": [3, 4, 9], "out_features": ["stage1", "stage2", "stage3"], "embedding_dynamic_padding": True, } SCREAMING_SNAKE_CASE_ : Union[str, Any] = BitConfig(**lowercase__ ) elif isinstance(lowercase__ , lowercase__ ): logger.info("Initializing the config with a `BiT` backbone." ) SCREAMING_SNAKE_CASE_ : Dict = BitConfig(**lowercase__ ) elif isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE_ : Optional[int] = backbone_config else: raise ValueError( F"backbone_config must be a dictionary or a `PretrainedConfig`, got {backbone_config.__class__}." ) SCREAMING_SNAKE_CASE_ : List[Any] = backbone_featmap_shape SCREAMING_SNAKE_CASE_ : Union[str, Any] = neck_ignore_stages if readout_type != "project": raise ValueError("Readout type must be 'project' when using `DPT-hybrid` mode." ) else: SCREAMING_SNAKE_CASE_ : Optional[Any] = None SCREAMING_SNAKE_CASE_ : int = None SCREAMING_SNAKE_CASE_ : List[Any] = [] SCREAMING_SNAKE_CASE_ : int = num_hidden_layers SCREAMING_SNAKE_CASE_ : Union[str, Any] = num_attention_heads SCREAMING_SNAKE_CASE_ : Tuple = intermediate_size SCREAMING_SNAKE_CASE_ : Optional[int] = hidden_act SCREAMING_SNAKE_CASE_ : Dict = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : str = initializer_range SCREAMING_SNAKE_CASE_ : List[Any] = layer_norm_eps SCREAMING_SNAKE_CASE_ : Any = image_size SCREAMING_SNAKE_CASE_ : Union[str, Any] = patch_size SCREAMING_SNAKE_CASE_ : Union[str, Any] = num_channels SCREAMING_SNAKE_CASE_ : Union[str, Any] = qkv_bias SCREAMING_SNAKE_CASE_ : Optional[Any] = backbone_out_indices if readout_type not in ["ignore", "add", "project"]: raise ValueError("Readout_type must be one of ['ignore', 'add', 'project']" ) SCREAMING_SNAKE_CASE_ : Any = readout_type SCREAMING_SNAKE_CASE_ : Optional[Any] = reassemble_factors SCREAMING_SNAKE_CASE_ : str = neck_hidden_sizes SCREAMING_SNAKE_CASE_ : Union[str, Any] = fusion_hidden_size SCREAMING_SNAKE_CASE_ : Any = head_in_index SCREAMING_SNAKE_CASE_ : str = use_batch_norm_in_fusion_residual # auxiliary head attributes (semantic segmentation) SCREAMING_SNAKE_CASE_ : List[Any] = use_auxiliary_head SCREAMING_SNAKE_CASE_ : int = auxiliary_loss_weight SCREAMING_SNAKE_CASE_ : Union[str, Any] = semantic_loss_ignore_index SCREAMING_SNAKE_CASE_ : Any = semantic_classifier_dropout def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = copy.deepcopy(self.__dict__ ) if output["backbone_config"] is not None: SCREAMING_SNAKE_CASE_ : List[str] = self.backbone_config.to_dict() SCREAMING_SNAKE_CASE_ : Optional[int] = self.__class__.model_type return output
68
1
'''simple docstring''' import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.generation import DisjunctiveConstraint @require_torch class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = [[1, 2, 4], [1, 2, 3, 4]] SCREAMING_SNAKE_CASE_ : Any = DisjunctiveConstraint(lowercase__ ) self.assertTrue(isinstance(dc.token_ids , lowercase__ ) ) with self.assertRaises(lowercase__ ): DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]] ) ) with self.assertRaises(lowercase__ ): DisjunctiveConstraint([torch.LongTensor([1, 2, 4] ), torch.LongTensor([1, 2, 3, 4, 5] )] ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = [[1, 2], [1, 2, 3, 4]] with self.assertRaises(lowercase__ ): DisjunctiveConstraint(lowercase__ ) # fails here def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = [[1, 2, 3], [1, 2, 4]] SCREAMING_SNAKE_CASE_ : Optional[Any] = DisjunctiveConstraint(lowercase__ ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = dc.update(1 ) SCREAMING_SNAKE_CASE_ : Optional[int] = stepped is True and completed is False and reset is False self.assertTrue(lowercase__ ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Tuple = dc.update(2 ) SCREAMING_SNAKE_CASE_ : Tuple = stepped is True and completed is False and reset is False self.assertTrue(lowercase__ ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Any = dc.update(3 ) SCREAMING_SNAKE_CASE_ : Tuple = stepped is True and completed is True and reset is False self.assertTrue(lowercase__ ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 3] ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]] SCREAMING_SNAKE_CASE_ : Dict = DisjunctiveConstraint(lowercase__ ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : List[Any] = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Dict = dc.update(4 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2, 4] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : List[Any] = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 4, 5] ) dc.reset() SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Tuple = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 3 ) self.assertTrue(dc.current_seq == [1] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : str = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 2 ) self.assertTrue(dc.current_seq == [1, 2] ) SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : str = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.remaining() == 0 ) self.assertTrue(dc.current_seq == [1, 2, 5] )
68
'''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 if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ChineseCLIPImageProcessor class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __init__( self , lowercase__ , lowercase__=7 , lowercase__=3 , lowercase__=18 , lowercase__=30 , lowercase__=400 , lowercase__=True , lowercase__=None , lowercase__=True , lowercase__=None , lowercase__=True , lowercase__=[0.48145466, 0.4578275, 0.40821073] , lowercase__=[0.26862954, 0.26130258, 0.27577711] , lowercase__=True , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = size if size is not None else {"height": 224, "width": 224} SCREAMING_SNAKE_CASE_ : Optional[Any] = crop_size if crop_size is not None else {"height": 18, "width": 18} SCREAMING_SNAKE_CASE_ : str = parent SCREAMING_SNAKE_CASE_ : List[Any] = batch_size SCREAMING_SNAKE_CASE_ : Dict = num_channels SCREAMING_SNAKE_CASE_ : Any = image_size SCREAMING_SNAKE_CASE_ : Tuple = min_resolution SCREAMING_SNAKE_CASE_ : Optional[Any] = max_resolution SCREAMING_SNAKE_CASE_ : Tuple = do_resize SCREAMING_SNAKE_CASE_ : List[str] = size SCREAMING_SNAKE_CASE_ : str = do_center_crop SCREAMING_SNAKE_CASE_ : List[str] = crop_size SCREAMING_SNAKE_CASE_ : int = do_normalize SCREAMING_SNAKE_CASE_ : Optional[int] = image_mean SCREAMING_SNAKE_CASE_ : Dict = image_std SCREAMING_SNAKE_CASE_ : List[Any] = do_convert_rgb def __lowerCamelCase ( self ): """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_convert_rgb": self.do_convert_rgb, } def __lowerCamelCase ( self , lowercase__=False , lowercase__=False , lowercase__=False ): """simple docstring""" assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time" if equal_resolution: SCREAMING_SNAKE_CASE_ : Optional[int] = [] for i in range(self.batch_size ): image_inputs.append( np.random.randint( 255 , size=(self.num_channels, self.max_resolution, self.max_resolution) , dtype=np.uinta ) ) else: SCREAMING_SNAKE_CASE_ : str = [] for i in range(self.batch_size ): SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ : Optional[Any] = np.random.choice(np.arange(self.min_resolution , self.max_resolution ) , 2 ) image_inputs.append(np.random.randint(255 , size=(self.num_channels, width, height) , dtype=np.uinta ) ) if not numpify and not torchify: # PIL expects the channel dimension as last dimension SCREAMING_SNAKE_CASE_ : str = [Image.fromarray(np.moveaxis(lowercase__ , 0 , -1 ) ) for x in image_inputs] if torchify: SCREAMING_SNAKE_CASE_ : List[str] = [torch.from_numpy(lowercase__ ) for x in image_inputs] return image_inputs @require_torch @require_vision class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,unittest.TestCase ): _A = ChineseCLIPImageProcessor if is_vision_available() else None def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = ChineseCLIPImageProcessingTester(self , do_center_crop=lowercase__ ) @property def __lowerCamelCase ( self ): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowercase__ , "do_resize" ) ) self.assertTrue(hasattr(lowercase__ , "size" ) ) self.assertTrue(hasattr(lowercase__ , "do_center_crop" ) ) self.assertTrue(hasattr(lowercase__ , "center_crop" ) ) self.assertTrue(hasattr(lowercase__ , "do_normalize" ) ) self.assertTrue(hasattr(lowercase__ , "image_mean" ) ) self.assertTrue(hasattr(lowercase__ , "image_std" ) ) self.assertTrue(hasattr(lowercase__ , "do_convert_rgb" ) ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"height": 224, "width": 224} ) self.assertEqual(image_processor.crop_size , {"height": 18, "width": 18} ) SCREAMING_SNAKE_CASE_ : str = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 ) self.assertEqual(image_processor.size , {"shortest_edge": 42} ) self.assertEqual(image_processor.crop_size , {"height": 84, "width": 84} ) def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE_ : Tuple = self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__ ) for image in image_inputs: self.assertIsInstance(lowercase__ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE_ : Dict = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE_ : Optional[int] = image_processing(lowercase__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__ , numpify=lowercase__ ) for image in image_inputs: self.assertIsInstance(lowercase__ , np.ndarray ) # Test not batched input SCREAMING_SNAKE_CASE_ : Optional[int] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE_ : List[str] = image_processing(lowercase__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors SCREAMING_SNAKE_CASE_ : List[str] = self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__ , torchify=lowercase__ ) for image in image_inputs: self.assertIsInstance(lowercase__ , torch.Tensor ) # Test not batched input SCREAMING_SNAKE_CASE_ : Union[str, Any] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE_ : int = image_processing(lowercase__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) @require_torch @require_vision class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,unittest.TestCase ): _A = ChineseCLIPImageProcessor if is_vision_available() else None def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int = ChineseCLIPImageProcessingTester(self , num_channels=4 , do_center_crop=lowercase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = 3 @property def __lowerCamelCase ( self ): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowercase__ , "do_resize" ) ) self.assertTrue(hasattr(lowercase__ , "size" ) ) self.assertTrue(hasattr(lowercase__ , "do_center_crop" ) ) self.assertTrue(hasattr(lowercase__ , "center_crop" ) ) self.assertTrue(hasattr(lowercase__ , "do_normalize" ) ) self.assertTrue(hasattr(lowercase__ , "image_mean" ) ) self.assertTrue(hasattr(lowercase__ , "image_std" ) ) self.assertTrue(hasattr(lowercase__ , "do_convert_rgb" ) ) def __lowerCamelCase ( self ): """simple docstring""" pass def __lowerCamelCase ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE_ : Optional[int] = self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__ ) for image in image_inputs: self.assertIsInstance(lowercase__ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE_ : Optional[Any] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE_ : List[str] = image_processing(lowercase__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , )
68
1