code
stringlengths
87
55.2k
code_codestyle
int64
0
349
style_context
stringlengths
135
49.1k
style_context_codestyle
int64
0
349
label
int64
0
1
'''simple docstring''' import contextlib import os import sqlitea import pytest from datasets import Dataset, Features, Value from datasets.io.sql import SqlDatasetReader, SqlDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases, require_sqlalchemy def snake_case_ ( __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" assert isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @require_sqlalchemy @pytest.mark.parametrize('''keep_in_memory''' , [False, True] ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : Union[str, Any] = tmp_path / '''cache''' lowercase_ : Optional[Any] = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): lowercase_ : Dict = SqlDatasetReader( '''dataset''' , '''sqlite:///''' + sqlite_path , cache_dir=__SCREAMING_SNAKE_CASE , keep_in_memory=__SCREAMING_SNAKE_CASE ).read() _check_sql_dataset(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) @require_sqlalchemy @pytest.mark.parametrize( '''features''' , [ None, {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}, {'''col_1''': '''string''', '''col_2''': '''string''', '''col_3''': '''string'''}, {'''col_1''': '''int32''', '''col_2''': '''int32''', '''col_3''': '''int32'''}, {'''col_1''': '''float32''', '''col_2''': '''float32''', '''col_3''': '''float32'''}, ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Optional[int] ): """simple docstring""" lowercase_ : Optional[Any] = tmp_path / '''cache''' lowercase_ : int = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} lowercase_ : Dict = features.copy() if features else default_expected_features lowercase_ : Tuple = ( Features({feature: Value(__SCREAMING_SNAKE_CASE ) for feature, dtype in features.items()} ) if features is not None else None ) lowercase_ : int = SqlDatasetReader('''dataset''' , '''sqlite:///''' + sqlite_path , features=__SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE ).read() _check_sql_dataset(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" with contextlib.closing(sqlitea.connect(__SCREAMING_SNAKE_CASE ) ) as con: lowercase_ : List[Any] = con.cursor() cur.execute('''SELECT * FROM dataset''' ) for row in cur: yield row @require_sqlalchemy def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : Tuple = tmp_path / '''cache''' lowercase_ : int = os.path.join(__SCREAMING_SNAKE_CASE , '''tmp.sql''' ) lowercase_ : Optional[Any] = SqlDatasetReader('''dataset''' , '''sqlite:///''' + sqlite_path , cache_dir=__SCREAMING_SNAKE_CASE ).read() SqlDatasetWriter(__SCREAMING_SNAKE_CASE , '''dataset''' , '''sqlite:///''' + output_sqlite_path , num_proc=1 ).write() lowercase_ : List[str] = iter_sql_file(__SCREAMING_SNAKE_CASE ) lowercase_ : List[str] = iter_sql_file(__SCREAMING_SNAKE_CASE ) for rowa, rowa in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): assert rowa == rowa @require_sqlalchemy def snake_case_ ( __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" lowercase_ : Dict = tmp_path / '''cache''' lowercase_ : List[Any] = os.path.join(__SCREAMING_SNAKE_CASE , '''tmp.sql''' ) lowercase_ : Any = SqlDatasetReader('''dataset''' , '''sqlite:///''' + sqlite_path , cache_dir=__SCREAMING_SNAKE_CASE ).read() SqlDatasetWriter(__SCREAMING_SNAKE_CASE , '''dataset''' , '''sqlite:///''' + output_sqlite_path , num_proc=2 ).write() lowercase_ : Dict = iter_sql_file(__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = iter_sql_file(__SCREAMING_SNAKE_CASE ) for rowa, rowa in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): assert rowa == rowa @require_sqlalchemy def snake_case_ ( __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" lowercase_ : Optional[Any] = tmp_path / '''cache''' lowercase_ : str = os.path.join(__SCREAMING_SNAKE_CASE , '''tmp.sql''' ) lowercase_ : Optional[int] = SqlDatasetReader('''dataset''' , '''sqlite:///''' + sqlite_path , cache_dir=__SCREAMING_SNAKE_CASE ).read() with pytest.raises(__SCREAMING_SNAKE_CASE ): SqlDatasetWriter(__SCREAMING_SNAKE_CASE , '''dataset''' , '''sqlite:///''' + output_sqlite_path , num_proc=0 ).write()
93
'''simple docstring''' import glob import os import random from string import ascii_lowercase, digits import cva import numpy as np # Parrameters _lowercase : Any = (7_2_0, 1_2_8_0) # Height, Width _lowercase : List[Any] = (0.4, 0.6) # if height or width lower than this scale, drop it. _lowercase : str = 1 / 1_0_0 _lowercase : Any = "" _lowercase : Union[str, Any] = "" _lowercase : Optional[int] = "" _lowercase : List[Any] = 2_5_0 def snake_case_ ( ): """simple docstring""" lowercase_ , lowercase_ : Any = get_dataset(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) for index in range(__SCREAMING_SNAKE_CASE ): lowercase_ : str = random.sample(range(len(__SCREAMING_SNAKE_CASE ) ) , 4 ) lowercase_ , lowercase_ , lowercase_ : Any = 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' lowercase_ : int = random_chars(32 ) lowercase_ : str = path.split(os.sep )[-1].rsplit('''.''' , 1 )[0] lowercase_ : int = F'''{OUTPUT_DIR}/{file_name}_MOSAIC_{letter_code}''' cva.imwrite(F'''{file_root}.jpg''' , __SCREAMING_SNAKE_CASE , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(F'''Succeeded {index+1}/{NUMBER_IMAGES} with {file_name}''' ) lowercase_ : List[Any] = [] for anno in new_annos: lowercase_ : List[Any] = anno[3] - anno[1] lowercase_ : List[str] = anno[4] - anno[2] lowercase_ : Dict = anno[1] + width / 2 lowercase_ : Dict = anno[2] + height / 2 lowercase_ : 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 snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : str ): """simple docstring""" lowercase_ : Optional[Any] = [] lowercase_ : Optional[Any] = [] for label_file in glob.glob(os.path.join(__SCREAMING_SNAKE_CASE , '''*.txt''' ) ): lowercase_ : int = label_file.split(os.sep )[-1].rsplit('''.''' , 1 )[0] with open(__SCREAMING_SNAKE_CASE ) as in_file: lowercase_ : List[str] = in_file.readlines() lowercase_ : Optional[Any] = os.path.join(__SCREAMING_SNAKE_CASE , F'''{label_name}.jpg''' ) lowercase_ : Optional[int] = [] for obj_list in obj_lists: lowercase_ : List[str] = obj_list.rstrip('''\n''' ).split(''' ''' ) lowercase_ : Optional[int] = float(obj[1] ) - float(obj[3] ) / 2 lowercase_ : Any = float(obj[2] ) - float(obj[4] ) / 2 lowercase_ : str = float(obj[1] ) + float(obj[3] ) / 2 lowercase_ : List[str] = 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 snake_case_ ( __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 , ): """simple docstring""" lowercase_ : List[Any] = np.zeros([output_size[0], output_size[1], 3] , dtype=np.uinta ) lowercase_ : Tuple = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) lowercase_ : List[Any] = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) lowercase_ : Optional[int] = int(scale_x * output_size[1] ) lowercase_ : Dict = int(scale_y * output_size[0] ) lowercase_ : Union[str, Any] = [] lowercase_ : List[Any] = [] for i, index in enumerate(__SCREAMING_SNAKE_CASE ): lowercase_ : Union[str, Any] = all_img_list[index] path_list.append(__SCREAMING_SNAKE_CASE ) lowercase_ : int = all_annos[index] lowercase_ : Dict = cva.imread(__SCREAMING_SNAKE_CASE ) if i == 0: # top-left lowercase_ : Optional[Any] = cva.resize(__SCREAMING_SNAKE_CASE , (divid_point_x, divid_point_y) ) lowercase_ : Tuple = img for bbox in img_annos: lowercase_ : Optional[int] = bbox[1] * scale_x lowercase_ : Optional[Any] = bbox[2] * scale_y lowercase_ : str = bbox[3] * scale_x lowercase_ : Tuple = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 1: # top-right lowercase_ : Dict = cva.resize(__SCREAMING_SNAKE_CASE , (output_size[1] - divid_point_x, divid_point_y) ) lowercase_ : Dict = img for bbox in img_annos: lowercase_ : int = scale_x + bbox[1] * (1 - scale_x) lowercase_ : Dict = bbox[2] * scale_y lowercase_ : Optional[int] = scale_x + bbox[3] * (1 - scale_x) lowercase_ : int = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 2: # bottom-left lowercase_ : List[Any] = cva.resize(__SCREAMING_SNAKE_CASE , (divid_point_x, output_size[0] - divid_point_y) ) lowercase_ : List[str] = img for bbox in img_annos: lowercase_ : Any = bbox[1] * scale_x lowercase_ : Optional[int] = scale_y + bbox[2] * (1 - scale_y) lowercase_ : str = bbox[3] * scale_x lowercase_ : Optional[int] = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) else: # bottom-right lowercase_ : int = cva.resize( __SCREAMING_SNAKE_CASE , (output_size[1] - divid_point_x, output_size[0] - divid_point_y) ) lowercase_ : List[str] = img for bbox in img_annos: lowercase_ : int = scale_x + bbox[1] * (1 - scale_x) lowercase_ : Any = scale_y + bbox[2] * (1 - scale_y) lowercase_ : Optional[Any] = scale_x + bbox[3] * (1 - scale_x) lowercase_ : int = 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: lowercase_ : Optional[Any] = [ anno for anno in new_anno if filter_scale < (anno[3] - anno[1]) and filter_scale < (anno[4] - anno[2]) ] return output_img, new_anno, path_list[0] def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" assert number_char > 1, "The number of character should greater than 1" lowercase_ : Any = ascii_lowercase + digits return "".join(random.choice(__SCREAMING_SNAKE_CASE ) for _ in range(__SCREAMING_SNAKE_CASE ) ) if __name__ == "__main__": main() print("DONE ✅")
93
1
'''simple docstring''' import argparse from collections import OrderedDict from pathlib import Path import torch from transformers import ( VisualBertConfig, VisualBertForMultipleChoice, VisualBertForPreTraining, VisualBertForQuestionAnswering, VisualBertForVisualReasoning, ) from transformers.utils import logging logging.set_verbosity_info() _lowercase : str = logging.get_logger(__name__) _lowercase : List[Any] = [ ("bert.bert", "visual_bert"), ("bert.cls", "cls"), ("bert.classifier", "cls"), ("token_type_embeddings_visual", "visual_token_type_embeddings"), ("position_embeddings_visual", "visual_position_embeddings"), ("projection", "visual_projection"), ] _lowercase : Tuple = [ "nlvr2_coco_pre_trained.th", "nlvr2_fine_tuned.th", "nlvr2_pre_trained.th", "vcr_coco_pre_train.th", "vcr_fine_tune.th", "vcr_pre_train.th", "vqa_coco_pre_trained.th", "vqa_fine_tuned.th", "vqa_pre_trained.th", ] def snake_case_ ( __SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" lowercase_ : Optional[Any] = torch.load(__SCREAMING_SNAKE_CASE , map_location='''cpu''' ) return sd def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Optional[int]=rename_keys_prefix ): """simple docstring""" lowercase_ : Any = OrderedDict() lowercase_ : Optional[int] = torch.arange(config.max_position_embeddings ).expand((1, -1) ) # detector_d = OrderedDict() for key in d: if "detector" in key: # detector_d[key.replace('detector.','')] = d[key] continue lowercase_ : Optional[Any] = key for name_pair in rename_keys_prefix: lowercase_ : str = new_key.replace(name_pair[0] , name_pair[1] ) lowercase_ : List[Any] = d[key] if key == "bert.cls.predictions.decoder.weight": # Old bert code didn't have `decoder.bias`, but was added separately lowercase_ : Tuple = new_d['''cls.predictions.bias'''] return new_d @torch.no_grad() def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : str ): """simple docstring""" assert ( checkpoint_path.split('''/''' )[-1] in ACCEPTABLE_CHECKPOINTS ), F'''The checkpoint provided must be in {ACCEPTABLE_CHECKPOINTS}.''' # Get Config if "pre" in checkpoint_path: lowercase_ : Optional[Any] = '''pretraining''' if "vcr" in checkpoint_path: lowercase_ : List[Any] = {'''visual_embedding_dim''': 512} elif "vqa_advanced" in checkpoint_path: lowercase_ : Any = {'''visual_embedding_dim''': 2048} elif "vqa" in checkpoint_path: lowercase_ : Optional[Any] = {'''visual_embedding_dim''': 2048} elif "nlvr" in checkpoint_path: lowercase_ : List[str] = {'''visual_embedding_dim''': 1024} else: raise NotImplementedError(F'''No implementation found for `{checkpoint_path}`.''' ) else: if "vcr" in checkpoint_path: lowercase_ : Dict = {'''visual_embedding_dim''': 512} lowercase_ : List[str] = '''multichoice''' elif "vqa_advanced" in checkpoint_path: lowercase_ : List[Any] = {'''visual_embedding_dim''': 2048} lowercase_ : List[Any] = '''vqa_advanced''' elif "vqa" in checkpoint_path: lowercase_ : Dict = {'''visual_embedding_dim''': 2048, '''num_labels''': 3129} lowercase_ : List[Any] = '''vqa''' elif "nlvr" in checkpoint_path: lowercase_ : Tuple = { '''visual_embedding_dim''': 1024, '''num_labels''': 2, } lowercase_ : Tuple = '''nlvr''' lowercase_ : Union[str, Any] = VisualBertConfig(**__SCREAMING_SNAKE_CASE ) # Load State Dict lowercase_ : str = load_state_dict(__SCREAMING_SNAKE_CASE ) lowercase_ : int = get_new_dict(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if model_type == "pretraining": lowercase_ : str = VisualBertForPreTraining(__SCREAMING_SNAKE_CASE ) elif model_type == "vqa": lowercase_ : Union[str, Any] = VisualBertForQuestionAnswering(__SCREAMING_SNAKE_CASE ) elif model_type == "nlvr": lowercase_ : List[str] = VisualBertForVisualReasoning(__SCREAMING_SNAKE_CASE ) elif model_type == "multichoice": lowercase_ : int = VisualBertForMultipleChoice(__SCREAMING_SNAKE_CASE ) model.load_state_dict(__SCREAMING_SNAKE_CASE ) # Save Checkpoints Path(__SCREAMING_SNAKE_CASE ).mkdir(exist_ok=__SCREAMING_SNAKE_CASE ) model.save_pretrained(__SCREAMING_SNAKE_CASE ) if __name__ == "__main__": _lowercase : str = argparse.ArgumentParser() # Required parameters parser.add_argument("orig_checkpoint_path", type=str, help="A path to .th on local filesystem.") parser.add_argument("pytorch_dump_folder_path", type=str, help="Path to the output PyTorch model.") _lowercase : str = parser.parse_args() convert_visual_bert_checkpoint(args.orig_checkpoint_path, args.pytorch_dump_folder_path)
93
'''simple docstring''' from __future__ import annotations from collections import Counter from random import random class lowerCAmelCase__ : def __init__( self ): """simple docstring""" lowercase_ : int = {} def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Dict = {} def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" if nodea not in self.connections: self.add_node(__SCREAMING_SNAKE_CASE ) if nodea not in self.connections: self.add_node(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = probability def _snake_case ( self ): """simple docstring""" return list(self.connections ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Any = 0 lowercase_ : Tuple = random() for dest in self.connections[node]: current_probability += self.connections[node][dest] if current_probability > random_value: return dest return "" def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : list[tuple[str, str, float]] , __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : List[Any] = MarkovChainGraphUndirectedUnweighted() for nodea, nodea, probability in transitions: graph.add_transition_probability(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : str = Counter(graph.get_nodes() ) lowercase_ : Any = start for _ in range(__SCREAMING_SNAKE_CASE ): lowercase_ : int = graph.transition(__SCREAMING_SNAKE_CASE ) visited[node] += 1 return visited if __name__ == "__main__": import doctest doctest.testmod()
93
1
'''simple docstring''' from random import randint, random def snake_case_ ( __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : bool = False , __SCREAMING_SNAKE_CASE : bool = False , __SCREAMING_SNAKE_CASE : int = 5 , ): """simple docstring""" lowercase_ : Dict = [[-1] * number_of_cells] # Create a highway without any car lowercase_ : Union[str, Any] = 0 lowercase_ : Union[str, Any] = max(__SCREAMING_SNAKE_CASE , 0 ) while i < number_of_cells: lowercase_ : List[Any] = ( randint(0 , __SCREAMING_SNAKE_CASE ) if random_speed else initial_speed ) # Place the cars i += ( randint(1 , max_speed * 2 ) if random_frequency else frequency ) # Arbitrary number, may need tuning return highway def snake_case_ ( __SCREAMING_SNAKE_CASE : list , __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : Union[str, Any] = 0 lowercase_ : Dict = highway_now[car_index + 1 :] for cell in range(len(__SCREAMING_SNAKE_CASE ) ): # May need a better name for this if cells[cell] != -1: # If the cell is not empty then return distance # we have the distance we wanted distance += 1 # Here if the car is near the end of the highway return distance + get_distance(__SCREAMING_SNAKE_CASE , -1 ) def snake_case_ ( __SCREAMING_SNAKE_CASE : list , __SCREAMING_SNAKE_CASE : float , __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : str = len(__SCREAMING_SNAKE_CASE ) # Beforce calculations, the highway is empty lowercase_ : List[str] = [-1] * number_of_cells for car_index in range(__SCREAMING_SNAKE_CASE ): if highway_now[car_index] != -1: # Add 1 to the current speed of the car and cap the speed lowercase_ : Dict = min(highway_now[car_index] + 1 , __SCREAMING_SNAKE_CASE ) # Number of empty cell before the next car lowercase_ : Optional[Any] = get_distance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) - 1 # We can't have the car causing an accident lowercase_ : Optional[Any] = min(next_highway[car_index] , __SCREAMING_SNAKE_CASE ) if random() < probability: # Randomly, a driver will slow down lowercase_ : Dict = max(next_highway[car_index] - 1 , 0 ) return next_highway def snake_case_ ( __SCREAMING_SNAKE_CASE : list , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : float , __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : Tuple = len(highway[0] ) for i in range(__SCREAMING_SNAKE_CASE ): lowercase_ : str = update(highway[i] , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : int = [-1] * number_of_cells for car_index in range(__SCREAMING_SNAKE_CASE ): lowercase_ : str = next_speeds_calculated[car_index] if speed != -1: # Change the position based on the speed (with % to create the loop) lowercase_ : Union[str, Any] = (car_index + speed) % number_of_cells # Commit the change of position lowercase_ : Optional[Any] = speed highway.append(__SCREAMING_SNAKE_CASE ) return highway if __name__ == "__main__": import doctest doctest.testmod()
93
'''simple docstring''' import torch from transformers import AutoModel class lowerCAmelCase__ ( torch.nn.Module ): def __init__( self , __SCREAMING_SNAKE_CASE="sayef/fsner-bert-base-uncased" ): """simple docstring""" super(__SCREAMING_SNAKE_CASE , self ).__init__() lowercase_ : Tuple = AutoModel.from_pretrained(__SCREAMING_SNAKE_CASE , return_dict=__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = torch.nn.CosineSimilarity(3 , 1E-0_8 ) lowercase_ : Optional[Any] = torch.nn.Softmax(dim=1 ) def _snake_case ( self , **__SCREAMING_SNAKE_CASE ): """simple docstring""" return self.bert(**__SCREAMING_SNAKE_CASE ).last_hidden_state def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" return token_embeddings.sum(2 , keepdim=__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=1 ): """simple docstring""" return self.softmax(T * self.cos(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Optional[Any] = W_supports['''sizes'''].tolist() lowercase_ : Dict = W_supports['''start_token_id'''].item() lowercase_ : List[Any] = W_supports['''end_token_id'''].item() del W_supports["sizes"] del W_supports["start_token_id"] del W_supports["end_token_id"] lowercase_ : List[str] = self.BERT(**__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = self.BERT(**__SCREAMING_SNAKE_CASE ) lowercase_ : str = None lowercase_ : Dict = None lowercase_ : Tuple = W_supports['''input_ids'''] == start_token_id lowercase_ : Any = W_supports['''input_ids'''] == end_token_id for i, size in enumerate(__SCREAMING_SNAKE_CASE ): if i == 0: lowercase_ : List[str] = 0 else: lowercase_ : List[Any] = support_sizes[i - 1] lowercase_ : str = S[s : s + size][start_token_masks[s : s + size]] lowercase_ : Optional[int] = S[s : s + size][end_token_masks[s : s + size]] lowercase_ : List[str] = torch.matmul(q[i] , s_start.T ).sum(1 ).softmax(0 ) lowercase_ : List[str] = torch.matmul(q[i] , s_end.T ).sum(1 ).softmax(0 ) if p_starts is not None: lowercase_ : Tuple = torch.vstack((p_starts, p_start) ) lowercase_ : Optional[Any] = torch.vstack((p_ends, p_end) ) else: lowercase_ : str = p_start lowercase_ : int = p_end return p_starts, p_ends
93
1
'''simple docstring''' def snake_case_ ( __SCREAMING_SNAKE_CASE : list ): """simple docstring""" if len(__SCREAMING_SNAKE_CASE ) <= 1: return [tuple(__SCREAMING_SNAKE_CASE )] lowercase_ : List[Any] = [] def generate(__SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : list ): if k == 1: res.append(tuple(arr[:] ) ) return generate(k - 1 , __SCREAMING_SNAKE_CASE ) for i in range(k - 1 ): if k % 2 == 0: # k is even lowercase_ , lowercase_ : Tuple = arr[k - 1], arr[i] else: # k is odd lowercase_ , lowercase_ : Optional[Any] = arr[k - 1], arr[0] generate(k - 1 , __SCREAMING_SNAKE_CASE ) generate(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) return res if __name__ == "__main__": _lowercase : int = input("Enter numbers separated by a comma:\n").strip() _lowercase : int = [int(item) for item in user_input.split(",")] print(heaps(arr))
93
'''simple docstring''' import json import os from pathlib import Path from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple, Union import sentencepiece from ...tokenization_utils import BatchEncoding, PreTrainedTokenizer from ...utils import logging _lowercase : List[Any] = logging.get_logger(__name__) _lowercase : List[Any] = "▁" _lowercase : Tuple = { "vocab_file": "vocab.json", "spm_file": "sentencepiece.bpe.model", "tokenizer_config_file": "tokenizer_config.json", } _lowercase : List[str] = { "vocab_file": { "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/vocab.json", "facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/vocab.json", }, "spm_file": { "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/sentencepiece.bpe.model", "facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/sentencepiece.bpe.model", }, "tokenizer_config_file": { "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/tokenizer_config.json", "facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/tokenizer_config.json", }, } _lowercase : List[str] = { "facebook/m2m100_418M": 1_0_2_4, } # fmt: off _lowercase : Tuple = { "m2m100": ["af", "am", "ar", "ast", "az", "ba", "be", "bg", "bn", "br", "bs", "ca", "ceb", "cs", "cy", "da", "de", "el", "en", "es", "et", "fa", "ff", "fi", "fr", "fy", "ga", "gd", "gl", "gu", "ha", "he", "hi", "hr", "ht", "hu", "hy", "id", "ig", "ilo", "is", "it", "ja", "jv", "ka", "kk", "km", "kn", "ko", "lb", "lg", "ln", "lo", "lt", "lv", "mg", "mk", "ml", "mn", "mr", "ms", "my", "ne", "nl", "no", "ns", "oc", "or", "pa", "pl", "ps", "pt", "ro", "ru", "sd", "si", "sk", "sl", "so", "sq", "sr", "ss", "su", "sv", "sw", "ta", "th", "tl", "tn", "tr", "uk", "ur", "uz", "vi", "wo", "xh", "yi", "yo", "zh", "zu"], "wmt21": ["en", "ha", "is", "ja", "cs", "ru", "zh", "de"] } class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = VOCAB_FILES_NAMES lowerCAmelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase_ = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase_ = ['''input_ids''', '''attention_mask'''] lowerCAmelCase_ = [] lowerCAmelCase_ = [] def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE="<s>" , __SCREAMING_SNAKE_CASE="</s>" , __SCREAMING_SNAKE_CASE="</s>" , __SCREAMING_SNAKE_CASE="<pad>" , __SCREAMING_SNAKE_CASE="<unk>" , __SCREAMING_SNAKE_CASE="m2m100" , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE=8 , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : Optional[Any] = {} if sp_model_kwargs is None else sp_model_kwargs lowercase_ : List[Any] = language_codes lowercase_ : Optional[int] = FAIRSEQ_LANGUAGE_CODES[language_codes] lowercase_ : List[Any] = {lang_code: F'''__{lang_code}__''' for lang_code in fairseq_language_code} lowercase_ : Union[str, Any] = kwargs.get('''additional_special_tokens''' , [] ) kwargs["additional_special_tokens"] += [ self.get_lang_token(__SCREAMING_SNAKE_CASE ) for lang_code in fairseq_language_code if self.get_lang_token(__SCREAMING_SNAKE_CASE ) not in kwargs["additional_special_tokens"] ] super().__init__( src_lang=__SCREAMING_SNAKE_CASE , tgt_lang=__SCREAMING_SNAKE_CASE , bos_token=__SCREAMING_SNAKE_CASE , eos_token=__SCREAMING_SNAKE_CASE , sep_token=__SCREAMING_SNAKE_CASE , unk_token=__SCREAMING_SNAKE_CASE , pad_token=__SCREAMING_SNAKE_CASE , language_codes=__SCREAMING_SNAKE_CASE , sp_model_kwargs=self.sp_model_kwargs , num_madeup_words=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) lowercase_ : int = vocab_file lowercase_ : Any = load_json(__SCREAMING_SNAKE_CASE ) lowercase_ : str = {v: k for k, v in self.encoder.items()} lowercase_ : Optional[int] = spm_file lowercase_ : Any = load_spm(__SCREAMING_SNAKE_CASE , self.sp_model_kwargs ) lowercase_ : List[Any] = len(self.encoder ) lowercase_ : Dict = { self.get_lang_token(__SCREAMING_SNAKE_CASE ): self.encoder_size + i for i, lang_code in enumerate(__SCREAMING_SNAKE_CASE ) } lowercase_ : Optional[int] = {lang_code: self.encoder_size + i for i, lang_code in enumerate(__SCREAMING_SNAKE_CASE )} lowercase_ : Union[str, Any] = {v: k for k, v in self.lang_token_to_id.items()} lowercase_ : Tuple = src_lang if src_lang is not None else '''en''' lowercase_ : Optional[int] = tgt_lang lowercase_ : Any = self.get_lang_id(self._src_lang ) self.set_src_lang_special_tokens(self._src_lang ) lowercase_ : Dict = num_madeup_words @property def _snake_case ( self ): """simple docstring""" return len(self.encoder ) + len(self.lang_token_to_id ) @property def _snake_case ( self ): """simple docstring""" return self._src_lang @src_lang.setter def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : str = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" return self.sp_model.encode(__SCREAMING_SNAKE_CASE , out_type=__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" if token in self.lang_token_to_id: return self.lang_token_to_id[token] return self.encoder.get(__SCREAMING_SNAKE_CASE , self.encoder[self.unk_token] ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" if index in self.id_to_lang_token: return self.id_to_lang_token[index] return self.decoder.get(__SCREAMING_SNAKE_CASE , self.unk_token ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Tuple = [] lowercase_ : List[str] = '''''' for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(__SCREAMING_SNAKE_CASE ) + token lowercase_ : Optional[Any] = [] else: current_sub_tokens.append(__SCREAMING_SNAKE_CASE ) out_string += self.sp_model.decode(__SCREAMING_SNAKE_CASE ) return out_string.strip() def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = False ): """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__SCREAMING_SNAKE_CASE , token_ids_a=__SCREAMING_SNAKE_CASE , already_has_special_tokens=__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = [1] * len(self.prefix_tokens ) lowercase_ : Any = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(__SCREAMING_SNAKE_CASE )) + suffix_ones return prefix_ones + ([0] * len(__SCREAMING_SNAKE_CASE )) + ([0] * len(__SCREAMING_SNAKE_CASE )) + suffix_ones def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def _snake_case ( self ): """simple docstring""" lowercase_ : Tuple = {self.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ): """simple docstring""" lowercase_ : List[Any] = self.__dict__.copy() lowercase_ : List[Any] = None return state def __setstate__( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Dict = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): lowercase_ : List[Any] = {} lowercase_ : Union[str, Any] = load_spm(self.spm_file , self.sp_model_kwargs ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" lowercase_ : Tuple = Path(__SCREAMING_SNAKE_CASE ) if not save_dir.is_dir(): raise OSError(F'''{save_directory} should be a directory''' ) lowercase_ : Dict = save_dir / ( (filename_prefix + '''-''' if filename_prefix else '''''') + self.vocab_files_names['''vocab_file'''] ) lowercase_ : Dict = save_dir / ( (filename_prefix + '''-''' if filename_prefix else '''''') + self.vocab_files_names['''spm_file'''] ) save_json(self.encoder , __SCREAMING_SNAKE_CASE ) if os.path.abspath(self.spm_file ) != os.path.abspath(__SCREAMING_SNAKE_CASE ) and os.path.isfile(self.spm_file ): copyfile(self.spm_file , __SCREAMING_SNAKE_CASE ) elif not os.path.isfile(self.spm_file ): with open(__SCREAMING_SNAKE_CASE , '''wb''' ) as fi: lowercase_ : int = self.sp_model.serialized_model_proto() fi.write(__SCREAMING_SNAKE_CASE ) return (str(__SCREAMING_SNAKE_CASE ), str(__SCREAMING_SNAKE_CASE )) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = "en" , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = "ro" , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : Optional[Any] = src_lang lowercase_ : List[str] = tgt_lang self.set_src_lang_special_tokens(self.src_lang ) return super().prepare_seqaseq_batch(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" if src_lang is None or tgt_lang is None: raise ValueError('''Translation requires a `src_lang` and a `tgt_lang` for this model''' ) lowercase_ : Tuple = src_lang lowercase_ : Any = self(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) lowercase_ : List[Any] = self.get_lang_id(__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = tgt_lang_id return inputs def _snake_case ( self ): """simple docstring""" self.set_src_lang_special_tokens(self.src_lang ) def _snake_case ( self ): """simple docstring""" self.set_tgt_lang_special_tokens(self.tgt_lang ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Any = self.get_lang_token(__SCREAMING_SNAKE_CASE ) lowercase_ : Dict = self.lang_token_to_id[lang_token] lowercase_ : Optional[Any] = [self.cur_lang_id] lowercase_ : Union[str, Any] = [self.eos_token_id] def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Any = self.get_lang_token(__SCREAMING_SNAKE_CASE ) lowercase_ : Any = self.lang_token_to_id[lang_token] lowercase_ : str = [self.cur_lang_id] lowercase_ : List[str] = [self.eos_token_id] def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" return self.lang_code_to_token[lang] def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : List[Any] = self.get_lang_token(__SCREAMING_SNAKE_CASE ) return self.lang_token_to_id[lang_token] def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Dict[str, Any] ): """simple docstring""" lowercase_ : Optional[int] = sentencepiece.SentencePieceProcessor(**__SCREAMING_SNAKE_CASE ) spm.Load(str(__SCREAMING_SNAKE_CASE ) ) return spm def snake_case_ ( __SCREAMING_SNAKE_CASE : str ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE , '''r''' ) as f: return json.load(__SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : str ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE , '''w''' ) as f: json.dump(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , indent=2 )
93
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 lowerCAmelCase__ ( lowerCamelCase_ ): def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = True , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = False , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = True , __SCREAMING_SNAKE_CASE = "arrow" , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" super().__init__( split=__SCREAMING_SNAKE_CASE , features=__SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE , keep_in_memory=__SCREAMING_SNAKE_CASE , streaming=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) lowercase_ : List[str] = load_from_cache_file lowercase_ : str = file_format lowercase_ : Tuple = Spark( df=__SCREAMING_SNAKE_CASE , features=__SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE , working_dir=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) def _snake_case ( self ): """simple docstring""" if self.streaming: return self.builder.as_streaming_dataset(split=self.split ) lowercase_ : Union[str, Any] = None if self._load_from_cache_file else DownloadMode.FORCE_REDOWNLOAD self.builder.download_and_prepare( download_mode=__SCREAMING_SNAKE_CASE , file_format=self._file_format , ) return self.builder.as_dataset(split=self.split )
93
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer from ...utils import logging _lowercase : str = logging.get_logger(__name__) _lowercase : List[Any] = "▁" _lowercase : List[Any] = {"vocab_file": "sentencepiece.bpe.model"} _lowercase : Optional[int] = { "vocab_file": { "facebook/mbart-large-en-ro": ( "https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/sentencepiece.bpe.model" ), "facebook/mbart-large-cc25": ( "https://huggingface.co/facebook/mbart-large-cc25/resolve/main/sentencepiece.bpe.model" ), } } _lowercase : str = { "facebook/mbart-large-en-ro": 1_0_2_4, "facebook/mbart-large-cc25": 1_0_2_4, } # fmt: off _lowercase : List[Any] = ["ar_AR", "cs_CZ", "de_DE", "en_XX", "es_XX", "et_EE", "fi_FI", "fr_XX", "gu_IN", "hi_IN", "it_IT", "ja_XX", "kk_KZ", "ko_KR", "lt_LT", "lv_LV", "my_MM", "ne_NP", "nl_XX", "ro_RO", "ru_RU", "si_LK", "tr_TR", "vi_VN", "zh_CN"] class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = VOCAB_FILES_NAMES lowerCAmelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase_ = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase_ = ['''input_ids''', '''attention_mask'''] lowerCAmelCase_ = [] lowerCAmelCase_ = [] def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE="<s>" , __SCREAMING_SNAKE_CASE="</s>" , __SCREAMING_SNAKE_CASE="</s>" , __SCREAMING_SNAKE_CASE="<s>" , __SCREAMING_SNAKE_CASE="<unk>" , __SCREAMING_SNAKE_CASE="<pad>" , __SCREAMING_SNAKE_CASE="<mask>" , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE=None , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : Any = AddedToken(__SCREAMING_SNAKE_CASE , lstrip=__SCREAMING_SNAKE_CASE , rstrip=__SCREAMING_SNAKE_CASE ) if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else mask_token lowercase_ : int = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=__SCREAMING_SNAKE_CASE , eos_token=__SCREAMING_SNAKE_CASE , unk_token=__SCREAMING_SNAKE_CASE , sep_token=__SCREAMING_SNAKE_CASE , cls_token=__SCREAMING_SNAKE_CASE , pad_token=__SCREAMING_SNAKE_CASE , mask_token=__SCREAMING_SNAKE_CASE , tokenizer_file=__SCREAMING_SNAKE_CASE , src_lang=__SCREAMING_SNAKE_CASE , tgt_lang=__SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , sp_model_kwargs=self.sp_model_kwargs , **__SCREAMING_SNAKE_CASE , ) lowercase_ : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__SCREAMING_SNAKE_CASE ) ) lowercase_ : List[str] = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # Mimic fairseq token-to-id alignment for the first 4 token lowercase_ : Tuple = {'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3} # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab lowercase_ : str = 1 lowercase_ : str = len(self.sp_model ) lowercase_ : List[Any] = { code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(__SCREAMING_SNAKE_CASE ) } lowercase_ : Union[str, Any] = {v: k for k, v in self.lang_code_to_id.items()} lowercase_ : List[Any] = len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset self.fairseq_tokens_to_ids.update(self.lang_code_to_id ) lowercase_ : Union[str, Any] = {v: k for k, v in self.fairseq_tokens_to_ids.items()} lowercase_ : Optional[Any] = list(self.lang_code_to_id.keys() ) if additional_special_tokens is not None: # Only add those special tokens if they are not already there. self._additional_special_tokens.extend( [t for t in additional_special_tokens if t not in self._additional_special_tokens] ) lowercase_ : Optional[Any] = src_lang if src_lang is not None else '''en_XX''' lowercase_ : str = self.lang_code_to_id[self._src_lang] lowercase_ : Optional[Any] = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) def __getstate__( self ): """simple docstring""" lowercase_ : Optional[int] = self.__dict__.copy() lowercase_ : Dict = None lowercase_ : Any = self.sp_model.serialized_model_proto() return state def __setstate__( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Optional[Any] = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): lowercase_ : Dict = {} lowercase_ : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) @property def _snake_case ( self ): """simple docstring""" return len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset + 1 # Plus 1 for the mask token @property def _snake_case ( self ): """simple docstring""" return self._src_lang @src_lang.setter def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Tuple = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = False ): """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__SCREAMING_SNAKE_CASE , token_ids_a=__SCREAMING_SNAKE_CASE , already_has_special_tokens=__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = [1] * len(self.prefix_tokens ) lowercase_ : Tuple = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(__SCREAMING_SNAKE_CASE )) + suffix_ones return prefix_ones + ([0] * len(__SCREAMING_SNAKE_CASE )) + ([0] * len(__SCREAMING_SNAKE_CASE )) + suffix_ones def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" lowercase_ : Optional[int] = [self.sep_token_id] lowercase_ : Any = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" if src_lang is None or tgt_lang is None: raise ValueError('''Translation requires a `src_lang` and a `tgt_lang` for this model''' ) lowercase_ : Optional[Any] = src_lang lowercase_ : Dict = self(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , return_tensors=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = self.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = tgt_lang_id return inputs def _snake_case ( self ): """simple docstring""" lowercase_ : str = {self.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" return self.sp_model.encode(__SCREAMING_SNAKE_CASE , out_type=__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] lowercase_ : Any = self.sp_model.PieceToId(__SCREAMING_SNAKE_CASE ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : int = ''''''.join(__SCREAMING_SNAKE_CASE ).replace(__SCREAMING_SNAKE_CASE , ''' ''' ).strip() return out_string def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" if not os.path.isdir(__SCREAMING_SNAKE_CASE ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return lowercase_ : Tuple = os.path.join( __SCREAMING_SNAKE_CASE , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__SCREAMING_SNAKE_CASE ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __SCREAMING_SNAKE_CASE ) elif not os.path.isfile(self.vocab_file ): with open(__SCREAMING_SNAKE_CASE , '''wb''' ) as fi: lowercase_ : List[str] = self.sp_model.serialized_model_proto() fi.write(__SCREAMING_SNAKE_CASE ) return (out_vocab_file,) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = "en_XX" , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = "ro_RO" , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : List[str] = src_lang lowercase_ : int = tgt_lang return super().prepare_seqaseq_batch(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" return self.set_src_lang_special_tokens(self.src_lang ) def _snake_case ( self ): """simple docstring""" return self.set_tgt_lang_special_tokens(self.tgt_lang ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Dict = self.lang_code_to_id[src_lang] lowercase_ : Optional[Any] = [] lowercase_ : List[str] = [self.eos_token_id, self.cur_lang_code] def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : List[Any] = self.lang_code_to_id[lang] lowercase_ : Dict = [] lowercase_ : Union[str, Any] = [self.eos_token_id, self.cur_lang_code]
93
1
'''simple docstring''' import faiss # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import requests # noqa: F401 # Here to have a nice missing dependency error message early on import sklearn # noqa: F401 # Here to have a nice missing dependency error message early on import tqdm # noqa: F401 # Here to have a nice missing dependency error message early on from mauve import compute_mauve # From: mauve-text import datasets _lowercase : Optional[Any] = "\\n@inproceedings{pillutla-etal:mauve:neurips2021,\n title={MAUVE: Measuring the Gap Between Neural Text and Human Text using Divergence Frontiers},\n author={Pillutla, Krishna and Swayamdipta, Swabha and Zellers, Rowan and Thickstun, John and Welleck, Sean and Choi, Yejin and Harchaoui, Zaid},\n booktitle = {NeurIPS},\n year = {2021}\n}\n\n" _lowercase : Optional[Any] = "\\nMAUVE is a library built on PyTorch and HuggingFace Transformers to measure the gap between neural text and human text with the eponymous MAUVE measure.\n\nMAUVE summarizes both Type I and Type II errors measured softly using Kullback–Leibler (KL) divergences.\n\nFor details, see the MAUVE paper: https://arxiv.org/abs/2102.01454 (Neurips, 2021).\n\nThis metrics is a wrapper around the official implementation of MAUVE:\nhttps://github.com/krishnap25/mauve\n" _lowercase : int = "\nCalculates MAUVE scores between two lists of generated text and reference text.\nArgs:\n predictions: list of generated text to score. Each predictions\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\nOptional Args:\n num_buckets: the size of the histogram to quantize P and Q. Options: 'auto' (default) or an integer\n pca_max_data: the number data points to use for PCA dimensionality reduction prior to clustering. If -1, use all the data. Default -1\n kmeans_explained_var: amount of variance of the data to keep in dimensionality reduction by PCA. Default 0.9\n kmeans_num_redo: number of times to redo k-means clustering (the best objective is kept). Default 5\n kmeans_max_iter: maximum number of k-means iterations. Default 500\n featurize_model_name: name of the model from which features are obtained. Default 'gpt2-large' Use one of ['gpt2', 'gpt2-medium', 'gpt2-large', 'gpt2-xl'].\n device_id: Device for featurization. Supply a GPU id (e.g. 0 or 3) to use GPU. If no GPU with this id is found, use CPU\n max_text_length: maximum number of tokens to consider. Default 1024\n divergence_curve_discretization_size: Number of points to consider on the divergence curve. Default 25\n mauve_scaling_factor: \"c\" from the paper. Default 5.\n verbose: If True (default), print running time updates\n seed: random seed to initialize k-means cluster assignments.\nReturns:\n mauve: MAUVE score, a number between 0 and 1. Larger values indicate that P and Q are closer,\n frontier_integral: Frontier Integral, a number between 0 and 1. Smaller values indicate that P and Q are closer,\n divergence_curve: a numpy.ndarray of shape (m, 2); plot it with matplotlib to view the divergence curve,\n p_hist: a discrete distribution, which is a quantized version of the text distribution p_text,\n q_hist: same as above, but with q_text.\nExamples:\n\n >>> # faiss segfaults in doctest for some reason, so the .compute call is not tested with doctest\n >>> import datasets\n >>> mauve = datasets.load_metric('mauve')\n >>> predictions = [\"hello there\", \"general kenobi\"]\n >>> references = [\"hello there\", \"general kenobi\"]\n >>> out = mauve.compute(predictions=predictions, references=references) # doctest: +SKIP\n >>> print(out.mauve) # doctest: +SKIP\n 1.0\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase__ ( datasets.Metric ): def _snake_case ( self ): """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage='''https://github.com/krishnap25/mauve''' , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''string''' , id='''sequence''' ), '''references''': datasets.Value('''string''' , id='''sequence''' ), } ) , codebase_urls=['''https://github.com/krishnap25/mauve'''] , reference_urls=[ '''https://arxiv.org/abs/2102.01454''', '''https://github.com/krishnap25/mauve''', ] , ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE="auto" , __SCREAMING_SNAKE_CASE=-1 , __SCREAMING_SNAKE_CASE=0.9 , __SCREAMING_SNAKE_CASE=5 , __SCREAMING_SNAKE_CASE=5_00 , __SCREAMING_SNAKE_CASE="gpt2-large" , __SCREAMING_SNAKE_CASE=-1 , __SCREAMING_SNAKE_CASE=10_24 , __SCREAMING_SNAKE_CASE=25 , __SCREAMING_SNAKE_CASE=5 , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=25 , ): """simple docstring""" lowercase_ : List[Any] = compute_mauve( p_text=__SCREAMING_SNAKE_CASE , q_text=__SCREAMING_SNAKE_CASE , p_features=__SCREAMING_SNAKE_CASE , q_features=__SCREAMING_SNAKE_CASE , p_tokens=__SCREAMING_SNAKE_CASE , q_tokens=__SCREAMING_SNAKE_CASE , num_buckets=__SCREAMING_SNAKE_CASE , pca_max_data=__SCREAMING_SNAKE_CASE , kmeans_explained_var=__SCREAMING_SNAKE_CASE , kmeans_num_redo=__SCREAMING_SNAKE_CASE , kmeans_max_iter=__SCREAMING_SNAKE_CASE , featurize_model_name=__SCREAMING_SNAKE_CASE , device_id=__SCREAMING_SNAKE_CASE , max_text_length=__SCREAMING_SNAKE_CASE , divergence_curve_discretization_size=__SCREAMING_SNAKE_CASE , mauve_scaling_factor=__SCREAMING_SNAKE_CASE , verbose=__SCREAMING_SNAKE_CASE , seed=__SCREAMING_SNAKE_CASE , ) return out
93
'''simple docstring''' import json import os import tempfile from transformers.testing_utils import check_json_file_has_correct_format class lowerCAmelCase__ : lowerCAmelCase_ = None def _snake_case ( self ): """simple docstring""" lowercase_ : Tuple = self.feature_extraction_class(**self.feat_extract_dict ) lowercase_ : Any = json.loads(feat_extract.to_json_string() ) for key, value in self.feat_extract_dict.items(): self.assertEqual(obj[key] , __SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" lowercase_ : str = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: lowercase_ : str = os.path.join(__SCREAMING_SNAKE_CASE , '''feat_extract.json''' ) feat_extract_first.to_json_file(__SCREAMING_SNAKE_CASE ) lowercase_ : str = self.feature_extraction_class.from_json_file(__SCREAMING_SNAKE_CASE ) self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() ) def _snake_case ( self ): """simple docstring""" lowercase_ : Tuple = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: lowercase_ : Union[str, Any] = feat_extract_first.save_pretrained(__SCREAMING_SNAKE_CASE )[0] check_json_file_has_correct_format(__SCREAMING_SNAKE_CASE ) lowercase_ : str = self.feature_extraction_class.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() ) def _snake_case ( self ): """simple docstring""" lowercase_ : Optional[Any] = self.feature_extraction_class() self.assertIsNotNone(__SCREAMING_SNAKE_CASE )
93
1
'''simple docstring''' from __future__ import annotations def snake_case_ ( __SCREAMING_SNAKE_CASE : list , __SCREAMING_SNAKE_CASE : int | None = None , __SCREAMING_SNAKE_CASE : int | None = None ): """simple docstring""" if start is None: lowercase_ : Dict = 0 if end is None: lowercase_ : List[Any] = len(__SCREAMING_SNAKE_CASE ) - 1 if start >= end: return lowercase_ : Tuple = (start + end) // 2 slowsort(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) slowsort(__SCREAMING_SNAKE_CASE , mid + 1 , __SCREAMING_SNAKE_CASE ) if sequence[end] < sequence[mid]: lowercase_ , lowercase_ : List[str] = sequence[mid], sequence[end] slowsort(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , end - 1 ) if __name__ == "__main__": from doctest import testmod testmod()
93
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging _lowercase : Optional[Any] = logging.get_logger(__name__) _lowercase : List[str] = { "google/pix2struct-textcaps-base": ( "https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json" ), } class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = '''pix2struct_text_model''' lowerCAmelCase_ = ['''past_key_values'''] lowerCAmelCase_ = { '''hidden_size''': '''hidden_size''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self , __SCREAMING_SNAKE_CASE=5_02_44 , __SCREAMING_SNAKE_CASE=7_68 , __SCREAMING_SNAKE_CASE=64 , __SCREAMING_SNAKE_CASE=20_48 , __SCREAMING_SNAKE_CASE=12 , __SCREAMING_SNAKE_CASE=12 , __SCREAMING_SNAKE_CASE=32 , __SCREAMING_SNAKE_CASE=1_28 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=1E-6 , __SCREAMING_SNAKE_CASE=1.0 , __SCREAMING_SNAKE_CASE="gelu_new" , __SCREAMING_SNAKE_CASE=0 , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=0 , __SCREAMING_SNAKE_CASE=1 , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=True , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : Any = vocab_size lowercase_ : Tuple = hidden_size lowercase_ : Optional[Any] = d_kv lowercase_ : List[str] = d_ff lowercase_ : List[str] = num_layers lowercase_ : Optional[Any] = num_heads lowercase_ : Union[str, Any] = relative_attention_num_buckets lowercase_ : Optional[int] = relative_attention_max_distance lowercase_ : Union[str, Any] = dropout_rate lowercase_ : Dict = layer_norm_epsilon lowercase_ : Dict = initializer_factor lowercase_ : List[Any] = use_cache lowercase_ : Optional[int] = eos_token_id lowercase_ : Optional[int] = decoder_start_token_id # for backwards compatibility lowercase_ : Any = dense_act_fn super().__init__( pad_token_id=__SCREAMING_SNAKE_CASE , eos_token_id=__SCREAMING_SNAKE_CASE , decoder_start_token_id=__SCREAMING_SNAKE_CASE , tie_word_embeddings=__SCREAMING_SNAKE_CASE , is_decoder=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) @classmethod def _snake_case ( cls , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" cls._set_token_in_kwargs(__SCREAMING_SNAKE_CASE ) lowercase_ , lowercase_ : Optional[int] = cls.get_config_dict(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) # get the text config dict if we are loading from Pix2StructConfig if config_dict.get('''model_type''' ) == "pix2struct": lowercase_ : List[Any] = config_dict['''text_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'''You are using a model of type {config_dict['model_type']} to instantiate a model of type ''' F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = '''pix2struct_vision_model''' def __init__( self , __SCREAMING_SNAKE_CASE=7_68 , __SCREAMING_SNAKE_CASE=7_68 , __SCREAMING_SNAKE_CASE=20_48 , __SCREAMING_SNAKE_CASE=64 , __SCREAMING_SNAKE_CASE=12 , __SCREAMING_SNAKE_CASE=12 , __SCREAMING_SNAKE_CASE="gelu_new" , __SCREAMING_SNAKE_CASE=1E-6 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=1E-1_0 , __SCREAMING_SNAKE_CASE=1.0 , __SCREAMING_SNAKE_CASE=40_96 , __SCREAMING_SNAKE_CASE=32 , __SCREAMING_SNAKE_CASE=1_28 , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = hidden_size lowercase_ : Any = patch_embed_hidden_size lowercase_ : List[Any] = d_ff lowercase_ : Dict = dropout_rate lowercase_ : Any = num_hidden_layers lowercase_ : Any = num_attention_heads lowercase_ : int = initializer_range lowercase_ : Dict = initializer_factor lowercase_ : Dict = attention_dropout lowercase_ : Optional[Any] = layer_norm_eps lowercase_ : str = dense_act_fn lowercase_ : Dict = seq_len lowercase_ : List[Any] = relative_attention_num_buckets lowercase_ : int = relative_attention_max_distance lowercase_ : Optional[int] = d_kv @classmethod def _snake_case ( cls , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" cls._set_token_in_kwargs(__SCREAMING_SNAKE_CASE ) lowercase_ , lowercase_ : str = cls.get_config_dict(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) # get the vision config dict if we are loading from Pix2StructConfig if config_dict.get('''model_type''' ) == "pix2struct": lowercase_ : Optional[int] = config_dict['''vision_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'''You are using a model of type {config_dict['model_type']} to instantiate a model of type ''' F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = '''pix2struct''' lowerCAmelCase_ = True def __init__( self , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=1.0 , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=True , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" super().__init__(tie_word_embeddings=__SCREAMING_SNAKE_CASE , is_encoder_decoder=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) if text_config is None: lowercase_ : Optional[Any] = {} logger.info('''text_config is None. Initializing the Pix2StructTextConfig with default values.''' ) if vision_config is None: lowercase_ : Dict = {} logger.info('''vision_config is None. Initializing the Pix2StructVisionConfig with default values.''' ) lowercase_ : str = PixaStructTextConfig(**__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = PixaStructVisionConfig(**__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = self.text_config.decoder_start_token_id lowercase_ : Union[str, Any] = self.text_config.pad_token_id lowercase_ : Union[str, Any] = self.text_config.eos_token_id lowercase_ : int = initializer_factor lowercase_ : Any = initializer_range lowercase_ : str = self.initializer_range lowercase_ : str = self.initializer_range lowercase_ : int = is_vqa @classmethod def _snake_case ( cls , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **__SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" lowercase_ : Tuple = copy.deepcopy(self.__dict__ ) lowercase_ : Any = self.text_config.to_dict() lowercase_ : Optional[Any] = self.vision_config.to_dict() lowercase_ : Optional[int] = self.__class__.model_type return output
93
1
'''simple docstring''' _lowercase : Union[str, Any] = "0.18.2" from .configuration_utils import ConfigMixin from .utils import ( OptionalDependencyNotAvailable, is_flax_available, is_inflect_available, is_invisible_watermark_available, is_k_diffusion_available, is_k_diffusion_version, is_librosa_available, is_note_seq_available, is_onnx_available, is_scipy_available, is_torch_available, is_torchsde_available, is_transformers_available, is_transformers_version, is_unidecode_available, logging, ) try: if not is_onnx_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_onnx_objects import * # noqa F403 else: from .pipelines import OnnxRuntimeModel try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_pt_objects import * # noqa F403 else: from .models import ( AutoencoderKL, ControlNetModel, ModelMixin, PriorTransformer, TaFilmDecoder, TransformeraDModel, UNetaDModel, UNetaDConditionModel, UNetaDModel, UNetaDConditionModel, VQModel, ) from .optimization import ( get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, get_scheduler, ) from .pipelines import ( AudioPipelineOutput, ConsistencyModelPipeline, DanceDiffusionPipeline, DDIMPipeline, DDPMPipeline, DiffusionPipeline, DiTPipeline, ImagePipelineOutput, KarrasVePipeline, LDMPipeline, LDMSuperResolutionPipeline, PNDMPipeline, RePaintPipeline, ScoreSdeVePipeline, ) from .schedulers import ( CMStochasticIterativeScheduler, DDIMInverseScheduler, DDIMParallelScheduler, DDIMScheduler, DDPMParallelScheduler, DDPMScheduler, DEISMultistepScheduler, DPMSolverMultistepInverseScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, HeunDiscreteScheduler, IPNDMScheduler, KarrasVeScheduler, KDPMaAncestralDiscreteScheduler, KDPMaDiscreteScheduler, PNDMScheduler, RePaintScheduler, SchedulerMixin, ScoreSdeVeScheduler, UnCLIPScheduler, UniPCMultistepScheduler, VQDiffusionScheduler, ) from .training_utils import EMAModel try: if not (is_torch_available() and is_scipy_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_scipy_objects import * # noqa F403 else: from .schedulers import LMSDiscreteScheduler try: if not (is_torch_available() and is_torchsde_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_torchsde_objects import * # noqa F403 else: from .schedulers import DPMSolverSDEScheduler try: if not (is_torch_available() and is_transformers_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .pipelines import ( AltDiffusionImgaImgPipeline, AltDiffusionPipeline, AudioLDMPipeline, CycleDiffusionPipeline, IFImgaImgPipeline, IFImgaImgSuperResolutionPipeline, IFInpaintingPipeline, IFInpaintingSuperResolutionPipeline, IFPipeline, IFSuperResolutionPipeline, ImageTextPipelineOutput, KandinskyImgaImgPipeline, KandinskyInpaintPipeline, KandinskyPipeline, KandinskyPriorPipeline, KandinskyVaaControlnetImgaImgPipeline, KandinskyVaaControlnetPipeline, KandinskyVaaImgaImgPipeline, KandinskyVaaInpaintPipeline, KandinskyVaaPipeline, KandinskyVaaPriorEmbaEmbPipeline, KandinskyVaaPriorPipeline, LDMTextToImagePipeline, PaintByExamplePipeline, SemanticStableDiffusionPipeline, ShapEImgaImgPipeline, ShapEPipeline, StableDiffusionAttendAndExcitePipeline, StableDiffusionControlNetImgaImgPipeline, StableDiffusionControlNetInpaintPipeline, StableDiffusionControlNetPipeline, StableDiffusionDepthaImgPipeline, StableDiffusionDiffEditPipeline, StableDiffusionImageVariationPipeline, StableDiffusionImgaImgPipeline, StableDiffusionInpaintPipeline, StableDiffusionInpaintPipelineLegacy, StableDiffusionInstructPixaPixPipeline, StableDiffusionLatentUpscalePipeline, StableDiffusionLDMaDPipeline, StableDiffusionModelEditingPipeline, StableDiffusionPanoramaPipeline, StableDiffusionParadigmsPipeline, StableDiffusionPipeline, StableDiffusionPipelineSafe, StableDiffusionPixaPixZeroPipeline, StableDiffusionSAGPipeline, StableDiffusionUpscalePipeline, StableUnCLIPImgaImgPipeline, StableUnCLIPPipeline, TextToVideoSDPipeline, TextToVideoZeroPipeline, UnCLIPImageVariationPipeline, UnCLIPPipeline, UniDiffuserModel, UniDiffuserPipeline, UniDiffuserTextDecoder, VersatileDiffusionDualGuidedPipeline, VersatileDiffusionImageVariationPipeline, VersatileDiffusionPipeline, VersatileDiffusionTextToImagePipeline, VideoToVideoSDPipeline, VQDiffusionPipeline, ) try: if not (is_torch_available() and is_transformers_available() and is_invisible_watermark_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_transformers_and_invisible_watermark_objects import * # noqa F403 else: from .pipelines import StableDiffusionXLImgaImgPipeline, StableDiffusionXLPipeline try: if not (is_torch_available() and is_transformers_available() and is_k_diffusion_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_transformers_and_k_diffusion_objects import * # noqa F403 else: from .pipelines import StableDiffusionKDiffusionPipeline try: if not (is_torch_available() and is_transformers_available() and is_onnx_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_transformers_and_onnx_objects import * # noqa F403 else: from .pipelines import ( OnnxStableDiffusionImgaImgPipeline, OnnxStableDiffusionInpaintPipeline, OnnxStableDiffusionInpaintPipelineLegacy, OnnxStableDiffusionPipeline, OnnxStableDiffusionUpscalePipeline, StableDiffusionOnnxPipeline, ) try: if not (is_torch_available() and is_librosa_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_librosa_objects import * # noqa F403 else: from .pipelines import AudioDiffusionPipeline, Mel try: if not (is_transformers_available() and is_torch_available() and is_note_seq_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_transformers_and_torch_and_note_seq_objects import * # noqa F403 else: from .pipelines import SpectrogramDiffusionPipeline try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_flax_objects import * # noqa F403 else: from .models.controlnet_flax import FlaxControlNetModel from .models.modeling_flax_utils import FlaxModelMixin from .models.unet_ad_condition_flax import FlaxUNetaDConditionModel from .models.vae_flax import FlaxAutoencoderKL from .pipelines import FlaxDiffusionPipeline from .schedulers import ( FlaxDDIMScheduler, FlaxDDPMScheduler, FlaxDPMSolverMultistepScheduler, FlaxKarrasVeScheduler, FlaxLMSDiscreteScheduler, FlaxPNDMScheduler, FlaxSchedulerMixin, FlaxScoreSdeVeScheduler, ) try: if not (is_flax_available() and is_transformers_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_flax_and_transformers_objects import * # noqa F403 else: from .pipelines import ( FlaxStableDiffusionControlNetPipeline, FlaxStableDiffusionImgaImgPipeline, FlaxStableDiffusionInpaintPipeline, FlaxStableDiffusionPipeline, ) try: if not (is_note_seq_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_note_seq_objects import * # noqa F403 else: from .pipelines import MidiProcessor
93
'''simple docstring''' from math import isqrt, loga def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : Any = [True] * max_number for i in range(2 , isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2 , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase_ : Optional[Any] = False return [i for i in range(2 , __SCREAMING_SNAKE_CASE ) if is_prime[i]] def snake_case_ ( __SCREAMING_SNAKE_CASE : int = 800800 , __SCREAMING_SNAKE_CASE : int = 800800 ): """simple docstring""" lowercase_ : Union[str, Any] = degree * loga(__SCREAMING_SNAKE_CASE ) lowercase_ : Any = int(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = calculate_prime_numbers(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = 0 lowercase_ : List[Any] = 0 lowercase_ : Union[str, Any] = len(__SCREAMING_SNAKE_CASE ) - 1 while left < right: while ( prime_numbers[right] * loga(prime_numbers[left] ) + prime_numbers[left] * loga(prime_numbers[right] ) > upper_bound ): right -= 1 hybrid_integers_count += right - left left += 1 return hybrid_integers_count if __name__ == "__main__": print(f"""{solution() = }""")
93
1
'''simple docstring''' from abc import ABC, abstractmethod from typing import List, Optional class lowerCAmelCase__ ( lowerCamelCase_ ): def __init__( self ): """simple docstring""" self.test() def _snake_case ( self ): """simple docstring""" lowercase_ : Optional[int] = 0 lowercase_ : Tuple = False while not completed: if counter == 1: self.reset() lowercase_ : Union[str, Any] = self.advance() if not self.does_advance(__SCREAMING_SNAKE_CASE ): raise Exception( '''Custom Constraint is not defined correctly. self.does_advance(self.advance()) must be true.''' ) lowercase_ , lowercase_ , lowercase_ : Dict = self.update(__SCREAMING_SNAKE_CASE ) counter += 1 if counter > 1_00_00: raise Exception('''update() does not fulfill the constraint.''' ) if self.remaining() != 0: raise Exception('''Custom Constraint is not defined correctly.''' ) @abstractmethod def _snake_case ( self ): """simple docstring""" raise NotImplementedError( F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) @abstractmethod def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" raise NotImplementedError( F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) @abstractmethod def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" raise NotImplementedError( F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) @abstractmethod def _snake_case ( self ): """simple docstring""" raise NotImplementedError( F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) @abstractmethod def _snake_case ( self ): """simple docstring""" raise NotImplementedError( F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) @abstractmethod def _snake_case ( self , __SCREAMING_SNAKE_CASE=False ): """simple docstring""" raise NotImplementedError( F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) class lowerCAmelCase__ ( lowerCamelCase_ ): def __init__( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" super(__SCREAMING_SNAKE_CASE , self ).__init__() if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) or len(__SCREAMING_SNAKE_CASE ) == 0: raise ValueError(F'''`token_ids` has to be a non-empty list, but is {token_ids}.''' ) if any((not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) or token_id < 0) for token_id in token_ids ): raise ValueError(F'''Each list in `token_ids` has to be a list of positive integers, but is {token_ids}.''' ) lowercase_ : List[Any] = token_ids lowercase_ : Any = len(self.token_ids ) lowercase_ : Optional[Any] = -1 # the index of the currently fulfilled step lowercase_ : str = False def _snake_case ( self ): """simple docstring""" if self.completed: return None return self.token_ids[self.fulfilled_idx + 1] def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): raise ValueError(F'''`token_id` has to be an `int`, but is {token_id} of type {type(__SCREAMING_SNAKE_CASE )}''' ) if self.completed: return False return token_id == self.token_ids[self.fulfilled_idx + 1] def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): raise ValueError(F'''`token_id` has to be an `int`, but is {token_id} of type {type(__SCREAMING_SNAKE_CASE )}''' ) lowercase_ : str = False lowercase_ : Optional[Any] = False lowercase_ : Optional[int] = False if self.does_advance(__SCREAMING_SNAKE_CASE ): self.fulfilled_idx += 1 lowercase_ : List[str] = True if self.fulfilled_idx == (self.seqlen - 1): lowercase_ : List[str] = True lowercase_ : Tuple = completed else: # failed to make progress. lowercase_ : Optional[Any] = True self.reset() return stepped, completed, reset def _snake_case ( self ): """simple docstring""" lowercase_ : Any = False lowercase_ : Union[str, Any] = 0 def _snake_case ( self ): """simple docstring""" return self.seqlen - (self.fulfilled_idx + 1) def _snake_case ( self , __SCREAMING_SNAKE_CASE=False ): """simple docstring""" lowercase_ : str = PhrasalConstraint(self.token_ids ) if stateful: lowercase_ : Optional[int] = self.seqlen lowercase_ : Tuple = self.fulfilled_idx lowercase_ : Dict = self.completed return new_constraint class lowerCAmelCase__ : def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=True ): """simple docstring""" lowercase_ : Tuple = max([len(__SCREAMING_SNAKE_CASE ) for one in nested_token_ids] ) lowercase_ : List[str] = {} for token_ids in nested_token_ids: lowercase_ : List[Any] = root for tidx, token_id in enumerate(__SCREAMING_SNAKE_CASE ): if token_id not in level: lowercase_ : Dict = {} lowercase_ : Optional[int] = level[token_id] if no_subsets and self.has_subsets(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): raise ValueError( '''Each list in `nested_token_ids` can\'t be a complete subset of another list, but is''' F''' {nested_token_ids}.''' ) lowercase_ : List[str] = root def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : List[Any] = self.trie for current_token in current_seq: lowercase_ : Any = start[current_token] lowercase_ : Optional[int] = list(start.keys() ) return next_tokens def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Tuple = self.next_tokens(__SCREAMING_SNAKE_CASE ) return len(__SCREAMING_SNAKE_CASE ) == 0 def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : List[str] = list(root.values() ) if len(__SCREAMING_SNAKE_CASE ) == 0: return 1 else: return sum([self.count_leaves(__SCREAMING_SNAKE_CASE ) for nn in next_nodes] ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : List[str] = self.count_leaves(__SCREAMING_SNAKE_CASE ) return len(__SCREAMING_SNAKE_CASE ) != leaf_count class lowerCAmelCase__ ( lowerCamelCase_ ): def __init__( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" super(__SCREAMING_SNAKE_CASE , self ).__init__() if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) or len(__SCREAMING_SNAKE_CASE ) == 0: raise ValueError(F'''`nested_token_ids` has to be a non-empty list, but is {nested_token_ids}.''' ) if any(not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) for token_ids in nested_token_ids ): raise ValueError(F'''`nested_token_ids` has to be a list of lists, but is {nested_token_ids}.''' ) if any( any((not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) or token_id < 0) for token_id in token_ids ) for token_ids in nested_token_ids ): raise ValueError( F'''Each list in `nested_token_ids` has to be a list of positive integers, but is {nested_token_ids}.''' ) lowercase_ : Optional[int] = DisjunctiveTrie(__SCREAMING_SNAKE_CASE ) lowercase_ : Dict = nested_token_ids lowercase_ : Optional[int] = self.trie.max_height lowercase_ : Optional[Any] = [] lowercase_ : List[Any] = False def _snake_case ( self ): """simple docstring""" lowercase_ : str = self.trie.next_tokens(self.current_seq ) if len(__SCREAMING_SNAKE_CASE ) == 0: return None else: return token_list def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): raise ValueError(F'''`token_id` is supposed to be type `int`, but is {token_id} of type {type(__SCREAMING_SNAKE_CASE )}''' ) lowercase_ : Tuple = self.trie.next_tokens(self.current_seq ) return token_id in next_tokens def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): raise ValueError(F'''`token_id` is supposed to be type `int`, but is {token_id} of type {type(__SCREAMING_SNAKE_CASE )}''' ) lowercase_ : Dict = False lowercase_ : int = False lowercase_ : Dict = False if self.does_advance(__SCREAMING_SNAKE_CASE ): self.current_seq.append(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = True else: lowercase_ : List[Any] = True self.reset() lowercase_ : List[Any] = self.trie.reached_leaf(self.current_seq ) lowercase_ : List[Any] = completed return stepped, completed, reset def _snake_case ( self ): """simple docstring""" lowercase_ : int = False lowercase_ : Optional[int] = [] def _snake_case ( self ): """simple docstring""" if self.completed: # since this can be completed without reaching max height return 0 else: return self.seqlen - len(self.current_seq ) def _snake_case ( self , __SCREAMING_SNAKE_CASE=False ): """simple docstring""" lowercase_ : Tuple = DisjunctiveConstraint(self.token_ids ) if stateful: lowercase_ : int = self.seqlen lowercase_ : Tuple = self.current_seq lowercase_ : Optional[Any] = self.completed return new_constraint class lowerCAmelCase__ : def __init__( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Dict = constraints # max # of steps required to fulfill a given constraint lowercase_ : str = max([c.seqlen for c in constraints] ) lowercase_ : int = len(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = False self.init_state() def _snake_case ( self ): """simple docstring""" lowercase_ : int = [] lowercase_ : Dict = None lowercase_ : Dict = [constraint.copy(stateful=__SCREAMING_SNAKE_CASE ) for constraint in self.constraints] def _snake_case ( self ): """simple docstring""" lowercase_ : Dict = 0 if self.inprogress_constraint: # extra points for having a constraint mid-fulfilled add += self.max_seqlen - self.inprogress_constraint.remaining() return (len(self.complete_constraints ) * self.max_seqlen) + add def _snake_case ( self ): """simple docstring""" lowercase_ : List[str] = [] if self.inprogress_constraint is None: for constraint in self.pending_constraints: # "pending" == "unfulfilled yet" lowercase_ : Union[str, Any] = constraint.advance() if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): token_list.append(__SCREAMING_SNAKE_CASE ) elif isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): token_list.extend(__SCREAMING_SNAKE_CASE ) else: lowercase_ : str = self.inprogress_constraint.advance() if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): token_list.append(__SCREAMING_SNAKE_CASE ) elif isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): token_list.extend(__SCREAMING_SNAKE_CASE ) if len(__SCREAMING_SNAKE_CASE ) == 0: return None else: return token_list def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" self.init_state() if token_ids is not None: for token in token_ids: # completes or steps **one** constraint lowercase_ , lowercase_ : List[Any] = self.add(__SCREAMING_SNAKE_CASE ) # the entire list of constraints are fulfilled if self.completed: break def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): raise ValueError(F'''`token_id` should be an `int`, but is `{token_id}`.''' ) lowercase_ , lowercase_ : List[str] = False, False if self.completed: lowercase_ : List[str] = True lowercase_ : Tuple = False return complete, stepped if self.inprogress_constraint is not None: # In the middle of fulfilling a constraint. If the `token_id` *does* makes an incremental progress to current # job, simply update the state lowercase_ , lowercase_ , lowercase_ : Tuple = self.inprogress_constraint.update(__SCREAMING_SNAKE_CASE ) if reset: # 1. If the next token breaks the progress, then we must restart. # e.g. constraint = "I love pies" and sequence so far is "I love" but `token_id` == "books". # But that doesn't mean we self.init_state(), since we only reset the state for this particular # constraint, not the full list of constraints. self.pending_constraints.append(self.inprogress_constraint.copy(stateful=__SCREAMING_SNAKE_CASE ) ) lowercase_ : Tuple = None if complete: # 2. If the next token completes the constraint, move it to completed list, set # inprogress to None. If there are no pending constraints either, then this full list of constraints # is complete. self.complete_constraints.append(self.inprogress_constraint ) lowercase_ : List[Any] = None if len(self.pending_constraints ) == 0: # we're done! lowercase_ : int = True else: # Not in the middle of fulfilling a constraint. So does this `token_id` helps us step towards any of our list # of constraints? for cidx, pending_constraint in enumerate(self.pending_constraints ): if pending_constraint.does_advance(__SCREAMING_SNAKE_CASE ): lowercase_ , lowercase_ , lowercase_ : str = pending_constraint.update(__SCREAMING_SNAKE_CASE ) if not stepped: raise Exception( '''`constraint.update(token_id)` is not yielding incremental progress, ''' '''even though `constraint.does_advance(token_id)` is true.''' ) if complete: self.complete_constraints.append(__SCREAMING_SNAKE_CASE ) lowercase_ : str = None if not complete and stepped: lowercase_ : Any = pending_constraint if complete or stepped: # If we made any progress at all, then it's at least not a "pending constraint". lowercase_ : List[Any] = ( self.pending_constraints[:cidx] + self.pending_constraints[cidx + 1 :] ) if len(self.pending_constraints ) == 0 and self.inprogress_constraint is None: # If there's no longer any pending after this and no inprogress either, then we must be # complete. lowercase_ : Union[str, Any] = True break # prevent accidentally stepping through multiple constraints with just one token. return complete, stepped def _snake_case ( self , __SCREAMING_SNAKE_CASE=True ): """simple docstring""" lowercase_ : str = ConstraintListState(self.constraints ) # we actually never though self.constraints objects # throughout this process. So it's at initialization state. if stateful: lowercase_ : Dict = [ constraint.copy(stateful=__SCREAMING_SNAKE_CASE ) for constraint in self.complete_constraints ] if self.inprogress_constraint is not None: lowercase_ : int = self.inprogress_constraint.copy(stateful=__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = [constraint.copy() for constraint in self.pending_constraints] return new_state
93
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices _lowercase : int = logging.get_logger(__name__) _lowercase : List[Any] = { "shi-labs/nat-mini-in1k-224": "https://huggingface.co/shi-labs/nat-mini-in1k-224/resolve/main/config.json", # See all Nat models at https://huggingface.co/models?filter=nat } class lowerCAmelCase__ ( lowerCamelCase_ , lowerCamelCase_ ): lowerCAmelCase_ = '''nat''' lowerCAmelCase_ = { '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self , __SCREAMING_SNAKE_CASE=4 , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=64 , __SCREAMING_SNAKE_CASE=[3, 4, 6, 5] , __SCREAMING_SNAKE_CASE=[2, 4, 8, 16] , __SCREAMING_SNAKE_CASE=7 , __SCREAMING_SNAKE_CASE=3.0 , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE="gelu" , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=1E-5 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = patch_size lowercase_ : List[Any] = num_channels lowercase_ : str = embed_dim lowercase_ : List[str] = depths lowercase_ : str = len(__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = num_heads lowercase_ : int = kernel_size lowercase_ : Union[str, Any] = mlp_ratio lowercase_ : Optional[int] = qkv_bias lowercase_ : List[Any] = hidden_dropout_prob lowercase_ : Optional[int] = attention_probs_dropout_prob lowercase_ : List[Any] = drop_path_rate lowercase_ : List[Any] = hidden_act lowercase_ : int = layer_norm_eps lowercase_ : int = initializer_range # we set the hidden_size attribute in order to make Nat work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model lowercase_ : Dict = int(embed_dim * 2 ** (len(__SCREAMING_SNAKE_CASE ) - 1) ) lowercase_ : Tuple = layer_scale_init_value lowercase_ : Union[str, Any] = ['''stem'''] + [F'''stage{idx}''' for idx in range(1 , len(__SCREAMING_SNAKE_CASE ) + 1 )] lowercase_ , lowercase_ : int = get_aligned_output_features_output_indices( out_features=__SCREAMING_SNAKE_CASE , out_indices=__SCREAMING_SNAKE_CASE , stage_names=self.stage_names )
93
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available _lowercase : List[Any] = { "configuration_roc_bert": ["ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "RoCBertConfig"], "tokenization_roc_bert": ["RoCBertTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: pass try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : Union[str, Any] = [ "ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST", "RoCBertForCausalLM", "RoCBertForMaskedLM", "RoCBertForMultipleChoice", "RoCBertForPreTraining", "RoCBertForQuestionAnswering", "RoCBertForSequenceClassification", "RoCBertForTokenClassification", "RoCBertLayer", "RoCBertModel", "RoCBertPreTrainedModel", "load_tf_weights_in_roc_bert", ] if TYPE_CHECKING: from .configuration_roc_bert import ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, RoCBertConfig from .tokenization_roc_bert import RoCBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: raise OptionalDependencyNotAvailable() try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roc_bert import ( ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, RoCBertForCausalLM, RoCBertForMaskedLM, RoCBertForMultipleChoice, RoCBertForPreTraining, RoCBertForQuestionAnswering, RoCBertForSequenceClassification, RoCBertForTokenClassification, RoCBertLayer, RoCBertModel, RoCBertPreTrainedModel, load_tf_weights_in_roc_bert, ) else: import sys _lowercase : str = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
93
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _lowercase : Union[str, Any] = { "configuration_mask2former": [ "MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "Mask2FormerConfig", ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : Optional[int] = ["Mask2FormerImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : str = [ "MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "Mask2FormerForUniversalSegmentation", "Mask2FormerModel", "Mask2FormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_maskaformer import MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskaFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_maskaformer import MaskaFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskaformer import ( MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskaFormerForUniversalSegmentation, MaskaFormerModel, MaskaFormerPreTrainedModel, ) else: import sys _lowercase : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure)
93
1
'''simple docstring''' _lowercase : Any = [ (1_0_0_0, "M"), (9_0_0, "CM"), (5_0_0, "D"), (4_0_0, "CD"), (1_0_0, "C"), (9_0, "XC"), (5_0, "L"), (4_0, "XL"), (1_0, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I"), ] def snake_case_ ( __SCREAMING_SNAKE_CASE : str ): """simple docstring""" lowercase_ : Tuple = {'''I''': 1, '''V''': 5, '''X''': 10, '''L''': 50, '''C''': 100, '''D''': 500, '''M''': 1000} lowercase_ : List[Any] = 0 lowercase_ : Union[str, Any] = 0 while place < len(__SCREAMING_SNAKE_CASE ): if (place + 1 < len(__SCREAMING_SNAKE_CASE )) and (vals[roman[place]] < vals[roman[place + 1]]): total += vals[roman[place + 1]] - vals[roman[place]] place += 2 else: total += vals[roman[place]] place += 1 return total def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : str = [] for arabic, roman in ROMAN: ((lowercase_) , (lowercase_)) : Optional[int] = divmod(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) result.append(roman * factor ) if number == 0: break return "".join(__SCREAMING_SNAKE_CASE ) if __name__ == "__main__": import doctest doctest.testmod()
93
'''simple docstring''' import unittest from knapsack import greedy_knapsack as kp class lowerCAmelCase__ ( unittest.TestCase ): def _snake_case ( self ): """simple docstring""" lowercase_ : List[str] = [10, 20, 30, 40, 50, 60] lowercase_ : Optional[Any] = [2, 4, 6, 8, 10, 12] lowercase_ : Union[str, Any] = 1_00 self.assertEqual(kp.calc_profit(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) , 2_10 ) def _snake_case ( self ): """simple docstring""" self.assertRaisesRegex(__SCREAMING_SNAKE_CASE , '''max_weight must greater than zero.''' ) def _snake_case ( self ): """simple docstring""" self.assertRaisesRegex(__SCREAMING_SNAKE_CASE , '''Weight can not be negative.''' ) def _snake_case ( self ): """simple docstring""" self.assertRaisesRegex(__SCREAMING_SNAKE_CASE , '''Profit can not be negative.''' ) def _snake_case ( self ): """simple docstring""" self.assertRaisesRegex(__SCREAMING_SNAKE_CASE , '''max_weight must greater than zero.''' ) def _snake_case ( self ): """simple docstring""" self.assertRaisesRegex( __SCREAMING_SNAKE_CASE , '''The length of profit and weight must be same.''' ) if __name__ == "__main__": unittest.main()
93
1
'''simple docstring''' import requests from bsa import BeautifulSoup def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : dict ): """simple docstring""" lowercase_ : Union[str, Any] = BeautifulSoup(requests.get(__SCREAMING_SNAKE_CASE , params=__SCREAMING_SNAKE_CASE ).content , '''html.parser''' ) lowercase_ : List[Any] = soup.find('''div''' , attrs={'''class''': '''gs_ri'''} ) lowercase_ : List[str] = div.find('''div''' , attrs={'''class''': '''gs_fl'''} ).find_all('''a''' ) return anchors[2].get_text() if __name__ == "__main__": _lowercase : Optional[int] = { "title": ( "Precisely geometry controlled microsupercapacitors for ultrahigh areal " "capacitance, volumetric capacitance, and energy density" ), "journal": "Chem. Mater.", "volume": 3_0, "pages": "3979-3990", "year": 2_0_1_8, "hl": "en", } print(get_citation("https://scholar.google.com/scholar_lookup", params=params))
93
'''simple docstring''' import argparse import copy def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[int] ): """simple docstring""" lowercase_ : List[Any] = {} with open(__SCREAMING_SNAKE_CASE ) as f: for line in f: if line.split()[0] not in dict_of_neighbours: lowercase_ : Union[str, Any] = [] _list.append([line.split()[1], line.split()[2]] ) lowercase_ : str = _list else: dict_of_neighbours[line.split()[0]].append( [line.split()[1], line.split()[2]] ) if line.split()[1] not in dict_of_neighbours: lowercase_ : Optional[int] = [] _list.append([line.split()[0], line.split()[2]] ) lowercase_ : Dict = _list else: dict_of_neighbours[line.split()[1]].append( [line.split()[0], line.split()[2]] ) return dict_of_neighbours def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE ) as f: lowercase_ : List[str] = f.read(1 ) lowercase_ : Optional[int] = start_node lowercase_ : Any = [] lowercase_ : List[str] = start_node lowercase_ : Optional[Any] = 0 while visiting not in first_solution: lowercase_ : Any = 10000 for k in dict_of_neighbours[visiting]: if int(k[1] ) < int(__SCREAMING_SNAKE_CASE ) and k[0] not in first_solution: lowercase_ : List[Any] = k[1] lowercase_ : List[Any] = k[0] first_solution.append(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = distance_of_first_solution + int(__SCREAMING_SNAKE_CASE ) lowercase_ : int = best_node first_solution.append(__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = 0 for k in dict_of_neighbours[first_solution[-2]]: if k[0] == start_node: break position += 1 lowercase_ : Optional[Any] = ( distance_of_first_solution + int(dict_of_neighbours[first_solution[-2]][position][1] ) - 10000 ) return first_solution, distance_of_first_solution def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" lowercase_ : Tuple = [] for n in solution[1:-1]: lowercase_ : List[str] = solution.index(__SCREAMING_SNAKE_CASE ) for kn in solution[1:-1]: lowercase_ : Any = solution.index(__SCREAMING_SNAKE_CASE ) if n == kn: continue lowercase_ : Dict = copy.deepcopy(__SCREAMING_SNAKE_CASE ) lowercase_ : Dict = kn lowercase_ : List[Any] = n lowercase_ : str = 0 for k in _tmp[:-1]: lowercase_ : Tuple = _tmp[_tmp.index(__SCREAMING_SNAKE_CASE ) + 1] for i in dict_of_neighbours[k]: if i[0] == next_node: lowercase_ : Optional[Any] = distance + int(i[1] ) _tmp.append(__SCREAMING_SNAKE_CASE ) if _tmp not in neighborhood_of_solution: neighborhood_of_solution.append(_tmp ) lowercase_ : Union[str, Any] = 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 snake_case_ ( __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" lowercase_ : Optional[int] = 1 lowercase_ : List[str] = first_solution lowercase_ : Dict = [] lowercase_ : List[str] = distance_of_first_solution lowercase_ : Optional[Any] = solution while count <= iters: lowercase_ : int = find_neighborhood(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : Any = 0 lowercase_ : Dict = neighborhood[index_of_best_solution] lowercase_ : Optional[Any] = len(__SCREAMING_SNAKE_CASE ) - 1 lowercase_ : Tuple = False while not found: lowercase_ : Optional[int] = 0 while i < len(__SCREAMING_SNAKE_CASE ): if best_solution[i] != solution[i]: lowercase_ : Tuple = best_solution[i] lowercase_ : Optional[int] = solution[i] break lowercase_ : 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] ) lowercase_ : Tuple = True lowercase_ : Optional[int] = best_solution[:-1] lowercase_ : Optional[Any] = neighborhood[index_of_best_solution][best_cost_index] if cost < best_cost: lowercase_ : Optional[Any] = cost lowercase_ : int = solution else: lowercase_ : Any = index_of_best_solution + 1 lowercase_ : Any = neighborhood[index_of_best_solution] if len(__SCREAMING_SNAKE_CASE ) >= size: tabu_list.pop(0 ) lowercase_ : List[Any] = count + 1 return best_solution_ever, best_cost def snake_case_ ( __SCREAMING_SNAKE_CASE : List[str]=None ): """simple docstring""" lowercase_ : Any = generate_neighbours(args.File ) lowercase_ , lowercase_ : Union[str, Any] = generate_first_solution( args.File , __SCREAMING_SNAKE_CASE ) lowercase_ , lowercase_ : Optional[int] = 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__": _lowercase : Any = 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())
93
1
'''simple docstring''' def snake_case_ ( __SCREAMING_SNAKE_CASE : str ): """simple docstring""" if n_term == "": return [] lowercase_ : list = [] for temp in range(int(__SCREAMING_SNAKE_CASE ) ): series.append(F'''1/{temp + 1}''' if series else '''1''' ) return series if __name__ == "__main__": _lowercase : Tuple = input("Enter the last number (nth term) of the Harmonic Series") print("Formula of Harmonic Series => 1+1/2+1/3 ..... 1/n") print(harmonic_series(nth_term))
93
'''simple docstring''' import unittest from transformers import is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device if is_torch_available(): from transformers import AutoModelForSeqaSeqLM, AutoTokenizer @require_torch @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( unittest.TestCase ): @slow def _snake_case ( self ): """simple docstring""" lowercase_ : Dict = AutoModelForSeqaSeqLM.from_pretrained('''google/mt5-small''' , return_dict=__SCREAMING_SNAKE_CASE ).to(__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = AutoTokenizer.from_pretrained('''google/mt5-small''' ) lowercase_ : int = tokenizer('''Hello there''' , return_tensors='''pt''' ).input_ids lowercase_ : Union[str, Any] = tokenizer('''Hi I am''' , return_tensors='''pt''' ).input_ids lowercase_ : Union[str, Any] = model(input_ids.to(__SCREAMING_SNAKE_CASE ) , labels=labels.to(__SCREAMING_SNAKE_CASE ) ).loss lowercase_ : int = -(labels.shape[-1] * loss.item()) lowercase_ : Any = -84.9_127 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1E-4 )
93
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. from pathlib import Path import torch from ...utils import is_npu_available, is_xpu_available from .config_args import ClusterConfig, default_json_config_file from .config_utils import SubcommandHelpFormatter _lowercase : str = "Create a default config file for Accelerate with only a few flags set." def snake_case_ ( __SCREAMING_SNAKE_CASE : Any="no" , __SCREAMING_SNAKE_CASE : str = default_json_config_file , __SCREAMING_SNAKE_CASE : bool = False ): """simple docstring""" lowercase_ : Union[str, Any] = Path(__SCREAMING_SNAKE_CASE ) path.parent.mkdir(parents=__SCREAMING_SNAKE_CASE , exist_ok=__SCREAMING_SNAKE_CASE ) if path.exists(): print( F'''Configuration already exists at {save_location}, will not override. Run `accelerate config` manually or pass a different `save_location`.''' ) return False lowercase_ : List[str] = mixed_precision.lower() if mixed_precision not in ["no", "fp16", "bf16", "fp8"]: raise ValueError( F'''`mixed_precision` should be one of \'no\', \'fp16\', \'bf16\', or \'fp8\'. Received {mixed_precision}''' ) lowercase_ : Any = { '''compute_environment''': '''LOCAL_MACHINE''', '''mixed_precision''': mixed_precision, } if torch.cuda.is_available(): lowercase_ : List[str] = torch.cuda.device_count() lowercase_ : str = num_gpus lowercase_ : Optional[int] = False if num_gpus > 1: lowercase_ : List[str] = '''MULTI_GPU''' else: lowercase_ : Dict = '''NO''' elif is_xpu_available() and use_xpu: lowercase_ : List[str] = torch.xpu.device_count() lowercase_ : List[Any] = num_xpus lowercase_ : Optional[Any] = False if num_xpus > 1: lowercase_ : Dict = '''MULTI_XPU''' else: lowercase_ : Optional[int] = '''NO''' elif is_npu_available(): lowercase_ : List[str] = torch.npu.device_count() lowercase_ : int = num_npus lowercase_ : Tuple = False if num_npus > 1: lowercase_ : Union[str, Any] = '''MULTI_NPU''' else: lowercase_ : int = '''NO''' else: lowercase_ : List[Any] = 0 lowercase_ : Union[str, Any] = True lowercase_ : Optional[int] = 1 lowercase_ : Tuple = '''NO''' lowercase_ : Optional[int] = ClusterConfig(**__SCREAMING_SNAKE_CASE ) config.to_json_file(__SCREAMING_SNAKE_CASE ) return path def snake_case_ ( __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Optional[int] ): """simple docstring""" lowercase_ : Optional[int] = parser.add_parser('''default''' , parents=__SCREAMING_SNAKE_CASE , help=__SCREAMING_SNAKE_CASE , formatter_class=__SCREAMING_SNAKE_CASE ) parser.add_argument( '''--config_file''' , default=__SCREAMING_SNAKE_CASE , help=( '''The path to use to store the config file. Will default to a file named default_config.yaml in the cache ''' '''location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have ''' '''such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed ''' '''with \'huggingface\'.''' ) , dest='''save_location''' , ) parser.add_argument( '''--mixed_precision''' , choices=['''no''', '''fp16''', '''bf16'''] , type=__SCREAMING_SNAKE_CASE , help='''Whether or not to use mixed precision training. ''' '''Choose between FP16 and BF16 (bfloat16) training. ''' '''BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later.''' , default='''no''' , ) parser.set_defaults(func=__SCREAMING_SNAKE_CASE ) return parser def snake_case_ ( __SCREAMING_SNAKE_CASE : Any ): """simple docstring""" lowercase_ : Dict = write_basic_config(args.mixed_precision , args.save_location ) if config_file: print(F'''accelerate configuration saved at {config_file}''' )
93
'''simple docstring''' def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : str ): """simple docstring""" lowercase_ : List[str] = len(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = [] for i in range(len(__SCREAMING_SNAKE_CASE ) - pat_len + 1 ): lowercase_ : Tuple = True for j in range(__SCREAMING_SNAKE_CASE ): if s[i + j] != pattern[j]: lowercase_ : List[str] = False break if match_found: position.append(__SCREAMING_SNAKE_CASE ) return position if __name__ == "__main__": assert naive_pattern_search("ABCDEFG", "DE") == [3] print(naive_pattern_search("ABAAABCDBBABCDDEBCABC", "ABC"))
93
1
'''simple docstring''' import argparse import glob import importlib.util import os import re import black from doc_builder.style_doc import style_docstrings_in_code # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py _lowercase : int = "src/diffusers" _lowercase : Any = "." # This is to make sure the diffusers module imported is the one in the repo. _lowercase : List[str] = importlib.util.spec_from_file_location( "diffusers", os.path.join(DIFFUSERS_PATH, "__init__.py"), submodule_search_locations=[DIFFUSERS_PATH], ) _lowercase : str = spec.loader.load_module() def snake_case_ ( __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" return line.startswith(__SCREAMING_SNAKE_CASE ) or len(__SCREAMING_SNAKE_CASE ) <= 1 or re.search(R'''^\s*\)(\s*->.*:|:)\s*$''' , __SCREAMING_SNAKE_CASE ) is not None def snake_case_ ( __SCREAMING_SNAKE_CASE : str ): """simple docstring""" lowercase_ : List[str] = object_name.split('''.''' ) lowercase_ : Optional[int] = 0 # First let's find the module where our object lives. lowercase_ : Optional[Any] = parts[i] while i < len(__SCREAMING_SNAKE_CASE ) and not os.path.isfile(os.path.join(__SCREAMING_SNAKE_CASE , F'''{module}.py''' ) ): i += 1 if i < len(__SCREAMING_SNAKE_CASE ): lowercase_ : Optional[Any] = os.path.join(__SCREAMING_SNAKE_CASE , parts[i] ) if i >= len(__SCREAMING_SNAKE_CASE ): raise ValueError(F'''`object_name` should begin with the name of a module of diffusers but got {object_name}.''' ) with open(os.path.join(__SCREAMING_SNAKE_CASE , F'''{module}.py''' ) , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: lowercase_ : Dict = f.readlines() # Now let's find the class / func in the code! lowercase_ : Tuple = '''''' lowercase_ : Union[str, Any] = 0 for name in parts[i + 1 :]: while ( line_index < len(__SCREAMING_SNAKE_CASE ) and re.search(RF'''^{indent}(class|def)\s+{name}(\(|\:)''' , lines[line_index] ) is None ): line_index += 1 indent += " " line_index += 1 if line_index >= len(__SCREAMING_SNAKE_CASE ): raise ValueError(F''' {object_name} does not match any function or class in {module}.''' ) # We found the beginning of the class / func, now let's find the end (when the indent diminishes). lowercase_ : Optional[Any] = line_index while line_index < len(__SCREAMING_SNAKE_CASE ) and _should_continue(lines[line_index] , __SCREAMING_SNAKE_CASE ): line_index += 1 # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 lowercase_ : List[Any] = lines[start_index:line_index] return "".join(__SCREAMING_SNAKE_CASE ) _lowercase : str = re.compile(r"^(\s*)#\s*Copied from\s+diffusers\.(\S+\.\S+)\s*($|\S.*$)") _lowercase : Optional[int] = re.compile(r"^\s*(\S+)->(\S+)(\s+.*|$)") _lowercase : List[str] = re.compile(r"<FILL\s+[^>]*>") def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : Any = code.split('''\n''' ) lowercase_ : Tuple = 0 while idx < len(__SCREAMING_SNAKE_CASE ) and len(lines[idx] ) == 0: idx += 1 if idx < len(__SCREAMING_SNAKE_CASE ): return re.search(R'''^(\s*)\S''' , lines[idx] ).groups()[0] return "" def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : Union[str, Any] = len(get_indent(__SCREAMING_SNAKE_CASE ) ) > 0 if has_indent: lowercase_ : str = F'''class Bla:\n{code}''' lowercase_ : Any = black.Mode(target_versions={black.TargetVersion.PYaa} , line_length=119 , preview=__SCREAMING_SNAKE_CASE ) lowercase_ : Any = black.format_str(__SCREAMING_SNAKE_CASE , mode=__SCREAMING_SNAKE_CASE ) lowercase_ , lowercase_ : int = style_docstrings_in_code(__SCREAMING_SNAKE_CASE ) return result[len('''class Bla:\n''' ) :] if has_indent else result def snake_case_ ( __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Union[str, Any]=False ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: lowercase_ : Dict = f.readlines() lowercase_ : Dict = [] lowercase_ : Optional[Any] = 0 # Not a for loop cause `lines` is going to change (if `overwrite=True`). while line_index < len(__SCREAMING_SNAKE_CASE ): lowercase_ : int = _re_copy_warning.search(lines[line_index] ) if search is None: line_index += 1 continue # There is some copied code here, let's retrieve the original. lowercase_ , lowercase_ , lowercase_ : int = search.groups() lowercase_ : Any = find_code_in_diffusers(__SCREAMING_SNAKE_CASE ) lowercase_ : List[str] = get_indent(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = line_index + 1 if indent == theoretical_indent else line_index + 2 lowercase_ : int = theoretical_indent lowercase_ : Any = start_index # Loop to check the observed code, stop when indentation diminishes or if we see a End copy comment. lowercase_ : Union[str, Any] = True while line_index < len(__SCREAMING_SNAKE_CASE ) and should_continue: line_index += 1 if line_index >= len(__SCREAMING_SNAKE_CASE ): break lowercase_ : Tuple = lines[line_index] lowercase_ : List[Any] = _should_continue(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) and re.search(F'''^{indent}# End copy''' , __SCREAMING_SNAKE_CASE ) is None # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 lowercase_ : List[str] = lines[start_index:line_index] lowercase_ : List[str] = ''''''.join(__SCREAMING_SNAKE_CASE ) # Remove any nested `Copied from` comments to avoid circular copies lowercase_ : Tuple = [line for line in theoretical_code.split('''\n''' ) if _re_copy_warning.search(__SCREAMING_SNAKE_CASE ) is None] lowercase_ : Any = '''\n'''.join(__SCREAMING_SNAKE_CASE ) # Before comparing, use the `replace_pattern` on the original code. if len(__SCREAMING_SNAKE_CASE ) > 0: lowercase_ : Any = replace_pattern.replace('''with''' , '''''' ).split(''',''' ) lowercase_ : Union[str, Any] = [_re_replace_pattern.search(__SCREAMING_SNAKE_CASE ) for p in patterns] for pattern in patterns: if pattern is None: continue lowercase_ , lowercase_ , lowercase_ : List[str] = pattern.groups() lowercase_ : Dict = re.sub(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if option.strip() == "all-casing": lowercase_ : int = re.sub(obja.lower() , obja.lower() , __SCREAMING_SNAKE_CASE ) lowercase_ : str = re.sub(obja.upper() , obja.upper() , __SCREAMING_SNAKE_CASE ) # Blackify after replacement. To be able to do that, we need the header (class or function definition) # from the previous line lowercase_ : Optional[int] = blackify(lines[start_index - 1] + theoretical_code ) lowercase_ : Any = theoretical_code[len(lines[start_index - 1] ) :] # Test for a diff and act accordingly. if observed_code != theoretical_code: diffs.append([object_name, start_index] ) if overwrite: lowercase_ : int = lines[:start_index] + [theoretical_code] + lines[line_index:] lowercase_ : Optional[Any] = start_index + 1 if overwrite and len(__SCREAMING_SNAKE_CASE ) > 0: # Warn the user a file has been modified. print(F'''Detected changes, rewriting {filename}.''' ) with open(__SCREAMING_SNAKE_CASE , '''w''' , encoding='''utf-8''' , newline='''\n''' ) as f: f.writelines(__SCREAMING_SNAKE_CASE ) return diffs def snake_case_ ( __SCREAMING_SNAKE_CASE : bool = False ): """simple docstring""" lowercase_ : Dict = glob.glob(os.path.join(__SCREAMING_SNAKE_CASE , '''**/*.py''' ) , recursive=__SCREAMING_SNAKE_CASE ) lowercase_ : Any = [] for filename in all_files: lowercase_ : List[Any] = is_copy_consistent(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) diffs += [F'''- {filename}: copy does not match {d[0]} at line {d[1]}''' for d in new_diffs] if not overwrite and len(__SCREAMING_SNAKE_CASE ) > 0: lowercase_ : Union[str, Any] = '''\n'''.join(__SCREAMING_SNAKE_CASE ) raise Exception( '''Found the following copy inconsistencies:\n''' + diff + '''\nRun `make fix-copies` or `python utils/check_copies.py --fix_and_overwrite` to fix them.''' ) if __name__ == "__main__": _lowercase : Tuple = argparse.ArgumentParser() parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.") _lowercase : Optional[int] = parser.parse_args() check_copies(args.fix_and_overwrite)
93
'''simple docstring''' import importlib import inspect import json import os import re import shutil import sys from pathlib import Path from typing import Dict, Optional, Union from urllib import request from huggingface_hub import HfFolder, cached_download, hf_hub_download, model_info from packaging import version from .. import __version__ from . import DIFFUSERS_DYNAMIC_MODULE_NAME, HF_MODULES_CACHE, logging _lowercase : Optional[Any] = ( "https://raw.githubusercontent.com/huggingface/diffusers/{revision}/examples/community/{pipeline}.py" ) _lowercase : Tuple = logging.get_logger(__name__) # pylint: disable=invalid-name def snake_case_ ( ): """simple docstring""" lowercase_ : Tuple = '''https://pypi.org/pypi/diffusers/json''' lowercase_ : Tuple = json.loads(request.urlopen(__SCREAMING_SNAKE_CASE ).read() )['''releases'''].keys() return sorted(__SCREAMING_SNAKE_CASE , key=lambda __SCREAMING_SNAKE_CASE : version.Version(__SCREAMING_SNAKE_CASE ) ) def snake_case_ ( ): """simple docstring""" if HF_MODULES_CACHE in sys.path: return sys.path.append(__SCREAMING_SNAKE_CASE ) os.makedirs(__SCREAMING_SNAKE_CASE , exist_ok=__SCREAMING_SNAKE_CASE ) lowercase_ : List[Any] = Path(__SCREAMING_SNAKE_CASE ) / '''__init__.py''' if not init_path.exists(): init_path.touch() def snake_case_ ( __SCREAMING_SNAKE_CASE : Union[str, os.PathLike] ): """simple docstring""" init_hf_modules() lowercase_ : Optional[int] = Path(__SCREAMING_SNAKE_CASE ) / name # If the parent module does not exist yet, recursively create it. if not dynamic_module_path.parent.exists(): create_dynamic_module(dynamic_module_path.parent ) os.makedirs(__SCREAMING_SNAKE_CASE , exist_ok=__SCREAMING_SNAKE_CASE ) lowercase_ : str = dynamic_module_path / '''__init__.py''' if not init_path.exists(): init_path.touch() def snake_case_ ( __SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE , '''r''' , encoding='''utf-8''' ) as f: lowercase_ : int = f.read() # Imports of the form `import .xxx` lowercase_ : List[Any] = re.findall('''^\s*import\s+\.(\S+)\s*$''' , __SCREAMING_SNAKE_CASE , flags=re.MULTILINE ) # Imports of the form `from .xxx import yyy` relative_imports += re.findall('''^\s*from\s+\.(\S+)\s+import''' , __SCREAMING_SNAKE_CASE , flags=re.MULTILINE ) # Unique-ify return list(set(__SCREAMING_SNAKE_CASE ) ) def snake_case_ ( __SCREAMING_SNAKE_CASE : str ): """simple docstring""" lowercase_ : int = False lowercase_ : Any = [module_file] lowercase_ : Dict = [] # Let's recurse through all relative imports while not no_change: lowercase_ : Dict = [] for f in files_to_check: new_imports.extend(get_relative_imports(__SCREAMING_SNAKE_CASE ) ) lowercase_ : Union[str, Any] = Path(__SCREAMING_SNAKE_CASE ).parent lowercase_ : Optional[int] = [str(module_path / m ) for m in new_imports] lowercase_ : str = [f for f in new_import_files if f not in all_relative_imports] lowercase_ : int = [F'''{f}.py''' for f in new_import_files] lowercase_ : Optional[Any] = len(__SCREAMING_SNAKE_CASE ) == 0 all_relative_imports.extend(__SCREAMING_SNAKE_CASE ) return all_relative_imports def snake_case_ ( __SCREAMING_SNAKE_CASE : Any ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE , '''r''' , encoding='''utf-8''' ) as f: lowercase_ : Union[str, Any] = f.read() # Imports of the form `import xxx` lowercase_ : Any = re.findall('''^\s*import\s+(\S+)\s*$''' , __SCREAMING_SNAKE_CASE , flags=re.MULTILINE ) # Imports of the form `from xxx import yyy` imports += re.findall('''^\s*from\s+(\S+)\s+import''' , __SCREAMING_SNAKE_CASE , flags=re.MULTILINE ) # Only keep the top-level module lowercase_ : List[str] = [imp.split('''.''' )[0] for imp in imports if not imp.startswith('''.''' )] # Unique-ify and test we got them all lowercase_ : Any = list(set(__SCREAMING_SNAKE_CASE ) ) lowercase_ : Optional[Any] = [] for imp in imports: try: importlib.import_module(__SCREAMING_SNAKE_CASE ) except ImportError: missing_packages.append(__SCREAMING_SNAKE_CASE ) if len(__SCREAMING_SNAKE_CASE ) > 0: raise ImportError( '''This modeling file requires the following packages that were not found in your environment: ''' F'''{', '.join(__SCREAMING_SNAKE_CASE )}. Run `pip install {' '.join(__SCREAMING_SNAKE_CASE )}`''' ) return get_relative_imports(__SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" lowercase_ : List[Any] = module_path.replace(os.path.sep , '''.''' ) lowercase_ : Any = importlib.import_module(__SCREAMING_SNAKE_CASE ) if class_name is None: return find_pipeline_class(__SCREAMING_SNAKE_CASE ) return getattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" from ..pipelines import DiffusionPipeline lowercase_ : int = dict(inspect.getmembers(__SCREAMING_SNAKE_CASE , inspect.isclass ) ) lowercase_ : Optional[Any] = None for cls_name, cls in cls_members.items(): if ( cls_name != DiffusionPipeline.__name__ and issubclass(cls , __SCREAMING_SNAKE_CASE ) and cls.__module__.split('''.''' )[0] != "diffusers" ): if pipeline_class is not None: raise ValueError( F'''Multiple classes that inherit from {DiffusionPipeline.__name__} have been found:''' F''' {pipeline_class.__name__}, and {cls_name}. Please make sure to define only one in''' F''' {loaded_module}.''' ) lowercase_ : List[Any] = cls return pipeline_class def snake_case_ ( __SCREAMING_SNAKE_CASE : Union[str, os.PathLike] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Optional[Union[str, os.PathLike]] = None , __SCREAMING_SNAKE_CASE : bool = False , __SCREAMING_SNAKE_CASE : bool = False , __SCREAMING_SNAKE_CASE : Optional[Dict[str, str]] = None , __SCREAMING_SNAKE_CASE : Optional[Union[bool, str]] = None , __SCREAMING_SNAKE_CASE : Optional[str] = None , __SCREAMING_SNAKE_CASE : bool = False , ): """simple docstring""" lowercase_ : Dict = str(__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if os.path.isfile(__SCREAMING_SNAKE_CASE ): lowercase_ : Dict = module_file_or_url lowercase_ : int = '''local''' elif pretrained_model_name_or_path.count('''/''' ) == 0: lowercase_ : Optional[int] = get_diffusers_versions() # cut ".dev0" lowercase_ : List[Any] = '''v''' + '''.'''.join(__version__.split('''.''' )[:3] ) # retrieve github version that matches if revision is None: lowercase_ : List[str] = latest_version if latest_version[1:] in available_versions else '''main''' logger.info(F'''Defaulting to latest_version: {revision}.''' ) elif revision in available_versions: lowercase_ : List[str] = F'''v{revision}''' elif revision == "main": lowercase_ : Optional[Any] = revision else: raise ValueError( F'''`custom_revision`: {revision} does not exist. Please make sure to choose one of''' F''' {', '.join(available_versions + ['main'] )}.''' ) # community pipeline on GitHub lowercase_ : Tuple = COMMUNITY_PIPELINES_URL.format(revision=__SCREAMING_SNAKE_CASE , pipeline=__SCREAMING_SNAKE_CASE ) try: lowercase_ : Optional[Any] = cached_download( __SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE , force_download=__SCREAMING_SNAKE_CASE , proxies=__SCREAMING_SNAKE_CASE , resume_download=__SCREAMING_SNAKE_CASE , local_files_only=__SCREAMING_SNAKE_CASE , use_auth_token=__SCREAMING_SNAKE_CASE , ) lowercase_ : Tuple = '''git''' lowercase_ : Tuple = pretrained_model_name_or_path + '''.py''' except EnvironmentError: logger.error(F'''Could not locate the {module_file} inside {pretrained_model_name_or_path}.''' ) raise else: try: # Load from URL or cache if already cached lowercase_ : str = hf_hub_download( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE , force_download=__SCREAMING_SNAKE_CASE , proxies=__SCREAMING_SNAKE_CASE , resume_download=__SCREAMING_SNAKE_CASE , local_files_only=__SCREAMING_SNAKE_CASE , use_auth_token=__SCREAMING_SNAKE_CASE , ) lowercase_ : Optional[Any] = os.path.join('''local''' , '''--'''.join(pretrained_model_name_or_path.split('''/''' ) ) ) except EnvironmentError: logger.error(F'''Could not locate the {module_file} inside {pretrained_model_name_or_path}.''' ) raise # Check we have all the requirements in our environment lowercase_ : Tuple = check_imports(__SCREAMING_SNAKE_CASE ) # Now we move the module inside our cached dynamic modules. lowercase_ : str = DIFFUSERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule create_dynamic_module(__SCREAMING_SNAKE_CASE ) lowercase_ : Any = Path(__SCREAMING_SNAKE_CASE ) / full_submodule if submodule == "local" or submodule == "git": # We always copy local files (we could hash the file to see if there was a change, and give them the name of # that hash, to only copy when there is a modification but it seems overkill for now). # The only reason we do the copy is to avoid putting too many folders in sys.path. shutil.copy(__SCREAMING_SNAKE_CASE , submodule_path / module_file ) for module_needed in modules_needed: lowercase_ : Union[str, Any] = F'''{module_needed}.py''' shutil.copy(os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) , submodule_path / module_needed ) else: # Get the commit hash # TODO: we will get this info in the etag soon, so retrieve it from there and not here. if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase_ : Tuple = use_auth_token elif use_auth_token is True: lowercase_ : List[Any] = HfFolder.get_token() else: lowercase_ : Optional[Any] = None lowercase_ : Optional[int] = model_info(__SCREAMING_SNAKE_CASE , revision=__SCREAMING_SNAKE_CASE , token=__SCREAMING_SNAKE_CASE ).sha # The module file will end up being placed in a subfolder with the git hash of the repo. This way we get the # benefit of versioning. lowercase_ : int = submodule_path / commit_hash lowercase_ : Tuple = full_submodule + os.path.sep + commit_hash create_dynamic_module(__SCREAMING_SNAKE_CASE ) if not (submodule_path / module_file).exists(): shutil.copy(__SCREAMING_SNAKE_CASE , submodule_path / module_file ) # Make sure we also have every file with relative for module_needed in modules_needed: if not (submodule_path / module_needed).exists(): get_cached_module_file( __SCREAMING_SNAKE_CASE , F'''{module_needed}.py''' , cache_dir=__SCREAMING_SNAKE_CASE , force_download=__SCREAMING_SNAKE_CASE , resume_download=__SCREAMING_SNAKE_CASE , proxies=__SCREAMING_SNAKE_CASE , use_auth_token=__SCREAMING_SNAKE_CASE , revision=__SCREAMING_SNAKE_CASE , local_files_only=__SCREAMING_SNAKE_CASE , ) return os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Union[str, os.PathLike] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Optional[str] = None , __SCREAMING_SNAKE_CASE : Optional[Union[str, os.PathLike]] = None , __SCREAMING_SNAKE_CASE : bool = False , __SCREAMING_SNAKE_CASE : bool = False , __SCREAMING_SNAKE_CASE : Optional[Dict[str, str]] = None , __SCREAMING_SNAKE_CASE : Optional[Union[bool, str]] = None , __SCREAMING_SNAKE_CASE : Optional[str] = None , __SCREAMING_SNAKE_CASE : bool = False , **__SCREAMING_SNAKE_CASE : Optional[Any] , ): """simple docstring""" lowercase_ : Optional[Any] = get_cached_module_file( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE , force_download=__SCREAMING_SNAKE_CASE , resume_download=__SCREAMING_SNAKE_CASE , proxies=__SCREAMING_SNAKE_CASE , use_auth_token=__SCREAMING_SNAKE_CASE , revision=__SCREAMING_SNAKE_CASE , local_files_only=__SCREAMING_SNAKE_CASE , ) return get_class_in_module(__SCREAMING_SNAKE_CASE , final_module.replace('''.py''' , '''''' ) )
93
1
'''simple docstring''' from __future__ import annotations def snake_case_ ( __SCREAMING_SNAKE_CASE : list[int] , __SCREAMING_SNAKE_CASE : list[int] , __SCREAMING_SNAKE_CASE : list[int] , __SCREAMING_SNAKE_CASE : list[list[str]] , __SCREAMING_SNAKE_CASE : int , ): """simple docstring""" lowercase_ : Tuple = len(__SCREAMING_SNAKE_CASE ) # If row is equal to the size of the board it means there are a queen in each row in # the current board (possible_board) if row == n: # We convert the variable possible_board that looks like this: [1, 3, 0, 2] to # this: ['. Q . . ', '. . . Q ', 'Q . . . ', '. . Q . '] boards.append(['''. ''' * i + '''Q ''' + '''. ''' * (n - 1 - i) for i in possible_board] ) return # We iterate each column in the row to find all possible results in each row for col in range(__SCREAMING_SNAKE_CASE ): # We apply that we learned previously. First we check that in the current board # (possible_board) there are not other same value because if there is it means # that there are a collision in vertical. Then we apply the two formulas we # learned before: # # 45º: y - x = b or 45: row - col = b # 135º: y + x = b or row + col = b. # # And we verify if the results of this two formulas not exist in their variables # respectively. (diagonal_right_collisions, diagonal_left_collisions) # # If any or these are True it means there is a collision so we continue to the # next value in the for loop. if ( col in possible_board or row - col in diagonal_right_collisions or row + col in diagonal_left_collisions ): continue # If it is False we call dfs function again and we update the inputs depth_first_search( [*possible_board, col] , [*diagonal_right_collisions, row - col] , [*diagonal_left_collisions, row + col] , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : list[list[str]] = [] depth_first_search([] , [] , [] , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Print all the boards for board in boards: for column in board: print(__SCREAMING_SNAKE_CASE ) print('''''' ) print(len(__SCREAMING_SNAKE_CASE ) , '''solutions were found.''' ) if __name__ == "__main__": import doctest doctest.testmod() n_queens_solution(4)
93
'''simple docstring''' import re import tempfile from pathlib import Path import pytest import yaml from datasets.utils.readme import ReadMe # @pytest.fixture # def example_yaml_structure(): _lowercase : Union[str, Any] = yaml.safe_load( "\\nname: \"\"\nallow_empty: false\nallow_empty_text: true\nsubsections:\n - name: \"Dataset Card for X\" # First-level markdown heading\n allow_empty: false\n allow_empty_text: true\n subsections:\n - name: \"Table of Contents\"\n allow_empty: false\n allow_empty_text: false\n subsections: null\n - name: \"Dataset Description\"\n allow_empty: false\n allow_empty_text: false\n subsections:\n - name: \"Dataset Summary\"\n allow_empty: false\n allow_empty_text: false\n subsections: null\n - name: \"Supported Tasks and Leaderboards\"\n allow_empty: true\n allow_empty_text: true\n subsections: null\n - name: Languages\n allow_empty: false\n allow_empty_text: true\n subsections: null\n" ) _lowercase : int = { "name": "root", "text": "", "is_empty_text": True, "subsections": [ { "name": "Dataset Card for My Dataset", "text": "", "is_empty_text": True, "subsections": [ {"name": "Table of Contents", "text": "Some text here.", "is_empty_text": False, "subsections": []}, { "name": "Dataset Description", "text": "Some text here.", "is_empty_text": False, "subsections": [ { "name": "Dataset Summary", "text": "Some text here.", "is_empty_text": False, "subsections": [], }, { "name": "Supported Tasks and Leaderboards", "text": "", "is_empty_text": True, "subsections": [], }, {"name": "Languages", "text": "Language Text", "is_empty_text": False, "subsections": []}, ], }, ], } ], } _lowercase : Optional[Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Union[str, Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n#### Extra Ignored Subsection\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Any = { "name": "root", "text": "", "is_empty_text": True, "subsections": [ { "name": "Dataset Card for My Dataset", "text": "", "is_empty_text": True, "subsections": [ {"name": "Table of Contents", "text": "Some text here.", "is_empty_text": False, "subsections": []}, { "name": "Dataset Description", "text": "Some text here.", "is_empty_text": False, "subsections": [ { "name": "Dataset Summary", "text": "Some text here.", "is_empty_text": False, "subsections": [ { "name": "Extra Ignored Subsection", "text": "", "is_empty_text": True, "subsections": [], } ], }, { "name": "Supported Tasks and Leaderboards", "text": "", "is_empty_text": True, "subsections": [], }, {"name": "Languages", "text": "Language Text", "is_empty_text": False, "subsections": []}, ], }, ], } ], } _lowercase : str = "\\n---\n---\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : List[str] = ( "The following issues were found for the README at `{path}`:\n-\tEmpty YAML markers are present in the README." ) _lowercase : Tuple = "\\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Optional[Any] = ( "The following issues were found for the README at `{path}`:\n-\tNo YAML markers are present in the README." ) _lowercase : Tuple = "\\n---\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Optional[int] = "The following issues were found for the README at `{path}`:\n-\tOnly the start of YAML tags present in the README." _lowercase : List[Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Optional[Any] = "The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Summary` but it is empty.\n-\tExpected some text in section `Dataset Summary` but it is empty (text in subsections are ignored)." _lowercase : Optional[int] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n" _lowercase : Union[str, Any] = "The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Card for My Dataset` but it is empty.\n-\tSection `Dataset Card for My Dataset` expected the following subsections: `Table of Contents`, `Dataset Description`. Found 'None'." _lowercase : Union[str, Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Languages\nLanguage Text\n" _lowercase : int = "The following issues were found for the README at `{path}`:\n-\tSection `Dataset Description` is missing subsection: `Supported Tasks and Leaderboards`." _lowercase : List[Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\n" _lowercase : int = "The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Languages` but it is empty." _lowercase : List[str] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : str = "The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README." _lowercase : Dict = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n# Dataset Card My Dataset\n" _lowercase : List[str] = "The following issues were found for the README at `{path}`:\n-\tThe README has several first-level headings: `Dataset Card for My Dataset`, `Dataset Card My Dataset`. Only one heading is expected. Skipping further validation for this README." _lowercase : str = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Union[str, Any] = "The following issues were found for the README at `{path}`:\n-\tNo first-level heading starting with `Dataset Card for` found in README. Skipping further validation for this README." _lowercase : List[Any] = "" _lowercase : Optional[Any] = "The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README.\n-\tNo YAML markers are present in the README." _lowercase : List[Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Optional[Any] = "The following issues were found while parsing the README at `{path}`:\n-\tMultiple sections with the same heading `Dataset Card for My Dataset` have been found. Please keep only one of these sections." @pytest.mark.parametrize( '''readme_md, expected_dict''' , [ (README_CORRECT, CORRECT_DICT), (README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" assert ReadMe.from_string(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).to_dict() == expected_dict @pytest.mark.parametrize( '''readme_md, expected_error''' , [ (README_NO_YAML, EXPECTED_ERROR_README_NO_YAML), (README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML), (README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML), (README_EMPTY, EXPECTED_ERROR_README_EMPTY), (README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION), (README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL), (README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION), (README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT), (README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL), (README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL), (README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" with pytest.raises(__SCREAMING_SNAKE_CASE , match=re.escape(expected_error.format(path='''root''' ) ) ): lowercase_ : Optional[int] = ReadMe.from_string(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) readme.validate() @pytest.mark.parametrize( '''readme_md, expected_error''' , [ (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" with pytest.raises(__SCREAMING_SNAKE_CASE , match=re.escape(expected_error.format(path='''root''' ) ) ): ReadMe.from_string(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( '''readme_md,''' , [ (README_MULTIPLE_SAME_HEADING_1), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Any ): """simple docstring""" ReadMe.from_string(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , suppress_parsing_errors=__SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( '''readme_md, expected_dict''' , [ (README_CORRECT, CORRECT_DICT), (README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : str ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: lowercase_ : Optional[int] = Path(__SCREAMING_SNAKE_CASE ) / '''README.md''' with open(__SCREAMING_SNAKE_CASE , '''w+''' ) as readme_file: readme_file.write(__SCREAMING_SNAKE_CASE ) lowercase_ : Any = ReadMe.from_readme(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).to_dict() assert out["name"] == path assert out["text"] == "" assert out["is_empty_text"] assert out["subsections"] == expected_dict["subsections"] @pytest.mark.parametrize( '''readme_md, expected_error''' , [ (README_NO_YAML, EXPECTED_ERROR_README_NO_YAML), (README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML), (README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML), (README_EMPTY, EXPECTED_ERROR_README_EMPTY), (README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION), (README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL), (README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION), (README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT), (README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL), (README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL), (README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: lowercase_ : str = Path(__SCREAMING_SNAKE_CASE ) / '''README.md''' with open(__SCREAMING_SNAKE_CASE , '''w+''' ) as readme_file: readme_file.write(__SCREAMING_SNAKE_CASE ) lowercase_ : List[str] = expected_error.format(path=__SCREAMING_SNAKE_CASE ) with pytest.raises(__SCREAMING_SNAKE_CASE , match=re.escape(__SCREAMING_SNAKE_CASE ) ): lowercase_ : int = ReadMe.from_readme(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) readme.validate() @pytest.mark.parametrize( '''readme_md, expected_error''' , [ (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: lowercase_ : Dict = Path(__SCREAMING_SNAKE_CASE ) / '''README.md''' with open(__SCREAMING_SNAKE_CASE , '''w+''' ) as readme_file: readme_file.write(__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = expected_error.format(path=__SCREAMING_SNAKE_CASE ) with pytest.raises(__SCREAMING_SNAKE_CASE , match=re.escape(__SCREAMING_SNAKE_CASE ) ): ReadMe.from_readme(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( '''readme_md,''' , [ (README_MULTIPLE_SAME_HEADING_1), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: lowercase_ : Optional[int] = Path(__SCREAMING_SNAKE_CASE ) / '''README.md''' with open(__SCREAMING_SNAKE_CASE , '''w+''' ) as readme_file: readme_file.write(__SCREAMING_SNAKE_CASE ) ReadMe.from_readme(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , suppress_parsing_errors=__SCREAMING_SNAKE_CASE )
93
1
'''simple docstring''' import numpy as np class lowerCAmelCase__ : def __init__( self ): """simple docstring""" lowercase_ : Optional[int] = (0, 0) lowercase_ : Dict = None lowercase_ : Optional[int] = 0 lowercase_ : List[Any] = 0 lowercase_ : Dict = 0 def __eq__( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" return self.position == cell.position def _snake_case ( self ): """simple docstring""" print(self.position ) class lowerCAmelCase__ : def __init__( self , __SCREAMING_SNAKE_CASE=(5, 5) ): """simple docstring""" lowercase_ : Union[str, Any] = np.zeros(__SCREAMING_SNAKE_CASE ) lowercase_ : List[str] = world_size[0] lowercase_ : Dict = world_size[1] def _snake_case ( self ): """simple docstring""" print(self.w ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : List[str] = [ (-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1), ] lowercase_ : str = cell.position[0] lowercase_ : int = cell.position[1] lowercase_ : Optional[int] = [] for n in neughbour_cord: lowercase_ : Optional[Any] = current_x + n[0] lowercase_ : List[str] = current_y + n[1] if 0 <= x < self.world_x_limit and 0 <= y < self.world_y_limit: lowercase_ : str = Cell() lowercase_ : List[str] = (x, y) lowercase_ : Any = cell neighbours.append(__SCREAMING_SNAKE_CASE ) return neighbours def snake_case_ ( __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : List[Any] ): """simple docstring""" lowercase_ : Any = [] lowercase_ : int = [] _open.append(__SCREAMING_SNAKE_CASE ) while _open: lowercase_ : str = np.argmin([n.f for n in _open] ) lowercase_ : Any = _open[min_f] _closed.append(_open.pop(__SCREAMING_SNAKE_CASE ) ) if current == goal: break for n in world.get_neigbours(__SCREAMING_SNAKE_CASE ): for c in _closed: if c == n: continue lowercase_ : Optional[int] = current.g + 1 lowercase_ , lowercase_ : str = n.position lowercase_ , lowercase_ : int = goal.position lowercase_ : Union[str, Any] = (ya - ya) ** 2 + (xa - xa) ** 2 lowercase_ : Optional[Any] = n.h + n.g for c in _open: if c == n and c.f < n.f: continue _open.append(__SCREAMING_SNAKE_CASE ) lowercase_ : Dict = [] while current.parent is not None: path.append(current.position ) lowercase_ : Dict = current.parent path.append(current.position ) return path[::-1] if __name__ == "__main__": _lowercase : Optional[int] = Gridworld() # Start position and goal _lowercase : List[str] = Cell() _lowercase : Optional[Any] = (0, 0) _lowercase : Union[str, Any] = Cell() _lowercase : Optional[Any] = (4, 4) print(f"""path from {start.position} to {goal.position}""") _lowercase : Any = astar(world, start, goal) # Just for visual reasons. for i in s: _lowercase : List[Any] = 1 print(world.w)
93
'''simple docstring''' import math import time from typing import Dict, List, Optional from torch.utils.data import Dataset from transformers import SeqaSeqTrainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput, speed_metrics if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class lowerCAmelCase__ ( lowerCamelCase_ ): def __init__( self , *__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , **__SCREAMING_SNAKE_CASE ): """simple docstring""" super().__init__(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = eval_examples lowercase_ : Tuple = post_process_function def _snake_case ( self , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = "eval" , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : Optional[int] = gen_kwargs.copy() lowercase_ : List[str] = ( gen_kwargs['''max_length'''] if gen_kwargs.get('''max_length''' ) is not None else self.args.generation_max_length ) lowercase_ : str = ( gen_kwargs['''num_beams'''] if gen_kwargs.get('''num_beams''' ) is not None else self.args.generation_num_beams ) lowercase_ : Dict = gen_kwargs lowercase_ : List[Any] = self.eval_dataset if eval_dataset is None else eval_dataset lowercase_ : List[str] = self.get_eval_dataloader(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. lowercase_ : Union[str, Any] = self.compute_metrics lowercase_ : Optional[int] = None lowercase_ : Tuple = time.time() lowercase_ : Tuple = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: lowercase_ : str = eval_loop( __SCREAMING_SNAKE_CASE , description='''Evaluation''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=__SCREAMING_SNAKE_CASE , metric_key_prefix=__SCREAMING_SNAKE_CASE , ) finally: lowercase_ : Any = compute_metrics lowercase_ : Any = self.args.eval_batch_size * self.args.world_size if F'''{metric_key_prefix}_jit_compilation_time''' in output.metrics: start_time += output.metrics[F'''{metric_key_prefix}_jit_compilation_time'''] output.metrics.update( speed_metrics( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save: # Only the main node write the results by default lowercase_ : Optional[Any] = self.post_process_function(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = self.compute_metrics(__SCREAMING_SNAKE_CASE ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F'''{metric_key_prefix}_''' ): lowercase_ : List[Any] = metrics.pop(__SCREAMING_SNAKE_CASE ) metrics.update(output.metrics ) else: lowercase_ : List[Any] = output.metrics if self.args.should_log: # Only the main node log the results by default self.log(__SCREAMING_SNAKE_CASE ) if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report() ) lowercase_ : List[Any] = self.callback_handler.on_evaluate(self.args , self.state , self.control , __SCREAMING_SNAKE_CASE ) return metrics def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE = "test" , **__SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Union[str, Any] = gen_kwargs.copy() lowercase_ : Tuple = self.get_test_dataloader(__SCREAMING_SNAKE_CASE ) # Temporarily disable metric computation, we will do it in the loop here. lowercase_ : Optional[Any] = self.compute_metrics lowercase_ : Optional[int] = None lowercase_ : List[Any] = time.time() lowercase_ : int = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: lowercase_ : Tuple = eval_loop( __SCREAMING_SNAKE_CASE , description='''Prediction''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=__SCREAMING_SNAKE_CASE , metric_key_prefix=__SCREAMING_SNAKE_CASE , ) finally: lowercase_ : Any = compute_metrics lowercase_ : Tuple = self.args.eval_batch_size * self.args.world_size if F'''{metric_key_prefix}_jit_compilation_time''' in output.metrics: start_time += output.metrics[F'''{metric_key_prefix}_jit_compilation_time'''] output.metrics.update( speed_metrics( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is None or self.compute_metrics is None: return output lowercase_ : Any = self.post_process_function(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , '''predict''' ) lowercase_ : str = self.compute_metrics(__SCREAMING_SNAKE_CASE ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F'''{metric_key_prefix}_''' ): lowercase_ : Optional[int] = metrics.pop(__SCREAMING_SNAKE_CASE ) metrics.update(output.metrics ) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=__SCREAMING_SNAKE_CASE )
93
1
'''simple docstring''' import os import shutil import tempfile import unittest import numpy as np from transformers import AutoTokenizer, BarkProcessor from transformers.testing_utils import require_torch, slow @require_torch class lowerCAmelCase__ ( unittest.TestCase ): def _snake_case ( self ): """simple docstring""" lowercase_ : Optional[int] = '''ylacombe/bark-small''' lowercase_ : Any = tempfile.mkdtemp() lowercase_ : Tuple = '''en_speaker_1''' lowercase_ : Dict = '''This is a test string''' lowercase_ : List[str] = '''speaker_embeddings_path.json''' lowercase_ : Optional[Any] = '''speaker_embeddings''' def _snake_case ( self , **__SCREAMING_SNAKE_CASE ): """simple docstring""" return AutoTokenizer.from_pretrained(self.checkpoint , **__SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" shutil.rmtree(self.tmpdirname ) def _snake_case ( self ): """simple docstring""" lowercase_ : Any = self.get_tokenizer() lowercase_ : str = BarkProcessor(tokenizer=__SCREAMING_SNAKE_CASE ) processor.save_pretrained(self.tmpdirname ) lowercase_ : List[str] = BarkProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) @slow def _snake_case ( self ): """simple docstring""" lowercase_ : Dict = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) processor.save_pretrained( self.tmpdirname , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , speaker_embeddings_directory=self.speaker_embeddings_directory , ) lowercase_ : Union[str, Any] = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) lowercase_ : Union[str, Any] = BarkProcessor.from_pretrained( self.tmpdirname , self.speaker_embeddings_dict_path , bos_token='''(BOS)''' , eos_token='''(EOS)''' , ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) def _snake_case ( self ): """simple docstring""" lowercase_ : Any = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) lowercase_ : List[Any] = 35 lowercase_ : Union[str, Any] = 2 lowercase_ : List[Any] = 8 lowercase_ : int = { '''semantic_prompt''': np.ones(__SCREAMING_SNAKE_CASE ), '''coarse_prompt''': np.ones((nb_codebooks_coarse, seq_len) ), '''fine_prompt''': np.ones((nb_codebooks_total, seq_len) ), } # test providing already loaded voice_preset lowercase_ : Tuple = processor(text=self.input_string , voice_preset=__SCREAMING_SNAKE_CASE ) lowercase_ : List[Any] = inputs['''history_prompt'''] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(__SCREAMING_SNAKE_CASE , np.array([] ) ).tolist() ) # test loading voice preset from npz file lowercase_ : Dict = os.path.join(self.tmpdirname , '''file.npz''' ) np.savez(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = processor(text=self.input_string , voice_preset=__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = inputs['''history_prompt'''] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(__SCREAMING_SNAKE_CASE , np.array([] ) ).tolist() ) # test loading voice preset from the hub lowercase_ : List[str] = processor(text=self.input_string , voice_preset=self.voice_preset ) def _snake_case ( self ): """simple docstring""" lowercase_ : Tuple = self.get_tokenizer() lowercase_ : int = BarkProcessor(tokenizer=__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = processor(text=self.input_string ) lowercase_ : List[Any] = tokenizer( self.input_string , padding='''max_length''' , max_length=2_56 , add_special_tokens=__SCREAMING_SNAKE_CASE , return_attention_mask=__SCREAMING_SNAKE_CASE , return_token_type_ids=__SCREAMING_SNAKE_CASE , ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key].squeeze().tolist() )
93
'''simple docstring''' from pathlib import Path from typing import List from transformers import is_torch_available, is_vision_available from transformers.testing_utils import get_tests_dir, is_tool_test from transformers.tools.agent_types import AGENT_TYPE_MAPPING, AgentAudio, AgentImage, AgentText if is_torch_available(): import torch if is_vision_available(): from PIL import Image _lowercase : List[str] = ["text", "image", "audio"] def snake_case_ ( __SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" lowercase_ : int = [] for input_type in input_types: if input_type == "text": inputs.append('''Text input''' ) elif input_type == "image": inputs.append( Image.open(Path(get_tests_dir('''fixtures/tests_samples/COCO''' ) ) / '''000000039769.png''' ).resize((512, 512) ) ) elif input_type == "audio": inputs.append(torch.ones(3000 ) ) elif isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): inputs.append(create_inputs(__SCREAMING_SNAKE_CASE ) ) else: raise ValueError(F'''Invalid type requested: {input_type}''' ) return inputs def snake_case_ ( __SCREAMING_SNAKE_CASE : List ): """simple docstring""" lowercase_ : Optional[Any] = [] for output in outputs: if isinstance(__SCREAMING_SNAKE_CASE , (str, AgentText) ): output_types.append('''text''' ) elif isinstance(__SCREAMING_SNAKE_CASE , (Image.Image, AgentImage) ): output_types.append('''image''' ) elif isinstance(__SCREAMING_SNAKE_CASE , (torch.Tensor, AgentAudio) ): output_types.append('''audio''' ) else: raise ValueError(F'''Invalid output: {output}''' ) return output_types @is_tool_test class lowerCAmelCase__ : def _snake_case ( self ): """simple docstring""" self.assertTrue(hasattr(self.tool , '''inputs''' ) ) self.assertTrue(hasattr(self.tool , '''outputs''' ) ) lowercase_ : Optional[Any] = self.tool.inputs for _input in inputs: if isinstance(_input , __SCREAMING_SNAKE_CASE ): for __input in _input: self.assertTrue(__input in authorized_types ) else: self.assertTrue(_input in authorized_types ) lowercase_ : int = self.tool.outputs for _output in outputs: self.assertTrue(_output in authorized_types ) def _snake_case ( self ): """simple docstring""" lowercase_ : int = create_inputs(self.tool.inputs ) lowercase_ : Tuple = self.tool(*__SCREAMING_SNAKE_CASE ) # There is a single output if len(self.tool.outputs ) == 1: lowercase_ : Any = [outputs] self.assertListEqual(output_types(__SCREAMING_SNAKE_CASE ) , self.tool.outputs ) def _snake_case ( self ): """simple docstring""" self.assertTrue(hasattr(self.tool , '''description''' ) ) self.assertTrue(hasattr(self.tool , '''default_checkpoint''' ) ) self.assertTrue(self.tool.description.startswith('''This is a tool that''' ) ) def _snake_case ( self ): """simple docstring""" lowercase_ : int = create_inputs(self.tool.inputs ) lowercase_ : int = self.tool(*__SCREAMING_SNAKE_CASE ) if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase_ : Optional[Any] = [outputs] self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , len(self.tool.outputs ) ) for output, output_type in zip(__SCREAMING_SNAKE_CASE , self.tool.outputs ): lowercase_ : Optional[int] = AGENT_TYPE_MAPPING[output_type] self.assertTrue(isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) def _snake_case ( self ): """simple docstring""" lowercase_ : Dict = create_inputs(self.tool.inputs ) lowercase_ : int = [] for _input, input_type in zip(__SCREAMING_SNAKE_CASE , self.tool.inputs ): if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): _inputs.append([AGENT_TYPE_MAPPING[_input_type](_input ) for _input_type in input_type] ) else: _inputs.append(AGENT_TYPE_MAPPING[input_type](_input ) ) # Should not raise an error lowercase_ : Optional[Any] = self.tool(*__SCREAMING_SNAKE_CASE ) if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase_ : Dict = [outputs] self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , len(self.tool.outputs ) )
93
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowercase : str = { "configuration_xlm_roberta_xl": [ "XLM_ROBERTA_XL_PRETRAINED_CONFIG_ARCHIVE_MAP", "XLMRobertaXLConfig", "XLMRobertaXLOnnxConfig", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : List[str] = [ "XLM_ROBERTA_XL_PRETRAINED_MODEL_ARCHIVE_LIST", "XLMRobertaXLForCausalLM", "XLMRobertaXLForMaskedLM", "XLMRobertaXLForMultipleChoice", "XLMRobertaXLForQuestionAnswering", "XLMRobertaXLForSequenceClassification", "XLMRobertaXLForTokenClassification", "XLMRobertaXLModel", "XLMRobertaXLPreTrainedModel", ] if TYPE_CHECKING: from .configuration_xlm_roberta_xl import ( XLM_ROBERTA_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMRobertaXLConfig, XLMRobertaXLOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm_roberta_xl import ( XLM_ROBERTA_XL_PRETRAINED_MODEL_ARCHIVE_LIST, XLMRobertaXLForCausalLM, XLMRobertaXLForMaskedLM, XLMRobertaXLForMultipleChoice, XLMRobertaXLForQuestionAnswering, XLMRobertaXLForSequenceClassification, XLMRobertaXLForTokenClassification, XLMRobertaXLModel, XLMRobertaXLPreTrainedModel, ) else: import sys _lowercase : Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure)
93
'''simple docstring''' # DISCLAIMER: This file is strongly influenced by https://github.com/ermongroup/ddim from dataclasses import dataclass from typing import Optional, Tuple, Union import flax import jax import jax.numpy as jnp from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils_flax import ( CommonSchedulerState, FlaxKarrasDiffusionSchedulers, FlaxSchedulerMixin, FlaxSchedulerOutput, add_noise_common, get_velocity_common, ) @flax.struct.dataclass class lowerCAmelCase__ : lowerCAmelCase_ = 42 # setable values lowerCAmelCase_ = 42 lowerCAmelCase_ = 42 lowerCAmelCase_ = None @classmethod def _snake_case ( cls , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" return cls(common=__SCREAMING_SNAKE_CASE , init_noise_sigma=__SCREAMING_SNAKE_CASE , timesteps=__SCREAMING_SNAKE_CASE ) @dataclass class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = 42 class lowerCAmelCase__ ( lowerCamelCase_ , lowerCamelCase_ ): lowerCAmelCase_ = [e.name for e in FlaxKarrasDiffusionSchedulers] lowerCAmelCase_ = 42 @property def _snake_case ( self ): """simple docstring""" return True @register_to_config def __init__( self , __SCREAMING_SNAKE_CASE = 10_00 , __SCREAMING_SNAKE_CASE = 0.0_001 , __SCREAMING_SNAKE_CASE = 0.02 , __SCREAMING_SNAKE_CASE = "linear" , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = "fixed_small" , __SCREAMING_SNAKE_CASE = True , __SCREAMING_SNAKE_CASE = "epsilon" , __SCREAMING_SNAKE_CASE = jnp.floataa , ): """simple docstring""" lowercase_ : Dict = dtype def _snake_case ( self , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" if common is None: lowercase_ : Tuple = CommonSchedulerState.create(self ) # standard deviation of the initial noise distribution lowercase_ : Union[str, Any] = jnp.array(1.0 , dtype=self.dtype ) lowercase_ : List[Any] = jnp.arange(0 , self.config.num_train_timesteps ).round()[::-1] return DDPMSchedulerState.create( common=__SCREAMING_SNAKE_CASE , init_noise_sigma=__SCREAMING_SNAKE_CASE , timesteps=__SCREAMING_SNAKE_CASE , ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" return sample def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = () ): """simple docstring""" lowercase_ : Optional[Any] = self.config.num_train_timesteps // num_inference_steps # creates integer timesteps by multiplying by ratio # rounding to avoid issues when num_inference_step is power of 3 lowercase_ : int = (jnp.arange(0 , __SCREAMING_SNAKE_CASE ) * step_ratio).round()[::-1] return state.replace( num_inference_steps=__SCREAMING_SNAKE_CASE , timesteps=__SCREAMING_SNAKE_CASE , ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None ): """simple docstring""" lowercase_ : List[Any] = state.common.alphas_cumprod[t] lowercase_ : str = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) ) # For t > 0, compute predicted variance βt (see formula (6) and (7) from https://arxiv.org/pdf/2006.11239.pdf) # and sample from it to get previous sample # x_{t-1} ~ N(pred_prev_sample, variance) == add variance to pred_sample lowercase_ : int = (1 - alpha_prod_t_prev) / (1 - alpha_prod_t) * state.common.betas[t] if variance_type is None: lowercase_ : str = self.config.variance_type # hacks - were probably added for training stability if variance_type == "fixed_small": lowercase_ : int = jnp.clip(__SCREAMING_SNAKE_CASE , a_min=1E-2_0 ) # for rl-diffuser https://arxiv.org/abs/2205.09991 elif variance_type == "fixed_small_log": lowercase_ : List[str] = jnp.log(jnp.clip(__SCREAMING_SNAKE_CASE , a_min=1E-2_0 ) ) elif variance_type == "fixed_large": lowercase_ : List[Any] = state.common.betas[t] elif variance_type == "fixed_large_log": # Glide max_log lowercase_ : List[Any] = jnp.log(state.common.betas[t] ) elif variance_type == "learned": return predicted_variance elif variance_type == "learned_range": lowercase_ : Optional[Any] = variance lowercase_ : Union[str, Any] = state.common.betas[t] lowercase_ : Union[str, Any] = (predicted_variance + 1) / 2 lowercase_ : Any = frac * max_log + (1 - frac) * min_log return variance def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = True , ): """simple docstring""" lowercase_ : Optional[int] = timestep if key is None: lowercase_ : int = jax.random.PRNGKey(0 ) if model_output.shape[1] == sample.shape[1] * 2 and self.config.variance_type in ["learned", "learned_range"]: lowercase_ , lowercase_ : Optional[Any] = jnp.split(__SCREAMING_SNAKE_CASE , sample.shape[1] , axis=1 ) else: lowercase_ : int = None # 1. compute alphas, betas lowercase_ : Any = state.common.alphas_cumprod[t] lowercase_ : Optional[int] = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) ) lowercase_ : int = 1 - alpha_prod_t lowercase_ : str = 1 - alpha_prod_t_prev # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if self.config.prediction_type == "epsilon": lowercase_ : Tuple = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif self.config.prediction_type == "sample": lowercase_ : Any = model_output elif self.config.prediction_type == "v_prediction": lowercase_ : List[Any] = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output else: raise ValueError( F'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample` ''' ''' for the FlaxDDPMScheduler.''' ) # 3. Clip "predicted x_0" if self.config.clip_sample: lowercase_ : Optional[Any] = jnp.clip(__SCREAMING_SNAKE_CASE , -1 , 1 ) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf lowercase_ : List[Any] = (alpha_prod_t_prev ** 0.5 * state.common.betas[t]) / beta_prod_t lowercase_ : Optional[Any] = state.common.alphas[t] ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf lowercase_ : Optional[Any] = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise def random_variance(): lowercase_ : str = jax.random.split(__SCREAMING_SNAKE_CASE , num=1 ) lowercase_ : List[Any] = jax.random.normal(__SCREAMING_SNAKE_CASE , shape=model_output.shape , dtype=self.dtype ) return (self._get_variance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , predicted_variance=__SCREAMING_SNAKE_CASE ) ** 0.5) * noise lowercase_ : Optional[Any] = jnp.where(t > 0 , random_variance() , jnp.zeros(model_output.shape , dtype=self.dtype ) ) lowercase_ : Any = pred_prev_sample + variance if not return_dict: return (pred_prev_sample, state) return FlaxDDPMSchedulerOutput(prev_sample=__SCREAMING_SNAKE_CASE , state=__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , ): """simple docstring""" return add_noise_common(state.common , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , ): """simple docstring""" return get_velocity_common(state.common , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def __len__( self ): """simple docstring""" return self.config.num_train_timesteps
93
1
'''simple docstring''' import os import unittest from tempfile import TemporaryDirectory import torch import torch.nn as nn from accelerate.utils import ( OffloadedWeightsLoader, extract_submodules_state_dict, load_offloaded_weight, offload_state_dict, offload_weight, ) class lowerCAmelCase__ ( nn.Module ): def __init__( self ): """simple docstring""" super().__init__() lowercase_ : Optional[int] = nn.Linear(3 , 4 ) lowercase_ : Optional[Any] = nn.BatchNormad(4 ) lowercase_ : Dict = nn.Linear(4 , 5 ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" return self.lineara(self.batchnorm(self.lineara(__SCREAMING_SNAKE_CASE ) ) ) class lowerCAmelCase__ ( unittest.TestCase ): def _snake_case ( self ): """simple docstring""" lowercase_ : List[Any] = ModelForTest() with TemporaryDirectory() as tmp_dir: offload_state_dict(__SCREAMING_SNAKE_CASE , model.state_dict() ) lowercase_ : List[str] = os.path.join(__SCREAMING_SNAKE_CASE , '''index.json''' ) self.assertTrue(os.path.isfile(__SCREAMING_SNAKE_CASE ) ) # TODO: add tests on what is inside the index for key in ["linear1.weight", "linear1.bias", "linear2.weight", "linear2.bias"]: lowercase_ : Any = os.path.join(__SCREAMING_SNAKE_CASE , F'''{key}.dat''' ) self.assertTrue(os.path.isfile(__SCREAMING_SNAKE_CASE ) ) # TODO: add tests on the fact weights are properly loaded def _snake_case ( self ): """simple docstring""" lowercase_ : Tuple = [torch.floataa, torch.floataa, torch.bfloataa] for dtype in dtypes: lowercase_ : Optional[int] = torch.randn(2 , 3 , dtype=__SCREAMING_SNAKE_CASE ) with TemporaryDirectory() as tmp_dir: lowercase_ : Optional[Any] = offload_weight(__SCREAMING_SNAKE_CASE , '''weight''' , __SCREAMING_SNAKE_CASE , {} ) lowercase_ : str = os.path.join(__SCREAMING_SNAKE_CASE , '''weight.dat''' ) self.assertTrue(os.path.isfile(__SCREAMING_SNAKE_CASE ) ) self.assertDictEqual(__SCREAMING_SNAKE_CASE , {'''weight''': {'''shape''': [2, 3], '''dtype''': str(__SCREAMING_SNAKE_CASE ).split('''.''' )[1]}} ) lowercase_ : int = load_offloaded_weight(__SCREAMING_SNAKE_CASE , index['''weight'''] ) self.assertTrue(torch.equal(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) def _snake_case ( self ): """simple docstring""" lowercase_ : str = ModelForTest() lowercase_ : Any = model.state_dict() lowercase_ : Dict = {k: v for k, v in state_dict.items() if '''linear2''' not in k} lowercase_ : int = {k: v for k, v in state_dict.items() if '''linear2''' in k} with TemporaryDirectory() as tmp_dir: offload_state_dict(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : Dict = OffloadedWeightsLoader(state_dict=__SCREAMING_SNAKE_CASE , save_folder=__SCREAMING_SNAKE_CASE ) # Every key is there with the right value self.assertEqual(sorted(__SCREAMING_SNAKE_CASE ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(__SCREAMING_SNAKE_CASE , weight_map[key] ) ) lowercase_ : Dict = {k: v for k, v in state_dict.items() if '''weight''' in k} lowercase_ : str = {k: v for k, v in state_dict.items() if '''weight''' not in k} with TemporaryDirectory() as tmp_dir: offload_state_dict(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : Any = OffloadedWeightsLoader(state_dict=__SCREAMING_SNAKE_CASE , save_folder=__SCREAMING_SNAKE_CASE ) # Every key is there with the right value self.assertEqual(sorted(__SCREAMING_SNAKE_CASE ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(__SCREAMING_SNAKE_CASE , weight_map[key] ) ) with TemporaryDirectory() as tmp_dir: offload_state_dict(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Duplicates are removed lowercase_ : Dict = OffloadedWeightsLoader(state_dict=__SCREAMING_SNAKE_CASE , save_folder=__SCREAMING_SNAKE_CASE ) # Every key is there with the right value self.assertEqual(sorted(__SCREAMING_SNAKE_CASE ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(__SCREAMING_SNAKE_CASE , weight_map[key] ) ) def _snake_case ( self ): """simple docstring""" lowercase_ : Optional[Any] = {'''a.1''': 0, '''a.10''': 1, '''a.2''': 2} lowercase_ : Dict = extract_submodules_state_dict(__SCREAMING_SNAKE_CASE , ['''a.1''', '''a.2'''] ) self.assertDictEqual(__SCREAMING_SNAKE_CASE , {'''a.1''': 0, '''a.2''': 2} ) lowercase_ : Any = {'''a.1.a''': 0, '''a.10.a''': 1, '''a.2.a''': 2} lowercase_ : Optional[int] = extract_submodules_state_dict(__SCREAMING_SNAKE_CASE , ['''a.1''', '''a.2'''] ) self.assertDictEqual(__SCREAMING_SNAKE_CASE , {'''a.1.a''': 0, '''a.2.a''': 2} )
93
'''simple docstring''' _lowercase : int = [sum(int(c, 1_0) ** 2 for c in i.__str__()) for i in range(1_0_0_0_0_0)] def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : Optional[int] = 0 while number: # Increased Speed Slightly by checking every 5 digits together. sum_of_digits_squared += DIGITS_SQUARED[number % 100000] number //= 100000 return sum_of_digits_squared # There are 2 Chains made, # One ends with 89 with the chain member 58 being the one which when declared first, # there will be the least number of iterations for all the members to be checked. # The other one ends with 1 and has only one element 1. # So 58 and 1 are chosen to be declared at the starting. # Changed dictionary to an array to quicken the solution _lowercase : list[bool | None] = [None] * 1_0_0_0_0_0_0_0 _lowercase : List[str] = True _lowercase : Optional[int] = False def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" if CHAINS[number - 1] is not None: return CHAINS[number - 1] # type: ignore lowercase_ : Tuple = chain(next_number(__SCREAMING_SNAKE_CASE ) ) lowercase_ : Union[str, Any] = number_chain while number < 10000000: lowercase_ : int = number_chain number *= 10 return number_chain def snake_case_ ( __SCREAMING_SNAKE_CASE : int = 10000000 ): """simple docstring""" for i in range(1 , __SCREAMING_SNAKE_CASE ): if CHAINS[i] is None: chain(i + 1 ) return CHAINS[:number].count(__SCREAMING_SNAKE_CASE ) if __name__ == "__main__": import doctest doctest.testmod() print(f"""{solution() = }""")
93
1
'''simple docstring''' import random def snake_case_ ( __SCREAMING_SNAKE_CASE : list , __SCREAMING_SNAKE_CASE : str ): """simple docstring""" lowercase_ , lowercase_ , lowercase_ : Optional[int] = [], [], [] for element in data: if element < pivot: less.append(__SCREAMING_SNAKE_CASE ) elif element > pivot: greater.append(__SCREAMING_SNAKE_CASE ) else: equal.append(__SCREAMING_SNAKE_CASE ) return less, equal, greater def snake_case_ ( __SCREAMING_SNAKE_CASE : list , __SCREAMING_SNAKE_CASE : int ): """simple docstring""" if index >= len(__SCREAMING_SNAKE_CASE ) or index < 0: return None lowercase_ : Dict = items[random.randint(0 , len(__SCREAMING_SNAKE_CASE ) - 1 )] lowercase_ : Optional[int] = 0 lowercase_ , lowercase_ , lowercase_ : Optional[int] = _partition(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : str = len(__SCREAMING_SNAKE_CASE ) lowercase_ : List[str] = len(__SCREAMING_SNAKE_CASE ) # index is the pivot if m <= index < m + count: return pivot # must be in smaller elif m > index: return quick_select(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # must be in larger else: return quick_select(__SCREAMING_SNAKE_CASE , index - (m + count) )
93
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _lowercase : Union[str, Any] = { "configuration_pix2struct": [ "PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP", "Pix2StructConfig", "Pix2StructTextConfig", "Pix2StructVisionConfig", ], "processing_pix2struct": ["Pix2StructProcessor"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : Dict = ["Pix2StructImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : List[str] = [ "PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST", "Pix2StructPreTrainedModel", "Pix2StructForConditionalGeneration", "Pix2StructVisionModel", "Pix2StructTextModel", ] if TYPE_CHECKING: from .configuration_pixastruct import ( PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP, PixaStructConfig, PixaStructTextConfig, PixaStructVisionConfig, ) from .processing_pixastruct import PixaStructProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_pixastruct import PixaStructImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_pixastruct import ( PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST, PixaStructForConditionalGeneration, PixaStructPreTrainedModel, PixaStructTextModel, PixaStructVisionModel, ) else: import sys _lowercase : Optional[int] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
93
1
'''simple docstring''' import logging from transformers import PretrainedConfig _lowercase : List[str] = logging.getLogger(__name__) _lowercase : Tuple = { "bertabs-finetuned-cnndm": "https://huggingface.co/remi/bertabs-finetuned-cnndm-extractive-abstractive-summarization/resolve/main/config.json", } class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = '''bertabs''' def __init__( self , __SCREAMING_SNAKE_CASE=3_05_22 , __SCREAMING_SNAKE_CASE=5_12 , __SCREAMING_SNAKE_CASE=6 , __SCREAMING_SNAKE_CASE=5_12 , __SCREAMING_SNAKE_CASE=8 , __SCREAMING_SNAKE_CASE=5_12 , __SCREAMING_SNAKE_CASE=0.2 , __SCREAMING_SNAKE_CASE=6 , __SCREAMING_SNAKE_CASE=7_68 , __SCREAMING_SNAKE_CASE=8 , __SCREAMING_SNAKE_CASE=20_48 , __SCREAMING_SNAKE_CASE=0.2 , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) lowercase_ : List[Any] = vocab_size lowercase_ : List[Any] = max_pos lowercase_ : Union[str, Any] = enc_layers lowercase_ : Optional[Any] = enc_hidden_size lowercase_ : str = enc_heads lowercase_ : str = enc_ff_size lowercase_ : List[str] = enc_dropout lowercase_ : List[str] = dec_layers lowercase_ : List[str] = dec_hidden_size lowercase_ : List[str] = dec_heads lowercase_ : Optional[int] = dec_ff_size lowercase_ : Optional[Any] = dec_dropout
93
'''simple docstring''' def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : Optional[int] = int(__SCREAMING_SNAKE_CASE ) if decimal in (0, 1): # Exit cases for the recursion return str(__SCREAMING_SNAKE_CASE ) lowercase_ , lowercase_ : List[str] = divmod(__SCREAMING_SNAKE_CASE , 2 ) return binary_recursive(__SCREAMING_SNAKE_CASE ) + str(__SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : str ): """simple docstring""" lowercase_ : str = str(__SCREAMING_SNAKE_CASE ).strip() if not number: raise ValueError('''No input value was provided''' ) lowercase_ : Optional[int] = '''-''' if number.startswith('''-''' ) else '''''' lowercase_ : Union[str, Any] = number.lstrip('''-''' ) if not number.isnumeric(): raise ValueError('''Input value is not an integer''' ) return F'''{negative}0b{binary_recursive(int(__SCREAMING_SNAKE_CASE ) )}''' if __name__ == "__main__": from doctest import testmod testmod()
93
1
'''simple docstring''' import tempfile import torch from diffusers import IPNDMScheduler from .test_schedulers import SchedulerCommonTest class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = (IPNDMScheduler,) lowerCAmelCase_ = (('''num_inference_steps''', 5_0),) def _snake_case ( self , **__SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Optional[Any] = {'''num_train_timesteps''': 10_00} config.update(**__SCREAMING_SNAKE_CASE ) return config def _snake_case ( self , __SCREAMING_SNAKE_CASE=0 , **__SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : str = dict(self.forward_default_kwargs ) lowercase_ : List[Any] = kwargs.pop('''num_inference_steps''' , __SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = self.dummy_sample lowercase_ : Optional[Any] = 0.1 * sample lowercase_ : List[Any] = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: lowercase_ : Any = self.get_scheduler_config(**__SCREAMING_SNAKE_CASE ) lowercase_ : int = scheduler_class(**__SCREAMING_SNAKE_CASE ) scheduler.set_timesteps(__SCREAMING_SNAKE_CASE ) # copy over dummy past residuals lowercase_ : Optional[Any] = dummy_past_residuals[:] if time_step is None: lowercase_ : List[Any] = scheduler.timesteps[len(scheduler.timesteps ) // 2] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = scheduler_class.from_pretrained(__SCREAMING_SNAKE_CASE ) new_scheduler.set_timesteps(__SCREAMING_SNAKE_CASE ) # copy over dummy past residuals lowercase_ : str = dummy_past_residuals[:] lowercase_ : Optional[int] = scheduler.step(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ).prev_sample lowercase_ : List[Any] = new_scheduler.step(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" lowercase_ : List[str] = scheduler.step(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ).prev_sample lowercase_ : Dict = new_scheduler.step(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def _snake_case ( self ): """simple docstring""" pass def _snake_case ( self , __SCREAMING_SNAKE_CASE=0 , **__SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : List[Any] = dict(self.forward_default_kwargs ) lowercase_ : Tuple = kwargs.pop('''num_inference_steps''' , __SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = self.dummy_sample lowercase_ : Dict = 0.1 * sample lowercase_ : str = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: lowercase_ : Optional[int] = self.get_scheduler_config() lowercase_ : Any = scheduler_class(**__SCREAMING_SNAKE_CASE ) scheduler.set_timesteps(__SCREAMING_SNAKE_CASE ) # copy over dummy past residuals (must be after setting timesteps) lowercase_ : List[Any] = dummy_past_residuals[:] if time_step is None: lowercase_ : Dict = scheduler.timesteps[len(scheduler.timesteps ) // 2] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(__SCREAMING_SNAKE_CASE ) lowercase_ : str = scheduler_class.from_pretrained(__SCREAMING_SNAKE_CASE ) # copy over dummy past residuals new_scheduler.set_timesteps(__SCREAMING_SNAKE_CASE ) # copy over dummy past residual (must be after setting timesteps) lowercase_ : Any = dummy_past_residuals[:] lowercase_ : Optional[Any] = scheduler.step(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ).prev_sample lowercase_ : Dict = new_scheduler.step(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" lowercase_ : int = scheduler.step(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ).prev_sample lowercase_ : int = new_scheduler.step(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def _snake_case ( self , **__SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : str = self.scheduler_classes[0] lowercase_ : Optional[Any] = self.get_scheduler_config(**__SCREAMING_SNAKE_CASE ) lowercase_ : Dict = scheduler_class(**__SCREAMING_SNAKE_CASE ) lowercase_ : Dict = 10 lowercase_ : List[Any] = self.dummy_model() lowercase_ : Tuple = self.dummy_sample_deter scheduler.set_timesteps(__SCREAMING_SNAKE_CASE ) for i, t in enumerate(scheduler.timesteps ): lowercase_ : int = model(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : int = scheduler.step(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).prev_sample for i, t in enumerate(scheduler.timesteps ): lowercase_ : List[Any] = model(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = scheduler.step(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).prev_sample return sample def _snake_case ( self ): """simple docstring""" lowercase_ : List[str] = dict(self.forward_default_kwargs ) lowercase_ : List[str] = kwargs.pop('''num_inference_steps''' , __SCREAMING_SNAKE_CASE ) for scheduler_class in self.scheduler_classes: lowercase_ : Dict = self.get_scheduler_config() lowercase_ : Dict = scheduler_class(**__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = self.dummy_sample lowercase_ : str = 0.1 * sample if num_inference_steps is not None and hasattr(__SCREAMING_SNAKE_CASE , '''set_timesteps''' ): scheduler.set_timesteps(__SCREAMING_SNAKE_CASE ) elif num_inference_steps is not None and not hasattr(__SCREAMING_SNAKE_CASE , '''set_timesteps''' ): lowercase_ : Any = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) lowercase_ : Any = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] lowercase_ : int = dummy_past_residuals[:] lowercase_ : List[str] = scheduler.timesteps[5] lowercase_ : Optional[int] = scheduler.timesteps[6] lowercase_ : int = scheduler.step(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ).prev_sample lowercase_ : int = scheduler.step(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) lowercase_ : Optional[int] = scheduler.step(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ).prev_sample lowercase_ : Tuple = scheduler.step(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def _snake_case ( self ): """simple docstring""" for timesteps in [1_00, 10_00]: self.check_over_configs(num_train_timesteps=__SCREAMING_SNAKE_CASE , time_step=__SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" for t, num_inference_steps in zip([1, 5, 10] , [10, 50, 1_00] ): self.check_over_forward(num_inference_steps=__SCREAMING_SNAKE_CASE , time_step=__SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" lowercase_ : Union[str, Any] = self.full_loop() lowercase_ : Optional[Any] = torch.mean(torch.abs(__SCREAMING_SNAKE_CASE ) ) assert abs(result_mean.item() - 2_54_05_29 ) < 10
93
'''simple docstring''' import glob import os import random from string import ascii_lowercase, digits import cva import numpy as np # Parrameters _lowercase : Any = (7_2_0, 1_2_8_0) # Height, Width _lowercase : List[Any] = (0.4, 0.6) # if height or width lower than this scale, drop it. _lowercase : str = 1 / 1_0_0 _lowercase : Any = "" _lowercase : Union[str, Any] = "" _lowercase : Optional[int] = "" _lowercase : List[Any] = 2_5_0 def snake_case_ ( ): """simple docstring""" lowercase_ , lowercase_ : Any = get_dataset(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) for index in range(__SCREAMING_SNAKE_CASE ): lowercase_ : str = random.sample(range(len(__SCREAMING_SNAKE_CASE ) ) , 4 ) lowercase_ , lowercase_ , lowercase_ : Any = 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' lowercase_ : int = random_chars(32 ) lowercase_ : str = path.split(os.sep )[-1].rsplit('''.''' , 1 )[0] lowercase_ : int = F'''{OUTPUT_DIR}/{file_name}_MOSAIC_{letter_code}''' cva.imwrite(F'''{file_root}.jpg''' , __SCREAMING_SNAKE_CASE , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(F'''Succeeded {index+1}/{NUMBER_IMAGES} with {file_name}''' ) lowercase_ : List[Any] = [] for anno in new_annos: lowercase_ : List[Any] = anno[3] - anno[1] lowercase_ : List[str] = anno[4] - anno[2] lowercase_ : Dict = anno[1] + width / 2 lowercase_ : Dict = anno[2] + height / 2 lowercase_ : 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 snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : str ): """simple docstring""" lowercase_ : Optional[Any] = [] lowercase_ : Optional[Any] = [] for label_file in glob.glob(os.path.join(__SCREAMING_SNAKE_CASE , '''*.txt''' ) ): lowercase_ : int = label_file.split(os.sep )[-1].rsplit('''.''' , 1 )[0] with open(__SCREAMING_SNAKE_CASE ) as in_file: lowercase_ : List[str] = in_file.readlines() lowercase_ : Optional[Any] = os.path.join(__SCREAMING_SNAKE_CASE , F'''{label_name}.jpg''' ) lowercase_ : Optional[int] = [] for obj_list in obj_lists: lowercase_ : List[str] = obj_list.rstrip('''\n''' ).split(''' ''' ) lowercase_ : Optional[int] = float(obj[1] ) - float(obj[3] ) / 2 lowercase_ : Any = float(obj[2] ) - float(obj[4] ) / 2 lowercase_ : str = float(obj[1] ) + float(obj[3] ) / 2 lowercase_ : List[str] = 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 snake_case_ ( __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 , ): """simple docstring""" lowercase_ : List[Any] = np.zeros([output_size[0], output_size[1], 3] , dtype=np.uinta ) lowercase_ : Tuple = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) lowercase_ : List[Any] = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) lowercase_ : Optional[int] = int(scale_x * output_size[1] ) lowercase_ : Dict = int(scale_y * output_size[0] ) lowercase_ : Union[str, Any] = [] lowercase_ : List[Any] = [] for i, index in enumerate(__SCREAMING_SNAKE_CASE ): lowercase_ : Union[str, Any] = all_img_list[index] path_list.append(__SCREAMING_SNAKE_CASE ) lowercase_ : int = all_annos[index] lowercase_ : Dict = cva.imread(__SCREAMING_SNAKE_CASE ) if i == 0: # top-left lowercase_ : Optional[Any] = cva.resize(__SCREAMING_SNAKE_CASE , (divid_point_x, divid_point_y) ) lowercase_ : Tuple = img for bbox in img_annos: lowercase_ : Optional[int] = bbox[1] * scale_x lowercase_ : Optional[Any] = bbox[2] * scale_y lowercase_ : str = bbox[3] * scale_x lowercase_ : Tuple = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 1: # top-right lowercase_ : Dict = cva.resize(__SCREAMING_SNAKE_CASE , (output_size[1] - divid_point_x, divid_point_y) ) lowercase_ : Dict = img for bbox in img_annos: lowercase_ : int = scale_x + bbox[1] * (1 - scale_x) lowercase_ : Dict = bbox[2] * scale_y lowercase_ : Optional[int] = scale_x + bbox[3] * (1 - scale_x) lowercase_ : int = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 2: # bottom-left lowercase_ : List[Any] = cva.resize(__SCREAMING_SNAKE_CASE , (divid_point_x, output_size[0] - divid_point_y) ) lowercase_ : List[str] = img for bbox in img_annos: lowercase_ : Any = bbox[1] * scale_x lowercase_ : Optional[int] = scale_y + bbox[2] * (1 - scale_y) lowercase_ : str = bbox[3] * scale_x lowercase_ : Optional[int] = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) else: # bottom-right lowercase_ : int = cva.resize( __SCREAMING_SNAKE_CASE , (output_size[1] - divid_point_x, output_size[0] - divid_point_y) ) lowercase_ : List[str] = img for bbox in img_annos: lowercase_ : int = scale_x + bbox[1] * (1 - scale_x) lowercase_ : Any = scale_y + bbox[2] * (1 - scale_y) lowercase_ : Optional[Any] = scale_x + bbox[3] * (1 - scale_x) lowercase_ : int = 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: lowercase_ : Optional[Any] = [ anno for anno in new_anno if filter_scale < (anno[3] - anno[1]) and filter_scale < (anno[4] - anno[2]) ] return output_img, new_anno, path_list[0] def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" assert number_char > 1, "The number of character should greater than 1" lowercase_ : Any = ascii_lowercase + digits return "".join(random.choice(__SCREAMING_SNAKE_CASE ) for _ in range(__SCREAMING_SNAKE_CASE ) ) if __name__ == "__main__": main() print("DONE ✅")
93
1
'''simple docstring''' def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : str ): """simple docstring""" lowercase_ : Optional[int] = len(__SCREAMING_SNAKE_CASE ) + 1 lowercase_ : Tuple = len(__SCREAMING_SNAKE_CASE ) + 1 # dp is a 2d matrix where dp[i][j] denotes whether prefix string of # length i of input_string matches with prefix string of length j of # given pattern. # "dp" stands for dynamic programming. lowercase_ : List[Any] = [[0 for i in range(__SCREAMING_SNAKE_CASE )] for j in range(__SCREAMING_SNAKE_CASE )] # since string of zero length match pattern of zero length lowercase_ : Optional[int] = 1 # since pattern of zero length will never match with string of non-zero length for i in range(1 , __SCREAMING_SNAKE_CASE ): lowercase_ : Dict = 0 # since string of zero length will match with pattern where there # is at least one * alternatively for j in range(1 , __SCREAMING_SNAKE_CASE ): lowercase_ : List[Any] = dp[0][j - 2] if pattern[j - 1] == '''*''' else 0 # now using bottom-up approach to find for all remaining lengths for i in range(1 , __SCREAMING_SNAKE_CASE ): for j in range(1 , __SCREAMING_SNAKE_CASE ): if input_string[i - 1] == pattern[j - 1] or pattern[j - 1] == ".": lowercase_ : str = dp[i - 1][j - 1] elif pattern[j - 1] == "*": if dp[i][j - 2] == 1: lowercase_ : int = 1 elif pattern[j - 2] in (input_string[i - 1], "."): lowercase_ : Tuple = dp[i - 1][j] else: lowercase_ : List[Any] = 0 else: lowercase_ : Dict = 0 return bool(dp[-1][-1] ) if __name__ == "__main__": import doctest doctest.testmod() # inputing the strings # input_string = input("input a string :") # pattern = input("input a pattern :") _lowercase : Any = "aab" _lowercase : List[Any] = "c*a*b" # using function to check whether given string matches the given pattern if match_pattern(input_string, pattern): print(f"""{input_string} matches the given pattern {pattern}""") else: print(f"""{input_string} does not match with the given pattern {pattern}""")
93
'''simple docstring''' from __future__ import annotations from collections import Counter from random import random class lowerCAmelCase__ : def __init__( self ): """simple docstring""" lowercase_ : int = {} def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Dict = {} def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" if nodea not in self.connections: self.add_node(__SCREAMING_SNAKE_CASE ) if nodea not in self.connections: self.add_node(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = probability def _snake_case ( self ): """simple docstring""" return list(self.connections ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Any = 0 lowercase_ : Tuple = random() for dest in self.connections[node]: current_probability += self.connections[node][dest] if current_probability > random_value: return dest return "" def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : list[tuple[str, str, float]] , __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : List[Any] = MarkovChainGraphUndirectedUnweighted() for nodea, nodea, probability in transitions: graph.add_transition_probability(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : str = Counter(graph.get_nodes() ) lowercase_ : Any = start for _ in range(__SCREAMING_SNAKE_CASE ): lowercase_ : int = graph.transition(__SCREAMING_SNAKE_CASE ) visited[node] += 1 return visited if __name__ == "__main__": import doctest doctest.testmod()
93
1
'''simple docstring''' import json import os import unittest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowerCAmelCase__ ( lowerCamelCase_ , unittest.TestCase ): lowerCAmelCase_ = CLIPTokenizer lowerCAmelCase_ = CLIPTokenizerFast lowerCAmelCase_ = True lowerCAmelCase_ = {} lowerCAmelCase_ = False def _snake_case ( self ): """simple docstring""" super().setUp() # fmt: off lowercase_ : List[str] = ['''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''lo''', '''l</w>''', '''w</w>''', '''r</w>''', '''t</w>''', '''low</w>''', '''er</w>''', '''lowest</w>''', '''newer</w>''', '''wider''', '''<unk>''', '''<|startoftext|>''', '''<|endoftext|>'''] # fmt: on lowercase_ : Union[str, Any] = dict(zip(__SCREAMING_SNAKE_CASE , range(len(__SCREAMING_SNAKE_CASE ) ) ) ) lowercase_ : Union[str, Any] = ['''#version: 0.2''', '''l o''', '''lo w</w>''', '''e r</w>'''] lowercase_ : Optional[Any] = {'''unk_token''': '''<unk>'''} lowercase_ : Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) lowercase_ : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(__SCREAMING_SNAKE_CASE ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(__SCREAMING_SNAKE_CASE ) ) def _snake_case ( self , **__SCREAMING_SNAKE_CASE ): """simple docstring""" kwargs.update(self.special_tokens_map ) return CLIPTokenizer.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def _snake_case ( self , **__SCREAMING_SNAKE_CASE ): """simple docstring""" kwargs.update(self.special_tokens_map ) return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Union[str, Any] = '''lower newer''' lowercase_ : Optional[int] = '''lower newer''' return input_text, output_text def _snake_case ( self ): """simple docstring""" lowercase_ : Optional[int] = CLIPTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) lowercase_ : Optional[Any] = '''lower newer''' lowercase_ : Any = ['''lo''', '''w''', '''er</w>''', '''n''', '''e''', '''w''', '''er</w>'''] lowercase_ : int = tokenizer.tokenize(__SCREAMING_SNAKE_CASE ) self.assertListEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : List[str] = tokens + [tokenizer.unk_token] lowercase_ : Tuple = [10, 2, 16, 9, 3, 2, 16, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) @require_ftfy def _snake_case ( self ): """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): lowercase_ : Union[str, Any] = self.tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) lowercase_ : int = self.rust_tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) lowercase_ : List[Any] = '''A\n\'ll 11p223RF☆ho!!to?\'d\'d\'\'d of a cat to-$\'\'d.''' lowercase_ : Tuple = tokenizer_s.tokenize(__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = tokenizer_r.tokenize(__SCREAMING_SNAKE_CASE ) self.assertListEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Test that the tokenization is identical on an example containing a character (Latin Small Letter A # with Tilde) encoded in 2 different ways lowercase_ : Optional[Any] = '''xa\u0303y''' + ''' ''' + '''x\xe3y''' lowercase_ : Any = tokenizer_s.tokenize(__SCREAMING_SNAKE_CASE ) lowercase_ : str = tokenizer_r.tokenize(__SCREAMING_SNAKE_CASE ) self.assertListEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Test that the tokenization is identical on unicode of space type lowercase_ : Any = [ '''\u0009''', # (horizontal tab, '\t') '''\u000B''', # (vertical tab) '''\u000C''', # (form feed) '''\u0020''', # (space, ' ') '''\u200E''', # (left-to-right mark):w '''\u200F''', # (right-to-left mark) ] for unicode_seq in spaces_unicodes: lowercase_ : int = tokenizer_s.tokenize(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = tokenizer_r.tokenize(__SCREAMING_SNAKE_CASE ) self.assertListEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Test that the tokenization is identical on unicode of line break type lowercase_ : List[Any] = [ '''\u000A''', # (line feed, '\n') '''\r\n''', # (carriage return and line feed, '\r\n') '''\u000D''', # (carriage return, '\r') '''\r''', # (carriage return, '\r') '''\u000D''', # (carriage return, '\r') '''\u2028''', # (line separator) '''\u2029''', # (paragraph separator) # "\u0085", # (next line) ] # The tokenization is not identical for the character "\u0085" (next line). The slow version using ftfy transforms # it into the Horizontal Ellipsis character "…" ("\u2026") while the fast version transforms it into a # space (and thus into an empty list). for unicode_seq in line_break_unicodes: lowercase_ : int = tokenizer_s.tokenize(__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = tokenizer_r.tokenize(__SCREAMING_SNAKE_CASE ) self.assertListEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): lowercase_ : List[str] = '''hello''' # `hello` is a token in the vocabulary of `pretrained_name` lowercase_ : Optional[int] = F'''{text_of_1_token} {text_of_1_token}''' lowercase_ : str = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , use_fast=__SCREAMING_SNAKE_CASE , ) lowercase_ : int = tokenizer_r(__SCREAMING_SNAKE_CASE , return_offsets_mapping=__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(encoding.offset_mapping[0] , (0, len(__SCREAMING_SNAKE_CASE )) ) self.assertEqual( encoding.offset_mapping[1] , (len(__SCREAMING_SNAKE_CASE ) + 1, len(__SCREAMING_SNAKE_CASE ) + 1 + len(__SCREAMING_SNAKE_CASE )) , ) lowercase_ : Dict = F''' {text}''' lowercase_ : Optional[Any] = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , use_fast=__SCREAMING_SNAKE_CASE , ) lowercase_ : Dict = tokenizer_r(__SCREAMING_SNAKE_CASE , return_offsets_mapping=__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(__SCREAMING_SNAKE_CASE )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(__SCREAMING_SNAKE_CASE ) + 1, 1 + len(__SCREAMING_SNAKE_CASE ) + 1 + len(__SCREAMING_SNAKE_CASE )) , ) def _snake_case ( self ): """simple docstring""" with self.assertRaises(__SCREAMING_SNAKE_CASE ) as context: self.rust_tokenizer_class.from_pretrained('''robot-test/old-clip-tokenizer''' ) self.assertTrue( context.exception.args[0].startswith( '''The `backend_tokenizer` provided does not match the expected format.''' ) ) @require_ftfy def _snake_case ( self ): """simple docstring""" super().test_tokenization_python_rust_equals() def _snake_case ( self ): """simple docstring""" pass
93
'''simple docstring''' import torch from transformers import AutoModel class lowerCAmelCase__ ( torch.nn.Module ): def __init__( self , __SCREAMING_SNAKE_CASE="sayef/fsner-bert-base-uncased" ): """simple docstring""" super(__SCREAMING_SNAKE_CASE , self ).__init__() lowercase_ : Tuple = AutoModel.from_pretrained(__SCREAMING_SNAKE_CASE , return_dict=__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = torch.nn.CosineSimilarity(3 , 1E-0_8 ) lowercase_ : Optional[Any] = torch.nn.Softmax(dim=1 ) def _snake_case ( self , **__SCREAMING_SNAKE_CASE ): """simple docstring""" return self.bert(**__SCREAMING_SNAKE_CASE ).last_hidden_state def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" return token_embeddings.sum(2 , keepdim=__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=1 ): """simple docstring""" return self.softmax(T * self.cos(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Optional[Any] = W_supports['''sizes'''].tolist() lowercase_ : Dict = W_supports['''start_token_id'''].item() lowercase_ : List[Any] = W_supports['''end_token_id'''].item() del W_supports["sizes"] del W_supports["start_token_id"] del W_supports["end_token_id"] lowercase_ : List[str] = self.BERT(**__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = self.BERT(**__SCREAMING_SNAKE_CASE ) lowercase_ : str = None lowercase_ : Dict = None lowercase_ : Tuple = W_supports['''input_ids'''] == start_token_id lowercase_ : Any = W_supports['''input_ids'''] == end_token_id for i, size in enumerate(__SCREAMING_SNAKE_CASE ): if i == 0: lowercase_ : List[str] = 0 else: lowercase_ : List[Any] = support_sizes[i - 1] lowercase_ : str = S[s : s + size][start_token_masks[s : s + size]] lowercase_ : Optional[int] = S[s : s + size][end_token_masks[s : s + size]] lowercase_ : List[str] = torch.matmul(q[i] , s_start.T ).sum(1 ).softmax(0 ) lowercase_ : List[str] = torch.matmul(q[i] , s_end.T ).sum(1 ).softmax(0 ) if p_starts is not None: lowercase_ : Tuple = torch.vstack((p_starts, p_start) ) lowercase_ : Optional[Any] = torch.vstack((p_ends, p_end) ) else: lowercase_ : str = p_start lowercase_ : int = p_end return p_starts, p_ends
93
1
'''simple docstring''' import torch from diffusers import StableDiffusionPipeline _lowercase : List[Any] = "path-to-your-trained-model" _lowercase : str = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.floataa).to("cuda") _lowercase : int = "A photo of sks dog in a bucket" _lowercase : Tuple = pipe(prompt, num_inference_steps=5_0, guidance_scale=7.5).images[0] image.save("dog-bucket.png")
93
'''simple docstring''' import json import os from pathlib import Path from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple, Union import sentencepiece from ...tokenization_utils import BatchEncoding, PreTrainedTokenizer from ...utils import logging _lowercase : List[Any] = logging.get_logger(__name__) _lowercase : List[Any] = "▁" _lowercase : Tuple = { "vocab_file": "vocab.json", "spm_file": "sentencepiece.bpe.model", "tokenizer_config_file": "tokenizer_config.json", } _lowercase : List[str] = { "vocab_file": { "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/vocab.json", "facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/vocab.json", }, "spm_file": { "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/sentencepiece.bpe.model", "facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/sentencepiece.bpe.model", }, "tokenizer_config_file": { "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/tokenizer_config.json", "facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/tokenizer_config.json", }, } _lowercase : List[str] = { "facebook/m2m100_418M": 1_0_2_4, } # fmt: off _lowercase : Tuple = { "m2m100": ["af", "am", "ar", "ast", "az", "ba", "be", "bg", "bn", "br", "bs", "ca", "ceb", "cs", "cy", "da", "de", "el", "en", "es", "et", "fa", "ff", "fi", "fr", "fy", "ga", "gd", "gl", "gu", "ha", "he", "hi", "hr", "ht", "hu", "hy", "id", "ig", "ilo", "is", "it", "ja", "jv", "ka", "kk", "km", "kn", "ko", "lb", "lg", "ln", "lo", "lt", "lv", "mg", "mk", "ml", "mn", "mr", "ms", "my", "ne", "nl", "no", "ns", "oc", "or", "pa", "pl", "ps", "pt", "ro", "ru", "sd", "si", "sk", "sl", "so", "sq", "sr", "ss", "su", "sv", "sw", "ta", "th", "tl", "tn", "tr", "uk", "ur", "uz", "vi", "wo", "xh", "yi", "yo", "zh", "zu"], "wmt21": ["en", "ha", "is", "ja", "cs", "ru", "zh", "de"] } class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = VOCAB_FILES_NAMES lowerCAmelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase_ = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase_ = ['''input_ids''', '''attention_mask'''] lowerCAmelCase_ = [] lowerCAmelCase_ = [] def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE="<s>" , __SCREAMING_SNAKE_CASE="</s>" , __SCREAMING_SNAKE_CASE="</s>" , __SCREAMING_SNAKE_CASE="<pad>" , __SCREAMING_SNAKE_CASE="<unk>" , __SCREAMING_SNAKE_CASE="m2m100" , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE=8 , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : Optional[Any] = {} if sp_model_kwargs is None else sp_model_kwargs lowercase_ : List[Any] = language_codes lowercase_ : Optional[int] = FAIRSEQ_LANGUAGE_CODES[language_codes] lowercase_ : List[Any] = {lang_code: F'''__{lang_code}__''' for lang_code in fairseq_language_code} lowercase_ : Union[str, Any] = kwargs.get('''additional_special_tokens''' , [] ) kwargs["additional_special_tokens"] += [ self.get_lang_token(__SCREAMING_SNAKE_CASE ) for lang_code in fairseq_language_code if self.get_lang_token(__SCREAMING_SNAKE_CASE ) not in kwargs["additional_special_tokens"] ] super().__init__( src_lang=__SCREAMING_SNAKE_CASE , tgt_lang=__SCREAMING_SNAKE_CASE , bos_token=__SCREAMING_SNAKE_CASE , eos_token=__SCREAMING_SNAKE_CASE , sep_token=__SCREAMING_SNAKE_CASE , unk_token=__SCREAMING_SNAKE_CASE , pad_token=__SCREAMING_SNAKE_CASE , language_codes=__SCREAMING_SNAKE_CASE , sp_model_kwargs=self.sp_model_kwargs , num_madeup_words=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) lowercase_ : int = vocab_file lowercase_ : Any = load_json(__SCREAMING_SNAKE_CASE ) lowercase_ : str = {v: k for k, v in self.encoder.items()} lowercase_ : Optional[int] = spm_file lowercase_ : Any = load_spm(__SCREAMING_SNAKE_CASE , self.sp_model_kwargs ) lowercase_ : List[Any] = len(self.encoder ) lowercase_ : Dict = { self.get_lang_token(__SCREAMING_SNAKE_CASE ): self.encoder_size + i for i, lang_code in enumerate(__SCREAMING_SNAKE_CASE ) } lowercase_ : Optional[int] = {lang_code: self.encoder_size + i for i, lang_code in enumerate(__SCREAMING_SNAKE_CASE )} lowercase_ : Union[str, Any] = {v: k for k, v in self.lang_token_to_id.items()} lowercase_ : Tuple = src_lang if src_lang is not None else '''en''' lowercase_ : Optional[int] = tgt_lang lowercase_ : Any = self.get_lang_id(self._src_lang ) self.set_src_lang_special_tokens(self._src_lang ) lowercase_ : Dict = num_madeup_words @property def _snake_case ( self ): """simple docstring""" return len(self.encoder ) + len(self.lang_token_to_id ) @property def _snake_case ( self ): """simple docstring""" return self._src_lang @src_lang.setter def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : str = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" return self.sp_model.encode(__SCREAMING_SNAKE_CASE , out_type=__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" if token in self.lang_token_to_id: return self.lang_token_to_id[token] return self.encoder.get(__SCREAMING_SNAKE_CASE , self.encoder[self.unk_token] ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" if index in self.id_to_lang_token: return self.id_to_lang_token[index] return self.decoder.get(__SCREAMING_SNAKE_CASE , self.unk_token ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Tuple = [] lowercase_ : List[str] = '''''' for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(__SCREAMING_SNAKE_CASE ) + token lowercase_ : Optional[Any] = [] else: current_sub_tokens.append(__SCREAMING_SNAKE_CASE ) out_string += self.sp_model.decode(__SCREAMING_SNAKE_CASE ) return out_string.strip() def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = False ): """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__SCREAMING_SNAKE_CASE , token_ids_a=__SCREAMING_SNAKE_CASE , already_has_special_tokens=__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = [1] * len(self.prefix_tokens ) lowercase_ : Any = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(__SCREAMING_SNAKE_CASE )) + suffix_ones return prefix_ones + ([0] * len(__SCREAMING_SNAKE_CASE )) + ([0] * len(__SCREAMING_SNAKE_CASE )) + suffix_ones def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def _snake_case ( self ): """simple docstring""" lowercase_ : Tuple = {self.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ): """simple docstring""" lowercase_ : List[Any] = self.__dict__.copy() lowercase_ : List[Any] = None return state def __setstate__( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Dict = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): lowercase_ : List[Any] = {} lowercase_ : Union[str, Any] = load_spm(self.spm_file , self.sp_model_kwargs ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" lowercase_ : Tuple = Path(__SCREAMING_SNAKE_CASE ) if not save_dir.is_dir(): raise OSError(F'''{save_directory} should be a directory''' ) lowercase_ : Dict = save_dir / ( (filename_prefix + '''-''' if filename_prefix else '''''') + self.vocab_files_names['''vocab_file'''] ) lowercase_ : Dict = save_dir / ( (filename_prefix + '''-''' if filename_prefix else '''''') + self.vocab_files_names['''spm_file'''] ) save_json(self.encoder , __SCREAMING_SNAKE_CASE ) if os.path.abspath(self.spm_file ) != os.path.abspath(__SCREAMING_SNAKE_CASE ) and os.path.isfile(self.spm_file ): copyfile(self.spm_file , __SCREAMING_SNAKE_CASE ) elif not os.path.isfile(self.spm_file ): with open(__SCREAMING_SNAKE_CASE , '''wb''' ) as fi: lowercase_ : int = self.sp_model.serialized_model_proto() fi.write(__SCREAMING_SNAKE_CASE ) return (str(__SCREAMING_SNAKE_CASE ), str(__SCREAMING_SNAKE_CASE )) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = "en" , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = "ro" , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : Optional[Any] = src_lang lowercase_ : List[str] = tgt_lang self.set_src_lang_special_tokens(self.src_lang ) return super().prepare_seqaseq_batch(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" if src_lang is None or tgt_lang is None: raise ValueError('''Translation requires a `src_lang` and a `tgt_lang` for this model''' ) lowercase_ : Tuple = src_lang lowercase_ : Any = self(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) lowercase_ : List[Any] = self.get_lang_id(__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = tgt_lang_id return inputs def _snake_case ( self ): """simple docstring""" self.set_src_lang_special_tokens(self.src_lang ) def _snake_case ( self ): """simple docstring""" self.set_tgt_lang_special_tokens(self.tgt_lang ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Any = self.get_lang_token(__SCREAMING_SNAKE_CASE ) lowercase_ : Dict = self.lang_token_to_id[lang_token] lowercase_ : Optional[Any] = [self.cur_lang_id] lowercase_ : Union[str, Any] = [self.eos_token_id] def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Any = self.get_lang_token(__SCREAMING_SNAKE_CASE ) lowercase_ : Any = self.lang_token_to_id[lang_token] lowercase_ : str = [self.cur_lang_id] lowercase_ : List[str] = [self.eos_token_id] def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" return self.lang_code_to_token[lang] def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : List[Any] = self.get_lang_token(__SCREAMING_SNAKE_CASE ) return self.lang_token_to_id[lang_token] def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Dict[str, Any] ): """simple docstring""" lowercase_ : Optional[int] = sentencepiece.SentencePieceProcessor(**__SCREAMING_SNAKE_CASE ) spm.Load(str(__SCREAMING_SNAKE_CASE ) ) return spm def snake_case_ ( __SCREAMING_SNAKE_CASE : str ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE , '''r''' ) as f: return json.load(__SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : str ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE , '''w''' ) as f: json.dump(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , indent=2 )
93
1
'''simple docstring''' from typing import List, Optional, Union from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = ['''image_processor''', '''tokenizer'''] lowerCAmelCase_ = '''BlipImageProcessor''' lowerCAmelCase_ = ('''BertTokenizer''', '''BertTokenizerFast''') def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Union[str, Any] = False super().__init__(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = self.image_processor def __call__( self , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = True , __SCREAMING_SNAKE_CASE = False , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = 0 , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = False , __SCREAMING_SNAKE_CASE = False , __SCREAMING_SNAKE_CASE = False , __SCREAMING_SNAKE_CASE = False , __SCREAMING_SNAKE_CASE = False , __SCREAMING_SNAKE_CASE = True , __SCREAMING_SNAKE_CASE = None , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" if images is None and text is None: raise ValueError('''You have to specify either images or text.''' ) # Get only text if images is None: lowercase_ : Dict = self.tokenizer lowercase_ : List[str] = self.tokenizer( text=__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=__SCREAMING_SNAKE_CASE , stride=__SCREAMING_SNAKE_CASE , pad_to_multiple_of=__SCREAMING_SNAKE_CASE , return_attention_mask=__SCREAMING_SNAKE_CASE , return_overflowing_tokens=__SCREAMING_SNAKE_CASE , return_special_tokens_mask=__SCREAMING_SNAKE_CASE , return_offsets_mapping=__SCREAMING_SNAKE_CASE , return_token_type_ids=__SCREAMING_SNAKE_CASE , return_length=__SCREAMING_SNAKE_CASE , verbose=__SCREAMING_SNAKE_CASE , return_tensors=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) return text_encoding # add pixel_values lowercase_ : Dict = self.image_processor(__SCREAMING_SNAKE_CASE , return_tensors=__SCREAMING_SNAKE_CASE ) if text is not None: lowercase_ : int = self.tokenizer( text=__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=__SCREAMING_SNAKE_CASE , stride=__SCREAMING_SNAKE_CASE , pad_to_multiple_of=__SCREAMING_SNAKE_CASE , return_attention_mask=__SCREAMING_SNAKE_CASE , return_overflowing_tokens=__SCREAMING_SNAKE_CASE , return_special_tokens_mask=__SCREAMING_SNAKE_CASE , return_offsets_mapping=__SCREAMING_SNAKE_CASE , return_token_type_ids=__SCREAMING_SNAKE_CASE , return_length=__SCREAMING_SNAKE_CASE , verbose=__SCREAMING_SNAKE_CASE , return_tensors=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) else: lowercase_ : Any = None if text_encoding is not None: encoding_image_processor.update(__SCREAMING_SNAKE_CASE ) return encoding_image_processor def _snake_case ( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" return self.tokenizer.batch_decode(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def _snake_case ( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" return self.tokenizer.decode(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) @property def _snake_case ( self ): """simple docstring""" lowercase_ : Optional[Any] = self.tokenizer.model_input_names lowercase_ : str = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
93
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer from ...utils import logging _lowercase : str = logging.get_logger(__name__) _lowercase : List[Any] = "▁" _lowercase : List[Any] = {"vocab_file": "sentencepiece.bpe.model"} _lowercase : Optional[int] = { "vocab_file": { "facebook/mbart-large-en-ro": ( "https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/sentencepiece.bpe.model" ), "facebook/mbart-large-cc25": ( "https://huggingface.co/facebook/mbart-large-cc25/resolve/main/sentencepiece.bpe.model" ), } } _lowercase : str = { "facebook/mbart-large-en-ro": 1_0_2_4, "facebook/mbart-large-cc25": 1_0_2_4, } # fmt: off _lowercase : List[Any] = ["ar_AR", "cs_CZ", "de_DE", "en_XX", "es_XX", "et_EE", "fi_FI", "fr_XX", "gu_IN", "hi_IN", "it_IT", "ja_XX", "kk_KZ", "ko_KR", "lt_LT", "lv_LV", "my_MM", "ne_NP", "nl_XX", "ro_RO", "ru_RU", "si_LK", "tr_TR", "vi_VN", "zh_CN"] class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = VOCAB_FILES_NAMES lowerCAmelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase_ = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase_ = ['''input_ids''', '''attention_mask'''] lowerCAmelCase_ = [] lowerCAmelCase_ = [] def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE="<s>" , __SCREAMING_SNAKE_CASE="</s>" , __SCREAMING_SNAKE_CASE="</s>" , __SCREAMING_SNAKE_CASE="<s>" , __SCREAMING_SNAKE_CASE="<unk>" , __SCREAMING_SNAKE_CASE="<pad>" , __SCREAMING_SNAKE_CASE="<mask>" , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE=None , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : Any = AddedToken(__SCREAMING_SNAKE_CASE , lstrip=__SCREAMING_SNAKE_CASE , rstrip=__SCREAMING_SNAKE_CASE ) if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else mask_token lowercase_ : int = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=__SCREAMING_SNAKE_CASE , eos_token=__SCREAMING_SNAKE_CASE , unk_token=__SCREAMING_SNAKE_CASE , sep_token=__SCREAMING_SNAKE_CASE , cls_token=__SCREAMING_SNAKE_CASE , pad_token=__SCREAMING_SNAKE_CASE , mask_token=__SCREAMING_SNAKE_CASE , tokenizer_file=__SCREAMING_SNAKE_CASE , src_lang=__SCREAMING_SNAKE_CASE , tgt_lang=__SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , sp_model_kwargs=self.sp_model_kwargs , **__SCREAMING_SNAKE_CASE , ) lowercase_ : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__SCREAMING_SNAKE_CASE ) ) lowercase_ : List[str] = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # Mimic fairseq token-to-id alignment for the first 4 token lowercase_ : Tuple = {'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3} # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab lowercase_ : str = 1 lowercase_ : str = len(self.sp_model ) lowercase_ : List[Any] = { code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(__SCREAMING_SNAKE_CASE ) } lowercase_ : Union[str, Any] = {v: k for k, v in self.lang_code_to_id.items()} lowercase_ : List[Any] = len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset self.fairseq_tokens_to_ids.update(self.lang_code_to_id ) lowercase_ : Union[str, Any] = {v: k for k, v in self.fairseq_tokens_to_ids.items()} lowercase_ : Optional[Any] = list(self.lang_code_to_id.keys() ) if additional_special_tokens is not None: # Only add those special tokens if they are not already there. self._additional_special_tokens.extend( [t for t in additional_special_tokens if t not in self._additional_special_tokens] ) lowercase_ : Optional[Any] = src_lang if src_lang is not None else '''en_XX''' lowercase_ : str = self.lang_code_to_id[self._src_lang] lowercase_ : Optional[Any] = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) def __getstate__( self ): """simple docstring""" lowercase_ : Optional[int] = self.__dict__.copy() lowercase_ : Dict = None lowercase_ : Any = self.sp_model.serialized_model_proto() return state def __setstate__( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Optional[Any] = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): lowercase_ : Dict = {} lowercase_ : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) @property def _snake_case ( self ): """simple docstring""" return len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset + 1 # Plus 1 for the mask token @property def _snake_case ( self ): """simple docstring""" return self._src_lang @src_lang.setter def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Tuple = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = False ): """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__SCREAMING_SNAKE_CASE , token_ids_a=__SCREAMING_SNAKE_CASE , already_has_special_tokens=__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = [1] * len(self.prefix_tokens ) lowercase_ : Tuple = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(__SCREAMING_SNAKE_CASE )) + suffix_ones return prefix_ones + ([0] * len(__SCREAMING_SNAKE_CASE )) + ([0] * len(__SCREAMING_SNAKE_CASE )) + suffix_ones def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" lowercase_ : Optional[int] = [self.sep_token_id] lowercase_ : Any = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" if src_lang is None or tgt_lang is None: raise ValueError('''Translation requires a `src_lang` and a `tgt_lang` for this model''' ) lowercase_ : Optional[Any] = src_lang lowercase_ : Dict = self(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , return_tensors=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = self.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = tgt_lang_id return inputs def _snake_case ( self ): """simple docstring""" lowercase_ : str = {self.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" return self.sp_model.encode(__SCREAMING_SNAKE_CASE , out_type=__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] lowercase_ : Any = self.sp_model.PieceToId(__SCREAMING_SNAKE_CASE ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : int = ''''''.join(__SCREAMING_SNAKE_CASE ).replace(__SCREAMING_SNAKE_CASE , ''' ''' ).strip() return out_string def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" if not os.path.isdir(__SCREAMING_SNAKE_CASE ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return lowercase_ : Tuple = os.path.join( __SCREAMING_SNAKE_CASE , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__SCREAMING_SNAKE_CASE ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __SCREAMING_SNAKE_CASE ) elif not os.path.isfile(self.vocab_file ): with open(__SCREAMING_SNAKE_CASE , '''wb''' ) as fi: lowercase_ : List[str] = self.sp_model.serialized_model_proto() fi.write(__SCREAMING_SNAKE_CASE ) return (out_vocab_file,) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = "en_XX" , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = "ro_RO" , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : List[str] = src_lang lowercase_ : int = tgt_lang return super().prepare_seqaseq_batch(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" return self.set_src_lang_special_tokens(self.src_lang ) def _snake_case ( self ): """simple docstring""" return self.set_tgt_lang_special_tokens(self.tgt_lang ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Dict = self.lang_code_to_id[src_lang] lowercase_ : Optional[Any] = [] lowercase_ : List[str] = [self.eos_token_id, self.cur_lang_code] def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : List[Any] = self.lang_code_to_id[lang] lowercase_ : Dict = [] lowercase_ : Union[str, Any] = [self.eos_token_id, self.cur_lang_code]
93
1
'''simple docstring''' import math import sys def snake_case_ ( __SCREAMING_SNAKE_CASE : str ): """simple docstring""" lowercase_ : str = '''''' try: with open(__SCREAMING_SNAKE_CASE , '''rb''' ) as binary_file: lowercase_ : str = binary_file.read() for dat in data: lowercase_ : Union[str, Any] = F'''{dat:08b}''' result += curr_byte return result except OSError: print('''File not accessible''' ) sys.exit() def snake_case_ ( __SCREAMING_SNAKE_CASE : str ): """simple docstring""" lowercase_ : List[Any] = {'''0''': '''0''', '''1''': '''1'''} lowercase_ , lowercase_ : int = '''''', '''''' lowercase_ : Optional[int] = len(__SCREAMING_SNAKE_CASE ) for i in range(len(__SCREAMING_SNAKE_CASE ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue lowercase_ : str = lexicon[curr_string] result += last_match_id lowercase_ : Optional[Any] = last_match_id + '''0''' if math.loga(__SCREAMING_SNAKE_CASE ).is_integer(): lowercase_ : str = {} for curr_key in list(__SCREAMING_SNAKE_CASE ): lowercase_ : str = lexicon.pop(__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = new_lex lowercase_ : Union[str, Any] = last_match_id + '''1''' index += 1 lowercase_ : List[str] = '''''' return result def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : str ): """simple docstring""" lowercase_ : int = 8 try: with open(__SCREAMING_SNAKE_CASE , '''wb''' ) as opened_file: lowercase_ : Union[str, 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 snake_case_ ( __SCREAMING_SNAKE_CASE : str ): """simple docstring""" lowercase_ : Tuple = 0 for letter in data_bits: if letter == "1": break counter += 1 lowercase_ : int = data_bits[counter:] lowercase_ : int = data_bits[counter + 1 :] return data_bits def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : str ): """simple docstring""" lowercase_ : Optional[int] = read_file_binary(__SCREAMING_SNAKE_CASE ) lowercase_ : Dict = remove_prefix(__SCREAMING_SNAKE_CASE ) lowercase_ : 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])
93
'''simple docstring''' import json import os import tempfile from transformers.testing_utils import check_json_file_has_correct_format class lowerCAmelCase__ : lowerCAmelCase_ = None def _snake_case ( self ): """simple docstring""" lowercase_ : Tuple = self.feature_extraction_class(**self.feat_extract_dict ) lowercase_ : Any = json.loads(feat_extract.to_json_string() ) for key, value in self.feat_extract_dict.items(): self.assertEqual(obj[key] , __SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" lowercase_ : str = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: lowercase_ : str = os.path.join(__SCREAMING_SNAKE_CASE , '''feat_extract.json''' ) feat_extract_first.to_json_file(__SCREAMING_SNAKE_CASE ) lowercase_ : str = self.feature_extraction_class.from_json_file(__SCREAMING_SNAKE_CASE ) self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() ) def _snake_case ( self ): """simple docstring""" lowercase_ : Tuple = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: lowercase_ : Union[str, Any] = feat_extract_first.save_pretrained(__SCREAMING_SNAKE_CASE )[0] check_json_file_has_correct_format(__SCREAMING_SNAKE_CASE ) lowercase_ : str = self.feature_extraction_class.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() ) def _snake_case ( self ): """simple docstring""" lowercase_ : Optional[Any] = self.feature_extraction_class() self.assertIsNotNone(__SCREAMING_SNAKE_CASE )
93
1
'''simple docstring''' import argparse from collections import defaultdict import yaml _lowercase : Dict = "docs/source/en/_toctree.yml" def snake_case_ ( __SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" lowercase_ : Optional[Any] = defaultdict(__SCREAMING_SNAKE_CASE ) lowercase_ : List[str] = [] lowercase_ : Optional[Any] = [] for doc in doc_list: if "local" in doc: counts[doc["local"]] += 1 if doc["title"].lower() == "overview": overview_doc.append({'''local''': doc['''local'''], '''title''': doc['''title''']} ) else: new_doc_list.append(__SCREAMING_SNAKE_CASE ) lowercase_ : List[str] = new_doc_list lowercase_ : Any = [key for key, value in counts.items() if value > 1] lowercase_ : Any = [] for duplicate_key in duplicates: lowercase_ : List[Any] = list({doc['''title'''] for doc in doc_list 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 doc_list if '''local''' not in counts or counts[doc['''local''']] == 1] ) lowercase_ : List[Any] = sorted(__SCREAMING_SNAKE_CASE , key=lambda __SCREAMING_SNAKE_CASE : s["title"].lower() ) # "overview" gets special treatment and is always first if len(__SCREAMING_SNAKE_CASE ) > 1: raise ValueError('''{doc_list} has two \'overview\' docs which is not allowed.''' ) overview_doc.extend(__SCREAMING_SNAKE_CASE ) # Sort return overview_doc def snake_case_ ( __SCREAMING_SNAKE_CASE : Any=False ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE , encoding='''utf-8''' ) as f: lowercase_ : Dict = yaml.safe_load(f.read() ) # Get to the API doc lowercase_ : Any = 0 while content[api_idx]["title"] != "API": api_idx += 1 lowercase_ : Optional[Any] = content[api_idx]['''sections'''] # Then to the model doc lowercase_ : Tuple = 0 while api_doc[scheduler_idx]["title"] != "Schedulers": scheduler_idx += 1 lowercase_ : Optional[int] = api_doc[scheduler_idx]['''sections'''] lowercase_ : Union[str, Any] = clean_doc_toc(__SCREAMING_SNAKE_CASE ) lowercase_ : List[Any] = False if new_scheduler_doc != scheduler_doc: lowercase_ : Any = True if overwrite: lowercase_ : List[str] = new_scheduler_doc if diff: if overwrite: lowercase_ : 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.''' ) def snake_case_ ( __SCREAMING_SNAKE_CASE : int=False ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE , encoding='''utf-8''' ) as f: lowercase_ : Optional[int] = yaml.safe_load(f.read() ) # Get to the API doc lowercase_ : int = 0 while content[api_idx]["title"] != "API": api_idx += 1 lowercase_ : Any = content[api_idx]['''sections'''] # Then to the model doc lowercase_ : Any = 0 while api_doc[pipeline_idx]["title"] != "Pipelines": pipeline_idx += 1 lowercase_ : Optional[int] = False lowercase_ : str = api_doc[pipeline_idx]['''sections'''] lowercase_ : Optional[int] = [] # sort sub pipeline docs for pipeline_doc in pipeline_docs: if "section" in pipeline_doc: lowercase_ : List[Any] = pipeline_doc['''section'''] lowercase_ : Union[str, Any] = clean_doc_toc(__SCREAMING_SNAKE_CASE ) if overwrite: lowercase_ : List[Any] = new_sub_pipeline_doc new_pipeline_docs.append(__SCREAMING_SNAKE_CASE ) # sort overall pipeline doc lowercase_ : int = clean_doc_toc(__SCREAMING_SNAKE_CASE ) if new_pipeline_docs != pipeline_docs: lowercase_ : List[str] = True if overwrite: lowercase_ : str = new_pipeline_docs if diff: if overwrite: lowercase_ : Union[str, 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__": _lowercase : List[str] = argparse.ArgumentParser() parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.") _lowercase : str = parser.parse_args() check_scheduler_doc(args.fix_and_overwrite) check_pipeline_doc(args.fix_and_overwrite)
93
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging _lowercase : Optional[Any] = logging.get_logger(__name__) _lowercase : List[str] = { "google/pix2struct-textcaps-base": ( "https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json" ), } class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = '''pix2struct_text_model''' lowerCAmelCase_ = ['''past_key_values'''] lowerCAmelCase_ = { '''hidden_size''': '''hidden_size''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self , __SCREAMING_SNAKE_CASE=5_02_44 , __SCREAMING_SNAKE_CASE=7_68 , __SCREAMING_SNAKE_CASE=64 , __SCREAMING_SNAKE_CASE=20_48 , __SCREAMING_SNAKE_CASE=12 , __SCREAMING_SNAKE_CASE=12 , __SCREAMING_SNAKE_CASE=32 , __SCREAMING_SNAKE_CASE=1_28 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=1E-6 , __SCREAMING_SNAKE_CASE=1.0 , __SCREAMING_SNAKE_CASE="gelu_new" , __SCREAMING_SNAKE_CASE=0 , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=0 , __SCREAMING_SNAKE_CASE=1 , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=True , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : Any = vocab_size lowercase_ : Tuple = hidden_size lowercase_ : Optional[Any] = d_kv lowercase_ : List[str] = d_ff lowercase_ : List[str] = num_layers lowercase_ : Optional[Any] = num_heads lowercase_ : Union[str, Any] = relative_attention_num_buckets lowercase_ : Optional[int] = relative_attention_max_distance lowercase_ : Union[str, Any] = dropout_rate lowercase_ : Dict = layer_norm_epsilon lowercase_ : Dict = initializer_factor lowercase_ : List[Any] = use_cache lowercase_ : Optional[int] = eos_token_id lowercase_ : Optional[int] = decoder_start_token_id # for backwards compatibility lowercase_ : Any = dense_act_fn super().__init__( pad_token_id=__SCREAMING_SNAKE_CASE , eos_token_id=__SCREAMING_SNAKE_CASE , decoder_start_token_id=__SCREAMING_SNAKE_CASE , tie_word_embeddings=__SCREAMING_SNAKE_CASE , is_decoder=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) @classmethod def _snake_case ( cls , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" cls._set_token_in_kwargs(__SCREAMING_SNAKE_CASE ) lowercase_ , lowercase_ : Optional[int] = cls.get_config_dict(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) # get the text config dict if we are loading from Pix2StructConfig if config_dict.get('''model_type''' ) == "pix2struct": lowercase_ : List[Any] = config_dict['''text_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'''You are using a model of type {config_dict['model_type']} to instantiate a model of type ''' F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = '''pix2struct_vision_model''' def __init__( self , __SCREAMING_SNAKE_CASE=7_68 , __SCREAMING_SNAKE_CASE=7_68 , __SCREAMING_SNAKE_CASE=20_48 , __SCREAMING_SNAKE_CASE=64 , __SCREAMING_SNAKE_CASE=12 , __SCREAMING_SNAKE_CASE=12 , __SCREAMING_SNAKE_CASE="gelu_new" , __SCREAMING_SNAKE_CASE=1E-6 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=1E-1_0 , __SCREAMING_SNAKE_CASE=1.0 , __SCREAMING_SNAKE_CASE=40_96 , __SCREAMING_SNAKE_CASE=32 , __SCREAMING_SNAKE_CASE=1_28 , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = hidden_size lowercase_ : Any = patch_embed_hidden_size lowercase_ : List[Any] = d_ff lowercase_ : Dict = dropout_rate lowercase_ : Any = num_hidden_layers lowercase_ : Any = num_attention_heads lowercase_ : int = initializer_range lowercase_ : Dict = initializer_factor lowercase_ : Dict = attention_dropout lowercase_ : Optional[Any] = layer_norm_eps lowercase_ : str = dense_act_fn lowercase_ : Dict = seq_len lowercase_ : List[Any] = relative_attention_num_buckets lowercase_ : int = relative_attention_max_distance lowercase_ : Optional[int] = d_kv @classmethod def _snake_case ( cls , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" cls._set_token_in_kwargs(__SCREAMING_SNAKE_CASE ) lowercase_ , lowercase_ : str = cls.get_config_dict(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) # get the vision config dict if we are loading from Pix2StructConfig if config_dict.get('''model_type''' ) == "pix2struct": lowercase_ : Optional[int] = config_dict['''vision_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'''You are using a model of type {config_dict['model_type']} to instantiate a model of type ''' F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = '''pix2struct''' lowerCAmelCase_ = True def __init__( self , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=1.0 , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=True , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" super().__init__(tie_word_embeddings=__SCREAMING_SNAKE_CASE , is_encoder_decoder=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) if text_config is None: lowercase_ : Optional[Any] = {} logger.info('''text_config is None. Initializing the Pix2StructTextConfig with default values.''' ) if vision_config is None: lowercase_ : Dict = {} logger.info('''vision_config is None. Initializing the Pix2StructVisionConfig with default values.''' ) lowercase_ : str = PixaStructTextConfig(**__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = PixaStructVisionConfig(**__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = self.text_config.decoder_start_token_id lowercase_ : Union[str, Any] = self.text_config.pad_token_id lowercase_ : Union[str, Any] = self.text_config.eos_token_id lowercase_ : int = initializer_factor lowercase_ : Any = initializer_range lowercase_ : str = self.initializer_range lowercase_ : str = self.initializer_range lowercase_ : int = is_vqa @classmethod def _snake_case ( cls , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **__SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" lowercase_ : Tuple = copy.deepcopy(self.__dict__ ) lowercase_ : Any = self.text_config.to_dict() lowercase_ : Optional[Any] = self.vision_config.to_dict() lowercase_ : Optional[int] = self.__class__.model_type return output
93
1
'''simple docstring''' import sys from typing import Tuple import numpy as np import torch from PIL import Image from torch import nn from transformers.image_utils import PILImageResampling from utils import img_tensorize class lowerCAmelCase__ : def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=sys.maxsize ): """simple docstring""" lowercase_ : str = '''bilinear''' lowercase_ : int = max_size lowercase_ : int = short_edge_length def __call__( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Tuple = [] for img in imgs: lowercase_ , lowercase_ : int = img.shape[:2] # later: provide list and randomly choose index for resize lowercase_ : int = np.random.randint(self.short_edge_length[0] , self.short_edge_length[1] + 1 ) if size == 0: return img lowercase_ : str = size * 1.0 / min(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if h < w: lowercase_ , lowercase_ : Tuple = size, scale * w else: lowercase_ , lowercase_ : str = scale * h, size if max(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) > self.max_size: lowercase_ : Union[str, Any] = self.max_size * 1.0 / max(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = newh * scale lowercase_ : Union[str, Any] = neww * scale lowercase_ : Tuple = int(neww + 0.5 ) lowercase_ : List[str] = int(newh + 0.5 ) if img.dtype == np.uinta: lowercase_ : Union[str, Any] = Image.fromarray(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = pil_image.resize((neww, newh) , PILImageResampling.BILINEAR ) lowercase_ : Any = np.asarray(__SCREAMING_SNAKE_CASE ) else: lowercase_ : List[Any] = img.permute(2 , 0 , 1 ).unsqueeze(0 ) # 3, 0, 1) # hw(c) -> nchw lowercase_ : int = nn.functional.interpolate( __SCREAMING_SNAKE_CASE , (newh, neww) , mode=self.interp_method , align_corners=__SCREAMING_SNAKE_CASE ).squeeze(0 ) img_augs.append(__SCREAMING_SNAKE_CASE ) return img_augs class lowerCAmelCase__ : def __init__( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Union[str, Any] = ResizeShortestEdge([cfg.INPUT.MIN_SIZE_TEST, cfg.INPUT.MIN_SIZE_TEST] , cfg.INPUT.MAX_SIZE_TEST ) lowercase_ : int = cfg.INPUT.FORMAT lowercase_ : Optional[int] = cfg.SIZE_DIVISIBILITY lowercase_ : List[Any] = cfg.PAD_VALUE lowercase_ : Optional[Any] = cfg.INPUT.MAX_SIZE_TEST lowercase_ : Tuple = cfg.MODEL.DEVICE lowercase_ : int = torch.tensor(cfg.MODEL.PIXEL_STD ).to(self.device ).view(len(cfg.MODEL.PIXEL_STD ) , 1 , 1 ) lowercase_ : List[Any] = torch.tensor(cfg.MODEL.PIXEL_MEAN ).to(self.device ).view(len(cfg.MODEL.PIXEL_STD ) , 1 , 1 ) lowercase_ : Union[str, Any] = lambda __SCREAMING_SNAKE_CASE : (x - self.pixel_mean) / self.pixel_std def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Union[str, Any] = tuple(max(__SCREAMING_SNAKE_CASE ) for s in zip(*[img.shape for img in images] ) ) lowercase_ : List[Any] = [im.shape[-2:] for im in images] lowercase_ : int = [ nn.functional.pad( __SCREAMING_SNAKE_CASE , [0, max_size[-1] - size[1], 0, max_size[-2] - size[0]] , value=self.pad_value , ) for size, im in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ] return torch.stack(__SCREAMING_SNAKE_CASE ), torch.tensor(__SCREAMING_SNAKE_CASE ) def __call__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=False ): """simple docstring""" with torch.no_grad(): if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase_ : Dict = [images] if single_image: assert len(__SCREAMING_SNAKE_CASE ) == 1 for i in range(len(__SCREAMING_SNAKE_CASE ) ): if isinstance(images[i] , torch.Tensor ): images.insert(__SCREAMING_SNAKE_CASE , images.pop(__SCREAMING_SNAKE_CASE ).to(self.device ).float() ) elif not isinstance(images[i] , torch.Tensor ): images.insert( __SCREAMING_SNAKE_CASE , torch.as_tensor(img_tensorize(images.pop(__SCREAMING_SNAKE_CASE ) , input_format=self.input_format ) ) .to(self.device ) .float() , ) # resize smallest edge lowercase_ : Any = torch.tensor([im.shape[:2] for im in images] ) lowercase_ : Tuple = self.aug(__SCREAMING_SNAKE_CASE ) # transpose images and convert to torch tensors # images = [torch.as_tensor(i.astype("float32")).permute(2, 0, 1).to(self.device) for i in images] # now normalize before pad to avoid useless arithmetic lowercase_ : Any = [self.normalizer(__SCREAMING_SNAKE_CASE ) for x in images] # now pad them to do the following operations lowercase_ , lowercase_ : Optional[Any] = self.pad(__SCREAMING_SNAKE_CASE ) # Normalize if self.size_divisibility > 0: raise NotImplementedError() # pad lowercase_ : List[str] = torch.true_divide(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if single_image: return images[0], sizes[0], scales_yx[0] else: return images, sizes, scales_yx def snake_case_ ( __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" boxes[:, 0::2] *= scale_yx[:, 1] boxes[:, 1::2] *= scale_yx[:, 0] return boxes def snake_case_ ( __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Tuple[int, int] ): """simple docstring""" assert torch.isfinite(__SCREAMING_SNAKE_CASE ).all(), "Box tensor contains infinite or NaN!" lowercase_ , lowercase_ : Union[str, Any] = box_size tensor[:, 0].clamp_(min=0 , max=__SCREAMING_SNAKE_CASE ) tensor[:, 1].clamp_(min=0 , max=__SCREAMING_SNAKE_CASE ) tensor[:, 2].clamp_(min=0 , max=__SCREAMING_SNAKE_CASE ) tensor[:, 3].clamp_(min=0 , max=__SCREAMING_SNAKE_CASE )
93
'''simple docstring''' from math import isqrt, loga def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : Any = [True] * max_number for i in range(2 , isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2 , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase_ : Optional[Any] = False return [i for i in range(2 , __SCREAMING_SNAKE_CASE ) if is_prime[i]] def snake_case_ ( __SCREAMING_SNAKE_CASE : int = 800800 , __SCREAMING_SNAKE_CASE : int = 800800 ): """simple docstring""" lowercase_ : Union[str, Any] = degree * loga(__SCREAMING_SNAKE_CASE ) lowercase_ : Any = int(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = calculate_prime_numbers(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = 0 lowercase_ : List[Any] = 0 lowercase_ : Union[str, Any] = len(__SCREAMING_SNAKE_CASE ) - 1 while left < right: while ( prime_numbers[right] * loga(prime_numbers[left] ) + prime_numbers[left] * loga(prime_numbers[right] ) > upper_bound ): right -= 1 hybrid_integers_count += right - left left += 1 return hybrid_integers_count if __name__ == "__main__": print(f"""{solution() = }""")
93
1
'''simple docstring''' def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : str ): """simple docstring""" assert x is not None assert y is not None lowercase_ : Dict = len(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = len(__SCREAMING_SNAKE_CASE ) # declaring the array for storing the dp values lowercase_ : Optional[Any] = [[0] * (n + 1) for _ in range(m + 1 )] # noqa: E741 for i in range(1 , m + 1 ): for j in range(1 , n + 1 ): lowercase_ : Any = 1 if x[i - 1] == y[j - 1] else 0 lowercase_ : List[Any] = max(l[i - 1][j] , l[i][j - 1] , l[i - 1][j - 1] + match ) lowercase_ : List[str] = '''''' lowercase_ , lowercase_ : int = m, n while i > 0 and j > 0: lowercase_ : List[str] = 1 if x[i - 1] == y[j - 1] else 0 if l[i][j] == l[i - 1][j - 1] + match: if match == 1: lowercase_ : 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__": _lowercase : str = "AGGTAB" _lowercase : List[str] = "GXTXAYB" _lowercase : List[Any] = 4 _lowercase : Optional[Any] = "GTAB" _lowercase , _lowercase : int = longest_common_subsequence(a, b) print("len =", ln, ", sub-sequence =", subseq) import doctest doctest.testmod()
93
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices _lowercase : int = logging.get_logger(__name__) _lowercase : List[Any] = { "shi-labs/nat-mini-in1k-224": "https://huggingface.co/shi-labs/nat-mini-in1k-224/resolve/main/config.json", # See all Nat models at https://huggingface.co/models?filter=nat } class lowerCAmelCase__ ( lowerCamelCase_ , lowerCamelCase_ ): lowerCAmelCase_ = '''nat''' lowerCAmelCase_ = { '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self , __SCREAMING_SNAKE_CASE=4 , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=64 , __SCREAMING_SNAKE_CASE=[3, 4, 6, 5] , __SCREAMING_SNAKE_CASE=[2, 4, 8, 16] , __SCREAMING_SNAKE_CASE=7 , __SCREAMING_SNAKE_CASE=3.0 , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE="gelu" , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=1E-5 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = patch_size lowercase_ : List[Any] = num_channels lowercase_ : str = embed_dim lowercase_ : List[str] = depths lowercase_ : str = len(__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = num_heads lowercase_ : int = kernel_size lowercase_ : Union[str, Any] = mlp_ratio lowercase_ : Optional[int] = qkv_bias lowercase_ : List[Any] = hidden_dropout_prob lowercase_ : Optional[int] = attention_probs_dropout_prob lowercase_ : List[Any] = drop_path_rate lowercase_ : List[Any] = hidden_act lowercase_ : int = layer_norm_eps lowercase_ : int = initializer_range # we set the hidden_size attribute in order to make Nat work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model lowercase_ : Dict = int(embed_dim * 2 ** (len(__SCREAMING_SNAKE_CASE ) - 1) ) lowercase_ : Tuple = layer_scale_init_value lowercase_ : Union[str, Any] = ['''stem'''] + [F'''stage{idx}''' for idx in range(1 , len(__SCREAMING_SNAKE_CASE ) + 1 )] lowercase_ , lowercase_ : int = get_aligned_output_features_output_indices( out_features=__SCREAMING_SNAKE_CASE , out_indices=__SCREAMING_SNAKE_CASE , stage_names=self.stage_names )
93
1
'''simple docstring''' import json import logging import os import socket import git import numpy as np import torch logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - PID: %(process)d - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO, ) _lowercase : Optional[Any] = logging.getLogger(__name__) def snake_case_ ( __SCREAMING_SNAKE_CASE : str ): """simple docstring""" lowercase_ : Optional[int] = git.Repo(search_parent_directories=__SCREAMING_SNAKE_CASE ) lowercase_ : Any = { '''repo_id''': str(__SCREAMING_SNAKE_CASE ), '''repo_sha''': str(repo.head.object.hexsha ), '''repo_branch''': str(repo.active_branch ), } with open(os.path.join(__SCREAMING_SNAKE_CASE , '''git_log.json''' ) , '''w''' ) as f: json.dump(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , indent=4 ) def snake_case_ ( __SCREAMING_SNAKE_CASE : str ): """simple docstring""" if params.n_gpu <= 0: lowercase_ : Any = 0 lowercase_ : Any = -1 lowercase_ : str = True lowercase_ : List[str] = False return assert torch.cuda.is_available() logger.info('''Initializing GPUs''' ) if params.n_gpu > 1: assert params.local_rank != -1 lowercase_ : str = int(os.environ['''WORLD_SIZE'''] ) lowercase_ : Any = int(os.environ['''N_GPU_NODE'''] ) lowercase_ : int = int(os.environ['''RANK'''] ) # number of nodes / node ID lowercase_ : Tuple = params.world_size // params.n_gpu_per_node lowercase_ : Any = params.global_rank // params.n_gpu_per_node lowercase_ : Dict = True assert params.n_nodes == int(os.environ['''N_NODES'''] ) assert params.node_id == int(os.environ['''NODE_RANK'''] ) # local job (single GPU) else: assert params.local_rank == -1 lowercase_ : List[str] = 1 lowercase_ : Tuple = 0 lowercase_ : Optional[int] = 0 lowercase_ : Any = 0 lowercase_ : Optional[Any] = 1 lowercase_ : Union[str, Any] = 1 lowercase_ : Any = False # sanity checks assert params.n_nodes >= 1 assert 0 <= params.node_id < params.n_nodes assert 0 <= params.local_rank <= params.global_rank < params.world_size assert params.world_size == params.n_nodes * params.n_gpu_per_node # define whether this is the master process / if we are in multi-node distributed mode lowercase_ : str = params.node_id == 0 and params.local_rank == 0 lowercase_ : List[str] = params.n_nodes > 1 # summary lowercase_ : List[Any] = F'''--- Global rank: {params.global_rank} - ''' logger.info(PREFIX + '''Number of nodes: %i''' % params.n_nodes ) logger.info(PREFIX + '''Node ID : %i''' % params.node_id ) logger.info(PREFIX + '''Local rank : %i''' % params.local_rank ) logger.info(PREFIX + '''World size : %i''' % params.world_size ) logger.info(PREFIX + '''GPUs per node : %i''' % params.n_gpu_per_node ) logger.info(PREFIX + '''Master : %s''' % str(params.is_master ) ) logger.info(PREFIX + '''Multi-node : %s''' % str(params.multi_node ) ) logger.info(PREFIX + '''Multi-GPU : %s''' % str(params.multi_gpu ) ) logger.info(PREFIX + '''Hostname : %s''' % socket.gethostname() ) # set GPU device torch.cuda.set_device(params.local_rank ) # initialize multi-GPU if params.multi_gpu: logger.info('''Initializing PyTorch distributed''' ) torch.distributed.init_process_group( init_method='''env://''' , backend='''nccl''' , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : str ): """simple docstring""" np.random.seed(args.seed ) torch.manual_seed(args.seed ) if args.n_gpu > 0: torch.cuda.manual_seed_all(args.seed )
93
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _lowercase : Union[str, Any] = { "configuration_mask2former": [ "MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "Mask2FormerConfig", ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : Optional[int] = ["Mask2FormerImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : str = [ "MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "Mask2FormerForUniversalSegmentation", "Mask2FormerModel", "Mask2FormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_maskaformer import MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskaFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_maskaformer import MaskaFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskaformer import ( MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskaFormerForUniversalSegmentation, MaskaFormerModel, MaskaFormerPreTrainedModel, ) else: import sys _lowercase : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure)
93
1
'''simple docstring''' import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class lowerCAmelCase__ ( unittest.TestCase ): def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=13 , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=2_24 , __SCREAMING_SNAKE_CASE=30 , __SCREAMING_SNAKE_CASE=4_00 , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , __SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , ): """simple docstring""" lowercase_ : str = size if size is not None else {'''height''': 18, '''width''': 18} lowercase_ : Dict = parent lowercase_ : int = batch_size lowercase_ : Dict = num_channels lowercase_ : Optional[Any] = image_size lowercase_ : Union[str, Any] = min_resolution lowercase_ : List[Any] = max_resolution lowercase_ : Any = do_resize lowercase_ : Any = size lowercase_ : Union[str, Any] = do_normalize lowercase_ : Optional[int] = image_mean lowercase_ : List[str] = image_std def _snake_case ( self ): """simple docstring""" return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, } @require_torch @require_vision class lowerCAmelCase__ ( lowerCamelCase_ , unittest.TestCase ): lowerCAmelCase_ = ViTImageProcessor if is_vision_available() else None def _snake_case ( self ): """simple docstring""" lowercase_ : int = EfficientFormerImageProcessorTester(self ) @property def _snake_case ( self ): """simple docstring""" return self.image_proc_tester.prepare_image_processor_dict() def _snake_case ( self ): """simple docstring""" lowercase_ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , '''image_mean''' ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , '''image_std''' ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , '''do_normalize''' ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , '''do_resize''' ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , '''size''' ) ) def _snake_case ( self ): """simple docstring""" pass def _snake_case ( self ): """simple docstring""" lowercase_ : int = self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowercase_ : Optional[Any] = prepare_image_inputs(self.image_proc_tester , equal_resolution=__SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(__SCREAMING_SNAKE_CASE , Image.Image ) # Test not batched input lowercase_ : Dict = image_processor(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) # Test batched lowercase_ : Tuple = image_processor(__SCREAMING_SNAKE_CASE , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) def _snake_case ( self ): """simple docstring""" lowercase_ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors lowercase_ : Any = prepare_image_inputs(self.image_proc_tester , equal_resolution=__SCREAMING_SNAKE_CASE , numpify=__SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(__SCREAMING_SNAKE_CASE , np.ndarray ) # Test not batched input lowercase_ : Optional[Any] = image_processor(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) # Test batched lowercase_ : Optional[int] = image_processor(__SCREAMING_SNAKE_CASE , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) def _snake_case ( self ): """simple docstring""" lowercase_ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors lowercase_ : str = prepare_image_inputs(self.image_proc_tester , equal_resolution=__SCREAMING_SNAKE_CASE , torchify=__SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(__SCREAMING_SNAKE_CASE , torch.Tensor ) # Test not batched input lowercase_ : List[Any] = image_processor(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) # Test batched lowercase_ : int = image_processor(__SCREAMING_SNAKE_CASE , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , )
93
'''simple docstring''' import unittest from knapsack import greedy_knapsack as kp class lowerCAmelCase__ ( unittest.TestCase ): def _snake_case ( self ): """simple docstring""" lowercase_ : List[str] = [10, 20, 30, 40, 50, 60] lowercase_ : Optional[Any] = [2, 4, 6, 8, 10, 12] lowercase_ : Union[str, Any] = 1_00 self.assertEqual(kp.calc_profit(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) , 2_10 ) def _snake_case ( self ): """simple docstring""" self.assertRaisesRegex(__SCREAMING_SNAKE_CASE , '''max_weight must greater than zero.''' ) def _snake_case ( self ): """simple docstring""" self.assertRaisesRegex(__SCREAMING_SNAKE_CASE , '''Weight can not be negative.''' ) def _snake_case ( self ): """simple docstring""" self.assertRaisesRegex(__SCREAMING_SNAKE_CASE , '''Profit can not be negative.''' ) def _snake_case ( self ): """simple docstring""" self.assertRaisesRegex(__SCREAMING_SNAKE_CASE , '''max_weight must greater than zero.''' ) def _snake_case ( self ): """simple docstring""" self.assertRaisesRegex( __SCREAMING_SNAKE_CASE , '''The length of profit and weight must be same.''' ) if __name__ == "__main__": unittest.main()
93
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available _lowercase : Optional[int] = { "configuration_data2vec_audio": ["DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP", "Data2VecAudioConfig"], "configuration_data2vec_text": [ "DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP", "Data2VecTextConfig", "Data2VecTextOnnxConfig", ], "configuration_data2vec_vision": [ "DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP", "Data2VecVisionConfig", "Data2VecVisionOnnxConfig", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : Optional[int] = [ "DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST", "Data2VecAudioForAudioFrameClassification", "Data2VecAudioForCTC", "Data2VecAudioForSequenceClassification", "Data2VecAudioForXVector", "Data2VecAudioModel", "Data2VecAudioPreTrainedModel", ] _lowercase : Dict = [ "DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST", "Data2VecTextForCausalLM", "Data2VecTextForMaskedLM", "Data2VecTextForMultipleChoice", "Data2VecTextForQuestionAnswering", "Data2VecTextForSequenceClassification", "Data2VecTextForTokenClassification", "Data2VecTextModel", "Data2VecTextPreTrainedModel", ] _lowercase : List[Any] = [ "DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST", "Data2VecVisionForImageClassification", "Data2VecVisionForMaskedImageModeling", "Data2VecVisionForSemanticSegmentation", "Data2VecVisionModel", "Data2VecVisionPreTrainedModel", ] if is_tf_available(): _lowercase : Tuple = [ "TFData2VecVisionForImageClassification", "TFData2VecVisionForSemanticSegmentation", "TFData2VecVisionModel", "TFData2VecVisionPreTrainedModel", ] if TYPE_CHECKING: from .configuration_dataavec_audio import DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecAudioConfig from .configuration_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecTextConfig, DataaVecTextOnnxConfig, ) from .configuration_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecVisionConfig, DataaVecVisionOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_dataavec_audio import ( DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecAudioForAudioFrameClassification, DataaVecAudioForCTC, DataaVecAudioForSequenceClassification, DataaVecAudioForXVector, DataaVecAudioModel, DataaVecAudioPreTrainedModel, ) from .modeling_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecTextForCausalLM, DataaVecTextForMaskedLM, DataaVecTextForMultipleChoice, DataaVecTextForQuestionAnswering, DataaVecTextForSequenceClassification, DataaVecTextForTokenClassification, DataaVecTextModel, DataaVecTextPreTrainedModel, ) from .modeling_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecVisionForImageClassification, DataaVecVisionForMaskedImageModeling, DataaVecVisionForSemanticSegmentation, DataaVecVisionModel, DataaVecVisionPreTrainedModel, ) if is_tf_available(): from .modeling_tf_dataavec_vision import ( TFDataaVecVisionForImageClassification, TFDataaVecVisionForSemanticSegmentation, TFDataaVecVisionModel, TFDataaVecVisionPreTrainedModel, ) else: import sys _lowercase : Union[str, Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
93
'''simple docstring''' import argparse import copy def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[int] ): """simple docstring""" lowercase_ : List[Any] = {} with open(__SCREAMING_SNAKE_CASE ) as f: for line in f: if line.split()[0] not in dict_of_neighbours: lowercase_ : Union[str, Any] = [] _list.append([line.split()[1], line.split()[2]] ) lowercase_ : str = _list else: dict_of_neighbours[line.split()[0]].append( [line.split()[1], line.split()[2]] ) if line.split()[1] not in dict_of_neighbours: lowercase_ : Optional[int] = [] _list.append([line.split()[0], line.split()[2]] ) lowercase_ : Dict = _list else: dict_of_neighbours[line.split()[1]].append( [line.split()[0], line.split()[2]] ) return dict_of_neighbours def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE ) as f: lowercase_ : List[str] = f.read(1 ) lowercase_ : Optional[int] = start_node lowercase_ : Any = [] lowercase_ : List[str] = start_node lowercase_ : Optional[Any] = 0 while visiting not in first_solution: lowercase_ : Any = 10000 for k in dict_of_neighbours[visiting]: if int(k[1] ) < int(__SCREAMING_SNAKE_CASE ) and k[0] not in first_solution: lowercase_ : List[Any] = k[1] lowercase_ : List[Any] = k[0] first_solution.append(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = distance_of_first_solution + int(__SCREAMING_SNAKE_CASE ) lowercase_ : int = best_node first_solution.append(__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = 0 for k in dict_of_neighbours[first_solution[-2]]: if k[0] == start_node: break position += 1 lowercase_ : Optional[Any] = ( distance_of_first_solution + int(dict_of_neighbours[first_solution[-2]][position][1] ) - 10000 ) return first_solution, distance_of_first_solution def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" lowercase_ : Tuple = [] for n in solution[1:-1]: lowercase_ : List[str] = solution.index(__SCREAMING_SNAKE_CASE ) for kn in solution[1:-1]: lowercase_ : Any = solution.index(__SCREAMING_SNAKE_CASE ) if n == kn: continue lowercase_ : Dict = copy.deepcopy(__SCREAMING_SNAKE_CASE ) lowercase_ : Dict = kn lowercase_ : List[Any] = n lowercase_ : str = 0 for k in _tmp[:-1]: lowercase_ : Tuple = _tmp[_tmp.index(__SCREAMING_SNAKE_CASE ) + 1] for i in dict_of_neighbours[k]: if i[0] == next_node: lowercase_ : Optional[Any] = distance + int(i[1] ) _tmp.append(__SCREAMING_SNAKE_CASE ) if _tmp not in neighborhood_of_solution: neighborhood_of_solution.append(_tmp ) lowercase_ : Union[str, Any] = 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 snake_case_ ( __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" lowercase_ : Optional[int] = 1 lowercase_ : List[str] = first_solution lowercase_ : Dict = [] lowercase_ : List[str] = distance_of_first_solution lowercase_ : Optional[Any] = solution while count <= iters: lowercase_ : int = find_neighborhood(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : Any = 0 lowercase_ : Dict = neighborhood[index_of_best_solution] lowercase_ : Optional[Any] = len(__SCREAMING_SNAKE_CASE ) - 1 lowercase_ : Tuple = False while not found: lowercase_ : Optional[int] = 0 while i < len(__SCREAMING_SNAKE_CASE ): if best_solution[i] != solution[i]: lowercase_ : Tuple = best_solution[i] lowercase_ : Optional[int] = solution[i] break lowercase_ : 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] ) lowercase_ : Tuple = True lowercase_ : Optional[int] = best_solution[:-1] lowercase_ : Optional[Any] = neighborhood[index_of_best_solution][best_cost_index] if cost < best_cost: lowercase_ : Optional[Any] = cost lowercase_ : int = solution else: lowercase_ : Any = index_of_best_solution + 1 lowercase_ : Any = neighborhood[index_of_best_solution] if len(__SCREAMING_SNAKE_CASE ) >= size: tabu_list.pop(0 ) lowercase_ : List[Any] = count + 1 return best_solution_ever, best_cost def snake_case_ ( __SCREAMING_SNAKE_CASE : List[str]=None ): """simple docstring""" lowercase_ : Any = generate_neighbours(args.File ) lowercase_ , lowercase_ : Union[str, Any] = generate_first_solution( args.File , __SCREAMING_SNAKE_CASE ) lowercase_ , lowercase_ : Optional[int] = 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__": _lowercase : Any = 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())
93
1
'''simple docstring''' def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" if length <= 0 or not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): raise ValueError('''Length must be a positive integer.''' ) return [n * (2 * n - 1) for n in range(__SCREAMING_SNAKE_CASE )] if __name__ == "__main__": print(hexagonal_numbers(length=5)) print(hexagonal_numbers(length=1_0))
93
'''simple docstring''' import unittest from transformers import is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device if is_torch_available(): from transformers import AutoModelForSeqaSeqLM, AutoTokenizer @require_torch @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( unittest.TestCase ): @slow def _snake_case ( self ): """simple docstring""" lowercase_ : Dict = AutoModelForSeqaSeqLM.from_pretrained('''google/mt5-small''' , return_dict=__SCREAMING_SNAKE_CASE ).to(__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = AutoTokenizer.from_pretrained('''google/mt5-small''' ) lowercase_ : int = tokenizer('''Hello there''' , return_tensors='''pt''' ).input_ids lowercase_ : Union[str, Any] = tokenizer('''Hi I am''' , return_tensors='''pt''' ).input_ids lowercase_ : Union[str, Any] = model(input_ids.to(__SCREAMING_SNAKE_CASE ) , labels=labels.to(__SCREAMING_SNAKE_CASE ) ).loss lowercase_ : int = -(labels.shape[-1] * loss.item()) lowercase_ : Any = -84.9_127 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1E-4 )
93
1
'''simple docstring''' _lowercase : Dict = { "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", }
93
'''simple docstring''' def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : str ): """simple docstring""" lowercase_ : List[str] = len(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = [] for i in range(len(__SCREAMING_SNAKE_CASE ) - pat_len + 1 ): lowercase_ : Tuple = True for j in range(__SCREAMING_SNAKE_CASE ): if s[i + j] != pattern[j]: lowercase_ : List[str] = False break if match_found: position.append(__SCREAMING_SNAKE_CASE ) return position if __name__ == "__main__": assert naive_pattern_search("ABCDEFG", "DE") == [3] print(naive_pattern_search("ABAAABCDBBABCDDEBCABC", "ABC"))
93
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 _lowercase : Any = logging.get_logger(__name__) class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = ['''pixel_values'''] def __init__( self , __SCREAMING_SNAKE_CASE = True , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = PILImageResampling.BICUBIC , __SCREAMING_SNAKE_CASE = True , __SCREAMING_SNAKE_CASE = 1 / 2_55 , __SCREAMING_SNAKE_CASE = True , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = True , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) lowercase_ : str = size if size is not None else {'''height''': 3_84, '''width''': 3_84} lowercase_ : Union[str, Any] = get_size_dict(__SCREAMING_SNAKE_CASE , default_to_square=__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = do_resize lowercase_ : Dict = size lowercase_ : Optional[Any] = resample lowercase_ : Tuple = do_rescale lowercase_ : str = rescale_factor lowercase_ : Union[str, Any] = do_normalize lowercase_ : Dict = image_mean if image_mean is not None else OPENAI_CLIP_MEAN lowercase_ : Union[str, Any] = image_std if image_std is not None else OPENAI_CLIP_STD lowercase_ : Dict = do_convert_rgb def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = PILImageResampling.BICUBIC , __SCREAMING_SNAKE_CASE = None , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : List[str] = get_size_dict(__SCREAMING_SNAKE_CASE , default_to_square=__SCREAMING_SNAKE_CASE ) 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()}''' ) lowercase_ : Any = (size['''height'''], size['''width''']) return resize(__SCREAMING_SNAKE_CASE , size=__SCREAMING_SNAKE_CASE , resample=__SCREAMING_SNAKE_CASE , data_format=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" return rescale(__SCREAMING_SNAKE_CASE , scale=__SCREAMING_SNAKE_CASE , data_format=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" return normalize(__SCREAMING_SNAKE_CASE , mean=__SCREAMING_SNAKE_CASE , std=__SCREAMING_SNAKE_CASE , data_format=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = ChannelDimension.FIRST , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : List[Any] = do_resize if do_resize is not None else self.do_resize lowercase_ : Dict = resample if resample is not None else self.resample lowercase_ : List[str] = do_rescale if do_rescale is not None else self.do_rescale lowercase_ : Dict = rescale_factor if rescale_factor is not None else self.rescale_factor lowercase_ : str = do_normalize if do_normalize is not None else self.do_normalize lowercase_ : Union[str, Any] = image_mean if image_mean is not None else self.image_mean lowercase_ : List[Any] = image_std if image_std is not None else self.image_std lowercase_ : Optional[Any] = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb lowercase_ : List[Any] = size if size is not None else self.size lowercase_ : Dict = get_size_dict(__SCREAMING_SNAKE_CASE , default_to_square=__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = make_list_of_images(__SCREAMING_SNAKE_CASE ) if not valid_images(__SCREAMING_SNAKE_CASE ): 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: lowercase_ : int = [convert_to_rgb(__SCREAMING_SNAKE_CASE ) for image in images] # All transformations expect numpy arrays. lowercase_ : Union[str, Any] = [to_numpy_array(__SCREAMING_SNAKE_CASE ) for image in images] if do_resize: lowercase_ : List[Any] = [self.resize(image=__SCREAMING_SNAKE_CASE , size=__SCREAMING_SNAKE_CASE , resample=__SCREAMING_SNAKE_CASE ) for image in images] if do_rescale: lowercase_ : Any = [self.rescale(image=__SCREAMING_SNAKE_CASE , scale=__SCREAMING_SNAKE_CASE ) for image in images] if do_normalize: lowercase_ : str = [self.normalize(image=__SCREAMING_SNAKE_CASE , mean=__SCREAMING_SNAKE_CASE , std=__SCREAMING_SNAKE_CASE ) for image in images] lowercase_ : List[str] = [to_channel_dimension_format(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) for image in images] lowercase_ : Dict = BatchFeature(data={'''pixel_values''': images} , tensor_type=__SCREAMING_SNAKE_CASE ) return encoded_outputs
93
'''simple docstring''' import importlib import inspect import json import os import re import shutil import sys from pathlib import Path from typing import Dict, Optional, Union from urllib import request from huggingface_hub import HfFolder, cached_download, hf_hub_download, model_info from packaging import version from .. import __version__ from . import DIFFUSERS_DYNAMIC_MODULE_NAME, HF_MODULES_CACHE, logging _lowercase : Optional[Any] = ( "https://raw.githubusercontent.com/huggingface/diffusers/{revision}/examples/community/{pipeline}.py" ) _lowercase : Tuple = logging.get_logger(__name__) # pylint: disable=invalid-name def snake_case_ ( ): """simple docstring""" lowercase_ : Tuple = '''https://pypi.org/pypi/diffusers/json''' lowercase_ : Tuple = json.loads(request.urlopen(__SCREAMING_SNAKE_CASE ).read() )['''releases'''].keys() return sorted(__SCREAMING_SNAKE_CASE , key=lambda __SCREAMING_SNAKE_CASE : version.Version(__SCREAMING_SNAKE_CASE ) ) def snake_case_ ( ): """simple docstring""" if HF_MODULES_CACHE in sys.path: return sys.path.append(__SCREAMING_SNAKE_CASE ) os.makedirs(__SCREAMING_SNAKE_CASE , exist_ok=__SCREAMING_SNAKE_CASE ) lowercase_ : List[Any] = Path(__SCREAMING_SNAKE_CASE ) / '''__init__.py''' if not init_path.exists(): init_path.touch() def snake_case_ ( __SCREAMING_SNAKE_CASE : Union[str, os.PathLike] ): """simple docstring""" init_hf_modules() lowercase_ : Optional[int] = Path(__SCREAMING_SNAKE_CASE ) / name # If the parent module does not exist yet, recursively create it. if not dynamic_module_path.parent.exists(): create_dynamic_module(dynamic_module_path.parent ) os.makedirs(__SCREAMING_SNAKE_CASE , exist_ok=__SCREAMING_SNAKE_CASE ) lowercase_ : str = dynamic_module_path / '''__init__.py''' if not init_path.exists(): init_path.touch() def snake_case_ ( __SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE , '''r''' , encoding='''utf-8''' ) as f: lowercase_ : int = f.read() # Imports of the form `import .xxx` lowercase_ : List[Any] = re.findall('''^\s*import\s+\.(\S+)\s*$''' , __SCREAMING_SNAKE_CASE , flags=re.MULTILINE ) # Imports of the form `from .xxx import yyy` relative_imports += re.findall('''^\s*from\s+\.(\S+)\s+import''' , __SCREAMING_SNAKE_CASE , flags=re.MULTILINE ) # Unique-ify return list(set(__SCREAMING_SNAKE_CASE ) ) def snake_case_ ( __SCREAMING_SNAKE_CASE : str ): """simple docstring""" lowercase_ : int = False lowercase_ : Any = [module_file] lowercase_ : Dict = [] # Let's recurse through all relative imports while not no_change: lowercase_ : Dict = [] for f in files_to_check: new_imports.extend(get_relative_imports(__SCREAMING_SNAKE_CASE ) ) lowercase_ : Union[str, Any] = Path(__SCREAMING_SNAKE_CASE ).parent lowercase_ : Optional[int] = [str(module_path / m ) for m in new_imports] lowercase_ : str = [f for f in new_import_files if f not in all_relative_imports] lowercase_ : int = [F'''{f}.py''' for f in new_import_files] lowercase_ : Optional[Any] = len(__SCREAMING_SNAKE_CASE ) == 0 all_relative_imports.extend(__SCREAMING_SNAKE_CASE ) return all_relative_imports def snake_case_ ( __SCREAMING_SNAKE_CASE : Any ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE , '''r''' , encoding='''utf-8''' ) as f: lowercase_ : Union[str, Any] = f.read() # Imports of the form `import xxx` lowercase_ : Any = re.findall('''^\s*import\s+(\S+)\s*$''' , __SCREAMING_SNAKE_CASE , flags=re.MULTILINE ) # Imports of the form `from xxx import yyy` imports += re.findall('''^\s*from\s+(\S+)\s+import''' , __SCREAMING_SNAKE_CASE , flags=re.MULTILINE ) # Only keep the top-level module lowercase_ : List[str] = [imp.split('''.''' )[0] for imp in imports if not imp.startswith('''.''' )] # Unique-ify and test we got them all lowercase_ : Any = list(set(__SCREAMING_SNAKE_CASE ) ) lowercase_ : Optional[Any] = [] for imp in imports: try: importlib.import_module(__SCREAMING_SNAKE_CASE ) except ImportError: missing_packages.append(__SCREAMING_SNAKE_CASE ) if len(__SCREAMING_SNAKE_CASE ) > 0: raise ImportError( '''This modeling file requires the following packages that were not found in your environment: ''' F'''{', '.join(__SCREAMING_SNAKE_CASE )}. Run `pip install {' '.join(__SCREAMING_SNAKE_CASE )}`''' ) return get_relative_imports(__SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" lowercase_ : List[Any] = module_path.replace(os.path.sep , '''.''' ) lowercase_ : Any = importlib.import_module(__SCREAMING_SNAKE_CASE ) if class_name is None: return find_pipeline_class(__SCREAMING_SNAKE_CASE ) return getattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" from ..pipelines import DiffusionPipeline lowercase_ : int = dict(inspect.getmembers(__SCREAMING_SNAKE_CASE , inspect.isclass ) ) lowercase_ : Optional[Any] = None for cls_name, cls in cls_members.items(): if ( cls_name != DiffusionPipeline.__name__ and issubclass(cls , __SCREAMING_SNAKE_CASE ) and cls.__module__.split('''.''' )[0] != "diffusers" ): if pipeline_class is not None: raise ValueError( F'''Multiple classes that inherit from {DiffusionPipeline.__name__} have been found:''' F''' {pipeline_class.__name__}, and {cls_name}. Please make sure to define only one in''' F''' {loaded_module}.''' ) lowercase_ : List[Any] = cls return pipeline_class def snake_case_ ( __SCREAMING_SNAKE_CASE : Union[str, os.PathLike] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Optional[Union[str, os.PathLike]] = None , __SCREAMING_SNAKE_CASE : bool = False , __SCREAMING_SNAKE_CASE : bool = False , __SCREAMING_SNAKE_CASE : Optional[Dict[str, str]] = None , __SCREAMING_SNAKE_CASE : Optional[Union[bool, str]] = None , __SCREAMING_SNAKE_CASE : Optional[str] = None , __SCREAMING_SNAKE_CASE : bool = False , ): """simple docstring""" lowercase_ : Dict = str(__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if os.path.isfile(__SCREAMING_SNAKE_CASE ): lowercase_ : Dict = module_file_or_url lowercase_ : int = '''local''' elif pretrained_model_name_or_path.count('''/''' ) == 0: lowercase_ : Optional[int] = get_diffusers_versions() # cut ".dev0" lowercase_ : List[Any] = '''v''' + '''.'''.join(__version__.split('''.''' )[:3] ) # retrieve github version that matches if revision is None: lowercase_ : List[str] = latest_version if latest_version[1:] in available_versions else '''main''' logger.info(F'''Defaulting to latest_version: {revision}.''' ) elif revision in available_versions: lowercase_ : List[str] = F'''v{revision}''' elif revision == "main": lowercase_ : Optional[Any] = revision else: raise ValueError( F'''`custom_revision`: {revision} does not exist. Please make sure to choose one of''' F''' {', '.join(available_versions + ['main'] )}.''' ) # community pipeline on GitHub lowercase_ : Tuple = COMMUNITY_PIPELINES_URL.format(revision=__SCREAMING_SNAKE_CASE , pipeline=__SCREAMING_SNAKE_CASE ) try: lowercase_ : Optional[Any] = cached_download( __SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE , force_download=__SCREAMING_SNAKE_CASE , proxies=__SCREAMING_SNAKE_CASE , resume_download=__SCREAMING_SNAKE_CASE , local_files_only=__SCREAMING_SNAKE_CASE , use_auth_token=__SCREAMING_SNAKE_CASE , ) lowercase_ : Tuple = '''git''' lowercase_ : Tuple = pretrained_model_name_or_path + '''.py''' except EnvironmentError: logger.error(F'''Could not locate the {module_file} inside {pretrained_model_name_or_path}.''' ) raise else: try: # Load from URL or cache if already cached lowercase_ : str = hf_hub_download( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE , force_download=__SCREAMING_SNAKE_CASE , proxies=__SCREAMING_SNAKE_CASE , resume_download=__SCREAMING_SNAKE_CASE , local_files_only=__SCREAMING_SNAKE_CASE , use_auth_token=__SCREAMING_SNAKE_CASE , ) lowercase_ : Optional[Any] = os.path.join('''local''' , '''--'''.join(pretrained_model_name_or_path.split('''/''' ) ) ) except EnvironmentError: logger.error(F'''Could not locate the {module_file} inside {pretrained_model_name_or_path}.''' ) raise # Check we have all the requirements in our environment lowercase_ : Tuple = check_imports(__SCREAMING_SNAKE_CASE ) # Now we move the module inside our cached dynamic modules. lowercase_ : str = DIFFUSERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule create_dynamic_module(__SCREAMING_SNAKE_CASE ) lowercase_ : Any = Path(__SCREAMING_SNAKE_CASE ) / full_submodule if submodule == "local" or submodule == "git": # We always copy local files (we could hash the file to see if there was a change, and give them the name of # that hash, to only copy when there is a modification but it seems overkill for now). # The only reason we do the copy is to avoid putting too many folders in sys.path. shutil.copy(__SCREAMING_SNAKE_CASE , submodule_path / module_file ) for module_needed in modules_needed: lowercase_ : Union[str, Any] = F'''{module_needed}.py''' shutil.copy(os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) , submodule_path / module_needed ) else: # Get the commit hash # TODO: we will get this info in the etag soon, so retrieve it from there and not here. if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase_ : Tuple = use_auth_token elif use_auth_token is True: lowercase_ : List[Any] = HfFolder.get_token() else: lowercase_ : Optional[Any] = None lowercase_ : Optional[int] = model_info(__SCREAMING_SNAKE_CASE , revision=__SCREAMING_SNAKE_CASE , token=__SCREAMING_SNAKE_CASE ).sha # The module file will end up being placed in a subfolder with the git hash of the repo. This way we get the # benefit of versioning. lowercase_ : int = submodule_path / commit_hash lowercase_ : Tuple = full_submodule + os.path.sep + commit_hash create_dynamic_module(__SCREAMING_SNAKE_CASE ) if not (submodule_path / module_file).exists(): shutil.copy(__SCREAMING_SNAKE_CASE , submodule_path / module_file ) # Make sure we also have every file with relative for module_needed in modules_needed: if not (submodule_path / module_needed).exists(): get_cached_module_file( __SCREAMING_SNAKE_CASE , F'''{module_needed}.py''' , cache_dir=__SCREAMING_SNAKE_CASE , force_download=__SCREAMING_SNAKE_CASE , resume_download=__SCREAMING_SNAKE_CASE , proxies=__SCREAMING_SNAKE_CASE , use_auth_token=__SCREAMING_SNAKE_CASE , revision=__SCREAMING_SNAKE_CASE , local_files_only=__SCREAMING_SNAKE_CASE , ) return os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Union[str, os.PathLike] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Optional[str] = None , __SCREAMING_SNAKE_CASE : Optional[Union[str, os.PathLike]] = None , __SCREAMING_SNAKE_CASE : bool = False , __SCREAMING_SNAKE_CASE : bool = False , __SCREAMING_SNAKE_CASE : Optional[Dict[str, str]] = None , __SCREAMING_SNAKE_CASE : Optional[Union[bool, str]] = None , __SCREAMING_SNAKE_CASE : Optional[str] = None , __SCREAMING_SNAKE_CASE : bool = False , **__SCREAMING_SNAKE_CASE : Optional[Any] , ): """simple docstring""" lowercase_ : Optional[Any] = get_cached_module_file( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE , force_download=__SCREAMING_SNAKE_CASE , resume_download=__SCREAMING_SNAKE_CASE , proxies=__SCREAMING_SNAKE_CASE , use_auth_token=__SCREAMING_SNAKE_CASE , revision=__SCREAMING_SNAKE_CASE , local_files_only=__SCREAMING_SNAKE_CASE , ) return get_class_in_module(__SCREAMING_SNAKE_CASE , final_module.replace('''.py''' , '''''' ) )
93
1
'''simple docstring''' import hashlib import unittest from typing import Dict import numpy as np from transformers import ( MODEL_FOR_MASK_GENERATION_MAPPING, TF_MODEL_FOR_MASK_GENERATION_MAPPING, is_vision_available, pipeline, ) from transformers.pipelines import MaskGenerationPipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) if is_vision_available(): from PIL import Image else: class lowerCAmelCase__ : @staticmethod def _snake_case ( *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" pass def snake_case_ ( __SCREAMING_SNAKE_CASE : Image ): """simple docstring""" lowercase_ : List[Any] = hashlib.mda(image.tobytes() ) return m.hexdigest()[:10] def snake_case_ ( __SCREAMING_SNAKE_CASE : Image ): """simple docstring""" lowercase_ : Optional[int] = np.array(__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = npimg.shape return {"hash": hashimage(__SCREAMING_SNAKE_CASE ), "shape": shape} @is_pipeline_test @require_vision @require_torch class lowerCAmelCase__ ( unittest.TestCase ): lowerCAmelCase_ = dict( (list(MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if MODEL_FOR_MASK_GENERATION_MAPPING else []) ) lowerCAmelCase_ = dict( (list(TF_MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if TF_MODEL_FOR_MASK_GENERATION_MAPPING else []) ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : str = MaskGenerationPipeline(model=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) return image_segmenter, [ "./tests/fixtures/tests_samples/COCO/000000039769.png", "./tests/fixtures/tests_samples/COCO/000000039769.png", ] def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" pass @require_tf @unittest.skip('''Image segmentation not implemented in TF''' ) def _snake_case ( self ): """simple docstring""" pass @slow @require_torch def _snake_case ( self ): """simple docstring""" lowercase_ : Dict = pipeline('''mask-generation''' , model='''facebook/sam-vit-huge''' ) lowercase_ : str = image_segmenter('''http://images.cocodataset.org/val2017/000000039769.jpg''' , points_per_batch=2_56 ) # Shortening by hashing lowercase_ : Union[str, Any] = [] for i, o in enumerate(outputs['''masks'''] ): new_outupt += [{"mask": mask_to_test_readable(__SCREAMING_SNAKE_CASE ), "scores": outputs["scores"][i]}] # fmt: off self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {'''mask''': {'''hash''': '''115ad19f5f''', '''shape''': (4_80, 6_40)}, '''scores''': 1.0_444}, {'''mask''': {'''hash''': '''6affa964c6''', '''shape''': (4_80, 6_40)}, '''scores''': 1.021}, {'''mask''': {'''hash''': '''dfe28a0388''', '''shape''': (4_80, 6_40)}, '''scores''': 1.0_167}, {'''mask''': {'''hash''': '''c0a5f4a318''', '''shape''': (4_80, 6_40)}, '''scores''': 1.0_132}, {'''mask''': {'''hash''': '''fe8065c197''', '''shape''': (4_80, 6_40)}, '''scores''': 1.0_053}, {'''mask''': {'''hash''': '''e2d0b7a0b7''', '''shape''': (4_80, 6_40)}, '''scores''': 0.9_967}, {'''mask''': {'''hash''': '''453c7844bd''', '''shape''': (4_80, 6_40)}, '''scores''': 0.993}, {'''mask''': {'''hash''': '''3d44f2926d''', '''shape''': (4_80, 6_40)}, '''scores''': 0.9_909}, {'''mask''': {'''hash''': '''64033ddc3f''', '''shape''': (4_80, 6_40)}, '''scores''': 0.9_879}, {'''mask''': {'''hash''': '''801064ff79''', '''shape''': (4_80, 6_40)}, '''scores''': 0.9_834}, {'''mask''': {'''hash''': '''6172f276ef''', '''shape''': (4_80, 6_40)}, '''scores''': 0.9_716}, {'''mask''': {'''hash''': '''b49e60e084''', '''shape''': (4_80, 6_40)}, '''scores''': 0.9_612}, {'''mask''': {'''hash''': '''a811e775fd''', '''shape''': (4_80, 6_40)}, '''scores''': 0.9_599}, {'''mask''': {'''hash''': '''a6a8ebcf4b''', '''shape''': (4_80, 6_40)}, '''scores''': 0.9_552}, {'''mask''': {'''hash''': '''9d8257e080''', '''shape''': (4_80, 6_40)}, '''scores''': 0.9_532}, {'''mask''': {'''hash''': '''32de6454a8''', '''shape''': (4_80, 6_40)}, '''scores''': 0.9_516}, {'''mask''': {'''hash''': '''af3d4af2c8''', '''shape''': (4_80, 6_40)}, '''scores''': 0.9_499}, {'''mask''': {'''hash''': '''3c6db475fb''', '''shape''': (4_80, 6_40)}, '''scores''': 0.9_483}, {'''mask''': {'''hash''': '''c290813fb9''', '''shape''': (4_80, 6_40)}, '''scores''': 0.9_464}, {'''mask''': {'''hash''': '''b6f0b8f606''', '''shape''': (4_80, 6_40)}, '''scores''': 0.943}, {'''mask''': {'''hash''': '''92ce16bfdf''', '''shape''': (4_80, 6_40)}, '''scores''': 0.943}, {'''mask''': {'''hash''': '''c749b25868''', '''shape''': (4_80, 6_40)}, '''scores''': 0.9_408}, {'''mask''': {'''hash''': '''efb6cab859''', '''shape''': (4_80, 6_40)}, '''scores''': 0.9_335}, {'''mask''': {'''hash''': '''1ff2eafb30''', '''shape''': (4_80, 6_40)}, '''scores''': 0.9_326}, {'''mask''': {'''hash''': '''788b798e24''', '''shape''': (4_80, 6_40)}, '''scores''': 0.9_262}, {'''mask''': {'''hash''': '''abea804f0e''', '''shape''': (4_80, 6_40)}, '''scores''': 0.8_999}, {'''mask''': {'''hash''': '''7b9e8ddb73''', '''shape''': (4_80, 6_40)}, '''scores''': 0.8_986}, {'''mask''': {'''hash''': '''cd24047c8a''', '''shape''': (4_80, 6_40)}, '''scores''': 0.8_984}, {'''mask''': {'''hash''': '''6943e6bcbd''', '''shape''': (4_80, 6_40)}, '''scores''': 0.8_873}, {'''mask''': {'''hash''': '''b5f47c9191''', '''shape''': (4_80, 6_40)}, '''scores''': 0.8_871} ] , ) # fmt: on @require_torch @slow def _snake_case ( self ): """simple docstring""" lowercase_ : str = '''facebook/sam-vit-huge''' lowercase_ : Dict = pipeline('''mask-generation''' , model=__SCREAMING_SNAKE_CASE ) lowercase_ : Any = image_segmenter( '''http://images.cocodataset.org/val2017/000000039769.jpg''' , pred_iou_thresh=1 , points_per_batch=2_56 ) # Shortening by hashing lowercase_ : List[str] = [] for i, o in enumerate(outputs['''masks'''] ): new_outupt += [{"mask": mask_to_test_readable(__SCREAMING_SNAKE_CASE ), "scores": outputs["scores"][i]}] self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {'''mask''': {'''hash''': '''115ad19f5f''', '''shape''': (4_80, 6_40)}, '''scores''': 1.0_444}, {'''mask''': {'''hash''': '''6affa964c6''', '''shape''': (4_80, 6_40)}, '''scores''': 1.0_210}, {'''mask''': {'''hash''': '''dfe28a0388''', '''shape''': (4_80, 6_40)}, '''scores''': 1.0_167}, {'''mask''': {'''hash''': '''c0a5f4a318''', '''shape''': (4_80, 6_40)}, '''scores''': 1.0_132}, {'''mask''': {'''hash''': '''fe8065c197''', '''shape''': (4_80, 6_40)}, '''scores''': 1.0_053}, ] , )
93
'''simple docstring''' import re import tempfile from pathlib import Path import pytest import yaml from datasets.utils.readme import ReadMe # @pytest.fixture # def example_yaml_structure(): _lowercase : Union[str, Any] = yaml.safe_load( "\\nname: \"\"\nallow_empty: false\nallow_empty_text: true\nsubsections:\n - name: \"Dataset Card for X\" # First-level markdown heading\n allow_empty: false\n allow_empty_text: true\n subsections:\n - name: \"Table of Contents\"\n allow_empty: false\n allow_empty_text: false\n subsections: null\n - name: \"Dataset Description\"\n allow_empty: false\n allow_empty_text: false\n subsections:\n - name: \"Dataset Summary\"\n allow_empty: false\n allow_empty_text: false\n subsections: null\n - name: \"Supported Tasks and Leaderboards\"\n allow_empty: true\n allow_empty_text: true\n subsections: null\n - name: Languages\n allow_empty: false\n allow_empty_text: true\n subsections: null\n" ) _lowercase : int = { "name": "root", "text": "", "is_empty_text": True, "subsections": [ { "name": "Dataset Card for My Dataset", "text": "", "is_empty_text": True, "subsections": [ {"name": "Table of Contents", "text": "Some text here.", "is_empty_text": False, "subsections": []}, { "name": "Dataset Description", "text": "Some text here.", "is_empty_text": False, "subsections": [ { "name": "Dataset Summary", "text": "Some text here.", "is_empty_text": False, "subsections": [], }, { "name": "Supported Tasks and Leaderboards", "text": "", "is_empty_text": True, "subsections": [], }, {"name": "Languages", "text": "Language Text", "is_empty_text": False, "subsections": []}, ], }, ], } ], } _lowercase : Optional[Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Union[str, Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n#### Extra Ignored Subsection\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Any = { "name": "root", "text": "", "is_empty_text": True, "subsections": [ { "name": "Dataset Card for My Dataset", "text": "", "is_empty_text": True, "subsections": [ {"name": "Table of Contents", "text": "Some text here.", "is_empty_text": False, "subsections": []}, { "name": "Dataset Description", "text": "Some text here.", "is_empty_text": False, "subsections": [ { "name": "Dataset Summary", "text": "Some text here.", "is_empty_text": False, "subsections": [ { "name": "Extra Ignored Subsection", "text": "", "is_empty_text": True, "subsections": [], } ], }, { "name": "Supported Tasks and Leaderboards", "text": "", "is_empty_text": True, "subsections": [], }, {"name": "Languages", "text": "Language Text", "is_empty_text": False, "subsections": []}, ], }, ], } ], } _lowercase : str = "\\n---\n---\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : List[str] = ( "The following issues were found for the README at `{path}`:\n-\tEmpty YAML markers are present in the README." ) _lowercase : Tuple = "\\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Optional[Any] = ( "The following issues were found for the README at `{path}`:\n-\tNo YAML markers are present in the README." ) _lowercase : Tuple = "\\n---\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Optional[int] = "The following issues were found for the README at `{path}`:\n-\tOnly the start of YAML tags present in the README." _lowercase : List[Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Optional[Any] = "The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Summary` but it is empty.\n-\tExpected some text in section `Dataset Summary` but it is empty (text in subsections are ignored)." _lowercase : Optional[int] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n" _lowercase : Union[str, Any] = "The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Card for My Dataset` but it is empty.\n-\tSection `Dataset Card for My Dataset` expected the following subsections: `Table of Contents`, `Dataset Description`. Found 'None'." _lowercase : Union[str, Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Languages\nLanguage Text\n" _lowercase : int = "The following issues were found for the README at `{path}`:\n-\tSection `Dataset Description` is missing subsection: `Supported Tasks and Leaderboards`." _lowercase : List[Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\n" _lowercase : int = "The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Languages` but it is empty." _lowercase : List[str] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : str = "The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README." _lowercase : Dict = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n# Dataset Card My Dataset\n" _lowercase : List[str] = "The following issues were found for the README at `{path}`:\n-\tThe README has several first-level headings: `Dataset Card for My Dataset`, `Dataset Card My Dataset`. Only one heading is expected. Skipping further validation for this README." _lowercase : str = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Union[str, Any] = "The following issues were found for the README at `{path}`:\n-\tNo first-level heading starting with `Dataset Card for` found in README. Skipping further validation for this README." _lowercase : List[Any] = "" _lowercase : Optional[Any] = "The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README.\n-\tNo YAML markers are present in the README." _lowercase : List[Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Optional[Any] = "The following issues were found while parsing the README at `{path}`:\n-\tMultiple sections with the same heading `Dataset Card for My Dataset` have been found. Please keep only one of these sections." @pytest.mark.parametrize( '''readme_md, expected_dict''' , [ (README_CORRECT, CORRECT_DICT), (README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" assert ReadMe.from_string(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).to_dict() == expected_dict @pytest.mark.parametrize( '''readme_md, expected_error''' , [ (README_NO_YAML, EXPECTED_ERROR_README_NO_YAML), (README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML), (README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML), (README_EMPTY, EXPECTED_ERROR_README_EMPTY), (README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION), (README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL), (README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION), (README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT), (README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL), (README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL), (README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" with pytest.raises(__SCREAMING_SNAKE_CASE , match=re.escape(expected_error.format(path='''root''' ) ) ): lowercase_ : Optional[int] = ReadMe.from_string(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) readme.validate() @pytest.mark.parametrize( '''readme_md, expected_error''' , [ (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" with pytest.raises(__SCREAMING_SNAKE_CASE , match=re.escape(expected_error.format(path='''root''' ) ) ): ReadMe.from_string(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( '''readme_md,''' , [ (README_MULTIPLE_SAME_HEADING_1), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Any ): """simple docstring""" ReadMe.from_string(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , suppress_parsing_errors=__SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( '''readme_md, expected_dict''' , [ (README_CORRECT, CORRECT_DICT), (README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : str ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: lowercase_ : Optional[int] = Path(__SCREAMING_SNAKE_CASE ) / '''README.md''' with open(__SCREAMING_SNAKE_CASE , '''w+''' ) as readme_file: readme_file.write(__SCREAMING_SNAKE_CASE ) lowercase_ : Any = ReadMe.from_readme(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).to_dict() assert out["name"] == path assert out["text"] == "" assert out["is_empty_text"] assert out["subsections"] == expected_dict["subsections"] @pytest.mark.parametrize( '''readme_md, expected_error''' , [ (README_NO_YAML, EXPECTED_ERROR_README_NO_YAML), (README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML), (README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML), (README_EMPTY, EXPECTED_ERROR_README_EMPTY), (README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION), (README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL), (README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION), (README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT), (README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL), (README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL), (README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: lowercase_ : str = Path(__SCREAMING_SNAKE_CASE ) / '''README.md''' with open(__SCREAMING_SNAKE_CASE , '''w+''' ) as readme_file: readme_file.write(__SCREAMING_SNAKE_CASE ) lowercase_ : List[str] = expected_error.format(path=__SCREAMING_SNAKE_CASE ) with pytest.raises(__SCREAMING_SNAKE_CASE , match=re.escape(__SCREAMING_SNAKE_CASE ) ): lowercase_ : int = ReadMe.from_readme(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) readme.validate() @pytest.mark.parametrize( '''readme_md, expected_error''' , [ (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: lowercase_ : Dict = Path(__SCREAMING_SNAKE_CASE ) / '''README.md''' with open(__SCREAMING_SNAKE_CASE , '''w+''' ) as readme_file: readme_file.write(__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = expected_error.format(path=__SCREAMING_SNAKE_CASE ) with pytest.raises(__SCREAMING_SNAKE_CASE , match=re.escape(__SCREAMING_SNAKE_CASE ) ): ReadMe.from_readme(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( '''readme_md,''' , [ (README_MULTIPLE_SAME_HEADING_1), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: lowercase_ : Optional[int] = Path(__SCREAMING_SNAKE_CASE ) / '''README.md''' with open(__SCREAMING_SNAKE_CASE , '''w+''' ) as readme_file: readme_file.write(__SCREAMING_SNAKE_CASE ) ReadMe.from_readme(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , suppress_parsing_errors=__SCREAMING_SNAKE_CASE )
93
1
'''simple docstring''' import json import os from pathlib import Path from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple, Union import sentencepiece from ...tokenization_utils import BatchEncoding, PreTrainedTokenizer from ...utils import logging _lowercase : List[Any] = logging.get_logger(__name__) _lowercase : List[Any] = "▁" _lowercase : Tuple = { "vocab_file": "vocab.json", "spm_file": "sentencepiece.bpe.model", "tokenizer_config_file": "tokenizer_config.json", } _lowercase : List[str] = { "vocab_file": { "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/vocab.json", "facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/vocab.json", }, "spm_file": { "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/sentencepiece.bpe.model", "facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/sentencepiece.bpe.model", }, "tokenizer_config_file": { "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/tokenizer_config.json", "facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/tokenizer_config.json", }, } _lowercase : List[str] = { "facebook/m2m100_418M": 1_0_2_4, } # fmt: off _lowercase : Tuple = { "m2m100": ["af", "am", "ar", "ast", "az", "ba", "be", "bg", "bn", "br", "bs", "ca", "ceb", "cs", "cy", "da", "de", "el", "en", "es", "et", "fa", "ff", "fi", "fr", "fy", "ga", "gd", "gl", "gu", "ha", "he", "hi", "hr", "ht", "hu", "hy", "id", "ig", "ilo", "is", "it", "ja", "jv", "ka", "kk", "km", "kn", "ko", "lb", "lg", "ln", "lo", "lt", "lv", "mg", "mk", "ml", "mn", "mr", "ms", "my", "ne", "nl", "no", "ns", "oc", "or", "pa", "pl", "ps", "pt", "ro", "ru", "sd", "si", "sk", "sl", "so", "sq", "sr", "ss", "su", "sv", "sw", "ta", "th", "tl", "tn", "tr", "uk", "ur", "uz", "vi", "wo", "xh", "yi", "yo", "zh", "zu"], "wmt21": ["en", "ha", "is", "ja", "cs", "ru", "zh", "de"] } class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = VOCAB_FILES_NAMES lowerCAmelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase_ = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase_ = ['''input_ids''', '''attention_mask'''] lowerCAmelCase_ = [] lowerCAmelCase_ = [] def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE="<s>" , __SCREAMING_SNAKE_CASE="</s>" , __SCREAMING_SNAKE_CASE="</s>" , __SCREAMING_SNAKE_CASE="<pad>" , __SCREAMING_SNAKE_CASE="<unk>" , __SCREAMING_SNAKE_CASE="m2m100" , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE=8 , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : Optional[Any] = {} if sp_model_kwargs is None else sp_model_kwargs lowercase_ : List[Any] = language_codes lowercase_ : Optional[int] = FAIRSEQ_LANGUAGE_CODES[language_codes] lowercase_ : List[Any] = {lang_code: F'''__{lang_code}__''' for lang_code in fairseq_language_code} lowercase_ : Union[str, Any] = kwargs.get('''additional_special_tokens''' , [] ) kwargs["additional_special_tokens"] += [ self.get_lang_token(__SCREAMING_SNAKE_CASE ) for lang_code in fairseq_language_code if self.get_lang_token(__SCREAMING_SNAKE_CASE ) not in kwargs["additional_special_tokens"] ] super().__init__( src_lang=__SCREAMING_SNAKE_CASE , tgt_lang=__SCREAMING_SNAKE_CASE , bos_token=__SCREAMING_SNAKE_CASE , eos_token=__SCREAMING_SNAKE_CASE , sep_token=__SCREAMING_SNAKE_CASE , unk_token=__SCREAMING_SNAKE_CASE , pad_token=__SCREAMING_SNAKE_CASE , language_codes=__SCREAMING_SNAKE_CASE , sp_model_kwargs=self.sp_model_kwargs , num_madeup_words=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) lowercase_ : int = vocab_file lowercase_ : Any = load_json(__SCREAMING_SNAKE_CASE ) lowercase_ : str = {v: k for k, v in self.encoder.items()} lowercase_ : Optional[int] = spm_file lowercase_ : Any = load_spm(__SCREAMING_SNAKE_CASE , self.sp_model_kwargs ) lowercase_ : List[Any] = len(self.encoder ) lowercase_ : Dict = { self.get_lang_token(__SCREAMING_SNAKE_CASE ): self.encoder_size + i for i, lang_code in enumerate(__SCREAMING_SNAKE_CASE ) } lowercase_ : Optional[int] = {lang_code: self.encoder_size + i for i, lang_code in enumerate(__SCREAMING_SNAKE_CASE )} lowercase_ : Union[str, Any] = {v: k for k, v in self.lang_token_to_id.items()} lowercase_ : Tuple = src_lang if src_lang is not None else '''en''' lowercase_ : Optional[int] = tgt_lang lowercase_ : Any = self.get_lang_id(self._src_lang ) self.set_src_lang_special_tokens(self._src_lang ) lowercase_ : Dict = num_madeup_words @property def _snake_case ( self ): """simple docstring""" return len(self.encoder ) + len(self.lang_token_to_id ) @property def _snake_case ( self ): """simple docstring""" return self._src_lang @src_lang.setter def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : str = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" return self.sp_model.encode(__SCREAMING_SNAKE_CASE , out_type=__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" if token in self.lang_token_to_id: return self.lang_token_to_id[token] return self.encoder.get(__SCREAMING_SNAKE_CASE , self.encoder[self.unk_token] ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" if index in self.id_to_lang_token: return self.id_to_lang_token[index] return self.decoder.get(__SCREAMING_SNAKE_CASE , self.unk_token ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Tuple = [] lowercase_ : List[str] = '''''' for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(__SCREAMING_SNAKE_CASE ) + token lowercase_ : Optional[Any] = [] else: current_sub_tokens.append(__SCREAMING_SNAKE_CASE ) out_string += self.sp_model.decode(__SCREAMING_SNAKE_CASE ) return out_string.strip() def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = False ): """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__SCREAMING_SNAKE_CASE , token_ids_a=__SCREAMING_SNAKE_CASE , already_has_special_tokens=__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = [1] * len(self.prefix_tokens ) lowercase_ : Any = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(__SCREAMING_SNAKE_CASE )) + suffix_ones return prefix_ones + ([0] * len(__SCREAMING_SNAKE_CASE )) + ([0] * len(__SCREAMING_SNAKE_CASE )) + suffix_ones def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def _snake_case ( self ): """simple docstring""" lowercase_ : Tuple = {self.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ): """simple docstring""" lowercase_ : List[Any] = self.__dict__.copy() lowercase_ : List[Any] = None return state def __setstate__( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Dict = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): lowercase_ : List[Any] = {} lowercase_ : Union[str, Any] = load_spm(self.spm_file , self.sp_model_kwargs ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" lowercase_ : Tuple = Path(__SCREAMING_SNAKE_CASE ) if not save_dir.is_dir(): raise OSError(F'''{save_directory} should be a directory''' ) lowercase_ : Dict = save_dir / ( (filename_prefix + '''-''' if filename_prefix else '''''') + self.vocab_files_names['''vocab_file'''] ) lowercase_ : Dict = save_dir / ( (filename_prefix + '''-''' if filename_prefix else '''''') + self.vocab_files_names['''spm_file'''] ) save_json(self.encoder , __SCREAMING_SNAKE_CASE ) if os.path.abspath(self.spm_file ) != os.path.abspath(__SCREAMING_SNAKE_CASE ) and os.path.isfile(self.spm_file ): copyfile(self.spm_file , __SCREAMING_SNAKE_CASE ) elif not os.path.isfile(self.spm_file ): with open(__SCREAMING_SNAKE_CASE , '''wb''' ) as fi: lowercase_ : int = self.sp_model.serialized_model_proto() fi.write(__SCREAMING_SNAKE_CASE ) return (str(__SCREAMING_SNAKE_CASE ), str(__SCREAMING_SNAKE_CASE )) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = "en" , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = "ro" , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : Optional[Any] = src_lang lowercase_ : List[str] = tgt_lang self.set_src_lang_special_tokens(self.src_lang ) return super().prepare_seqaseq_batch(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" if src_lang is None or tgt_lang is None: raise ValueError('''Translation requires a `src_lang` and a `tgt_lang` for this model''' ) lowercase_ : Tuple = src_lang lowercase_ : Any = self(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) lowercase_ : List[Any] = self.get_lang_id(__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = tgt_lang_id return inputs def _snake_case ( self ): """simple docstring""" self.set_src_lang_special_tokens(self.src_lang ) def _snake_case ( self ): """simple docstring""" self.set_tgt_lang_special_tokens(self.tgt_lang ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Any = self.get_lang_token(__SCREAMING_SNAKE_CASE ) lowercase_ : Dict = self.lang_token_to_id[lang_token] lowercase_ : Optional[Any] = [self.cur_lang_id] lowercase_ : Union[str, Any] = [self.eos_token_id] def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Any = self.get_lang_token(__SCREAMING_SNAKE_CASE ) lowercase_ : Any = self.lang_token_to_id[lang_token] lowercase_ : str = [self.cur_lang_id] lowercase_ : List[str] = [self.eos_token_id] def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" return self.lang_code_to_token[lang] def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : List[Any] = self.get_lang_token(__SCREAMING_SNAKE_CASE ) return self.lang_token_to_id[lang_token] def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Dict[str, Any] ): """simple docstring""" lowercase_ : Optional[int] = sentencepiece.SentencePieceProcessor(**__SCREAMING_SNAKE_CASE ) spm.Load(str(__SCREAMING_SNAKE_CASE ) ) return spm def snake_case_ ( __SCREAMING_SNAKE_CASE : str ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE , '''r''' ) as f: return json.load(__SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : str ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE , '''w''' ) as f: json.dump(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , indent=2 )
93
'''simple docstring''' import math import time from typing import Dict, List, Optional from torch.utils.data import Dataset from transformers import SeqaSeqTrainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput, speed_metrics if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class lowerCAmelCase__ ( lowerCamelCase_ ): def __init__( self , *__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , **__SCREAMING_SNAKE_CASE ): """simple docstring""" super().__init__(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = eval_examples lowercase_ : Tuple = post_process_function def _snake_case ( self , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = "eval" , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : Optional[int] = gen_kwargs.copy() lowercase_ : List[str] = ( gen_kwargs['''max_length'''] if gen_kwargs.get('''max_length''' ) is not None else self.args.generation_max_length ) lowercase_ : str = ( gen_kwargs['''num_beams'''] if gen_kwargs.get('''num_beams''' ) is not None else self.args.generation_num_beams ) lowercase_ : Dict = gen_kwargs lowercase_ : List[Any] = self.eval_dataset if eval_dataset is None else eval_dataset lowercase_ : List[str] = self.get_eval_dataloader(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. lowercase_ : Union[str, Any] = self.compute_metrics lowercase_ : Optional[int] = None lowercase_ : Tuple = time.time() lowercase_ : Tuple = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: lowercase_ : str = eval_loop( __SCREAMING_SNAKE_CASE , description='''Evaluation''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=__SCREAMING_SNAKE_CASE , metric_key_prefix=__SCREAMING_SNAKE_CASE , ) finally: lowercase_ : Any = compute_metrics lowercase_ : Any = self.args.eval_batch_size * self.args.world_size if F'''{metric_key_prefix}_jit_compilation_time''' in output.metrics: start_time += output.metrics[F'''{metric_key_prefix}_jit_compilation_time'''] output.metrics.update( speed_metrics( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save: # Only the main node write the results by default lowercase_ : Optional[Any] = self.post_process_function(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = self.compute_metrics(__SCREAMING_SNAKE_CASE ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F'''{metric_key_prefix}_''' ): lowercase_ : List[Any] = metrics.pop(__SCREAMING_SNAKE_CASE ) metrics.update(output.metrics ) else: lowercase_ : List[Any] = output.metrics if self.args.should_log: # Only the main node log the results by default self.log(__SCREAMING_SNAKE_CASE ) if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report() ) lowercase_ : List[Any] = self.callback_handler.on_evaluate(self.args , self.state , self.control , __SCREAMING_SNAKE_CASE ) return metrics def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE = "test" , **__SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Union[str, Any] = gen_kwargs.copy() lowercase_ : Tuple = self.get_test_dataloader(__SCREAMING_SNAKE_CASE ) # Temporarily disable metric computation, we will do it in the loop here. lowercase_ : Optional[Any] = self.compute_metrics lowercase_ : Optional[int] = None lowercase_ : List[Any] = time.time() lowercase_ : int = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: lowercase_ : Tuple = eval_loop( __SCREAMING_SNAKE_CASE , description='''Prediction''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=__SCREAMING_SNAKE_CASE , metric_key_prefix=__SCREAMING_SNAKE_CASE , ) finally: lowercase_ : Any = compute_metrics lowercase_ : Tuple = self.args.eval_batch_size * self.args.world_size if F'''{metric_key_prefix}_jit_compilation_time''' in output.metrics: start_time += output.metrics[F'''{metric_key_prefix}_jit_compilation_time'''] output.metrics.update( speed_metrics( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is None or self.compute_metrics is None: return output lowercase_ : Any = self.post_process_function(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , '''predict''' ) lowercase_ : str = self.compute_metrics(__SCREAMING_SNAKE_CASE ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F'''{metric_key_prefix}_''' ): lowercase_ : Optional[int] = metrics.pop(__SCREAMING_SNAKE_CASE ) metrics.update(output.metrics ) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=__SCREAMING_SNAKE_CASE )
93
1
'''simple docstring''' import numpy as np def snake_case_ ( __SCREAMING_SNAKE_CASE : np.ndarray ): """simple docstring""" return 1 / (1 + np.exp(-vector )) def snake_case_ ( __SCREAMING_SNAKE_CASE : np.ndarray ): """simple docstring""" return vector * sigmoid(__SCREAMING_SNAKE_CASE ) if __name__ == "__main__": import doctest doctest.testmod()
93
'''simple docstring''' from pathlib import Path from typing import List from transformers import is_torch_available, is_vision_available from transformers.testing_utils import get_tests_dir, is_tool_test from transformers.tools.agent_types import AGENT_TYPE_MAPPING, AgentAudio, AgentImage, AgentText if is_torch_available(): import torch if is_vision_available(): from PIL import Image _lowercase : List[str] = ["text", "image", "audio"] def snake_case_ ( __SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" lowercase_ : int = [] for input_type in input_types: if input_type == "text": inputs.append('''Text input''' ) elif input_type == "image": inputs.append( Image.open(Path(get_tests_dir('''fixtures/tests_samples/COCO''' ) ) / '''000000039769.png''' ).resize((512, 512) ) ) elif input_type == "audio": inputs.append(torch.ones(3000 ) ) elif isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): inputs.append(create_inputs(__SCREAMING_SNAKE_CASE ) ) else: raise ValueError(F'''Invalid type requested: {input_type}''' ) return inputs def snake_case_ ( __SCREAMING_SNAKE_CASE : List ): """simple docstring""" lowercase_ : Optional[Any] = [] for output in outputs: if isinstance(__SCREAMING_SNAKE_CASE , (str, AgentText) ): output_types.append('''text''' ) elif isinstance(__SCREAMING_SNAKE_CASE , (Image.Image, AgentImage) ): output_types.append('''image''' ) elif isinstance(__SCREAMING_SNAKE_CASE , (torch.Tensor, AgentAudio) ): output_types.append('''audio''' ) else: raise ValueError(F'''Invalid output: {output}''' ) return output_types @is_tool_test class lowerCAmelCase__ : def _snake_case ( self ): """simple docstring""" self.assertTrue(hasattr(self.tool , '''inputs''' ) ) self.assertTrue(hasattr(self.tool , '''outputs''' ) ) lowercase_ : Optional[Any] = self.tool.inputs for _input in inputs: if isinstance(_input , __SCREAMING_SNAKE_CASE ): for __input in _input: self.assertTrue(__input in authorized_types ) else: self.assertTrue(_input in authorized_types ) lowercase_ : int = self.tool.outputs for _output in outputs: self.assertTrue(_output in authorized_types ) def _snake_case ( self ): """simple docstring""" lowercase_ : int = create_inputs(self.tool.inputs ) lowercase_ : Tuple = self.tool(*__SCREAMING_SNAKE_CASE ) # There is a single output if len(self.tool.outputs ) == 1: lowercase_ : Any = [outputs] self.assertListEqual(output_types(__SCREAMING_SNAKE_CASE ) , self.tool.outputs ) def _snake_case ( self ): """simple docstring""" self.assertTrue(hasattr(self.tool , '''description''' ) ) self.assertTrue(hasattr(self.tool , '''default_checkpoint''' ) ) self.assertTrue(self.tool.description.startswith('''This is a tool that''' ) ) def _snake_case ( self ): """simple docstring""" lowercase_ : int = create_inputs(self.tool.inputs ) lowercase_ : int = self.tool(*__SCREAMING_SNAKE_CASE ) if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase_ : Optional[Any] = [outputs] self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , len(self.tool.outputs ) ) for output, output_type in zip(__SCREAMING_SNAKE_CASE , self.tool.outputs ): lowercase_ : Optional[int] = AGENT_TYPE_MAPPING[output_type] self.assertTrue(isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) def _snake_case ( self ): """simple docstring""" lowercase_ : Dict = create_inputs(self.tool.inputs ) lowercase_ : int = [] for _input, input_type in zip(__SCREAMING_SNAKE_CASE , self.tool.inputs ): if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): _inputs.append([AGENT_TYPE_MAPPING[_input_type](_input ) for _input_type in input_type] ) else: _inputs.append(AGENT_TYPE_MAPPING[input_type](_input ) ) # Should not raise an error lowercase_ : Optional[Any] = self.tool(*__SCREAMING_SNAKE_CASE ) if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase_ : Dict = [outputs] self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , len(self.tool.outputs ) )
93
1
'''simple docstring''' import json import os import tempfile from transformers.testing_utils import check_json_file_has_correct_format class lowerCAmelCase__ : lowerCAmelCase_ = None def _snake_case ( self ): """simple docstring""" lowercase_ : Tuple = self.feature_extraction_class(**self.feat_extract_dict ) lowercase_ : Any = json.loads(feat_extract.to_json_string() ) for key, value in self.feat_extract_dict.items(): self.assertEqual(obj[key] , __SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" lowercase_ : str = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: lowercase_ : str = os.path.join(__SCREAMING_SNAKE_CASE , '''feat_extract.json''' ) feat_extract_first.to_json_file(__SCREAMING_SNAKE_CASE ) lowercase_ : str = self.feature_extraction_class.from_json_file(__SCREAMING_SNAKE_CASE ) self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() ) def _snake_case ( self ): """simple docstring""" lowercase_ : Tuple = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: lowercase_ : Union[str, Any] = feat_extract_first.save_pretrained(__SCREAMING_SNAKE_CASE )[0] check_json_file_has_correct_format(__SCREAMING_SNAKE_CASE ) lowercase_ : str = self.feature_extraction_class.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() ) def _snake_case ( self ): """simple docstring""" lowercase_ : Optional[Any] = self.feature_extraction_class() self.assertIsNotNone(__SCREAMING_SNAKE_CASE )
93
'''simple docstring''' # DISCLAIMER: This file is strongly influenced by https://github.com/ermongroup/ddim from dataclasses import dataclass from typing import Optional, Tuple, Union import flax import jax import jax.numpy as jnp from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils_flax import ( CommonSchedulerState, FlaxKarrasDiffusionSchedulers, FlaxSchedulerMixin, FlaxSchedulerOutput, add_noise_common, get_velocity_common, ) @flax.struct.dataclass class lowerCAmelCase__ : lowerCAmelCase_ = 42 # setable values lowerCAmelCase_ = 42 lowerCAmelCase_ = 42 lowerCAmelCase_ = None @classmethod def _snake_case ( cls , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" return cls(common=__SCREAMING_SNAKE_CASE , init_noise_sigma=__SCREAMING_SNAKE_CASE , timesteps=__SCREAMING_SNAKE_CASE ) @dataclass class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = 42 class lowerCAmelCase__ ( lowerCamelCase_ , lowerCamelCase_ ): lowerCAmelCase_ = [e.name for e in FlaxKarrasDiffusionSchedulers] lowerCAmelCase_ = 42 @property def _snake_case ( self ): """simple docstring""" return True @register_to_config def __init__( self , __SCREAMING_SNAKE_CASE = 10_00 , __SCREAMING_SNAKE_CASE = 0.0_001 , __SCREAMING_SNAKE_CASE = 0.02 , __SCREAMING_SNAKE_CASE = "linear" , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = "fixed_small" , __SCREAMING_SNAKE_CASE = True , __SCREAMING_SNAKE_CASE = "epsilon" , __SCREAMING_SNAKE_CASE = jnp.floataa , ): """simple docstring""" lowercase_ : Dict = dtype def _snake_case ( self , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" if common is None: lowercase_ : Tuple = CommonSchedulerState.create(self ) # standard deviation of the initial noise distribution lowercase_ : Union[str, Any] = jnp.array(1.0 , dtype=self.dtype ) lowercase_ : List[Any] = jnp.arange(0 , self.config.num_train_timesteps ).round()[::-1] return DDPMSchedulerState.create( common=__SCREAMING_SNAKE_CASE , init_noise_sigma=__SCREAMING_SNAKE_CASE , timesteps=__SCREAMING_SNAKE_CASE , ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" return sample def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = () ): """simple docstring""" lowercase_ : Optional[Any] = self.config.num_train_timesteps // num_inference_steps # creates integer timesteps by multiplying by ratio # rounding to avoid issues when num_inference_step is power of 3 lowercase_ : int = (jnp.arange(0 , __SCREAMING_SNAKE_CASE ) * step_ratio).round()[::-1] return state.replace( num_inference_steps=__SCREAMING_SNAKE_CASE , timesteps=__SCREAMING_SNAKE_CASE , ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None ): """simple docstring""" lowercase_ : List[Any] = state.common.alphas_cumprod[t] lowercase_ : str = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) ) # For t > 0, compute predicted variance βt (see formula (6) and (7) from https://arxiv.org/pdf/2006.11239.pdf) # and sample from it to get previous sample # x_{t-1} ~ N(pred_prev_sample, variance) == add variance to pred_sample lowercase_ : int = (1 - alpha_prod_t_prev) / (1 - alpha_prod_t) * state.common.betas[t] if variance_type is None: lowercase_ : str = self.config.variance_type # hacks - were probably added for training stability if variance_type == "fixed_small": lowercase_ : int = jnp.clip(__SCREAMING_SNAKE_CASE , a_min=1E-2_0 ) # for rl-diffuser https://arxiv.org/abs/2205.09991 elif variance_type == "fixed_small_log": lowercase_ : List[str] = jnp.log(jnp.clip(__SCREAMING_SNAKE_CASE , a_min=1E-2_0 ) ) elif variance_type == "fixed_large": lowercase_ : List[Any] = state.common.betas[t] elif variance_type == "fixed_large_log": # Glide max_log lowercase_ : List[Any] = jnp.log(state.common.betas[t] ) elif variance_type == "learned": return predicted_variance elif variance_type == "learned_range": lowercase_ : Optional[Any] = variance lowercase_ : Union[str, Any] = state.common.betas[t] lowercase_ : Union[str, Any] = (predicted_variance + 1) / 2 lowercase_ : Any = frac * max_log + (1 - frac) * min_log return variance def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = True , ): """simple docstring""" lowercase_ : Optional[int] = timestep if key is None: lowercase_ : int = jax.random.PRNGKey(0 ) if model_output.shape[1] == sample.shape[1] * 2 and self.config.variance_type in ["learned", "learned_range"]: lowercase_ , lowercase_ : Optional[Any] = jnp.split(__SCREAMING_SNAKE_CASE , sample.shape[1] , axis=1 ) else: lowercase_ : int = None # 1. compute alphas, betas lowercase_ : Any = state.common.alphas_cumprod[t] lowercase_ : Optional[int] = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) ) lowercase_ : int = 1 - alpha_prod_t lowercase_ : str = 1 - alpha_prod_t_prev # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if self.config.prediction_type == "epsilon": lowercase_ : Tuple = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif self.config.prediction_type == "sample": lowercase_ : Any = model_output elif self.config.prediction_type == "v_prediction": lowercase_ : List[Any] = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output else: raise ValueError( F'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample` ''' ''' for the FlaxDDPMScheduler.''' ) # 3. Clip "predicted x_0" if self.config.clip_sample: lowercase_ : Optional[Any] = jnp.clip(__SCREAMING_SNAKE_CASE , -1 , 1 ) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf lowercase_ : List[Any] = (alpha_prod_t_prev ** 0.5 * state.common.betas[t]) / beta_prod_t lowercase_ : Optional[Any] = state.common.alphas[t] ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf lowercase_ : Optional[Any] = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise def random_variance(): lowercase_ : str = jax.random.split(__SCREAMING_SNAKE_CASE , num=1 ) lowercase_ : List[Any] = jax.random.normal(__SCREAMING_SNAKE_CASE , shape=model_output.shape , dtype=self.dtype ) return (self._get_variance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , predicted_variance=__SCREAMING_SNAKE_CASE ) ** 0.5) * noise lowercase_ : Optional[Any] = jnp.where(t > 0 , random_variance() , jnp.zeros(model_output.shape , dtype=self.dtype ) ) lowercase_ : Any = pred_prev_sample + variance if not return_dict: return (pred_prev_sample, state) return FlaxDDPMSchedulerOutput(prev_sample=__SCREAMING_SNAKE_CASE , state=__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , ): """simple docstring""" return add_noise_common(state.common , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , ): """simple docstring""" return get_velocity_common(state.common , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def __len__( self ): """simple docstring""" return self.config.num_train_timesteps
93
1
'''simple docstring''' class lowerCAmelCase__ : def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None ): """simple docstring""" lowercase_ : Optional[Any] = data lowercase_ : List[Any] = previous lowercase_ : int = next_node def __str__( self ): """simple docstring""" return F'''{self.data}''' def _snake_case ( self ): """simple docstring""" return self.data def _snake_case ( self ): """simple docstring""" return self.next def _snake_case ( self ): """simple docstring""" return self.previous class lowerCAmelCase__ : def __init__( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Any = head def __iter__( self ): """simple docstring""" return self def _snake_case ( self ): """simple docstring""" if not self.current: raise StopIteration else: lowercase_ : Union[str, Any] = self.current.get_data() lowercase_ : Optional[Any] = self.current.get_next() return value class lowerCAmelCase__ : def __init__( self ): """simple docstring""" lowercase_ : Dict = None # First node in list lowercase_ : Optional[int] = None # Last node in list def __str__( self ): """simple docstring""" lowercase_ : Any = self.head lowercase_ : List[Any] = [] while current is not None: nodes.append(current.get_data() ) lowercase_ : str = current.get_next() return " ".join(str(__SCREAMING_SNAKE_CASE ) for node in nodes ) def __contains__( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Optional[Any] = self.head while current: if current.get_data() == value: return True lowercase_ : int = current.get_next() return False def __iter__( self ): """simple docstring""" return LinkedListIterator(self.head ) def _snake_case ( self ): """simple docstring""" if self.head: return self.head.get_data() return None def _snake_case ( self ): """simple docstring""" if self.tail: return self.tail.get_data() return None def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" if self.head is None: lowercase_ : int = node lowercase_ : List[Any] = node else: self.insert_before_node(self.head , __SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" if self.head is None: self.set_head(__SCREAMING_SNAKE_CASE ) else: self.insert_after_node(self.tail , __SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Dict = Node(__SCREAMING_SNAKE_CASE ) if self.head is None: self.set_head(__SCREAMING_SNAKE_CASE ) else: self.set_tail(__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Dict = node lowercase_ : List[str] = node.previous if node.get_previous() is None: lowercase_ : Union[str, Any] = node_to_insert else: lowercase_ : Optional[Any] = node_to_insert lowercase_ : Any = node_to_insert def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Optional[Any] = node lowercase_ : Dict = node.next if node.get_next() is None: lowercase_ : Union[str, Any] = node_to_insert else: lowercase_ : Any = node_to_insert lowercase_ : Union[str, Any] = node_to_insert def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : List[str] = 1 lowercase_ : Tuple = Node(__SCREAMING_SNAKE_CASE ) lowercase_ : Dict = self.head while node: if current_position == position: self.insert_before_node(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) return current_position += 1 lowercase_ : List[Any] = node.next self.insert_after_node(self.tail , __SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Optional[Any] = self.head while node: if node.get_data() == item: return node lowercase_ : Tuple = node.get_next() raise Exception('''Node not found''' ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" if (node := self.get_node(__SCREAMING_SNAKE_CASE )) is not None: if node == self.head: lowercase_ : Union[str, Any] = self.head.get_next() if node == self.tail: lowercase_ : List[Any] = self.tail.get_previous() self.remove_node_pointers(__SCREAMING_SNAKE_CASE ) @staticmethod def _snake_case ( __SCREAMING_SNAKE_CASE ): """simple docstring""" if node.get_next(): lowercase_ : str = node.previous if node.get_previous(): lowercase_ : List[Any] = node.next lowercase_ : Optional[Any] = None lowercase_ : Dict = None def _snake_case ( self ): """simple docstring""" return self.head is None def snake_case_ ( ): """simple docstring""" if __name__ == "__main__": import doctest doctest.testmod()
93
'''simple docstring''' _lowercase : int = [sum(int(c, 1_0) ** 2 for c in i.__str__()) for i in range(1_0_0_0_0_0)] def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : Optional[int] = 0 while number: # Increased Speed Slightly by checking every 5 digits together. sum_of_digits_squared += DIGITS_SQUARED[number % 100000] number //= 100000 return sum_of_digits_squared # There are 2 Chains made, # One ends with 89 with the chain member 58 being the one which when declared first, # there will be the least number of iterations for all the members to be checked. # The other one ends with 1 and has only one element 1. # So 58 and 1 are chosen to be declared at the starting. # Changed dictionary to an array to quicken the solution _lowercase : list[bool | None] = [None] * 1_0_0_0_0_0_0_0 _lowercase : List[str] = True _lowercase : Optional[int] = False def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" if CHAINS[number - 1] is not None: return CHAINS[number - 1] # type: ignore lowercase_ : Tuple = chain(next_number(__SCREAMING_SNAKE_CASE ) ) lowercase_ : Union[str, Any] = number_chain while number < 10000000: lowercase_ : int = number_chain number *= 10 return number_chain def snake_case_ ( __SCREAMING_SNAKE_CASE : int = 10000000 ): """simple docstring""" for i in range(1 , __SCREAMING_SNAKE_CASE ): if CHAINS[i] is None: chain(i + 1 ) return CHAINS[:number].count(__SCREAMING_SNAKE_CASE ) if __name__ == "__main__": import doctest doctest.testmod() print(f"""{solution() = }""")
93
1
'''simple docstring''' import importlib import inspect import json import os import re import shutil import sys from pathlib import Path from typing import Dict, Optional, Union from urllib import request from huggingface_hub import HfFolder, cached_download, hf_hub_download, model_info from packaging import version from .. import __version__ from . import DIFFUSERS_DYNAMIC_MODULE_NAME, HF_MODULES_CACHE, logging _lowercase : Optional[Any] = ( "https://raw.githubusercontent.com/huggingface/diffusers/{revision}/examples/community/{pipeline}.py" ) _lowercase : Tuple = logging.get_logger(__name__) # pylint: disable=invalid-name def snake_case_ ( ): """simple docstring""" lowercase_ : Tuple = '''https://pypi.org/pypi/diffusers/json''' lowercase_ : Tuple = json.loads(request.urlopen(__SCREAMING_SNAKE_CASE ).read() )['''releases'''].keys() return sorted(__SCREAMING_SNAKE_CASE , key=lambda __SCREAMING_SNAKE_CASE : version.Version(__SCREAMING_SNAKE_CASE ) ) def snake_case_ ( ): """simple docstring""" if HF_MODULES_CACHE in sys.path: return sys.path.append(__SCREAMING_SNAKE_CASE ) os.makedirs(__SCREAMING_SNAKE_CASE , exist_ok=__SCREAMING_SNAKE_CASE ) lowercase_ : List[Any] = Path(__SCREAMING_SNAKE_CASE ) / '''__init__.py''' if not init_path.exists(): init_path.touch() def snake_case_ ( __SCREAMING_SNAKE_CASE : Union[str, os.PathLike] ): """simple docstring""" init_hf_modules() lowercase_ : Optional[int] = Path(__SCREAMING_SNAKE_CASE ) / name # If the parent module does not exist yet, recursively create it. if not dynamic_module_path.parent.exists(): create_dynamic_module(dynamic_module_path.parent ) os.makedirs(__SCREAMING_SNAKE_CASE , exist_ok=__SCREAMING_SNAKE_CASE ) lowercase_ : str = dynamic_module_path / '''__init__.py''' if not init_path.exists(): init_path.touch() def snake_case_ ( __SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE , '''r''' , encoding='''utf-8''' ) as f: lowercase_ : int = f.read() # Imports of the form `import .xxx` lowercase_ : List[Any] = re.findall('''^\s*import\s+\.(\S+)\s*$''' , __SCREAMING_SNAKE_CASE , flags=re.MULTILINE ) # Imports of the form `from .xxx import yyy` relative_imports += re.findall('''^\s*from\s+\.(\S+)\s+import''' , __SCREAMING_SNAKE_CASE , flags=re.MULTILINE ) # Unique-ify return list(set(__SCREAMING_SNAKE_CASE ) ) def snake_case_ ( __SCREAMING_SNAKE_CASE : str ): """simple docstring""" lowercase_ : int = False lowercase_ : Any = [module_file] lowercase_ : Dict = [] # Let's recurse through all relative imports while not no_change: lowercase_ : Dict = [] for f in files_to_check: new_imports.extend(get_relative_imports(__SCREAMING_SNAKE_CASE ) ) lowercase_ : Union[str, Any] = Path(__SCREAMING_SNAKE_CASE ).parent lowercase_ : Optional[int] = [str(module_path / m ) for m in new_imports] lowercase_ : str = [f for f in new_import_files if f not in all_relative_imports] lowercase_ : int = [F'''{f}.py''' for f in new_import_files] lowercase_ : Optional[Any] = len(__SCREAMING_SNAKE_CASE ) == 0 all_relative_imports.extend(__SCREAMING_SNAKE_CASE ) return all_relative_imports def snake_case_ ( __SCREAMING_SNAKE_CASE : Any ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE , '''r''' , encoding='''utf-8''' ) as f: lowercase_ : Union[str, Any] = f.read() # Imports of the form `import xxx` lowercase_ : Any = re.findall('''^\s*import\s+(\S+)\s*$''' , __SCREAMING_SNAKE_CASE , flags=re.MULTILINE ) # Imports of the form `from xxx import yyy` imports += re.findall('''^\s*from\s+(\S+)\s+import''' , __SCREAMING_SNAKE_CASE , flags=re.MULTILINE ) # Only keep the top-level module lowercase_ : List[str] = [imp.split('''.''' )[0] for imp in imports if not imp.startswith('''.''' )] # Unique-ify and test we got them all lowercase_ : Any = list(set(__SCREAMING_SNAKE_CASE ) ) lowercase_ : Optional[Any] = [] for imp in imports: try: importlib.import_module(__SCREAMING_SNAKE_CASE ) except ImportError: missing_packages.append(__SCREAMING_SNAKE_CASE ) if len(__SCREAMING_SNAKE_CASE ) > 0: raise ImportError( '''This modeling file requires the following packages that were not found in your environment: ''' F'''{', '.join(__SCREAMING_SNAKE_CASE )}. Run `pip install {' '.join(__SCREAMING_SNAKE_CASE )}`''' ) return get_relative_imports(__SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" lowercase_ : List[Any] = module_path.replace(os.path.sep , '''.''' ) lowercase_ : Any = importlib.import_module(__SCREAMING_SNAKE_CASE ) if class_name is None: return find_pipeline_class(__SCREAMING_SNAKE_CASE ) return getattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" from ..pipelines import DiffusionPipeline lowercase_ : int = dict(inspect.getmembers(__SCREAMING_SNAKE_CASE , inspect.isclass ) ) lowercase_ : Optional[Any] = None for cls_name, cls in cls_members.items(): if ( cls_name != DiffusionPipeline.__name__ and issubclass(cls , __SCREAMING_SNAKE_CASE ) and cls.__module__.split('''.''' )[0] != "diffusers" ): if pipeline_class is not None: raise ValueError( F'''Multiple classes that inherit from {DiffusionPipeline.__name__} have been found:''' F''' {pipeline_class.__name__}, and {cls_name}. Please make sure to define only one in''' F''' {loaded_module}.''' ) lowercase_ : List[Any] = cls return pipeline_class def snake_case_ ( __SCREAMING_SNAKE_CASE : Union[str, os.PathLike] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Optional[Union[str, os.PathLike]] = None , __SCREAMING_SNAKE_CASE : bool = False , __SCREAMING_SNAKE_CASE : bool = False , __SCREAMING_SNAKE_CASE : Optional[Dict[str, str]] = None , __SCREAMING_SNAKE_CASE : Optional[Union[bool, str]] = None , __SCREAMING_SNAKE_CASE : Optional[str] = None , __SCREAMING_SNAKE_CASE : bool = False , ): """simple docstring""" lowercase_ : Dict = str(__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if os.path.isfile(__SCREAMING_SNAKE_CASE ): lowercase_ : Dict = module_file_or_url lowercase_ : int = '''local''' elif pretrained_model_name_or_path.count('''/''' ) == 0: lowercase_ : Optional[int] = get_diffusers_versions() # cut ".dev0" lowercase_ : List[Any] = '''v''' + '''.'''.join(__version__.split('''.''' )[:3] ) # retrieve github version that matches if revision is None: lowercase_ : List[str] = latest_version if latest_version[1:] in available_versions else '''main''' logger.info(F'''Defaulting to latest_version: {revision}.''' ) elif revision in available_versions: lowercase_ : List[str] = F'''v{revision}''' elif revision == "main": lowercase_ : Optional[Any] = revision else: raise ValueError( F'''`custom_revision`: {revision} does not exist. Please make sure to choose one of''' F''' {', '.join(available_versions + ['main'] )}.''' ) # community pipeline on GitHub lowercase_ : Tuple = COMMUNITY_PIPELINES_URL.format(revision=__SCREAMING_SNAKE_CASE , pipeline=__SCREAMING_SNAKE_CASE ) try: lowercase_ : Optional[Any] = cached_download( __SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE , force_download=__SCREAMING_SNAKE_CASE , proxies=__SCREAMING_SNAKE_CASE , resume_download=__SCREAMING_SNAKE_CASE , local_files_only=__SCREAMING_SNAKE_CASE , use_auth_token=__SCREAMING_SNAKE_CASE , ) lowercase_ : Tuple = '''git''' lowercase_ : Tuple = pretrained_model_name_or_path + '''.py''' except EnvironmentError: logger.error(F'''Could not locate the {module_file} inside {pretrained_model_name_or_path}.''' ) raise else: try: # Load from URL or cache if already cached lowercase_ : str = hf_hub_download( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE , force_download=__SCREAMING_SNAKE_CASE , proxies=__SCREAMING_SNAKE_CASE , resume_download=__SCREAMING_SNAKE_CASE , local_files_only=__SCREAMING_SNAKE_CASE , use_auth_token=__SCREAMING_SNAKE_CASE , ) lowercase_ : Optional[Any] = os.path.join('''local''' , '''--'''.join(pretrained_model_name_or_path.split('''/''' ) ) ) except EnvironmentError: logger.error(F'''Could not locate the {module_file} inside {pretrained_model_name_or_path}.''' ) raise # Check we have all the requirements in our environment lowercase_ : Tuple = check_imports(__SCREAMING_SNAKE_CASE ) # Now we move the module inside our cached dynamic modules. lowercase_ : str = DIFFUSERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule create_dynamic_module(__SCREAMING_SNAKE_CASE ) lowercase_ : Any = Path(__SCREAMING_SNAKE_CASE ) / full_submodule if submodule == "local" or submodule == "git": # We always copy local files (we could hash the file to see if there was a change, and give them the name of # that hash, to only copy when there is a modification but it seems overkill for now). # The only reason we do the copy is to avoid putting too many folders in sys.path. shutil.copy(__SCREAMING_SNAKE_CASE , submodule_path / module_file ) for module_needed in modules_needed: lowercase_ : Union[str, Any] = F'''{module_needed}.py''' shutil.copy(os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) , submodule_path / module_needed ) else: # Get the commit hash # TODO: we will get this info in the etag soon, so retrieve it from there and not here. if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase_ : Tuple = use_auth_token elif use_auth_token is True: lowercase_ : List[Any] = HfFolder.get_token() else: lowercase_ : Optional[Any] = None lowercase_ : Optional[int] = model_info(__SCREAMING_SNAKE_CASE , revision=__SCREAMING_SNAKE_CASE , token=__SCREAMING_SNAKE_CASE ).sha # The module file will end up being placed in a subfolder with the git hash of the repo. This way we get the # benefit of versioning. lowercase_ : int = submodule_path / commit_hash lowercase_ : Tuple = full_submodule + os.path.sep + commit_hash create_dynamic_module(__SCREAMING_SNAKE_CASE ) if not (submodule_path / module_file).exists(): shutil.copy(__SCREAMING_SNAKE_CASE , submodule_path / module_file ) # Make sure we also have every file with relative for module_needed in modules_needed: if not (submodule_path / module_needed).exists(): get_cached_module_file( __SCREAMING_SNAKE_CASE , F'''{module_needed}.py''' , cache_dir=__SCREAMING_SNAKE_CASE , force_download=__SCREAMING_SNAKE_CASE , resume_download=__SCREAMING_SNAKE_CASE , proxies=__SCREAMING_SNAKE_CASE , use_auth_token=__SCREAMING_SNAKE_CASE , revision=__SCREAMING_SNAKE_CASE , local_files_only=__SCREAMING_SNAKE_CASE , ) return os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Union[str, os.PathLike] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Optional[str] = None , __SCREAMING_SNAKE_CASE : Optional[Union[str, os.PathLike]] = None , __SCREAMING_SNAKE_CASE : bool = False , __SCREAMING_SNAKE_CASE : bool = False , __SCREAMING_SNAKE_CASE : Optional[Dict[str, str]] = None , __SCREAMING_SNAKE_CASE : Optional[Union[bool, str]] = None , __SCREAMING_SNAKE_CASE : Optional[str] = None , __SCREAMING_SNAKE_CASE : bool = False , **__SCREAMING_SNAKE_CASE : Optional[Any] , ): """simple docstring""" lowercase_ : Optional[Any] = get_cached_module_file( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE , force_download=__SCREAMING_SNAKE_CASE , resume_download=__SCREAMING_SNAKE_CASE , proxies=__SCREAMING_SNAKE_CASE , use_auth_token=__SCREAMING_SNAKE_CASE , revision=__SCREAMING_SNAKE_CASE , local_files_only=__SCREAMING_SNAKE_CASE , ) return get_class_in_module(__SCREAMING_SNAKE_CASE , final_module.replace('''.py''' , '''''' ) )
93
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _lowercase : Union[str, Any] = { "configuration_pix2struct": [ "PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP", "Pix2StructConfig", "Pix2StructTextConfig", "Pix2StructVisionConfig", ], "processing_pix2struct": ["Pix2StructProcessor"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : Dict = ["Pix2StructImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : List[str] = [ "PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST", "Pix2StructPreTrainedModel", "Pix2StructForConditionalGeneration", "Pix2StructVisionModel", "Pix2StructTextModel", ] if TYPE_CHECKING: from .configuration_pixastruct import ( PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP, PixaStructConfig, PixaStructTextConfig, PixaStructVisionConfig, ) from .processing_pixastruct import PixaStructProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_pixastruct import PixaStructImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_pixastruct import ( PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST, PixaStructForConditionalGeneration, PixaStructPreTrainedModel, PixaStructTextModel, PixaStructVisionModel, ) else: import sys _lowercase : Optional[int] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
93
1
'''simple docstring''' import inspect import unittest class lowerCAmelCase__ ( unittest.TestCase ): def _snake_case ( self ): """simple docstring""" try: import diffusers # noqa: F401 except ImportError: assert False def _snake_case ( self ): """simple docstring""" import diffusers from diffusers.dependency_versions_table import deps lowercase_ : List[Any] = inspect.getmembers(__SCREAMING_SNAKE_CASE , inspect.isclass ) for cls_name, cls_module in all_classes: if "dummy_" in cls_module.__module__: for backend in cls_module._backends: if backend == "k_diffusion": lowercase_ : Any = '''k-diffusion''' elif backend == "invisible_watermark": lowercase_ : Dict = '''invisible-watermark''' assert backend in deps, F'''{backend} is not in the deps table!'''
93
'''simple docstring''' def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : Optional[int] = int(__SCREAMING_SNAKE_CASE ) if decimal in (0, 1): # Exit cases for the recursion return str(__SCREAMING_SNAKE_CASE ) lowercase_ , lowercase_ : List[str] = divmod(__SCREAMING_SNAKE_CASE , 2 ) return binary_recursive(__SCREAMING_SNAKE_CASE ) + str(__SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : str ): """simple docstring""" lowercase_ : str = str(__SCREAMING_SNAKE_CASE ).strip() if not number: raise ValueError('''No input value was provided''' ) lowercase_ : Optional[int] = '''-''' if number.startswith('''-''' ) else '''''' lowercase_ : Union[str, Any] = number.lstrip('''-''' ) if not number.isnumeric(): raise ValueError('''Input value is not an integer''' ) return F'''{negative}0b{binary_recursive(int(__SCREAMING_SNAKE_CASE ) )}''' if __name__ == "__main__": from doctest import testmod testmod()
93
1
'''simple docstring''' def snake_case_ ( __SCREAMING_SNAKE_CASE : int = 10 , __SCREAMING_SNAKE_CASE : int = 22 ): """simple docstring""" lowercase_ : Tuple = range(1 , __SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = range(1 , __SCREAMING_SNAKE_CASE ) return sum( 1 for power in powers for base in bases if len(str(base**power ) ) == power ) if __name__ == "__main__": print(f"""{solution(1_0, 2_2) = }""")
93
'''simple docstring''' import glob import os import random from string import ascii_lowercase, digits import cva import numpy as np # Parrameters _lowercase : Any = (7_2_0, 1_2_8_0) # Height, Width _lowercase : List[Any] = (0.4, 0.6) # if height or width lower than this scale, drop it. _lowercase : str = 1 / 1_0_0 _lowercase : Any = "" _lowercase : Union[str, Any] = "" _lowercase : Optional[int] = "" _lowercase : List[Any] = 2_5_0 def snake_case_ ( ): """simple docstring""" lowercase_ , lowercase_ : Any = get_dataset(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) for index in range(__SCREAMING_SNAKE_CASE ): lowercase_ : str = random.sample(range(len(__SCREAMING_SNAKE_CASE ) ) , 4 ) lowercase_ , lowercase_ , lowercase_ : Any = 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' lowercase_ : int = random_chars(32 ) lowercase_ : str = path.split(os.sep )[-1].rsplit('''.''' , 1 )[0] lowercase_ : int = F'''{OUTPUT_DIR}/{file_name}_MOSAIC_{letter_code}''' cva.imwrite(F'''{file_root}.jpg''' , __SCREAMING_SNAKE_CASE , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(F'''Succeeded {index+1}/{NUMBER_IMAGES} with {file_name}''' ) lowercase_ : List[Any] = [] for anno in new_annos: lowercase_ : List[Any] = anno[3] - anno[1] lowercase_ : List[str] = anno[4] - anno[2] lowercase_ : Dict = anno[1] + width / 2 lowercase_ : Dict = anno[2] + height / 2 lowercase_ : 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 snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : str ): """simple docstring""" lowercase_ : Optional[Any] = [] lowercase_ : Optional[Any] = [] for label_file in glob.glob(os.path.join(__SCREAMING_SNAKE_CASE , '''*.txt''' ) ): lowercase_ : int = label_file.split(os.sep )[-1].rsplit('''.''' , 1 )[0] with open(__SCREAMING_SNAKE_CASE ) as in_file: lowercase_ : List[str] = in_file.readlines() lowercase_ : Optional[Any] = os.path.join(__SCREAMING_SNAKE_CASE , F'''{label_name}.jpg''' ) lowercase_ : Optional[int] = [] for obj_list in obj_lists: lowercase_ : List[str] = obj_list.rstrip('''\n''' ).split(''' ''' ) lowercase_ : Optional[int] = float(obj[1] ) - float(obj[3] ) / 2 lowercase_ : Any = float(obj[2] ) - float(obj[4] ) / 2 lowercase_ : str = float(obj[1] ) + float(obj[3] ) / 2 lowercase_ : List[str] = 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 snake_case_ ( __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 , ): """simple docstring""" lowercase_ : List[Any] = np.zeros([output_size[0], output_size[1], 3] , dtype=np.uinta ) lowercase_ : Tuple = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) lowercase_ : List[Any] = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) lowercase_ : Optional[int] = int(scale_x * output_size[1] ) lowercase_ : Dict = int(scale_y * output_size[0] ) lowercase_ : Union[str, Any] = [] lowercase_ : List[Any] = [] for i, index in enumerate(__SCREAMING_SNAKE_CASE ): lowercase_ : Union[str, Any] = all_img_list[index] path_list.append(__SCREAMING_SNAKE_CASE ) lowercase_ : int = all_annos[index] lowercase_ : Dict = cva.imread(__SCREAMING_SNAKE_CASE ) if i == 0: # top-left lowercase_ : Optional[Any] = cva.resize(__SCREAMING_SNAKE_CASE , (divid_point_x, divid_point_y) ) lowercase_ : Tuple = img for bbox in img_annos: lowercase_ : Optional[int] = bbox[1] * scale_x lowercase_ : Optional[Any] = bbox[2] * scale_y lowercase_ : str = bbox[3] * scale_x lowercase_ : Tuple = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 1: # top-right lowercase_ : Dict = cva.resize(__SCREAMING_SNAKE_CASE , (output_size[1] - divid_point_x, divid_point_y) ) lowercase_ : Dict = img for bbox in img_annos: lowercase_ : int = scale_x + bbox[1] * (1 - scale_x) lowercase_ : Dict = bbox[2] * scale_y lowercase_ : Optional[int] = scale_x + bbox[3] * (1 - scale_x) lowercase_ : int = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 2: # bottom-left lowercase_ : List[Any] = cva.resize(__SCREAMING_SNAKE_CASE , (divid_point_x, output_size[0] - divid_point_y) ) lowercase_ : List[str] = img for bbox in img_annos: lowercase_ : Any = bbox[1] * scale_x lowercase_ : Optional[int] = scale_y + bbox[2] * (1 - scale_y) lowercase_ : str = bbox[3] * scale_x lowercase_ : Optional[int] = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) else: # bottom-right lowercase_ : int = cva.resize( __SCREAMING_SNAKE_CASE , (output_size[1] - divid_point_x, output_size[0] - divid_point_y) ) lowercase_ : List[str] = img for bbox in img_annos: lowercase_ : int = scale_x + bbox[1] * (1 - scale_x) lowercase_ : Any = scale_y + bbox[2] * (1 - scale_y) lowercase_ : Optional[Any] = scale_x + bbox[3] * (1 - scale_x) lowercase_ : int = 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: lowercase_ : Optional[Any] = [ anno for anno in new_anno if filter_scale < (anno[3] - anno[1]) and filter_scale < (anno[4] - anno[2]) ] return output_img, new_anno, path_list[0] def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" assert number_char > 1, "The number of character should greater than 1" lowercase_ : Any = ascii_lowercase + digits return "".join(random.choice(__SCREAMING_SNAKE_CASE ) for _ in range(__SCREAMING_SNAKE_CASE ) ) if __name__ == "__main__": main() print("DONE ✅")
93
1
'''simple docstring''' import numpy as np from cva import COLOR_BGR2GRAY, cvtColor, imread from numpy import array, uinta from PIL import Image from digital_image_processing import change_contrast as cc from digital_image_processing import convert_to_negative as cn from digital_image_processing import sepia as sp from digital_image_processing.dithering import burkes as bs from digital_image_processing.edge_detection import canny from digital_image_processing.filters import convolve as conv from digital_image_processing.filters import gaussian_filter as gg from digital_image_processing.filters import local_binary_pattern as lbp from digital_image_processing.filters import median_filter as med from digital_image_processing.filters import sobel_filter as sob from digital_image_processing.resize import resize as rs _lowercase : Dict = imread(r"digital_image_processing/image_data/lena_small.jpg") _lowercase : List[str] = cvtColor(img, COLOR_BGR2GRAY) def snake_case_ ( ): """simple docstring""" lowercase_ : Optional[int] = cn.convert_to_negative(__SCREAMING_SNAKE_CASE ) # assert negative_img array for at least one True assert negative_img.any() def snake_case_ ( ): """simple docstring""" with Image.open('''digital_image_processing/image_data/lena_small.jpg''' ) as img: # Work around assertion for response assert str(cc.change_contrast(__SCREAMING_SNAKE_CASE , 110 ) ).startswith( '''<PIL.Image.Image image mode=RGB size=100x100 at''' ) def snake_case_ ( ): """simple docstring""" lowercase_ : Union[str, Any] = canny.gen_gaussian_kernel(9 , sigma=1.4 ) # Assert ambiguous array assert resp.all() def snake_case_ ( ): """simple docstring""" lowercase_ : int = imread('''digital_image_processing/image_data/lena_small.jpg''' , 0 ) # assert ambiguous array for all == True assert canny_img.all() lowercase_ : Dict = canny.canny(__SCREAMING_SNAKE_CASE ) # assert canny array for at least one True assert canny_array.any() def snake_case_ ( ): """simple docstring""" assert gg.gaussian_filter(__SCREAMING_SNAKE_CASE , 5 , sigma=0.9 ).all() def snake_case_ ( ): """simple docstring""" lowercase_ : Tuple = array([[0.25, 0.5, 0.25], [0.5, -3, 0.5], [0.25, 0.5, 0.25]] ) lowercase_ : Optional[Any] = conv.img_convolve(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).astype(__SCREAMING_SNAKE_CASE ) assert res.any() def snake_case_ ( ): """simple docstring""" assert med.median_filter(__SCREAMING_SNAKE_CASE , 3 ).any() def snake_case_ ( ): """simple docstring""" lowercase_ , lowercase_ : List[str] = sob.sobel_filter(__SCREAMING_SNAKE_CASE ) assert grad.any() and theta.any() def snake_case_ ( ): """simple docstring""" lowercase_ : int = sp.make_sepia(__SCREAMING_SNAKE_CASE , 20 ) assert sepia.all() def snake_case_ ( __SCREAMING_SNAKE_CASE : str = "digital_image_processing/image_data/lena_small.jpg" ): """simple docstring""" lowercase_ : int = bs.Burkes(imread(__SCREAMING_SNAKE_CASE , 1 ) , 120 ) burkes.process() assert burkes.output_img.any() def snake_case_ ( __SCREAMING_SNAKE_CASE : str = "digital_image_processing/image_data/lena_small.jpg" , ): """simple docstring""" lowercase_ : Any = rs.NearestNeighbour(imread(__SCREAMING_SNAKE_CASE , 1 ) , 400 , 200 ) nn.process() assert nn.output.any() def snake_case_ ( ): """simple docstring""" lowercase_ : Optional[Any] = '''digital_image_processing/image_data/lena.jpg''' # Reading the image and converting it to grayscale. lowercase_ : List[Any] = imread(__SCREAMING_SNAKE_CASE , 0 ) # Test for get_neighbors_pixel function() return not None lowercase_ : Tuple = 0 lowercase_ : List[Any] = 0 lowercase_ : Dict = image[x_coordinate][y_coordinate] lowercase_ : Any = lbp.get_neighbors_pixel( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) assert neighbors_pixels is not None # Test for local_binary_pattern function() # Create a numpy array as the same height and width of read image lowercase_ : int = np.zeros((image.shape[0], image.shape[1]) ) # Iterating through the image and calculating the local binary pattern value # for each pixel. for i in range(0 , image.shape[0] ): for j in range(0 , image.shape[1] ): lowercase_ : Optional[Any] = lbp.local_binary_value(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) assert lbp_image.any()
93
'''simple docstring''' from __future__ import annotations from collections import Counter from random import random class lowerCAmelCase__ : def __init__( self ): """simple docstring""" lowercase_ : int = {} def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Dict = {} def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" if nodea not in self.connections: self.add_node(__SCREAMING_SNAKE_CASE ) if nodea not in self.connections: self.add_node(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = probability def _snake_case ( self ): """simple docstring""" return list(self.connections ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Any = 0 lowercase_ : Tuple = random() for dest in self.connections[node]: current_probability += self.connections[node][dest] if current_probability > random_value: return dest return "" def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : list[tuple[str, str, float]] , __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : List[Any] = MarkovChainGraphUndirectedUnweighted() for nodea, nodea, probability in transitions: graph.add_transition_probability(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : str = Counter(graph.get_nodes() ) lowercase_ : Any = start for _ in range(__SCREAMING_SNAKE_CASE ): lowercase_ : int = graph.transition(__SCREAMING_SNAKE_CASE ) visited[node] += 1 return visited if __name__ == "__main__": import doctest doctest.testmod()
93
1
'''simple docstring''' def snake_case_ ( __SCREAMING_SNAKE_CASE : int = 1000 ): """simple docstring""" lowercase_ , lowercase_ : Optional[int] = 1, 1 lowercase_ : int = 2 while True: lowercase_ : List[Any] = 0 lowercase_ : int = fa + fa lowercase_ , lowercase_ : Tuple = fa, f index += 1 for _ in str(__SCREAMING_SNAKE_CASE ): i += 1 if i == n: break return index if __name__ == "__main__": print(solution(int(str(input()).strip())))
93
'''simple docstring''' import torch from transformers import AutoModel class lowerCAmelCase__ ( torch.nn.Module ): def __init__( self , __SCREAMING_SNAKE_CASE="sayef/fsner-bert-base-uncased" ): """simple docstring""" super(__SCREAMING_SNAKE_CASE , self ).__init__() lowercase_ : Tuple = AutoModel.from_pretrained(__SCREAMING_SNAKE_CASE , return_dict=__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = torch.nn.CosineSimilarity(3 , 1E-0_8 ) lowercase_ : Optional[Any] = torch.nn.Softmax(dim=1 ) def _snake_case ( self , **__SCREAMING_SNAKE_CASE ): """simple docstring""" return self.bert(**__SCREAMING_SNAKE_CASE ).last_hidden_state def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" return token_embeddings.sum(2 , keepdim=__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=1 ): """simple docstring""" return self.softmax(T * self.cos(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Optional[Any] = W_supports['''sizes'''].tolist() lowercase_ : Dict = W_supports['''start_token_id'''].item() lowercase_ : List[Any] = W_supports['''end_token_id'''].item() del W_supports["sizes"] del W_supports["start_token_id"] del W_supports["end_token_id"] lowercase_ : List[str] = self.BERT(**__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = self.BERT(**__SCREAMING_SNAKE_CASE ) lowercase_ : str = None lowercase_ : Dict = None lowercase_ : Tuple = W_supports['''input_ids'''] == start_token_id lowercase_ : Any = W_supports['''input_ids'''] == end_token_id for i, size in enumerate(__SCREAMING_SNAKE_CASE ): if i == 0: lowercase_ : List[str] = 0 else: lowercase_ : List[Any] = support_sizes[i - 1] lowercase_ : str = S[s : s + size][start_token_masks[s : s + size]] lowercase_ : Optional[int] = S[s : s + size][end_token_masks[s : s + size]] lowercase_ : List[str] = torch.matmul(q[i] , s_start.T ).sum(1 ).softmax(0 ) lowercase_ : List[str] = torch.matmul(q[i] , s_end.T ).sum(1 ).softmax(0 ) if p_starts is not None: lowercase_ : Tuple = torch.vstack((p_starts, p_start) ) lowercase_ : Optional[Any] = torch.vstack((p_ends, p_end) ) else: lowercase_ : str = p_start lowercase_ : int = p_end return p_starts, p_ends
93
1
'''simple docstring''' from collections.abc import Sequence from queue import Queue class lowerCAmelCase__ : def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None ): """simple docstring""" lowercase_ : int = start lowercase_ : List[Any] = end lowercase_ : Tuple = val lowercase_ : List[str] = (start + end) // 2 lowercase_ : Dict = left lowercase_ : Dict = right def __repr__( self ): """simple docstring""" return F'''SegmentTreeNode(start={self.start}, end={self.end}, val={self.val})''' class lowerCAmelCase__ : def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Optional[Any] = collection lowercase_ : int = function if self.collection: lowercase_ : List[Any] = self._build_tree(0 , len(__SCREAMING_SNAKE_CASE ) - 1 ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" self._update_tree(self.root , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" return self._query_range(self.root , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" if start == end: return SegmentTreeNode(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , self.collection[start] ) lowercase_ : Union[str, Any] = (start + end) // 2 lowercase_ : int = self._build_tree(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : Dict = self._build_tree(mid + 1 , __SCREAMING_SNAKE_CASE ) return SegmentTreeNode(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , self.fn(left.val , right.val ) , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" if node.start == i and node.end == i: lowercase_ : List[Any] = val return if i <= node.mid: self._update_tree(node.left , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else: self._update_tree(node.right , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : List[str] = self.fn(node.left.val , node.right.val ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" if node.start == i and node.end == j: return node.val if i <= node.mid: if j <= node.mid: # range in left child tree return self._query_range(node.left , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else: # range in left child tree and right child tree return self.fn( self._query_range(node.left , __SCREAMING_SNAKE_CASE , node.mid ) , self._query_range(node.right , node.mid + 1 , __SCREAMING_SNAKE_CASE ) , ) else: # range in right child tree return self._query_range(node.right , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" if self.root is not None: lowercase_ : Dict = Queue() queue.put(self.root ) while not queue.empty(): lowercase_ : Optional[Any] = queue.get() yield node if node.left is not None: queue.put(node.left ) if node.right is not None: queue.put(node.right ) if __name__ == "__main__": import operator for fn in [operator.add, max, min]: print("*" * 5_0) _lowercase : List[Any] = SegmentTree([2, 1, 5, 3, 4], fn) for node in arr.traverse(): print(node) print() arr.update(1, 5) for node in arr.traverse(): print(node) print() print(arr.query_range(3, 4)) # 7 print(arr.query_range(2, 2)) # 5 print(arr.query_range(1, 3)) # 13 print()
93
'''simple docstring''' import json import os from pathlib import Path from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple, Union import sentencepiece from ...tokenization_utils import BatchEncoding, PreTrainedTokenizer from ...utils import logging _lowercase : List[Any] = logging.get_logger(__name__) _lowercase : List[Any] = "▁" _lowercase : Tuple = { "vocab_file": "vocab.json", "spm_file": "sentencepiece.bpe.model", "tokenizer_config_file": "tokenizer_config.json", } _lowercase : List[str] = { "vocab_file": { "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/vocab.json", "facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/vocab.json", }, "spm_file": { "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/sentencepiece.bpe.model", "facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/sentencepiece.bpe.model", }, "tokenizer_config_file": { "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/tokenizer_config.json", "facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/tokenizer_config.json", }, } _lowercase : List[str] = { "facebook/m2m100_418M": 1_0_2_4, } # fmt: off _lowercase : Tuple = { "m2m100": ["af", "am", "ar", "ast", "az", "ba", "be", "bg", "bn", "br", "bs", "ca", "ceb", "cs", "cy", "da", "de", "el", "en", "es", "et", "fa", "ff", "fi", "fr", "fy", "ga", "gd", "gl", "gu", "ha", "he", "hi", "hr", "ht", "hu", "hy", "id", "ig", "ilo", "is", "it", "ja", "jv", "ka", "kk", "km", "kn", "ko", "lb", "lg", "ln", "lo", "lt", "lv", "mg", "mk", "ml", "mn", "mr", "ms", "my", "ne", "nl", "no", "ns", "oc", "or", "pa", "pl", "ps", "pt", "ro", "ru", "sd", "si", "sk", "sl", "so", "sq", "sr", "ss", "su", "sv", "sw", "ta", "th", "tl", "tn", "tr", "uk", "ur", "uz", "vi", "wo", "xh", "yi", "yo", "zh", "zu"], "wmt21": ["en", "ha", "is", "ja", "cs", "ru", "zh", "de"] } class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = VOCAB_FILES_NAMES lowerCAmelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase_ = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase_ = ['''input_ids''', '''attention_mask'''] lowerCAmelCase_ = [] lowerCAmelCase_ = [] def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE="<s>" , __SCREAMING_SNAKE_CASE="</s>" , __SCREAMING_SNAKE_CASE="</s>" , __SCREAMING_SNAKE_CASE="<pad>" , __SCREAMING_SNAKE_CASE="<unk>" , __SCREAMING_SNAKE_CASE="m2m100" , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE=8 , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : Optional[Any] = {} if sp_model_kwargs is None else sp_model_kwargs lowercase_ : List[Any] = language_codes lowercase_ : Optional[int] = FAIRSEQ_LANGUAGE_CODES[language_codes] lowercase_ : List[Any] = {lang_code: F'''__{lang_code}__''' for lang_code in fairseq_language_code} lowercase_ : Union[str, Any] = kwargs.get('''additional_special_tokens''' , [] ) kwargs["additional_special_tokens"] += [ self.get_lang_token(__SCREAMING_SNAKE_CASE ) for lang_code in fairseq_language_code if self.get_lang_token(__SCREAMING_SNAKE_CASE ) not in kwargs["additional_special_tokens"] ] super().__init__( src_lang=__SCREAMING_SNAKE_CASE , tgt_lang=__SCREAMING_SNAKE_CASE , bos_token=__SCREAMING_SNAKE_CASE , eos_token=__SCREAMING_SNAKE_CASE , sep_token=__SCREAMING_SNAKE_CASE , unk_token=__SCREAMING_SNAKE_CASE , pad_token=__SCREAMING_SNAKE_CASE , language_codes=__SCREAMING_SNAKE_CASE , sp_model_kwargs=self.sp_model_kwargs , num_madeup_words=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) lowercase_ : int = vocab_file lowercase_ : Any = load_json(__SCREAMING_SNAKE_CASE ) lowercase_ : str = {v: k for k, v in self.encoder.items()} lowercase_ : Optional[int] = spm_file lowercase_ : Any = load_spm(__SCREAMING_SNAKE_CASE , self.sp_model_kwargs ) lowercase_ : List[Any] = len(self.encoder ) lowercase_ : Dict = { self.get_lang_token(__SCREAMING_SNAKE_CASE ): self.encoder_size + i for i, lang_code in enumerate(__SCREAMING_SNAKE_CASE ) } lowercase_ : Optional[int] = {lang_code: self.encoder_size + i for i, lang_code in enumerate(__SCREAMING_SNAKE_CASE )} lowercase_ : Union[str, Any] = {v: k for k, v in self.lang_token_to_id.items()} lowercase_ : Tuple = src_lang if src_lang is not None else '''en''' lowercase_ : Optional[int] = tgt_lang lowercase_ : Any = self.get_lang_id(self._src_lang ) self.set_src_lang_special_tokens(self._src_lang ) lowercase_ : Dict = num_madeup_words @property def _snake_case ( self ): """simple docstring""" return len(self.encoder ) + len(self.lang_token_to_id ) @property def _snake_case ( self ): """simple docstring""" return self._src_lang @src_lang.setter def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : str = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" return self.sp_model.encode(__SCREAMING_SNAKE_CASE , out_type=__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" if token in self.lang_token_to_id: return self.lang_token_to_id[token] return self.encoder.get(__SCREAMING_SNAKE_CASE , self.encoder[self.unk_token] ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" if index in self.id_to_lang_token: return self.id_to_lang_token[index] return self.decoder.get(__SCREAMING_SNAKE_CASE , self.unk_token ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Tuple = [] lowercase_ : List[str] = '''''' for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(__SCREAMING_SNAKE_CASE ) + token lowercase_ : Optional[Any] = [] else: current_sub_tokens.append(__SCREAMING_SNAKE_CASE ) out_string += self.sp_model.decode(__SCREAMING_SNAKE_CASE ) return out_string.strip() def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = False ): """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__SCREAMING_SNAKE_CASE , token_ids_a=__SCREAMING_SNAKE_CASE , already_has_special_tokens=__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = [1] * len(self.prefix_tokens ) lowercase_ : Any = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(__SCREAMING_SNAKE_CASE )) + suffix_ones return prefix_ones + ([0] * len(__SCREAMING_SNAKE_CASE )) + ([0] * len(__SCREAMING_SNAKE_CASE )) + suffix_ones def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def _snake_case ( self ): """simple docstring""" lowercase_ : Tuple = {self.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ): """simple docstring""" lowercase_ : List[Any] = self.__dict__.copy() lowercase_ : List[Any] = None return state def __setstate__( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Dict = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): lowercase_ : List[Any] = {} lowercase_ : Union[str, Any] = load_spm(self.spm_file , self.sp_model_kwargs ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" lowercase_ : Tuple = Path(__SCREAMING_SNAKE_CASE ) if not save_dir.is_dir(): raise OSError(F'''{save_directory} should be a directory''' ) lowercase_ : Dict = save_dir / ( (filename_prefix + '''-''' if filename_prefix else '''''') + self.vocab_files_names['''vocab_file'''] ) lowercase_ : Dict = save_dir / ( (filename_prefix + '''-''' if filename_prefix else '''''') + self.vocab_files_names['''spm_file'''] ) save_json(self.encoder , __SCREAMING_SNAKE_CASE ) if os.path.abspath(self.spm_file ) != os.path.abspath(__SCREAMING_SNAKE_CASE ) and os.path.isfile(self.spm_file ): copyfile(self.spm_file , __SCREAMING_SNAKE_CASE ) elif not os.path.isfile(self.spm_file ): with open(__SCREAMING_SNAKE_CASE , '''wb''' ) as fi: lowercase_ : int = self.sp_model.serialized_model_proto() fi.write(__SCREAMING_SNAKE_CASE ) return (str(__SCREAMING_SNAKE_CASE ), str(__SCREAMING_SNAKE_CASE )) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = "en" , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = "ro" , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : Optional[Any] = src_lang lowercase_ : List[str] = tgt_lang self.set_src_lang_special_tokens(self.src_lang ) return super().prepare_seqaseq_batch(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" if src_lang is None or tgt_lang is None: raise ValueError('''Translation requires a `src_lang` and a `tgt_lang` for this model''' ) lowercase_ : Tuple = src_lang lowercase_ : Any = self(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) lowercase_ : List[Any] = self.get_lang_id(__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = tgt_lang_id return inputs def _snake_case ( self ): """simple docstring""" self.set_src_lang_special_tokens(self.src_lang ) def _snake_case ( self ): """simple docstring""" self.set_tgt_lang_special_tokens(self.tgt_lang ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Any = self.get_lang_token(__SCREAMING_SNAKE_CASE ) lowercase_ : Dict = self.lang_token_to_id[lang_token] lowercase_ : Optional[Any] = [self.cur_lang_id] lowercase_ : Union[str, Any] = [self.eos_token_id] def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Any = self.get_lang_token(__SCREAMING_SNAKE_CASE ) lowercase_ : Any = self.lang_token_to_id[lang_token] lowercase_ : str = [self.cur_lang_id] lowercase_ : List[str] = [self.eos_token_id] def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" return self.lang_code_to_token[lang] def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : List[Any] = self.get_lang_token(__SCREAMING_SNAKE_CASE ) return self.lang_token_to_id[lang_token] def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Dict[str, Any] ): """simple docstring""" lowercase_ : Optional[int] = sentencepiece.SentencePieceProcessor(**__SCREAMING_SNAKE_CASE ) spm.Load(str(__SCREAMING_SNAKE_CASE ) ) return spm def snake_case_ ( __SCREAMING_SNAKE_CASE : str ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE , '''r''' ) as f: return json.load(__SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : str ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE , '''w''' ) as f: json.dump(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , indent=2 )
93
1
'''simple docstring''' import math def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase_ : Union[str, Any] = F'''Input value of [number={number}] must be an integer''' raise TypeError(__SCREAMING_SNAKE_CASE ) if number < 1: lowercase_ : Union[str, Any] = F'''Input value of [number={number}] must be > 0''' raise ValueError(__SCREAMING_SNAKE_CASE ) elif number == 1: return 3 elif number == 2: return 5 else: lowercase_ : Any = int(math.log(number // 3 , 2 ) ) + 2 lowercase_ : List[str] = [3, 5] lowercase_ : Any = 2 lowercase_ : Union[str, Any] = 3 for block in range(1 , __SCREAMING_SNAKE_CASE ): for _ in range(__SCREAMING_SNAKE_CASE ): proth_list.append(2 ** (block + 1) + proth_list[proth_index - 1] ) proth_index += 1 increment *= 2 return proth_list[number - 1] if __name__ == "__main__": import doctest doctest.testmod() for number in range(1_1): _lowercase : Any = 0 try: _lowercase : List[str] = proth(number) except ValueError: print(f"""ValueError: there is no {number}th Proth number""") continue print(f"""The {number}th Proth number: {value}""")
93
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer from ...utils import logging _lowercase : str = logging.get_logger(__name__) _lowercase : List[Any] = "▁" _lowercase : List[Any] = {"vocab_file": "sentencepiece.bpe.model"} _lowercase : Optional[int] = { "vocab_file": { "facebook/mbart-large-en-ro": ( "https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/sentencepiece.bpe.model" ), "facebook/mbart-large-cc25": ( "https://huggingface.co/facebook/mbart-large-cc25/resolve/main/sentencepiece.bpe.model" ), } } _lowercase : str = { "facebook/mbart-large-en-ro": 1_0_2_4, "facebook/mbart-large-cc25": 1_0_2_4, } # fmt: off _lowercase : List[Any] = ["ar_AR", "cs_CZ", "de_DE", "en_XX", "es_XX", "et_EE", "fi_FI", "fr_XX", "gu_IN", "hi_IN", "it_IT", "ja_XX", "kk_KZ", "ko_KR", "lt_LT", "lv_LV", "my_MM", "ne_NP", "nl_XX", "ro_RO", "ru_RU", "si_LK", "tr_TR", "vi_VN", "zh_CN"] class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = VOCAB_FILES_NAMES lowerCAmelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase_ = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase_ = ['''input_ids''', '''attention_mask'''] lowerCAmelCase_ = [] lowerCAmelCase_ = [] def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE="<s>" , __SCREAMING_SNAKE_CASE="</s>" , __SCREAMING_SNAKE_CASE="</s>" , __SCREAMING_SNAKE_CASE="<s>" , __SCREAMING_SNAKE_CASE="<unk>" , __SCREAMING_SNAKE_CASE="<pad>" , __SCREAMING_SNAKE_CASE="<mask>" , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE=None , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : Any = AddedToken(__SCREAMING_SNAKE_CASE , lstrip=__SCREAMING_SNAKE_CASE , rstrip=__SCREAMING_SNAKE_CASE ) if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else mask_token lowercase_ : int = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=__SCREAMING_SNAKE_CASE , eos_token=__SCREAMING_SNAKE_CASE , unk_token=__SCREAMING_SNAKE_CASE , sep_token=__SCREAMING_SNAKE_CASE , cls_token=__SCREAMING_SNAKE_CASE , pad_token=__SCREAMING_SNAKE_CASE , mask_token=__SCREAMING_SNAKE_CASE , tokenizer_file=__SCREAMING_SNAKE_CASE , src_lang=__SCREAMING_SNAKE_CASE , tgt_lang=__SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , sp_model_kwargs=self.sp_model_kwargs , **__SCREAMING_SNAKE_CASE , ) lowercase_ : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__SCREAMING_SNAKE_CASE ) ) lowercase_ : List[str] = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # Mimic fairseq token-to-id alignment for the first 4 token lowercase_ : Tuple = {'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3} # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab lowercase_ : str = 1 lowercase_ : str = len(self.sp_model ) lowercase_ : List[Any] = { code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(__SCREAMING_SNAKE_CASE ) } lowercase_ : Union[str, Any] = {v: k for k, v in self.lang_code_to_id.items()} lowercase_ : List[Any] = len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset self.fairseq_tokens_to_ids.update(self.lang_code_to_id ) lowercase_ : Union[str, Any] = {v: k for k, v in self.fairseq_tokens_to_ids.items()} lowercase_ : Optional[Any] = list(self.lang_code_to_id.keys() ) if additional_special_tokens is not None: # Only add those special tokens if they are not already there. self._additional_special_tokens.extend( [t for t in additional_special_tokens if t not in self._additional_special_tokens] ) lowercase_ : Optional[Any] = src_lang if src_lang is not None else '''en_XX''' lowercase_ : str = self.lang_code_to_id[self._src_lang] lowercase_ : Optional[Any] = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) def __getstate__( self ): """simple docstring""" lowercase_ : Optional[int] = self.__dict__.copy() lowercase_ : Dict = None lowercase_ : Any = self.sp_model.serialized_model_proto() return state def __setstate__( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Optional[Any] = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): lowercase_ : Dict = {} lowercase_ : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) @property def _snake_case ( self ): """simple docstring""" return len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset + 1 # Plus 1 for the mask token @property def _snake_case ( self ): """simple docstring""" return self._src_lang @src_lang.setter def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Tuple = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = False ): """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__SCREAMING_SNAKE_CASE , token_ids_a=__SCREAMING_SNAKE_CASE , already_has_special_tokens=__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = [1] * len(self.prefix_tokens ) lowercase_ : Tuple = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(__SCREAMING_SNAKE_CASE )) + suffix_ones return prefix_ones + ([0] * len(__SCREAMING_SNAKE_CASE )) + ([0] * len(__SCREAMING_SNAKE_CASE )) + suffix_ones def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" lowercase_ : Optional[int] = [self.sep_token_id] lowercase_ : Any = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" if src_lang is None or tgt_lang is None: raise ValueError('''Translation requires a `src_lang` and a `tgt_lang` for this model''' ) lowercase_ : Optional[Any] = src_lang lowercase_ : Dict = self(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , return_tensors=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = self.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = tgt_lang_id return inputs def _snake_case ( self ): """simple docstring""" lowercase_ : str = {self.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" return self.sp_model.encode(__SCREAMING_SNAKE_CASE , out_type=__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] lowercase_ : Any = self.sp_model.PieceToId(__SCREAMING_SNAKE_CASE ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : int = ''''''.join(__SCREAMING_SNAKE_CASE ).replace(__SCREAMING_SNAKE_CASE , ''' ''' ).strip() return out_string def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" if not os.path.isdir(__SCREAMING_SNAKE_CASE ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return lowercase_ : Tuple = os.path.join( __SCREAMING_SNAKE_CASE , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__SCREAMING_SNAKE_CASE ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __SCREAMING_SNAKE_CASE ) elif not os.path.isfile(self.vocab_file ): with open(__SCREAMING_SNAKE_CASE , '''wb''' ) as fi: lowercase_ : List[str] = self.sp_model.serialized_model_proto() fi.write(__SCREAMING_SNAKE_CASE ) return (out_vocab_file,) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = "en_XX" , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = "ro_RO" , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : List[str] = src_lang lowercase_ : int = tgt_lang return super().prepare_seqaseq_batch(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" return self.set_src_lang_special_tokens(self.src_lang ) def _snake_case ( self ): """simple docstring""" return self.set_tgt_lang_special_tokens(self.tgt_lang ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Dict = self.lang_code_to_id[src_lang] lowercase_ : Optional[Any] = [] lowercase_ : List[str] = [self.eos_token_id, self.cur_lang_code] def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : List[Any] = self.lang_code_to_id[lang] lowercase_ : Dict = [] lowercase_ : Union[str, Any] = [self.eos_token_id, self.cur_lang_code]
93
1
'''simple docstring''' def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : list[str] ): """simple docstring""" lowercase_ : List[str] = '''''' for word_or_phrase in separated: if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): raise Exception('''join() accepts only strings to be joined''' ) joined += word_or_phrase + separator return joined.strip(__SCREAMING_SNAKE_CASE ) if __name__ == "__main__": from doctest import testmod testmod()
93
'''simple docstring''' import json import os import tempfile from transformers.testing_utils import check_json_file_has_correct_format class lowerCAmelCase__ : lowerCAmelCase_ = None def _snake_case ( self ): """simple docstring""" lowercase_ : Tuple = self.feature_extraction_class(**self.feat_extract_dict ) lowercase_ : Any = json.loads(feat_extract.to_json_string() ) for key, value in self.feat_extract_dict.items(): self.assertEqual(obj[key] , __SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" lowercase_ : str = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: lowercase_ : str = os.path.join(__SCREAMING_SNAKE_CASE , '''feat_extract.json''' ) feat_extract_first.to_json_file(__SCREAMING_SNAKE_CASE ) lowercase_ : str = self.feature_extraction_class.from_json_file(__SCREAMING_SNAKE_CASE ) self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() ) def _snake_case ( self ): """simple docstring""" lowercase_ : Tuple = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: lowercase_ : Union[str, Any] = feat_extract_first.save_pretrained(__SCREAMING_SNAKE_CASE )[0] check_json_file_has_correct_format(__SCREAMING_SNAKE_CASE ) lowercase_ : str = self.feature_extraction_class.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() ) def _snake_case ( self ): """simple docstring""" lowercase_ : Optional[Any] = self.feature_extraction_class() self.assertIsNotNone(__SCREAMING_SNAKE_CASE )
93
1
'''simple docstring''' from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Features, Value from .base import TaskTemplate @dataclass(frozen=lowerCamelCase_ ) class lowerCAmelCase__ ( lowerCamelCase_ ): # `task` is not a ClassVar since we want it to be part of the `asdict` output for JSON serialization lowerCAmelCase_ = field(default='''summarization''' , metadata={'''include_in_asdict_even_if_is_default''': True} ) lowerCAmelCase_ = Features({'''text''': Value('''string''' )} ) lowerCAmelCase_ = Features({'''summary''': Value('''string''' )} ) lowerCAmelCase_ = "text" lowerCAmelCase_ = "summary" @property def _snake_case ( self ): """simple docstring""" return {self.text_column: "text", self.summary_column: "summary"}
93
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging _lowercase : Optional[Any] = logging.get_logger(__name__) _lowercase : List[str] = { "google/pix2struct-textcaps-base": ( "https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json" ), } class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = '''pix2struct_text_model''' lowerCAmelCase_ = ['''past_key_values'''] lowerCAmelCase_ = { '''hidden_size''': '''hidden_size''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self , __SCREAMING_SNAKE_CASE=5_02_44 , __SCREAMING_SNAKE_CASE=7_68 , __SCREAMING_SNAKE_CASE=64 , __SCREAMING_SNAKE_CASE=20_48 , __SCREAMING_SNAKE_CASE=12 , __SCREAMING_SNAKE_CASE=12 , __SCREAMING_SNAKE_CASE=32 , __SCREAMING_SNAKE_CASE=1_28 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=1E-6 , __SCREAMING_SNAKE_CASE=1.0 , __SCREAMING_SNAKE_CASE="gelu_new" , __SCREAMING_SNAKE_CASE=0 , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=0 , __SCREAMING_SNAKE_CASE=1 , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=True , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : Any = vocab_size lowercase_ : Tuple = hidden_size lowercase_ : Optional[Any] = d_kv lowercase_ : List[str] = d_ff lowercase_ : List[str] = num_layers lowercase_ : Optional[Any] = num_heads lowercase_ : Union[str, Any] = relative_attention_num_buckets lowercase_ : Optional[int] = relative_attention_max_distance lowercase_ : Union[str, Any] = dropout_rate lowercase_ : Dict = layer_norm_epsilon lowercase_ : Dict = initializer_factor lowercase_ : List[Any] = use_cache lowercase_ : Optional[int] = eos_token_id lowercase_ : Optional[int] = decoder_start_token_id # for backwards compatibility lowercase_ : Any = dense_act_fn super().__init__( pad_token_id=__SCREAMING_SNAKE_CASE , eos_token_id=__SCREAMING_SNAKE_CASE , decoder_start_token_id=__SCREAMING_SNAKE_CASE , tie_word_embeddings=__SCREAMING_SNAKE_CASE , is_decoder=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) @classmethod def _snake_case ( cls , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" cls._set_token_in_kwargs(__SCREAMING_SNAKE_CASE ) lowercase_ , lowercase_ : Optional[int] = cls.get_config_dict(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) # get the text config dict if we are loading from Pix2StructConfig if config_dict.get('''model_type''' ) == "pix2struct": lowercase_ : List[Any] = config_dict['''text_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'''You are using a model of type {config_dict['model_type']} to instantiate a model of type ''' F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = '''pix2struct_vision_model''' def __init__( self , __SCREAMING_SNAKE_CASE=7_68 , __SCREAMING_SNAKE_CASE=7_68 , __SCREAMING_SNAKE_CASE=20_48 , __SCREAMING_SNAKE_CASE=64 , __SCREAMING_SNAKE_CASE=12 , __SCREAMING_SNAKE_CASE=12 , __SCREAMING_SNAKE_CASE="gelu_new" , __SCREAMING_SNAKE_CASE=1E-6 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=1E-1_0 , __SCREAMING_SNAKE_CASE=1.0 , __SCREAMING_SNAKE_CASE=40_96 , __SCREAMING_SNAKE_CASE=32 , __SCREAMING_SNAKE_CASE=1_28 , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = hidden_size lowercase_ : Any = patch_embed_hidden_size lowercase_ : List[Any] = d_ff lowercase_ : Dict = dropout_rate lowercase_ : Any = num_hidden_layers lowercase_ : Any = num_attention_heads lowercase_ : int = initializer_range lowercase_ : Dict = initializer_factor lowercase_ : Dict = attention_dropout lowercase_ : Optional[Any] = layer_norm_eps lowercase_ : str = dense_act_fn lowercase_ : Dict = seq_len lowercase_ : List[Any] = relative_attention_num_buckets lowercase_ : int = relative_attention_max_distance lowercase_ : Optional[int] = d_kv @classmethod def _snake_case ( cls , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" cls._set_token_in_kwargs(__SCREAMING_SNAKE_CASE ) lowercase_ , lowercase_ : str = cls.get_config_dict(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) # get the vision config dict if we are loading from Pix2StructConfig if config_dict.get('''model_type''' ) == "pix2struct": lowercase_ : Optional[int] = config_dict['''vision_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'''You are using a model of type {config_dict['model_type']} to instantiate a model of type ''' F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = '''pix2struct''' lowerCAmelCase_ = True def __init__( self , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=1.0 , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=True , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" super().__init__(tie_word_embeddings=__SCREAMING_SNAKE_CASE , is_encoder_decoder=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) if text_config is None: lowercase_ : Optional[Any] = {} logger.info('''text_config is None. Initializing the Pix2StructTextConfig with default values.''' ) if vision_config is None: lowercase_ : Dict = {} logger.info('''vision_config is None. Initializing the Pix2StructVisionConfig with default values.''' ) lowercase_ : str = PixaStructTextConfig(**__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = PixaStructVisionConfig(**__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = self.text_config.decoder_start_token_id lowercase_ : Union[str, Any] = self.text_config.pad_token_id lowercase_ : Union[str, Any] = self.text_config.eos_token_id lowercase_ : int = initializer_factor lowercase_ : Any = initializer_range lowercase_ : str = self.initializer_range lowercase_ : str = self.initializer_range lowercase_ : int = is_vqa @classmethod def _snake_case ( cls , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **__SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" lowercase_ : Tuple = copy.deepcopy(self.__dict__ ) lowercase_ : Any = self.text_config.to_dict() lowercase_ : Optional[Any] = self.vision_config.to_dict() lowercase_ : Optional[int] = self.__class__.model_type return output
93
1
'''simple docstring''' import math import time from typing import Dict, List, Optional from torch.utils.data import Dataset from transformers import SeqaSeqTrainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput, speed_metrics if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class lowerCAmelCase__ ( lowerCamelCase_ ): def __init__( self , *__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , **__SCREAMING_SNAKE_CASE ): """simple docstring""" super().__init__(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = eval_examples lowercase_ : Tuple = post_process_function def _snake_case ( self , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = "eval" , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : Optional[int] = gen_kwargs.copy() lowercase_ : List[str] = ( gen_kwargs['''max_length'''] if gen_kwargs.get('''max_length''' ) is not None else self.args.generation_max_length ) lowercase_ : str = ( gen_kwargs['''num_beams'''] if gen_kwargs.get('''num_beams''' ) is not None else self.args.generation_num_beams ) lowercase_ : Dict = gen_kwargs lowercase_ : List[Any] = self.eval_dataset if eval_dataset is None else eval_dataset lowercase_ : List[str] = self.get_eval_dataloader(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. lowercase_ : Union[str, Any] = self.compute_metrics lowercase_ : Optional[int] = None lowercase_ : Tuple = time.time() lowercase_ : Tuple = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: lowercase_ : str = eval_loop( __SCREAMING_SNAKE_CASE , description='''Evaluation''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=__SCREAMING_SNAKE_CASE , metric_key_prefix=__SCREAMING_SNAKE_CASE , ) finally: lowercase_ : Any = compute_metrics lowercase_ : Any = self.args.eval_batch_size * self.args.world_size if F'''{metric_key_prefix}_jit_compilation_time''' in output.metrics: start_time += output.metrics[F'''{metric_key_prefix}_jit_compilation_time'''] output.metrics.update( speed_metrics( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save: # Only the main node write the results by default lowercase_ : Optional[Any] = self.post_process_function(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = self.compute_metrics(__SCREAMING_SNAKE_CASE ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F'''{metric_key_prefix}_''' ): lowercase_ : List[Any] = metrics.pop(__SCREAMING_SNAKE_CASE ) metrics.update(output.metrics ) else: lowercase_ : List[Any] = output.metrics if self.args.should_log: # Only the main node log the results by default self.log(__SCREAMING_SNAKE_CASE ) if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report() ) lowercase_ : List[Any] = self.callback_handler.on_evaluate(self.args , self.state , self.control , __SCREAMING_SNAKE_CASE ) return metrics def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE = "test" , **__SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Union[str, Any] = gen_kwargs.copy() lowercase_ : Tuple = self.get_test_dataloader(__SCREAMING_SNAKE_CASE ) # Temporarily disable metric computation, we will do it in the loop here. lowercase_ : Optional[Any] = self.compute_metrics lowercase_ : Optional[int] = None lowercase_ : List[Any] = time.time() lowercase_ : int = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: lowercase_ : Tuple = eval_loop( __SCREAMING_SNAKE_CASE , description='''Prediction''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=__SCREAMING_SNAKE_CASE , metric_key_prefix=__SCREAMING_SNAKE_CASE , ) finally: lowercase_ : Any = compute_metrics lowercase_ : Tuple = self.args.eval_batch_size * self.args.world_size if F'''{metric_key_prefix}_jit_compilation_time''' in output.metrics: start_time += output.metrics[F'''{metric_key_prefix}_jit_compilation_time'''] output.metrics.update( speed_metrics( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is None or self.compute_metrics is None: return output lowercase_ : Any = self.post_process_function(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , '''predict''' ) lowercase_ : str = self.compute_metrics(__SCREAMING_SNAKE_CASE ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F'''{metric_key_prefix}_''' ): lowercase_ : Optional[int] = metrics.pop(__SCREAMING_SNAKE_CASE ) metrics.update(output.metrics ) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=__SCREAMING_SNAKE_CASE )
93
'''simple docstring''' from math import isqrt, loga def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : Any = [True] * max_number for i in range(2 , isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2 , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase_ : Optional[Any] = False return [i for i in range(2 , __SCREAMING_SNAKE_CASE ) if is_prime[i]] def snake_case_ ( __SCREAMING_SNAKE_CASE : int = 800800 , __SCREAMING_SNAKE_CASE : int = 800800 ): """simple docstring""" lowercase_ : Union[str, Any] = degree * loga(__SCREAMING_SNAKE_CASE ) lowercase_ : Any = int(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = calculate_prime_numbers(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = 0 lowercase_ : List[Any] = 0 lowercase_ : Union[str, Any] = len(__SCREAMING_SNAKE_CASE ) - 1 while left < right: while ( prime_numbers[right] * loga(prime_numbers[left] ) + prime_numbers[left] * loga(prime_numbers[right] ) > upper_bound ): right -= 1 hybrid_integers_count += right - left left += 1 return hybrid_integers_count if __name__ == "__main__": print(f"""{solution() = }""")
93
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices _lowercase : List[str] = logging.get_logger(__name__) _lowercase : Any = { "shi-labs/dinat-mini-in1k-224": "https://huggingface.co/shi-labs/dinat-mini-in1k-224/resolve/main/config.json", # See all Dinat models at https://huggingface.co/models?filter=dinat } class lowerCAmelCase__ ( lowerCamelCase_ , lowerCamelCase_ ): lowerCAmelCase_ = '''dinat''' lowerCAmelCase_ = { '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self , __SCREAMING_SNAKE_CASE=4 , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=64 , __SCREAMING_SNAKE_CASE=[3, 4, 6, 5] , __SCREAMING_SNAKE_CASE=[2, 4, 8, 16] , __SCREAMING_SNAKE_CASE=7 , __SCREAMING_SNAKE_CASE=[[1, 8, 1], [1, 4, 1, 4], [1, 2, 1, 2, 1, 2], [1, 1, 1, 1, 1]] , __SCREAMING_SNAKE_CASE=3.0 , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE="gelu" , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=1E-5 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) lowercase_ : List[Any] = patch_size lowercase_ : Any = num_channels lowercase_ : str = embed_dim lowercase_ : List[str] = depths lowercase_ : Any = len(__SCREAMING_SNAKE_CASE ) lowercase_ : Dict = num_heads lowercase_ : Tuple = kernel_size lowercase_ : Union[str, Any] = dilations lowercase_ : List[str] = mlp_ratio lowercase_ : Any = qkv_bias lowercase_ : List[str] = hidden_dropout_prob lowercase_ : Union[str, Any] = attention_probs_dropout_prob lowercase_ : Tuple = drop_path_rate lowercase_ : List[str] = hidden_act lowercase_ : List[Any] = layer_norm_eps lowercase_ : int = initializer_range # we set the hidden_size attribute in order to make Dinat work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model lowercase_ : List[Any] = int(embed_dim * 2 ** (len(__SCREAMING_SNAKE_CASE ) - 1) ) lowercase_ : Dict = layer_scale_init_value lowercase_ : Optional[int] = ['''stem'''] + [F'''stage{idx}''' for idx in range(1 , len(__SCREAMING_SNAKE_CASE ) + 1 )] lowercase_ , lowercase_ : Optional[Any] = get_aligned_output_features_output_indices( out_features=__SCREAMING_SNAKE_CASE , out_indices=__SCREAMING_SNAKE_CASE , stage_names=self.stage_names )
93
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices _lowercase : int = logging.get_logger(__name__) _lowercase : List[Any] = { "shi-labs/nat-mini-in1k-224": "https://huggingface.co/shi-labs/nat-mini-in1k-224/resolve/main/config.json", # See all Nat models at https://huggingface.co/models?filter=nat } class lowerCAmelCase__ ( lowerCamelCase_ , lowerCamelCase_ ): lowerCAmelCase_ = '''nat''' lowerCAmelCase_ = { '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self , __SCREAMING_SNAKE_CASE=4 , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=64 , __SCREAMING_SNAKE_CASE=[3, 4, 6, 5] , __SCREAMING_SNAKE_CASE=[2, 4, 8, 16] , __SCREAMING_SNAKE_CASE=7 , __SCREAMING_SNAKE_CASE=3.0 , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE="gelu" , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=1E-5 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = patch_size lowercase_ : List[Any] = num_channels lowercase_ : str = embed_dim lowercase_ : List[str] = depths lowercase_ : str = len(__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = num_heads lowercase_ : int = kernel_size lowercase_ : Union[str, Any] = mlp_ratio lowercase_ : Optional[int] = qkv_bias lowercase_ : List[Any] = hidden_dropout_prob lowercase_ : Optional[int] = attention_probs_dropout_prob lowercase_ : List[Any] = drop_path_rate lowercase_ : List[Any] = hidden_act lowercase_ : int = layer_norm_eps lowercase_ : int = initializer_range # we set the hidden_size attribute in order to make Nat work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model lowercase_ : Dict = int(embed_dim * 2 ** (len(__SCREAMING_SNAKE_CASE ) - 1) ) lowercase_ : Tuple = layer_scale_init_value lowercase_ : Union[str, Any] = ['''stem'''] + [F'''stage{idx}''' for idx in range(1 , len(__SCREAMING_SNAKE_CASE ) + 1 )] lowercase_ , lowercase_ : int = get_aligned_output_features_output_indices( out_features=__SCREAMING_SNAKE_CASE , out_indices=__SCREAMING_SNAKE_CASE , stage_names=self.stage_names )
93
1
'''simple docstring''' import argparse import json import os import tensorstore as ts import torch from flax import serialization from flax.traverse_util import flatten_dict, unflatten_dict from tensorflow.io import gfile from transformers.modeling_utils import dtype_byte_size from transformers.models.switch_transformers.convert_switch_transformers_original_flax_checkpoint_to_pytorch import ( rename_keys, ) from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME from transformers.utils.hub import convert_file_size_to_int def snake_case_ ( __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" if flax_key_tuple[-1] == "kernel" and flax_tensor.ndim == 3: # expert layer lowercase_ : str = flax_key_tuple[:-1] + ('''weight''',) lowercase_ : Tuple = torch.permute(__SCREAMING_SNAKE_CASE , (0, 2, 1) ) elif flax_key_tuple[-1] == "kernel" and ".".join(__SCREAMING_SNAKE_CASE ): # linear layer lowercase_ : List[str] = flax_key_tuple[:-1] + ('''weight''',) lowercase_ : Union[str, Any] = flax_tensor.T elif flax_key_tuple[-1] in ["scale", "embedding"]: lowercase_ : Optional[int] = flax_key_tuple[:-1] + ('''weight''',) return flax_key_tuple, flax_tensor def snake_case_ ( __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" if "metadata" in layer: lowercase_ : List[Any] = layer.split('''metadata''' ) lowercase_ : Dict = ''''''.join(split_layer[0] )[:-1] lowercase_ : Any = [tuple(('''metadata''' + split_layer[1]).split('''/''' ) )] elif "kvstore" in layer: lowercase_ : List[Any] = layer.split('''kvstore''' ) lowercase_ : int = ''''''.join(split_layer[0] )[:-1] lowercase_ : str = [tuple(('''kvstore''' + split_layer[1]).split('''/''' ) )] else: lowercase_ : List[Any] = layer.split('''/''' ) lowercase_ : Optional[Any] = '''/'''.join(split_layer[:-1] ) lowercase_ : Union[str, Any] = (split_layer[-1],) if "kvstore/path" in layer: lowercase_ : str = F'''{switch_checkpoint_path}/{checkpoint_info[layer]}''' elif "kvstore/driver" in layer: lowercase_ : List[Any] = '''file''' else: lowercase_ : Dict = checkpoint_info[layer] return curr_real_layer_name, split_layer, content def snake_case_ ( __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" lowercase_ : Optional[Any] = rename_keys(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = {} for k, v in current_block.items(): lowercase_ : Any = v lowercase_ : Any = new_current_block torch.save(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : str = WEIGHTS_NAME ): """simple docstring""" lowercase_ : Dict = convert_file_size_to_int(__SCREAMING_SNAKE_CASE ) lowercase_ : List[str] = [] lowercase_ : Dict = {} lowercase_ : List[str] = 0 lowercase_ : str = 0 os.makedirs(__SCREAMING_SNAKE_CASE , exist_ok=__SCREAMING_SNAKE_CASE ) with gfile.GFile(switch_checkpoint_path + '''/checkpoint''' , '''rb''' ) as fp: lowercase_ : Optional[int] = serialization.msgpack_restore(fp.read() )['''optimizer''']['''target'''] lowercase_ : int = flatten_dict(__SCREAMING_SNAKE_CASE , sep='''/''' ) lowercase_ : Tuple = {} for layer in checkpoint_info.keys(): lowercase_ , lowercase_ , lowercase_ : Dict = get_key_and_tensorstore_dict( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if curr_real_layer_name in all_layers: lowercase_ : List[Any] = content else: lowercase_ : Tuple = {split_layer[-1]: content} for key in all_layers.keys(): # open tensorstore file lowercase_ : List[str] = ts.open(unflatten_dict(all_layers[key] ) ).result().read().result() lowercase_ : Tuple = torch.tensor(__SCREAMING_SNAKE_CASE ) lowercase_ : int = raw_weights.numel() * dtype_byte_size(raw_weights.dtype ) # use the renaming pattern from the small conversion scripts lowercase_ , lowercase_ : Tuple = rename_base_flax_keys(tuple(key.split('''/''' ) ) , __SCREAMING_SNAKE_CASE ) lowercase_ : Any = '''/'''.join(__SCREAMING_SNAKE_CASE ) # If this weight is going to tip up over the maximal size, we split. if current_block_size + weight_size > max_shard_size: lowercase_ : Optional[Any] = os.path.join( __SCREAMING_SNAKE_CASE , weights_name.replace('''.bin''' , F'''-{len(__SCREAMING_SNAKE_CASE )+1:05d}-of-???.bin''' ) ) rename_and_save_block(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) sharded_state_dicts.append(current_block.keys() ) del current_block lowercase_ : List[Any] = {} lowercase_ : Any = 0 lowercase_ : Union[str, Any] = raw_weights.to(getattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) current_block_size += weight_size total_size += weight_size # Add the last block lowercase_ : Dict = os.path.join(__SCREAMING_SNAKE_CASE , weights_name.replace('''.bin''' , F'''-{len(__SCREAMING_SNAKE_CASE )+1:05d}-of-???.bin''' ) ) rename_and_save_block(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) sharded_state_dicts.append(current_block.keys() ) # If we only have one shard, we return it if len(__SCREAMING_SNAKE_CASE ) == 1: return {weights_name: sharded_state_dicts[0]}, None # Otherwise, let's build the index lowercase_ : Optional[Any] = {} lowercase_ : List[str] = {} for idx, shard in enumerate(__SCREAMING_SNAKE_CASE ): lowercase_ : str = weights_name.replace( '''.bin''' , F'''-{idx+1:05d}-of-{len(__SCREAMING_SNAKE_CASE ):05d}.bin''' ) # len(sharded_state_dicts):05d} lowercase_ : Any = os.path.join(__SCREAMING_SNAKE_CASE , weights_name.replace('''.bin''' , F'''-{idx+1:05d}-of-???.bin''' ) ) os.rename(__SCREAMING_SNAKE_CASE , os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) lowercase_ : int = shard for key in shard: lowercase_ : int = shard_file # Add the metadata lowercase_ : Tuple = {'''total_size''': total_size} lowercase_ : Any = {'''metadata''': metadata, '''weight_map''': weight_map} with open(os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) , '''w''' , encoding='''utf-8''' ) as f: lowercase_ : Dict = json.dumps(__SCREAMING_SNAKE_CASE , indent=2 , sort_keys=__SCREAMING_SNAKE_CASE ) + '''\n''' f.write(__SCREAMING_SNAKE_CASE ) return metadata, index if __name__ == "__main__": _lowercase : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--switch_t5x_checkpoint_path", default="/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128/checkpoint_634600", type=str, required=False, help="Path to a directory containing a folder per layer. Follows the original Google format.", ) parser.add_argument("--max_shard_size", default="10GB", required=False, help="Max shard size") parser.add_argument("--dtype", default="bfloat16", type=str, required=False, help="dtype of the saved model") parser.add_argument( "--pytorch_dump_folder_path", default="/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128-converted", type=str, required=False, help="Path to the output pytorch model.", ) _lowercase : Optional[Any] = parser.parse_args() shard_on_the_fly( args.switch_tax_checkpoint_path, args.pytorch_dump_folder_path, args.max_shard_size, args.dtype, ) def snake_case_ ( ): """simple docstring""" from transformers import SwitchTransformersConfig, SwitchTransformersForConditionalGeneration, TaTokenizer lowercase_ : Optional[Any] = SwitchTransformersConfig.from_pretrained('''google/switch-base-8''' ) config.save_pretrained('''/home/arthur_huggingface_co/transformers/switch_converted''' ) lowercase_ : str = SwitchTransformersForConditionalGeneration.from_pretrained( '''/home/arthur_huggingface_co/transformers/switch_converted''' , device_map='''auto''' ) lowercase_ : Optional[int] = TaTokenizer.from_pretrained('''t5-small''' ) lowercase_ : List[str] = '''A <extra_id_0> walks into a bar a orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.''' lowercase_ : Dict = tokenizer(__SCREAMING_SNAKE_CASE , return_tensors='''pt''' ).input_ids lowercase_ : Optional[Any] = model.generate(__SCREAMING_SNAKE_CASE , decoder_start_token_id=0 ) print(tokenizer.decode(out[0] ) )
93
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _lowercase : Union[str, Any] = { "configuration_mask2former": [ "MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "Mask2FormerConfig", ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : Optional[int] = ["Mask2FormerImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : str = [ "MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "Mask2FormerForUniversalSegmentation", "Mask2FormerModel", "Mask2FormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_maskaformer import MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskaFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_maskaformer import MaskaFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskaformer import ( MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskaFormerForUniversalSegmentation, MaskaFormerModel, MaskaFormerPreTrainedModel, ) else: import sys _lowercase : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure)
93
1
'''simple docstring''' from argparse import ArgumentParser from .add_new_model import AddNewModelCommand from .add_new_model_like import AddNewModelLikeCommand from .convert import ConvertCommand from .download import DownloadCommand from .env import EnvironmentCommand from .lfs import LfsCommands from .pt_to_tf import PTtoTFCommand from .run import RunCommand from .serving import ServeCommand from .user import UserCommands def snake_case_ ( ): """simple docstring""" lowercase_ : List[Any] = ArgumentParser('''Transformers CLI tool''' , usage='''transformers-cli <command> [<args>]''' ) lowercase_ : Any = parser.add_subparsers(help='''transformers-cli command helpers''' ) # Register commands ConvertCommand.register_subcommand(__SCREAMING_SNAKE_CASE ) DownloadCommand.register_subcommand(__SCREAMING_SNAKE_CASE ) EnvironmentCommand.register_subcommand(__SCREAMING_SNAKE_CASE ) RunCommand.register_subcommand(__SCREAMING_SNAKE_CASE ) ServeCommand.register_subcommand(__SCREAMING_SNAKE_CASE ) UserCommands.register_subcommand(__SCREAMING_SNAKE_CASE ) AddNewModelCommand.register_subcommand(__SCREAMING_SNAKE_CASE ) AddNewModelLikeCommand.register_subcommand(__SCREAMING_SNAKE_CASE ) LfsCommands.register_subcommand(__SCREAMING_SNAKE_CASE ) PTtoTFCommand.register_subcommand(__SCREAMING_SNAKE_CASE ) # Let's go lowercase_ : Optional[int] = parser.parse_args() if not hasattr(__SCREAMING_SNAKE_CASE , '''func''' ): parser.print_help() exit(1 ) # Run lowercase_ : List[Any] = args.func(__SCREAMING_SNAKE_CASE ) service.run() if __name__ == "__main__": main()
93
'''simple docstring''' import unittest from knapsack import greedy_knapsack as kp class lowerCAmelCase__ ( unittest.TestCase ): def _snake_case ( self ): """simple docstring""" lowercase_ : List[str] = [10, 20, 30, 40, 50, 60] lowercase_ : Optional[Any] = [2, 4, 6, 8, 10, 12] lowercase_ : Union[str, Any] = 1_00 self.assertEqual(kp.calc_profit(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) , 2_10 ) def _snake_case ( self ): """simple docstring""" self.assertRaisesRegex(__SCREAMING_SNAKE_CASE , '''max_weight must greater than zero.''' ) def _snake_case ( self ): """simple docstring""" self.assertRaisesRegex(__SCREAMING_SNAKE_CASE , '''Weight can not be negative.''' ) def _snake_case ( self ): """simple docstring""" self.assertRaisesRegex(__SCREAMING_SNAKE_CASE , '''Profit can not be negative.''' ) def _snake_case ( self ): """simple docstring""" self.assertRaisesRegex(__SCREAMING_SNAKE_CASE , '''max_weight must greater than zero.''' ) def _snake_case ( self ): """simple docstring""" self.assertRaisesRegex( __SCREAMING_SNAKE_CASE , '''The length of profit and weight must be same.''' ) if __name__ == "__main__": unittest.main()
93
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 from .tokenization_gpta import GPTaTokenizer if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation _lowercase : Union[str, Any] = logging.get_logger(__name__) _lowercase : Optional[Any] = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"} _lowercase : str = { "vocab_file": { "gpt2": "https://huggingface.co/gpt2/resolve/main/vocab.json", "gpt2-medium": "https://huggingface.co/gpt2-medium/resolve/main/vocab.json", "gpt2-large": "https://huggingface.co/gpt2-large/resolve/main/vocab.json", "gpt2-xl": "https://huggingface.co/gpt2-xl/resolve/main/vocab.json", "distilgpt2": "https://huggingface.co/distilgpt2/resolve/main/vocab.json", }, "merges_file": { "gpt2": "https://huggingface.co/gpt2/resolve/main/merges.txt", "gpt2-medium": "https://huggingface.co/gpt2-medium/resolve/main/merges.txt", "gpt2-large": "https://huggingface.co/gpt2-large/resolve/main/merges.txt", "gpt2-xl": "https://huggingface.co/gpt2-xl/resolve/main/merges.txt", "distilgpt2": "https://huggingface.co/distilgpt2/resolve/main/merges.txt", }, "tokenizer_file": { "gpt2": "https://huggingface.co/gpt2/resolve/main/tokenizer.json", "gpt2-medium": "https://huggingface.co/gpt2-medium/resolve/main/tokenizer.json", "gpt2-large": "https://huggingface.co/gpt2-large/resolve/main/tokenizer.json", "gpt2-xl": "https://huggingface.co/gpt2-xl/resolve/main/tokenizer.json", "distilgpt2": "https://huggingface.co/distilgpt2/resolve/main/tokenizer.json", }, } _lowercase : Dict = { "gpt2": 1_0_2_4, "gpt2-medium": 1_0_2_4, "gpt2-large": 1_0_2_4, "gpt2-xl": 1_0_2_4, "distilgpt2": 1_0_2_4, } class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = VOCAB_FILES_NAMES lowerCAmelCase_ = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase_ = ['''input_ids''', '''attention_mask'''] lowerCAmelCase_ = GPTaTokenizer def __init__( self , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE="<|endoftext|>" , __SCREAMING_SNAKE_CASE="<|endoftext|>" , __SCREAMING_SNAKE_CASE="<|endoftext|>" , __SCREAMING_SNAKE_CASE=False , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" super().__init__( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , tokenizer_file=__SCREAMING_SNAKE_CASE , unk_token=__SCREAMING_SNAKE_CASE , bos_token=__SCREAMING_SNAKE_CASE , eos_token=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) lowercase_ : int = kwargs.pop('''add_bos_token''' , __SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get('''add_prefix_space''' , __SCREAMING_SNAKE_CASE ) != add_prefix_space: lowercase_ : Optional[Any] = getattr(__SCREAMING_SNAKE_CASE , pre_tok_state.pop('''type''' ) ) lowercase_ : List[Any] = add_prefix_space lowercase_ : Optional[int] = pre_tok_class(**__SCREAMING_SNAKE_CASE ) lowercase_ : List[str] = add_prefix_space def _snake_case ( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : List[str] = kwargs.get('''is_split_into_words''' , __SCREAMING_SNAKE_CASE ) 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(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def _snake_case ( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : str = kwargs.get('''is_split_into_words''' , __SCREAMING_SNAKE_CASE ) 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(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" lowercase_ : str = self._tokenizer.model.save(__SCREAMING_SNAKE_CASE , name=__SCREAMING_SNAKE_CASE ) return tuple(__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Any = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE ) + [self.eos_token_id] ) if len(__SCREAMING_SNAKE_CASE ) > self.model_max_length: lowercase_ : Union[str, Any] = input_ids[-self.model_max_length :] return input_ids
93
'''simple docstring''' import argparse import copy def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[int] ): """simple docstring""" lowercase_ : List[Any] = {} with open(__SCREAMING_SNAKE_CASE ) as f: for line in f: if line.split()[0] not in dict_of_neighbours: lowercase_ : Union[str, Any] = [] _list.append([line.split()[1], line.split()[2]] ) lowercase_ : str = _list else: dict_of_neighbours[line.split()[0]].append( [line.split()[1], line.split()[2]] ) if line.split()[1] not in dict_of_neighbours: lowercase_ : Optional[int] = [] _list.append([line.split()[0], line.split()[2]] ) lowercase_ : Dict = _list else: dict_of_neighbours[line.split()[1]].append( [line.split()[0], line.split()[2]] ) return dict_of_neighbours def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE ) as f: lowercase_ : List[str] = f.read(1 ) lowercase_ : Optional[int] = start_node lowercase_ : Any = [] lowercase_ : List[str] = start_node lowercase_ : Optional[Any] = 0 while visiting not in first_solution: lowercase_ : Any = 10000 for k in dict_of_neighbours[visiting]: if int(k[1] ) < int(__SCREAMING_SNAKE_CASE ) and k[0] not in first_solution: lowercase_ : List[Any] = k[1] lowercase_ : List[Any] = k[0] first_solution.append(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = distance_of_first_solution + int(__SCREAMING_SNAKE_CASE ) lowercase_ : int = best_node first_solution.append(__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = 0 for k in dict_of_neighbours[first_solution[-2]]: if k[0] == start_node: break position += 1 lowercase_ : Optional[Any] = ( distance_of_first_solution + int(dict_of_neighbours[first_solution[-2]][position][1] ) - 10000 ) return first_solution, distance_of_first_solution def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" lowercase_ : Tuple = [] for n in solution[1:-1]: lowercase_ : List[str] = solution.index(__SCREAMING_SNAKE_CASE ) for kn in solution[1:-1]: lowercase_ : Any = solution.index(__SCREAMING_SNAKE_CASE ) if n == kn: continue lowercase_ : Dict = copy.deepcopy(__SCREAMING_SNAKE_CASE ) lowercase_ : Dict = kn lowercase_ : List[Any] = n lowercase_ : str = 0 for k in _tmp[:-1]: lowercase_ : Tuple = _tmp[_tmp.index(__SCREAMING_SNAKE_CASE ) + 1] for i in dict_of_neighbours[k]: if i[0] == next_node: lowercase_ : Optional[Any] = distance + int(i[1] ) _tmp.append(__SCREAMING_SNAKE_CASE ) if _tmp not in neighborhood_of_solution: neighborhood_of_solution.append(_tmp ) lowercase_ : Union[str, Any] = 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 snake_case_ ( __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" lowercase_ : Optional[int] = 1 lowercase_ : List[str] = first_solution lowercase_ : Dict = [] lowercase_ : List[str] = distance_of_first_solution lowercase_ : Optional[Any] = solution while count <= iters: lowercase_ : int = find_neighborhood(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : Any = 0 lowercase_ : Dict = neighborhood[index_of_best_solution] lowercase_ : Optional[Any] = len(__SCREAMING_SNAKE_CASE ) - 1 lowercase_ : Tuple = False while not found: lowercase_ : Optional[int] = 0 while i < len(__SCREAMING_SNAKE_CASE ): if best_solution[i] != solution[i]: lowercase_ : Tuple = best_solution[i] lowercase_ : Optional[int] = solution[i] break lowercase_ : 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] ) lowercase_ : Tuple = True lowercase_ : Optional[int] = best_solution[:-1] lowercase_ : Optional[Any] = neighborhood[index_of_best_solution][best_cost_index] if cost < best_cost: lowercase_ : Optional[Any] = cost lowercase_ : int = solution else: lowercase_ : Any = index_of_best_solution + 1 lowercase_ : Any = neighborhood[index_of_best_solution] if len(__SCREAMING_SNAKE_CASE ) >= size: tabu_list.pop(0 ) lowercase_ : List[Any] = count + 1 return best_solution_ever, best_cost def snake_case_ ( __SCREAMING_SNAKE_CASE : List[str]=None ): """simple docstring""" lowercase_ : Any = generate_neighbours(args.File ) lowercase_ , lowercase_ : Union[str, Any] = generate_first_solution( args.File , __SCREAMING_SNAKE_CASE ) lowercase_ , lowercase_ : Optional[int] = 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__": _lowercase : Any = 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())
93
1
'''simple docstring''' import importlib.util import os import platform from argparse import ArgumentParser import huggingface_hub from .. import __version__ as version from ..utils import ( is_accelerate_available, is_flax_available, is_safetensors_available, is_tf_available, is_torch_available, ) from . import BaseTransformersCLICommand def snake_case_ ( __SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" return EnvironmentCommand() def snake_case_ ( __SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" return EnvironmentCommand(args.accelerate_config_file ) class lowerCAmelCase__ ( lowerCamelCase_ ): @staticmethod def _snake_case ( __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : List[str] = parser.add_parser('''env''' ) download_parser.set_defaults(func=__SCREAMING_SNAKE_CASE ) download_parser.add_argument( '''--accelerate-config_file''' , default=__SCREAMING_SNAKE_CASE , help='''The accelerate config file to use for the default values in the launching script.''' , ) download_parser.set_defaults(func=__SCREAMING_SNAKE_CASE ) def __init__( self , __SCREAMING_SNAKE_CASE , *__SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Optional[int] = accelerate_config_file def _snake_case ( self ): """simple docstring""" lowercase_ : Any = '''not installed''' if is_safetensors_available(): import safetensors lowercase_ : int = safetensors.__version__ elif importlib.util.find_spec('''safetensors''' ) is not None: import safetensors lowercase_ : Any = F'''{safetensors.__version__} but is ignored because of PyTorch version too old.''' lowercase_ : Optional[Any] = '''not installed''' lowercase_ : str = '''not found''' if is_accelerate_available(): import accelerate from accelerate.commands.config import default_config_file, load_config_from_file lowercase_ : Union[str, Any] = accelerate.__version__ # Get the default from the config file. if self._accelerate_config_file is not None or os.path.isfile(__SCREAMING_SNAKE_CASE ): lowercase_ : List[Any] = load_config_from_file(self._accelerate_config_file ).to_dict() lowercase_ : List[str] = ( '''\n'''.join([F'''\t- {prop}: {val}''' for prop, val in accelerate_config.items()] ) if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else F'''\t{accelerate_config}''' ) lowercase_ : str = '''not installed''' lowercase_ : Any = '''NA''' if is_torch_available(): import torch lowercase_ : str = torch.__version__ lowercase_ : Dict = torch.cuda.is_available() lowercase_ : Optional[int] = '''not installed''' lowercase_ : str = '''NA''' if is_tf_available(): import tensorflow as tf lowercase_ : int = tf.__version__ try: # deprecated in v2.1 lowercase_ : List[Any] = tf.test.is_gpu_available() except AttributeError: # returns list of devices, convert to bool lowercase_ : Dict = bool(tf.config.list_physical_devices('''GPU''' ) ) lowercase_ : List[str] = '''not installed''' lowercase_ : Dict = '''not installed''' lowercase_ : List[Any] = '''not installed''' lowercase_ : Optional[Any] = '''NA''' if is_flax_available(): import flax import jax import jaxlib lowercase_ : str = flax.__version__ lowercase_ : List[str] = jax.__version__ lowercase_ : int = jaxlib.__version__ lowercase_ : Any = jax.lib.xla_bridge.get_backend().platform lowercase_ : Dict = { '''`transformers` version''': version, '''Platform''': platform.platform(), '''Python version''': platform.python_version(), '''Huggingface_hub version''': huggingface_hub.__version__, '''Safetensors version''': F'''{safetensors_version}''', '''Accelerate version''': F'''{accelerate_version}''', '''Accelerate config''': F'''{accelerate_config_str}''', '''PyTorch version (GPU?)''': F'''{pt_version} ({pt_cuda_available})''', '''Tensorflow version (GPU?)''': F'''{tf_version} ({tf_cuda_available})''', '''Flax version (CPU?/GPU?/TPU?)''': F'''{flax_version} ({jax_backend})''', '''Jax version''': F'''{jax_version}''', '''JaxLib version''': F'''{jaxlib_version}''', '''Using GPU in script?''': '''<fill in>''', '''Using distributed or parallel set-up in script?''': '''<fill in>''', } print('''\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n''' ) print(self.format_dict(__SCREAMING_SNAKE_CASE ) ) return info @staticmethod def _snake_case ( __SCREAMING_SNAKE_CASE ): """simple docstring""" return "\n".join([F'''- {prop}: {val}''' for prop, val in d.items()] ) + "\n"
93
'''simple docstring''' import unittest from transformers import is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device if is_torch_available(): from transformers import AutoModelForSeqaSeqLM, AutoTokenizer @require_torch @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( unittest.TestCase ): @slow def _snake_case ( self ): """simple docstring""" lowercase_ : Dict = AutoModelForSeqaSeqLM.from_pretrained('''google/mt5-small''' , return_dict=__SCREAMING_SNAKE_CASE ).to(__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = AutoTokenizer.from_pretrained('''google/mt5-small''' ) lowercase_ : int = tokenizer('''Hello there''' , return_tensors='''pt''' ).input_ids lowercase_ : Union[str, Any] = tokenizer('''Hi I am''' , return_tensors='''pt''' ).input_ids lowercase_ : Union[str, Any] = model(input_ids.to(__SCREAMING_SNAKE_CASE ) , labels=labels.to(__SCREAMING_SNAKE_CASE ) ).loss lowercase_ : int = -(labels.shape[-1] * loss.item()) lowercase_ : Any = -84.9_127 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1E-4 )
93
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowercase : List[Any] = { "configuration_nllb_moe": [ "NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP", "NllbMoeConfig", ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : Optional[Any] = [ "NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST", "NllbMoeForConditionalGeneration", "NllbMoeModel", "NllbMoePreTrainedModel", "NllbMoeTop2Router", "NllbMoeSparseMLP", ] if TYPE_CHECKING: from .configuration_nllb_moe import ( NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP, NllbMoeConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_nllb_moe import ( NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST, NllbMoeForConditionalGeneration, NllbMoeModel, NllbMoePreTrainedModel, NllbMoeSparseMLP, NllbMoeTopaRouter, ) else: import sys _lowercase : Optional[int] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
93
'''simple docstring''' def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : str ): """simple docstring""" lowercase_ : List[str] = len(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = [] for i in range(len(__SCREAMING_SNAKE_CASE ) - pat_len + 1 ): lowercase_ : Tuple = True for j in range(__SCREAMING_SNAKE_CASE ): if s[i + j] != pattern[j]: lowercase_ : List[str] = False break if match_found: position.append(__SCREAMING_SNAKE_CASE ) return position if __name__ == "__main__": assert naive_pattern_search("ABCDEFG", "DE") == [3] print(naive_pattern_search("ABAAABCDBBABCDDEBCABC", "ABC"))
93
1
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging _lowercase : Union[str, Any] = logging.get_logger(__name__) _lowercase : Dict = { "microsoft/git-base": "https://huggingface.co/microsoft/git-base/resolve/main/config.json", } class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = '''git_vision_model''' def __init__( self , __SCREAMING_SNAKE_CASE=7_68 , __SCREAMING_SNAKE_CASE=30_72 , __SCREAMING_SNAKE_CASE=12 , __SCREAMING_SNAKE_CASE=12 , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=2_24 , __SCREAMING_SNAKE_CASE=16 , __SCREAMING_SNAKE_CASE="quick_gelu" , __SCREAMING_SNAKE_CASE=1E-5 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=0.02 , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) lowercase_ : Any = hidden_size lowercase_ : Any = intermediate_size lowercase_ : Any = num_hidden_layers lowercase_ : Tuple = num_attention_heads lowercase_ : Union[str, Any] = num_channels lowercase_ : Tuple = patch_size lowercase_ : Union[str, Any] = image_size lowercase_ : int = initializer_range lowercase_ : Optional[Any] = attention_dropout lowercase_ : List[str] = layer_norm_eps lowercase_ : List[str] = hidden_act @classmethod def _snake_case ( cls , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" cls._set_token_in_kwargs(__SCREAMING_SNAKE_CASE ) lowercase_ , lowercase_ : Union[str, Any] = cls.get_config_dict(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) # get the vision config dict if we are loading from GITConfig if config_dict.get('''model_type''' ) == "git": lowercase_ : Optional[Any] = config_dict['''vision_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'''You are using a model of type {config_dict['model_type']} to instantiate a model of type ''' F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = '''git''' def __init__( self , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=3_05_22 , __SCREAMING_SNAKE_CASE=7_68 , __SCREAMING_SNAKE_CASE=6 , __SCREAMING_SNAKE_CASE=12 , __SCREAMING_SNAKE_CASE=30_72 , __SCREAMING_SNAKE_CASE="gelu" , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=10_24 , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=1E-1_2 , __SCREAMING_SNAKE_CASE=0 , __SCREAMING_SNAKE_CASE="absolute" , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=1_01 , __SCREAMING_SNAKE_CASE=1_02 , __SCREAMING_SNAKE_CASE=None , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" super().__init__(bos_token_id=__SCREAMING_SNAKE_CASE , eos_token_id=__SCREAMING_SNAKE_CASE , pad_token_id=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) if vision_config is None: lowercase_ : str = {} logger.info('''vision_config is None. initializing the GitVisionConfig with default values.''' ) lowercase_ : List[Any] = GitVisionConfig(**__SCREAMING_SNAKE_CASE ) lowercase_ : Dict = vocab_size lowercase_ : int = hidden_size lowercase_ : Tuple = num_hidden_layers lowercase_ : int = num_attention_heads lowercase_ : List[str] = hidden_act lowercase_ : Optional[int] = intermediate_size lowercase_ : Optional[int] = hidden_dropout_prob lowercase_ : Optional[Any] = attention_probs_dropout_prob lowercase_ : str = max_position_embeddings lowercase_ : Tuple = initializer_range lowercase_ : List[str] = layer_norm_eps lowercase_ : int = position_embedding_type lowercase_ : Dict = use_cache lowercase_ : List[str] = tie_word_embeddings lowercase_ : Union[str, Any] = num_image_with_embedding lowercase_ : int = bos_token_id lowercase_ : int = eos_token_id def _snake_case ( self ): """simple docstring""" lowercase_ : str = copy.deepcopy(self.__dict__ ) lowercase_ : Optional[int] = self.vision_config.to_dict() lowercase_ : List[str] = self.__class__.model_type return output
93
'''simple docstring''' import importlib import inspect import json import os import re import shutil import sys from pathlib import Path from typing import Dict, Optional, Union from urllib import request from huggingface_hub import HfFolder, cached_download, hf_hub_download, model_info from packaging import version from .. import __version__ from . import DIFFUSERS_DYNAMIC_MODULE_NAME, HF_MODULES_CACHE, logging _lowercase : Optional[Any] = ( "https://raw.githubusercontent.com/huggingface/diffusers/{revision}/examples/community/{pipeline}.py" ) _lowercase : Tuple = logging.get_logger(__name__) # pylint: disable=invalid-name def snake_case_ ( ): """simple docstring""" lowercase_ : Tuple = '''https://pypi.org/pypi/diffusers/json''' lowercase_ : Tuple = json.loads(request.urlopen(__SCREAMING_SNAKE_CASE ).read() )['''releases'''].keys() return sorted(__SCREAMING_SNAKE_CASE , key=lambda __SCREAMING_SNAKE_CASE : version.Version(__SCREAMING_SNAKE_CASE ) ) def snake_case_ ( ): """simple docstring""" if HF_MODULES_CACHE in sys.path: return sys.path.append(__SCREAMING_SNAKE_CASE ) os.makedirs(__SCREAMING_SNAKE_CASE , exist_ok=__SCREAMING_SNAKE_CASE ) lowercase_ : List[Any] = Path(__SCREAMING_SNAKE_CASE ) / '''__init__.py''' if not init_path.exists(): init_path.touch() def snake_case_ ( __SCREAMING_SNAKE_CASE : Union[str, os.PathLike] ): """simple docstring""" init_hf_modules() lowercase_ : Optional[int] = Path(__SCREAMING_SNAKE_CASE ) / name # If the parent module does not exist yet, recursively create it. if not dynamic_module_path.parent.exists(): create_dynamic_module(dynamic_module_path.parent ) os.makedirs(__SCREAMING_SNAKE_CASE , exist_ok=__SCREAMING_SNAKE_CASE ) lowercase_ : str = dynamic_module_path / '''__init__.py''' if not init_path.exists(): init_path.touch() def snake_case_ ( __SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE , '''r''' , encoding='''utf-8''' ) as f: lowercase_ : int = f.read() # Imports of the form `import .xxx` lowercase_ : List[Any] = re.findall('''^\s*import\s+\.(\S+)\s*$''' , __SCREAMING_SNAKE_CASE , flags=re.MULTILINE ) # Imports of the form `from .xxx import yyy` relative_imports += re.findall('''^\s*from\s+\.(\S+)\s+import''' , __SCREAMING_SNAKE_CASE , flags=re.MULTILINE ) # Unique-ify return list(set(__SCREAMING_SNAKE_CASE ) ) def snake_case_ ( __SCREAMING_SNAKE_CASE : str ): """simple docstring""" lowercase_ : int = False lowercase_ : Any = [module_file] lowercase_ : Dict = [] # Let's recurse through all relative imports while not no_change: lowercase_ : Dict = [] for f in files_to_check: new_imports.extend(get_relative_imports(__SCREAMING_SNAKE_CASE ) ) lowercase_ : Union[str, Any] = Path(__SCREAMING_SNAKE_CASE ).parent lowercase_ : Optional[int] = [str(module_path / m ) for m in new_imports] lowercase_ : str = [f for f in new_import_files if f not in all_relative_imports] lowercase_ : int = [F'''{f}.py''' for f in new_import_files] lowercase_ : Optional[Any] = len(__SCREAMING_SNAKE_CASE ) == 0 all_relative_imports.extend(__SCREAMING_SNAKE_CASE ) return all_relative_imports def snake_case_ ( __SCREAMING_SNAKE_CASE : Any ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE , '''r''' , encoding='''utf-8''' ) as f: lowercase_ : Union[str, Any] = f.read() # Imports of the form `import xxx` lowercase_ : Any = re.findall('''^\s*import\s+(\S+)\s*$''' , __SCREAMING_SNAKE_CASE , flags=re.MULTILINE ) # Imports of the form `from xxx import yyy` imports += re.findall('''^\s*from\s+(\S+)\s+import''' , __SCREAMING_SNAKE_CASE , flags=re.MULTILINE ) # Only keep the top-level module lowercase_ : List[str] = [imp.split('''.''' )[0] for imp in imports if not imp.startswith('''.''' )] # Unique-ify and test we got them all lowercase_ : Any = list(set(__SCREAMING_SNAKE_CASE ) ) lowercase_ : Optional[Any] = [] for imp in imports: try: importlib.import_module(__SCREAMING_SNAKE_CASE ) except ImportError: missing_packages.append(__SCREAMING_SNAKE_CASE ) if len(__SCREAMING_SNAKE_CASE ) > 0: raise ImportError( '''This modeling file requires the following packages that were not found in your environment: ''' F'''{', '.join(__SCREAMING_SNAKE_CASE )}. Run `pip install {' '.join(__SCREAMING_SNAKE_CASE )}`''' ) return get_relative_imports(__SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" lowercase_ : List[Any] = module_path.replace(os.path.sep , '''.''' ) lowercase_ : Any = importlib.import_module(__SCREAMING_SNAKE_CASE ) if class_name is None: return find_pipeline_class(__SCREAMING_SNAKE_CASE ) return getattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" from ..pipelines import DiffusionPipeline lowercase_ : int = dict(inspect.getmembers(__SCREAMING_SNAKE_CASE , inspect.isclass ) ) lowercase_ : Optional[Any] = None for cls_name, cls in cls_members.items(): if ( cls_name != DiffusionPipeline.__name__ and issubclass(cls , __SCREAMING_SNAKE_CASE ) and cls.__module__.split('''.''' )[0] != "diffusers" ): if pipeline_class is not None: raise ValueError( F'''Multiple classes that inherit from {DiffusionPipeline.__name__} have been found:''' F''' {pipeline_class.__name__}, and {cls_name}. Please make sure to define only one in''' F''' {loaded_module}.''' ) lowercase_ : List[Any] = cls return pipeline_class def snake_case_ ( __SCREAMING_SNAKE_CASE : Union[str, os.PathLike] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Optional[Union[str, os.PathLike]] = None , __SCREAMING_SNAKE_CASE : bool = False , __SCREAMING_SNAKE_CASE : bool = False , __SCREAMING_SNAKE_CASE : Optional[Dict[str, str]] = None , __SCREAMING_SNAKE_CASE : Optional[Union[bool, str]] = None , __SCREAMING_SNAKE_CASE : Optional[str] = None , __SCREAMING_SNAKE_CASE : bool = False , ): """simple docstring""" lowercase_ : Dict = str(__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if os.path.isfile(__SCREAMING_SNAKE_CASE ): lowercase_ : Dict = module_file_or_url lowercase_ : int = '''local''' elif pretrained_model_name_or_path.count('''/''' ) == 0: lowercase_ : Optional[int] = get_diffusers_versions() # cut ".dev0" lowercase_ : List[Any] = '''v''' + '''.'''.join(__version__.split('''.''' )[:3] ) # retrieve github version that matches if revision is None: lowercase_ : List[str] = latest_version if latest_version[1:] in available_versions else '''main''' logger.info(F'''Defaulting to latest_version: {revision}.''' ) elif revision in available_versions: lowercase_ : List[str] = F'''v{revision}''' elif revision == "main": lowercase_ : Optional[Any] = revision else: raise ValueError( F'''`custom_revision`: {revision} does not exist. Please make sure to choose one of''' F''' {', '.join(available_versions + ['main'] )}.''' ) # community pipeline on GitHub lowercase_ : Tuple = COMMUNITY_PIPELINES_URL.format(revision=__SCREAMING_SNAKE_CASE , pipeline=__SCREAMING_SNAKE_CASE ) try: lowercase_ : Optional[Any] = cached_download( __SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE , force_download=__SCREAMING_SNAKE_CASE , proxies=__SCREAMING_SNAKE_CASE , resume_download=__SCREAMING_SNAKE_CASE , local_files_only=__SCREAMING_SNAKE_CASE , use_auth_token=__SCREAMING_SNAKE_CASE , ) lowercase_ : Tuple = '''git''' lowercase_ : Tuple = pretrained_model_name_or_path + '''.py''' except EnvironmentError: logger.error(F'''Could not locate the {module_file} inside {pretrained_model_name_or_path}.''' ) raise else: try: # Load from URL or cache if already cached lowercase_ : str = hf_hub_download( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE , force_download=__SCREAMING_SNAKE_CASE , proxies=__SCREAMING_SNAKE_CASE , resume_download=__SCREAMING_SNAKE_CASE , local_files_only=__SCREAMING_SNAKE_CASE , use_auth_token=__SCREAMING_SNAKE_CASE , ) lowercase_ : Optional[Any] = os.path.join('''local''' , '''--'''.join(pretrained_model_name_or_path.split('''/''' ) ) ) except EnvironmentError: logger.error(F'''Could not locate the {module_file} inside {pretrained_model_name_or_path}.''' ) raise # Check we have all the requirements in our environment lowercase_ : Tuple = check_imports(__SCREAMING_SNAKE_CASE ) # Now we move the module inside our cached dynamic modules. lowercase_ : str = DIFFUSERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule create_dynamic_module(__SCREAMING_SNAKE_CASE ) lowercase_ : Any = Path(__SCREAMING_SNAKE_CASE ) / full_submodule if submodule == "local" or submodule == "git": # We always copy local files (we could hash the file to see if there was a change, and give them the name of # that hash, to only copy when there is a modification but it seems overkill for now). # The only reason we do the copy is to avoid putting too many folders in sys.path. shutil.copy(__SCREAMING_SNAKE_CASE , submodule_path / module_file ) for module_needed in modules_needed: lowercase_ : Union[str, Any] = F'''{module_needed}.py''' shutil.copy(os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) , submodule_path / module_needed ) else: # Get the commit hash # TODO: we will get this info in the etag soon, so retrieve it from there and not here. if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase_ : Tuple = use_auth_token elif use_auth_token is True: lowercase_ : List[Any] = HfFolder.get_token() else: lowercase_ : Optional[Any] = None lowercase_ : Optional[int] = model_info(__SCREAMING_SNAKE_CASE , revision=__SCREAMING_SNAKE_CASE , token=__SCREAMING_SNAKE_CASE ).sha # The module file will end up being placed in a subfolder with the git hash of the repo. This way we get the # benefit of versioning. lowercase_ : int = submodule_path / commit_hash lowercase_ : Tuple = full_submodule + os.path.sep + commit_hash create_dynamic_module(__SCREAMING_SNAKE_CASE ) if not (submodule_path / module_file).exists(): shutil.copy(__SCREAMING_SNAKE_CASE , submodule_path / module_file ) # Make sure we also have every file with relative for module_needed in modules_needed: if not (submodule_path / module_needed).exists(): get_cached_module_file( __SCREAMING_SNAKE_CASE , F'''{module_needed}.py''' , cache_dir=__SCREAMING_SNAKE_CASE , force_download=__SCREAMING_SNAKE_CASE , resume_download=__SCREAMING_SNAKE_CASE , proxies=__SCREAMING_SNAKE_CASE , use_auth_token=__SCREAMING_SNAKE_CASE , revision=__SCREAMING_SNAKE_CASE , local_files_only=__SCREAMING_SNAKE_CASE , ) return os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Union[str, os.PathLike] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Optional[str] = None , __SCREAMING_SNAKE_CASE : Optional[Union[str, os.PathLike]] = None , __SCREAMING_SNAKE_CASE : bool = False , __SCREAMING_SNAKE_CASE : bool = False , __SCREAMING_SNAKE_CASE : Optional[Dict[str, str]] = None , __SCREAMING_SNAKE_CASE : Optional[Union[bool, str]] = None , __SCREAMING_SNAKE_CASE : Optional[str] = None , __SCREAMING_SNAKE_CASE : bool = False , **__SCREAMING_SNAKE_CASE : Optional[Any] , ): """simple docstring""" lowercase_ : Optional[Any] = get_cached_module_file( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE , force_download=__SCREAMING_SNAKE_CASE , resume_download=__SCREAMING_SNAKE_CASE , proxies=__SCREAMING_SNAKE_CASE , use_auth_token=__SCREAMING_SNAKE_CASE , revision=__SCREAMING_SNAKE_CASE , local_files_only=__SCREAMING_SNAKE_CASE , ) return get_class_in_module(__SCREAMING_SNAKE_CASE , final_module.replace('''.py''' , '''''' ) )
93
1
'''simple docstring''' # Lint as: python3 # pylint: enable=line-too-long # pylint: disable=g-import-not-at-top,g-bad-import-order,wrong-import-position _lowercase : str = "2.13.1" import platform import pyarrow from packaging import version if version.parse(platform.python_version()) < version.parse("3.7"): raise ImportWarning( "To use `datasets`, Python>=3.7 is required, and the current version of Python doesn't match this condition." ) if version.parse(pyarrow.__version__).major < 8: raise ImportWarning( "To use `datasets`, the module `pyarrow>=8.0.0` is required, and the current version of `pyarrow` doesn't match this condition.\n" "If you are running this in a Google Colab, you should probably just restart the runtime to use the right version of `pyarrow`." ) del platform del pyarrow del version from .arrow_dataset import Dataset from .arrow_reader import ReadInstruction from .builder import ArrowBasedBuilder, BeamBasedBuilder, BuilderConfig, DatasetBuilder, GeneratorBasedBuilder from .combine import concatenate_datasets, interleave_datasets from .dataset_dict import DatasetDict, IterableDatasetDict from .download import * from .features import * from .fingerprint import disable_caching, enable_caching, is_caching_enabled, set_caching_enabled from .info import DatasetInfo, MetricInfo from .inspect import ( get_dataset_config_info, get_dataset_config_names, get_dataset_infos, get_dataset_split_names, inspect_dataset, inspect_metric, list_datasets, list_metrics, ) from .iterable_dataset import IterableDataset from .load import load_dataset, load_dataset_builder, load_from_disk, load_metric from .metric import Metric from .splits import ( NamedSplit, NamedSplitAll, Split, SplitBase, SplitDict, SplitGenerator, SplitInfo, SubSplitInfo, percent, ) from .tasks import * from .utils import * from .utils import logging # deprecated modules from datasets import arrow_dataset as _arrow_dataset # isort:skip from datasets import utils as _utils # isort:skip from datasets.utils import download_manager as _deprecated_download_manager # isort:skip _lowercase : str = concatenate_datasets _lowercase : Any = DownloadConfig _lowercase : Tuple = DownloadManager _lowercase : Dict = DownloadMode _lowercase : Union[str, Any] = DownloadConfig _lowercase : str = DownloadMode _lowercase : Optional[int] = DownloadManager del _arrow_dataset, _utils, _deprecated_download_manager
93
'''simple docstring''' import re import tempfile from pathlib import Path import pytest import yaml from datasets.utils.readme import ReadMe # @pytest.fixture # def example_yaml_structure(): _lowercase : Union[str, Any] = yaml.safe_load( "\\nname: \"\"\nallow_empty: false\nallow_empty_text: true\nsubsections:\n - name: \"Dataset Card for X\" # First-level markdown heading\n allow_empty: false\n allow_empty_text: true\n subsections:\n - name: \"Table of Contents\"\n allow_empty: false\n allow_empty_text: false\n subsections: null\n - name: \"Dataset Description\"\n allow_empty: false\n allow_empty_text: false\n subsections:\n - name: \"Dataset Summary\"\n allow_empty: false\n allow_empty_text: false\n subsections: null\n - name: \"Supported Tasks and Leaderboards\"\n allow_empty: true\n allow_empty_text: true\n subsections: null\n - name: Languages\n allow_empty: false\n allow_empty_text: true\n subsections: null\n" ) _lowercase : int = { "name": "root", "text": "", "is_empty_text": True, "subsections": [ { "name": "Dataset Card for My Dataset", "text": "", "is_empty_text": True, "subsections": [ {"name": "Table of Contents", "text": "Some text here.", "is_empty_text": False, "subsections": []}, { "name": "Dataset Description", "text": "Some text here.", "is_empty_text": False, "subsections": [ { "name": "Dataset Summary", "text": "Some text here.", "is_empty_text": False, "subsections": [], }, { "name": "Supported Tasks and Leaderboards", "text": "", "is_empty_text": True, "subsections": [], }, {"name": "Languages", "text": "Language Text", "is_empty_text": False, "subsections": []}, ], }, ], } ], } _lowercase : Optional[Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Union[str, Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n#### Extra Ignored Subsection\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Any = { "name": "root", "text": "", "is_empty_text": True, "subsections": [ { "name": "Dataset Card for My Dataset", "text": "", "is_empty_text": True, "subsections": [ {"name": "Table of Contents", "text": "Some text here.", "is_empty_text": False, "subsections": []}, { "name": "Dataset Description", "text": "Some text here.", "is_empty_text": False, "subsections": [ { "name": "Dataset Summary", "text": "Some text here.", "is_empty_text": False, "subsections": [ { "name": "Extra Ignored Subsection", "text": "", "is_empty_text": True, "subsections": [], } ], }, { "name": "Supported Tasks and Leaderboards", "text": "", "is_empty_text": True, "subsections": [], }, {"name": "Languages", "text": "Language Text", "is_empty_text": False, "subsections": []}, ], }, ], } ], } _lowercase : str = "\\n---\n---\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : List[str] = ( "The following issues were found for the README at `{path}`:\n-\tEmpty YAML markers are present in the README." ) _lowercase : Tuple = "\\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Optional[Any] = ( "The following issues were found for the README at `{path}`:\n-\tNo YAML markers are present in the README." ) _lowercase : Tuple = "\\n---\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Optional[int] = "The following issues were found for the README at `{path}`:\n-\tOnly the start of YAML tags present in the README." _lowercase : List[Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Optional[Any] = "The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Summary` but it is empty.\n-\tExpected some text in section `Dataset Summary` but it is empty (text in subsections are ignored)." _lowercase : Optional[int] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n" _lowercase : Union[str, Any] = "The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Card for My Dataset` but it is empty.\n-\tSection `Dataset Card for My Dataset` expected the following subsections: `Table of Contents`, `Dataset Description`. Found 'None'." _lowercase : Union[str, Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Languages\nLanguage Text\n" _lowercase : int = "The following issues were found for the README at `{path}`:\n-\tSection `Dataset Description` is missing subsection: `Supported Tasks and Leaderboards`." _lowercase : List[Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\n" _lowercase : int = "The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Languages` but it is empty." _lowercase : List[str] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : str = "The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README." _lowercase : Dict = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n# Dataset Card My Dataset\n" _lowercase : List[str] = "The following issues were found for the README at `{path}`:\n-\tThe README has several first-level headings: `Dataset Card for My Dataset`, `Dataset Card My Dataset`. Only one heading is expected. Skipping further validation for this README." _lowercase : str = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Union[str, Any] = "The following issues were found for the README at `{path}`:\n-\tNo first-level heading starting with `Dataset Card for` found in README. Skipping further validation for this README." _lowercase : List[Any] = "" _lowercase : Optional[Any] = "The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README.\n-\tNo YAML markers are present in the README." _lowercase : List[Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Optional[Any] = "The following issues were found while parsing the README at `{path}`:\n-\tMultiple sections with the same heading `Dataset Card for My Dataset` have been found. Please keep only one of these sections." @pytest.mark.parametrize( '''readme_md, expected_dict''' , [ (README_CORRECT, CORRECT_DICT), (README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" assert ReadMe.from_string(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).to_dict() == expected_dict @pytest.mark.parametrize( '''readme_md, expected_error''' , [ (README_NO_YAML, EXPECTED_ERROR_README_NO_YAML), (README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML), (README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML), (README_EMPTY, EXPECTED_ERROR_README_EMPTY), (README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION), (README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL), (README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION), (README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT), (README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL), (README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL), (README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" with pytest.raises(__SCREAMING_SNAKE_CASE , match=re.escape(expected_error.format(path='''root''' ) ) ): lowercase_ : Optional[int] = ReadMe.from_string(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) readme.validate() @pytest.mark.parametrize( '''readme_md, expected_error''' , [ (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" with pytest.raises(__SCREAMING_SNAKE_CASE , match=re.escape(expected_error.format(path='''root''' ) ) ): ReadMe.from_string(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( '''readme_md,''' , [ (README_MULTIPLE_SAME_HEADING_1), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Any ): """simple docstring""" ReadMe.from_string(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , suppress_parsing_errors=__SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( '''readme_md, expected_dict''' , [ (README_CORRECT, CORRECT_DICT), (README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : str ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: lowercase_ : Optional[int] = Path(__SCREAMING_SNAKE_CASE ) / '''README.md''' with open(__SCREAMING_SNAKE_CASE , '''w+''' ) as readme_file: readme_file.write(__SCREAMING_SNAKE_CASE ) lowercase_ : Any = ReadMe.from_readme(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).to_dict() assert out["name"] == path assert out["text"] == "" assert out["is_empty_text"] assert out["subsections"] == expected_dict["subsections"] @pytest.mark.parametrize( '''readme_md, expected_error''' , [ (README_NO_YAML, EXPECTED_ERROR_README_NO_YAML), (README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML), (README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML), (README_EMPTY, EXPECTED_ERROR_README_EMPTY), (README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION), (README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL), (README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION), (README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT), (README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL), (README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL), (README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: lowercase_ : str = Path(__SCREAMING_SNAKE_CASE ) / '''README.md''' with open(__SCREAMING_SNAKE_CASE , '''w+''' ) as readme_file: readme_file.write(__SCREAMING_SNAKE_CASE ) lowercase_ : List[str] = expected_error.format(path=__SCREAMING_SNAKE_CASE ) with pytest.raises(__SCREAMING_SNAKE_CASE , match=re.escape(__SCREAMING_SNAKE_CASE ) ): lowercase_ : int = ReadMe.from_readme(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) readme.validate() @pytest.mark.parametrize( '''readme_md, expected_error''' , [ (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: lowercase_ : Dict = Path(__SCREAMING_SNAKE_CASE ) / '''README.md''' with open(__SCREAMING_SNAKE_CASE , '''w+''' ) as readme_file: readme_file.write(__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = expected_error.format(path=__SCREAMING_SNAKE_CASE ) with pytest.raises(__SCREAMING_SNAKE_CASE , match=re.escape(__SCREAMING_SNAKE_CASE ) ): ReadMe.from_readme(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( '''readme_md,''' , [ (README_MULTIPLE_SAME_HEADING_1), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: lowercase_ : Optional[int] = Path(__SCREAMING_SNAKE_CASE ) / '''README.md''' with open(__SCREAMING_SNAKE_CASE , '''w+''' ) as readme_file: readme_file.write(__SCREAMING_SNAKE_CASE ) ReadMe.from_readme(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , suppress_parsing_errors=__SCREAMING_SNAKE_CASE )
93
1
'''simple docstring''' class lowerCAmelCase__ : def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Any = name lowercase_ : List[Any] = value lowercase_ : Tuple = weight def __repr__( self ): """simple docstring""" return F'''{self.__class__.__name__}({self.name}, {self.value}, {self.weight})''' def _snake_case ( self ): """simple docstring""" return self.value def _snake_case ( self ): """simple docstring""" return self.name def _snake_case ( self ): """simple docstring""" return self.weight def _snake_case ( self ): """simple docstring""" return self.value / self.weight def snake_case_ ( __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : List[Any] ): """simple docstring""" lowercase_ : List[Any] = [] for i in range(len(__SCREAMING_SNAKE_CASE ) ): menu.append(Things(name[i] , value[i] , weight[i] ) ) return menu def snake_case_ ( __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : str ): """simple docstring""" lowercase_ : Dict = sorted(__SCREAMING_SNAKE_CASE , key=__SCREAMING_SNAKE_CASE , reverse=__SCREAMING_SNAKE_CASE ) lowercase_ : int = [] lowercase_ , lowercase_ : Optional[Any] = 0.0, 0.0 for i in range(len(__SCREAMING_SNAKE_CASE ) ): if (total_cost + items_copy[i].get_weight()) <= max_cost: result.append(items_copy[i] ) total_cost += items_copy[i].get_weight() total_value += items_copy[i].get_value() return (result, total_value) def snake_case_ ( ): """simple docstring""" if __name__ == "__main__": import doctest doctest.testmod()
93
'''simple docstring''' import math import time from typing import Dict, List, Optional from torch.utils.data import Dataset from transformers import SeqaSeqTrainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput, speed_metrics if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class lowerCAmelCase__ ( lowerCamelCase_ ): def __init__( self , *__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , **__SCREAMING_SNAKE_CASE ): """simple docstring""" super().__init__(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = eval_examples lowercase_ : Tuple = post_process_function def _snake_case ( self , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = "eval" , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : Optional[int] = gen_kwargs.copy() lowercase_ : List[str] = ( gen_kwargs['''max_length'''] if gen_kwargs.get('''max_length''' ) is not None else self.args.generation_max_length ) lowercase_ : str = ( gen_kwargs['''num_beams'''] if gen_kwargs.get('''num_beams''' ) is not None else self.args.generation_num_beams ) lowercase_ : Dict = gen_kwargs lowercase_ : List[Any] = self.eval_dataset if eval_dataset is None else eval_dataset lowercase_ : List[str] = self.get_eval_dataloader(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. lowercase_ : Union[str, Any] = self.compute_metrics lowercase_ : Optional[int] = None lowercase_ : Tuple = time.time() lowercase_ : Tuple = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: lowercase_ : str = eval_loop( __SCREAMING_SNAKE_CASE , description='''Evaluation''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=__SCREAMING_SNAKE_CASE , metric_key_prefix=__SCREAMING_SNAKE_CASE , ) finally: lowercase_ : Any = compute_metrics lowercase_ : Any = self.args.eval_batch_size * self.args.world_size if F'''{metric_key_prefix}_jit_compilation_time''' in output.metrics: start_time += output.metrics[F'''{metric_key_prefix}_jit_compilation_time'''] output.metrics.update( speed_metrics( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save: # Only the main node write the results by default lowercase_ : Optional[Any] = self.post_process_function(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = self.compute_metrics(__SCREAMING_SNAKE_CASE ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F'''{metric_key_prefix}_''' ): lowercase_ : List[Any] = metrics.pop(__SCREAMING_SNAKE_CASE ) metrics.update(output.metrics ) else: lowercase_ : List[Any] = output.metrics if self.args.should_log: # Only the main node log the results by default self.log(__SCREAMING_SNAKE_CASE ) if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report() ) lowercase_ : List[Any] = self.callback_handler.on_evaluate(self.args , self.state , self.control , __SCREAMING_SNAKE_CASE ) return metrics def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE = "test" , **__SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Union[str, Any] = gen_kwargs.copy() lowercase_ : Tuple = self.get_test_dataloader(__SCREAMING_SNAKE_CASE ) # Temporarily disable metric computation, we will do it in the loop here. lowercase_ : Optional[Any] = self.compute_metrics lowercase_ : Optional[int] = None lowercase_ : List[Any] = time.time() lowercase_ : int = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: lowercase_ : Tuple = eval_loop( __SCREAMING_SNAKE_CASE , description='''Prediction''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=__SCREAMING_SNAKE_CASE , metric_key_prefix=__SCREAMING_SNAKE_CASE , ) finally: lowercase_ : Any = compute_metrics lowercase_ : Tuple = self.args.eval_batch_size * self.args.world_size if F'''{metric_key_prefix}_jit_compilation_time''' in output.metrics: start_time += output.metrics[F'''{metric_key_prefix}_jit_compilation_time'''] output.metrics.update( speed_metrics( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is None or self.compute_metrics is None: return output lowercase_ : Any = self.post_process_function(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , '''predict''' ) lowercase_ : str = self.compute_metrics(__SCREAMING_SNAKE_CASE ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F'''{metric_key_prefix}_''' ): lowercase_ : Optional[int] = metrics.pop(__SCREAMING_SNAKE_CASE ) metrics.update(output.metrics ) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=__SCREAMING_SNAKE_CASE )
93
1
'''simple docstring''' import unittest import numpy as np import torch from diffusers import DDIMPipeline, DDIMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow, torch_device from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class lowerCAmelCase__ ( lowerCamelCase_ , unittest.TestCase ): lowerCAmelCase_ = DDIMPipeline lowerCAmelCase_ = UNCONDITIONAL_IMAGE_GENERATION_PARAMS lowerCAmelCase_ = PipelineTesterMixin.required_optional_params - { '''num_images_per_prompt''', '''latents''', '''callback''', '''callback_steps''', } lowerCAmelCase_ = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS lowerCAmelCase_ = False def _snake_case ( self ): """simple docstring""" torch.manual_seed(0 ) lowercase_ : int = 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''') , ) lowercase_ : List[str] = DDIMScheduler() lowercase_ : Dict = {'''unet''': unet, '''scheduler''': scheduler} return components def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=0 ): """simple docstring""" if str(__SCREAMING_SNAKE_CASE ).startswith('''mps''' ): lowercase_ : List[str] = torch.manual_seed(__SCREAMING_SNAKE_CASE ) else: lowercase_ : List[Any] = torch.Generator(device=__SCREAMING_SNAKE_CASE ).manual_seed(__SCREAMING_SNAKE_CASE ) lowercase_ : Dict = { '''batch_size''': 1, '''generator''': generator, '''num_inference_steps''': 2, '''output_type''': '''numpy''', } return inputs def _snake_case ( self ): """simple docstring""" lowercase_ : int = '''cpu''' lowercase_ : Optional[int] = self.get_dummy_components() lowercase_ : Union[str, Any] = self.pipeline_class(**__SCREAMING_SNAKE_CASE ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) lowercase_ : Dict = self.get_dummy_inputs(__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = pipe(**__SCREAMING_SNAKE_CASE ).images lowercase_ : int = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 32, 32, 3) ) lowercase_ : Union[str, Any] = np.array( [1.0_0_0E0_0, 5.7_1_7E-0_1, 4.7_1_7E-0_1, 1.0_0_0E0_0, 0.0_0_0E0_0, 1.0_0_0E0_0, 3.0_0_0E-0_4, 0.0_0_0E0_0, 9.0_0_0E-0_4] ) lowercase_ : Tuple = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(__SCREAMING_SNAKE_CASE , 1E-3 ) def _snake_case ( self ): """simple docstring""" super().test_dict_tuple_outputs_equivalent(expected_max_difference=3E-3 ) def _snake_case ( self ): """simple docstring""" super().test_save_load_local(expected_max_difference=3E-3 ) def _snake_case ( self ): """simple docstring""" super().test_save_load_optional_components(expected_max_difference=3E-3 ) def _snake_case ( self ): """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): def _snake_case ( self ): """simple docstring""" lowercase_ : Optional[int] = '''google/ddpm-cifar10-32''' lowercase_ : Union[str, Any] = UNetaDModel.from_pretrained(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = DDIMScheduler() lowercase_ : Union[str, Any] = DDIMPipeline(unet=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE ) ddim.to(__SCREAMING_SNAKE_CASE ) ddim.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) lowercase_ : int = torch.manual_seed(0 ) lowercase_ : Tuple = ddim(generator=__SCREAMING_SNAKE_CASE , eta=0.0 , output_type='''numpy''' ).images lowercase_ : Union[str, Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) lowercase_ : Union[str, Any] = np.array([0.1_723, 0.1_617, 0.1_600, 0.1_626, 0.1_497, 0.1_513, 0.1_505, 0.1_442, 0.1_453] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _snake_case ( self ): """simple docstring""" lowercase_ : Optional[Any] = '''google/ddpm-ema-bedroom-256''' lowercase_ : Dict = UNetaDModel.from_pretrained(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = DDIMScheduler.from_pretrained(__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = DDIMPipeline(unet=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE ) ddpm.to(__SCREAMING_SNAKE_CASE ) ddpm.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) lowercase_ : str = torch.manual_seed(0 ) lowercase_ : str = ddpm(generator=__SCREAMING_SNAKE_CASE , output_type='''numpy''' ).images lowercase_ : Optional[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 2_56, 2_56, 3) lowercase_ : Tuple = np.array([0.0_060, 0.0_201, 0.0_344, 0.0_024, 0.0_018, 0.0_002, 0.0_022, 0.0_000, 0.0_069] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
93
'''simple docstring''' from pathlib import Path from typing import List from transformers import is_torch_available, is_vision_available from transformers.testing_utils import get_tests_dir, is_tool_test from transformers.tools.agent_types import AGENT_TYPE_MAPPING, AgentAudio, AgentImage, AgentText if is_torch_available(): import torch if is_vision_available(): from PIL import Image _lowercase : List[str] = ["text", "image", "audio"] def snake_case_ ( __SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" lowercase_ : int = [] for input_type in input_types: if input_type == "text": inputs.append('''Text input''' ) elif input_type == "image": inputs.append( Image.open(Path(get_tests_dir('''fixtures/tests_samples/COCO''' ) ) / '''000000039769.png''' ).resize((512, 512) ) ) elif input_type == "audio": inputs.append(torch.ones(3000 ) ) elif isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): inputs.append(create_inputs(__SCREAMING_SNAKE_CASE ) ) else: raise ValueError(F'''Invalid type requested: {input_type}''' ) return inputs def snake_case_ ( __SCREAMING_SNAKE_CASE : List ): """simple docstring""" lowercase_ : Optional[Any] = [] for output in outputs: if isinstance(__SCREAMING_SNAKE_CASE , (str, AgentText) ): output_types.append('''text''' ) elif isinstance(__SCREAMING_SNAKE_CASE , (Image.Image, AgentImage) ): output_types.append('''image''' ) elif isinstance(__SCREAMING_SNAKE_CASE , (torch.Tensor, AgentAudio) ): output_types.append('''audio''' ) else: raise ValueError(F'''Invalid output: {output}''' ) return output_types @is_tool_test class lowerCAmelCase__ : def _snake_case ( self ): """simple docstring""" self.assertTrue(hasattr(self.tool , '''inputs''' ) ) self.assertTrue(hasattr(self.tool , '''outputs''' ) ) lowercase_ : Optional[Any] = self.tool.inputs for _input in inputs: if isinstance(_input , __SCREAMING_SNAKE_CASE ): for __input in _input: self.assertTrue(__input in authorized_types ) else: self.assertTrue(_input in authorized_types ) lowercase_ : int = self.tool.outputs for _output in outputs: self.assertTrue(_output in authorized_types ) def _snake_case ( self ): """simple docstring""" lowercase_ : int = create_inputs(self.tool.inputs ) lowercase_ : Tuple = self.tool(*__SCREAMING_SNAKE_CASE ) # There is a single output if len(self.tool.outputs ) == 1: lowercase_ : Any = [outputs] self.assertListEqual(output_types(__SCREAMING_SNAKE_CASE ) , self.tool.outputs ) def _snake_case ( self ): """simple docstring""" self.assertTrue(hasattr(self.tool , '''description''' ) ) self.assertTrue(hasattr(self.tool , '''default_checkpoint''' ) ) self.assertTrue(self.tool.description.startswith('''This is a tool that''' ) ) def _snake_case ( self ): """simple docstring""" lowercase_ : int = create_inputs(self.tool.inputs ) lowercase_ : int = self.tool(*__SCREAMING_SNAKE_CASE ) if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase_ : Optional[Any] = [outputs] self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , len(self.tool.outputs ) ) for output, output_type in zip(__SCREAMING_SNAKE_CASE , self.tool.outputs ): lowercase_ : Optional[int] = AGENT_TYPE_MAPPING[output_type] self.assertTrue(isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) def _snake_case ( self ): """simple docstring""" lowercase_ : Dict = create_inputs(self.tool.inputs ) lowercase_ : int = [] for _input, input_type in zip(__SCREAMING_SNAKE_CASE , self.tool.inputs ): if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): _inputs.append([AGENT_TYPE_MAPPING[_input_type](_input ) for _input_type in input_type] ) else: _inputs.append(AGENT_TYPE_MAPPING[input_type](_input ) ) # Should not raise an error lowercase_ : Optional[Any] = self.tool(*__SCREAMING_SNAKE_CASE ) if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase_ : Dict = [outputs] self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , len(self.tool.outputs ) )
93
1
'''simple docstring''' import unittest from transformers import DonutProcessor _lowercase : int = "naver-clova-ix/donut-base" class lowerCAmelCase__ ( unittest.TestCase ): def _snake_case ( self ): """simple docstring""" lowercase_ : List[str] = DonutProcessor.from_pretrained(__SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" lowercase_ : int = { '''name''': '''John Doe''', '''age''': '''99''', '''city''': '''Atlanta''', '''state''': '''GA''', '''zip''': '''30301''', '''phone''': '''123-4567''', '''nicknames''': [{'''nickname''': '''Johnny'''}, {'''nickname''': '''JD'''}], } lowercase_ : Optional[int] = ( '''<s_name>John Doe</s_name><s_age>99</s_age><s_city>Atlanta</s_city>''' '''<s_state>GA</s_state><s_zip>30301</s_zip><s_phone>123-4567</s_phone>''' '''<s_nicknames><s_nickname>Johnny</s_nickname>''' '''<sep/><s_nickname>JD</s_nickname></s_nicknames>''' ) lowercase_ : str = self.processor.tokenajson(__SCREAMING_SNAKE_CASE ) self.assertDictEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
93
'''simple docstring''' # DISCLAIMER: This file is strongly influenced by https://github.com/ermongroup/ddim from dataclasses import dataclass from typing import Optional, Tuple, Union import flax import jax import jax.numpy as jnp from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils_flax import ( CommonSchedulerState, FlaxKarrasDiffusionSchedulers, FlaxSchedulerMixin, FlaxSchedulerOutput, add_noise_common, get_velocity_common, ) @flax.struct.dataclass class lowerCAmelCase__ : lowerCAmelCase_ = 42 # setable values lowerCAmelCase_ = 42 lowerCAmelCase_ = 42 lowerCAmelCase_ = None @classmethod def _snake_case ( cls , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" return cls(common=__SCREAMING_SNAKE_CASE , init_noise_sigma=__SCREAMING_SNAKE_CASE , timesteps=__SCREAMING_SNAKE_CASE ) @dataclass class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = 42 class lowerCAmelCase__ ( lowerCamelCase_ , lowerCamelCase_ ): lowerCAmelCase_ = [e.name for e in FlaxKarrasDiffusionSchedulers] lowerCAmelCase_ = 42 @property def _snake_case ( self ): """simple docstring""" return True @register_to_config def __init__( self , __SCREAMING_SNAKE_CASE = 10_00 , __SCREAMING_SNAKE_CASE = 0.0_001 , __SCREAMING_SNAKE_CASE = 0.02 , __SCREAMING_SNAKE_CASE = "linear" , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = "fixed_small" , __SCREAMING_SNAKE_CASE = True , __SCREAMING_SNAKE_CASE = "epsilon" , __SCREAMING_SNAKE_CASE = jnp.floataa , ): """simple docstring""" lowercase_ : Dict = dtype def _snake_case ( self , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" if common is None: lowercase_ : Tuple = CommonSchedulerState.create(self ) # standard deviation of the initial noise distribution lowercase_ : Union[str, Any] = jnp.array(1.0 , dtype=self.dtype ) lowercase_ : List[Any] = jnp.arange(0 , self.config.num_train_timesteps ).round()[::-1] return DDPMSchedulerState.create( common=__SCREAMING_SNAKE_CASE , init_noise_sigma=__SCREAMING_SNAKE_CASE , timesteps=__SCREAMING_SNAKE_CASE , ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" return sample def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = () ): """simple docstring""" lowercase_ : Optional[Any] = self.config.num_train_timesteps // num_inference_steps # creates integer timesteps by multiplying by ratio # rounding to avoid issues when num_inference_step is power of 3 lowercase_ : int = (jnp.arange(0 , __SCREAMING_SNAKE_CASE ) * step_ratio).round()[::-1] return state.replace( num_inference_steps=__SCREAMING_SNAKE_CASE , timesteps=__SCREAMING_SNAKE_CASE , ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None ): """simple docstring""" lowercase_ : List[Any] = state.common.alphas_cumprod[t] lowercase_ : str = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) ) # For t > 0, compute predicted variance βt (see formula (6) and (7) from https://arxiv.org/pdf/2006.11239.pdf) # and sample from it to get previous sample # x_{t-1} ~ N(pred_prev_sample, variance) == add variance to pred_sample lowercase_ : int = (1 - alpha_prod_t_prev) / (1 - alpha_prod_t) * state.common.betas[t] if variance_type is None: lowercase_ : str = self.config.variance_type # hacks - were probably added for training stability if variance_type == "fixed_small": lowercase_ : int = jnp.clip(__SCREAMING_SNAKE_CASE , a_min=1E-2_0 ) # for rl-diffuser https://arxiv.org/abs/2205.09991 elif variance_type == "fixed_small_log": lowercase_ : List[str] = jnp.log(jnp.clip(__SCREAMING_SNAKE_CASE , a_min=1E-2_0 ) ) elif variance_type == "fixed_large": lowercase_ : List[Any] = state.common.betas[t] elif variance_type == "fixed_large_log": # Glide max_log lowercase_ : List[Any] = jnp.log(state.common.betas[t] ) elif variance_type == "learned": return predicted_variance elif variance_type == "learned_range": lowercase_ : Optional[Any] = variance lowercase_ : Union[str, Any] = state.common.betas[t] lowercase_ : Union[str, Any] = (predicted_variance + 1) / 2 lowercase_ : Any = frac * max_log + (1 - frac) * min_log return variance def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = True , ): """simple docstring""" lowercase_ : Optional[int] = timestep if key is None: lowercase_ : int = jax.random.PRNGKey(0 ) if model_output.shape[1] == sample.shape[1] * 2 and self.config.variance_type in ["learned", "learned_range"]: lowercase_ , lowercase_ : Optional[Any] = jnp.split(__SCREAMING_SNAKE_CASE , sample.shape[1] , axis=1 ) else: lowercase_ : int = None # 1. compute alphas, betas lowercase_ : Any = state.common.alphas_cumprod[t] lowercase_ : Optional[int] = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) ) lowercase_ : int = 1 - alpha_prod_t lowercase_ : str = 1 - alpha_prod_t_prev # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if self.config.prediction_type == "epsilon": lowercase_ : Tuple = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif self.config.prediction_type == "sample": lowercase_ : Any = model_output elif self.config.prediction_type == "v_prediction": lowercase_ : List[Any] = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output else: raise ValueError( F'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample` ''' ''' for the FlaxDDPMScheduler.''' ) # 3. Clip "predicted x_0" if self.config.clip_sample: lowercase_ : Optional[Any] = jnp.clip(__SCREAMING_SNAKE_CASE , -1 , 1 ) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf lowercase_ : List[Any] = (alpha_prod_t_prev ** 0.5 * state.common.betas[t]) / beta_prod_t lowercase_ : Optional[Any] = state.common.alphas[t] ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf lowercase_ : Optional[Any] = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise def random_variance(): lowercase_ : str = jax.random.split(__SCREAMING_SNAKE_CASE , num=1 ) lowercase_ : List[Any] = jax.random.normal(__SCREAMING_SNAKE_CASE , shape=model_output.shape , dtype=self.dtype ) return (self._get_variance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , predicted_variance=__SCREAMING_SNAKE_CASE ) ** 0.5) * noise lowercase_ : Optional[Any] = jnp.where(t > 0 , random_variance() , jnp.zeros(model_output.shape , dtype=self.dtype ) ) lowercase_ : Any = pred_prev_sample + variance if not return_dict: return (pred_prev_sample, state) return FlaxDDPMSchedulerOutput(prev_sample=__SCREAMING_SNAKE_CASE , state=__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , ): """simple docstring""" return add_noise_common(state.common , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , ): """simple docstring""" return get_velocity_common(state.common , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def __len__( self ): """simple docstring""" return self.config.num_train_timesteps
93
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.activations import gelu_new, gelu_python, get_activation @require_torch class lowerCAmelCase__ ( unittest.TestCase ): def _snake_case ( self ): """simple docstring""" lowercase_ : str = torch.tensor([-1_00, -1, -0.1, 0, 0.1, 1.0, 1_00] ) lowercase_ : Union[str, Any] = get_activation('''gelu''' ) self.assertTrue(torch.allclose(gelu_python(__SCREAMING_SNAKE_CASE ) , torch_builtin(__SCREAMING_SNAKE_CASE ) ) ) self.assertFalse(torch.allclose(gelu_python(__SCREAMING_SNAKE_CASE ) , gelu_new(__SCREAMING_SNAKE_CASE ) ) ) def _snake_case ( self ): """simple docstring""" lowercase_ : Optional[Any] = torch.tensor([-1_00, -1, -0.1, 0, 0.1, 1.0, 1_00] ) lowercase_ : Tuple = get_activation('''gelu''' ) lowercase_ : Any = get_activation('''gelu_10''' ) lowercase_ : List[str] = torch_builtin(__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = geluaa(__SCREAMING_SNAKE_CASE ) lowercase_ : Dict = torch.where(y_gelu_aa < 10.0 , 1 , 0 ) self.assertTrue(torch.max(__SCREAMING_SNAKE_CASE ).item() == 10.0 ) self.assertTrue(torch.allclose(y_gelu * clipped_mask , y_gelu_aa * clipped_mask ) ) def _snake_case ( self ): """simple docstring""" get_activation('''gelu''' ) get_activation('''gelu_10''' ) get_activation('''gelu_fast''' ) get_activation('''gelu_new''' ) get_activation('''gelu_python''' ) get_activation('''gelu_pytorch_tanh''' ) get_activation('''linear''' ) get_activation('''mish''' ) get_activation('''quick_gelu''' ) get_activation('''relu''' ) get_activation('''sigmoid''' ) get_activation('''silu''' ) get_activation('''swish''' ) get_activation('''tanh''' ) with self.assertRaises(__SCREAMING_SNAKE_CASE ): get_activation('''bogus''' ) with self.assertRaises(__SCREAMING_SNAKE_CASE ): get_activation(__SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" lowercase_ : int = get_activation('''gelu''' ) lowercase_ : Any = 1 lowercase_ : str = get_activation('''gelu''' ) self.assertEqual(acta.a , 1 ) with self.assertRaises(__SCREAMING_SNAKE_CASE ): lowercase_ : Dict = acta.a
93
'''simple docstring''' _lowercase : int = [sum(int(c, 1_0) ** 2 for c in i.__str__()) for i in range(1_0_0_0_0_0)] def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : Optional[int] = 0 while number: # Increased Speed Slightly by checking every 5 digits together. sum_of_digits_squared += DIGITS_SQUARED[number % 100000] number //= 100000 return sum_of_digits_squared # There are 2 Chains made, # One ends with 89 with the chain member 58 being the one which when declared first, # there will be the least number of iterations for all the members to be checked. # The other one ends with 1 and has only one element 1. # So 58 and 1 are chosen to be declared at the starting. # Changed dictionary to an array to quicken the solution _lowercase : list[bool | None] = [None] * 1_0_0_0_0_0_0_0 _lowercase : List[str] = True _lowercase : Optional[int] = False def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" if CHAINS[number - 1] is not None: return CHAINS[number - 1] # type: ignore lowercase_ : Tuple = chain(next_number(__SCREAMING_SNAKE_CASE ) ) lowercase_ : Union[str, Any] = number_chain while number < 10000000: lowercase_ : int = number_chain number *= 10 return number_chain def snake_case_ ( __SCREAMING_SNAKE_CASE : int = 10000000 ): """simple docstring""" for i in range(1 , __SCREAMING_SNAKE_CASE ): if CHAINS[i] is None: chain(i + 1 ) return CHAINS[:number].count(__SCREAMING_SNAKE_CASE ) if __name__ == "__main__": import doctest doctest.testmod() print(f"""{solution() = }""")
93
1
'''simple docstring''' from __future__ import annotations _lowercase : List[str] = [-1_0, -5, 0, 5, 5.1, 1_1, 1_3, 2_1, 3, 4, -2_1, -1_0, -5, -1, 0] _lowercase : List[Any] = [-5, 0, 5, 5.1, 1_1, 1_3, 2_1, -1, 4, -1, -1_0, -5, -1, 0, -1] def snake_case_ ( __SCREAMING_SNAKE_CASE : list[float] ): """simple docstring""" lowercase_ : Dict = [] lowercase_ : int = len(__SCREAMING_SNAKE_CASE ) for i in range(__SCREAMING_SNAKE_CASE ): lowercase_ : float = -1 for j in range(i + 1 , __SCREAMING_SNAKE_CASE ): if arr[i] < arr[j]: lowercase_ : int = arr[j] break result.append(__SCREAMING_SNAKE_CASE ) return result def snake_case_ ( __SCREAMING_SNAKE_CASE : list[float] ): """simple docstring""" lowercase_ : Optional[Any] = [] for i, outer in enumerate(__SCREAMING_SNAKE_CASE ): lowercase_ : float = -1 for inner in arr[i + 1 :]: if outer < inner: lowercase_ : Tuple = inner break result.append(__SCREAMING_SNAKE_CASE ) return result def snake_case_ ( __SCREAMING_SNAKE_CASE : list[float] ): """simple docstring""" lowercase_ : Optional[Any] = len(__SCREAMING_SNAKE_CASE ) lowercase_ : list[float] = [] lowercase_ : list[float] = [-1] * arr_size for index in reversed(range(__SCREAMING_SNAKE_CASE ) ): if stack: while stack[-1] <= arr[index]: stack.pop() if not stack: break if stack: lowercase_ : Tuple = stack[-1] stack.append(arr[index] ) return result if __name__ == "__main__": from doctest import testmod from timeit import timeit testmod() print(next_greatest_element_slow(arr)) print(next_greatest_element_fast(arr)) print(next_greatest_element(arr)) _lowercase : Union[str, Any] = ( "from __main__ import arr, next_greatest_element_slow, " "next_greatest_element_fast, next_greatest_element" ) print( "next_greatest_element_slow():", timeit("next_greatest_element_slow(arr)", setup=setup), ) print( "next_greatest_element_fast():", timeit("next_greatest_element_fast(arr)", setup=setup), ) print( " next_greatest_element():", timeit("next_greatest_element(arr)", setup=setup), )
93
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _lowercase : Union[str, Any] = { "configuration_pix2struct": [ "PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP", "Pix2StructConfig", "Pix2StructTextConfig", "Pix2StructVisionConfig", ], "processing_pix2struct": ["Pix2StructProcessor"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : Dict = ["Pix2StructImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : List[str] = [ "PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST", "Pix2StructPreTrainedModel", "Pix2StructForConditionalGeneration", "Pix2StructVisionModel", "Pix2StructTextModel", ] if TYPE_CHECKING: from .configuration_pixastruct import ( PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP, PixaStructConfig, PixaStructTextConfig, PixaStructVisionConfig, ) from .processing_pixastruct import PixaStructProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_pixastruct import PixaStructImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_pixastruct import ( PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST, PixaStructForConditionalGeneration, PixaStructPreTrainedModel, PixaStructTextModel, PixaStructVisionModel, ) else: import sys _lowercase : Optional[int] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
93
1
'''simple docstring''' _lowercase : Tuple = 8.3_1_4_4_6_2 # Unit - J mol-1 K-1 def snake_case_ ( __SCREAMING_SNAKE_CASE : float , __SCREAMING_SNAKE_CASE : float , __SCREAMING_SNAKE_CASE : 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 snake_case_ ( __SCREAMING_SNAKE_CASE : float , __SCREAMING_SNAKE_CASE : float , __SCREAMING_SNAKE_CASE : 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()
93
'''simple docstring''' def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : Optional[int] = int(__SCREAMING_SNAKE_CASE ) if decimal in (0, 1): # Exit cases for the recursion return str(__SCREAMING_SNAKE_CASE ) lowercase_ , lowercase_ : List[str] = divmod(__SCREAMING_SNAKE_CASE , 2 ) return binary_recursive(__SCREAMING_SNAKE_CASE ) + str(__SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : str ): """simple docstring""" lowercase_ : str = str(__SCREAMING_SNAKE_CASE ).strip() if not number: raise ValueError('''No input value was provided''' ) lowercase_ : Optional[int] = '''-''' if number.startswith('''-''' ) else '''''' lowercase_ : Union[str, Any] = number.lstrip('''-''' ) if not number.isnumeric(): raise ValueError('''Input value is not an integer''' ) return F'''{negative}0b{binary_recursive(int(__SCREAMING_SNAKE_CASE ) )}''' if __name__ == "__main__": from doctest import testmod testmod()
93
1
'''simple docstring''' from math import ceil def snake_case_ ( __SCREAMING_SNAKE_CASE : int = 1001 ): """simple docstring""" lowercase_ : Tuple = 1 for i in range(1 , int(ceil(n / 2.0 ) ) ): lowercase_ : Optional[Any] = 2 * i + 1 lowercase_ : Any = 2 * i lowercase_ : List[str] = total + 4 * odd**2 - 6 * even return total if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution()) else: try: _lowercase : Optional[int] = int(sys.argv[1]) print(solution(n)) except ValueError: print("Invalid entry - please enter a number")
93
'''simple docstring''' import glob import os import random from string import ascii_lowercase, digits import cva import numpy as np # Parrameters _lowercase : Any = (7_2_0, 1_2_8_0) # Height, Width _lowercase : List[Any] = (0.4, 0.6) # if height or width lower than this scale, drop it. _lowercase : str = 1 / 1_0_0 _lowercase : Any = "" _lowercase : Union[str, Any] = "" _lowercase : Optional[int] = "" _lowercase : List[Any] = 2_5_0 def snake_case_ ( ): """simple docstring""" lowercase_ , lowercase_ : Any = get_dataset(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) for index in range(__SCREAMING_SNAKE_CASE ): lowercase_ : str = random.sample(range(len(__SCREAMING_SNAKE_CASE ) ) , 4 ) lowercase_ , lowercase_ , lowercase_ : Any = 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' lowercase_ : int = random_chars(32 ) lowercase_ : str = path.split(os.sep )[-1].rsplit('''.''' , 1 )[0] lowercase_ : int = F'''{OUTPUT_DIR}/{file_name}_MOSAIC_{letter_code}''' cva.imwrite(F'''{file_root}.jpg''' , __SCREAMING_SNAKE_CASE , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(F'''Succeeded {index+1}/{NUMBER_IMAGES} with {file_name}''' ) lowercase_ : List[Any] = [] for anno in new_annos: lowercase_ : List[Any] = anno[3] - anno[1] lowercase_ : List[str] = anno[4] - anno[2] lowercase_ : Dict = anno[1] + width / 2 lowercase_ : Dict = anno[2] + height / 2 lowercase_ : 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 snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : str ): """simple docstring""" lowercase_ : Optional[Any] = [] lowercase_ : Optional[Any] = [] for label_file in glob.glob(os.path.join(__SCREAMING_SNAKE_CASE , '''*.txt''' ) ): lowercase_ : int = label_file.split(os.sep )[-1].rsplit('''.''' , 1 )[0] with open(__SCREAMING_SNAKE_CASE ) as in_file: lowercase_ : List[str] = in_file.readlines() lowercase_ : Optional[Any] = os.path.join(__SCREAMING_SNAKE_CASE , F'''{label_name}.jpg''' ) lowercase_ : Optional[int] = [] for obj_list in obj_lists: lowercase_ : List[str] = obj_list.rstrip('''\n''' ).split(''' ''' ) lowercase_ : Optional[int] = float(obj[1] ) - float(obj[3] ) / 2 lowercase_ : Any = float(obj[2] ) - float(obj[4] ) / 2 lowercase_ : str = float(obj[1] ) + float(obj[3] ) / 2 lowercase_ : List[str] = 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 snake_case_ ( __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 , ): """simple docstring""" lowercase_ : List[Any] = np.zeros([output_size[0], output_size[1], 3] , dtype=np.uinta ) lowercase_ : Tuple = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) lowercase_ : List[Any] = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) lowercase_ : Optional[int] = int(scale_x * output_size[1] ) lowercase_ : Dict = int(scale_y * output_size[0] ) lowercase_ : Union[str, Any] = [] lowercase_ : List[Any] = [] for i, index in enumerate(__SCREAMING_SNAKE_CASE ): lowercase_ : Union[str, Any] = all_img_list[index] path_list.append(__SCREAMING_SNAKE_CASE ) lowercase_ : int = all_annos[index] lowercase_ : Dict = cva.imread(__SCREAMING_SNAKE_CASE ) if i == 0: # top-left lowercase_ : Optional[Any] = cva.resize(__SCREAMING_SNAKE_CASE , (divid_point_x, divid_point_y) ) lowercase_ : Tuple = img for bbox in img_annos: lowercase_ : Optional[int] = bbox[1] * scale_x lowercase_ : Optional[Any] = bbox[2] * scale_y lowercase_ : str = bbox[3] * scale_x lowercase_ : Tuple = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 1: # top-right lowercase_ : Dict = cva.resize(__SCREAMING_SNAKE_CASE , (output_size[1] - divid_point_x, divid_point_y) ) lowercase_ : Dict = img for bbox in img_annos: lowercase_ : int = scale_x + bbox[1] * (1 - scale_x) lowercase_ : Dict = bbox[2] * scale_y lowercase_ : Optional[int] = scale_x + bbox[3] * (1 - scale_x) lowercase_ : int = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 2: # bottom-left lowercase_ : List[Any] = cva.resize(__SCREAMING_SNAKE_CASE , (divid_point_x, output_size[0] - divid_point_y) ) lowercase_ : List[str] = img for bbox in img_annos: lowercase_ : Any = bbox[1] * scale_x lowercase_ : Optional[int] = scale_y + bbox[2] * (1 - scale_y) lowercase_ : str = bbox[3] * scale_x lowercase_ : Optional[int] = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) else: # bottom-right lowercase_ : int = cva.resize( __SCREAMING_SNAKE_CASE , (output_size[1] - divid_point_x, output_size[0] - divid_point_y) ) lowercase_ : List[str] = img for bbox in img_annos: lowercase_ : int = scale_x + bbox[1] * (1 - scale_x) lowercase_ : Any = scale_y + bbox[2] * (1 - scale_y) lowercase_ : Optional[Any] = scale_x + bbox[3] * (1 - scale_x) lowercase_ : int = 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: lowercase_ : Optional[Any] = [ anno for anno in new_anno if filter_scale < (anno[3] - anno[1]) and filter_scale < (anno[4] - anno[2]) ] return output_img, new_anno, path_list[0] def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" assert number_char > 1, "The number of character should greater than 1" lowercase_ : Any = ascii_lowercase + digits return "".join(random.choice(__SCREAMING_SNAKE_CASE ) for _ in range(__SCREAMING_SNAKE_CASE ) ) if __name__ == "__main__": main() print("DONE ✅")
93
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) _lowercase : Optional[int] = { "configuration_mega": ["MEGA_PRETRAINED_CONFIG_ARCHIVE_MAP", "MegaConfig", "MegaOnnxConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : Tuple = [ "MEGA_PRETRAINED_MODEL_ARCHIVE_LIST", "MegaForCausalLM", "MegaForMaskedLM", "MegaForMultipleChoice", "MegaForQuestionAnswering", "MegaForSequenceClassification", "MegaForTokenClassification", "MegaModel", "MegaPreTrainedModel", ] if TYPE_CHECKING: from .configuration_mega import MEGA_PRETRAINED_CONFIG_ARCHIVE_MAP, MegaConfig, MegaOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mega import ( MEGA_PRETRAINED_MODEL_ARCHIVE_LIST, MegaForCausalLM, MegaForMaskedLM, MegaForMultipleChoice, MegaForQuestionAnswering, MegaForSequenceClassification, MegaForTokenClassification, MegaModel, MegaPreTrainedModel, ) else: import sys _lowercase : Optional[int] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
93
'''simple docstring''' from __future__ import annotations from collections import Counter from random import random class lowerCAmelCase__ : def __init__( self ): """simple docstring""" lowercase_ : int = {} def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Dict = {} def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" if nodea not in self.connections: self.add_node(__SCREAMING_SNAKE_CASE ) if nodea not in self.connections: self.add_node(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = probability def _snake_case ( self ): """simple docstring""" return list(self.connections ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Any = 0 lowercase_ : Tuple = random() for dest in self.connections[node]: current_probability += self.connections[node][dest] if current_probability > random_value: return dest return "" def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : list[tuple[str, str, float]] , __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : List[Any] = MarkovChainGraphUndirectedUnweighted() for nodea, nodea, probability in transitions: graph.add_transition_probability(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : str = Counter(graph.get_nodes() ) lowercase_ : Any = start for _ in range(__SCREAMING_SNAKE_CASE ): lowercase_ : int = graph.transition(__SCREAMING_SNAKE_CASE ) visited[node] += 1 return visited if __name__ == "__main__": import doctest doctest.testmod()
93
1
'''simple docstring''' from collections import defaultdict def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : str ): """simple docstring""" lowercase_ : List[Any] = first_str.lower().strip() lowercase_ : Tuple = second_str.lower().strip() # Remove whitespace lowercase_ : Optional[int] = first_str.replace(''' ''' , '''''' ) lowercase_ : Dict = second_str.replace(''' ''' , '''''' ) # Strings of different lengths are not anagrams if len(__SCREAMING_SNAKE_CASE ) != len(__SCREAMING_SNAKE_CASE ): return False # Default values for count should be 0 lowercase_ : defaultdict[str, int] = defaultdict(__SCREAMING_SNAKE_CASE ) # For each character in input strings, # increment count in the corresponding for i in range(len(__SCREAMING_SNAKE_CASE ) ): count[first_str[i]] += 1 count[second_str[i]] -= 1 return all(_count == 0 for _count in count.values() ) if __name__ == "__main__": from doctest import testmod testmod() _lowercase : Optional[Any] = input("Enter the first string ").strip() _lowercase : Dict = input("Enter the second string ").strip() _lowercase : List[str] = check_anagrams(input_a, input_b) print(f"""{input_a} and {input_b} are {'' if status else 'not '}anagrams.""")
93
'''simple docstring''' import torch from transformers import AutoModel class lowerCAmelCase__ ( torch.nn.Module ): def __init__( self , __SCREAMING_SNAKE_CASE="sayef/fsner-bert-base-uncased" ): """simple docstring""" super(__SCREAMING_SNAKE_CASE , self ).__init__() lowercase_ : Tuple = AutoModel.from_pretrained(__SCREAMING_SNAKE_CASE , return_dict=__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = torch.nn.CosineSimilarity(3 , 1E-0_8 ) lowercase_ : Optional[Any] = torch.nn.Softmax(dim=1 ) def _snake_case ( self , **__SCREAMING_SNAKE_CASE ): """simple docstring""" return self.bert(**__SCREAMING_SNAKE_CASE ).last_hidden_state def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" return token_embeddings.sum(2 , keepdim=__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=1 ): """simple docstring""" return self.softmax(T * self.cos(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Optional[Any] = W_supports['''sizes'''].tolist() lowercase_ : Dict = W_supports['''start_token_id'''].item() lowercase_ : List[Any] = W_supports['''end_token_id'''].item() del W_supports["sizes"] del W_supports["start_token_id"] del W_supports["end_token_id"] lowercase_ : List[str] = self.BERT(**__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = self.BERT(**__SCREAMING_SNAKE_CASE ) lowercase_ : str = None lowercase_ : Dict = None lowercase_ : Tuple = W_supports['''input_ids'''] == start_token_id lowercase_ : Any = W_supports['''input_ids'''] == end_token_id for i, size in enumerate(__SCREAMING_SNAKE_CASE ): if i == 0: lowercase_ : List[str] = 0 else: lowercase_ : List[Any] = support_sizes[i - 1] lowercase_ : str = S[s : s + size][start_token_masks[s : s + size]] lowercase_ : Optional[int] = S[s : s + size][end_token_masks[s : s + size]] lowercase_ : List[str] = torch.matmul(q[i] , s_start.T ).sum(1 ).softmax(0 ) lowercase_ : List[str] = torch.matmul(q[i] , s_end.T ).sum(1 ).softmax(0 ) if p_starts is not None: lowercase_ : Tuple = torch.vstack((p_starts, p_start) ) lowercase_ : Optional[Any] = torch.vstack((p_ends, p_end) ) else: lowercase_ : str = p_start lowercase_ : int = p_end return p_starts, p_ends
93
1
'''simple docstring''' import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin from .feature_extraction_wavaveca import WavaVecaFeatureExtractor from .tokenization_wavaveca import WavaVecaCTCTokenizer class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = '''Wav2Vec2FeatureExtractor''' lowerCAmelCase_ = '''AutoTokenizer''' def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" super().__init__(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : Any = self.feature_extractor lowercase_ : List[Any] = False @classmethod def _snake_case ( cls , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" try: return super().from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) except OSError: warnings.warn( F'''Loading a tokenizer inside {cls.__name__} from a config that does not''' ''' include a `tokenizer_class` attribute is deprecated and will be ''' '''removed in v5. Please add `\'tokenizer_class\': \'Wav2Vec2CTCTokenizer\'`''' ''' attribute to either your `config.json` or `tokenizer_config.json` ''' '''file to suppress this warning: ''' , __SCREAMING_SNAKE_CASE , ) lowercase_ : str = WavaVecaFeatureExtractor.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) lowercase_ : Any = WavaVecaCTCTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) return cls(feature_extractor=__SCREAMING_SNAKE_CASE , tokenizer=__SCREAMING_SNAKE_CASE ) def __call__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" if self._in_target_context_manager: return self.current_processor(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) if "raw_speech" in kwargs: warnings.warn('''Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.''' ) lowercase_ : Tuple = kwargs.pop('''raw_speech''' ) else: lowercase_ : Optional[Any] = kwargs.pop('''audio''' , __SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = kwargs.pop('''sampling_rate''' , __SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = kwargs.pop('''text''' , __SCREAMING_SNAKE_CASE ) if len(__SCREAMING_SNAKE_CASE ) > 0: lowercase_ : Any = args[0] lowercase_ : Optional[int] = args[1:] if audio is None and text is None: raise ValueError('''You need to specify either an `audio` or `text` input to process.''' ) if audio is not None: lowercase_ : List[Any] = self.feature_extractor(__SCREAMING_SNAKE_CASE , *__SCREAMING_SNAKE_CASE , sampling_rate=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) if text is not None: lowercase_ : Optional[int] = self.tokenizer(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) if text is None: return inputs elif audio is None: return encodings else: lowercase_ : str = encodings['''input_ids'''] return inputs def _snake_case ( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" if self._in_target_context_manager: return self.current_processor.pad(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = kwargs.pop('''input_features''' , __SCREAMING_SNAKE_CASE ) lowercase_ : Any = kwargs.pop('''labels''' , __SCREAMING_SNAKE_CASE ) if len(__SCREAMING_SNAKE_CASE ) > 0: lowercase_ : List[Any] = args[0] lowercase_ : List[Any] = args[1:] if input_features is not None: lowercase_ : Optional[int] = self.feature_extractor.pad(__SCREAMING_SNAKE_CASE , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) if labels is not None: lowercase_ : Union[str, Any] = self.tokenizer.pad(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) if labels is None: return input_features elif input_features is None: return labels else: lowercase_ : Union[str, Any] = labels['''input_ids'''] return input_features def _snake_case ( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" return self.tokenizer.batch_decode(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def _snake_case ( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" return self.tokenizer.decode(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) @contextmanager def _snake_case ( self ): """simple docstring""" warnings.warn( '''`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your ''' '''labels by using the argument `text` of the regular `__call__` method (either in the same call as ''' '''your audio inputs, or in a separate call.''' ) lowercase_ : List[Any] = True lowercase_ : str = self.tokenizer yield lowercase_ : List[str] = self.feature_extractor lowercase_ : int = False
93
'''simple docstring''' import json import os from pathlib import Path from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple, Union import sentencepiece from ...tokenization_utils import BatchEncoding, PreTrainedTokenizer from ...utils import logging _lowercase : List[Any] = logging.get_logger(__name__) _lowercase : List[Any] = "▁" _lowercase : Tuple = { "vocab_file": "vocab.json", "spm_file": "sentencepiece.bpe.model", "tokenizer_config_file": "tokenizer_config.json", } _lowercase : List[str] = { "vocab_file": { "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/vocab.json", "facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/vocab.json", }, "spm_file": { "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/sentencepiece.bpe.model", "facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/sentencepiece.bpe.model", }, "tokenizer_config_file": { "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/tokenizer_config.json", "facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/tokenizer_config.json", }, } _lowercase : List[str] = { "facebook/m2m100_418M": 1_0_2_4, } # fmt: off _lowercase : Tuple = { "m2m100": ["af", "am", "ar", "ast", "az", "ba", "be", "bg", "bn", "br", "bs", "ca", "ceb", "cs", "cy", "da", "de", "el", "en", "es", "et", "fa", "ff", "fi", "fr", "fy", "ga", "gd", "gl", "gu", "ha", "he", "hi", "hr", "ht", "hu", "hy", "id", "ig", "ilo", "is", "it", "ja", "jv", "ka", "kk", "km", "kn", "ko", "lb", "lg", "ln", "lo", "lt", "lv", "mg", "mk", "ml", "mn", "mr", "ms", "my", "ne", "nl", "no", "ns", "oc", "or", "pa", "pl", "ps", "pt", "ro", "ru", "sd", "si", "sk", "sl", "so", "sq", "sr", "ss", "su", "sv", "sw", "ta", "th", "tl", "tn", "tr", "uk", "ur", "uz", "vi", "wo", "xh", "yi", "yo", "zh", "zu"], "wmt21": ["en", "ha", "is", "ja", "cs", "ru", "zh", "de"] } class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = VOCAB_FILES_NAMES lowerCAmelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase_ = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase_ = ['''input_ids''', '''attention_mask'''] lowerCAmelCase_ = [] lowerCAmelCase_ = [] def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE="<s>" , __SCREAMING_SNAKE_CASE="</s>" , __SCREAMING_SNAKE_CASE="</s>" , __SCREAMING_SNAKE_CASE="<pad>" , __SCREAMING_SNAKE_CASE="<unk>" , __SCREAMING_SNAKE_CASE="m2m100" , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE=8 , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : Optional[Any] = {} if sp_model_kwargs is None else sp_model_kwargs lowercase_ : List[Any] = language_codes lowercase_ : Optional[int] = FAIRSEQ_LANGUAGE_CODES[language_codes] lowercase_ : List[Any] = {lang_code: F'''__{lang_code}__''' for lang_code in fairseq_language_code} lowercase_ : Union[str, Any] = kwargs.get('''additional_special_tokens''' , [] ) kwargs["additional_special_tokens"] += [ self.get_lang_token(__SCREAMING_SNAKE_CASE ) for lang_code in fairseq_language_code if self.get_lang_token(__SCREAMING_SNAKE_CASE ) not in kwargs["additional_special_tokens"] ] super().__init__( src_lang=__SCREAMING_SNAKE_CASE , tgt_lang=__SCREAMING_SNAKE_CASE , bos_token=__SCREAMING_SNAKE_CASE , eos_token=__SCREAMING_SNAKE_CASE , sep_token=__SCREAMING_SNAKE_CASE , unk_token=__SCREAMING_SNAKE_CASE , pad_token=__SCREAMING_SNAKE_CASE , language_codes=__SCREAMING_SNAKE_CASE , sp_model_kwargs=self.sp_model_kwargs , num_madeup_words=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) lowercase_ : int = vocab_file lowercase_ : Any = load_json(__SCREAMING_SNAKE_CASE ) lowercase_ : str = {v: k for k, v in self.encoder.items()} lowercase_ : Optional[int] = spm_file lowercase_ : Any = load_spm(__SCREAMING_SNAKE_CASE , self.sp_model_kwargs ) lowercase_ : List[Any] = len(self.encoder ) lowercase_ : Dict = { self.get_lang_token(__SCREAMING_SNAKE_CASE ): self.encoder_size + i for i, lang_code in enumerate(__SCREAMING_SNAKE_CASE ) } lowercase_ : Optional[int] = {lang_code: self.encoder_size + i for i, lang_code in enumerate(__SCREAMING_SNAKE_CASE )} lowercase_ : Union[str, Any] = {v: k for k, v in self.lang_token_to_id.items()} lowercase_ : Tuple = src_lang if src_lang is not None else '''en''' lowercase_ : Optional[int] = tgt_lang lowercase_ : Any = self.get_lang_id(self._src_lang ) self.set_src_lang_special_tokens(self._src_lang ) lowercase_ : Dict = num_madeup_words @property def _snake_case ( self ): """simple docstring""" return len(self.encoder ) + len(self.lang_token_to_id ) @property def _snake_case ( self ): """simple docstring""" return self._src_lang @src_lang.setter def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : str = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" return self.sp_model.encode(__SCREAMING_SNAKE_CASE , out_type=__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" if token in self.lang_token_to_id: return self.lang_token_to_id[token] return self.encoder.get(__SCREAMING_SNAKE_CASE , self.encoder[self.unk_token] ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" if index in self.id_to_lang_token: return self.id_to_lang_token[index] return self.decoder.get(__SCREAMING_SNAKE_CASE , self.unk_token ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Tuple = [] lowercase_ : List[str] = '''''' for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(__SCREAMING_SNAKE_CASE ) + token lowercase_ : Optional[Any] = [] else: current_sub_tokens.append(__SCREAMING_SNAKE_CASE ) out_string += self.sp_model.decode(__SCREAMING_SNAKE_CASE ) return out_string.strip() def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = False ): """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__SCREAMING_SNAKE_CASE , token_ids_a=__SCREAMING_SNAKE_CASE , already_has_special_tokens=__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = [1] * len(self.prefix_tokens ) lowercase_ : Any = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(__SCREAMING_SNAKE_CASE )) + suffix_ones return prefix_ones + ([0] * len(__SCREAMING_SNAKE_CASE )) + ([0] * len(__SCREAMING_SNAKE_CASE )) + suffix_ones def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def _snake_case ( self ): """simple docstring""" lowercase_ : Tuple = {self.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ): """simple docstring""" lowercase_ : List[Any] = self.__dict__.copy() lowercase_ : List[Any] = None return state def __setstate__( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Dict = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): lowercase_ : List[Any] = {} lowercase_ : Union[str, Any] = load_spm(self.spm_file , self.sp_model_kwargs ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" lowercase_ : Tuple = Path(__SCREAMING_SNAKE_CASE ) if not save_dir.is_dir(): raise OSError(F'''{save_directory} should be a directory''' ) lowercase_ : Dict = save_dir / ( (filename_prefix + '''-''' if filename_prefix else '''''') + self.vocab_files_names['''vocab_file'''] ) lowercase_ : Dict = save_dir / ( (filename_prefix + '''-''' if filename_prefix else '''''') + self.vocab_files_names['''spm_file'''] ) save_json(self.encoder , __SCREAMING_SNAKE_CASE ) if os.path.abspath(self.spm_file ) != os.path.abspath(__SCREAMING_SNAKE_CASE ) and os.path.isfile(self.spm_file ): copyfile(self.spm_file , __SCREAMING_SNAKE_CASE ) elif not os.path.isfile(self.spm_file ): with open(__SCREAMING_SNAKE_CASE , '''wb''' ) as fi: lowercase_ : int = self.sp_model.serialized_model_proto() fi.write(__SCREAMING_SNAKE_CASE ) return (str(__SCREAMING_SNAKE_CASE ), str(__SCREAMING_SNAKE_CASE )) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = "en" , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = "ro" , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : Optional[Any] = src_lang lowercase_ : List[str] = tgt_lang self.set_src_lang_special_tokens(self.src_lang ) return super().prepare_seqaseq_batch(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" if src_lang is None or tgt_lang is None: raise ValueError('''Translation requires a `src_lang` and a `tgt_lang` for this model''' ) lowercase_ : Tuple = src_lang lowercase_ : Any = self(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) lowercase_ : List[Any] = self.get_lang_id(__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = tgt_lang_id return inputs def _snake_case ( self ): """simple docstring""" self.set_src_lang_special_tokens(self.src_lang ) def _snake_case ( self ): """simple docstring""" self.set_tgt_lang_special_tokens(self.tgt_lang ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Any = self.get_lang_token(__SCREAMING_SNAKE_CASE ) lowercase_ : Dict = self.lang_token_to_id[lang_token] lowercase_ : Optional[Any] = [self.cur_lang_id] lowercase_ : Union[str, Any] = [self.eos_token_id] def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Any = self.get_lang_token(__SCREAMING_SNAKE_CASE ) lowercase_ : Any = self.lang_token_to_id[lang_token] lowercase_ : str = [self.cur_lang_id] lowercase_ : List[str] = [self.eos_token_id] def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" return self.lang_code_to_token[lang] def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : List[Any] = self.get_lang_token(__SCREAMING_SNAKE_CASE ) return self.lang_token_to_id[lang_token] def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Dict[str, Any] ): """simple docstring""" lowercase_ : Optional[int] = sentencepiece.SentencePieceProcessor(**__SCREAMING_SNAKE_CASE ) spm.Load(str(__SCREAMING_SNAKE_CASE ) ) return spm def snake_case_ ( __SCREAMING_SNAKE_CASE : str ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE , '''r''' ) as f: return json.load(__SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : str ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE , '''w''' ) as f: json.dump(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , indent=2 )
93
1
'''simple docstring''' _lowercase : int = [sum(int(c, 1_0) ** 2 for c in i.__str__()) for i in range(1_0_0_0_0_0)] def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : Optional[int] = 0 while number: # Increased Speed Slightly by checking every 5 digits together. sum_of_digits_squared += DIGITS_SQUARED[number % 100000] number //= 100000 return sum_of_digits_squared # There are 2 Chains made, # One ends with 89 with the chain member 58 being the one which when declared first, # there will be the least number of iterations for all the members to be checked. # The other one ends with 1 and has only one element 1. # So 58 and 1 are chosen to be declared at the starting. # Changed dictionary to an array to quicken the solution _lowercase : list[bool | None] = [None] * 1_0_0_0_0_0_0_0 _lowercase : List[str] = True _lowercase : Optional[int] = False def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" if CHAINS[number - 1] is not None: return CHAINS[number - 1] # type: ignore lowercase_ : Tuple = chain(next_number(__SCREAMING_SNAKE_CASE ) ) lowercase_ : Union[str, Any] = number_chain while number < 10000000: lowercase_ : int = number_chain number *= 10 return number_chain def snake_case_ ( __SCREAMING_SNAKE_CASE : int = 10000000 ): """simple docstring""" for i in range(1 , __SCREAMING_SNAKE_CASE ): if CHAINS[i] is None: chain(i + 1 ) return CHAINS[:number].count(__SCREAMING_SNAKE_CASE ) if __name__ == "__main__": import doctest doctest.testmod() print(f"""{solution() = }""")
93
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer from ...utils import logging _lowercase : str = logging.get_logger(__name__) _lowercase : List[Any] = "▁" _lowercase : List[Any] = {"vocab_file": "sentencepiece.bpe.model"} _lowercase : Optional[int] = { "vocab_file": { "facebook/mbart-large-en-ro": ( "https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/sentencepiece.bpe.model" ), "facebook/mbart-large-cc25": ( "https://huggingface.co/facebook/mbart-large-cc25/resolve/main/sentencepiece.bpe.model" ), } } _lowercase : str = { "facebook/mbart-large-en-ro": 1_0_2_4, "facebook/mbart-large-cc25": 1_0_2_4, } # fmt: off _lowercase : List[Any] = ["ar_AR", "cs_CZ", "de_DE", "en_XX", "es_XX", "et_EE", "fi_FI", "fr_XX", "gu_IN", "hi_IN", "it_IT", "ja_XX", "kk_KZ", "ko_KR", "lt_LT", "lv_LV", "my_MM", "ne_NP", "nl_XX", "ro_RO", "ru_RU", "si_LK", "tr_TR", "vi_VN", "zh_CN"] class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = VOCAB_FILES_NAMES lowerCAmelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase_ = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase_ = ['''input_ids''', '''attention_mask'''] lowerCAmelCase_ = [] lowerCAmelCase_ = [] def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE="<s>" , __SCREAMING_SNAKE_CASE="</s>" , __SCREAMING_SNAKE_CASE="</s>" , __SCREAMING_SNAKE_CASE="<s>" , __SCREAMING_SNAKE_CASE="<unk>" , __SCREAMING_SNAKE_CASE="<pad>" , __SCREAMING_SNAKE_CASE="<mask>" , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE=None , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : Any = AddedToken(__SCREAMING_SNAKE_CASE , lstrip=__SCREAMING_SNAKE_CASE , rstrip=__SCREAMING_SNAKE_CASE ) if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else mask_token lowercase_ : int = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=__SCREAMING_SNAKE_CASE , eos_token=__SCREAMING_SNAKE_CASE , unk_token=__SCREAMING_SNAKE_CASE , sep_token=__SCREAMING_SNAKE_CASE , cls_token=__SCREAMING_SNAKE_CASE , pad_token=__SCREAMING_SNAKE_CASE , mask_token=__SCREAMING_SNAKE_CASE , tokenizer_file=__SCREAMING_SNAKE_CASE , src_lang=__SCREAMING_SNAKE_CASE , tgt_lang=__SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , sp_model_kwargs=self.sp_model_kwargs , **__SCREAMING_SNAKE_CASE , ) lowercase_ : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__SCREAMING_SNAKE_CASE ) ) lowercase_ : List[str] = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # Mimic fairseq token-to-id alignment for the first 4 token lowercase_ : Tuple = {'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3} # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab lowercase_ : str = 1 lowercase_ : str = len(self.sp_model ) lowercase_ : List[Any] = { code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(__SCREAMING_SNAKE_CASE ) } lowercase_ : Union[str, Any] = {v: k for k, v in self.lang_code_to_id.items()} lowercase_ : List[Any] = len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset self.fairseq_tokens_to_ids.update(self.lang_code_to_id ) lowercase_ : Union[str, Any] = {v: k for k, v in self.fairseq_tokens_to_ids.items()} lowercase_ : Optional[Any] = list(self.lang_code_to_id.keys() ) if additional_special_tokens is not None: # Only add those special tokens if they are not already there. self._additional_special_tokens.extend( [t for t in additional_special_tokens if t not in self._additional_special_tokens] ) lowercase_ : Optional[Any] = src_lang if src_lang is not None else '''en_XX''' lowercase_ : str = self.lang_code_to_id[self._src_lang] lowercase_ : Optional[Any] = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) def __getstate__( self ): """simple docstring""" lowercase_ : Optional[int] = self.__dict__.copy() lowercase_ : Dict = None lowercase_ : Any = self.sp_model.serialized_model_proto() return state def __setstate__( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Optional[Any] = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): lowercase_ : Dict = {} lowercase_ : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) @property def _snake_case ( self ): """simple docstring""" return len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset + 1 # Plus 1 for the mask token @property def _snake_case ( self ): """simple docstring""" return self._src_lang @src_lang.setter def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Tuple = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = False ): """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__SCREAMING_SNAKE_CASE , token_ids_a=__SCREAMING_SNAKE_CASE , already_has_special_tokens=__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = [1] * len(self.prefix_tokens ) lowercase_ : Tuple = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(__SCREAMING_SNAKE_CASE )) + suffix_ones return prefix_ones + ([0] * len(__SCREAMING_SNAKE_CASE )) + ([0] * len(__SCREAMING_SNAKE_CASE )) + suffix_ones def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" lowercase_ : Optional[int] = [self.sep_token_id] lowercase_ : Any = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" if src_lang is None or tgt_lang is None: raise ValueError('''Translation requires a `src_lang` and a `tgt_lang` for this model''' ) lowercase_ : Optional[Any] = src_lang lowercase_ : Dict = self(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , return_tensors=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = self.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = tgt_lang_id return inputs def _snake_case ( self ): """simple docstring""" lowercase_ : str = {self.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" return self.sp_model.encode(__SCREAMING_SNAKE_CASE , out_type=__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] lowercase_ : Any = self.sp_model.PieceToId(__SCREAMING_SNAKE_CASE ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : int = ''''''.join(__SCREAMING_SNAKE_CASE ).replace(__SCREAMING_SNAKE_CASE , ''' ''' ).strip() return out_string def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" if not os.path.isdir(__SCREAMING_SNAKE_CASE ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return lowercase_ : Tuple = os.path.join( __SCREAMING_SNAKE_CASE , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__SCREAMING_SNAKE_CASE ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __SCREAMING_SNAKE_CASE ) elif not os.path.isfile(self.vocab_file ): with open(__SCREAMING_SNAKE_CASE , '''wb''' ) as fi: lowercase_ : List[str] = self.sp_model.serialized_model_proto() fi.write(__SCREAMING_SNAKE_CASE ) return (out_vocab_file,) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = "en_XX" , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = "ro_RO" , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : List[str] = src_lang lowercase_ : int = tgt_lang return super().prepare_seqaseq_batch(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" return self.set_src_lang_special_tokens(self.src_lang ) def _snake_case ( self ): """simple docstring""" return self.set_tgt_lang_special_tokens(self.tgt_lang ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Dict = self.lang_code_to_id[src_lang] lowercase_ : Optional[Any] = [] lowercase_ : List[str] = [self.eos_token_id, self.cur_lang_code] def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : List[Any] = self.lang_code_to_id[lang] lowercase_ : Dict = [] lowercase_ : Union[str, Any] = [self.eos_token_id, self.cur_lang_code]
93
1
'''simple docstring''' from collections import OrderedDict from typing import TYPE_CHECKING, Any, List, Mapping, Optional from packaging import version if TYPE_CHECKING: from ... import PreTrainedTokenizer, TensorType from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import is_torch_available, logging _lowercase : List[str] = logging.get_logger(__name__) _lowercase : List[Any] = { "bigscience/bloom": "https://huggingface.co/bigscience/bloom/resolve/main/config.json", "bigscience/bloom-560m": "https://huggingface.co/bigscience/bloom-560m/blob/main/config.json", "bigscience/bloom-1b1": "https://huggingface.co/bigscience/bloom-1b1/blob/main/config.json", "bigscience/bloom-1b7": "https://huggingface.co/bigscience/bloom-1b7/blob/main/config.json", "bigscience/bloom-3b": "https://huggingface.co/bigscience/bloom-3b/blob/main/config.json", "bigscience/bloom-7b1": "https://huggingface.co/bigscience/bloom-7b1/blob/main/config.json", } class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = '''bloom''' lowerCAmelCase_ = ['''past_key_values'''] lowerCAmelCase_ = { '''num_hidden_layers''': '''n_layer''', '''num_attention_heads''': '''n_head''', } def __init__( self , __SCREAMING_SNAKE_CASE=25_08_80 , __SCREAMING_SNAKE_CASE=64 , __SCREAMING_SNAKE_CASE=2 , __SCREAMING_SNAKE_CASE=8 , __SCREAMING_SNAKE_CASE=1E-5 , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=1 , __SCREAMING_SNAKE_CASE=2 , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=1 , __SCREAMING_SNAKE_CASE=False , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : Optional[Any] = vocab_size # Backward compatibility with n_embed kwarg lowercase_ : Optional[int] = kwargs.pop('''n_embed''' , __SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = hidden_size if n_embed is None else n_embed lowercase_ : Union[str, Any] = n_layer lowercase_ : Union[str, Any] = n_head lowercase_ : Optional[int] = layer_norm_epsilon lowercase_ : str = initializer_range lowercase_ : Dict = use_cache lowercase_ : Union[str, Any] = pretraining_tp lowercase_ : Union[str, Any] = apply_residual_connection_post_layernorm lowercase_ : Union[str, Any] = hidden_dropout lowercase_ : List[str] = attention_dropout lowercase_ : Dict = bos_token_id lowercase_ : int = eos_token_id lowercase_ : Any = slow_but_exact super().__init__(bos_token_id=__SCREAMING_SNAKE_CASE , eos_token_id=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = version.parse('''1.12''' ) def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = "default" , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = False , ): """simple docstring""" super().__init__(__SCREAMING_SNAKE_CASE , task=__SCREAMING_SNAKE_CASE , patching_specs=__SCREAMING_SNAKE_CASE , use_past=__SCREAMING_SNAKE_CASE ) if not getattr(self._config , '''pad_token_id''' , __SCREAMING_SNAKE_CASE ): # TODO: how to do that better? lowercase_ : Any = 0 @property def _snake_case ( self ): """simple docstring""" lowercase_ : List[Any] = OrderedDict({'''input_ids''': {0: '''batch''', 1: '''sequence'''}} ) if self.use_past: # BLOOM stores values on dynamic axis 2. For more details see: https://github.com/huggingface/transformers/pull/18344 self.fill_with_past_key_values_(__SCREAMING_SNAKE_CASE , direction='''inputs''' , inverted_values_shape=__SCREAMING_SNAKE_CASE ) lowercase_ : List[str] = {0: '''batch''', 1: '''past_sequence + sequence'''} else: lowercase_ : Any = {0: '''batch''', 1: '''sequence'''} return common_inputs @property def _snake_case ( self ): """simple docstring""" return self._config.n_layer @property def _snake_case ( self ): """simple docstring""" return self._config.n_head @property def _snake_case ( self ): """simple docstring""" return 1E-3 def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = -1 , __SCREAMING_SNAKE_CASE = -1 , __SCREAMING_SNAKE_CASE = False , __SCREAMING_SNAKE_CASE = None , ): """simple docstring""" lowercase_ : Optional[int] = super(__SCREAMING_SNAKE_CASE , self ).generate_dummy_inputs( __SCREAMING_SNAKE_CASE , batch_size=__SCREAMING_SNAKE_CASE , seq_length=__SCREAMING_SNAKE_CASE , is_pair=__SCREAMING_SNAKE_CASE , framework=__SCREAMING_SNAKE_CASE ) # We need to order the input in the way they appears in the forward() lowercase_ : Optional[Any] = OrderedDict({'''input_ids''': common_inputs['''input_ids''']} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError('''Cannot generate dummy past_keys inputs without PyTorch installed.''' ) else: import torch lowercase_ , lowercase_ : Tuple = common_inputs['''input_ids'''].shape # Not using the same length for past_key_values lowercase_ : Tuple = seqlen + 2 lowercase_ : Optional[Any] = self._config.hidden_size // self.num_attention_heads lowercase_ : Optional[int] = ( batch * self.num_attention_heads, head_dim, past_key_values_length, ) lowercase_ : Tuple = ( batch * self.num_attention_heads, past_key_values_length, head_dim, ) lowercase_ : Union[str, Any] = [ (torch.zeros(__SCREAMING_SNAKE_CASE ), torch.zeros(__SCREAMING_SNAKE_CASE )) for _ in range(self.num_layers ) ] lowercase_ : Union[str, Any] = common_inputs['''attention_mask'''] if self.use_past: lowercase_ : Any = ordered_inputs['''attention_mask'''].dtype lowercase_ : Union[str, Any] = torch.cat( [ordered_inputs['''attention_mask'''], torch.ones(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , dtype=__SCREAMING_SNAKE_CASE )] , dim=1 ) return ordered_inputs @property def _snake_case ( self ): """simple docstring""" return 13
93
'''simple docstring''' import json import os import tempfile from transformers.testing_utils import check_json_file_has_correct_format class lowerCAmelCase__ : lowerCAmelCase_ = None def _snake_case ( self ): """simple docstring""" lowercase_ : Tuple = self.feature_extraction_class(**self.feat_extract_dict ) lowercase_ : Any = json.loads(feat_extract.to_json_string() ) for key, value in self.feat_extract_dict.items(): self.assertEqual(obj[key] , __SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" lowercase_ : str = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: lowercase_ : str = os.path.join(__SCREAMING_SNAKE_CASE , '''feat_extract.json''' ) feat_extract_first.to_json_file(__SCREAMING_SNAKE_CASE ) lowercase_ : str = self.feature_extraction_class.from_json_file(__SCREAMING_SNAKE_CASE ) self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() ) def _snake_case ( self ): """simple docstring""" lowercase_ : Tuple = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: lowercase_ : Union[str, Any] = feat_extract_first.save_pretrained(__SCREAMING_SNAKE_CASE )[0] check_json_file_has_correct_format(__SCREAMING_SNAKE_CASE ) lowercase_ : str = self.feature_extraction_class.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() ) def _snake_case ( self ): """simple docstring""" lowercase_ : Optional[Any] = self.feature_extraction_class() self.assertIsNotNone(__SCREAMING_SNAKE_CASE )
93
1
'''simple docstring''' def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : Optional[int] = int(__SCREAMING_SNAKE_CASE ) if decimal in (0, 1): # Exit cases for the recursion return str(__SCREAMING_SNAKE_CASE ) lowercase_ , lowercase_ : List[str] = divmod(__SCREAMING_SNAKE_CASE , 2 ) return binary_recursive(__SCREAMING_SNAKE_CASE ) + str(__SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : str ): """simple docstring""" lowercase_ : str = str(__SCREAMING_SNAKE_CASE ).strip() if not number: raise ValueError('''No input value was provided''' ) lowercase_ : Optional[int] = '''-''' if number.startswith('''-''' ) else '''''' lowercase_ : Union[str, Any] = number.lstrip('''-''' ) if not number.isnumeric(): raise ValueError('''Input value is not an integer''' ) return F'''{negative}0b{binary_recursive(int(__SCREAMING_SNAKE_CASE ) )}''' if __name__ == "__main__": from doctest import testmod testmod()
93
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging _lowercase : Optional[Any] = logging.get_logger(__name__) _lowercase : List[str] = { "google/pix2struct-textcaps-base": ( "https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json" ), } class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = '''pix2struct_text_model''' lowerCAmelCase_ = ['''past_key_values'''] lowerCAmelCase_ = { '''hidden_size''': '''hidden_size''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self , __SCREAMING_SNAKE_CASE=5_02_44 , __SCREAMING_SNAKE_CASE=7_68 , __SCREAMING_SNAKE_CASE=64 , __SCREAMING_SNAKE_CASE=20_48 , __SCREAMING_SNAKE_CASE=12 , __SCREAMING_SNAKE_CASE=12 , __SCREAMING_SNAKE_CASE=32 , __SCREAMING_SNAKE_CASE=1_28 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=1E-6 , __SCREAMING_SNAKE_CASE=1.0 , __SCREAMING_SNAKE_CASE="gelu_new" , __SCREAMING_SNAKE_CASE=0 , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=0 , __SCREAMING_SNAKE_CASE=1 , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=True , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : Any = vocab_size lowercase_ : Tuple = hidden_size lowercase_ : Optional[Any] = d_kv lowercase_ : List[str] = d_ff lowercase_ : List[str] = num_layers lowercase_ : Optional[Any] = num_heads lowercase_ : Union[str, Any] = relative_attention_num_buckets lowercase_ : Optional[int] = relative_attention_max_distance lowercase_ : Union[str, Any] = dropout_rate lowercase_ : Dict = layer_norm_epsilon lowercase_ : Dict = initializer_factor lowercase_ : List[Any] = use_cache lowercase_ : Optional[int] = eos_token_id lowercase_ : Optional[int] = decoder_start_token_id # for backwards compatibility lowercase_ : Any = dense_act_fn super().__init__( pad_token_id=__SCREAMING_SNAKE_CASE , eos_token_id=__SCREAMING_SNAKE_CASE , decoder_start_token_id=__SCREAMING_SNAKE_CASE , tie_word_embeddings=__SCREAMING_SNAKE_CASE , is_decoder=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) @classmethod def _snake_case ( cls , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" cls._set_token_in_kwargs(__SCREAMING_SNAKE_CASE ) lowercase_ , lowercase_ : Optional[int] = cls.get_config_dict(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) # get the text config dict if we are loading from Pix2StructConfig if config_dict.get('''model_type''' ) == "pix2struct": lowercase_ : List[Any] = config_dict['''text_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'''You are using a model of type {config_dict['model_type']} to instantiate a model of type ''' F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = '''pix2struct_vision_model''' def __init__( self , __SCREAMING_SNAKE_CASE=7_68 , __SCREAMING_SNAKE_CASE=7_68 , __SCREAMING_SNAKE_CASE=20_48 , __SCREAMING_SNAKE_CASE=64 , __SCREAMING_SNAKE_CASE=12 , __SCREAMING_SNAKE_CASE=12 , __SCREAMING_SNAKE_CASE="gelu_new" , __SCREAMING_SNAKE_CASE=1E-6 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=1E-1_0 , __SCREAMING_SNAKE_CASE=1.0 , __SCREAMING_SNAKE_CASE=40_96 , __SCREAMING_SNAKE_CASE=32 , __SCREAMING_SNAKE_CASE=1_28 , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = hidden_size lowercase_ : Any = patch_embed_hidden_size lowercase_ : List[Any] = d_ff lowercase_ : Dict = dropout_rate lowercase_ : Any = num_hidden_layers lowercase_ : Any = num_attention_heads lowercase_ : int = initializer_range lowercase_ : Dict = initializer_factor lowercase_ : Dict = attention_dropout lowercase_ : Optional[Any] = layer_norm_eps lowercase_ : str = dense_act_fn lowercase_ : Dict = seq_len lowercase_ : List[Any] = relative_attention_num_buckets lowercase_ : int = relative_attention_max_distance lowercase_ : Optional[int] = d_kv @classmethod def _snake_case ( cls , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" cls._set_token_in_kwargs(__SCREAMING_SNAKE_CASE ) lowercase_ , lowercase_ : str = cls.get_config_dict(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) # get the vision config dict if we are loading from Pix2StructConfig if config_dict.get('''model_type''' ) == "pix2struct": lowercase_ : Optional[int] = config_dict['''vision_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'''You are using a model of type {config_dict['model_type']} to instantiate a model of type ''' F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = '''pix2struct''' lowerCAmelCase_ = True def __init__( self , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=1.0 , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=True , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" super().__init__(tie_word_embeddings=__SCREAMING_SNAKE_CASE , is_encoder_decoder=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) if text_config is None: lowercase_ : Optional[Any] = {} logger.info('''text_config is None. Initializing the Pix2StructTextConfig with default values.''' ) if vision_config is None: lowercase_ : Dict = {} logger.info('''vision_config is None. Initializing the Pix2StructVisionConfig with default values.''' ) lowercase_ : str = PixaStructTextConfig(**__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = PixaStructVisionConfig(**__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = self.text_config.decoder_start_token_id lowercase_ : Union[str, Any] = self.text_config.pad_token_id lowercase_ : Union[str, Any] = self.text_config.eos_token_id lowercase_ : int = initializer_factor lowercase_ : Any = initializer_range lowercase_ : str = self.initializer_range lowercase_ : str = self.initializer_range lowercase_ : int = is_vqa @classmethod def _snake_case ( cls , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **__SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" lowercase_ : Tuple = copy.deepcopy(self.__dict__ ) lowercase_ : Any = self.text_config.to_dict() lowercase_ : Optional[Any] = self.vision_config.to_dict() lowercase_ : Optional[int] = self.__class__.model_type return output
93
1
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging _lowercase : Optional[int] = logging.get_logger(__name__) _lowercase : Union[str, Any] = {"vocab_file": "spiece.model"} _lowercase : Optional[Any] = { "vocab_file": { "bert_for_seq_generation": ( "https://huggingface.co/google/bert_for_seq_generation_L-24_bbc_encoder/resolve/main/spiece.model" ), } } _lowercase : List[str] = {"bert_for_seq_generation": 5_1_2} class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = VOCAB_FILES_NAMES lowerCAmelCase_ = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase_ = [] lowerCAmelCase_ = ['''input_ids''', '''attention_mask'''] def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE="<s>" , __SCREAMING_SNAKE_CASE="</s>" , __SCREAMING_SNAKE_CASE="<unk>" , __SCREAMING_SNAKE_CASE="<pad>" , __SCREAMING_SNAKE_CASE="<::::>" , __SCREAMING_SNAKE_CASE = None , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : str = {} if sp_model_kwargs is None else sp_model_kwargs # Add extra_ids to the special token list super().__init__( bos_token=__SCREAMING_SNAKE_CASE , eos_token=__SCREAMING_SNAKE_CASE , unk_token=__SCREAMING_SNAKE_CASE , pad_token=__SCREAMING_SNAKE_CASE , sep_token=__SCREAMING_SNAKE_CASE , sp_model_kwargs=self.sp_model_kwargs , **__SCREAMING_SNAKE_CASE , ) lowercase_ : Dict = vocab_file lowercase_ : int = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(__SCREAMING_SNAKE_CASE ) @property def _snake_case ( self ): """simple docstring""" return self.sp_model.get_piece_size() def _snake_case ( self ): """simple docstring""" lowercase_ : int = {self.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ): """simple docstring""" lowercase_ : int = self.__dict__.copy() lowercase_ : Union[str, Any] = None return state def __setstate__( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Optional[Any] = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): lowercase_ : List[Any] = {} lowercase_ : Tuple = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" return self.sp_model.encode(__SCREAMING_SNAKE_CASE , out_type=__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" return self.sp_model.piece_to_id(__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Dict = self.sp_model.IdToPiece(__SCREAMING_SNAKE_CASE ) return token def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Optional[int] = [] lowercase_ : Any = '''''' for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(__SCREAMING_SNAKE_CASE ) + token lowercase_ : List[str] = [] else: current_sub_tokens.append(__SCREAMING_SNAKE_CASE ) out_string += self.sp_model.decode(__SCREAMING_SNAKE_CASE ) return out_string.strip() def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" if not os.path.isdir(__SCREAMING_SNAKE_CASE ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return lowercase_ : int = os.path.join( __SCREAMING_SNAKE_CASE , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__SCREAMING_SNAKE_CASE ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __SCREAMING_SNAKE_CASE ) elif not os.path.isfile(self.vocab_file ): with open(__SCREAMING_SNAKE_CASE , '''wb''' ) as fi: lowercase_ : Any = self.sp_model.serialized_model_proto() fi.write(__SCREAMING_SNAKE_CASE ) return (out_vocab_file,)
93
'''simple docstring''' from math import isqrt, loga def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : Any = [True] * max_number for i in range(2 , isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2 , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase_ : Optional[Any] = False return [i for i in range(2 , __SCREAMING_SNAKE_CASE ) if is_prime[i]] def snake_case_ ( __SCREAMING_SNAKE_CASE : int = 800800 , __SCREAMING_SNAKE_CASE : int = 800800 ): """simple docstring""" lowercase_ : Union[str, Any] = degree * loga(__SCREAMING_SNAKE_CASE ) lowercase_ : Any = int(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = calculate_prime_numbers(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = 0 lowercase_ : List[Any] = 0 lowercase_ : Union[str, Any] = len(__SCREAMING_SNAKE_CASE ) - 1 while left < right: while ( prime_numbers[right] * loga(prime_numbers[left] ) + prime_numbers[left] * loga(prime_numbers[right] ) > upper_bound ): right -= 1 hybrid_integers_count += right - left left += 1 return hybrid_integers_count if __name__ == "__main__": print(f"""{solution() = }""")
93
1
'''simple docstring''' import warnings from ...utils import logging from .image_processing_yolos import YolosImageProcessor _lowercase : int = logging.get_logger(__name__) class lowerCAmelCase__ ( lowerCamelCase_ ): def __init__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" warnings.warn( '''The class YolosFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please''' ''' use YolosImageProcessor instead.''' , __SCREAMING_SNAKE_CASE , ) super().__init__(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE )
93
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices _lowercase : int = logging.get_logger(__name__) _lowercase : List[Any] = { "shi-labs/nat-mini-in1k-224": "https://huggingface.co/shi-labs/nat-mini-in1k-224/resolve/main/config.json", # See all Nat models at https://huggingface.co/models?filter=nat } class lowerCAmelCase__ ( lowerCamelCase_ , lowerCamelCase_ ): lowerCAmelCase_ = '''nat''' lowerCAmelCase_ = { '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self , __SCREAMING_SNAKE_CASE=4 , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=64 , __SCREAMING_SNAKE_CASE=[3, 4, 6, 5] , __SCREAMING_SNAKE_CASE=[2, 4, 8, 16] , __SCREAMING_SNAKE_CASE=7 , __SCREAMING_SNAKE_CASE=3.0 , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE="gelu" , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=1E-5 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = patch_size lowercase_ : List[Any] = num_channels lowercase_ : str = embed_dim lowercase_ : List[str] = depths lowercase_ : str = len(__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = num_heads lowercase_ : int = kernel_size lowercase_ : Union[str, Any] = mlp_ratio lowercase_ : Optional[int] = qkv_bias lowercase_ : List[Any] = hidden_dropout_prob lowercase_ : Optional[int] = attention_probs_dropout_prob lowercase_ : List[Any] = drop_path_rate lowercase_ : List[Any] = hidden_act lowercase_ : int = layer_norm_eps lowercase_ : int = initializer_range # we set the hidden_size attribute in order to make Nat work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model lowercase_ : Dict = int(embed_dim * 2 ** (len(__SCREAMING_SNAKE_CASE ) - 1) ) lowercase_ : Tuple = layer_scale_init_value lowercase_ : Union[str, Any] = ['''stem'''] + [F'''stage{idx}''' for idx in range(1 , len(__SCREAMING_SNAKE_CASE ) + 1 )] lowercase_ , lowercase_ : int = get_aligned_output_features_output_indices( out_features=__SCREAMING_SNAKE_CASE , out_indices=__SCREAMING_SNAKE_CASE , stage_names=self.stage_names )
93
1
'''simple docstring''' import gc import random import unittest import numpy as np import torch from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModel from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEImgaImgPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import floats_tensor, load_image, load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class lowerCAmelCase__ ( lowerCamelCase_ , unittest.TestCase ): lowerCAmelCase_ = ShapEImgaImgPipeline lowerCAmelCase_ = ['''image'''] lowerCAmelCase_ = ['''image'''] lowerCAmelCase_ = [ '''num_images_per_prompt''', '''num_inference_steps''', '''generator''', '''latents''', '''guidance_scale''', '''frame_size''', '''output_type''', '''return_dict''', ] lowerCAmelCase_ = False @property def _snake_case ( self ): """simple docstring""" return 32 @property def _snake_case ( self ): """simple docstring""" return 32 @property def _snake_case ( self ): """simple docstring""" return self.time_input_dim * 4 @property def _snake_case ( self ): """simple docstring""" return 8 @property def _snake_case ( self ): """simple docstring""" torch.manual_seed(0 ) lowercase_ : Any = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=64 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=1 , ) lowercase_ : Tuple = CLIPVisionModel(__SCREAMING_SNAKE_CASE ) return model @property def _snake_case ( self ): """simple docstring""" lowercase_ : Union[str, Any] = CLIPImageProcessor( crop_size=2_24 , do_center_crop=__SCREAMING_SNAKE_CASE , do_normalize=__SCREAMING_SNAKE_CASE , do_resize=__SCREAMING_SNAKE_CASE , image_mean=[0.48_145_466, 0.4_578_275, 0.40_821_073] , image_std=[0.26_862_954, 0.26_130_258, 0.27_577_711] , resample=3 , size=2_24 , ) return image_processor @property def _snake_case ( self ): """simple docstring""" torch.manual_seed(0 ) lowercase_ : List[Any] = { '''num_attention_heads''': 2, '''attention_head_dim''': 16, '''embedding_dim''': self.time_input_dim, '''num_embeddings''': 32, '''embedding_proj_dim''': self.text_embedder_hidden_size, '''time_embed_dim''': self.time_embed_dim, '''num_layers''': 1, '''clip_embed_dim''': self.time_input_dim * 2, '''additional_embeddings''': 0, '''time_embed_act_fn''': '''gelu''', '''norm_in_type''': '''layer''', '''embedding_proj_norm_type''': '''layer''', '''encoder_hid_proj_type''': None, '''added_emb_type''': None, } lowercase_ : Any = PriorTransformer(**__SCREAMING_SNAKE_CASE ) return model @property def _snake_case ( self ): """simple docstring""" torch.manual_seed(0 ) lowercase_ : Union[str, Any] = { '''param_shapes''': ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), '''d_latent''': self.time_input_dim, '''d_hidden''': self.renderer_dim, '''n_output''': 12, '''background''': ( 0.1, 0.1, 0.1, ), } lowercase_ : Optional[Any] = ShapERenderer(**__SCREAMING_SNAKE_CASE ) return model def _snake_case ( self ): """simple docstring""" lowercase_ : str = self.dummy_prior lowercase_ : Union[str, Any] = self.dummy_image_encoder lowercase_ : Tuple = self.dummy_image_processor lowercase_ : Optional[Any] = self.dummy_renderer lowercase_ : Tuple = HeunDiscreteScheduler( beta_schedule='''exp''' , num_train_timesteps=10_24 , prediction_type='''sample''' , use_karras_sigmas=__SCREAMING_SNAKE_CASE , clip_sample=__SCREAMING_SNAKE_CASE , clip_sample_range=1.0 , ) lowercase_ : Dict = { '''prior''': prior, '''image_encoder''': image_encoder, '''image_processor''': image_processor, '''renderer''': renderer, '''scheduler''': scheduler, } return components def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=0 ): """simple docstring""" lowercase_ : List[Any] = floats_tensor((1, 3, 64, 64) , rng=random.Random(__SCREAMING_SNAKE_CASE ) ).to(__SCREAMING_SNAKE_CASE ) if str(__SCREAMING_SNAKE_CASE ).startswith('''mps''' ): lowercase_ : int = torch.manual_seed(__SCREAMING_SNAKE_CASE ) else: lowercase_ : List[Any] = torch.Generator(device=__SCREAMING_SNAKE_CASE ).manual_seed(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = { '''image''': input_image, '''generator''': generator, '''num_inference_steps''': 1, '''frame_size''': 32, '''output_type''': '''np''', } return inputs def _snake_case ( self ): """simple docstring""" lowercase_ : List[str] = '''cpu''' lowercase_ : List[str] = self.get_dummy_components() lowercase_ : Optional[int] = self.pipeline_class(**__SCREAMING_SNAKE_CASE ) lowercase_ : Dict = pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) lowercase_ : List[str] = pipe(**self.get_dummy_inputs(__SCREAMING_SNAKE_CASE ) ) lowercase_ : List[Any] = output.images[0] lowercase_ : Union[str, Any] = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) lowercase_ : Optional[Any] = np.array( [ 0.00_039_216, 0.00_039_216, 0.00_039_216, 0.00_039_216, 0.00_039_216, 0.00_039_216, 0.00_039_216, 0.00_039_216, 0.00_039_216, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _snake_case ( self ): """simple docstring""" self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def _snake_case ( self ): """simple docstring""" lowercase_ : List[str] = torch_device == '''cpu''' lowercase_ : int = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=__SCREAMING_SNAKE_CASE , relax_max_difference=__SCREAMING_SNAKE_CASE , ) def _snake_case ( self ): """simple docstring""" lowercase_ : List[str] = self.get_dummy_components() lowercase_ : Optional[Any] = self.pipeline_class(**__SCREAMING_SNAKE_CASE ) lowercase_ : str = pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) lowercase_ : List[str] = 1 lowercase_ : Any = 2 lowercase_ : str = self.get_dummy_inputs(__SCREAMING_SNAKE_CASE ) for key in inputs.keys(): if key in self.batch_params: lowercase_ : Optional[int] = batch_size * [inputs[key]] lowercase_ : Any = pipe(**__SCREAMING_SNAKE_CASE , num_images_per_prompt=__SCREAMING_SNAKE_CASE )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): def _snake_case ( self ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _snake_case ( self ): """simple docstring""" lowercase_ : Dict = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/shap_e/corgi.png''' ) lowercase_ : Tuple = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/shap_e/test_shap_e_img2img_out.npy''' ) lowercase_ : Optional[Any] = ShapEImgaImgPipeline.from_pretrained('''openai/shap-e-img2img''' ) lowercase_ : List[str] = pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = torch.Generator(device=__SCREAMING_SNAKE_CASE ).manual_seed(0 ) lowercase_ : Union[str, Any] = pipe( __SCREAMING_SNAKE_CASE , generator=__SCREAMING_SNAKE_CASE , guidance_scale=3.0 , num_inference_steps=64 , frame_size=64 , output_type='''np''' , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
93
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _lowercase : Union[str, Any] = { "configuration_mask2former": [ "MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "Mask2FormerConfig", ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : Optional[int] = ["Mask2FormerImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : str = [ "MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "Mask2FormerForUniversalSegmentation", "Mask2FormerModel", "Mask2FormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_maskaformer import MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskaFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_maskaformer import MaskaFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskaformer import ( MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskaFormerForUniversalSegmentation, MaskaFormerModel, MaskaFormerPreTrainedModel, ) else: import sys _lowercase : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure)
93
1
'''simple docstring''' import copy import os import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np import pyarrow as pa import pyarrow.parquet as pq import pytest from datasets.arrow_writer import ArrowWriter, OptimizedTypedSequence, ParquetWriter, TypedSequence from datasets.features import ArrayaD, ClassLabel, Features, Image, Value from datasets.features.features import ArrayaDExtensionType, cast_to_python_objects from datasets.keyhash import DuplicatedKeysError, InvalidKeyError from .utils import require_pil class lowerCAmelCase__ ( lowerCamelCase_ ): def _snake_case ( self ): """simple docstring""" lowercase_ : Tuple = pa.array(TypedSequence([1, 2, 3] ) ) self.assertEqual(arr.type , pa.intaa() ) def _snake_case ( self ): """simple docstring""" with self.assertRaises(__SCREAMING_SNAKE_CASE ): lowercase_ : List[str] = pa.array(TypedSequence([1, 2, 3] ) , type=pa.intaa() ) def _snake_case ( self ): """simple docstring""" with self.assertRaises(__SCREAMING_SNAKE_CASE ): lowercase_ : str = pa.array(TypedSequence([1, 2, 3] , try_type=Value('''bool''' ) , type=Value('''int64''' ) ) ) def _snake_case ( self ): """simple docstring""" lowercase_ : Any = pa.array(TypedSequence([1, 2, 3] , type=Value('''int32''' ) ) ) self.assertEqual(arr.type , pa.intaa() ) def _snake_case ( self ): """simple docstring""" with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): lowercase_ : List[Any] = pa.array(TypedSequence(['''foo''', '''bar'''] , type=Value('''int64''' ) ) ) def _snake_case ( self ): """simple docstring""" lowercase_ : Optional[int] = pa.array(TypedSequence([1, 2, 3] , try_type=Value('''int32''' ) ) ) self.assertEqual(arr.type , pa.intaa() ) def _snake_case ( self ): """simple docstring""" lowercase_ : Dict = pa.array(TypedSequence(['''foo''', '''bar'''] , try_type=Value('''int64''' ) ) ) self.assertEqual(arr.type , pa.string() ) def _snake_case ( self ): """simple docstring""" lowercase_ : str = pa.array(TypedSequence([[[1, 2, 3]]] , type=ArrayaD((1, 3) , '''int64''' ) ) ) self.assertEqual(arr.type , ArrayaDExtensionType((1, 3) , '''int64''' ) ) def _snake_case ( self ): """simple docstring""" with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): lowercase_ : Optional[Any] = pa.array(TypedSequence(['''foo''', '''bar'''] , type=ArrayaD((1, 3) , '''int64''' ) ) ) def _snake_case ( self ): """simple docstring""" lowercase_ : Any = pa.array(TypedSequence([[[1, 2, 3]]] , try_type=ArrayaD((1, 3) , '''int64''' ) ) ) self.assertEqual(arr.type , ArrayaDExtensionType((1, 3) , '''int64''' ) ) def _snake_case ( self ): """simple docstring""" lowercase_ : str = pa.array(TypedSequence(['''foo''', '''bar'''] , try_type=ArrayaD((1, 3) , '''int64''' ) ) ) self.assertEqual(arr.type , pa.string() ) @require_pil def _snake_case ( self ): """simple docstring""" import PIL.Image lowercase_ : Optional[Any] = PIL.Image.fromarray(np.arange(10 , dtype=np.uinta ).reshape(2 , 5 ) ) with patch( '''datasets.arrow_writer.cast_to_python_objects''' , side_effect=__SCREAMING_SNAKE_CASE ) as mock_cast_to_python_objects: lowercase_ : int = pa.array(TypedSequence([{'''path''': None, '''bytes''': b'''image_bytes'''}, pil_image] , type=Image() ) ) lowercase_ , lowercase_ : Optional[int] = mock_cast_to_python_objects.call_args_list[-1] self.assertIn('''optimize_list_casting''' , __SCREAMING_SNAKE_CASE ) self.assertFalse(kwargs['''optimize_list_casting'''] ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : Union[str, Any] = pa.BufferReader(__SCREAMING_SNAKE_CASE ) if isinstance(__SCREAMING_SNAKE_CASE , pa.Buffer ) else pa.memory_map(__SCREAMING_SNAKE_CASE ) lowercase_ : str = pa.ipc.open_stream(__SCREAMING_SNAKE_CASE ) lowercase_ : pa.Table = f.read_all() assert len(pa_table.to_batches() ) == expected_num_chunks assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} del pa_table @pytest.mark.parametrize('''writer_batch_size''' , [None, 1, 10] ) @pytest.mark.parametrize( '''fields''' , [None, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}] ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" lowercase_ : Any = pa.BufferOutputStream() lowercase_ : Union[str, Any] = pa.schema(__SCREAMING_SNAKE_CASE ) if fields else None with ArrowWriter(stream=__SCREAMING_SNAKE_CASE , schema=__SCREAMING_SNAKE_CASE , writer_batch_size=__SCREAMING_SNAKE_CASE ) as writer: writer.write({'''col_1''': '''foo''', '''col_2''': 1} ) writer.write({'''col_1''': '''bar''', '''col_2''': 2} ) lowercase_ , lowercase_ : Optional[int] = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: lowercase_ : Union[str, Any] = {'''col_1''': pa.string(), '''col_2''': pa.intaa()} assert writer._schema == pa.schema(__SCREAMING_SNAKE_CASE , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def snake_case_ ( ): """simple docstring""" lowercase_ : Optional[int] = pa.BufferOutputStream() lowercase_ : Union[str, Any] = Features({'''labels''': ClassLabel(names=['''neg''', '''pos'''] )} ) with ArrowWriter(stream=__SCREAMING_SNAKE_CASE , features=__SCREAMING_SNAKE_CASE ) as writer: writer.write({'''labels''': 0} ) writer.write({'''labels''': 1} ) lowercase_ , lowercase_ : str = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == features.arrow_schema assert writer._schema.metadata == features.arrow_schema.metadata lowercase_ : Union[str, Any] = pa.BufferReader(output.getvalue() ) lowercase_ : Dict = pa.ipc.open_stream(__SCREAMING_SNAKE_CASE ) lowercase_ : pa.Table = f.read_all() lowercase_ : Tuple = pa_table.schema assert pa_table.num_rows == 2 assert schema == features.arrow_schema assert schema.metadata == features.arrow_schema.metadata assert features == Features.from_arrow_schema(__SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize('''writer_batch_size''' , [None, 1, 10] ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" lowercase_ : int = pa.BufferOutputStream() with ArrowWriter( stream=__SCREAMING_SNAKE_CASE , writer_batch_size=__SCREAMING_SNAKE_CASE , hash_salt='''split_name''' , check_duplicates=__SCREAMING_SNAKE_CASE , ) as writer: with pytest.raises(__SCREAMING_SNAKE_CASE ): writer.write({'''col_1''': '''foo''', '''col_2''': 1} , key=[1, 2] ) lowercase_ , lowercase_ : List[str] = writer.finalize() @pytest.mark.parametrize('''writer_batch_size''' , [None, 2, 10] ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Any ): """simple docstring""" lowercase_ : Union[str, Any] = pa.BufferOutputStream() with ArrowWriter( stream=__SCREAMING_SNAKE_CASE , writer_batch_size=__SCREAMING_SNAKE_CASE , hash_salt='''split_name''' , check_duplicates=__SCREAMING_SNAKE_CASE , ) as writer: with pytest.raises(__SCREAMING_SNAKE_CASE ): writer.write({'''col_1''': '''foo''', '''col_2''': 1} , key=10 ) writer.write({'''col_1''': '''bar''', '''col_2''': 2} , key=10 ) lowercase_ , lowercase_ : Tuple = writer.finalize() @pytest.mark.parametrize('''writer_batch_size''' , [None, 2, 10] ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[int] ): """simple docstring""" lowercase_ : List[str] = pa.BufferOutputStream() with ArrowWriter( stream=__SCREAMING_SNAKE_CASE , writer_batch_size=__SCREAMING_SNAKE_CASE , hash_salt='''split_name''' , check_duplicates=__SCREAMING_SNAKE_CASE , ) as writer: writer.write({'''col_1''': '''foo''', '''col_2''': 1} , key=1 ) writer.write({'''col_1''': '''bar''', '''col_2''': 2} , key=2 ) lowercase_ , lowercase_ : List[str] = writer.finalize() assert num_examples == 2 assert num_bytes > 0 _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize('''writer_batch_size''' , [None, 1, 10] ) @pytest.mark.parametrize( '''fields''' , [None, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}] ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" lowercase_ : Optional[Any] = pa.BufferOutputStream() lowercase_ : Any = pa.schema(__SCREAMING_SNAKE_CASE ) if fields else None with ArrowWriter(stream=__SCREAMING_SNAKE_CASE , schema=__SCREAMING_SNAKE_CASE , writer_batch_size=__SCREAMING_SNAKE_CASE ) as writer: writer.write_batch({'''col_1''': ['''foo''', '''bar'''], '''col_2''': [1, 2]} ) writer.write_batch({'''col_1''': [], '''col_2''': []} ) lowercase_ , lowercase_ : List[Any] = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: lowercase_ : str = {'''col_1''': pa.string(), '''col_2''': pa.intaa()} assert writer._schema == pa.schema(__SCREAMING_SNAKE_CASE , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize('''writer_batch_size''' , [None, 1, 10] ) @pytest.mark.parametrize( '''fields''' , [None, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}] ) def snake_case_ ( __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : List[Any] ): """simple docstring""" lowercase_ : Any = pa.BufferOutputStream() lowercase_ : Optional[int] = pa.schema(__SCREAMING_SNAKE_CASE ) if fields else None with ArrowWriter(stream=__SCREAMING_SNAKE_CASE , schema=__SCREAMING_SNAKE_CASE , writer_batch_size=__SCREAMING_SNAKE_CASE ) as writer: writer.write_table(pa.Table.from_pydict({'''col_1''': ['''foo''', '''bar'''], '''col_2''': [1, 2]} ) ) lowercase_ , lowercase_ : str = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: lowercase_ : Union[str, Any] = {'''col_1''': pa.string(), '''col_2''': pa.intaa()} assert writer._schema == pa.schema(__SCREAMING_SNAKE_CASE , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize('''writer_batch_size''' , [None, 1, 10] ) @pytest.mark.parametrize( '''fields''' , [None, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}] ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" lowercase_ : int = pa.BufferOutputStream() lowercase_ : Union[str, Any] = pa.schema(__SCREAMING_SNAKE_CASE ) if fields else None with ArrowWriter(stream=__SCREAMING_SNAKE_CASE , schema=__SCREAMING_SNAKE_CASE , writer_batch_size=__SCREAMING_SNAKE_CASE ) as writer: writer.write_row(pa.Table.from_pydict({'''col_1''': ['''foo'''], '''col_2''': [1]} ) ) writer.write_row(pa.Table.from_pydict({'''col_1''': ['''bar'''], '''col_2''': [2]} ) ) lowercase_ , lowercase_ : Union[str, Any] = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: lowercase_ : List[Any] = {'''col_1''': pa.string(), '''col_2''': pa.intaa()} assert writer._schema == pa.schema(__SCREAMING_SNAKE_CASE , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def snake_case_ ( ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: lowercase_ : Union[str, Any] = {'''col_1''': pa.string(), '''col_2''': pa.intaa()} lowercase_ : int = os.path.join(__SCREAMING_SNAKE_CASE , '''test.arrow''' ) with ArrowWriter(path=__SCREAMING_SNAKE_CASE , schema=pa.schema(__SCREAMING_SNAKE_CASE ) ) as writer: writer.write_batch({'''col_1''': ['''foo''', '''bar'''], '''col_2''': [1, 2]} ) lowercase_ , lowercase_ : Optional[int] = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == pa.schema(__SCREAMING_SNAKE_CASE , metadata=writer._schema.metadata ) _check_output(__SCREAMING_SNAKE_CASE , 1 ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[int] ): """simple docstring""" if pa.types.is_list(__SCREAMING_SNAKE_CASE ): return get_base_dtype(arr_type.value_type ) else: return arr_type def snake_case_ ( __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" if isinstance(lst[0] , __SCREAMING_SNAKE_CASE ): change_first_primitive_element_in_list(lst[0] , __SCREAMING_SNAKE_CASE ) else: lowercase_ : Tuple = value @pytest.mark.parametrize('''optimized_int_type, expected_dtype''' , [(None, pa.intaa()), (Value('''int32''' ), pa.intaa())] ) @pytest.mark.parametrize('''sequence''' , [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def snake_case_ ( __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" lowercase_ : Union[str, Any] = pa.array(TypedSequence(__SCREAMING_SNAKE_CASE , optimized_int_type=__SCREAMING_SNAKE_CASE ) ) assert get_base_dtype(arr.type ) == expected_dtype @pytest.mark.parametrize( '''col, expected_dtype''' , [ ('''attention_mask''', pa.inta()), ('''special_tokens_mask''', pa.inta()), ('''token_type_ids''', pa.inta()), ('''input_ids''', pa.intaa()), ('''other''', pa.intaa()), ] , ) @pytest.mark.parametrize('''sequence''' , [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" lowercase_ : Any = pa.array(OptimizedTypedSequence(__SCREAMING_SNAKE_CASE , col=__SCREAMING_SNAKE_CASE ) ) assert get_base_dtype(arr.type ) == expected_dtype # not in range if col != "other": # avoids errors due to in-place modifications lowercase_ : Union[str, Any] = copy.deepcopy(__SCREAMING_SNAKE_CASE ) lowercase_ : Any = np.iinfo(expected_dtype.to_pandas_dtype() ).max + 1 change_first_primitive_element_in_list(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : Any = pa.array(OptimizedTypedSequence(__SCREAMING_SNAKE_CASE , col=__SCREAMING_SNAKE_CASE ) ) assert get_base_dtype(arr.type ) == pa.intaa() @pytest.mark.parametrize('''raise_exception''' , [False, True] ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" lowercase_ : Dict = str(tmp_path / '''dataset-train.arrow''' ) try: with ArrowWriter(path=__SCREAMING_SNAKE_CASE ) as writer: if raise_exception: raise pa.lib.ArrowInvalid() else: writer.stream.close() except pa.lib.ArrowInvalid: pass finally: assert writer.stream.closed def snake_case_ ( __SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" lowercase_ : List[str] = '''mock://dataset-train.arrow''' with ArrowWriter(path=__SCREAMING_SNAKE_CASE , storage_options=mockfs.storage_options ) as writer: assert isinstance(writer._fs , type(__SCREAMING_SNAKE_CASE ) ) assert writer._fs.storage_options == mockfs.storage_options writer.write({'''col_1''': '''foo''', '''col_2''': 1} ) writer.write({'''col_1''': '''bar''', '''col_2''': 2} ) lowercase_ , lowercase_ : Tuple = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert mockfs.exists(__SCREAMING_SNAKE_CASE ) def snake_case_ ( ): """simple docstring""" lowercase_ : List[Any] = pa.BufferOutputStream() with ParquetWriter(stream=__SCREAMING_SNAKE_CASE ) as writer: writer.write({'''col_1''': '''foo''', '''col_2''': 1} ) writer.write({'''col_1''': '''bar''', '''col_2''': 2} ) lowercase_ , lowercase_ : Dict = writer.finalize() assert num_examples == 2 assert num_bytes > 0 lowercase_ : Optional[int] = pa.BufferReader(output.getvalue() ) lowercase_ : pa.Table = pq.read_table(__SCREAMING_SNAKE_CASE ) assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} @require_pil @pytest.mark.parametrize('''embed_local_files''' , [False, True] ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : str ): """simple docstring""" import PIL.Image lowercase_ : Any = str(tmp_path / '''test_image_rgb.jpg''' ) PIL.Image.fromarray(np.zeros((5, 5) , dtype=np.uinta ) ).save(__SCREAMING_SNAKE_CASE , format='''png''' ) lowercase_ : Tuple = pa.BufferOutputStream() with ParquetWriter( stream=__SCREAMING_SNAKE_CASE , features=Features({'''image''': Image()} ) , embed_local_files=__SCREAMING_SNAKE_CASE ) as writer: writer.write({'''image''': image_path} ) writer.finalize() lowercase_ : Tuple = pa.BufferReader(output.getvalue() ) lowercase_ : pa.Table = pq.read_table(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = pa_table.to_pydict() if embed_local_files: assert isinstance(out['''image'''][0]['''path'''] , __SCREAMING_SNAKE_CASE ) with open(__SCREAMING_SNAKE_CASE , '''rb''' ) as f: assert out["image"][0]["bytes"] == f.read() else: assert out["image"][0]["path"] == image_path assert out["image"][0]["bytes"] is None def snake_case_ ( ): """simple docstring""" lowercase_ : Any = pa.schema([pa.field('''col_1''' , pa.string() , nullable=__SCREAMING_SNAKE_CASE )] ) lowercase_ : Union[str, Any] = pa.BufferOutputStream() with ArrowWriter(stream=__SCREAMING_SNAKE_CASE ) as writer: writer._build_writer(inferred_schema=__SCREAMING_SNAKE_CASE ) assert writer._schema == pa.schema([pa.field('''col_1''' , pa.string() )] )
93
'''simple docstring''' import unittest from knapsack import greedy_knapsack as kp class lowerCAmelCase__ ( unittest.TestCase ): def _snake_case ( self ): """simple docstring""" lowercase_ : List[str] = [10, 20, 30, 40, 50, 60] lowercase_ : Optional[Any] = [2, 4, 6, 8, 10, 12] lowercase_ : Union[str, Any] = 1_00 self.assertEqual(kp.calc_profit(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) , 2_10 ) def _snake_case ( self ): """simple docstring""" self.assertRaisesRegex(__SCREAMING_SNAKE_CASE , '''max_weight must greater than zero.''' ) def _snake_case ( self ): """simple docstring""" self.assertRaisesRegex(__SCREAMING_SNAKE_CASE , '''Weight can not be negative.''' ) def _snake_case ( self ): """simple docstring""" self.assertRaisesRegex(__SCREAMING_SNAKE_CASE , '''Profit can not be negative.''' ) def _snake_case ( self ): """simple docstring""" self.assertRaisesRegex(__SCREAMING_SNAKE_CASE , '''max_weight must greater than zero.''' ) def _snake_case ( self ): """simple docstring""" self.assertRaisesRegex( __SCREAMING_SNAKE_CASE , '''The length of profit and weight must be same.''' ) if __name__ == "__main__": unittest.main()
93
1
'''simple docstring''' from .glue import glue_convert_examples_to_features, glue_output_modes, glue_processors, glue_tasks_num_labels from .squad import SquadExample, SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features from .utils import DataProcessor, InputExample, InputFeatures, SingleSentenceClassificationProcessor from .xnli import xnli_output_modes, xnli_processors, xnli_tasks_num_labels
93
'''simple docstring''' import argparse import copy def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[int] ): """simple docstring""" lowercase_ : List[Any] = {} with open(__SCREAMING_SNAKE_CASE ) as f: for line in f: if line.split()[0] not in dict_of_neighbours: lowercase_ : Union[str, Any] = [] _list.append([line.split()[1], line.split()[2]] ) lowercase_ : str = _list else: dict_of_neighbours[line.split()[0]].append( [line.split()[1], line.split()[2]] ) if line.split()[1] not in dict_of_neighbours: lowercase_ : Optional[int] = [] _list.append([line.split()[0], line.split()[2]] ) lowercase_ : Dict = _list else: dict_of_neighbours[line.split()[1]].append( [line.split()[0], line.split()[2]] ) return dict_of_neighbours def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE ) as f: lowercase_ : List[str] = f.read(1 ) lowercase_ : Optional[int] = start_node lowercase_ : Any = [] lowercase_ : List[str] = start_node lowercase_ : Optional[Any] = 0 while visiting not in first_solution: lowercase_ : Any = 10000 for k in dict_of_neighbours[visiting]: if int(k[1] ) < int(__SCREAMING_SNAKE_CASE ) and k[0] not in first_solution: lowercase_ : List[Any] = k[1] lowercase_ : List[Any] = k[0] first_solution.append(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = distance_of_first_solution + int(__SCREAMING_SNAKE_CASE ) lowercase_ : int = best_node first_solution.append(__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = 0 for k in dict_of_neighbours[first_solution[-2]]: if k[0] == start_node: break position += 1 lowercase_ : Optional[Any] = ( distance_of_first_solution + int(dict_of_neighbours[first_solution[-2]][position][1] ) - 10000 ) return first_solution, distance_of_first_solution def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" lowercase_ : Tuple = [] for n in solution[1:-1]: lowercase_ : List[str] = solution.index(__SCREAMING_SNAKE_CASE ) for kn in solution[1:-1]: lowercase_ : Any = solution.index(__SCREAMING_SNAKE_CASE ) if n == kn: continue lowercase_ : Dict = copy.deepcopy(__SCREAMING_SNAKE_CASE ) lowercase_ : Dict = kn lowercase_ : List[Any] = n lowercase_ : str = 0 for k in _tmp[:-1]: lowercase_ : Tuple = _tmp[_tmp.index(__SCREAMING_SNAKE_CASE ) + 1] for i in dict_of_neighbours[k]: if i[0] == next_node: lowercase_ : Optional[Any] = distance + int(i[1] ) _tmp.append(__SCREAMING_SNAKE_CASE ) if _tmp not in neighborhood_of_solution: neighborhood_of_solution.append(_tmp ) lowercase_ : Union[str, Any] = 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 snake_case_ ( __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" lowercase_ : Optional[int] = 1 lowercase_ : List[str] = first_solution lowercase_ : Dict = [] lowercase_ : List[str] = distance_of_first_solution lowercase_ : Optional[Any] = solution while count <= iters: lowercase_ : int = find_neighborhood(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : Any = 0 lowercase_ : Dict = neighborhood[index_of_best_solution] lowercase_ : Optional[Any] = len(__SCREAMING_SNAKE_CASE ) - 1 lowercase_ : Tuple = False while not found: lowercase_ : Optional[int] = 0 while i < len(__SCREAMING_SNAKE_CASE ): if best_solution[i] != solution[i]: lowercase_ : Tuple = best_solution[i] lowercase_ : Optional[int] = solution[i] break lowercase_ : 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] ) lowercase_ : Tuple = True lowercase_ : Optional[int] = best_solution[:-1] lowercase_ : Optional[Any] = neighborhood[index_of_best_solution][best_cost_index] if cost < best_cost: lowercase_ : Optional[Any] = cost lowercase_ : int = solution else: lowercase_ : Any = index_of_best_solution + 1 lowercase_ : Any = neighborhood[index_of_best_solution] if len(__SCREAMING_SNAKE_CASE ) >= size: tabu_list.pop(0 ) lowercase_ : List[Any] = count + 1 return best_solution_ever, best_cost def snake_case_ ( __SCREAMING_SNAKE_CASE : List[str]=None ): """simple docstring""" lowercase_ : Any = generate_neighbours(args.File ) lowercase_ , lowercase_ : Union[str, Any] = generate_first_solution( args.File , __SCREAMING_SNAKE_CASE ) lowercase_ , lowercase_ : Optional[int] = 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__": _lowercase : Any = 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())
93
1
'''simple docstring''' import numpy as np from nltk.translate import meteor_score import datasets from datasets.config import importlib_metadata, version _lowercase : List[str] = version.parse(importlib_metadata.version("nltk")) if NLTK_VERSION >= version.Version("3.6.4"): from nltk import word_tokenize _lowercase : List[Any] = "\\n@inproceedings{banarjee2005,\n title = {{METEOR}: An Automatic Metric for {MT} Evaluation with Improved Correlation with Human Judgments},\n author = {Banerjee, Satanjeev and Lavie, Alon},\n booktitle = {Proceedings of the {ACL} Workshop on Intrinsic and Extrinsic Evaluation Measures for Machine Translation and/or Summarization},\n month = jun,\n year = {2005},\n address = {Ann Arbor, Michigan},\n publisher = {Association for Computational Linguistics},\n url = {https://www.aclweb.org/anthology/W05-0909},\n pages = {65--72},\n}\n" _lowercase : Tuple = "\\nMETEOR, an automatic metric for machine translation evaluation\nthat is based on a generalized concept of unigram matching between the\nmachine-produced translation and human-produced reference translations.\nUnigrams can be matched based on their surface forms, stemmed forms,\nand meanings; furthermore, METEOR can be easily extended to include more\nadvanced matching strategies. Once all generalized unigram matches\nbetween the two strings have been found, METEOR computes a score for\nthis matching using a combination of unigram-precision, unigram-recall, and\na measure of fragmentation that is designed to directly capture how\nwell-ordered the matched words in the machine translation are in relation\nto the reference.\n\nMETEOR gets an R correlation value of 0.347 with human evaluation on the Arabic\ndata and 0.331 on the Chinese data. This is shown to be an improvement on\nusing simply unigram-precision, unigram-recall and their harmonic F1\ncombination.\n" _lowercase : Tuple = "\nComputes METEOR score of translated segments against one or more references.\nArgs:\n predictions: list of predictions to score. Each prediction\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\n alpha: Parameter for controlling relative weights of precision and recall. default: 0.9\n beta: Parameter for controlling shape of penalty as a function of fragmentation. default: 3\n gamma: Relative weight assigned to fragmentation penalty. default: 0.5\nReturns:\n 'meteor': meteor score.\nExamples:\n\n >>> meteor = datasets.load_metric('meteor')\n >>> predictions = [\"It is a guide to action which ensures that the military always obeys the commands of the party\"]\n >>> references = [\"It is a guide to action that ensures that the military will forever heed Party commands\"]\n >>> results = meteor.compute(predictions=predictions, references=references)\n >>> print(round(results[\"meteor\"], 4))\n 0.6944\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase__ ( datasets.Metric ): def _snake_case ( 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''' ), } ) , codebase_urls=['''https://github.com/nltk/nltk/blob/develop/nltk/translate/meteor_score.py'''] , reference_urls=[ '''https://www.nltk.org/api/nltk.translate.html#module-nltk.translate.meteor_score''', '''https://en.wikipedia.org/wiki/METEOR''', ] , ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" import nltk nltk.download('''wordnet''' ) if NLTK_VERSION >= version.Version('''3.6.5''' ): nltk.download('''punkt''' ) if NLTK_VERSION >= version.Version('''3.6.6''' ): nltk.download('''omw-1.4''' ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=0.9 , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=0.5 ): """simple docstring""" if NLTK_VERSION >= version.Version('''3.6.5''' ): lowercase_ : Dict = [ meteor_score.single_meteor_score( word_tokenize(__SCREAMING_SNAKE_CASE ) , word_tokenize(__SCREAMING_SNAKE_CASE ) , alpha=__SCREAMING_SNAKE_CASE , beta=__SCREAMING_SNAKE_CASE , gamma=__SCREAMING_SNAKE_CASE ) for ref, pred in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ] else: lowercase_ : Union[str, Any] = [ meteor_score.single_meteor_score(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , alpha=__SCREAMING_SNAKE_CASE , beta=__SCREAMING_SNAKE_CASE , gamma=__SCREAMING_SNAKE_CASE ) for ref, pred in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ] return {"meteor": np.mean(__SCREAMING_SNAKE_CASE )}
93
'''simple docstring''' import unittest from transformers import is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device if is_torch_available(): from transformers import AutoModelForSeqaSeqLM, AutoTokenizer @require_torch @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( unittest.TestCase ): @slow def _snake_case ( self ): """simple docstring""" lowercase_ : Dict = AutoModelForSeqaSeqLM.from_pretrained('''google/mt5-small''' , return_dict=__SCREAMING_SNAKE_CASE ).to(__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = AutoTokenizer.from_pretrained('''google/mt5-small''' ) lowercase_ : int = tokenizer('''Hello there''' , return_tensors='''pt''' ).input_ids lowercase_ : Union[str, Any] = tokenizer('''Hi I am''' , return_tensors='''pt''' ).input_ids lowercase_ : Union[str, Any] = model(input_ids.to(__SCREAMING_SNAKE_CASE ) , labels=labels.to(__SCREAMING_SNAKE_CASE ) ).loss lowercase_ : int = -(labels.shape[-1] * loss.item()) lowercase_ : Any = -84.9_127 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1E-4 )
93
1
'''simple docstring''' def snake_case_ ( __SCREAMING_SNAKE_CASE : list ): """simple docstring""" def merge(__SCREAMING_SNAKE_CASE : list , __SCREAMING_SNAKE_CASE : list ) -> list: def _merge(): while left and right: yield (left if left[0] <= right[0] else right).pop(0 ) yield from left yield from right return list(_merge() ) if len(__SCREAMING_SNAKE_CASE ) <= 1: return collection lowercase_ : Any = len(__SCREAMING_SNAKE_CASE ) // 2 return merge(merge_sort(collection[:mid] ) , merge_sort(collection[mid:] ) ) if __name__ == "__main__": import doctest doctest.testmod() _lowercase : str = input("Enter numbers separated by a comma:\n").strip() _lowercase : Any = [int(item) for item in user_input.split(",")] print(*merge_sort(unsorted), sep=",")
93
'''simple docstring''' def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : str ): """simple docstring""" lowercase_ : List[str] = len(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = [] for i in range(len(__SCREAMING_SNAKE_CASE ) - pat_len + 1 ): lowercase_ : Tuple = True for j in range(__SCREAMING_SNAKE_CASE ): if s[i + j] != pattern[j]: lowercase_ : List[str] = False break if match_found: position.append(__SCREAMING_SNAKE_CASE ) return position if __name__ == "__main__": assert naive_pattern_search("ABCDEFG", "DE") == [3] print(naive_pattern_search("ABAAABCDBBABCDDEBCABC", "ABC"))
93
1
'''simple docstring''' from ..utils import DummyObject, requires_backends class lowerCAmelCase__ ( metaclass=lowerCamelCase_ ): lowerCAmelCase_ = ['''torch''', '''scipy'''] def __init__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" requires_backends(self , ['''torch''', '''scipy'''] ) @classmethod def _snake_case ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" requires_backends(cls , ['''torch''', '''scipy'''] ) @classmethod def _snake_case ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" requires_backends(cls , ['''torch''', '''scipy'''] )
93
'''simple docstring''' import importlib import inspect import json import os import re import shutil import sys from pathlib import Path from typing import Dict, Optional, Union from urllib import request from huggingface_hub import HfFolder, cached_download, hf_hub_download, model_info from packaging import version from .. import __version__ from . import DIFFUSERS_DYNAMIC_MODULE_NAME, HF_MODULES_CACHE, logging _lowercase : Optional[Any] = ( "https://raw.githubusercontent.com/huggingface/diffusers/{revision}/examples/community/{pipeline}.py" ) _lowercase : Tuple = logging.get_logger(__name__) # pylint: disable=invalid-name def snake_case_ ( ): """simple docstring""" lowercase_ : Tuple = '''https://pypi.org/pypi/diffusers/json''' lowercase_ : Tuple = json.loads(request.urlopen(__SCREAMING_SNAKE_CASE ).read() )['''releases'''].keys() return sorted(__SCREAMING_SNAKE_CASE , key=lambda __SCREAMING_SNAKE_CASE : version.Version(__SCREAMING_SNAKE_CASE ) ) def snake_case_ ( ): """simple docstring""" if HF_MODULES_CACHE in sys.path: return sys.path.append(__SCREAMING_SNAKE_CASE ) os.makedirs(__SCREAMING_SNAKE_CASE , exist_ok=__SCREAMING_SNAKE_CASE ) lowercase_ : List[Any] = Path(__SCREAMING_SNAKE_CASE ) / '''__init__.py''' if not init_path.exists(): init_path.touch() def snake_case_ ( __SCREAMING_SNAKE_CASE : Union[str, os.PathLike] ): """simple docstring""" init_hf_modules() lowercase_ : Optional[int] = Path(__SCREAMING_SNAKE_CASE ) / name # If the parent module does not exist yet, recursively create it. if not dynamic_module_path.parent.exists(): create_dynamic_module(dynamic_module_path.parent ) os.makedirs(__SCREAMING_SNAKE_CASE , exist_ok=__SCREAMING_SNAKE_CASE ) lowercase_ : str = dynamic_module_path / '''__init__.py''' if not init_path.exists(): init_path.touch() def snake_case_ ( __SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE , '''r''' , encoding='''utf-8''' ) as f: lowercase_ : int = f.read() # Imports of the form `import .xxx` lowercase_ : List[Any] = re.findall('''^\s*import\s+\.(\S+)\s*$''' , __SCREAMING_SNAKE_CASE , flags=re.MULTILINE ) # Imports of the form `from .xxx import yyy` relative_imports += re.findall('''^\s*from\s+\.(\S+)\s+import''' , __SCREAMING_SNAKE_CASE , flags=re.MULTILINE ) # Unique-ify return list(set(__SCREAMING_SNAKE_CASE ) ) def snake_case_ ( __SCREAMING_SNAKE_CASE : str ): """simple docstring""" lowercase_ : int = False lowercase_ : Any = [module_file] lowercase_ : Dict = [] # Let's recurse through all relative imports while not no_change: lowercase_ : Dict = [] for f in files_to_check: new_imports.extend(get_relative_imports(__SCREAMING_SNAKE_CASE ) ) lowercase_ : Union[str, Any] = Path(__SCREAMING_SNAKE_CASE ).parent lowercase_ : Optional[int] = [str(module_path / m ) for m in new_imports] lowercase_ : str = [f for f in new_import_files if f not in all_relative_imports] lowercase_ : int = [F'''{f}.py''' for f in new_import_files] lowercase_ : Optional[Any] = len(__SCREAMING_SNAKE_CASE ) == 0 all_relative_imports.extend(__SCREAMING_SNAKE_CASE ) return all_relative_imports def snake_case_ ( __SCREAMING_SNAKE_CASE : Any ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE , '''r''' , encoding='''utf-8''' ) as f: lowercase_ : Union[str, Any] = f.read() # Imports of the form `import xxx` lowercase_ : Any = re.findall('''^\s*import\s+(\S+)\s*$''' , __SCREAMING_SNAKE_CASE , flags=re.MULTILINE ) # Imports of the form `from xxx import yyy` imports += re.findall('''^\s*from\s+(\S+)\s+import''' , __SCREAMING_SNAKE_CASE , flags=re.MULTILINE ) # Only keep the top-level module lowercase_ : List[str] = [imp.split('''.''' )[0] for imp in imports if not imp.startswith('''.''' )] # Unique-ify and test we got them all lowercase_ : Any = list(set(__SCREAMING_SNAKE_CASE ) ) lowercase_ : Optional[Any] = [] for imp in imports: try: importlib.import_module(__SCREAMING_SNAKE_CASE ) except ImportError: missing_packages.append(__SCREAMING_SNAKE_CASE ) if len(__SCREAMING_SNAKE_CASE ) > 0: raise ImportError( '''This modeling file requires the following packages that were not found in your environment: ''' F'''{', '.join(__SCREAMING_SNAKE_CASE )}. Run `pip install {' '.join(__SCREAMING_SNAKE_CASE )}`''' ) return get_relative_imports(__SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" lowercase_ : List[Any] = module_path.replace(os.path.sep , '''.''' ) lowercase_ : Any = importlib.import_module(__SCREAMING_SNAKE_CASE ) if class_name is None: return find_pipeline_class(__SCREAMING_SNAKE_CASE ) return getattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" from ..pipelines import DiffusionPipeline lowercase_ : int = dict(inspect.getmembers(__SCREAMING_SNAKE_CASE , inspect.isclass ) ) lowercase_ : Optional[Any] = None for cls_name, cls in cls_members.items(): if ( cls_name != DiffusionPipeline.__name__ and issubclass(cls , __SCREAMING_SNAKE_CASE ) and cls.__module__.split('''.''' )[0] != "diffusers" ): if pipeline_class is not None: raise ValueError( F'''Multiple classes that inherit from {DiffusionPipeline.__name__} have been found:''' F''' {pipeline_class.__name__}, and {cls_name}. Please make sure to define only one in''' F''' {loaded_module}.''' ) lowercase_ : List[Any] = cls return pipeline_class def snake_case_ ( __SCREAMING_SNAKE_CASE : Union[str, os.PathLike] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Optional[Union[str, os.PathLike]] = None , __SCREAMING_SNAKE_CASE : bool = False , __SCREAMING_SNAKE_CASE : bool = False , __SCREAMING_SNAKE_CASE : Optional[Dict[str, str]] = None , __SCREAMING_SNAKE_CASE : Optional[Union[bool, str]] = None , __SCREAMING_SNAKE_CASE : Optional[str] = None , __SCREAMING_SNAKE_CASE : bool = False , ): """simple docstring""" lowercase_ : Dict = str(__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if os.path.isfile(__SCREAMING_SNAKE_CASE ): lowercase_ : Dict = module_file_or_url lowercase_ : int = '''local''' elif pretrained_model_name_or_path.count('''/''' ) == 0: lowercase_ : Optional[int] = get_diffusers_versions() # cut ".dev0" lowercase_ : List[Any] = '''v''' + '''.'''.join(__version__.split('''.''' )[:3] ) # retrieve github version that matches if revision is None: lowercase_ : List[str] = latest_version if latest_version[1:] in available_versions else '''main''' logger.info(F'''Defaulting to latest_version: {revision}.''' ) elif revision in available_versions: lowercase_ : List[str] = F'''v{revision}''' elif revision == "main": lowercase_ : Optional[Any] = revision else: raise ValueError( F'''`custom_revision`: {revision} does not exist. Please make sure to choose one of''' F''' {', '.join(available_versions + ['main'] )}.''' ) # community pipeline on GitHub lowercase_ : Tuple = COMMUNITY_PIPELINES_URL.format(revision=__SCREAMING_SNAKE_CASE , pipeline=__SCREAMING_SNAKE_CASE ) try: lowercase_ : Optional[Any] = cached_download( __SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE , force_download=__SCREAMING_SNAKE_CASE , proxies=__SCREAMING_SNAKE_CASE , resume_download=__SCREAMING_SNAKE_CASE , local_files_only=__SCREAMING_SNAKE_CASE , use_auth_token=__SCREAMING_SNAKE_CASE , ) lowercase_ : Tuple = '''git''' lowercase_ : Tuple = pretrained_model_name_or_path + '''.py''' except EnvironmentError: logger.error(F'''Could not locate the {module_file} inside {pretrained_model_name_or_path}.''' ) raise else: try: # Load from URL or cache if already cached lowercase_ : str = hf_hub_download( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE , force_download=__SCREAMING_SNAKE_CASE , proxies=__SCREAMING_SNAKE_CASE , resume_download=__SCREAMING_SNAKE_CASE , local_files_only=__SCREAMING_SNAKE_CASE , use_auth_token=__SCREAMING_SNAKE_CASE , ) lowercase_ : Optional[Any] = os.path.join('''local''' , '''--'''.join(pretrained_model_name_or_path.split('''/''' ) ) ) except EnvironmentError: logger.error(F'''Could not locate the {module_file} inside {pretrained_model_name_or_path}.''' ) raise # Check we have all the requirements in our environment lowercase_ : Tuple = check_imports(__SCREAMING_SNAKE_CASE ) # Now we move the module inside our cached dynamic modules. lowercase_ : str = DIFFUSERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule create_dynamic_module(__SCREAMING_SNAKE_CASE ) lowercase_ : Any = Path(__SCREAMING_SNAKE_CASE ) / full_submodule if submodule == "local" or submodule == "git": # We always copy local files (we could hash the file to see if there was a change, and give them the name of # that hash, to only copy when there is a modification but it seems overkill for now). # The only reason we do the copy is to avoid putting too many folders in sys.path. shutil.copy(__SCREAMING_SNAKE_CASE , submodule_path / module_file ) for module_needed in modules_needed: lowercase_ : Union[str, Any] = F'''{module_needed}.py''' shutil.copy(os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) , submodule_path / module_needed ) else: # Get the commit hash # TODO: we will get this info in the etag soon, so retrieve it from there and not here. if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase_ : Tuple = use_auth_token elif use_auth_token is True: lowercase_ : List[Any] = HfFolder.get_token() else: lowercase_ : Optional[Any] = None lowercase_ : Optional[int] = model_info(__SCREAMING_SNAKE_CASE , revision=__SCREAMING_SNAKE_CASE , token=__SCREAMING_SNAKE_CASE ).sha # The module file will end up being placed in a subfolder with the git hash of the repo. This way we get the # benefit of versioning. lowercase_ : int = submodule_path / commit_hash lowercase_ : Tuple = full_submodule + os.path.sep + commit_hash create_dynamic_module(__SCREAMING_SNAKE_CASE ) if not (submodule_path / module_file).exists(): shutil.copy(__SCREAMING_SNAKE_CASE , submodule_path / module_file ) # Make sure we also have every file with relative for module_needed in modules_needed: if not (submodule_path / module_needed).exists(): get_cached_module_file( __SCREAMING_SNAKE_CASE , F'''{module_needed}.py''' , cache_dir=__SCREAMING_SNAKE_CASE , force_download=__SCREAMING_SNAKE_CASE , resume_download=__SCREAMING_SNAKE_CASE , proxies=__SCREAMING_SNAKE_CASE , use_auth_token=__SCREAMING_SNAKE_CASE , revision=__SCREAMING_SNAKE_CASE , local_files_only=__SCREAMING_SNAKE_CASE , ) return os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Union[str, os.PathLike] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Optional[str] = None , __SCREAMING_SNAKE_CASE : Optional[Union[str, os.PathLike]] = None , __SCREAMING_SNAKE_CASE : bool = False , __SCREAMING_SNAKE_CASE : bool = False , __SCREAMING_SNAKE_CASE : Optional[Dict[str, str]] = None , __SCREAMING_SNAKE_CASE : Optional[Union[bool, str]] = None , __SCREAMING_SNAKE_CASE : Optional[str] = None , __SCREAMING_SNAKE_CASE : bool = False , **__SCREAMING_SNAKE_CASE : Optional[Any] , ): """simple docstring""" lowercase_ : Optional[Any] = get_cached_module_file( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE , force_download=__SCREAMING_SNAKE_CASE , resume_download=__SCREAMING_SNAKE_CASE , proxies=__SCREAMING_SNAKE_CASE , use_auth_token=__SCREAMING_SNAKE_CASE , revision=__SCREAMING_SNAKE_CASE , local_files_only=__SCREAMING_SNAKE_CASE , ) return get_class_in_module(__SCREAMING_SNAKE_CASE , final_module.replace('''.py''' , '''''' ) )
93
1
'''simple docstring''' import inspect import jax import jax.lax as lax import jax.numpy as jnp from ..utils import add_start_docstrings from ..utils.logging import get_logger _lowercase : Tuple = get_logger(__name__) _lowercase : Union[str, Any] = r"\n Args:\n input_ids (`jnp.ndarray` of shape `(batch_size, sequence_length)`):\n Indices of input sequence tokens in the vocabulary.\n\n Indices can be obtained using [`PreTrainedTokenizer`]. See [`PreTrainedTokenizer.encode`] and\n [`PreTrainedTokenizer.__call__`] for details.\n\n [What are input IDs?](../glossary#input-ids)\n scores (`jnp.ndarray` of shape `(batch_size, config.vocab_size)`):\n Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam\n search or log softmax for each vocabulary token when using beam search\n kwargs (`Dict[str, Any]`, *optional*):\n Additional logits processor specific kwargs.\n\n Return:\n `jnp.ndarray` of shape `(batch_size, config.vocab_size)`: The processed prediction scores.\n\n" class lowerCAmelCase__ : @add_start_docstrings(__SCREAMING_SNAKE_CASE ) def __call__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" raise NotImplementedError( F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) class lowerCAmelCase__ : @add_start_docstrings(__SCREAMING_SNAKE_CASE ) def __call__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" raise NotImplementedError( F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) class lowerCAmelCase__ ( lowerCamelCase_ ): @add_start_docstrings(__SCREAMING_SNAKE_CASE ) def __call__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" for processor in self: lowercase_ : Dict = inspect.signature(processor.__call__ ).parameters if len(__SCREAMING_SNAKE_CASE ) > 3: if not all(arg in kwargs for arg in list(function_args.keys() )[2:] ): raise ValueError( F'''Make sure that all the required parameters: {list(function_args.keys() )} for ''' F'''{processor.__class__} are passed to the logits processor.''' ) lowercase_ : Dict = processor(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) else: lowercase_ : Dict = processor(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) return scores class lowerCAmelCase__ ( lowerCamelCase_ ): def __init__( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) or not (temperature > 0): raise ValueError(F'''`temperature` has to be a strictly positive float, but is {temperature}''' ) lowercase_ : int = temperature def __call__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Tuple = scores / self.temperature return scores class lowerCAmelCase__ ( lowerCamelCase_ ): def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = -float('''Inf''' ) , __SCREAMING_SNAKE_CASE = 1 ): """simple docstring""" if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) or (top_p < 0 or top_p > 1.0): raise ValueError(F'''`top_p` has to be a float > 0 and < 1, but is {top_p}''' ) if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) or (min_tokens_to_keep < 1): raise ValueError(F'''`min_tokens_to_keep` has to be a positive integer, but is {min_tokens_to_keep}''' ) lowercase_ : Optional[int] = top_p lowercase_ : Optional[Any] = filter_value lowercase_ : Optional[Any] = min_tokens_to_keep def __call__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ , lowercase_ : Optional[int] = lax.top_k(__SCREAMING_SNAKE_CASE , scores.shape[-1] ) lowercase_ : List[str] = jnp.full_like(__SCREAMING_SNAKE_CASE , self.filter_value ) lowercase_ : List[Any] = jax.nn.softmax(__SCREAMING_SNAKE_CASE , axis=-1 ).cumsum(axis=-1 ) lowercase_ : Dict = cumulative_probs < self.top_p # include the token that is higher than top_p as well lowercase_ : List[Any] = jnp.roll(__SCREAMING_SNAKE_CASE , 1 ) score_mask |= score_mask.at[:, 0].set(__SCREAMING_SNAKE_CASE ) # min tokens to keep lowercase_ : List[str] = score_mask.at[:, : self.min_tokens_to_keep].set(__SCREAMING_SNAKE_CASE ) lowercase_ : Any = jnp.where(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : str = jax.lax.sort_key_val(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )[-1] return next_scores class lowerCAmelCase__ ( lowerCamelCase_ ): def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = -float('''Inf''' ) , __SCREAMING_SNAKE_CASE = 1 ): """simple docstring""" if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) or top_k <= 0: raise ValueError(F'''`top_k` has to be a strictly positive integer, but is {top_k}''' ) lowercase_ : str = max(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = filter_value def __call__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ , lowercase_ : Union[str, Any] = scores.shape lowercase_ : int = jnp.full(batch_size * vocab_size , self.filter_value ) lowercase_ : List[Any] = min(self.top_k , scores.shape[-1] ) # Safety check lowercase_ , lowercase_ : int = lax.top_k(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : Dict = jnp.broadcast_to((jnp.arange(__SCREAMING_SNAKE_CASE ) * vocab_size)[:, None] , (batch_size, topk) ).flatten() lowercase_ : int = topk_scores.flatten() lowercase_ : Tuple = topk_indices.flatten() + shift lowercase_ : str = next_scores_flat.at[topk_indices_flat].set(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = next_scores_flat.reshape(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) return next_scores class lowerCAmelCase__ ( lowerCamelCase_ ): def __init__( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Dict = bos_token_id def __call__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Optional[Any] = jnp.full(scores.shape , -float('''inf''' ) ) lowercase_ : Union[str, Any] = 1 - jnp.bool_(cur_len - 1 ) lowercase_ : Optional[int] = jnp.where(__SCREAMING_SNAKE_CASE , new_scores.at[:, self.bos_token_id].set(0 ) , __SCREAMING_SNAKE_CASE ) return scores class lowerCAmelCase__ ( lowerCamelCase_ ): def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Any = max_length lowercase_ : Union[str, Any] = eos_token_id def __call__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Optional[int] = jnp.full(scores.shape , -float('''inf''' ) ) lowercase_ : List[str] = 1 - jnp.bool_(cur_len - self.max_length + 1 ) lowercase_ : Union[str, Any] = jnp.where(__SCREAMING_SNAKE_CASE , new_scores.at[:, self.eos_token_id].set(0 ) , __SCREAMING_SNAKE_CASE ) return scores class lowerCAmelCase__ ( lowerCamelCase_ ): def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) or min_length < 0: raise ValueError(F'''`min_length` has to be a positive integer, but is {min_length}''' ) if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) or eos_token_id < 0: raise ValueError(F'''`eos_token_id` has to be a positive integer, but is {eos_token_id}''' ) lowercase_ : str = min_length lowercase_ : List[Any] = eos_token_id def __call__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Dict = 1 - jnp.clip(cur_len - self.min_length , 0 , 1 ) lowercase_ : Dict = jnp.where(__SCREAMING_SNAKE_CASE , scores.at[:, self.eos_token_id].set(-float('''inf''' ) ) , __SCREAMING_SNAKE_CASE ) return scores class lowerCAmelCase__ ( lowerCamelCase_ ): def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Optional[int] = list(__SCREAMING_SNAKE_CASE ) lowercase_ : str = begin_index def __call__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : List[str] = 1 - jnp.bool_(cur_len - self.begin_index ) lowercase_ : Optional[int] = jnp.where(__SCREAMING_SNAKE_CASE , scores.at[:, self.begin_suppress_tokens].set(-float('''inf''' ) ) , __SCREAMING_SNAKE_CASE ) return scores class lowerCAmelCase__ ( lowerCamelCase_ ): def __init__( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Optional[int] = list(__SCREAMING_SNAKE_CASE ) def __call__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Tuple = scores.at[..., self.suppress_tokens].set(-float('''inf''' ) ) return scores class lowerCAmelCase__ ( lowerCamelCase_ ): def __init__( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : List[str] = dict(__SCREAMING_SNAKE_CASE ) # Converts the dictionary of format {index: token} containing the tokens to be forced to an array, where the # index of the array corresponds to the index of the token to be forced, for XLA compatibility. # Indexes without forced tokens will have a negative value. lowercase_ : Optional[int] = jnp.ones((max(force_token_map.keys() ) + 1) , dtype=jnp.intaa ) * -1 for index, token in force_token_map.items(): if token is not None: lowercase_ : List[Any] = force_token_array.at[index].set(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = jnp.intaa(__SCREAMING_SNAKE_CASE ) def __call__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" def _force_token(__SCREAMING_SNAKE_CASE ): lowercase_ : Any = scores.shape[0] lowercase_ : str = self.force_token_array[generation_idx] lowercase_ : Union[str, Any] = jnp.ones_like(__SCREAMING_SNAKE_CASE , dtype=scores.dtype ) * -float('''inf''' ) lowercase_ : Optional[int] = jnp.zeros((batch_size, 1) , dtype=scores.dtype ) lowercase_ : int = lax.dynamic_update_slice(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , (0, current_token) ) return new_scores lowercase_ : Any = lax.cond( cur_len >= self.force_token_array.shape[0] , lambda: scores , lambda: lax.cond( self.force_token_array[cur_len] >= 0 , lambda: _force_token(__SCREAMING_SNAKE_CASE ) , lambda: scores , ) , ) return scores class lowerCAmelCase__ ( lowerCamelCase_ ): def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Optional[int] = generate_config.eos_token_id lowercase_ : List[str] = generate_config.no_timestamps_token_id lowercase_ : str = generate_config.no_timestamps_token_id + 1 lowercase_ : Any = decoder_input_length + 1 if generate_config.is_multilingual: # room for language token and task token self.begin_index += 2 if hasattr(__SCREAMING_SNAKE_CASE , '''max_initial_timestamp_index''' ): lowercase_ : List[Any] = generate_config.max_initial_timestamp_index else: lowercase_ : Dict = model_config.vocab_size if self.max_initial_timestamp_index is None: lowercase_ : Optional[Any] = model_config.vocab_size def __call__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Any = scores.at[:, self.no_timestamps_token_id].set(-float('''inf''' ) ) def handle_pairs(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase_ : int = jnp.where((cur_len - self.begin_index) >= 1 , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : Dict = jnp.where( input_ids_k[cur_len - 1] >= self.timestamp_begin , True and last_was_timestamp , __SCREAMING_SNAKE_CASE , ) lowercase_ : Optional[int] = jnp.where((cur_len - self.begin_index) < 2 , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : str = jnp.where( input_ids_k[cur_len - 2] >= self.timestamp_begin , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , ) return jnp.where( __SCREAMING_SNAKE_CASE , jnp.where( penultimate_was_timestamp > 0 , scores_k.at[self.timestamp_begin :].set(-float('''inf''' ) ) , scores_k.at[: self.eos_token_id].set(-float('''inf''' ) ) , ) , __SCREAMING_SNAKE_CASE , ) lowercase_ : Dict = jax.vmap(__SCREAMING_SNAKE_CASE )(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = jnp.where(cur_len == self.begin_index , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = jnp.where( self.max_initial_timestamp_index is not None , True and apply_max_initial_timestamp , __SCREAMING_SNAKE_CASE , ) lowercase_ : Union[str, Any] = self.timestamp_begin + self.max_initial_timestamp_index lowercase_ : Optional[Any] = jnp.where( __SCREAMING_SNAKE_CASE , scores.at[:, last_allowed + 1 :].set(-float('''inf''' ) ) , __SCREAMING_SNAKE_CASE , ) # if sum of probability over timestamps is above any other token, sample timestamp lowercase_ : List[Any] = jax.nn.log_softmax(__SCREAMING_SNAKE_CASE , axis=-1 ) def handle_cumulative_probs(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase_ : Union[str, Any] = jax.nn.logsumexp(logprobs_k[self.timestamp_begin :] , axis=-1 ) lowercase_ : List[str] = jnp.max(logprobs_k[: self.timestamp_begin] ) return jnp.where( timestamp_logprob > max_text_token_logprob , scores_k.at[: self.timestamp_begin].set(-float('''inf''' ) ) , __SCREAMING_SNAKE_CASE , ) lowercase_ : int = jax.vmap(__SCREAMING_SNAKE_CASE )(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) return scores
93
'''simple docstring''' import re import tempfile from pathlib import Path import pytest import yaml from datasets.utils.readme import ReadMe # @pytest.fixture # def example_yaml_structure(): _lowercase : Union[str, Any] = yaml.safe_load( "\\nname: \"\"\nallow_empty: false\nallow_empty_text: true\nsubsections:\n - name: \"Dataset Card for X\" # First-level markdown heading\n allow_empty: false\n allow_empty_text: true\n subsections:\n - name: \"Table of Contents\"\n allow_empty: false\n allow_empty_text: false\n subsections: null\n - name: \"Dataset Description\"\n allow_empty: false\n allow_empty_text: false\n subsections:\n - name: \"Dataset Summary\"\n allow_empty: false\n allow_empty_text: false\n subsections: null\n - name: \"Supported Tasks and Leaderboards\"\n allow_empty: true\n allow_empty_text: true\n subsections: null\n - name: Languages\n allow_empty: false\n allow_empty_text: true\n subsections: null\n" ) _lowercase : int = { "name": "root", "text": "", "is_empty_text": True, "subsections": [ { "name": "Dataset Card for My Dataset", "text": "", "is_empty_text": True, "subsections": [ {"name": "Table of Contents", "text": "Some text here.", "is_empty_text": False, "subsections": []}, { "name": "Dataset Description", "text": "Some text here.", "is_empty_text": False, "subsections": [ { "name": "Dataset Summary", "text": "Some text here.", "is_empty_text": False, "subsections": [], }, { "name": "Supported Tasks and Leaderboards", "text": "", "is_empty_text": True, "subsections": [], }, {"name": "Languages", "text": "Language Text", "is_empty_text": False, "subsections": []}, ], }, ], } ], } _lowercase : Optional[Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Union[str, Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n#### Extra Ignored Subsection\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Any = { "name": "root", "text": "", "is_empty_text": True, "subsections": [ { "name": "Dataset Card for My Dataset", "text": "", "is_empty_text": True, "subsections": [ {"name": "Table of Contents", "text": "Some text here.", "is_empty_text": False, "subsections": []}, { "name": "Dataset Description", "text": "Some text here.", "is_empty_text": False, "subsections": [ { "name": "Dataset Summary", "text": "Some text here.", "is_empty_text": False, "subsections": [ { "name": "Extra Ignored Subsection", "text": "", "is_empty_text": True, "subsections": [], } ], }, { "name": "Supported Tasks and Leaderboards", "text": "", "is_empty_text": True, "subsections": [], }, {"name": "Languages", "text": "Language Text", "is_empty_text": False, "subsections": []}, ], }, ], } ], } _lowercase : str = "\\n---\n---\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : List[str] = ( "The following issues were found for the README at `{path}`:\n-\tEmpty YAML markers are present in the README." ) _lowercase : Tuple = "\\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Optional[Any] = ( "The following issues were found for the README at `{path}`:\n-\tNo YAML markers are present in the README." ) _lowercase : Tuple = "\\n---\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Optional[int] = "The following issues were found for the README at `{path}`:\n-\tOnly the start of YAML tags present in the README." _lowercase : List[Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Optional[Any] = "The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Summary` but it is empty.\n-\tExpected some text in section `Dataset Summary` but it is empty (text in subsections are ignored)." _lowercase : Optional[int] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n" _lowercase : Union[str, Any] = "The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Card for My Dataset` but it is empty.\n-\tSection `Dataset Card for My Dataset` expected the following subsections: `Table of Contents`, `Dataset Description`. Found 'None'." _lowercase : Union[str, Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Languages\nLanguage Text\n" _lowercase : int = "The following issues were found for the README at `{path}`:\n-\tSection `Dataset Description` is missing subsection: `Supported Tasks and Leaderboards`." _lowercase : List[Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\n" _lowercase : int = "The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Languages` but it is empty." _lowercase : List[str] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : str = "The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README." _lowercase : Dict = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n# Dataset Card My Dataset\n" _lowercase : List[str] = "The following issues were found for the README at `{path}`:\n-\tThe README has several first-level headings: `Dataset Card for My Dataset`, `Dataset Card My Dataset`. Only one heading is expected. Skipping further validation for this README." _lowercase : str = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Union[str, Any] = "The following issues were found for the README at `{path}`:\n-\tNo first-level heading starting with `Dataset Card for` found in README. Skipping further validation for this README." _lowercase : List[Any] = "" _lowercase : Optional[Any] = "The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README.\n-\tNo YAML markers are present in the README." _lowercase : List[Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" _lowercase : Optional[Any] = "The following issues were found while parsing the README at `{path}`:\n-\tMultiple sections with the same heading `Dataset Card for My Dataset` have been found. Please keep only one of these sections." @pytest.mark.parametrize( '''readme_md, expected_dict''' , [ (README_CORRECT, CORRECT_DICT), (README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" assert ReadMe.from_string(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).to_dict() == expected_dict @pytest.mark.parametrize( '''readme_md, expected_error''' , [ (README_NO_YAML, EXPECTED_ERROR_README_NO_YAML), (README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML), (README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML), (README_EMPTY, EXPECTED_ERROR_README_EMPTY), (README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION), (README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL), (README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION), (README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT), (README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL), (README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL), (README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" with pytest.raises(__SCREAMING_SNAKE_CASE , match=re.escape(expected_error.format(path='''root''' ) ) ): lowercase_ : Optional[int] = ReadMe.from_string(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) readme.validate() @pytest.mark.parametrize( '''readme_md, expected_error''' , [ (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" with pytest.raises(__SCREAMING_SNAKE_CASE , match=re.escape(expected_error.format(path='''root''' ) ) ): ReadMe.from_string(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( '''readme_md,''' , [ (README_MULTIPLE_SAME_HEADING_1), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Any ): """simple docstring""" ReadMe.from_string(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , suppress_parsing_errors=__SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( '''readme_md, expected_dict''' , [ (README_CORRECT, CORRECT_DICT), (README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : str ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: lowercase_ : Optional[int] = Path(__SCREAMING_SNAKE_CASE ) / '''README.md''' with open(__SCREAMING_SNAKE_CASE , '''w+''' ) as readme_file: readme_file.write(__SCREAMING_SNAKE_CASE ) lowercase_ : Any = ReadMe.from_readme(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).to_dict() assert out["name"] == path assert out["text"] == "" assert out["is_empty_text"] assert out["subsections"] == expected_dict["subsections"] @pytest.mark.parametrize( '''readme_md, expected_error''' , [ (README_NO_YAML, EXPECTED_ERROR_README_NO_YAML), (README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML), (README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML), (README_EMPTY, EXPECTED_ERROR_README_EMPTY), (README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION), (README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL), (README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION), (README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT), (README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL), (README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL), (README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: lowercase_ : str = Path(__SCREAMING_SNAKE_CASE ) / '''README.md''' with open(__SCREAMING_SNAKE_CASE , '''w+''' ) as readme_file: readme_file.write(__SCREAMING_SNAKE_CASE ) lowercase_ : List[str] = expected_error.format(path=__SCREAMING_SNAKE_CASE ) with pytest.raises(__SCREAMING_SNAKE_CASE , match=re.escape(__SCREAMING_SNAKE_CASE ) ): lowercase_ : int = ReadMe.from_readme(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) readme.validate() @pytest.mark.parametrize( '''readme_md, expected_error''' , [ (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: lowercase_ : Dict = Path(__SCREAMING_SNAKE_CASE ) / '''README.md''' with open(__SCREAMING_SNAKE_CASE , '''w+''' ) as readme_file: readme_file.write(__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = expected_error.format(path=__SCREAMING_SNAKE_CASE ) with pytest.raises(__SCREAMING_SNAKE_CASE , match=re.escape(__SCREAMING_SNAKE_CASE ) ): ReadMe.from_readme(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( '''readme_md,''' , [ (README_MULTIPLE_SAME_HEADING_1), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: lowercase_ : Optional[int] = Path(__SCREAMING_SNAKE_CASE ) / '''README.md''' with open(__SCREAMING_SNAKE_CASE , '''w+''' ) as readme_file: readme_file.write(__SCREAMING_SNAKE_CASE ) ReadMe.from_readme(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , suppress_parsing_errors=__SCREAMING_SNAKE_CASE )
93
1
'''simple docstring''' import pytest from datasets.splits import SplitDict, SplitInfo from datasets.utils.py_utils import asdict @pytest.mark.parametrize( '''split_dict''' , [ SplitDict(), SplitDict({'''train''': SplitInfo(name='''train''' , num_bytes=1337 , num_examples=42 , dataset_name='''my_dataset''' )} ), SplitDict({'''train''': SplitInfo(name='''train''' , num_bytes=1337 , num_examples=42 )} ), SplitDict({'''train''': SplitInfo()} ), ] , ) def snake_case_ ( __SCREAMING_SNAKE_CASE : SplitDict ): """simple docstring""" lowercase_ : Dict = split_dict._to_yaml_list() assert len(__SCREAMING_SNAKE_CASE ) == len(__SCREAMING_SNAKE_CASE ) lowercase_ : Any = SplitDict._from_yaml_list(__SCREAMING_SNAKE_CASE ) for split_name, split_info in split_dict.items(): # dataset_name field is deprecated, and is therefore not part of the YAML dump lowercase_ : str = None # the split name of split_dict takes over the name of the split info object lowercase_ : Any = split_name assert split_dict == reloaded @pytest.mark.parametrize( '''split_info''' , [SplitInfo(), SplitInfo(dataset_name=__SCREAMING_SNAKE_CASE ), SplitInfo(dataset_name='''my_dataset''' )] ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" lowercase_ : List[str] = asdict(SplitDict({'''train''': split_info} ) ) assert "dataset_name" in split_dict_asdict["train"] assert split_dict_asdict["train"]["dataset_name"] == split_info.dataset_name
93
'''simple docstring''' import math import time from typing import Dict, List, Optional from torch.utils.data import Dataset from transformers import SeqaSeqTrainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput, speed_metrics if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class lowerCAmelCase__ ( lowerCamelCase_ ): def __init__( self , *__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , **__SCREAMING_SNAKE_CASE ): """simple docstring""" super().__init__(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = eval_examples lowercase_ : Tuple = post_process_function def _snake_case ( self , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = "eval" , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : Optional[int] = gen_kwargs.copy() lowercase_ : List[str] = ( gen_kwargs['''max_length'''] if gen_kwargs.get('''max_length''' ) is not None else self.args.generation_max_length ) lowercase_ : str = ( gen_kwargs['''num_beams'''] if gen_kwargs.get('''num_beams''' ) is not None else self.args.generation_num_beams ) lowercase_ : Dict = gen_kwargs lowercase_ : List[Any] = self.eval_dataset if eval_dataset is None else eval_dataset lowercase_ : List[str] = self.get_eval_dataloader(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. lowercase_ : Union[str, Any] = self.compute_metrics lowercase_ : Optional[int] = None lowercase_ : Tuple = time.time() lowercase_ : Tuple = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: lowercase_ : str = eval_loop( __SCREAMING_SNAKE_CASE , description='''Evaluation''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=__SCREAMING_SNAKE_CASE , metric_key_prefix=__SCREAMING_SNAKE_CASE , ) finally: lowercase_ : Any = compute_metrics lowercase_ : Any = self.args.eval_batch_size * self.args.world_size if F'''{metric_key_prefix}_jit_compilation_time''' in output.metrics: start_time += output.metrics[F'''{metric_key_prefix}_jit_compilation_time'''] output.metrics.update( speed_metrics( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save: # Only the main node write the results by default lowercase_ : Optional[Any] = self.post_process_function(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = self.compute_metrics(__SCREAMING_SNAKE_CASE ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F'''{metric_key_prefix}_''' ): lowercase_ : List[Any] = metrics.pop(__SCREAMING_SNAKE_CASE ) metrics.update(output.metrics ) else: lowercase_ : List[Any] = output.metrics if self.args.should_log: # Only the main node log the results by default self.log(__SCREAMING_SNAKE_CASE ) if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report() ) lowercase_ : List[Any] = self.callback_handler.on_evaluate(self.args , self.state , self.control , __SCREAMING_SNAKE_CASE ) return metrics def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE = "test" , **__SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Union[str, Any] = gen_kwargs.copy() lowercase_ : Tuple = self.get_test_dataloader(__SCREAMING_SNAKE_CASE ) # Temporarily disable metric computation, we will do it in the loop here. lowercase_ : Optional[Any] = self.compute_metrics lowercase_ : Optional[int] = None lowercase_ : List[Any] = time.time() lowercase_ : int = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: lowercase_ : Tuple = eval_loop( __SCREAMING_SNAKE_CASE , description='''Prediction''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=__SCREAMING_SNAKE_CASE , metric_key_prefix=__SCREAMING_SNAKE_CASE , ) finally: lowercase_ : Any = compute_metrics lowercase_ : Tuple = self.args.eval_batch_size * self.args.world_size if F'''{metric_key_prefix}_jit_compilation_time''' in output.metrics: start_time += output.metrics[F'''{metric_key_prefix}_jit_compilation_time'''] output.metrics.update( speed_metrics( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is None or self.compute_metrics is None: return output lowercase_ : Any = self.post_process_function(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , '''predict''' ) lowercase_ : str = self.compute_metrics(__SCREAMING_SNAKE_CASE ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F'''{metric_key_prefix}_''' ): lowercase_ : Optional[int] = metrics.pop(__SCREAMING_SNAKE_CASE ) metrics.update(output.metrics ) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=__SCREAMING_SNAKE_CASE )
93
1
'''simple docstring''' import argparse import os import re _lowercase : int = "src/transformers" # Pattern that looks at the indentation in a line. _lowercase : int = re.compile(r"^(\s*)\S") # Pattern that matches `"key":" and puts `key` in group 0. _lowercase : Tuple = re.compile(r"^\s*\"([^\"]+)\":") # Pattern that matches `_import_structure["key"]` and puts `key` in group 0. _lowercase : Dict = re.compile(r"^\s*_import_structure\[\"([^\"]+)\"\]") # Pattern that matches `"key",` and puts `key` in group 0. _lowercase : Union[str, Any] = re.compile(r"^\s*\"([^\"]+)\",\s*$") # Pattern that matches any `[stuff]` and puts `stuff` in group 0. _lowercase : List[str] = re.compile(r"\[([^\]]+)\]") def snake_case_ ( __SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" lowercase_ : Any = _re_indent.search(__SCREAMING_SNAKE_CASE ) return "" if search is None else search.groups()[0] def snake_case_ ( __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : Tuple="" , __SCREAMING_SNAKE_CASE : Optional[Any]=None , __SCREAMING_SNAKE_CASE : Optional[Any]=None ): """simple docstring""" lowercase_ : Union[str, Any] = 0 lowercase_ : Dict = code.split('''\n''' ) if start_prompt is not None: while not lines[index].startswith(__SCREAMING_SNAKE_CASE ): index += 1 lowercase_ : int = ['''\n'''.join(lines[:index] )] else: lowercase_ : Optional[Any] = [] # We split into blocks until we get to the `end_prompt` (or the end of the block). lowercase_ : Optional[Any] = [lines[index]] index += 1 while index < len(__SCREAMING_SNAKE_CASE ) and (end_prompt is None or not lines[index].startswith(__SCREAMING_SNAKE_CASE )): if len(lines[index] ) > 0 and get_indent(lines[index] ) == indent_level: if len(__SCREAMING_SNAKE_CASE ) > 0 and get_indent(current_block[-1] ).startswith(indent_level + ''' ''' ): current_block.append(lines[index] ) blocks.append('''\n'''.join(__SCREAMING_SNAKE_CASE ) ) if index < len(__SCREAMING_SNAKE_CASE ) - 1: lowercase_ : Optional[Any] = [lines[index + 1]] index += 1 else: lowercase_ : Tuple = [] else: blocks.append('''\n'''.join(__SCREAMING_SNAKE_CASE ) ) lowercase_ : List[Any] = [lines[index]] else: current_block.append(lines[index] ) index += 1 # Adds current block if it's nonempty. if len(__SCREAMING_SNAKE_CASE ) > 0: blocks.append('''\n'''.join(__SCREAMING_SNAKE_CASE ) ) # Add final block after end_prompt if provided. if end_prompt is not None and index < len(__SCREAMING_SNAKE_CASE ): blocks.append('''\n'''.join(lines[index:] ) ) return blocks def snake_case_ ( __SCREAMING_SNAKE_CASE : List[Any] ): """simple docstring""" def _inner(__SCREAMING_SNAKE_CASE : Union[str, Any] ): return key(__SCREAMING_SNAKE_CASE ).lower().replace('''_''' , '''''' ) return _inner def snake_case_ ( __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : List[str]=None ): """simple docstring""" def noop(__SCREAMING_SNAKE_CASE : List[str] ): return x if key is None: lowercase_ : Optional[Any] = noop # Constants are all uppercase, they go first. lowercase_ : str = [obj for obj in objects if key(__SCREAMING_SNAKE_CASE ).isupper()] # Classes are not all uppercase but start with a capital, they go second. lowercase_ : str = [obj for obj in objects if key(__SCREAMING_SNAKE_CASE )[0].isupper() and not key(__SCREAMING_SNAKE_CASE ).isupper()] # Functions begin with a lowercase, they go last. lowercase_ : List[str] = [obj for obj in objects if not key(__SCREAMING_SNAKE_CASE )[0].isupper()] lowercase_ : str = ignore_underscore(__SCREAMING_SNAKE_CASE ) return sorted(__SCREAMING_SNAKE_CASE , key=__SCREAMING_SNAKE_CASE ) + sorted(__SCREAMING_SNAKE_CASE , key=__SCREAMING_SNAKE_CASE ) + sorted(__SCREAMING_SNAKE_CASE , key=__SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" def _replace(__SCREAMING_SNAKE_CASE : Dict ): lowercase_ : List[str] = match.groups()[0] if "," not in imports: return F'''[{imports}]''' lowercase_ : Union[str, Any] = [part.strip().replace('''"''' , '''''' ) for part in imports.split(''',''' )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: lowercase_ : Dict = keys[:-1] return "[" + ", ".join([F'''"{k}"''' for k in sort_objects(__SCREAMING_SNAKE_CASE )] ) + "]" lowercase_ : List[str] = import_statement.split('''\n''' ) if len(__SCREAMING_SNAKE_CASE ) > 3: # Here we have to sort internal imports that are on several lines (one per name): # key: [ # "object1", # "object2", # ... # ] # We may have to ignore one or two lines on each side. lowercase_ : int = 2 if lines[1].strip() == '''[''' else 1 lowercase_ : Optional[int] = [(i, _re_strip_line.search(__SCREAMING_SNAKE_CASE ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )] lowercase_ : str = sort_objects(__SCREAMING_SNAKE_CASE , key=lambda __SCREAMING_SNAKE_CASE : x[1] ) lowercase_ : Any = [lines[x[0] + idx] for x in sorted_indices] return "\n".join(lines[:idx] + sorted_lines + lines[-idx:] ) elif len(__SCREAMING_SNAKE_CASE ) == 3: # Here we have to sort internal imports that are on one separate line: # key: [ # "object1", "object2", ... # ] if _re_bracket_content.search(lines[1] ) is not None: lowercase_ : int = _re_bracket_content.sub(_replace , lines[1] ) else: lowercase_ : str = [part.strip().replace('''"''' , '''''' ) for part in lines[1].split(''',''' )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: lowercase_ : Optional[int] = keys[:-1] lowercase_ : str = get_indent(lines[1] ) + ''', '''.join([F'''"{k}"''' for k in sort_objects(__SCREAMING_SNAKE_CASE )] ) return "\n".join(__SCREAMING_SNAKE_CASE ) else: # Finally we have to deal with imports fitting on one line lowercase_ : List[str] = _re_bracket_content.sub(_replace , __SCREAMING_SNAKE_CASE ) return import_statement def snake_case_ ( __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Any=True ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE , encoding='''utf-8''' ) as f: lowercase_ : Optional[int] = f.read() if "_import_structure" not in code: return # Blocks of indent level 0 lowercase_ : Dict = split_code_in_indented_blocks( __SCREAMING_SNAKE_CASE , start_prompt='''_import_structure = {''' , end_prompt='''if TYPE_CHECKING:''' ) # We ignore block 0 (everything untils start_prompt) and the last block (everything after end_prompt). for block_idx in range(1 , len(__SCREAMING_SNAKE_CASE ) - 1 ): # Check if the block contains some `_import_structure`s thingy to sort. lowercase_ : Dict = main_blocks[block_idx] lowercase_ : str = block.split('''\n''' ) # Get to the start of the imports. lowercase_ : Any = 0 while line_idx < len(__SCREAMING_SNAKE_CASE ) and "_import_structure" not in block_lines[line_idx]: # Skip dummy import blocks if "import dummy" in block_lines[line_idx]: lowercase_ : Dict = len(__SCREAMING_SNAKE_CASE ) else: line_idx += 1 if line_idx >= len(__SCREAMING_SNAKE_CASE ): continue # Ignore beginning and last line: they don't contain anything. lowercase_ : Any = '''\n'''.join(block_lines[line_idx:-1] ) lowercase_ : Tuple = get_indent(block_lines[1] ) # Slit the internal block into blocks of indent level 1. lowercase_ : Tuple = split_code_in_indented_blocks(__SCREAMING_SNAKE_CASE , indent_level=__SCREAMING_SNAKE_CASE ) # We have two categories of import key: list or _import_structure[key].append/extend lowercase_ : str = _re_direct_key if '''_import_structure = {''' in block_lines[0] else _re_indirect_key # Grab the keys, but there is a trap: some lines are empty or just comments. lowercase_ : Optional[int] = [(pattern.search(__SCREAMING_SNAKE_CASE ).groups()[0] if pattern.search(__SCREAMING_SNAKE_CASE ) is not None else None) for b in internal_blocks] # We only sort the lines with a key. lowercase_ : List[str] = [(i, key) for i, key in enumerate(__SCREAMING_SNAKE_CASE ) if key is not None] lowercase_ : Optional[Any] = [x[0] for x in sorted(__SCREAMING_SNAKE_CASE , key=lambda __SCREAMING_SNAKE_CASE : x[1] )] # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. lowercase_ : int = 0 lowercase_ : Union[str, Any] = [] for i in range(len(__SCREAMING_SNAKE_CASE ) ): if keys[i] is None: reorderded_blocks.append(internal_blocks[i] ) else: lowercase_ : Optional[Any] = sort_objects_in_import(internal_blocks[sorted_indices[count]] ) reorderded_blocks.append(__SCREAMING_SNAKE_CASE ) count += 1 # And we put our main block back together with its first and last line. lowercase_ : int = '''\n'''.join(block_lines[:line_idx] + reorderded_blocks + [block_lines[-1]] ) if code != "\n".join(__SCREAMING_SNAKE_CASE ): if check_only: return True else: print(F'''Overwriting {file}.''' ) with open(__SCREAMING_SNAKE_CASE , '''w''' , encoding='''utf-8''' ) as f: f.write('''\n'''.join(__SCREAMING_SNAKE_CASE ) ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[int]=True ): """simple docstring""" lowercase_ : str = [] for root, _, files in os.walk(__SCREAMING_SNAKE_CASE ): if "__init__.py" in files: lowercase_ : Optional[Any] = sort_imports(os.path.join(__SCREAMING_SNAKE_CASE , '''__init__.py''' ) , check_only=__SCREAMING_SNAKE_CASE ) if result: lowercase_ : List[str] = [os.path.join(__SCREAMING_SNAKE_CASE , '''__init__.py''' )] if len(__SCREAMING_SNAKE_CASE ) > 0: raise ValueError(F'''Would overwrite {len(__SCREAMING_SNAKE_CASE )} files, run `make style`.''' ) if __name__ == "__main__": _lowercase : Union[str, Any] = argparse.ArgumentParser() parser.add_argument("--check_only", action="store_true", help="Whether to only check or fix style.") _lowercase : Any = parser.parse_args() sort_imports_in_all_inits(check_only=args.check_only)
93
'''simple docstring''' from pathlib import Path from typing import List from transformers import is_torch_available, is_vision_available from transformers.testing_utils import get_tests_dir, is_tool_test from transformers.tools.agent_types import AGENT_TYPE_MAPPING, AgentAudio, AgentImage, AgentText if is_torch_available(): import torch if is_vision_available(): from PIL import Image _lowercase : List[str] = ["text", "image", "audio"] def snake_case_ ( __SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" lowercase_ : int = [] for input_type in input_types: if input_type == "text": inputs.append('''Text input''' ) elif input_type == "image": inputs.append( Image.open(Path(get_tests_dir('''fixtures/tests_samples/COCO''' ) ) / '''000000039769.png''' ).resize((512, 512) ) ) elif input_type == "audio": inputs.append(torch.ones(3000 ) ) elif isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): inputs.append(create_inputs(__SCREAMING_SNAKE_CASE ) ) else: raise ValueError(F'''Invalid type requested: {input_type}''' ) return inputs def snake_case_ ( __SCREAMING_SNAKE_CASE : List ): """simple docstring""" lowercase_ : Optional[Any] = [] for output in outputs: if isinstance(__SCREAMING_SNAKE_CASE , (str, AgentText) ): output_types.append('''text''' ) elif isinstance(__SCREAMING_SNAKE_CASE , (Image.Image, AgentImage) ): output_types.append('''image''' ) elif isinstance(__SCREAMING_SNAKE_CASE , (torch.Tensor, AgentAudio) ): output_types.append('''audio''' ) else: raise ValueError(F'''Invalid output: {output}''' ) return output_types @is_tool_test class lowerCAmelCase__ : def _snake_case ( self ): """simple docstring""" self.assertTrue(hasattr(self.tool , '''inputs''' ) ) self.assertTrue(hasattr(self.tool , '''outputs''' ) ) lowercase_ : Optional[Any] = self.tool.inputs for _input in inputs: if isinstance(_input , __SCREAMING_SNAKE_CASE ): for __input in _input: self.assertTrue(__input in authorized_types ) else: self.assertTrue(_input in authorized_types ) lowercase_ : int = self.tool.outputs for _output in outputs: self.assertTrue(_output in authorized_types ) def _snake_case ( self ): """simple docstring""" lowercase_ : int = create_inputs(self.tool.inputs ) lowercase_ : Tuple = self.tool(*__SCREAMING_SNAKE_CASE ) # There is a single output if len(self.tool.outputs ) == 1: lowercase_ : Any = [outputs] self.assertListEqual(output_types(__SCREAMING_SNAKE_CASE ) , self.tool.outputs ) def _snake_case ( self ): """simple docstring""" self.assertTrue(hasattr(self.tool , '''description''' ) ) self.assertTrue(hasattr(self.tool , '''default_checkpoint''' ) ) self.assertTrue(self.tool.description.startswith('''This is a tool that''' ) ) def _snake_case ( self ): """simple docstring""" lowercase_ : int = create_inputs(self.tool.inputs ) lowercase_ : int = self.tool(*__SCREAMING_SNAKE_CASE ) if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase_ : Optional[Any] = [outputs] self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , len(self.tool.outputs ) ) for output, output_type in zip(__SCREAMING_SNAKE_CASE , self.tool.outputs ): lowercase_ : Optional[int] = AGENT_TYPE_MAPPING[output_type] self.assertTrue(isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) def _snake_case ( self ): """simple docstring""" lowercase_ : Dict = create_inputs(self.tool.inputs ) lowercase_ : int = [] for _input, input_type in zip(__SCREAMING_SNAKE_CASE , self.tool.inputs ): if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): _inputs.append([AGENT_TYPE_MAPPING[_input_type](_input ) for _input_type in input_type] ) else: _inputs.append(AGENT_TYPE_MAPPING[input_type](_input ) ) # Should not raise an error lowercase_ : Optional[Any] = self.tool(*__SCREAMING_SNAKE_CASE ) if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase_ : Dict = [outputs] self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , len(self.tool.outputs ) )
93
1
'''simple docstring''' import itertools import json import os import unittest from transformers import AddedToken, RobertaTokenizer, RobertaTokenizerFast from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowerCAmelCase__ ( lowerCamelCase_ , unittest.TestCase ): lowerCAmelCase_ = RobertaTokenizer lowerCAmelCase_ = RobertaTokenizerFast lowerCAmelCase_ = True lowerCAmelCase_ = {'''cls_token''': '''<s>'''} def _snake_case ( self ): """simple docstring""" super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt lowercase_ : Any = [ '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''\u0120''', '''\u0120l''', '''\u0120n''', '''\u0120lo''', '''\u0120low''', '''er''', '''\u0120lowest''', '''\u0120newer''', '''\u0120wider''', '''<unk>''', ] lowercase_ : List[str] = dict(zip(__SCREAMING_SNAKE_CASE , range(len(__SCREAMING_SNAKE_CASE ) ) ) ) lowercase_ : List[Any] = ['''#version: 0.2''', '''\u0120 l''', '''\u0120l o''', '''\u0120lo w''', '''e r''', ''''''] lowercase_ : Union[str, Any] = {'''unk_token''': '''<unk>'''} lowercase_ : Optional[int] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) lowercase_ : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(__SCREAMING_SNAKE_CASE ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(__SCREAMING_SNAKE_CASE ) ) def _snake_case ( self , **__SCREAMING_SNAKE_CASE ): """simple docstring""" kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def _snake_case ( self , **__SCREAMING_SNAKE_CASE ): """simple docstring""" kwargs.update(self.special_tokens_map ) return RobertaTokenizerFast.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : List[Any] = '''lower newer''' lowercase_ : Dict = '''lower newer''' return input_text, output_text def _snake_case ( self ): """simple docstring""" lowercase_ : Optional[int] = self.tokenizer_class(self.vocab_file , self.merges_file , **self.special_tokens_map ) lowercase_ : List[Any] = '''lower newer''' lowercase_ : Union[str, Any] = ['''l''', '''o''', '''w''', '''er''', '''\u0120''', '''n''', '''e''', '''w''', '''er'''] lowercase_ : Union[str, Any] = tokenizer.tokenize(__SCREAMING_SNAKE_CASE ) # , add_prefix_space=True) self.assertListEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = tokens + [tokenizer.unk_token] lowercase_ : Tuple = [0, 1, 2, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" lowercase_ : List[str] = self.get_tokenizer() self.assertListEqual(tokenizer.encode('''Hello world!''' , add_special_tokens=__SCREAMING_SNAKE_CASE ) , [0, 3_14_14, 2_32, 3_28, 2] ) self.assertListEqual( tokenizer.encode('''Hello world! cécé herlolip 418''' , add_special_tokens=__SCREAMING_SNAKE_CASE ) , [0, 3_14_14, 2_32, 3_28, 7_40, 11_40, 1_26_95, 69, 4_60_78, 15_88, 2] , ) @slow def _snake_case ( self ): """simple docstring""" lowercase_ : List[Any] = self.tokenizer_class.from_pretrained('''roberta-base''' ) lowercase_ : Optional[Any] = tokenizer.encode('''sequence builders''' , add_special_tokens=__SCREAMING_SNAKE_CASE ) lowercase_ : List[Any] = tokenizer.encode('''multi-sequence build''' , add_special_tokens=__SCREAMING_SNAKE_CASE ) lowercase_ : str = tokenizer.encode( '''sequence builders''' , add_special_tokens=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE ) lowercase_ : str = tokenizer.encode( '''sequence builders''' , '''multi-sequence build''' , add_special_tokens=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE ) lowercase_ : str = tokenizer.build_inputs_with_special_tokens(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = tokenizer.build_inputs_with_special_tokens(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) assert encoded_sentence == encoded_text_from_decode assert encoded_pair == encoded_pair_from_decode def _snake_case ( self ): """simple docstring""" lowercase_ : Tuple = self.get_tokenizer() lowercase_ : Optional[Any] = '''Encode this sequence.''' lowercase_ : Optional[Any] = tokenizer.byte_encoder[''' '''.encode('''utf-8''' )[0]] # Testing encoder arguments lowercase_ : int = tokenizer.encode(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertNotEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = tokenizer.encode(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE ) lowercase_ : List[Any] = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) tokenizer.add_special_tokens({'''bos_token''': '''<s>'''} ) lowercase_ : List[str] = tokenizer.encode(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE ) lowercase_ : Any = tokenizer.convert_ids_to_tokens(encoded[1] )[0] self.assertNotEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Testing spaces after special tokens lowercase_ : Any = '''<mask>''' tokenizer.add_special_tokens( {'''mask_token''': AddedToken(__SCREAMING_SNAKE_CASE , lstrip=__SCREAMING_SNAKE_CASE , rstrip=__SCREAMING_SNAKE_CASE )} ) # mask token has a left space lowercase_ : List[Any] = tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) lowercase_ : int = '''Encode <mask> sequence''' lowercase_ : List[Any] = '''Encode <mask>sequence''' lowercase_ : Tuple = tokenizer.encode(__SCREAMING_SNAKE_CASE ) lowercase_ : Dict = encoded.index(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : List[str] = tokenizer.encode(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = encoded.index(__SCREAMING_SNAKE_CASE ) lowercase_ : str = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertNotEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" pass def _snake_case ( self ): """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): lowercase_ : Optional[Any] = self.rust_tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = self.tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) lowercase_ : str = '''A, <mask> AllenNLP sentence.''' lowercase_ : Optional[int] = tokenizer_r.encode_plus(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , return_token_type_ids=__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = tokenizer_p.encode_plus(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , return_token_type_ids=__SCREAMING_SNAKE_CASE ) # token_type_ids should put 0 everywhere self.assertEqual(sum(tokens_r['''token_type_ids'''] ) , sum(tokens_p['''token_type_ids'''] ) ) # attention_mask should put 1 everywhere, so sum over length should be 1 self.assertEqual( sum(tokens_r['''attention_mask'''] ) / len(tokens_r['''attention_mask'''] ) , sum(tokens_p['''attention_mask'''] ) / len(tokens_p['''attention_mask'''] ) , ) lowercase_ : Union[str, Any] = tokenizer_r.convert_ids_to_tokens(tokens_r['''input_ids'''] ) lowercase_ : List[Any] = tokenizer_p.convert_ids_to_tokens(tokens_p['''input_ids'''] ) # Rust correctly handles the space before the mask while python doesnt self.assertSequenceEqual(tokens_p['''input_ids'''] , [0, 2_50, 6, 5_02_64, 38_23, 4_87, 2_19_92, 36_45, 4, 2] ) self.assertSequenceEqual(tokens_r['''input_ids'''] , [0, 2_50, 6, 5_02_64, 38_23, 4_87, 2_19_92, 36_45, 4, 2] ) self.assertSequenceEqual( __SCREAMING_SNAKE_CASE , ['''<s>''', '''A''', ''',''', '''<mask>''', '''ĠAllen''', '''N''', '''LP''', '''Ġsentence''', '''.''', '''</s>'''] ) self.assertSequenceEqual( __SCREAMING_SNAKE_CASE , ['''<s>''', '''A''', ''',''', '''<mask>''', '''ĠAllen''', '''N''', '''LP''', '''Ġsentence''', '''.''', '''</s>'''] ) def _snake_case ( self ): """simple docstring""" for trim_offsets, add_prefix_space in itertools.product([True, False] , repeat=2 ): lowercase_ : List[str] = self.rust_tokenizer_class.from_pretrained( self.tmpdirname , use_fast=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE , trim_offsets=__SCREAMING_SNAKE_CASE ) lowercase_ : List[str] = json.loads(tokenizer_r.backend_tokenizer.pre_tokenizer.__getstate__() ) lowercase_ : List[Any] = json.loads(tokenizer_r.backend_tokenizer.post_processor.__getstate__() ) self.assertEqual(pre_tokenizer_state['''add_prefix_space'''] , __SCREAMING_SNAKE_CASE ) self.assertEqual(post_processor_state['''add_prefix_space'''] , __SCREAMING_SNAKE_CASE ) self.assertEqual(post_processor_state['''trim_offsets'''] , __SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): lowercase_ : Optional[Any] = '''hello''' # `hello` is a token in the vocabulary of `pretrained_name` lowercase_ : int = F'''{text_of_1_token} {text_of_1_token}''' lowercase_ : Dict = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , use_fast=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE , trim_offsets=__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = tokenizer_r(__SCREAMING_SNAKE_CASE , return_offsets_mapping=__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(encoding.offset_mapping[0] , (0, len(__SCREAMING_SNAKE_CASE )) ) self.assertEqual( encoding.offset_mapping[1] , (len(__SCREAMING_SNAKE_CASE ) + 1, len(__SCREAMING_SNAKE_CASE ) + 1 + len(__SCREAMING_SNAKE_CASE )) , ) lowercase_ : Optional[int] = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , use_fast=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE , trim_offsets=__SCREAMING_SNAKE_CASE ) lowercase_ : List[str] = tokenizer_r(__SCREAMING_SNAKE_CASE , return_offsets_mapping=__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(encoding.offset_mapping[0] , (0, len(__SCREAMING_SNAKE_CASE )) ) self.assertEqual( encoding.offset_mapping[1] , (len(__SCREAMING_SNAKE_CASE ) + 1, len(__SCREAMING_SNAKE_CASE ) + 1 + len(__SCREAMING_SNAKE_CASE )) , ) lowercase_ : Optional[Any] = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , use_fast=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE , trim_offsets=__SCREAMING_SNAKE_CASE ) lowercase_ : Dict = tokenizer_r(__SCREAMING_SNAKE_CASE , return_offsets_mapping=__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(encoding.offset_mapping[0] , (0, len(__SCREAMING_SNAKE_CASE )) ) self.assertEqual( encoding.offset_mapping[1] , (len(__SCREAMING_SNAKE_CASE ), len(__SCREAMING_SNAKE_CASE ) + 1 + len(__SCREAMING_SNAKE_CASE )) , ) lowercase_ : Union[str, Any] = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , use_fast=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE , trim_offsets=__SCREAMING_SNAKE_CASE ) lowercase_ : Dict = tokenizer_r(__SCREAMING_SNAKE_CASE , return_offsets_mapping=__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(encoding.offset_mapping[0] , (0, len(__SCREAMING_SNAKE_CASE )) ) self.assertEqual( encoding.offset_mapping[1] , (len(__SCREAMING_SNAKE_CASE ), len(__SCREAMING_SNAKE_CASE ) + 1 + len(__SCREAMING_SNAKE_CASE )) , ) lowercase_ : List[str] = F''' {text}''' # tokenizer_r = self.rust_tokenizer_class.from_pretrained( # pretrained_name, use_fast=True, add_prefix_space=True, trim_offsets=True # ) # encoding = tokenizer_r(text, return_offsets_mapping=True, add_special_tokens=False) # self.assertEqual(encoding.offset_mapping[0], (1, 1 + len(text_of_1_token))) # self.assertEqual( # encoding.offset_mapping[1], # (1 + len(text_of_1_token) + 1, 1 + len(text_of_1_token) + 1 + len(text_of_1_token)), # ) lowercase_ : str = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , use_fast=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE , trim_offsets=__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = tokenizer_r(__SCREAMING_SNAKE_CASE , return_offsets_mapping=__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(__SCREAMING_SNAKE_CASE )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(__SCREAMING_SNAKE_CASE ) + 1, 1 + len(__SCREAMING_SNAKE_CASE ) + 1 + len(__SCREAMING_SNAKE_CASE )) , ) lowercase_ : Any = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , use_fast=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE , trim_offsets=__SCREAMING_SNAKE_CASE ) lowercase_ : str = tokenizer_r(__SCREAMING_SNAKE_CASE , return_offsets_mapping=__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(__SCREAMING_SNAKE_CASE )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(__SCREAMING_SNAKE_CASE ), 1 + len(__SCREAMING_SNAKE_CASE ) + 1 + len(__SCREAMING_SNAKE_CASE )) , ) lowercase_ : List[str] = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , use_fast=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE , trim_offsets=__SCREAMING_SNAKE_CASE ) lowercase_ : Dict = tokenizer_r(__SCREAMING_SNAKE_CASE , return_offsets_mapping=__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(__SCREAMING_SNAKE_CASE )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(__SCREAMING_SNAKE_CASE ), 1 + len(__SCREAMING_SNAKE_CASE ) + 1 + len(__SCREAMING_SNAKE_CASE )) , )
93
'''simple docstring''' # DISCLAIMER: This file is strongly influenced by https://github.com/ermongroup/ddim from dataclasses import dataclass from typing import Optional, Tuple, Union import flax import jax import jax.numpy as jnp from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils_flax import ( CommonSchedulerState, FlaxKarrasDiffusionSchedulers, FlaxSchedulerMixin, FlaxSchedulerOutput, add_noise_common, get_velocity_common, ) @flax.struct.dataclass class lowerCAmelCase__ : lowerCAmelCase_ = 42 # setable values lowerCAmelCase_ = 42 lowerCAmelCase_ = 42 lowerCAmelCase_ = None @classmethod def _snake_case ( cls , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" return cls(common=__SCREAMING_SNAKE_CASE , init_noise_sigma=__SCREAMING_SNAKE_CASE , timesteps=__SCREAMING_SNAKE_CASE ) @dataclass class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = 42 class lowerCAmelCase__ ( lowerCamelCase_ , lowerCamelCase_ ): lowerCAmelCase_ = [e.name for e in FlaxKarrasDiffusionSchedulers] lowerCAmelCase_ = 42 @property def _snake_case ( self ): """simple docstring""" return True @register_to_config def __init__( self , __SCREAMING_SNAKE_CASE = 10_00 , __SCREAMING_SNAKE_CASE = 0.0_001 , __SCREAMING_SNAKE_CASE = 0.02 , __SCREAMING_SNAKE_CASE = "linear" , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = "fixed_small" , __SCREAMING_SNAKE_CASE = True , __SCREAMING_SNAKE_CASE = "epsilon" , __SCREAMING_SNAKE_CASE = jnp.floataa , ): """simple docstring""" lowercase_ : Dict = dtype def _snake_case ( self , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" if common is None: lowercase_ : Tuple = CommonSchedulerState.create(self ) # standard deviation of the initial noise distribution lowercase_ : Union[str, Any] = jnp.array(1.0 , dtype=self.dtype ) lowercase_ : List[Any] = jnp.arange(0 , self.config.num_train_timesteps ).round()[::-1] return DDPMSchedulerState.create( common=__SCREAMING_SNAKE_CASE , init_noise_sigma=__SCREAMING_SNAKE_CASE , timesteps=__SCREAMING_SNAKE_CASE , ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" return sample def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = () ): """simple docstring""" lowercase_ : Optional[Any] = self.config.num_train_timesteps // num_inference_steps # creates integer timesteps by multiplying by ratio # rounding to avoid issues when num_inference_step is power of 3 lowercase_ : int = (jnp.arange(0 , __SCREAMING_SNAKE_CASE ) * step_ratio).round()[::-1] return state.replace( num_inference_steps=__SCREAMING_SNAKE_CASE , timesteps=__SCREAMING_SNAKE_CASE , ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None ): """simple docstring""" lowercase_ : List[Any] = state.common.alphas_cumprod[t] lowercase_ : str = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) ) # For t > 0, compute predicted variance βt (see formula (6) and (7) from https://arxiv.org/pdf/2006.11239.pdf) # and sample from it to get previous sample # x_{t-1} ~ N(pred_prev_sample, variance) == add variance to pred_sample lowercase_ : int = (1 - alpha_prod_t_prev) / (1 - alpha_prod_t) * state.common.betas[t] if variance_type is None: lowercase_ : str = self.config.variance_type # hacks - were probably added for training stability if variance_type == "fixed_small": lowercase_ : int = jnp.clip(__SCREAMING_SNAKE_CASE , a_min=1E-2_0 ) # for rl-diffuser https://arxiv.org/abs/2205.09991 elif variance_type == "fixed_small_log": lowercase_ : List[str] = jnp.log(jnp.clip(__SCREAMING_SNAKE_CASE , a_min=1E-2_0 ) ) elif variance_type == "fixed_large": lowercase_ : List[Any] = state.common.betas[t] elif variance_type == "fixed_large_log": # Glide max_log lowercase_ : List[Any] = jnp.log(state.common.betas[t] ) elif variance_type == "learned": return predicted_variance elif variance_type == "learned_range": lowercase_ : Optional[Any] = variance lowercase_ : Union[str, Any] = state.common.betas[t] lowercase_ : Union[str, Any] = (predicted_variance + 1) / 2 lowercase_ : Any = frac * max_log + (1 - frac) * min_log return variance def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = True , ): """simple docstring""" lowercase_ : Optional[int] = timestep if key is None: lowercase_ : int = jax.random.PRNGKey(0 ) if model_output.shape[1] == sample.shape[1] * 2 and self.config.variance_type in ["learned", "learned_range"]: lowercase_ , lowercase_ : Optional[Any] = jnp.split(__SCREAMING_SNAKE_CASE , sample.shape[1] , axis=1 ) else: lowercase_ : int = None # 1. compute alphas, betas lowercase_ : Any = state.common.alphas_cumprod[t] lowercase_ : Optional[int] = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) ) lowercase_ : int = 1 - alpha_prod_t lowercase_ : str = 1 - alpha_prod_t_prev # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if self.config.prediction_type == "epsilon": lowercase_ : Tuple = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif self.config.prediction_type == "sample": lowercase_ : Any = model_output elif self.config.prediction_type == "v_prediction": lowercase_ : List[Any] = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output else: raise ValueError( F'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample` ''' ''' for the FlaxDDPMScheduler.''' ) # 3. Clip "predicted x_0" if self.config.clip_sample: lowercase_ : Optional[Any] = jnp.clip(__SCREAMING_SNAKE_CASE , -1 , 1 ) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf lowercase_ : List[Any] = (alpha_prod_t_prev ** 0.5 * state.common.betas[t]) / beta_prod_t lowercase_ : Optional[Any] = state.common.alphas[t] ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf lowercase_ : Optional[Any] = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise def random_variance(): lowercase_ : str = jax.random.split(__SCREAMING_SNAKE_CASE , num=1 ) lowercase_ : List[Any] = jax.random.normal(__SCREAMING_SNAKE_CASE , shape=model_output.shape , dtype=self.dtype ) return (self._get_variance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , predicted_variance=__SCREAMING_SNAKE_CASE ) ** 0.5) * noise lowercase_ : Optional[Any] = jnp.where(t > 0 , random_variance() , jnp.zeros(model_output.shape , dtype=self.dtype ) ) lowercase_ : Any = pred_prev_sample + variance if not return_dict: return (pred_prev_sample, state) return FlaxDDPMSchedulerOutput(prev_sample=__SCREAMING_SNAKE_CASE , state=__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , ): """simple docstring""" return add_noise_common(state.common , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , ): """simple docstring""" return get_velocity_common(state.common , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def __len__( self ): """simple docstring""" return self.config.num_train_timesteps
93
1
'''simple docstring''' # tests directory-specific settings - this file is run automatically # by pytest before any tests are run import sys import warnings from os.path import abspath, dirname, join # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. _lowercase : Dict = abspath(join(dirname(dirname(__file__)), "src")) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action="ignore", category=FutureWarning) def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" from diffusers.utils.testing_utils import pytest_addoption_shared pytest_addoption_shared(__SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" from diffusers.utils.testing_utils import pytest_terminal_summary_main lowercase_ : Optional[Any] = terminalreporter.config.getoption('''--make-reports''' ) if make_reports: pytest_terminal_summary_main(__SCREAMING_SNAKE_CASE , id=__SCREAMING_SNAKE_CASE )
93
'''simple docstring''' _lowercase : int = [sum(int(c, 1_0) ** 2 for c in i.__str__()) for i in range(1_0_0_0_0_0)] def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : Optional[int] = 0 while number: # Increased Speed Slightly by checking every 5 digits together. sum_of_digits_squared += DIGITS_SQUARED[number % 100000] number //= 100000 return sum_of_digits_squared # There are 2 Chains made, # One ends with 89 with the chain member 58 being the one which when declared first, # there will be the least number of iterations for all the members to be checked. # The other one ends with 1 and has only one element 1. # So 58 and 1 are chosen to be declared at the starting. # Changed dictionary to an array to quicken the solution _lowercase : list[bool | None] = [None] * 1_0_0_0_0_0_0_0 _lowercase : List[str] = True _lowercase : Optional[int] = False def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" if CHAINS[number - 1] is not None: return CHAINS[number - 1] # type: ignore lowercase_ : Tuple = chain(next_number(__SCREAMING_SNAKE_CASE ) ) lowercase_ : Union[str, Any] = number_chain while number < 10000000: lowercase_ : int = number_chain number *= 10 return number_chain def snake_case_ ( __SCREAMING_SNAKE_CASE : int = 10000000 ): """simple docstring""" for i in range(1 , __SCREAMING_SNAKE_CASE ): if CHAINS[i] is None: chain(i + 1 ) return CHAINS[:number].count(__SCREAMING_SNAKE_CASE ) if __name__ == "__main__": import doctest doctest.testmod() print(f"""{solution() = }""")
93
1
'''simple docstring''' from sklearn.metrics import fa_score, matthews_corrcoef import datasets from .record_evaluation import evaluate as evaluate_record _lowercase : Any = "\\n@article{wang2019superglue,\n title={SuperGLUE: A Stickier Benchmark for General-Purpose Language Understanding Systems},\n author={Wang, Alex and Pruksachatkun, Yada and Nangia, Nikita and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R},\n journal={arXiv preprint arXiv:1905.00537},\n year={2019}\n}\n" _lowercase : List[Any] = "\\nSuperGLUE (https://super.gluebenchmark.com/) is a new benchmark styled after\nGLUE with a new set of more difficult language understanding tasks, improved\nresources, and a new public leaderboard.\n" _lowercase : Optional[Any] = "\nCompute SuperGLUE evaluation metric associated to each SuperGLUE dataset.\nArgs:\n predictions: list of predictions to score. Depending on the SuperGlUE subset:\n - for 'record': list of question-answer dictionaries with the following keys:\n - 'idx': index of the question as specified by the dataset\n - 'prediction_text': the predicted answer text\n - for 'multirc': list of question-answer dictionaries with the following keys:\n - 'idx': index of the question-answer pair as specified by the dataset\n - 'prediction': the predicted answer label\n - otherwise: list of predicted labels\n references: list of reference labels. Depending on the SuperGLUE subset:\n - for 'record': list of question-answers dictionaries with the following keys:\n - 'idx': index of the question as specified by the dataset\n - 'answers': list of possible answers\n - otherwise: list of reference labels\nReturns: depending on the SuperGLUE subset:\n - for 'record':\n - 'exact_match': Exact match between answer and gold answer\n - 'f1': F1 score\n - for 'multirc':\n - 'exact_match': Exact match between answer and gold answer\n - 'f1_m': Per-question macro-F1 score\n - 'f1_a': Average F1 score over all answers\n - for 'axb':\n 'matthews_correlation': Matthew Correlation\n - for 'cb':\n - 'accuracy': Accuracy\n - 'f1': F1 score\n - for all others:\n - 'accuracy': Accuracy\nExamples:\n\n >>> super_glue_metric = datasets.load_metric('super_glue', 'copa') # any of [\"copa\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"boolq\", \"axg\"]\n >>> predictions = [0, 1]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'accuracy': 1.0}\n\n >>> super_glue_metric = datasets.load_metric('super_glue', 'cb')\n >>> predictions = [0, 1]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'accuracy': 1.0, 'f1': 1.0}\n\n >>> super_glue_metric = datasets.load_metric('super_glue', 'record')\n >>> predictions = [{'idx': {'passage': 0, 'query': 0}, 'prediction_text': 'answer'}]\n >>> references = [{'idx': {'passage': 0, 'query': 0}, 'answers': ['answer', 'another_answer']}]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'exact_match': 1.0, 'f1': 1.0}\n\n >>> super_glue_metric = datasets.load_metric('super_glue', 'multirc')\n >>> predictions = [{'idx': {'answer': 0, 'paragraph': 0, 'question': 0}, 'prediction': 0}, {'idx': {'answer': 1, 'paragraph': 2, 'question': 3}, 'prediction': 1}]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'exact_match': 1.0, 'f1_m': 1.0, 'f1_a': 1.0}\n\n >>> super_glue_metric = datasets.load_metric('super_glue', 'axb')\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'matthews_correlation': 1.0}\n" def snake_case_ ( __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : str ): """simple docstring""" return float((preds == labels).mean() ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : str="binary" ): """simple docstring""" lowercase_ : Dict = simple_accuracy(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = float(fa_score(y_true=__SCREAMING_SNAKE_CASE , y_pred=__SCREAMING_SNAKE_CASE , average=__SCREAMING_SNAKE_CASE ) ) return { "accuracy": acc, "f1": fa, } def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[int] ): """simple docstring""" lowercase_ : str = {} for id_pred, label in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase_ : str = F'''{id_pred['idx']['paragraph']}-{id_pred['idx']['question']}''' lowercase_ : Any = id_pred['''prediction'''] if question_id in question_map: question_map[question_id].append((pred, label) ) else: lowercase_ : List[str] = [(pred, label)] lowercase_ , lowercase_ : Dict = [], [] for question, preds_labels in question_map.items(): lowercase_ , lowercase_ : List[Any] = zip(*__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = fa_score(y_true=__SCREAMING_SNAKE_CASE , y_pred=__SCREAMING_SNAKE_CASE , average='''macro''' ) fas.append(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = int(sum(pred == label for pred, label in preds_labels ) == len(__SCREAMING_SNAKE_CASE ) ) ems.append(__SCREAMING_SNAKE_CASE ) lowercase_ : str = float(sum(__SCREAMING_SNAKE_CASE ) / len(__SCREAMING_SNAKE_CASE ) ) lowercase_ : Tuple = sum(__SCREAMING_SNAKE_CASE ) / len(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = float(fa_score(y_true=__SCREAMING_SNAKE_CASE , y_pred=[id_pred['''prediction'''] for id_pred in ids_preds] ) ) return {"exact_match": em, "f1_m": fa_m, "f1_a": fa_a} @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase__ ( datasets.Metric ): def _snake_case ( self ): """simple docstring""" if self.config_name not in [ "boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg", ]: raise KeyError( '''You should supply a configuration name selected in ''' '''["boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg",]''' ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , codebase_urls=[] , reference_urls=[] , format='''numpy''' if not self.config_name == '''record''' and not self.config_name == '''multirc''' else None , ) def _snake_case ( self ): """simple docstring""" if self.config_name == "record": return { "predictions": { "idx": { "passage": datasets.Value('''int64''' ), "query": datasets.Value('''int64''' ), }, "prediction_text": datasets.Value('''string''' ), }, "references": { "idx": { "passage": datasets.Value('''int64''' ), "query": datasets.Value('''int64''' ), }, "answers": datasets.Sequence(datasets.Value('''string''' ) ), }, } elif self.config_name == "multirc": return { "predictions": { "idx": { "answer": datasets.Value('''int64''' ), "paragraph": datasets.Value('''int64''' ), "question": datasets.Value('''int64''' ), }, "prediction": datasets.Value('''int64''' ), }, "references": datasets.Value('''int64''' ), } else: return { "predictions": datasets.Value('''int64''' ), "references": datasets.Value('''int64''' ), } def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" if self.config_name == "axb": return {"matthews_correlation": matthews_corrcoef(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )} elif self.config_name == "cb": return acc_and_fa(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , fa_avg='''macro''' ) elif self.config_name == "record": lowercase_ : List[str] = [ { '''qas''': [ {'''id''': ref['''idx''']['''query'''], '''answers''': [{'''text''': ans} for ans in ref['''answers''']]} for ref in references ] } ] lowercase_ : str = {pred['''idx''']['''query''']: pred['''prediction_text'''] for pred in predictions} return evaluate_record(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )[0] elif self.config_name == "multirc": return evaluate_multirc(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) elif self.config_name in ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]: return {"accuracy": simple_accuracy(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )} else: raise KeyError( '''You should supply a configuration name selected in ''' '''["boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg",]''' )
93
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _lowercase : Union[str, Any] = { "configuration_pix2struct": [ "PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP", "Pix2StructConfig", "Pix2StructTextConfig", "Pix2StructVisionConfig", ], "processing_pix2struct": ["Pix2StructProcessor"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : Dict = ["Pix2StructImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : List[str] = [ "PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST", "Pix2StructPreTrainedModel", "Pix2StructForConditionalGeneration", "Pix2StructVisionModel", "Pix2StructTextModel", ] if TYPE_CHECKING: from .configuration_pixastruct import ( PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP, PixaStructConfig, PixaStructTextConfig, PixaStructVisionConfig, ) from .processing_pixastruct import PixaStructProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_pixastruct import PixaStructImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_pixastruct import ( PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST, PixaStructForConditionalGeneration, PixaStructPreTrainedModel, PixaStructTextModel, PixaStructVisionModel, ) else: import sys _lowercase : Optional[int] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
93
1
'''simple docstring''' import unittest from transformers import load_tool from transformers.utils import is_torch_available if is_torch_available(): import torch from transformers.testing_utils import require_torch from .test_tools_common import ToolTesterMixin @require_torch class lowerCAmelCase__ ( unittest.TestCase , lowerCamelCase_ ): def _snake_case ( self ): """simple docstring""" lowercase_ : List[Any] = load_tool('''text-to-speech''' ) self.tool.setup() def _snake_case ( self ): """simple docstring""" torch.manual_seed(0 ) lowercase_ : Dict = self.tool('''hey''' ) lowercase_ : List[Any] = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] , torch.tensor([-0.0_005_966_668_832_115_829, -0.0_003_657_640_190_795_064, -0.00_013_439_502_799_883_485] ) , ) ) def _snake_case ( self ): """simple docstring""" torch.manual_seed(0 ) lowercase_ : Optional[Any] = self.tool('''hey''' ) lowercase_ : Optional[int] = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] , torch.tensor([-0.0_005_966_668_832_115_829, -0.0_003_657_640_190_795_064, -0.00_013_439_502_799_883_485] ) , ) )
93
'''simple docstring''' def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : Optional[int] = int(__SCREAMING_SNAKE_CASE ) if decimal in (0, 1): # Exit cases for the recursion return str(__SCREAMING_SNAKE_CASE ) lowercase_ , lowercase_ : List[str] = divmod(__SCREAMING_SNAKE_CASE , 2 ) return binary_recursive(__SCREAMING_SNAKE_CASE ) + str(__SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : str ): """simple docstring""" lowercase_ : str = str(__SCREAMING_SNAKE_CASE ).strip() if not number: raise ValueError('''No input value was provided''' ) lowercase_ : Optional[int] = '''-''' if number.startswith('''-''' ) else '''''' lowercase_ : Union[str, Any] = number.lstrip('''-''' ) if not number.isnumeric(): raise ValueError('''Input value is not an integer''' ) return F'''{negative}0b{binary_recursive(int(__SCREAMING_SNAKE_CASE ) )}''' if __name__ == "__main__": from doctest import testmod testmod()
93
1
'''simple docstring''' from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_pool as _descriptor_pool from google.protobuf import symbol_database as _symbol_database from google.protobuf.internal import builder as _builder # @@protoc_insertion_point(imports) _lowercase : Tuple = _symbol_database.Default() _lowercase : List[Any] = _descriptor_pool.Default().AddSerializedFile( B"\n\x19sentencepiece_model.proto\x12\rsentencepiece\"\x80\x0c\n\x0bTrainerSpec\x12\r\n\x05input\x18\x01 \x03(\t\x12\x14\n\x0cinput_format\x18\x07 \x01(\t\x12\x14\n\x0cmodel_prefix\x18\x02 \x01(\t\x12\x41\n\nmodel_type\x18\x03 \x01(\x0e\x32$.sentencepiece.TrainerSpec.ModelType:\x07UNIGRAM\x12\x18\n\nvocab_size\x18\x04 \x01(\x05:\x04\x38\x30\x30\x30\x12\x17\n\x0f\x61\x63\x63\x65pt_language\x18\x05 \x03(\t\x12 \n\x15self_test_sample_size\x18\x06 \x01(\x05:\x01\x30\x12*\n\x1b\x65nable_differential_privacy\x18\x32 \x01(\x08:\x05\x66\x61lse\x12+\n differential_privacy_noise_level\x18\x33 \x01(\x02:\x01\x30\x12\x32\n\'differential_privacy_clipping_threshold\x18\x34 \x01(\x04:\x01\x30\x12\"\n\x12\x63haracter_coverage\x18\n \x01(\x02:\x06\x30.9995\x12\x1e\n\x13input_sentence_size\x18\x0b \x01(\x04:\x01\x30\x12$\n\x16shuffle_input_sentence\x18\x13 \x01(\x08:\x04true\x12 \n\x14mining_sentence_size\x18\x0c \x01(\x05\x42\x02\x18\x01\x12\"\n\x16training_sentence_size\x18\r \x01(\x05\x42\x02\x18\x01\x12(\n\x17seed_sentencepiece_size\x18\x0e \x01(\x05:\x07\x31\x30\x30\x30\x30\x30\x30\x12\x1e\n\x10shrinking_factor\x18\x0f \x01(\x02:\x04\x30.75\x12!\n\x13max_sentence_length\x18\x12 \x01(\x05:\x04\x34\x31\x39\x32\x12\x17\n\x0bnum_threads\x18\x10 \x01(\x05:\x02\x31\x36\x12\x1d\n\x12num_sub_iterations\x18\x11 \x01(\x05:\x01\x32\x12$\n\x18max_sentencepiece_length\x18\x14 \x01(\x05:\x02\x31\x36\x12%\n\x17split_by_unicode_script\x18\x15 \x01(\x08:\x04true\x12\x1d\n\x0fsplit_by_number\x18\x17 \x01(\x08:\x04true\x12!\n\x13split_by_whitespace\x18\x16 \x01(\x08:\x04true\x12)\n\x1atreat_whitespace_as_suffix\x18\x18 \x01(\x08:\x05\x66\x61lse\x12+\n\x1c\x61llow_whitespace_only_pieces\x18\x1a \x01(\x08:\x05\x66\x61lse\x12\x1b\n\x0csplit_digits\x18\x19 \x01(\x08:\x05\x66\x61lse\x12#\n\x19pretokenization_delimiter\x18\x35 \x01(\t:\x00\x12\x17\n\x0f\x63ontrol_symbols\x18\x1e \x03(\t\x12\x1c\n\x14user_defined_symbols\x18\x1f \x03(\t\x12\x16\n\x0erequired_chars\x18$ \x01(\t\x12\x1c\n\rbyte_fallback\x18# \x01(\x08:\x05\x66\x61lse\x12+\n\x1dvocabulary_output_piece_score\x18 \x01(\x08:\x04true\x12\x1e\n\x10hard_vocab_limit\x18! \x01(\x08:\x04true\x12\x1c\n\ruse_all_vocab\x18\" \x01(\x08:\x05\x66\x61lse\x12\x11\n\x06unk_id\x18( \x01(\x05:\x01\x30\x12\x11\n\x06\x62os_id\x18) \x01(\x05:\x01\x31\x12\x11\n\x06\x65os_id\x18* \x01(\x05:\x01\x32\x12\x12\n\x06pad_id\x18+ \x01(\x05:\x02-1\x12\x18\n\tunk_piece\x18- \x01(\t:\x05<unk>\x12\x16\n\tbos_piece\x18. \x01(\t:\x03<s>\x12\x17\n\teos_piece\x18/ \x01(\t:\x04</s>\x12\x18\n\tpad_piece\x18\x30 \x01(\t:\x05<pad>\x12\x1a\n\x0bunk_surface\x18, \x01(\t:\x05 \xe2\x81\x87 \x12+\n\x1ctrain_extremely_large_corpus\x18\x31 \x01(\x08:\x05\x66\x61lse\"5\n\tModelType\x12\x0b\n\x07UNIGRAM\x10\x01\x12\x07\n\x03\x42PE\x10\x02\x12\x08\n\x04WORD\x10\x03\x12\x08\n\x04\x43HAR\x10\x04*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\"\xd1\x01\n\x0eNormalizerSpec\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x1c\n\x14precompiled_charsmap\x18\x02 \x01(\x0c\x12\x1e\n\x10\x61\x64\x64_dummy_prefix\x18\x03 \x01(\x08:\x04true\x12&\n\x18remove_extra_whitespaces\x18\x04 \x01(\x08:\x04true\x12 \n\x12\x65scape_whitespaces\x18\x05 \x01(\x08:\x04true\x12\x1e\n\x16normalization_rule_tsv\x18\x06 \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\"y\n\x0cSelfTestData\x12\x33\n\x07samples\x18\x01 \x03(\x0b\x32\".sentencepiece.SelfTestData.Sample\x1a)\n\x06Sample\x12\r\n\x05input\x18\x01 \x01(\t\x12\x10\n\x08\x65xpected\x18\x02 \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\"\xfe\x03\n\nModelProto\x12\x37\n\x06pieces\x18\x01 \x03(\x0b\x32\'.sentencepiece.ModelProto.SentencePiece\x12\x30\n\x0ctrainer_spec\x18\x02 \x01(\x0b\x32\x1a.sentencepiece.TrainerSpec\x12\x36\n\x0fnormalizer_spec\x18\x03 \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x12\x33\n\x0eself_test_data\x18\x04 \x01(\x0b\x32\x1b.sentencepiece.SelfTestData\x12\x38\n\x11\x64\x65normalizer_spec\x18\x05 \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x1a\xd2\x01\n\rSentencePiece\x12\r\n\x05piece\x18\x01 \x01(\t\x12\r\n\x05score\x18\x02 \x01(\x02\x12\x42\n\x04type\x18\x03 \x01(\x0e\x32,.sentencepiece.ModelProto.SentencePiece.Type:\x06NORMAL\"T\n\x04Type\x12\n\n\x06NORMAL\x10\x01\x12\x0b\n\x07UNKNOWN\x10\x02\x12\x0b\n\x07\x43ONTROL\x10\x03\x12\x10\n\x0cUSER_DEFINED\x10\x04\x12\x08\n\x04\x42YTE\x10\x06\x12\n\n\x06UNUSED\x10\x05*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\x42\x02H\x03" ) _lowercase : Optional[Any] = globals() _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, "sentencepiece_model_pb2", _globals) if _descriptor._USE_C_DESCRIPTORS is False: _lowercase : Optional[Any] = None _lowercase : int = B"H\003" # (generated by protobuf compiler, but `_TRAINERSPEC` is not defined) # _TRAINERSPEC.fields_by_name["mining_sentence_size"]._options = None # _TRAINERSPEC.fields_by_name["mining_sentence_size"]._serialized_options = b"\030\001" # _TRAINERSPEC.fields_by_name["training_sentence_size"]._options = None # _TRAINERSPEC.fields_by_name["training_sentence_size"]._serialized_options = b"\030\001" _lowercase : Dict = 4_5 _lowercase : int = 1_5_8_1 _lowercase : Any = 1_5_1_7 _lowercase : Dict = 1_5_7_0 _lowercase : List[str] = 1_5_8_4 _lowercase : Any = 1_7_9_3 _lowercase : Optional[int] = 1_7_9_5 _lowercase : List[Any] = 1_9_1_6 _lowercase : List[str] = 1_8_6_4 _lowercase : Optional[Any] = 1_9_0_5 _lowercase : List[Any] = 1_9_1_9 _lowercase : int = 2_4_2_9 _lowercase : Dict = 2_2_0_8 _lowercase : Any = 2_4_1_8 _lowercase : str = 2_3_2_3 _lowercase : str = 2_4_0_7 # @@protoc_insertion_point(module_scope)
93
'''simple docstring''' import glob import os import random from string import ascii_lowercase, digits import cva import numpy as np # Parrameters _lowercase : Any = (7_2_0, 1_2_8_0) # Height, Width _lowercase : List[Any] = (0.4, 0.6) # if height or width lower than this scale, drop it. _lowercase : str = 1 / 1_0_0 _lowercase : Any = "" _lowercase : Union[str, Any] = "" _lowercase : Optional[int] = "" _lowercase : List[Any] = 2_5_0 def snake_case_ ( ): """simple docstring""" lowercase_ , lowercase_ : Any = get_dataset(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) for index in range(__SCREAMING_SNAKE_CASE ): lowercase_ : str = random.sample(range(len(__SCREAMING_SNAKE_CASE ) ) , 4 ) lowercase_ , lowercase_ , lowercase_ : Any = 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' lowercase_ : int = random_chars(32 ) lowercase_ : str = path.split(os.sep )[-1].rsplit('''.''' , 1 )[0] lowercase_ : int = F'''{OUTPUT_DIR}/{file_name}_MOSAIC_{letter_code}''' cva.imwrite(F'''{file_root}.jpg''' , __SCREAMING_SNAKE_CASE , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(F'''Succeeded {index+1}/{NUMBER_IMAGES} with {file_name}''' ) lowercase_ : List[Any] = [] for anno in new_annos: lowercase_ : List[Any] = anno[3] - anno[1] lowercase_ : List[str] = anno[4] - anno[2] lowercase_ : Dict = anno[1] + width / 2 lowercase_ : Dict = anno[2] + height / 2 lowercase_ : 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 snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : str ): """simple docstring""" lowercase_ : Optional[Any] = [] lowercase_ : Optional[Any] = [] for label_file in glob.glob(os.path.join(__SCREAMING_SNAKE_CASE , '''*.txt''' ) ): lowercase_ : int = label_file.split(os.sep )[-1].rsplit('''.''' , 1 )[0] with open(__SCREAMING_SNAKE_CASE ) as in_file: lowercase_ : List[str] = in_file.readlines() lowercase_ : Optional[Any] = os.path.join(__SCREAMING_SNAKE_CASE , F'''{label_name}.jpg''' ) lowercase_ : Optional[int] = [] for obj_list in obj_lists: lowercase_ : List[str] = obj_list.rstrip('''\n''' ).split(''' ''' ) lowercase_ : Optional[int] = float(obj[1] ) - float(obj[3] ) / 2 lowercase_ : Any = float(obj[2] ) - float(obj[4] ) / 2 lowercase_ : str = float(obj[1] ) + float(obj[3] ) / 2 lowercase_ : List[str] = 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 snake_case_ ( __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 , ): """simple docstring""" lowercase_ : List[Any] = np.zeros([output_size[0], output_size[1], 3] , dtype=np.uinta ) lowercase_ : Tuple = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) lowercase_ : List[Any] = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) lowercase_ : Optional[int] = int(scale_x * output_size[1] ) lowercase_ : Dict = int(scale_y * output_size[0] ) lowercase_ : Union[str, Any] = [] lowercase_ : List[Any] = [] for i, index in enumerate(__SCREAMING_SNAKE_CASE ): lowercase_ : Union[str, Any] = all_img_list[index] path_list.append(__SCREAMING_SNAKE_CASE ) lowercase_ : int = all_annos[index] lowercase_ : Dict = cva.imread(__SCREAMING_SNAKE_CASE ) if i == 0: # top-left lowercase_ : Optional[Any] = cva.resize(__SCREAMING_SNAKE_CASE , (divid_point_x, divid_point_y) ) lowercase_ : Tuple = img for bbox in img_annos: lowercase_ : Optional[int] = bbox[1] * scale_x lowercase_ : Optional[Any] = bbox[2] * scale_y lowercase_ : str = bbox[3] * scale_x lowercase_ : Tuple = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 1: # top-right lowercase_ : Dict = cva.resize(__SCREAMING_SNAKE_CASE , (output_size[1] - divid_point_x, divid_point_y) ) lowercase_ : Dict = img for bbox in img_annos: lowercase_ : int = scale_x + bbox[1] * (1 - scale_x) lowercase_ : Dict = bbox[2] * scale_y lowercase_ : Optional[int] = scale_x + bbox[3] * (1 - scale_x) lowercase_ : int = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 2: # bottom-left lowercase_ : List[Any] = cva.resize(__SCREAMING_SNAKE_CASE , (divid_point_x, output_size[0] - divid_point_y) ) lowercase_ : List[str] = img for bbox in img_annos: lowercase_ : Any = bbox[1] * scale_x lowercase_ : Optional[int] = scale_y + bbox[2] * (1 - scale_y) lowercase_ : str = bbox[3] * scale_x lowercase_ : Optional[int] = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) else: # bottom-right lowercase_ : int = cva.resize( __SCREAMING_SNAKE_CASE , (output_size[1] - divid_point_x, output_size[0] - divid_point_y) ) lowercase_ : List[str] = img for bbox in img_annos: lowercase_ : int = scale_x + bbox[1] * (1 - scale_x) lowercase_ : Any = scale_y + bbox[2] * (1 - scale_y) lowercase_ : Optional[Any] = scale_x + bbox[3] * (1 - scale_x) lowercase_ : int = 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: lowercase_ : Optional[Any] = [ anno for anno in new_anno if filter_scale < (anno[3] - anno[1]) and filter_scale < (anno[4] - anno[2]) ] return output_img, new_anno, path_list[0] def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" assert number_char > 1, "The number of character should greater than 1" lowercase_ : Any = ascii_lowercase + digits return "".join(random.choice(__SCREAMING_SNAKE_CASE ) for _ in range(__SCREAMING_SNAKE_CASE ) ) if __name__ == "__main__": main() print("DONE ✅")
93
1
'''simple docstring''' def snake_case_ ( __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : str = 1 # To kept the Calculated Value # Since C(n, k) = C(n, n-k) if k > (n - k): lowercase_ : Any = n - k # Calculate C(n,k) for i in range(__SCREAMING_SNAKE_CASE ): result *= n - i result //= i + 1 return result def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" return binomial_coefficient(2 * node_count , __SCREAMING_SNAKE_CASE ) // (node_count + 1) def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" if n < 0: raise ValueError('''factorial() not defined for negative values''' ) lowercase_ : List[Any] = 1 for i in range(1 , n + 1 ): result *= i return result def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" return catalan_number(__SCREAMING_SNAKE_CASE ) * factorial(__SCREAMING_SNAKE_CASE ) if __name__ == "__main__": _lowercase : Tuple = int(input("Enter the number of nodes: ").strip() or 0) if node_count <= 0: raise ValueError("We need some nodes to work with.") print( f"""Given {node_count} nodes, there are {binary_tree_count(node_count)} """ f"""binary trees and {catalan_number(node_count)} binary search trees.""" )
93
'''simple docstring''' from __future__ import annotations from collections import Counter from random import random class lowerCAmelCase__ : def __init__( self ): """simple docstring""" lowercase_ : int = {} def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Dict = {} def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" if nodea not in self.connections: self.add_node(__SCREAMING_SNAKE_CASE ) if nodea not in self.connections: self.add_node(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = probability def _snake_case ( self ): """simple docstring""" return list(self.connections ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Any = 0 lowercase_ : Tuple = random() for dest in self.connections[node]: current_probability += self.connections[node][dest] if current_probability > random_value: return dest return "" def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : list[tuple[str, str, float]] , __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : List[Any] = MarkovChainGraphUndirectedUnweighted() for nodea, nodea, probability in transitions: graph.add_transition_probability(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : str = Counter(graph.get_nodes() ) lowercase_ : Any = start for _ in range(__SCREAMING_SNAKE_CASE ): lowercase_ : int = graph.transition(__SCREAMING_SNAKE_CASE ) visited[node] += 1 return visited if __name__ == "__main__": import doctest doctest.testmod()
93
1
'''simple docstring''' import argparse import copy def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[int] ): """simple docstring""" lowercase_ : List[Any] = {} with open(__SCREAMING_SNAKE_CASE ) as f: for line in f: if line.split()[0] not in dict_of_neighbours: lowercase_ : Union[str, Any] = [] _list.append([line.split()[1], line.split()[2]] ) lowercase_ : str = _list else: dict_of_neighbours[line.split()[0]].append( [line.split()[1], line.split()[2]] ) if line.split()[1] not in dict_of_neighbours: lowercase_ : Optional[int] = [] _list.append([line.split()[0], line.split()[2]] ) lowercase_ : Dict = _list else: dict_of_neighbours[line.split()[1]].append( [line.split()[0], line.split()[2]] ) return dict_of_neighbours def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE ) as f: lowercase_ : List[str] = f.read(1 ) lowercase_ : Optional[int] = start_node lowercase_ : Any = [] lowercase_ : List[str] = start_node lowercase_ : Optional[Any] = 0 while visiting not in first_solution: lowercase_ : Any = 10000 for k in dict_of_neighbours[visiting]: if int(k[1] ) < int(__SCREAMING_SNAKE_CASE ) and k[0] not in first_solution: lowercase_ : List[Any] = k[1] lowercase_ : List[Any] = k[0] first_solution.append(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = distance_of_first_solution + int(__SCREAMING_SNAKE_CASE ) lowercase_ : int = best_node first_solution.append(__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = 0 for k in dict_of_neighbours[first_solution[-2]]: if k[0] == start_node: break position += 1 lowercase_ : Optional[Any] = ( distance_of_first_solution + int(dict_of_neighbours[first_solution[-2]][position][1] ) - 10000 ) return first_solution, distance_of_first_solution def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" lowercase_ : Tuple = [] for n in solution[1:-1]: lowercase_ : List[str] = solution.index(__SCREAMING_SNAKE_CASE ) for kn in solution[1:-1]: lowercase_ : Any = solution.index(__SCREAMING_SNAKE_CASE ) if n == kn: continue lowercase_ : Dict = copy.deepcopy(__SCREAMING_SNAKE_CASE ) lowercase_ : Dict = kn lowercase_ : List[Any] = n lowercase_ : str = 0 for k in _tmp[:-1]: lowercase_ : Tuple = _tmp[_tmp.index(__SCREAMING_SNAKE_CASE ) + 1] for i in dict_of_neighbours[k]: if i[0] == next_node: lowercase_ : Optional[Any] = distance + int(i[1] ) _tmp.append(__SCREAMING_SNAKE_CASE ) if _tmp not in neighborhood_of_solution: neighborhood_of_solution.append(_tmp ) lowercase_ : Union[str, Any] = 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 snake_case_ ( __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" lowercase_ : Optional[int] = 1 lowercase_ : List[str] = first_solution lowercase_ : Dict = [] lowercase_ : List[str] = distance_of_first_solution lowercase_ : Optional[Any] = solution while count <= iters: lowercase_ : int = find_neighborhood(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : Any = 0 lowercase_ : Dict = neighborhood[index_of_best_solution] lowercase_ : Optional[Any] = len(__SCREAMING_SNAKE_CASE ) - 1 lowercase_ : Tuple = False while not found: lowercase_ : Optional[int] = 0 while i < len(__SCREAMING_SNAKE_CASE ): if best_solution[i] != solution[i]: lowercase_ : Tuple = best_solution[i] lowercase_ : Optional[int] = solution[i] break lowercase_ : 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] ) lowercase_ : Tuple = True lowercase_ : Optional[int] = best_solution[:-1] lowercase_ : Optional[Any] = neighborhood[index_of_best_solution][best_cost_index] if cost < best_cost: lowercase_ : Optional[Any] = cost lowercase_ : int = solution else: lowercase_ : Any = index_of_best_solution + 1 lowercase_ : Any = neighborhood[index_of_best_solution] if len(__SCREAMING_SNAKE_CASE ) >= size: tabu_list.pop(0 ) lowercase_ : List[Any] = count + 1 return best_solution_ever, best_cost def snake_case_ ( __SCREAMING_SNAKE_CASE : List[str]=None ): """simple docstring""" lowercase_ : Any = generate_neighbours(args.File ) lowercase_ , lowercase_ : Union[str, Any] = generate_first_solution( args.File , __SCREAMING_SNAKE_CASE ) lowercase_ , lowercase_ : Optional[int] = 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__": _lowercase : Any = 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())
93
'''simple docstring''' import torch from transformers import AutoModel class lowerCAmelCase__ ( torch.nn.Module ): def __init__( self , __SCREAMING_SNAKE_CASE="sayef/fsner-bert-base-uncased" ): """simple docstring""" super(__SCREAMING_SNAKE_CASE , self ).__init__() lowercase_ : Tuple = AutoModel.from_pretrained(__SCREAMING_SNAKE_CASE , return_dict=__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = torch.nn.CosineSimilarity(3 , 1E-0_8 ) lowercase_ : Optional[Any] = torch.nn.Softmax(dim=1 ) def _snake_case ( self , **__SCREAMING_SNAKE_CASE ): """simple docstring""" return self.bert(**__SCREAMING_SNAKE_CASE ).last_hidden_state def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" return token_embeddings.sum(2 , keepdim=__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=1 ): """simple docstring""" return self.softmax(T * self.cos(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Optional[Any] = W_supports['''sizes'''].tolist() lowercase_ : Dict = W_supports['''start_token_id'''].item() lowercase_ : List[Any] = W_supports['''end_token_id'''].item() del W_supports["sizes"] del W_supports["start_token_id"] del W_supports["end_token_id"] lowercase_ : List[str] = self.BERT(**__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = self.BERT(**__SCREAMING_SNAKE_CASE ) lowercase_ : str = None lowercase_ : Dict = None lowercase_ : Tuple = W_supports['''input_ids'''] == start_token_id lowercase_ : Any = W_supports['''input_ids'''] == end_token_id for i, size in enumerate(__SCREAMING_SNAKE_CASE ): if i == 0: lowercase_ : List[str] = 0 else: lowercase_ : List[Any] = support_sizes[i - 1] lowercase_ : str = S[s : s + size][start_token_masks[s : s + size]] lowercase_ : Optional[int] = S[s : s + size][end_token_masks[s : s + size]] lowercase_ : List[str] = torch.matmul(q[i] , s_start.T ).sum(1 ).softmax(0 ) lowercase_ : List[str] = torch.matmul(q[i] , s_end.T ).sum(1 ).softmax(0 ) if p_starts is not None: lowercase_ : Tuple = torch.vstack((p_starts, p_start) ) lowercase_ : Optional[Any] = torch.vstack((p_ends, p_end) ) else: lowercase_ : str = p_start lowercase_ : int = p_end return p_starts, p_ends
93
1
'''simple docstring''' def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : Union[str, Any] = int(__SCREAMING_SNAKE_CASE ) if n_element < 1: lowercase_ : str = ValueError('''a should be a positive number''' ) raise my_error lowercase_ : str = [1] lowercase_ , lowercase_ , lowercase_ : Any = (0, 0, 0) lowercase_ : Any = 1 while index < n_element: while hamming_list[i] * 2 <= hamming_list[-1]: i += 1 while hamming_list[j] * 3 <= hamming_list[-1]: j += 1 while hamming_list[k] * 5 <= hamming_list[-1]: k += 1 hamming_list.append( min(hamming_list[i] * 2 , hamming_list[j] * 3 , hamming_list[k] * 5 ) ) index += 1 return hamming_list if __name__ == "__main__": _lowercase : str = input("Enter the last number (nth term) of the Hamming Number Series: ") print("Formula of Hamming Number Series => 2^i * 3^j * 5^k") _lowercase : List[Any] = hamming(int(n)) print("-----------------------------------------------------") print(f"""The list with nth numbers is: {hamming_numbers}""") print("-----------------------------------------------------")
93
'''simple docstring''' import json import os from pathlib import Path from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple, Union import sentencepiece from ...tokenization_utils import BatchEncoding, PreTrainedTokenizer from ...utils import logging _lowercase : List[Any] = logging.get_logger(__name__) _lowercase : List[Any] = "▁" _lowercase : Tuple = { "vocab_file": "vocab.json", "spm_file": "sentencepiece.bpe.model", "tokenizer_config_file": "tokenizer_config.json", } _lowercase : List[str] = { "vocab_file": { "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/vocab.json", "facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/vocab.json", }, "spm_file": { "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/sentencepiece.bpe.model", "facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/sentencepiece.bpe.model", }, "tokenizer_config_file": { "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/tokenizer_config.json", "facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/tokenizer_config.json", }, } _lowercase : List[str] = { "facebook/m2m100_418M": 1_0_2_4, } # fmt: off _lowercase : Tuple = { "m2m100": ["af", "am", "ar", "ast", "az", "ba", "be", "bg", "bn", "br", "bs", "ca", "ceb", "cs", "cy", "da", "de", "el", "en", "es", "et", "fa", "ff", "fi", "fr", "fy", "ga", "gd", "gl", "gu", "ha", "he", "hi", "hr", "ht", "hu", "hy", "id", "ig", "ilo", "is", "it", "ja", "jv", "ka", "kk", "km", "kn", "ko", "lb", "lg", "ln", "lo", "lt", "lv", "mg", "mk", "ml", "mn", "mr", "ms", "my", "ne", "nl", "no", "ns", "oc", "or", "pa", "pl", "ps", "pt", "ro", "ru", "sd", "si", "sk", "sl", "so", "sq", "sr", "ss", "su", "sv", "sw", "ta", "th", "tl", "tn", "tr", "uk", "ur", "uz", "vi", "wo", "xh", "yi", "yo", "zh", "zu"], "wmt21": ["en", "ha", "is", "ja", "cs", "ru", "zh", "de"] } class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = VOCAB_FILES_NAMES lowerCAmelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase_ = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase_ = ['''input_ids''', '''attention_mask'''] lowerCAmelCase_ = [] lowerCAmelCase_ = [] def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE="<s>" , __SCREAMING_SNAKE_CASE="</s>" , __SCREAMING_SNAKE_CASE="</s>" , __SCREAMING_SNAKE_CASE="<pad>" , __SCREAMING_SNAKE_CASE="<unk>" , __SCREAMING_SNAKE_CASE="m2m100" , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE=8 , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : Optional[Any] = {} if sp_model_kwargs is None else sp_model_kwargs lowercase_ : List[Any] = language_codes lowercase_ : Optional[int] = FAIRSEQ_LANGUAGE_CODES[language_codes] lowercase_ : List[Any] = {lang_code: F'''__{lang_code}__''' for lang_code in fairseq_language_code} lowercase_ : Union[str, Any] = kwargs.get('''additional_special_tokens''' , [] ) kwargs["additional_special_tokens"] += [ self.get_lang_token(__SCREAMING_SNAKE_CASE ) for lang_code in fairseq_language_code if self.get_lang_token(__SCREAMING_SNAKE_CASE ) not in kwargs["additional_special_tokens"] ] super().__init__( src_lang=__SCREAMING_SNAKE_CASE , tgt_lang=__SCREAMING_SNAKE_CASE , bos_token=__SCREAMING_SNAKE_CASE , eos_token=__SCREAMING_SNAKE_CASE , sep_token=__SCREAMING_SNAKE_CASE , unk_token=__SCREAMING_SNAKE_CASE , pad_token=__SCREAMING_SNAKE_CASE , language_codes=__SCREAMING_SNAKE_CASE , sp_model_kwargs=self.sp_model_kwargs , num_madeup_words=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) lowercase_ : int = vocab_file lowercase_ : Any = load_json(__SCREAMING_SNAKE_CASE ) lowercase_ : str = {v: k for k, v in self.encoder.items()} lowercase_ : Optional[int] = spm_file lowercase_ : Any = load_spm(__SCREAMING_SNAKE_CASE , self.sp_model_kwargs ) lowercase_ : List[Any] = len(self.encoder ) lowercase_ : Dict = { self.get_lang_token(__SCREAMING_SNAKE_CASE ): self.encoder_size + i for i, lang_code in enumerate(__SCREAMING_SNAKE_CASE ) } lowercase_ : Optional[int] = {lang_code: self.encoder_size + i for i, lang_code in enumerate(__SCREAMING_SNAKE_CASE )} lowercase_ : Union[str, Any] = {v: k for k, v in self.lang_token_to_id.items()} lowercase_ : Tuple = src_lang if src_lang is not None else '''en''' lowercase_ : Optional[int] = tgt_lang lowercase_ : Any = self.get_lang_id(self._src_lang ) self.set_src_lang_special_tokens(self._src_lang ) lowercase_ : Dict = num_madeup_words @property def _snake_case ( self ): """simple docstring""" return len(self.encoder ) + len(self.lang_token_to_id ) @property def _snake_case ( self ): """simple docstring""" return self._src_lang @src_lang.setter def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : str = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" return self.sp_model.encode(__SCREAMING_SNAKE_CASE , out_type=__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" if token in self.lang_token_to_id: return self.lang_token_to_id[token] return self.encoder.get(__SCREAMING_SNAKE_CASE , self.encoder[self.unk_token] ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" if index in self.id_to_lang_token: return self.id_to_lang_token[index] return self.decoder.get(__SCREAMING_SNAKE_CASE , self.unk_token ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Tuple = [] lowercase_ : List[str] = '''''' for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(__SCREAMING_SNAKE_CASE ) + token lowercase_ : Optional[Any] = [] else: current_sub_tokens.append(__SCREAMING_SNAKE_CASE ) out_string += self.sp_model.decode(__SCREAMING_SNAKE_CASE ) return out_string.strip() def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = False ): """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__SCREAMING_SNAKE_CASE , token_ids_a=__SCREAMING_SNAKE_CASE , already_has_special_tokens=__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = [1] * len(self.prefix_tokens ) lowercase_ : Any = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(__SCREAMING_SNAKE_CASE )) + suffix_ones return prefix_ones + ([0] * len(__SCREAMING_SNAKE_CASE )) + ([0] * len(__SCREAMING_SNAKE_CASE )) + suffix_ones def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def _snake_case ( self ): """simple docstring""" lowercase_ : Tuple = {self.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ): """simple docstring""" lowercase_ : List[Any] = self.__dict__.copy() lowercase_ : List[Any] = None return state def __setstate__( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Dict = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): lowercase_ : List[Any] = {} lowercase_ : Union[str, Any] = load_spm(self.spm_file , self.sp_model_kwargs ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" lowercase_ : Tuple = Path(__SCREAMING_SNAKE_CASE ) if not save_dir.is_dir(): raise OSError(F'''{save_directory} should be a directory''' ) lowercase_ : Dict = save_dir / ( (filename_prefix + '''-''' if filename_prefix else '''''') + self.vocab_files_names['''vocab_file'''] ) lowercase_ : Dict = save_dir / ( (filename_prefix + '''-''' if filename_prefix else '''''') + self.vocab_files_names['''spm_file'''] ) save_json(self.encoder , __SCREAMING_SNAKE_CASE ) if os.path.abspath(self.spm_file ) != os.path.abspath(__SCREAMING_SNAKE_CASE ) and os.path.isfile(self.spm_file ): copyfile(self.spm_file , __SCREAMING_SNAKE_CASE ) elif not os.path.isfile(self.spm_file ): with open(__SCREAMING_SNAKE_CASE , '''wb''' ) as fi: lowercase_ : int = self.sp_model.serialized_model_proto() fi.write(__SCREAMING_SNAKE_CASE ) return (str(__SCREAMING_SNAKE_CASE ), str(__SCREAMING_SNAKE_CASE )) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = "en" , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = "ro" , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : Optional[Any] = src_lang lowercase_ : List[str] = tgt_lang self.set_src_lang_special_tokens(self.src_lang ) return super().prepare_seqaseq_batch(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" if src_lang is None or tgt_lang is None: raise ValueError('''Translation requires a `src_lang` and a `tgt_lang` for this model''' ) lowercase_ : Tuple = src_lang lowercase_ : Any = self(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) lowercase_ : List[Any] = self.get_lang_id(__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = tgt_lang_id return inputs def _snake_case ( self ): """simple docstring""" self.set_src_lang_special_tokens(self.src_lang ) def _snake_case ( self ): """simple docstring""" self.set_tgt_lang_special_tokens(self.tgt_lang ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Any = self.get_lang_token(__SCREAMING_SNAKE_CASE ) lowercase_ : Dict = self.lang_token_to_id[lang_token] lowercase_ : Optional[Any] = [self.cur_lang_id] lowercase_ : Union[str, Any] = [self.eos_token_id] def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Any = self.get_lang_token(__SCREAMING_SNAKE_CASE ) lowercase_ : Any = self.lang_token_to_id[lang_token] lowercase_ : str = [self.cur_lang_id] lowercase_ : List[str] = [self.eos_token_id] def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" return self.lang_code_to_token[lang] def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : List[Any] = self.get_lang_token(__SCREAMING_SNAKE_CASE ) return self.lang_token_to_id[lang_token] def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Dict[str, Any] ): """simple docstring""" lowercase_ : Optional[int] = sentencepiece.SentencePieceProcessor(**__SCREAMING_SNAKE_CASE ) spm.Load(str(__SCREAMING_SNAKE_CASE ) ) return spm def snake_case_ ( __SCREAMING_SNAKE_CASE : str ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE , '''r''' ) as f: return json.load(__SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : str ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE , '''w''' ) as f: json.dump(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , indent=2 )
93
1
'''simple docstring''' _lowercase : Optional[int] = {"a": ["c", "b"], "b": ["d", "e"], "c": [], "d": [], "e": []} _lowercase : str = ["a", "b", "c", "d", "e"] def snake_case_ ( __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" lowercase_ : Optional[int] = start # add current to visited visited.append(__SCREAMING_SNAKE_CASE ) lowercase_ : Dict = edges[current] for neighbor in neighbors: # if neighbor not in visited, visit if neighbor not in visited: lowercase_ : Dict = topological_sort(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # if all neighbors visited add current to sort sort.append(__SCREAMING_SNAKE_CASE ) # if all vertices haven't been visited select a new one to visit if len(__SCREAMING_SNAKE_CASE ) != len(__SCREAMING_SNAKE_CASE ): for vertice in vertices: if vertice not in visited: lowercase_ : List[Any] = topological_sort(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # return sort return sort if __name__ == "__main__": _lowercase : Dict = topological_sort("a", [], []) print(sort)
93
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer from ...utils import logging _lowercase : str = logging.get_logger(__name__) _lowercase : List[Any] = "▁" _lowercase : List[Any] = {"vocab_file": "sentencepiece.bpe.model"} _lowercase : Optional[int] = { "vocab_file": { "facebook/mbart-large-en-ro": ( "https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/sentencepiece.bpe.model" ), "facebook/mbart-large-cc25": ( "https://huggingface.co/facebook/mbart-large-cc25/resolve/main/sentencepiece.bpe.model" ), } } _lowercase : str = { "facebook/mbart-large-en-ro": 1_0_2_4, "facebook/mbart-large-cc25": 1_0_2_4, } # fmt: off _lowercase : List[Any] = ["ar_AR", "cs_CZ", "de_DE", "en_XX", "es_XX", "et_EE", "fi_FI", "fr_XX", "gu_IN", "hi_IN", "it_IT", "ja_XX", "kk_KZ", "ko_KR", "lt_LT", "lv_LV", "my_MM", "ne_NP", "nl_XX", "ro_RO", "ru_RU", "si_LK", "tr_TR", "vi_VN", "zh_CN"] class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = VOCAB_FILES_NAMES lowerCAmelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase_ = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase_ = ['''input_ids''', '''attention_mask'''] lowerCAmelCase_ = [] lowerCAmelCase_ = [] def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE="<s>" , __SCREAMING_SNAKE_CASE="</s>" , __SCREAMING_SNAKE_CASE="</s>" , __SCREAMING_SNAKE_CASE="<s>" , __SCREAMING_SNAKE_CASE="<unk>" , __SCREAMING_SNAKE_CASE="<pad>" , __SCREAMING_SNAKE_CASE="<mask>" , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE=None , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : Any = AddedToken(__SCREAMING_SNAKE_CASE , lstrip=__SCREAMING_SNAKE_CASE , rstrip=__SCREAMING_SNAKE_CASE ) if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else mask_token lowercase_ : int = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=__SCREAMING_SNAKE_CASE , eos_token=__SCREAMING_SNAKE_CASE , unk_token=__SCREAMING_SNAKE_CASE , sep_token=__SCREAMING_SNAKE_CASE , cls_token=__SCREAMING_SNAKE_CASE , pad_token=__SCREAMING_SNAKE_CASE , mask_token=__SCREAMING_SNAKE_CASE , tokenizer_file=__SCREAMING_SNAKE_CASE , src_lang=__SCREAMING_SNAKE_CASE , tgt_lang=__SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , sp_model_kwargs=self.sp_model_kwargs , **__SCREAMING_SNAKE_CASE , ) lowercase_ : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__SCREAMING_SNAKE_CASE ) ) lowercase_ : List[str] = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # Mimic fairseq token-to-id alignment for the first 4 token lowercase_ : Tuple = {'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3} # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab lowercase_ : str = 1 lowercase_ : str = len(self.sp_model ) lowercase_ : List[Any] = { code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(__SCREAMING_SNAKE_CASE ) } lowercase_ : Union[str, Any] = {v: k for k, v in self.lang_code_to_id.items()} lowercase_ : List[Any] = len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset self.fairseq_tokens_to_ids.update(self.lang_code_to_id ) lowercase_ : Union[str, Any] = {v: k for k, v in self.fairseq_tokens_to_ids.items()} lowercase_ : Optional[Any] = list(self.lang_code_to_id.keys() ) if additional_special_tokens is not None: # Only add those special tokens if they are not already there. self._additional_special_tokens.extend( [t for t in additional_special_tokens if t not in self._additional_special_tokens] ) lowercase_ : Optional[Any] = src_lang if src_lang is not None else '''en_XX''' lowercase_ : str = self.lang_code_to_id[self._src_lang] lowercase_ : Optional[Any] = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) def __getstate__( self ): """simple docstring""" lowercase_ : Optional[int] = self.__dict__.copy() lowercase_ : Dict = None lowercase_ : Any = self.sp_model.serialized_model_proto() return state def __setstate__( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Optional[Any] = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): lowercase_ : Dict = {} lowercase_ : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) @property def _snake_case ( self ): """simple docstring""" return len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset + 1 # Plus 1 for the mask token @property def _snake_case ( self ): """simple docstring""" return self._src_lang @src_lang.setter def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Tuple = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = False ): """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__SCREAMING_SNAKE_CASE , token_ids_a=__SCREAMING_SNAKE_CASE , already_has_special_tokens=__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = [1] * len(self.prefix_tokens ) lowercase_ : Tuple = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(__SCREAMING_SNAKE_CASE )) + suffix_ones return prefix_ones + ([0] * len(__SCREAMING_SNAKE_CASE )) + ([0] * len(__SCREAMING_SNAKE_CASE )) + suffix_ones def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" lowercase_ : Optional[int] = [self.sep_token_id] lowercase_ : Any = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" if src_lang is None or tgt_lang is None: raise ValueError('''Translation requires a `src_lang` and a `tgt_lang` for this model''' ) lowercase_ : Optional[Any] = src_lang lowercase_ : Dict = self(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , return_tensors=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = self.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = tgt_lang_id return inputs def _snake_case ( self ): """simple docstring""" lowercase_ : str = {self.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" return self.sp_model.encode(__SCREAMING_SNAKE_CASE , out_type=__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] lowercase_ : Any = self.sp_model.PieceToId(__SCREAMING_SNAKE_CASE ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : int = ''''''.join(__SCREAMING_SNAKE_CASE ).replace(__SCREAMING_SNAKE_CASE , ''' ''' ).strip() return out_string def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" if not os.path.isdir(__SCREAMING_SNAKE_CASE ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return lowercase_ : Tuple = os.path.join( __SCREAMING_SNAKE_CASE , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__SCREAMING_SNAKE_CASE ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __SCREAMING_SNAKE_CASE ) elif not os.path.isfile(self.vocab_file ): with open(__SCREAMING_SNAKE_CASE , '''wb''' ) as fi: lowercase_ : List[str] = self.sp_model.serialized_model_proto() fi.write(__SCREAMING_SNAKE_CASE ) return (out_vocab_file,) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = "en_XX" , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = "ro_RO" , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : List[str] = src_lang lowercase_ : int = tgt_lang return super().prepare_seqaseq_batch(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" return self.set_src_lang_special_tokens(self.src_lang ) def _snake_case ( self ): """simple docstring""" return self.set_tgt_lang_special_tokens(self.tgt_lang ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Dict = self.lang_code_to_id[src_lang] lowercase_ : Optional[Any] = [] lowercase_ : List[str] = [self.eos_token_id, self.cur_lang_code] def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : List[Any] = self.lang_code_to_id[lang] lowercase_ : Dict = [] lowercase_ : Union[str, Any] = [self.eos_token_id, self.cur_lang_code]
93
1
'''simple docstring''' from typing import Optional import torch import torch.utils.checkpoint from torch import Tensor, nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_outputs import ( BaseModelOutputWithNoAttention, BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention, ) from ...modeling_utils import PreTrainedModel from ...utils import logging from .configuration_regnet import RegNetConfig _lowercase : List[Any] = logging.get_logger(__name__) # General docstring _lowercase : Optional[Any] = "RegNetConfig" # Base docstring _lowercase : Optional[int] = "facebook/regnet-y-040" _lowercase : Union[str, Any] = [1, 1_0_8_8, 7, 7] # Image classification docstring _lowercase : Union[str, Any] = "facebook/regnet-y-040" _lowercase : int = "tabby, tabby cat" _lowercase : Union[str, Any] = [ "facebook/regnet-y-040", # See all regnet models at https://huggingface.co/models?filter=regnet ] class lowerCAmelCase__ ( nn.Module ): def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = 3 , __SCREAMING_SNAKE_CASE = 1 , __SCREAMING_SNAKE_CASE = 1 , __SCREAMING_SNAKE_CASE = "relu" , ): """simple docstring""" super().__init__() lowercase_ : Dict = nn.Convad( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , kernel_size=__SCREAMING_SNAKE_CASE , stride=__SCREAMING_SNAKE_CASE , padding=kernel_size // 2 , groups=__SCREAMING_SNAKE_CASE , bias=__SCREAMING_SNAKE_CASE , ) lowercase_ : int = nn.BatchNormad(__SCREAMING_SNAKE_CASE ) lowercase_ : List[Any] = ACTaFN[activation] if activation is not None else nn.Identity() def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Tuple = self.convolution(__SCREAMING_SNAKE_CASE ) lowercase_ : Dict = self.normalization(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = self.activation(__SCREAMING_SNAKE_CASE ) return hidden_state class lowerCAmelCase__ ( nn.Module ): def __init__( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" super().__init__() lowercase_ : Dict = RegNetConvLayer( config.num_channels , config.embedding_size , kernel_size=3 , stride=2 , activation=config.hidden_act ) lowercase_ : Union[str, Any] = config.num_channels def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Union[str, Any] = pixel_values.shape[1] if num_channels != self.num_channels: raise ValueError( '''Make sure that the channel dimension of the pixel values match with the one set in the configuration.''' ) lowercase_ : Any = self.embedder(__SCREAMING_SNAKE_CASE ) return hidden_state class lowerCAmelCase__ ( nn.Module ): def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = 2 ): """simple docstring""" super().__init__() lowercase_ : Optional[Any] = nn.Convad(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , kernel_size=1 , stride=__SCREAMING_SNAKE_CASE , bias=__SCREAMING_SNAKE_CASE ) lowercase_ : List[str] = nn.BatchNormad(__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : str = self.convolution(__SCREAMING_SNAKE_CASE ) lowercase_ : List[Any] = self.normalization(__SCREAMING_SNAKE_CASE ) return hidden_state class lowerCAmelCase__ ( nn.Module ): def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" super().__init__() lowercase_ : Any = nn.AdaptiveAvgPoolad((1, 1) ) lowercase_ : Tuple = nn.Sequential( nn.Convad(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , kernel_size=1 ) , nn.ReLU() , nn.Convad(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , kernel_size=1 ) , nn.Sigmoid() , ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Optional[Any] = self.pooler(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = self.attention(__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = hidden_state * attention return hidden_state class lowerCAmelCase__ ( nn.Module ): def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = 1 ): """simple docstring""" super().__init__() lowercase_ : Any = in_channels != out_channels or stride != 1 lowercase_ : str = max(1 , out_channels // config.groups_width ) lowercase_ : str = ( RegNetShortCut(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , stride=__SCREAMING_SNAKE_CASE ) if should_apply_shortcut else nn.Identity() ) lowercase_ : int = nn.Sequential( RegNetConvLayer(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , kernel_size=1 , activation=config.hidden_act ) , RegNetConvLayer(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , stride=__SCREAMING_SNAKE_CASE , groups=__SCREAMING_SNAKE_CASE , activation=config.hidden_act ) , RegNetConvLayer(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , kernel_size=1 , activation=__SCREAMING_SNAKE_CASE ) , ) lowercase_ : Optional[int] = ACTaFN[config.hidden_act] def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Dict = hidden_state lowercase_ : int = self.layer(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = self.shortcut(__SCREAMING_SNAKE_CASE ) hidden_state += residual lowercase_ : str = self.activation(__SCREAMING_SNAKE_CASE ) return hidden_state class lowerCAmelCase__ ( nn.Module ): def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = 1 ): """simple docstring""" super().__init__() lowercase_ : Optional[int] = in_channels != out_channels or stride != 1 lowercase_ : Dict = max(1 , out_channels // config.groups_width ) lowercase_ : Dict = ( RegNetShortCut(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , stride=__SCREAMING_SNAKE_CASE ) if should_apply_shortcut else nn.Identity() ) lowercase_ : str = nn.Sequential( RegNetConvLayer(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , kernel_size=1 , activation=config.hidden_act ) , RegNetConvLayer(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , stride=__SCREAMING_SNAKE_CASE , groups=__SCREAMING_SNAKE_CASE , activation=config.hidden_act ) , RegNetSELayer(__SCREAMING_SNAKE_CASE , reduced_channels=int(round(in_channels / 4 ) ) ) , RegNetConvLayer(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , kernel_size=1 , activation=__SCREAMING_SNAKE_CASE ) , ) lowercase_ : Optional[Any] = ACTaFN[config.hidden_act] def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Optional[int] = hidden_state lowercase_ : Optional[Any] = self.layer(__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = self.shortcut(__SCREAMING_SNAKE_CASE ) hidden_state += residual lowercase_ : Union[str, Any] = self.activation(__SCREAMING_SNAKE_CASE ) return hidden_state class lowerCAmelCase__ ( nn.Module ): def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = 2 , __SCREAMING_SNAKE_CASE = 2 , ): """simple docstring""" super().__init__() lowercase_ : Any = RegNetXLayer if config.layer_type == '''x''' else RegNetYLayer lowercase_ : Any = nn.Sequential( # downsampling is done in the first layer with stride of 2 layer( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , stride=__SCREAMING_SNAKE_CASE , ) , *[layer(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) for _ in range(depth - 1 )] , ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Dict = self.layers(__SCREAMING_SNAKE_CASE ) return hidden_state class lowerCAmelCase__ ( nn.Module ): def __init__( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" super().__init__() lowercase_ : Optional[Any] = nn.ModuleList([] ) # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( RegNetStage( __SCREAMING_SNAKE_CASE , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , ) ) lowercase_ : Dict = zip(config.hidden_sizes , config.hidden_sizes[1:] ) for (in_channels, out_channels), depth in zip(__SCREAMING_SNAKE_CASE , config.depths[1:] ): self.stages.append(RegNetStage(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , depth=__SCREAMING_SNAKE_CASE ) ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = False , __SCREAMING_SNAKE_CASE = True ): """simple docstring""" lowercase_ : int = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: lowercase_ : int = hidden_states + (hidden_state,) lowercase_ : List[str] = stage_module(__SCREAMING_SNAKE_CASE ) if output_hidden_states: lowercase_ : Optional[int] = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return BaseModelOutputWithNoAttention(last_hidden_state=__SCREAMING_SNAKE_CASE , hidden_states=__SCREAMING_SNAKE_CASE ) class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = RegNetConfig lowerCAmelCase_ = '''regnet''' lowerCAmelCase_ = '''pixel_values''' lowerCAmelCase_ = True def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" if isinstance(__SCREAMING_SNAKE_CASE , nn.Convad ): nn.init.kaiming_normal_(module.weight , mode='''fan_out''' , nonlinearity='''relu''' ) elif isinstance(__SCREAMING_SNAKE_CASE , (nn.BatchNormad, nn.GroupNorm) ): nn.init.constant_(module.weight , 1 ) nn.init.constant_(module.bias , 0 ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=False ): """simple docstring""" if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase_ : Union[str, Any] = value _lowercase : List[Any] = r"\n This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it\n as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n behavior.\n\n Parameters:\n config ([`RegNetConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n" _lowercase : Optional[int] = r"\n Args:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`ConvNextImageProcessor.__call__`] for details.\n\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.\n" @add_start_docstrings( '''The bare RegNet model outputting raw features without any specific head on top.''' , lowerCamelCase_ , ) # Copied from transformers.models.resnet.modeling_resnet.ResNetModel with RESNET->REGNET,ResNet->RegNet class lowerCAmelCase__ ( lowerCamelCase_ ): def __init__( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" super().__init__(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = config lowercase_ : Tuple = RegNetEmbeddings(__SCREAMING_SNAKE_CASE ) lowercase_ : List[Any] = RegNetEncoder(__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = nn.AdaptiveAvgPoolad((1, 1) ) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(__SCREAMING_SNAKE_CASE ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=__SCREAMING_SNAKE_CASE , config_class=_CONFIG_FOR_DOC , modality='''vision''' , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" lowercase_ : Tuple = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) lowercase_ : str = return_dict if return_dict is not None else self.config.use_return_dict lowercase_ : int = self.embedder(__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = self.encoder( __SCREAMING_SNAKE_CASE , output_hidden_states=__SCREAMING_SNAKE_CASE , return_dict=__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = encoder_outputs[0] lowercase_ : List[Any] = self.pooler(__SCREAMING_SNAKE_CASE ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return BaseModelOutputWithPoolingAndNoAttention( last_hidden_state=__SCREAMING_SNAKE_CASE , pooler_output=__SCREAMING_SNAKE_CASE , hidden_states=encoder_outputs.hidden_states , ) @add_start_docstrings( ''' RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet. ''' , lowerCamelCase_ , ) # Copied from transformers.models.resnet.modeling_resnet.ResNetForImageClassification with RESNET->REGNET,ResNet->RegNet,resnet->regnet class lowerCAmelCase__ ( lowerCamelCase_ ): def __init__( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" super().__init__(__SCREAMING_SNAKE_CASE ) lowercase_ : str = config.num_labels lowercase_ : Optional[int] = RegNetModel(__SCREAMING_SNAKE_CASE ) # classification head lowercase_ : List[Any] = nn.Sequential( nn.Flatten() , nn.Linear(config.hidden_sizes[-1] , config.num_labels ) if config.num_labels > 0 else nn.Identity() , ) # initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(__SCREAMING_SNAKE_CASE ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=__SCREAMING_SNAKE_CASE , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def _snake_case ( self , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , ): """simple docstring""" lowercase_ : Optional[int] = return_dict if return_dict is not None else self.config.use_return_dict lowercase_ : str = self.regnet(__SCREAMING_SNAKE_CASE , output_hidden_states=__SCREAMING_SNAKE_CASE , return_dict=__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = outputs.pooler_output if return_dict else outputs[1] lowercase_ : Any = self.classifier(__SCREAMING_SNAKE_CASE ) lowercase_ : Any = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: lowercase_ : str = '''regression''' elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): lowercase_ : List[Any] = '''single_label_classification''' else: lowercase_ : Optional[int] = '''multi_label_classification''' if self.config.problem_type == "regression": lowercase_ : int = MSELoss() if self.num_labels == 1: lowercase_ : Dict = loss_fct(logits.squeeze() , labels.squeeze() ) else: lowercase_ : List[str] = loss_fct(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) elif self.config.problem_type == "single_label_classification": lowercase_ : List[str] = CrossEntropyLoss() lowercase_ : str = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": lowercase_ : Union[str, Any] = BCEWithLogitsLoss() lowercase_ : Optional[int] = loss_fct(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if not return_dict: lowercase_ : str = (logits,) + outputs[2:] return (loss,) + output if loss is not None else output return ImageClassifierOutputWithNoAttention(loss=__SCREAMING_SNAKE_CASE , logits=__SCREAMING_SNAKE_CASE , hidden_states=outputs.hidden_states )
93
'''simple docstring''' import json import os import tempfile from transformers.testing_utils import check_json_file_has_correct_format class lowerCAmelCase__ : lowerCAmelCase_ = None def _snake_case ( self ): """simple docstring""" lowercase_ : Tuple = self.feature_extraction_class(**self.feat_extract_dict ) lowercase_ : Any = json.loads(feat_extract.to_json_string() ) for key, value in self.feat_extract_dict.items(): self.assertEqual(obj[key] , __SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" lowercase_ : str = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: lowercase_ : str = os.path.join(__SCREAMING_SNAKE_CASE , '''feat_extract.json''' ) feat_extract_first.to_json_file(__SCREAMING_SNAKE_CASE ) lowercase_ : str = self.feature_extraction_class.from_json_file(__SCREAMING_SNAKE_CASE ) self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() ) def _snake_case ( self ): """simple docstring""" lowercase_ : Tuple = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: lowercase_ : Union[str, Any] = feat_extract_first.save_pretrained(__SCREAMING_SNAKE_CASE )[0] check_json_file_has_correct_format(__SCREAMING_SNAKE_CASE ) lowercase_ : str = self.feature_extraction_class.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() ) def _snake_case ( self ): """simple docstring""" lowercase_ : Optional[Any] = self.feature_extraction_class() self.assertIsNotNone(__SCREAMING_SNAKE_CASE )
93
1
'''simple docstring''' from statistics import mean import numpy as np def snake_case_ ( __SCREAMING_SNAKE_CASE : list , __SCREAMING_SNAKE_CASE : list , __SCREAMING_SNAKE_CASE : list , __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : int = 0 # Number of processes finished lowercase_ : str = 0 # Displays the finished process. # If it is 0, the performance is completed if it is 1, before the performance. lowercase_ : List[Any] = [0] * no_of_process # List to include calculation results lowercase_ : Any = [0] * no_of_process # Sort by arrival time. lowercase_ : Any = [burst_time[i] for i in np.argsort(__SCREAMING_SNAKE_CASE )] lowercase_ : Dict = [process_name[i] for i in np.argsort(__SCREAMING_SNAKE_CASE )] arrival_time.sort() while no_of_process > finished_process_count: lowercase_ : List[str] = 0 while finished_process[i] == 1: i += 1 if current_time < arrival_time[i]: lowercase_ : List[Any] = arrival_time[i] lowercase_ : List[str] = 0 # Index showing the location of the process being performed lowercase_ : List[str] = 0 # Saves the current response ratio. lowercase_ : List[Any] = 0 for i in range(0 , __SCREAMING_SNAKE_CASE ): if finished_process[i] == 0 and arrival_time[i] <= current_time: lowercase_ : List[Any] = (burst_time[i] + (current_time - arrival_time[i])) / burst_time[ i ] if response_ratio < temp: lowercase_ : Optional[int] = temp lowercase_ : Optional[Any] = i # Calculate the turn around time lowercase_ : int = current_time + burst_time[loc] - arrival_time[loc] current_time += burst_time[loc] # Indicates that the process has been performed. lowercase_ : Union[str, Any] = 1 # Increase finished_process_count by 1 finished_process_count += 1 return turn_around_time def snake_case_ ( __SCREAMING_SNAKE_CASE : list , __SCREAMING_SNAKE_CASE : list , __SCREAMING_SNAKE_CASE : list , __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : Optional[int] = [0] * no_of_process for i in range(0 , __SCREAMING_SNAKE_CASE ): lowercase_ : Optional[Any] = turn_around_time[i] - burst_time[i] return waiting_time if __name__ == "__main__": _lowercase : str = 5 _lowercase : int = ["A", "B", "C", "D", "E"] _lowercase : List[str] = [1, 2, 3, 4, 5] _lowercase : Tuple = [1, 2, 3, 4, 5] _lowercase : Any = calculate_turn_around_time( process_name, arrival_time, burst_time, no_of_process ) _lowercase : Dict = calculate_waiting_time( process_name, turn_around_time, burst_time, no_of_process ) print("Process name \tArrival time \tBurst time \tTurn around time \tWaiting time") for i in range(0, no_of_process): print( f"""{process_name[i]}\t\t{arrival_time[i]}\t\t{burst_time[i]}\t\t""" f"""{turn_around_time[i]}\t\t\t{waiting_time[i]}""" ) print(f"""average waiting time : {mean(waiting_time):.5f}""") print(f"""average turn around time : {mean(turn_around_time):.5f}""")
93
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging _lowercase : Optional[Any] = logging.get_logger(__name__) _lowercase : List[str] = { "google/pix2struct-textcaps-base": ( "https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json" ), } class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = '''pix2struct_text_model''' lowerCAmelCase_ = ['''past_key_values'''] lowerCAmelCase_ = { '''hidden_size''': '''hidden_size''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self , __SCREAMING_SNAKE_CASE=5_02_44 , __SCREAMING_SNAKE_CASE=7_68 , __SCREAMING_SNAKE_CASE=64 , __SCREAMING_SNAKE_CASE=20_48 , __SCREAMING_SNAKE_CASE=12 , __SCREAMING_SNAKE_CASE=12 , __SCREAMING_SNAKE_CASE=32 , __SCREAMING_SNAKE_CASE=1_28 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=1E-6 , __SCREAMING_SNAKE_CASE=1.0 , __SCREAMING_SNAKE_CASE="gelu_new" , __SCREAMING_SNAKE_CASE=0 , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=0 , __SCREAMING_SNAKE_CASE=1 , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=True , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : Any = vocab_size lowercase_ : Tuple = hidden_size lowercase_ : Optional[Any] = d_kv lowercase_ : List[str] = d_ff lowercase_ : List[str] = num_layers lowercase_ : Optional[Any] = num_heads lowercase_ : Union[str, Any] = relative_attention_num_buckets lowercase_ : Optional[int] = relative_attention_max_distance lowercase_ : Union[str, Any] = dropout_rate lowercase_ : Dict = layer_norm_epsilon lowercase_ : Dict = initializer_factor lowercase_ : List[Any] = use_cache lowercase_ : Optional[int] = eos_token_id lowercase_ : Optional[int] = decoder_start_token_id # for backwards compatibility lowercase_ : Any = dense_act_fn super().__init__( pad_token_id=__SCREAMING_SNAKE_CASE , eos_token_id=__SCREAMING_SNAKE_CASE , decoder_start_token_id=__SCREAMING_SNAKE_CASE , tie_word_embeddings=__SCREAMING_SNAKE_CASE , is_decoder=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) @classmethod def _snake_case ( cls , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" cls._set_token_in_kwargs(__SCREAMING_SNAKE_CASE ) lowercase_ , lowercase_ : Optional[int] = cls.get_config_dict(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) # get the text config dict if we are loading from Pix2StructConfig if config_dict.get('''model_type''' ) == "pix2struct": lowercase_ : List[Any] = config_dict['''text_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'''You are using a model of type {config_dict['model_type']} to instantiate a model of type ''' F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = '''pix2struct_vision_model''' def __init__( self , __SCREAMING_SNAKE_CASE=7_68 , __SCREAMING_SNAKE_CASE=7_68 , __SCREAMING_SNAKE_CASE=20_48 , __SCREAMING_SNAKE_CASE=64 , __SCREAMING_SNAKE_CASE=12 , __SCREAMING_SNAKE_CASE=12 , __SCREAMING_SNAKE_CASE="gelu_new" , __SCREAMING_SNAKE_CASE=1E-6 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=1E-1_0 , __SCREAMING_SNAKE_CASE=1.0 , __SCREAMING_SNAKE_CASE=40_96 , __SCREAMING_SNAKE_CASE=32 , __SCREAMING_SNAKE_CASE=1_28 , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = hidden_size lowercase_ : Any = patch_embed_hidden_size lowercase_ : List[Any] = d_ff lowercase_ : Dict = dropout_rate lowercase_ : Any = num_hidden_layers lowercase_ : Any = num_attention_heads lowercase_ : int = initializer_range lowercase_ : Dict = initializer_factor lowercase_ : Dict = attention_dropout lowercase_ : Optional[Any] = layer_norm_eps lowercase_ : str = dense_act_fn lowercase_ : Dict = seq_len lowercase_ : List[Any] = relative_attention_num_buckets lowercase_ : int = relative_attention_max_distance lowercase_ : Optional[int] = d_kv @classmethod def _snake_case ( cls , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" cls._set_token_in_kwargs(__SCREAMING_SNAKE_CASE ) lowercase_ , lowercase_ : str = cls.get_config_dict(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) # get the vision config dict if we are loading from Pix2StructConfig if config_dict.get('''model_type''' ) == "pix2struct": lowercase_ : Optional[int] = config_dict['''vision_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'''You are using a model of type {config_dict['model_type']} to instantiate a model of type ''' F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = '''pix2struct''' lowerCAmelCase_ = True def __init__( self , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=1.0 , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=True , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" super().__init__(tie_word_embeddings=__SCREAMING_SNAKE_CASE , is_encoder_decoder=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) if text_config is None: lowercase_ : Optional[Any] = {} logger.info('''text_config is None. Initializing the Pix2StructTextConfig with default values.''' ) if vision_config is None: lowercase_ : Dict = {} logger.info('''vision_config is None. Initializing the Pix2StructVisionConfig with default values.''' ) lowercase_ : str = PixaStructTextConfig(**__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = PixaStructVisionConfig(**__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = self.text_config.decoder_start_token_id lowercase_ : Union[str, Any] = self.text_config.pad_token_id lowercase_ : Union[str, Any] = self.text_config.eos_token_id lowercase_ : int = initializer_factor lowercase_ : Any = initializer_range lowercase_ : str = self.initializer_range lowercase_ : str = self.initializer_range lowercase_ : int = is_vqa @classmethod def _snake_case ( cls , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **__SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" lowercase_ : Tuple = copy.deepcopy(self.__dict__ ) lowercase_ : Any = self.text_config.to_dict() lowercase_ : Optional[Any] = self.vision_config.to_dict() lowercase_ : Optional[int] = self.__class__.model_type return output
93
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available _lowercase : Tuple = { "configuration_ctrl": ["CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP", "CTRLConfig"], "tokenization_ctrl": ["CTRLTokenizer"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : str = [ "CTRL_PRETRAINED_MODEL_ARCHIVE_LIST", "CTRLForSequenceClassification", "CTRLLMHeadModel", "CTRLModel", "CTRLPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : str = [ "TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST", "TFCTRLForSequenceClassification", "TFCTRLLMHeadModel", "TFCTRLModel", "TFCTRLPreTrainedModel", ] if TYPE_CHECKING: from .configuration_ctrl import CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, CTRLConfig from .tokenization_ctrl import CTRLTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ctrl import ( CTRL_PRETRAINED_MODEL_ARCHIVE_LIST, CTRLForSequenceClassification, CTRLLMHeadModel, CTRLModel, CTRLPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_ctrl import ( TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST, TFCTRLForSequenceClassification, TFCTRLLMHeadModel, TFCTRLModel, TFCTRLPreTrainedModel, ) else: import sys _lowercase : List[str] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
93
'''simple docstring''' from math import isqrt, loga def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : Any = [True] * max_number for i in range(2 , isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2 , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase_ : Optional[Any] = False return [i for i in range(2 , __SCREAMING_SNAKE_CASE ) if is_prime[i]] def snake_case_ ( __SCREAMING_SNAKE_CASE : int = 800800 , __SCREAMING_SNAKE_CASE : int = 800800 ): """simple docstring""" lowercase_ : Union[str, Any] = degree * loga(__SCREAMING_SNAKE_CASE ) lowercase_ : Any = int(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = calculate_prime_numbers(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = 0 lowercase_ : List[Any] = 0 lowercase_ : Union[str, Any] = len(__SCREAMING_SNAKE_CASE ) - 1 while left < right: while ( prime_numbers[right] * loga(prime_numbers[left] ) + prime_numbers[left] * loga(prime_numbers[right] ) > upper_bound ): right -= 1 hybrid_integers_count += right - left left += 1 return hybrid_integers_count if __name__ == "__main__": print(f"""{solution() = }""")
93
1
'''simple docstring''' from .integrations import ( is_optuna_available, is_ray_available, is_sigopt_available, is_wandb_available, run_hp_search_optuna, run_hp_search_ray, run_hp_search_sigopt, run_hp_search_wandb, ) from .trainer_utils import ( HPSearchBackend, default_hp_space_optuna, default_hp_space_ray, default_hp_space_sigopt, default_hp_space_wandb, ) from .utils import logging _lowercase : Union[str, Any] = logging.get_logger(__name__) class lowerCAmelCase__ : lowerCAmelCase_ = 42 lowerCAmelCase_ = None @staticmethod def _snake_case ( ): """simple docstring""" raise NotImplementedError def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" raise NotImplementedError def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" raise NotImplementedError def _snake_case ( self ): """simple docstring""" if not self.is_available(): raise RuntimeError( F'''You picked the {self.name} backend, but it is not installed. Run {self.pip_install()}.''' ) @classmethod def _snake_case ( cls ): """simple docstring""" return F'''`pip install {cls.pip_package or cls.name}`''' class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = '''optuna''' @staticmethod def _snake_case ( ): """simple docstring""" return is_optuna_available() def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" return run_hp_search_optuna(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" return default_hp_space_optuna(__SCREAMING_SNAKE_CASE ) class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = '''ray''' lowerCAmelCase_ = '''\'ray[tune]\'''' @staticmethod def _snake_case ( ): """simple docstring""" return is_ray_available() def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" return run_hp_search_ray(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" return default_hp_space_ray(__SCREAMING_SNAKE_CASE ) class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = '''sigopt''' @staticmethod def _snake_case ( ): """simple docstring""" return is_sigopt_available() def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" return run_hp_search_sigopt(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" return default_hp_space_sigopt(__SCREAMING_SNAKE_CASE ) class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = '''wandb''' @staticmethod def _snake_case ( ): """simple docstring""" return is_wandb_available() def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" return run_hp_search_wandb(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" return default_hp_space_wandb(__SCREAMING_SNAKE_CASE ) _lowercase : Any = { HPSearchBackend(backend.name): backend for backend in [OptunaBackend, RayTuneBackend, SigOptBackend, WandbBackend] } def snake_case_ ( ): """simple docstring""" lowercase_ : Any = [backend for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() if backend.is_available()] if len(__SCREAMING_SNAKE_CASE ) > 0: lowercase_ : Union[str, Any] = available_backends[0].name if len(__SCREAMING_SNAKE_CASE ) > 1: logger.info( F'''{len(__SCREAMING_SNAKE_CASE )} hyperparameter search backends available. Using {name} as the default.''' ) return name raise RuntimeError( '''No hyperparameter search backend available.\n''' + '''\n'''.join( F''' - To install {backend.name} run {backend.pip_install()}''' for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() ) )
93
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices _lowercase : int = logging.get_logger(__name__) _lowercase : List[Any] = { "shi-labs/nat-mini-in1k-224": "https://huggingface.co/shi-labs/nat-mini-in1k-224/resolve/main/config.json", # See all Nat models at https://huggingface.co/models?filter=nat } class lowerCAmelCase__ ( lowerCamelCase_ , lowerCamelCase_ ): lowerCAmelCase_ = '''nat''' lowerCAmelCase_ = { '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self , __SCREAMING_SNAKE_CASE=4 , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=64 , __SCREAMING_SNAKE_CASE=[3, 4, 6, 5] , __SCREAMING_SNAKE_CASE=[2, 4, 8, 16] , __SCREAMING_SNAKE_CASE=7 , __SCREAMING_SNAKE_CASE=3.0 , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE="gelu" , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=1E-5 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" super().__init__(**__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = patch_size lowercase_ : List[Any] = num_channels lowercase_ : str = embed_dim lowercase_ : List[str] = depths lowercase_ : str = len(__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = num_heads lowercase_ : int = kernel_size lowercase_ : Union[str, Any] = mlp_ratio lowercase_ : Optional[int] = qkv_bias lowercase_ : List[Any] = hidden_dropout_prob lowercase_ : Optional[int] = attention_probs_dropout_prob lowercase_ : List[Any] = drop_path_rate lowercase_ : List[Any] = hidden_act lowercase_ : int = layer_norm_eps lowercase_ : int = initializer_range # we set the hidden_size attribute in order to make Nat work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model lowercase_ : Dict = int(embed_dim * 2 ** (len(__SCREAMING_SNAKE_CASE ) - 1) ) lowercase_ : Tuple = layer_scale_init_value lowercase_ : Union[str, Any] = ['''stem'''] + [F'''stage{idx}''' for idx in range(1 , len(__SCREAMING_SNAKE_CASE ) + 1 )] lowercase_ , lowercase_ : int = get_aligned_output_features_output_indices( out_features=__SCREAMING_SNAKE_CASE , out_indices=__SCREAMING_SNAKE_CASE , stage_names=self.stage_names )
93
1
'''simple docstring''' import warnings from .generation import TFGenerationMixin class lowerCAmelCase__ ( lowerCamelCase_ ): # warning at import time warnings.warn( '''Importing `TFGenerationMixin` from `src/transformers/generation_tf_utils.py` is deprecated and will ''' '''be removed in Transformers v5. Import as `from transformers import TFGenerationMixin` instead.''' , lowerCamelCase_ , )
93
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _lowercase : Union[str, Any] = { "configuration_mask2former": [ "MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "Mask2FormerConfig", ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : Optional[int] = ["Mask2FormerImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : str = [ "MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "Mask2FormerForUniversalSegmentation", "Mask2FormerModel", "Mask2FormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_maskaformer import MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskaFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_maskaformer import MaskaFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskaformer import ( MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskaFormerForUniversalSegmentation, MaskaFormerModel, MaskaFormerPreTrainedModel, ) else: import sys _lowercase : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure)
93
1
'''simple docstring''' import random import sys import numpy as np from matplotlib import pyplot as plt from matplotlib.colors import ListedColormap _lowercase : Union[str, Any] = "Usage of script: script_name <size_of_canvas:int>" _lowercase : Union[str, Any] = [0] * 1_0_0 + [1] * 1_0 random.shuffle(choice) def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : Union[str, Any] = [[False for i in range(__SCREAMING_SNAKE_CASE )] for j in range(__SCREAMING_SNAKE_CASE )] return canvas def snake_case_ ( __SCREAMING_SNAKE_CASE : list[list[bool]] ): """simple docstring""" for i, row in enumerate(__SCREAMING_SNAKE_CASE ): for j, _ in enumerate(__SCREAMING_SNAKE_CASE ): lowercase_ : Union[str, Any] = bool(random.getrandbits(1 ) ) def snake_case_ ( __SCREAMING_SNAKE_CASE : list[list[bool]] ): """simple docstring""" lowercase_ : str = np.array(__SCREAMING_SNAKE_CASE ) lowercase_ : Any = np.array(create_canvas(current_canvas.shape[0] ) ) for r, row in enumerate(__SCREAMING_SNAKE_CASE ): for c, pt in enumerate(__SCREAMING_SNAKE_CASE ): lowercase_ : List[Any] = __judge_point( __SCREAMING_SNAKE_CASE , current_canvas[r - 1 : r + 2, c - 1 : c + 2] ) lowercase_ : Dict = next_gen_canvas del next_gen_canvas # cleaning memory as we move on. lowercase_ : list[list[bool]] = current_canvas.tolist() return return_canvas def snake_case_ ( __SCREAMING_SNAKE_CASE : bool , __SCREAMING_SNAKE_CASE : list[list[bool]] ): """simple docstring""" lowercase_ : List[str] = 0 lowercase_ : Tuple = 0 # finding dead or alive neighbours count. for i in neighbours: for status in i: if status: alive += 1 else: dead += 1 # handling duplicate entry for focus pt. if pt: alive -= 1 else: dead -= 1 # running the rules of game here. lowercase_ : Union[str, Any] = pt if pt: if alive < 2: lowercase_ : Optional[int] = False elif alive == 2 or alive == 3: lowercase_ : int = True elif alive > 3: lowercase_ : Any = False else: if alive == 3: lowercase_ : str = True return state if __name__ == "__main__": if len(sys.argv) != 2: raise Exception(usage_doc) _lowercase : Tuple = int(sys.argv[1]) # main working structure of this module. _lowercase : int = create_canvas(canvas_size) seed(c) _lowercase , _lowercase : List[str] = plt.subplots() fig.show() _lowercase : str = ListedColormap(["w", "k"]) try: while True: _lowercase : str = run(c) ax.matshow(c, cmap=cmap) fig.canvas.draw() ax.cla() except KeyboardInterrupt: # do nothing. pass
93
'''simple docstring''' import unittest from knapsack import greedy_knapsack as kp class lowerCAmelCase__ ( unittest.TestCase ): def _snake_case ( self ): """simple docstring""" lowercase_ : List[str] = [10, 20, 30, 40, 50, 60] lowercase_ : Optional[Any] = [2, 4, 6, 8, 10, 12] lowercase_ : Union[str, Any] = 1_00 self.assertEqual(kp.calc_profit(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) , 2_10 ) def _snake_case ( self ): """simple docstring""" self.assertRaisesRegex(__SCREAMING_SNAKE_CASE , '''max_weight must greater than zero.''' ) def _snake_case ( self ): """simple docstring""" self.assertRaisesRegex(__SCREAMING_SNAKE_CASE , '''Weight can not be negative.''' ) def _snake_case ( self ): """simple docstring""" self.assertRaisesRegex(__SCREAMING_SNAKE_CASE , '''Profit can not be negative.''' ) def _snake_case ( self ): """simple docstring""" self.assertRaisesRegex(__SCREAMING_SNAKE_CASE , '''max_weight must greater than zero.''' ) def _snake_case ( self ): """simple docstring""" self.assertRaisesRegex( __SCREAMING_SNAKE_CASE , '''The length of profit and weight must be same.''' ) if __name__ == "__main__": unittest.main()
93
1
'''simple docstring''' import argparse import os import torch from transformers.utils import WEIGHTS_NAME _lowercase : Optional[Any] = ["small", "medium", "large"] _lowercase : Any = "lm_head.decoder.weight" _lowercase : List[str] = "lm_head.weight" def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : str ): """simple docstring""" lowercase_ : Union[str, Any] = torch.load(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = d.pop(__SCREAMING_SNAKE_CASE ) os.makedirs(__SCREAMING_SNAKE_CASE , exist_ok=__SCREAMING_SNAKE_CASE ) torch.save(__SCREAMING_SNAKE_CASE , os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) if __name__ == "__main__": _lowercase : Dict = argparse.ArgumentParser() parser.add_argument("--dialogpt_path", default=".", type=str) _lowercase : List[Any] = parser.parse_args() for MODEL in DIALOGPT_MODELS: _lowercase : Optional[int] = os.path.join(args.dialogpt_path, f"""{MODEL}_ft.pkl""") _lowercase : Optional[Any] = f"""./DialoGPT-{MODEL}""" convert_dialogpt_checkpoint( checkpoint_path, pytorch_dump_folder_path, )
93
'''simple docstring''' import argparse import copy def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[int] ): """simple docstring""" lowercase_ : List[Any] = {} with open(__SCREAMING_SNAKE_CASE ) as f: for line in f: if line.split()[0] not in dict_of_neighbours: lowercase_ : Union[str, Any] = [] _list.append([line.split()[1], line.split()[2]] ) lowercase_ : str = _list else: dict_of_neighbours[line.split()[0]].append( [line.split()[1], line.split()[2]] ) if line.split()[1] not in dict_of_neighbours: lowercase_ : Optional[int] = [] _list.append([line.split()[0], line.split()[2]] ) lowercase_ : Dict = _list else: dict_of_neighbours[line.split()[1]].append( [line.split()[0], line.split()[2]] ) return dict_of_neighbours def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE ) as f: lowercase_ : List[str] = f.read(1 ) lowercase_ : Optional[int] = start_node lowercase_ : Any = [] lowercase_ : List[str] = start_node lowercase_ : Optional[Any] = 0 while visiting not in first_solution: lowercase_ : Any = 10000 for k in dict_of_neighbours[visiting]: if int(k[1] ) < int(__SCREAMING_SNAKE_CASE ) and k[0] not in first_solution: lowercase_ : List[Any] = k[1] lowercase_ : List[Any] = k[0] first_solution.append(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = distance_of_first_solution + int(__SCREAMING_SNAKE_CASE ) lowercase_ : int = best_node first_solution.append(__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = 0 for k in dict_of_neighbours[first_solution[-2]]: if k[0] == start_node: break position += 1 lowercase_ : Optional[Any] = ( distance_of_first_solution + int(dict_of_neighbours[first_solution[-2]][position][1] ) - 10000 ) return first_solution, distance_of_first_solution def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" lowercase_ : Tuple = [] for n in solution[1:-1]: lowercase_ : List[str] = solution.index(__SCREAMING_SNAKE_CASE ) for kn in solution[1:-1]: lowercase_ : Any = solution.index(__SCREAMING_SNAKE_CASE ) if n == kn: continue lowercase_ : Dict = copy.deepcopy(__SCREAMING_SNAKE_CASE ) lowercase_ : Dict = kn lowercase_ : List[Any] = n lowercase_ : str = 0 for k in _tmp[:-1]: lowercase_ : Tuple = _tmp[_tmp.index(__SCREAMING_SNAKE_CASE ) + 1] for i in dict_of_neighbours[k]: if i[0] == next_node: lowercase_ : Optional[Any] = distance + int(i[1] ) _tmp.append(__SCREAMING_SNAKE_CASE ) if _tmp not in neighborhood_of_solution: neighborhood_of_solution.append(_tmp ) lowercase_ : Union[str, Any] = 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 snake_case_ ( __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" lowercase_ : Optional[int] = 1 lowercase_ : List[str] = first_solution lowercase_ : Dict = [] lowercase_ : List[str] = distance_of_first_solution lowercase_ : Optional[Any] = solution while count <= iters: lowercase_ : int = find_neighborhood(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : Any = 0 lowercase_ : Dict = neighborhood[index_of_best_solution] lowercase_ : Optional[Any] = len(__SCREAMING_SNAKE_CASE ) - 1 lowercase_ : Tuple = False while not found: lowercase_ : Optional[int] = 0 while i < len(__SCREAMING_SNAKE_CASE ): if best_solution[i] != solution[i]: lowercase_ : Tuple = best_solution[i] lowercase_ : Optional[int] = solution[i] break lowercase_ : 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] ) lowercase_ : Tuple = True lowercase_ : Optional[int] = best_solution[:-1] lowercase_ : Optional[Any] = neighborhood[index_of_best_solution][best_cost_index] if cost < best_cost: lowercase_ : Optional[Any] = cost lowercase_ : int = solution else: lowercase_ : Any = index_of_best_solution + 1 lowercase_ : Any = neighborhood[index_of_best_solution] if len(__SCREAMING_SNAKE_CASE ) >= size: tabu_list.pop(0 ) lowercase_ : List[Any] = count + 1 return best_solution_ever, best_cost def snake_case_ ( __SCREAMING_SNAKE_CASE : List[str]=None ): """simple docstring""" lowercase_ : Any = generate_neighbours(args.File ) lowercase_ , lowercase_ : Union[str, Any] = generate_first_solution( args.File , __SCREAMING_SNAKE_CASE ) lowercase_ , lowercase_ : Optional[int] = 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__": _lowercase : Any = 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())
93
1